Primo Committ

This commit is contained in:
paoloar77
2024-05-07 12:17:25 +02:00
commit e73d0e5113
7204 changed files with 884387 additions and 0 deletions

View File

@@ -0,0 +1,243 @@
<?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
* @return void
*/
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 $alias
* @param string $class
* @return void
*/
public function alias($alias, $class)
{
$this->aliases[$alias] = $class;
}
/**
* 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 the given abilities.
*
* @param iterable|string $abilities
* @param array|mixed $arguments
* @return bool
*/
public function can($abilities, $arguments = [])
{
return app(Gate::class)->forUser($this)->check($abilities, $arguments);
}
/**
* Determine if the entity does not have the given abilities.
*
* @param iterable|string $abilities
* @param array|mixed $arguments
* @return bool
*/
public function cant($abilities, $arguments = [])
{
return ! $this->can($abilities, $arguments);
}
/**
* Determine if the entity does not have the given abilities.
*
* @param iterable|string $abilities
* @param array|mixed $arguments
* @return bool
*/
public function cannot($abilities, $arguments = [])
{
return $this->cant($abilities, $arguments);
}
}

View File

@@ -0,0 +1,127 @@
<?php
namespace Illuminate\Foundation\Auth\Access;
use Illuminate\Contracts\Auth\Access\Gate;
use Illuminate\Support\Str;
trait AuthorizesRequests
{
/**
* Authorize a given action for the current user.
*
* @param mixed $ability
* @param mixed|array $arguments
* @return \Illuminate\Auth\Access\Response
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function authorize($ability, $arguments = [])
{
[$ability, $arguments] = $this->parseAbilityAndArguments($ability, $arguments);
return app(Gate::class)->authorize($ability, $arguments);
}
/**
* Authorize a given action for a user.
*
* @param \Illuminate\Contracts\Auth\Authenticatable|mixed $user
* @param mixed $ability
* @param mixed|array $arguments
* @return \Illuminate\Auth\Access\Response
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function authorizeForUser($user, $ability, $arguments = [])
{
[$ability, $arguments] = $this->parseAbilityAndArguments($ability, $arguments);
return app(Gate::class)->forUser($user)->authorize($ability, $arguments);
}
/**
* Guesses the ability's name if it wasn't provided.
*
* @param mixed $ability
* @param mixed|array $arguments
* @return array
*/
protected function parseAbilityAndArguments($ability, $arguments)
{
if (is_string($ability) && 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 $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 ?: Str::snake(class_basename($model));
$middleware = [];
foreach ($this->resourceAbilityMap() as $method => $ability) {
$modelName = in_array($method, $this->resourceMethodsWithoutModels()) ? $model : $parameter;
$middleware["can:{$ability},{$modelName}"][] = $method;
}
foreach ($middleware as $middlewareName => $methods) {
$this->middleware($middlewareName, $options)->only($methods);
}
}
/**
* Get the map of resource methods to ability names.
*
* @return array
*/
protected function resourceAbilityMap()
{
return [
'index' => 'viewAny',
'show' => 'view',
'create' => 'create',
'store' => 'create',
'edit' => 'update',
'update' => 'update',
'destroy' => 'delete',
];
}
/**
* Get the list of resource methods which do not have model parameters.
*
* @return array
*/
protected function resourceMethodsWithoutModels()
{
return ['index', 'create', 'store'];
}
}

View File

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

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,166 @@
<?php
namespace Illuminate\Foundation\Bootstrap;
use ErrorException;
use Exception;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Contracts\Foundation\Application;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\ErrorHandler\Error\FatalError;
use Throwable;
class HandleExceptions
{
/**
* Reserved memory so that errors can be displayed properly on memory exhaustion.
*
* @var string
*/
public static $reservedMemory;
/**
* 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)
{
self::$reservedMemory = str_repeat('x', 10240);
$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(Throwable $e)
{
try {
self::$reservedMemory = null;
$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 \Throwable $e
* @return void
*/
protected function renderForConsole(Throwable $e)
{
$this->getExceptionHandler()->renderForConsole(new ConsoleOutput, $e);
}
/**
* Render an exception as an HTTP response and send it.
*
* @param \Throwable $e
* @return void
*/
protected function renderHttpResponse(Throwable $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->fatalErrorFromPhpError($error, 0));
}
}
/**
* Create a new fatal error instance from an error array.
*
* @param array $error
* @param int|null $traceOffset
* @return \Symfony\Component\ErrorHandler\Error\FatalError
*/
protected function fatalErrorFromPhpError(array $error, $traceOffset = null)
{
return new FatalError($error['message'], 0, $error, $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,116 @@
<?php
namespace Illuminate\Foundation\Bootstrap;
use Exception;
use Illuminate\Config\Repository;
use Illuminate\Contracts\Config\Repository as RepositoryContract;
use Illuminate\Contracts\Foundation\Application;
use SplFileInfo;
use Symfony\Component\Finder\Finder;
class LoadConfiguration
{
/**
* Bootstrap the given application.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function bootstrap(Application $app)
{
$items = [];
// First we will see if we have a cache configuration file. If we do, we'll load
// the configuration items from that file so that it is very quick. Otherwise
// we will need to spin through every configuration file and load them all.
if (file_exists($cached = $app->getCachedConfigPath())) {
$items = require $cached;
$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();
}
ksort($files, SORT_NATURAL);
return $files;
}
/**
* Get the configuration file nesting path.
*
* @param \SplFileInfo $file
* @param string $configPath
* @return string
*/
protected function getNestedDirectory(SplFileInfo $file, $configPath)
{
$directory = $file->getPath();
if ($nested = trim(str_replace($configPath, '', $directory), DIRECTORY_SEPARATOR)) {
$nested = str_replace(DIRECTORY_SEPARATOR, '.', $nested).'.';
}
return $nested;
}
}

View File

@@ -0,0 +1,110 @@
<?php
namespace Illuminate\Foundation\Bootstrap;
use Dotenv\Dotenv;
use Dotenv\Exception\InvalidFileException;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Env;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
class LoadEnvironmentVariables
{
/**
* Bootstrap the given application.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function bootstrap(Application $app)
{
if ($app->configurationIsCached()) {
return;
}
$this->checkForSpecificEnvironmentFile($app);
try {
$this->createDotenv($app)->safeLoad();
} catch (InvalidFileException $e) {
$this->writeErrorAndDie($e);
}
}
/**
* Detect if a custom environment file matching the APP_ENV exists.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
protected function checkForSpecificEnvironmentFile($app)
{
if ($app->runningInConsole() && ($input = new ArgvInput)->hasParameterOption('--env')) {
if ($this->setEnvironmentFilePath(
$app, $app->environmentFile().'.'.$input->getParameterOption('--env')
)) {
return;
}
}
$environment = Env::get('APP_ENV');
if (! $environment) {
return;
}
$this->setEnvironmentFilePath(
$app, $app->environmentFile().'.'.$environment
);
}
/**
* Load a custom environment file.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @param string $file
* @return bool
*/
protected function setEnvironmentFilePath($app, $file)
{
if (file_exists($app->environmentPath().'/'.$file)) {
$app->loadEnvironmentFrom($file);
return true;
}
return false;
}
/**
* Create a Dotenv instance.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return \Dotenv\Dotenv
*/
protected function createDotenv($app)
{
return Dotenv::create(
Env::getRepository(),
$app->environmentPath(),
$app->environmentFile()
);
}
/**
* Write the error information to the screen and exit.
*
* @param \Dotenv\Exception\InvalidFileException $e
* @return void
*/
protected function writeErrorAndDie(InvalidFileException $e)
{
$output = (new ConsoleOutput)->getErrorOutput();
$output->writeln('The environment file is invalid!');
$output->writeln($e->getMessage());
exit(1);
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Illuminate\Foundation\Bootstrap;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Foundation\PackageManifest;
use Illuminate\Support\Facades\Facade;
class RegisterFacades
{
/**
* Bootstrap the given application.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function bootstrap(Application $app)
{
Facade::clearResolvedInstances();
Facade::setFacadeApplication($app);
AliasLoader::getInstance(array_merge(
$app->make('config')->get('app.aliases', []),
$app->make(PackageManifest::class)->aliases()
))->register();
}
}

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,35 @@
<?php
namespace Illuminate\Foundation\Bootstrap;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;
class SetRequestForConsole
{
/**
* Bootstrap the given application.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function bootstrap(Application $app)
{
$uri = $app->make('config')->get('app.url', 'http://localhost');
$components = parse_url($uri);
$server = $_SERVER;
if (isset($components['path'])) {
$server = array_merge($server, [
'SCRIPT_FILENAME' => $components['path'],
'SCRIPT_NAME' => $components['path'],
]);
}
$app->instance('request', Request::create(
$uri, 'GET', [], [], [], $server
));
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace Illuminate\Foundation\Bus;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Support\Fluent;
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()));
}
/**
* Dispatch the job with the given arguments if the given truth test passes.
*
* @param bool $boolean
* @return \Illuminate\Foundation\Bus\PendingDispatch|\Illuminate\Support\Fluent
*/
public static function dispatchIf($boolean, ...$arguments)
{
return $boolean
? new PendingDispatch(new static(...$arguments))
: new Fluent;
}
/**
* Dispatch the job with the given arguments unless the given truth test passes.
*
* @param bool $boolean
* @return \Illuminate\Foundation\Bus\PendingDispatch|\Illuminate\Support\Fluent
*/
public static function dispatchUnless($boolean, ...$arguments)
{
return ! $boolean
? new PendingDispatch(new static(...$arguments))
: new Fluent;
}
/**
* Dispatch a command to its appropriate handler in the current process.
*
* @return mixed
*/
public static function dispatchNow()
{
return app(Dispatcher::class)->dispatchNow(new static(...func_get_args()));
}
/**
* Dispatch a command to its appropriate handler after the current process.
*
* @return mixed
*/
public static function dispatchAfterResponse()
{
return app(Dispatcher::class)->dispatchAfterResponse(new static(...func_get_args()));
}
/**
* Set the jobs that should run if this job is successful.
*
* @param array $chain
* @return \Illuminate\Foundation\Bus\PendingChain
*/
public static function withChain($chain)
{
return new PendingChain(static::class, $chain);
}
}

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 job 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,54 @@
<?php
namespace Illuminate\Foundation\Bus;
use Closure;
use Illuminate\Queue\CallQueuedClosure;
class PendingChain
{
/**
* The class name of the job being dispatched.
*
* @var mixed
*/
public $job;
/**
* The jobs to be chained.
*
* @var array
*/
public $chain;
/**
* Create a new PendingChain instance.
*
* @param mixed $job
* @param array $chain
* @return void
*/
public function __construct($job, $chain)
{
$this->job = $job;
$this->chain = $chain;
}
/**
* Dispatch the job with the given arguments.
*
* @return \Illuminate\Foundation\Bus\PendingDispatch
*/
public function dispatch()
{
if (is_string($this->job)) {
$firstJob = new $this->job(...func_get_args());
} elseif ($this->job instanceof Closure) {
$firstJob = CallQueuedClosure::create($this->job);
} else {
$firstJob = $this->job;
}
return (new PendingDispatch($firstJob))->chain($this->chain);
}
}

View File

@@ -0,0 +1,137 @@
<?php
namespace Illuminate\Foundation\Bus;
use Illuminate\Contracts\Bus\Dispatcher;
class PendingDispatch
{
/**
* The job.
*
* @var mixed
*/
protected $job;
/**
* Indicates if the job should be dispatched immediately after sending the response.
*
* @var bool
*/
protected $afterResponse = false;
/**
* 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 connection for the chain.
*
* @param string|null $connection
* @return $this
*/
public function allOnConnection($connection)
{
$this->job->allOnConnection($connection);
return $this;
}
/**
* Set the desired queue for the chain.
*
* @param string|null $queue
* @return $this
*/
public function allOnQueue($queue)
{
$this->job->allOnQueue($queue);
return $this;
}
/**
* Set the desired delay for the job.
*
* @param \DateTimeInterface|\DateInterval|int|null $delay
* @return $this
*/
public function delay($delay)
{
$this->job->delay($delay);
return $this;
}
/**
* Set the jobs that should run if this job is successful.
*
* @param array $chain
* @return $this
*/
public function chain($chain)
{
$this->job->chain($chain);
return $this;
}
/**
* Indicate that the job should be dispatched after the response is sent to the browser.
*
* @return $this
*/
public function afterResponse()
{
$this->afterResponse = true;
return $this;
}
/**
* Handle the object's destruction.
*
* @return void
*/
public function __destruct()
{
if ($this->afterResponse) {
app(Dispatcher::class)->dispatchAfterResponse($this->job);
} else {
app(Dispatcher::class)->dispatch($this->job);
}
}
}

View File

@@ -0,0 +1,65 @@
<?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();
}
/**
* Handle the post-autoload-dump Composer event.
*
* @param \Composer\Script\Event $event
* @return void
*/
public static function postAutoloadDump(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);
}
if (file_exists($packagesPath = $laravel->getCachedPackagesPath())) {
@unlink($packagesPath);
}
}
}

View File

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

View File

@@ -0,0 +1,65 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
class ChannelMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:channel';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new channel class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Channel';
/**
* Build the class with the given name.
*
* @param string $name
* @return string
*/
protected function buildClass($name)
{
return str_replace(
'DummyUser',
class_basename($this->userProviderModel()),
parent::buildClass($name)
);
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return __DIR__.'/stubs/channel.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Broadcasting';
}
}

View File

@@ -0,0 +1,40 @@
<?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 handle()
{
if (file_exists($servicesPath = $this->laravel->getCachedServicesPath())) {
@unlink($servicesPath);
}
if (file_exists($packagesPath = $this->laravel->getCachedPackagesPath())) {
@unlink($packagesPath);
}
$this->info('Compiled services and packages files removed!');
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace Illuminate\Foundation\Console;
use Closure;
use Illuminate\Console\Command;
use ReflectionFunction;
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 int
*/
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->getName()])) {
$parameters[$parameter->getName()] = $inputs[$parameter->getName()];
}
}
return (int) $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,144 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Str;
use Symfony\Component\Console\Input\InputOption;
class ComponentMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:component';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new view component class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Component';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
if (parent::handle() === false && ! $this->option('force')) {
return false;
}
if (! $this->option('inline')) {
$this->writeView();
}
}
/**
* Write the view for the component.
*
* @return void
*/
protected function writeView()
{
$path = $this->viewPath(
str_replace('.', '/', 'components.'.$this->getView())
);
if (! $this->files->isDirectory(dirname($path))) {
$this->files->makeDirectory(dirname($path), 0777, true, true);
}
file_put_contents(
$path.'.blade.php',
'<div>
<!-- '.Inspiring::quote().' -->
</div>'
);
}
/**
* Build the class with the given name.
*
* @param string $name
* @return string
*/
protected function buildClass($name)
{
if ($this->option('inline')) {
return str_replace(
'DummyView',
"<<<'blade'\n<div>\n <!-- ".Inspiring::quote()." -->\n</div>\nblade",
parent::buildClass($name)
);
}
return str_replace(
'DummyView',
'view(\'components.'.$this->getView().'\')',
parent::buildClass($name)
);
}
/**
* Get the view name relative to the components directory.
*
* @return string view
*/
protected function getView()
{
$name = str_replace('\\', '/', $this->argument('name'));
return collect(explode('/', $name))
->map(function ($part) {
return Str::kebab($part);
})
->implode('.');
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return __DIR__.'/stubs/view-component.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\View\Components';
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['force', null, InputOption::VALUE_NONE, 'Create the class even if the component already exists'],
['inline', null, InputOption::VALUE_NONE, 'Create a component that renders an inline view'],
];
}
}

View File

@@ -0,0 +1,92 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Kernel as ConsoleKernelContract;
use Illuminate\Filesystem\Filesystem;
use LogicException;
use Throwable;
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
*
* @throws \LogicException
*/
public function handle()
{
$this->call('config:clear');
$config = $this->getFreshConfiguration();
$configPath = $this->laravel->getCachedConfigPath();
$this->files->put(
$configPath, '<?php return '.var_export($config, true).';'.PHP_EOL
);
try {
require $configPath;
} catch (Throwable $e) {
$this->files->delete($configPath);
throw new LogicException('Your configuration files are not serializable.', 0, $e);
}
$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->useStoragePath($this->laravel->storagePath());
$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 handle()
{
$this->files->delete($this->laravel->getCachedConfigPath());
$this->info('Configuration cache cleared!');
}
}

View File

@@ -0,0 +1,94 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
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', '{{ command }}'], $this->option('command'), $stub);
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
$relativePath = '/stubs/console.stub';
return file_exists($customPath = $this->laravel->basePath(trim($relativePath, '/')))
? $customPath
: __DIR__.$relativePath;
}
/**
* 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,83 @@
<?php
namespace Illuminate\Foundation\Console;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\InteractsWithTime;
class DownCommand extends Command
{
use InteractsWithTime;
/**
* 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}
{--allow=* : IP or networks allowed to access the application while in maintenance mode}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Put the application into maintenance mode';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
try {
if (file_exists(storage_path('framework/down'))) {
$this->comment('Application is already down.');
return true;
}
file_put_contents(storage_path('framework/down'),
json_encode($this->getDownFilePayload(),
JSON_PRETTY_PRINT));
$this->comment('Application is now in maintenance mode.');
} catch (Exception $e) {
$this->error('Failed to enter maintenance mode.');
$this->error($e->getMessage());
return 1;
}
}
/**
* Get the payload to be placed in the "down" file.
*
* @return array
*/
protected function getDownFilePayload()
{
return [
'time' => $this->currentTime(),
'message' => $this->option('message'),
'retry' => $this->getRetryTime(),
'allowed' => $this->option('allow'),
];
}
/**
* 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 handle()
{
$this->line('<info>Current application environment:</info> <comment>'.$this->laravel['env'].'</comment>');
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Foundation\Support\Providers\EventServiceProvider;
class EventCacheCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'event:cache';
/**
* The console command description.
*
* @var string
*/
protected $description = "Discover and cache the application's events and listeners";
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->call('event:clear');
file_put_contents(
$this->laravel->getCachedEventsPath(),
'<?php return '.var_export($this->getEvents(), true).';'
);
$this->info('Events cached successfully!');
}
/**
* Get all of the events and listeners configured for the application.
*
* @return array
*/
protected function getEvents()
{
$events = [];
foreach ($this->laravel->getProviders(EventServiceProvider::class) as $provider) {
$providerEvents = array_merge_recursive($provider->shouldDiscoverEvents() ? $provider->discoverEvents() : [], $provider->listens());
$events[get_class($provider)] = $providerEvents;
}
return $events;
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
class EventClearCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'event:clear';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Clear all cached events and listeners';
/**
* 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
*
* @throws \RuntimeException
*/
public function handle()
{
$this->files->delete($this->laravel->getCachedEventsPath());
$this->info('Cached events cleared!');
}
}

View File

@@ -0,0 +1,78 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Foundation\Support\Providers\EventServiceProvider;
use Illuminate\Support\Str;
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 handle()
{
$providers = $this->laravel->getProviders(EventServiceProvider::class);
foreach ($providers as $provider) {
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', array_filter(
['name' => $listener, '--event' => $event]
));
}
}
}

View File

@@ -0,0 +1,91 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Foundation\Support\Providers\EventServiceProvider;
use Illuminate\Support\Str;
class EventListCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'event:list {--event= : Filter the events by name}';
/**
* The console command description.
*
* @var string
*/
protected $description = "List the application's events and listeners";
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$events = $this->getEvents();
if (empty($events)) {
return $this->error("Your application doesn't have any events matching the given criteria.");
}
$this->table(['Event', 'Listeners'], $events);
}
/**
* Get all of the events and listeners configured for the application.
*
* @return array
*/
protected function getEvents()
{
$events = [];
foreach ($this->laravel->getProviders(EventServiceProvider::class) as $provider) {
$providerEvents = array_merge_recursive($provider->shouldDiscoverEvents() ? $provider->discoverEvents() : [], $provider->listens());
$events = array_merge_recursive($events, $providerEvents);
}
if ($this->filteringByEvent()) {
$events = $this->filterEvents($events);
}
return collect($events)->map(function ($listeners, $event) {
return ['Event' => $event, 'Listeners' => implode(PHP_EOL, $listeners)];
})->sortBy('Event')->values()->toArray();
}
/**
* Filter the given events using the provided event name filter.
*
* @param array $events
* @return array
*/
protected function filterEvents(array $events)
{
if (! $eventName = $this->option('event')) {
return $events;
}
return collect($events)->filter(function ($listeners, $event) use ($eventName) {
return Str::contains($event, $eventName);
})->toArray();
}
/**
* Determine whether the user is filtering by an event name.
*
* @return bool
*/
protected function filteringByEvent()
{
return ! empty($this->option('event'));
}
}

View File

@@ -0,0 +1,62 @@
<?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) ||
$this->files->exists($this->getPath($this->qualifyClass($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,84 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class ExceptionMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:exception';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new custom exception class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Exception';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
if ($this->option('render')) {
return $this->option('report')
? __DIR__.'/stubs/exception-render-report.stub'
: __DIR__.'/stubs/exception-render.stub';
}
return $this->option('report')
? __DIR__.'/stubs/exception-report.stub'
: __DIR__.'/stubs/exception.stub';
}
/**
* Determine if the class already exists.
*
* @param string $rawName
* @return bool
*/
protected function alreadyExists($rawName)
{
return class_exists($this->rootNamespace().'Exceptions\\'.$rawName);
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Exceptions';
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['render', null, InputOption::VALUE_NONE, 'Create the exception with an empty render method'],
['report', null, InputOption::VALUE_NONE, 'Create the exception with an empty report method'],
];
}
}

View File

@@ -0,0 +1,78 @@
<?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')
? $this->resolveStubPath('/stubs/job.stub')
: $this->resolveStubPath('/stubs/job.queued.stub');
}
/**
* Resolve the fully-qualified path to the stub.
*
* @param string $stub
* @return string
*/
protected function resolveStubPath($stub)
{
return file_exists($customPath = $this->laravel->basePath(trim($stub, '/')))
? $customPath
: __DIR__.$stub;
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\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,380 @@
<?php
namespace Illuminate\Foundation\Console;
use Closure;
use Illuminate\Console\Application as Artisan;
use Illuminate\Console\Command;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Contracts\Console\Kernel as KernelContract;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Arr;
use Illuminate\Support\Env;
use Illuminate\Support\Str;
use ReflectionClass;
use Symfony\Component\Finder\Finder;
use Throwable;
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|null
*/
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->singleton(Schedule::class, function ($app) {
return tap(new Schedule($this->scheduleTimezone()), function ($schedule) {
$this->schedule($schedule->useCache($this->scheduleCache()));
});
});
}
/**
* Get the name of the cache store that should manage scheduling mutexes.
*
* @return string
*/
protected function scheduleCache()
{
return Env::get('SCHEDULE_CACHE_DRIVER');
}
/**
* Run the console application.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface|null $output
* @return int
*/
public function handle($input, $output = null)
{
try {
$this->bootstrap();
return $this->getArtisan()->run($input, $output);
} catch (Throwable $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)
{
//
}
/**
* Get the timezone that should be used by default for scheduled events.
*
* @return \DateTimeZone|string|null
*/
protected function scheduleTimezone()
{
$config = $this->app['config'];
return $config->get('app.schedule_timezone', $config->get('app.timezone'));
}
/**
* 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 all of the commands in the given directory.
*
* @param array|string $paths
* @return void
*/
protected function load($paths)
{
$paths = array_unique(Arr::wrap($paths));
$paths = array_filter($paths, function ($path) {
return is_dir($path);
});
if (empty($paths)) {
return;
}
$namespace = $this->app->getNamespace();
foreach ((new Finder)->in($paths)->files() as $command) {
$command = $namespace.str_replace(
['/', '.php'],
['\\', ''],
Str::after($command->getPathname(), realpath(app_path()).DIRECTORY_SEPARATOR)
);
if (is_subclass_of($command, Command::class) &&
! (new ReflectionClass($command))->isAbstract()) {
Artisan::starting(function ($artisan) use ($command) {
$artisan->resolve($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|null $outputBuffer
* @return int
*
* @throws \Symfony\Component\Console\Exception\CommandNotFoundException
*/
public function call($command, array $parameters = [], $outputBuffer = null)
{
$this->bootstrap();
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());
}
$this->app->loadDeferredProviders();
if (! $this->commandsLoaded) {
$this->commands();
$this->commandsLoaded = true;
}
}
/**
* 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 \Throwable $e
* @return void
*/
protected function reportException(Throwable $e)
{
$this->app[ExceptionHandler::class]->report($e);
}
/**
* Render the given exception.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param \Throwable $e
* @return void
*/
protected function renderException($output, Throwable $e)
{
$this->app[ExceptionHandler::class]->renderForConsole($output, $e);
}
}

View File

@@ -0,0 +1,111 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
use Illuminate\Encryption\Encrypter;
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 handle()
{
$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 set successfully.');
}
/**
* Generate a random key for the application.
*
* @return string
*/
protected function generateRandomKey()
{
return 'base64:'.base64_encode(
Encrypter::generateKey($this->laravel['config']['app.cipher'])
);
}
/**
* 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,112 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Str;
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';
/**
* 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(),
'Illuminate',
'\\',
])) {
$event = $this->laravel->getNamespace().'Events\\'.$event;
}
$stub = str_replace(
'DummyEvent', class_basename($event), parent::buildClass($name)
);
return str_replace(
'DummyFullEvent', trim($event, '\\'), $stub
);
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
if ($this->option('queued')) {
return $this->option('event')
? __DIR__.'/stubs/listener-queued.stub'
: __DIR__.'/stubs/listener-queued-duck.stub';
}
return $this->option('event')
? __DIR__.'/stubs/listener.stub'
: __DIR__.'/stubs/listener-duck.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_OPTIONAL, 'The event class being listened for'],
['queued', null, InputOption::VALUE_NONE, 'Indicates the event listener should be queued'],
];
}
}

View File

@@ -0,0 +1,118 @@
<?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 handle()
{
if (parent::handle() === false && ! $this->option('force')) {
return;
}
if ($this->option('markdown')) {
$this->writeMarkdownTemplate();
}
}
/**
* Write the Markdown template for the mailable.
*
* @return void
*/
protected function writeMarkdownTemplate()
{
$path = $this->viewPath(
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,178 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Str;
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 handle()
{
if (parent::handle() === false && ! $this->option('force')) {
return false;
}
if ($this->option('all')) {
$this->input->setOption('factory', true);
$this->input->setOption('seed', true);
$this->input->setOption('migration', true);
$this->input->setOption('controller', true);
$this->input->setOption('resource', true);
}
if ($this->option('factory')) {
$this->createFactory();
}
if ($this->option('migration')) {
$this->createMigration();
}
if ($this->option('seed')) {
$this->createSeeder();
}
if ($this->option('controller') || $this->option('resource') || $this->option('api')) {
$this->createController();
}
}
/**
* Create a model factory for the model.
*
* @return void
*/
protected function createFactory()
{
$factory = Str::studly(class_basename($this->argument('name')));
$this->call('make:factory', [
'name' => "{$factory}Factory",
'--model' => $this->qualifyClass($this->getNameInput()),
]);
}
/**
* Create a migration file for the model.
*
* @return void
*/
protected function createMigration()
{
$table = Str::snake(Str::pluralStudly(class_basename($this->argument('name'))));
if ($this->option('pivot')) {
$table = Str::singular($table);
}
$this->call('make:migration', [
'name' => "create_{$table}_table",
'--create' => $table,
]);
}
/**
* Create a seeder file for the model.
*
* @return void
*/
protected function createSeeder()
{
$seeder = Str::studly(class_basename($this->argument('name')));
$this->call('make:seed', [
'name' => "{$seeder}Seeder",
]);
}
/**
* 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', array_filter([
'name' => "{$controller}Controller",
'--model' => $this->option('resource') || $this->option('api') ? $modelName : null,
'--api' => $this->option('api'),
]));
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return $this->option('pivot')
? $this->resolveStubPath('/stubs/model.pivot.stub')
: $this->resolveStubPath('/stubs/model.stub');
}
/**
* Resolve the fully-qualified path to the stub.
*
* @param string $stub
* @return string
*/
protected function resolveStubPath($stub)
{
return file_exists($customPath = $this->laravel->basePath(trim($stub, '/')))
? $customPath
: __DIR__.$stub;
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['all', 'a', InputOption::VALUE_NONE, 'Generate a migration, seeder, factory, and resource controller for the model'],
['controller', 'c', InputOption::VALUE_NONE, 'Create a new controller for the model'],
['factory', 'f', InputOption::VALUE_NONE, 'Create a new factory for the model'],
['force', null, 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'],
['seed', 's', InputOption::VALUE_NONE, 'Create a new seeder file for the model'],
['pivot', 'p', InputOption::VALUE_NONE, 'Indicates if the generated model should be a custom intermediate table model'],
['resource', 'r', InputOption::VALUE_NONE, 'Indicates if the generated controller should be a resource controller'],
['api', null, InputOption::VALUE_NONE, 'Indicates if the generated controller should be an API controller'],
];
}
}

View File

@@ -0,0 +1,118 @@
<?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 handle()
{
if (parent::handle() === false && ! $this->option('force')) {
return;
}
if ($this->option('markdown')) {
$this->writeMarkdownTemplate();
}
}
/**
* Write the Markdown template for the mailable.
*
* @return void
*/
protected function writeMarkdownTemplate()
{
$path = $this->viewPath(
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,113 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Str;
use Symfony\Component\Console\Input\InputOption;
class ObserverMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:observer';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new observer class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Observer';
/**
* Build the class with the given name.
*
* @param string $name
* @return string
*/
protected function buildClass($name)
{
$stub = parent::buildClass($name);
$model = $this->option('model');
return $model ? $this->replaceModel($stub, $model) : $stub;
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return $this->option('model')
? __DIR__.'/stubs/observer.stub'
: __DIR__.'/stubs/observer.plain.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);
$namespaceModel = $this->laravel->getNamespace().$model;
if (Str::startsWith($model, '\\')) {
$stub = str_replace('NamespacedDummyModel', trim($model, '\\'), $stub);
} else {
$stub = str_replace('NamespacedDummyModel', $namespaceModel, $stub);
}
$stub = str_replace(
"use {$namespaceModel};\nuse {$namespaceModel};", "use {$namespaceModel};", $stub
);
$model = class_basename(trim($model, '\\'));
$stub = str_replace('DocDummyModel', Str::snake($model, ' '), $stub);
$stub = str_replace('DummyModel', $model, $stub);
return str_replace('dummyModel', Str::camel($model), $stub);
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Observers';
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getOptions()
{
return [
['model', 'm', InputOption::VALUE_OPTIONAL, 'The model that the observer applies to.'],
];
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
class OptimizeClearCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'optimize:clear';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Remove the cached bootstrap files';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
$this->call('view:clear');
$this->call('cache:clear');
$this->call('route:clear');
$this->call('config:clear');
$this->call('clear-compiled');
$this->info('Caches cleared successfully!');
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
class OptimizeCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'optimize';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Cache the framework bootstrap files';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
$this->call('config:cache');
$this->call('route:cache');
$this->info('Files cached successfully!');
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Foundation\PackageManifest;
class PackageDiscoverCommand extends Command
{
/**
* The console command signature.
*
* @var string
*/
protected $signature = 'package:discover';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Rebuild the cached package manifest';
/**
* Execute the console command.
*
* @param \Illuminate\Foundation\PackageManifest $manifest
* @return void
*/
public function handle(PackageManifest $manifest)
{
$manifest->build();
foreach (array_keys($manifest->manifest) as $package) {
$this->line("Discovered Package: <info>{$package}</info>");
}
$this->info('Package manifest generated successfully.');
}
}

View File

@@ -0,0 +1,182 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Str;
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)
{
$model = $this->userProviderModel();
if (! $model) {
return $stub;
}
return str_replace(
$this->rootNamespace().'User',
$model,
$stub
);
}
/**
* Get the model for the guard's user provider.
*
* @return string|null
*/
protected function userProviderModel()
{
$config = $this->laravel['config'];
$guard = $this->option('guard') ?: $config->get('auth.defaults.guard');
return $config->get(
'auth.providers.'.$config->get('auth.guards.'.$guard.'.provider').'.model'
);
}
/**
* 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, '\\')) {
$namespacedModel = trim($model, '\\');
} else {
$namespacedModel = $this->laravel->getNamespace().$model;
}
$model = class_basename(trim($model, '\\'));
$dummyUser = class_basename($this->userProviderModel());
$dummyModel = Str::camel($model) === 'user' ? 'model' : $model;
$replace = [
'NamespacedDummyModel' => $namespacedModel,
'{{ namespacedModel }}' => $namespacedModel,
'{{namespacedModel}}' => $namespacedModel,
'DummyModel' => $model,
'{{ model }}' => $model,
'{{model}}' => $model,
'dummyModel' => Str::camel($dummyModel),
'{{ modelVariable }}' => Str::camel($dummyModel),
'{{modelVariable}}' => Str::camel($dummyModel),
'DummyUser' => $dummyUser,
'{{ user }}' => $dummyUser,
'{{user}}' => $dummyUser,
'$user' => '$'.Str::camel($dummyUser),
];
$stub = str_replace(
array_keys($replace), array_values($replace), $stub
);
return str_replace(
"use {$namespacedModel};\nuse {$namespacedModel};", "use {$namespacedModel};", $stub
);
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return $this->option('model')
? $this->resolveStubPath('/stubs/policy.stub')
: $this->resolveStubPath('/stubs/policy.plain.stub');
}
/**
* Resolve the fully-qualified path to the stub.
*
* @param string $stub
* @return string
*/
protected function resolveStubPath($stub)
{
return file_exists($customPath = $this->laravel->basePath(trim($stub, '/')))
? $customPath
: __DIR__.$stub;
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Policies';
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getOptions()
{
return [
['model', 'm', InputOption::VALUE_OPTIONAL, 'The model that the policy applies to'],
['guard', 'g', InputOption::VALUE_OPTIONAL, 'The guard that the policy relies on'],
];
}
}

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\Console\Kernel as KernelContract;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
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)
{
$kernel->call(...array_values($this->data));
}
}

View File

@@ -0,0 +1,63 @@
<?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 $this->resolveStubPath('/stubs/request.stub');
}
/**
* Resolve the fully-qualified path to the stub.
*
* @param string $stub
* @return string
*/
protected function resolveStubPath($stub)
{
return file_exists($customPath = $this->laravel->basePath(trim($stub, '/')))
? $customPath
: __DIR__.$stub;
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Http\Requests';
}
}

View File

@@ -0,0 +1,104 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Str;
use Symfony\Component\Console\Input\InputOption;
class ResourceMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:resource';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new resource';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Resource';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
if ($this->collection()) {
$this->type = 'Resource collection';
}
parent::handle();
}
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return $this->collection()
? $this->resolveStubPath('/stubs/resource-collection.stub')
: $this->resolveStubPath('/stubs/resource.stub');
}
/**
* Determine if the command is generating a resource collection.
*
* @return bool
*/
protected function collection()
{
return $this->option('collection') ||
Str::endsWith($this->argument('name'), 'Collection');
}
/**
* Resolve the fully-qualified path to the stub.
*
* @param string $stub
* @return string
*/
protected function resolveStubPath($stub)
{
return file_exists($customPath = $this->laravel->basePath(trim($stub, '/')))
? $customPath
: __DIR__.$stub;
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Http\Resources';
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['collection', 'c', InputOption::VALUE_NONE, 'Create a resource collection'],
];
}
}

View File

@@ -0,0 +1,109 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Kernel as ConsoleKernelContract;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Routing\RouteCollection;
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 handle()
{
$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\Contracts\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}}', var_export($routes->compile(), true), $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 handle()
{
$this->files->delete($this->laravel->getCachedRoutesPath());
$this->info('Route cache cleared!');
}
}

View File

@@ -0,0 +1,264 @@
<?php
namespace Illuminate\Foundation\Console;
use Closure;
use Illuminate\Console\Command;
use Illuminate\Routing\Route;
use Illuminate\Routing\Router;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
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;
/**
* The table headers for the command.
*
* @var array
*/
protected $headers = ['Domain', 'Method', 'URI', 'Name', 'Action', 'Middleware'];
/**
* The columns to display when using the "compact" flag.
*
* @var array
*/
protected $compactColumns = ['method', 'uri', 'action'];
/**
* Create a new route command instance.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function __construct(Router $router)
{
parent::__construct();
$this->router = $router;
}
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
if (empty($this->router->getRoutes())) {
return $this->error("Your application doesn't have any routes.");
}
if (empty($routes = $this->getRoutes())) {
return $this->error("Your application doesn't have any routes matching the given criteria.");
}
$this->displayRoutes($routes);
}
/**
* Compile the routes into a displayable format.
*
* @return array
*/
protected function getRoutes()
{
$routes = collect($this->router->getRoutes())->map(function ($route) {
return $this->getRouteInformation($route);
})->filter()->all();
if ($sort = $this->option('sort')) {
$routes = $this->sortRoutes($sort, $routes);
}
if ($this->option('reverse')) {
$routes = array_reverse($routes);
}
return $this->pluckColumns($routes);
}
/**
* Get the route information for a given route.
*
* @param \Illuminate\Routing\Route $route
* @return array
*/
protected function getRouteInformation(Route $route)
{
return $this->filterRoute([
'domain' => $route->domain(),
'method' => implode('|', $route->methods()),
'uri' => $route->uri(),
'name' => $route->getName(),
'action' => ltrim($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, array $routes)
{
return Arr::sort($routes, function ($route) use ($sort) {
return $route[$sort];
});
}
/**
* Remove unnecessary columns from the routes.
*
* @param array $routes
* @return array
*/
protected function pluckColumns(array $routes)
{
return array_map(function ($route) {
return Arr::only($route, $this->getColumns());
}, $routes);
}
/**
* Display the route information on the console.
*
* @param array $routes
* @return void
*/
protected function displayRoutes(array $routes)
{
if ($this->option('json')) {
$this->line(json_encode(array_values($routes)));
return;
}
$this->table($this->getHeaders(), $routes);
}
/**
* Get before filters.
*
* @param \Illuminate\Routing\Route $route
* @return string
*/
protected function getMiddleware($route)
{
return collect($this->router->gatherRouteMiddleware($route))->map(function ($middleware) {
return $middleware instanceof Closure ? 'Closure' : $middleware;
})->implode("\n");
}
/**
* 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'], strtoupper($this->option('method')))) {
return;
}
return $route;
}
/**
* Get the table headers for the visible columns.
*
* @return array
*/
protected function getHeaders()
{
return Arr::only($this->headers, array_keys($this->getColumns()));
}
/**
* Get the column names to show (lowercase table headers).
*
* @return array
*/
protected function getColumns()
{
$availableColumns = array_map('strtolower', $this->headers);
if ($this->option('compact')) {
return array_intersect($availableColumns, $this->compactColumns);
}
if ($columns = $this->option('columns')) {
return array_intersect($availableColumns, $this->parseColumns($columns));
}
return $availableColumns;
}
/**
* Parse the column list.
*
* @param array $columns
* @return array
*/
protected function parseColumns(array $columns)
{
$results = [];
foreach ($columns as $i => $column) {
if (Str::contains($column, ',')) {
$results = array_merge($results, explode(',', $column));
} else {
$results[] = $column;
}
}
return array_map('strtolower', $results);
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['columns', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Columns to include in the route table'],
['compact', 'c', InputOption::VALUE_NONE, 'Only show method, URI and action columns'],
['json', null, InputOption::VALUE_NONE, 'Output the route list as JSON'],
['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 (domain, method, uri, name, action, middleware) to sort by', 'uri'],
];
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
class RuleMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:rule';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new validation rule';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Rule';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
$relativePath = '/stubs/rule.stub';
return file_exists($customPath = $this->laravel->basePath(trim($relativePath, '/')))
? $customPath
: __DIR__.$relativePath;
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Rules';
}
}

View File

@@ -0,0 +1,121 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Env;
use Illuminate\Support\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';
/**
* The current port offset.
*
* @var int
*/
protected $portOffset = 0;
/**
* Execute the console command.
*
* @return int
*
* @throws \Exception
*/
public function handle()
{
chdir(public_path());
$this->line("<info>Laravel development server started:</info> http://{$this->host()}:{$this->port()}");
passthru($this->serverCommand(), $status);
if ($status && $this->canTryAnotherPort()) {
$this->portOffset += 1;
return $this->handle();
}
return $status;
}
/**
* Get the full server command.
*
* @return string
*/
protected function serverCommand()
{
return sprintf('%s -S %s:%s %s',
ProcessUtils::escapeArgument((new PhpExecutableFinder)->find(false)),
$this->host(),
$this->port(),
ProcessUtils::escapeArgument(base_path('server.php'))
);
}
/**
* 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()
{
$port = $this->input->getOption('port') ?: 8000;
return $port + $this->portOffset;
}
/**
* Check if command has reached its max amount of port tries.
*
* @return bool
*/
protected function canTryAnotherPort()
{
return is_null($this->input->getOption('port')) &&
($this->input->getOption('tries') > $this->portOffset);
}
/**
* 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', Env::get('SERVER_PORT')],
['tries', null, InputOption::VALUE_OPTIONAL, 'The max number of ports to attempt to serve from', 10],
];
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use RuntimeException;
use Symfony\Component\Filesystem\Filesystem as SymfonyFilesystem;
class StorageLinkCommand extends Command
{
/**
* The console command signature.
*
* @var string
*/
protected $signature = 'storage:link {--relative : Create the symbolic link using relative paths}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create the symbolic links configured for the application';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
foreach ($this->links() as $link => $target) {
if (file_exists($link)) {
$this->error("The [$link] link already exists.");
} else {
if ($this->option('relative')) {
$target = $this->getRelativeTarget($link, $target);
}
$this->laravel->make('files')->link($target, $link);
$this->info("The [$link] link has been connected to [$target].");
}
}
$this->info('The links have been created.');
}
/**
* Get the symbolic links that are configured for the application.
*
* @return array
*/
protected function links()
{
return $this->laravel['config']['filesystems.links'] ??
[public_path('storage') => storage_path('app/public')];
}
/**
* Get the relative path to the target.
*
* @param string $link
* @param string $target
* @return string
*/
protected function getRelativeTarget($link, $target)
{
if (! class_exists(SymfonyFilesystem::class)) {
throw new RuntimeException('To enable support for relative links, please install the symfony/filesystem package.');
}
return (new SymfonyFilesystem)->makePathRelative($target, dirname($link));
}
}

View File

@@ -0,0 +1,73 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
class StubPublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'stub:publish {--force : Overwrite any existing files}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publish all stubs that are available for customization';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
if (! is_dir($stubsPath = $this->laravel->basePath('stubs'))) {
(new Filesystem)->makeDirectory($stubsPath);
}
$files = [
__DIR__.'/stubs/job.queued.stub' => $stubsPath.'/job.queued.stub',
__DIR__.'/stubs/job.stub' => $stubsPath.'/job.stub',
__DIR__.'/stubs/model.pivot.stub' => $stubsPath.'/model.pivot.stub',
__DIR__.'/stubs/model.stub' => $stubsPath.'/model.stub',
__DIR__.'/stubs/request.stub' => $stubsPath.'/request.stub',
__DIR__.'/stubs/resource.stub' => $stubsPath.'/resource.stub',
__DIR__.'/stubs/resource-collection.stub' => $stubsPath.'/resource-collection.stub',
__DIR__.'/stubs/test.stub' => $stubsPath.'/test.stub',
__DIR__.'/stubs/test.unit.stub' => $stubsPath.'/test.unit.stub',
realpath(__DIR__.'/../../Database/Console/Factories/stubs/factory.stub') => $stubsPath.'/factory.stub',
realpath(__DIR__.'/../../Database/Console/Seeds/stubs/seeder.stub') => $stubsPath.'/seeder.stub',
realpath(__DIR__.'/../../Database/Migrations/stubs/migration.create.stub') => $stubsPath.'/migration.create.stub',
realpath(__DIR__.'/../../Database/Migrations/stubs/migration.stub') => $stubsPath.'/migration.stub',
realpath(__DIR__.'/../../Database/Migrations/stubs/migration.update.stub') => $stubsPath.'/migration.update.stub',
realpath(__DIR__.'/../../Foundation/Console/stubs/console.stub') => $stubsPath.'/console.stub',
realpath(__DIR__.'/../../Foundation/Console/stubs/policy.plain.stub') => $stubsPath.'/policy.plain.stub',
realpath(__DIR__.'/../../Foundation/Console/stubs/policy.stub') => $stubsPath.'/policy.stub',
realpath(__DIR__.'/../../Foundation/Console/stubs/rule.stub') => $stubsPath.'/rule.stub',
realpath(__DIR__.'/../../Routing/Console/stubs/controller.api.stub') => $stubsPath.'/controller.api.stub',
realpath(__DIR__.'/../../Routing/Console/stubs/controller.invokable.stub') => $stubsPath.'/controller.invokable.stub',
realpath(__DIR__.'/../../Routing/Console/stubs/controller.model.api.stub') => $stubsPath.'/controller.model.api.stub',
realpath(__DIR__.'/../../Routing/Console/stubs/controller.model.stub') => $stubsPath.'/controller.model.stub',
realpath(__DIR__.'/../../Routing/Console/stubs/controller.nested.api.stub') => $stubsPath.'/controller.nested.api.stub',
realpath(__DIR__.'/../../Routing/Console/stubs/controller.nested.stub') => $stubsPath.'/controller.nested.stub',
realpath(__DIR__.'/../../Routing/Console/stubs/controller.plain.stub') => $stubsPath.'/controller.plain.stub',
realpath(__DIR__.'/../../Routing/Console/stubs/controller.stub') => $stubsPath.'/controller.stub',
realpath(__DIR__.'/../../Routing/Console/stubs/middleware.stub') => $stubsPath.'/middleware.stub',
];
foreach ($files as $from => $to) {
if (! file_exists($to) || $this->option('force')) {
file_put_contents($to, file_get_contents($from));
}
}
$this->info('Stubs published successfully.');
}
}

View File

@@ -0,0 +1,93 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Str;
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()
{
return $this->option('unit')
? $this->resolveStubPath('/stubs/test.unit.stub')
: $this->resolveStubPath('/stubs/test.stub');
}
/**
* Resolve the fully-qualified path to the stub.
*
* @param string $stub
* @return string
*/
protected function resolveStubPath($stub)
{
return file_exists($customPath = $this->laravel->basePath(trim($stub, '/')))
? $customPath
: __DIR__.$stub;
}
/**
* Get the destination class path.
*
* @param string $name
* @return string
*/
protected function getPath($name)
{
$name = Str::replaceFirst($this->rootNamespace(), '', $name);
return base_path('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,49 @@
<?php
namespace Illuminate\Foundation\Console;
use Exception;
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 int
*/
public function handle()
{
try {
if (! file_exists(storage_path('framework/down'))) {
$this->comment('Application is already up.');
return true;
}
unlink(storage_path('framework/down'));
$this->info('Application is now live.');
} catch (Exception $e) {
$this->error('Failed to disable maintenance mode.');
$this->error($e->getMessage());
return 1;
}
}
}

View File

@@ -0,0 +1,283 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Arr;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Adapter\Local as LocalAdapter;
use League\Flysystem\Filesystem as Flysystem;
use League\Flysystem\MountManager;
class VendorPublishCommand extends Command
{
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* The provider to publish.
*
* @var string
*/
protected $provider = null;
/**
* The tags to publish.
*
* @var array
*/
protected $tags = [];
/**
* The console command signature.
*
* @var string
*/
protected $signature = 'vendor:publish {--force : Overwrite any existing files}
{--all : Publish assets for all service providers without prompt}
{--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 handle()
{
$this->determineWhatShouldBePublished();
foreach ($this->tags ?: [null] as $tag) {
$this->publishTag($tag);
}
$this->info('Publishing complete.');
}
/**
* Determine the provider or tag(s) to publish.
*
* @return void
*/
protected function determineWhatShouldBePublished()
{
if ($this->option('all')) {
return;
}
[$this->provider, $this->tags] = [
$this->option('provider'), (array) $this->option('tag'),
];
if (! $this->provider && ! $this->tags) {
$this->promptForProviderOrTag();
}
}
/**
* Prompt for which provider or tag to publish.
*
* @return void
*/
protected function promptForProviderOrTag()
{
$choice = $this->choice(
"Which provider or tag's files would you like to publish?",
$choices = $this->publishableChoices()
);
if ($choice == $choices[0] || is_null($choice)) {
return;
}
$this->parseChoice($choice);
}
/**
* The choices available via the prompt.
*
* @return array
*/
protected function publishableChoices()
{
return array_merge(
['<comment>Publish files from all providers and tags listed below</comment>'],
preg_filter('/^/', '<comment>Provider: </comment>', Arr::sort(ServiceProvider::publishableProviders())),
preg_filter('/^/', '<comment>Tag: </comment>', Arr::sort(ServiceProvider::publishableGroups()))
);
}
/**
* Parse the answer that was given via the prompt.
*
* @param string $choice
* @return void
*/
protected function parseChoice($choice)
{
[$type, $value] = explode(': ', strip_tags($choice));
if ($type === 'Provider') {
$this->provider = $value;
} elseif ($type === 'Tag') {
$this->tags = [$value];
}
}
/**
* Publishes the assets for a tag.
*
* @param string $tag
* @return mixed
*/
protected function publishTag($tag)
{
$published = false;
foreach ($this->pathsToPublish($tag) as $from => $to) {
$this->publishItem($from, $to);
$published = true;
}
if ($published === false) {
$this->error('Unable to locate publishable resources.');
}
}
/**
* Get all of the paths to publish.
*
* @param string $tag
* @return array
*/
protected function pathsToPublish($tag)
{
return ServiceProvider::pathsToPublish(
$this->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,87 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
class ViewCacheCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'view:cache';
/**
* The console command description.
*
* @var string
*/
protected $description = "Compile all of the application's Blade templates";
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->call('view:clear');
$this->paths()->each(function ($path) {
$this->compileViews($this->bladeFilesIn([$path]));
});
$this->info('Blade templates cached successfully!');
}
/**
* Compile the given view files.
*
* @param \Illuminate\Support\Collection $views
* @return void
*/
protected function compileViews(Collection $views)
{
$compiler = $this->laravel['view']->getEngineResolver()->resolve('blade')->getCompiler();
$views->map(function (SplFileInfo $file) use ($compiler) {
$compiler->compile($file->getRealPath());
});
}
/**
* Get the Blade files in the given path.
*
* @param array $paths
* @return \Illuminate\Support\Collection
*/
protected function bladeFilesIn(array $paths)
{
return collect(
Finder::create()
->in($paths)
->exclude('vendor')
->name('*.blade.php')
->files()
);
}
/**
* Get all of the possible view paths.
*
* @return \Illuminate\Support\Collection
*/
protected function paths()
{
$finder = $this->laravel['view']->getFinder();
return collect($finder->getPaths())->merge(
collect($finder->getHints())->flatten()
);
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use RuntimeException;
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
*
* @throws \RuntimeException
*/
public function handle()
{
$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,36 @@
<?php
namespace DummyNamespace;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class DummyClass implements CastsAttributes
{
/**
* Cast the given value.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return mixed
*/
public function get($model, $key, $value, $attributes)
{
return $value;
}
/**
* Prepare the given value for storage.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param array $value
* @param array $attributes
* @return mixed
*/
public function set($model, $key, $value, $attributes)
{
return $value;
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace DummyNamespace;
use NamespacedDummyUserModel;
class DummyClass
{
/**
* Create a new channel instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Authenticate the user's access to the channel.
*
* @param \NamespacedDummyUserModel $user
* @return array|bool
*/
public function join(DummyUser $user)
{
//
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace {{ namespace }};
use Illuminate\Console\Command;
class {{ class }} extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = '{{ 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 int
*/
public function handle()
{
return 0;
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace DummyNamespace;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
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 \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace DummyNamespace;
use Exception;
class DummyClass extends Exception
{
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
//
}
/**
* Render the exception as an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function render($request)
{
//
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace DummyNamespace;
use Exception;
class DummyClass extends Exception
{
/**
* Render the exception as an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function render($request)
{
//
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace DummyNamespace;
use Exception;
class DummyClass extends Exception
{
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
//
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace DummyNamespace;
use Exception;
class DummyClass extends Exception
{
//
}

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,33 @@
<?php
namespace DummyNamespace;
use DummyFullEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
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\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
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\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
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\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
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\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
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 {{ namespace }};
use Illuminate\Database\Eloquent\Relations\Pivot;
class {{ class }} extends Pivot
{
//
}

View File

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

View File

@@ -0,0 +1,61 @@
<?php
namespace DummyNamespace;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
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,8 @@
<?php
namespace DummyNamespace;
class DummyClass
{
//
}

View File

@@ -0,0 +1,63 @@
<?php
namespace DummyNamespace;
use NamespacedDummyModel;
class DummyClass
{
/**
* Handle the DocDummyModel "created" event.
*
* @param \NamespacedDummyModel $dummyModel
* @return void
*/
public function created(DummyModel $dummyModel)
{
//
}
/**
* Handle the DocDummyModel "updated" event.
*
* @param \NamespacedDummyModel $dummyModel
* @return void
*/
public function updated(DummyModel $dummyModel)
{
//
}
/**
* Handle the DocDummyModel "deleted" event.
*
* @param \NamespacedDummyModel $dummyModel
* @return void
*/
public function deleted(DummyModel $dummyModel)
{
//
}
/**
* Handle the DocDummyModel "restored" event.
*
* @param \NamespacedDummyModel $dummyModel
* @return void
*/
public function restored(DummyModel $dummyModel)
{
//
}
/**
* Handle the DocDummyModel "force deleted" event.
*
* @param \NamespacedDummyModel $dummyModel
* @return void
*/
public function forceDeleted(DummyModel $dummyModel)
{
//
}
}

View File

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

View File

@@ -0,0 +1,94 @@
<?php
namespace {{ namespace }};
use Illuminate\Auth\Access\HandlesAuthorization;
use {{ namespacedModel }};
use {{ namespacedUserModel }};
class {{ class }}
{
use HandlesAuthorization;
/**
* Determine whether the user can view any models.
*
* @param \{{ namespacedUserModel }} $user
* @return mixed
*/
public function viewAny({{ user }} $user)
{
//
}
/**
* Determine whether the user can view the model.
*
* @param \{{ namespacedUserModel }} $user
* @param \{{ namespacedModel }} ${{ modelVariable }}
* @return mixed
*/
public function view({{ user }} $user, {{ model }} ${{ modelVariable }})
{
//
}
/**
* Determine whether the user can create models.
*
* @param \{{ namespacedUserModel }} $user
* @return mixed
*/
public function create({{ user }} $user)
{
//
}
/**
* Determine whether the user can update the model.
*
* @param \{{ namespacedUserModel }} $user
* @param \{{ namespacedModel }} ${{ modelVariable }}
* @return mixed
*/
public function update({{ user }} $user, {{ model }} ${{ modelVariable }})
{
//
}
/**
* Determine whether the user can delete the model.
*
* @param \{{ namespacedUserModel }} $user
* @param \{{ namespacedModel }} ${{ modelVariable }}
* @return mixed
*/
public function delete({{ user }} $user, {{ model }} ${{ modelVariable }})
{
//
}
/**
* Determine whether the user can restore the model.
*
* @param \{{ namespacedUserModel }} $user
* @param \{{ namespacedModel }} ${{ modelVariable }}
* @return mixed
*/
public function restore({{ user }} $user, {{ model }} ${{ modelVariable }})
{
//
}
/**
* Determine whether the user can permanently delete the model.
*
* @param \{{ namespacedUserModel }} $user
* @param \{{ namespacedModel }} ${{ modelVariable }}
* @return mixed
*/
public function forceDelete({{ user }} $user, {{ model }} ${{ modelVariable }})
{
//
}
}

View File

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

View File

@@ -0,0 +1,30 @@
<?php
namespace {{ namespace }};
use Illuminate\Foundation\Http\FormRequest;
class {{ class }} 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,19 @@
<?php
namespace {{ namespace }};
use Illuminate\Http\Resources\Json\ResourceCollection;
class {{ class }} extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace {{ namespace }};
use Illuminate\Http\Resources\Json\JsonResource;
class {{ class }} extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}

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')->setCompiledRoutes(
{{routes}}
);

View File

@@ -0,0 +1,40 @@
<?php
namespace {{ namespace }};
use Illuminate\Contracts\Validation\Rule;
class {{ class }} implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
//
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The validation error message.';
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace {{ namespace }};
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class {{ class }} extends TestCase
{
/**
* A basic feature test example.
*
* @return void
*/
public function testExample()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace {{ namespace }};
use PHPUnit\Framework\TestCase;
class {{ class }} extends TestCase
{
/**
* A basic unit test example.
*
* @return void
*/
public function testExample()
{
$this->assertTrue(true);
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace DummyNamespace;
use Illuminate\View\Component;
class DummyClass extends Component
{
/**
* Create a new component instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return DummyView;
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace Illuminate\Foundation;
use Closure;
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 $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 $value;
}
return $this->detectWebEnvironment($callback);
}
/**
* Get the environment argument from the console.
*
* @param array $args
* @return string|null
*/
protected function getEnvironmentArgument(array $args)
{
foreach ($args as $i => $value) {
if ($value === '--env') {
return $args[$i + 1] ?? null;
}
if (Str::startsWith($value, '--env')) {
return head(array_slice(explode('=', $value), 1));
}
}
}
}

View File

@@ -0,0 +1,86 @@
<?php
namespace Illuminate\Foundation\Events;
use Illuminate\Support\Reflector;
use Illuminate\Support\Str;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use SplFileInfo;
use Symfony\Component\Finder\Finder;
class DiscoverEvents
{
/**
* Get all of the events and listeners by searching the given listener directory.
*
* @param string $listenerPath
* @param string $basePath
* @return array
*/
public static function within($listenerPath, $basePath)
{
return collect(static::getListenerEvents(
(new Finder)->files()->in($listenerPath), $basePath
))->mapToDictionary(function ($event, $listener) {
return [$event => $listener];
})->all();
}
/**
* Get all of the listeners and their corresponding events.
*
* @param iterable $listeners
* @param string $basePath
* @return array
*/
protected static function getListenerEvents($listeners, $basePath)
{
$listenerEvents = [];
foreach ($listeners as $listener) {
try {
$listener = new ReflectionClass(
static::classFromFile($listener, $basePath)
);
} catch (ReflectionException $e) {
continue;
}
if (! $listener->isInstantiable()) {
continue;
}
foreach ($listener->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
if (! Str::is('handle*', $method->name) ||
! isset($method->getParameters()[0])) {
continue;
}
$listenerEvents[$listener->name.'@'.$method->name] =
Reflector::getParameterClassName($method->getParameters()[0]);
}
}
return array_filter($listenerEvents);
}
/**
* Extract the class name from the given file path.
*
* @param \SplFileInfo $file
* @param string $basePath
* @return string
*/
protected static function classFromFile(SplFileInfo $file, $basePath)
{
$class = trim(Str::replaceFirst($basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR);
return str_replace(
[DIRECTORY_SEPARATOR, ucfirst(basename(app()->path())).'\\'],
['\\', app()->getNamespace()],
ucfirst(Str::replaceLast('.php', '', $class))
);
}
}

View File

@@ -0,0 +1,52 @@
<?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()));
}
/**
* Dispatch the event with the given arguments if the given truth test passes.
*
* @param bool $boolean
* @return void
*/
public static function dispatchIf($boolean, ...$arguments)
{
if ($boolean) {
return event(new static(...$arguments));
}
}
/**
* Dispatch the event with the given arguments unless the given truth test passes.
*
* @param bool $boolean
* @return void
*/
public static function dispatchUnless($boolean, ...$arguments)
{
if (! $boolean) {
return event(new static(...$arguments));
}
}
/**
* 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,522 @@
<?php
namespace Illuminate\Foundation\Exceptions;
use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Debug\ExceptionHandler as ExceptionHandlerContract;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;
use Illuminate\Routing\Router;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Reflector;
use Illuminate\Support\ViewErrorBag;
use Illuminate\Validation\ValidationException;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Application as ConsoleApplication;
use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer;
use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException;
use Symfony\Component\HttpFoundation\RedirectResponse as SymfonyRedirectResponse;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
use Whoops\Handler\HandlerInterface;
use Whoops\Run as Whoops;
class Handler implements ExceptionHandlerContract
{
/**
* The container implementation.
*
* @var \Illuminate\Contracts\Container\Container
*/
protected $container;
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [];
/**
* A list of the internal exception types that should not be reported.
*
* @var array
*/
protected $internalDontReport = [
AuthenticationException::class,
AuthorizationException::class,
HttpException::class,
HttpResponseException::class,
ModelNotFoundException::class,
SuspiciousOperationException::class,
TokenMismatchException::class,
ValidationException::class,
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* 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 \Throwable $e
* @return void
*
* @throws \Throwable
*/
public function report(Throwable $e)
{
if ($this->shouldntReport($e)) {
return;
}
if (Reflector::isCallable($reportCallable = [$e, 'report'])) {
$this->container->call($reportCallable);
return;
}
try {
$logger = $this->container->make(LoggerInterface::class);
} catch (Exception $ex) {
throw $e;
}
$logger->error(
$e->getMessage(),
array_merge(
$this->exceptionContext($e),
$this->context(),
['exception' => $e]
)
);
}
/**
* Determine if the exception should be reported.
*
* @param \Throwable $e
* @return bool
*/
public function shouldReport(Throwable $e)
{
return ! $this->shouldntReport($e);
}
/**
* Determine if the exception is in the "do not report" list.
*
* @param \Throwable $e
* @return bool
*/
protected function shouldntReport(Throwable $e)
{
$dontReport = array_merge($this->dontReport, $this->internalDontReport);
return ! is_null(Arr::first($dontReport, function ($type) use ($e) {
return $e instanceof $type;
}));
}
/**
* Get the default exception context variables for logging.
*
* @param \Throwable $e
* @return array
*/
protected function exceptionContext(Throwable $e)
{
return [];
}
/**
* Get the default context variables for logging.
*
* @return array
*/
protected function context()
{
try {
return array_filter([
'userId' => Auth::id(),
// 'email' => optional(Auth::user())->email,
]);
} catch (Throwable $e) {
return [];
}
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $e
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Throwable
*/
public function render($request, Throwable $e)
{
if (method_exists($e, 'render') && $response = $e->render($request)) {
return Router::toResponse($request, $response);
} elseif ($e instanceof Responsable) {
return $e->toResponse($request);
}
$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 $request->expectsJson()
? $this->prepareJsonResponse($request, $e)
: $this->prepareResponse($request, $e);
}
/**
* Prepare exception for rendering.
*
* @param \Throwable $e
* @return \Throwable
*/
protected function prepareException(Throwable $e)
{
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
} elseif ($e instanceof AuthorizationException) {
$e = new AccessDeniedHttpException($e->getMessage(), $e);
} elseif ($e instanceof TokenMismatchException) {
$e = new HttpException(419, $e->getMessage(), $e);
} elseif ($e instanceof SuspiciousOperationException) {
$e = new NotFoundHttpException('Bad hostname provided.', $e);
}
return $e;
}
/**
* Convert an authentication exception into a response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
return $request->expectsJson()
? response()->json(['message' => $exception->getMessage()], 401)
: redirect()->guest($exception->redirectTo() ?? route('login'));
}
/**
* Create a response object from the given validation exception.
*
* @param \Illuminate\Validation\ValidationException $e
* @param \Illuminate\Http\Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function convertValidationExceptionToResponse(ValidationException $e, $request)
{
if ($e->response) {
return $e->response;
}
return $request->expectsJson()
? $this->invalidJson($request, $e)
: $this->invalid($request, $e);
}
/**
* Convert a validation exception into a response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Validation\ValidationException $exception
* @return \Illuminate\Http\Response
*/
protected function invalid($request, ValidationException $exception)
{
return redirect($exception->redirectTo ?? url()->previous())
->withInput(Arr::except($request->input(), $this->dontFlash))
->withErrors($exception->errors(), $exception->errorBag);
}
/**
* Convert a validation exception into a JSON response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Validation\ValidationException $exception
* @return \Illuminate\Http\JsonResponse
*/
protected function invalidJson($request, ValidationException $exception)
{
return response()->json([
'message' => $exception->getMessage(),
'errors' => $exception->errors(),
], $exception->status);
}
/**
* Prepare a response for the given exception.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $e
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function prepareResponse($request, Throwable $e)
{
if (! $this->isHttpException($e) && config('app.debug')) {
return $this->toIlluminateResponse($this->convertExceptionToResponse($e), $e);
}
if (! $this->isHttpException($e)) {
$e = new HttpException(500, $e->getMessage());
}
return $this->toIlluminateResponse(
$this->renderHttpException($e), $e
);
}
/**
* Create a Symfony response for the given exception.
*
* @param \Throwable $e
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function convertExceptionToResponse(Throwable $e)
{
return new SymfonyResponse(
$this->renderExceptionContent($e),
$this->isHttpException($e) ? $e->getStatusCode() : 500,
$this->isHttpException($e) ? $e->getHeaders() : []
);
}
/**
* Get the response content for the given exception.
*
* @param \Throwable $e
* @return string
*/
protected function renderExceptionContent(Throwable $e)
{
try {
return config('app.debug') && class_exists(Whoops::class)
? $this->renderExceptionWithWhoops($e)
: $this->renderExceptionWithSymfony($e, config('app.debug'));
} catch (Exception $e) {
return $this->renderExceptionWithSymfony($e, config('app.debug'));
}
}
/**
* Render an exception to a string using "Whoops".
*
* @param \Throwable $e
* @return string
*/
protected function renderExceptionWithWhoops(Throwable $e)
{
return tap(new Whoops, function ($whoops) {
$whoops->appendHandler($this->whoopsHandler());
$whoops->writeToOutput(false);
$whoops->allowQuit(false);
})->handleException($e);
}
/**
* Get the Whoops handler for the application.
*
* @return \Whoops\Handler\Handler
*/
protected function whoopsHandler()
{
try {
return app(HandlerInterface::class);
} catch (BindingResolutionException $e) {
return (new WhoopsHandler)->forDebug();
}
}
/**
* Render an exception to a string using Symfony.
*
* @param \Throwable $e
* @param bool $debug
* @return string
*/
protected function renderExceptionWithSymfony(Throwable $e, $debug)
{
$renderer = new HtmlErrorRenderer($debug);
return $renderer->render($e)->getAsString();
}
/**
* Render the given HttpException.
*
* @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function renderHttpException(HttpExceptionInterface $e)
{
$this->registerErrorViewPaths();
if (view()->exists($view = $this->getHttpExceptionView($e))) {
return response()->view($view, [
'errors' => new ViewErrorBag,
'exception' => $e,
], $e->getStatusCode(), $e->getHeaders());
}
return $this->convertExceptionToResponse($e);
}
/**
* Register the error template hint paths.
*
* @return void
*/
protected function registerErrorViewPaths()
{
$paths = collect(config('view.paths'));
View::replaceNamespace('errors', $paths->map(function ($path) {
return "{$path}/errors";
})->push(__DIR__.'/views')->all());
}
/**
* Get the view used to render HTTP exceptions.
*
* @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e
* @return string
*/
protected function getHttpExceptionView(HttpExceptionInterface $e)
{
return "errors::{$e->getStatusCode()}";
}
/**
* Map the given exception into an Illuminate response.
*
* @param \Symfony\Component\HttpFoundation\Response $response
* @param \Throwable $e
* @return \Illuminate\Http\Response
*/
protected function toIlluminateResponse($response, Throwable $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);
}
/**
* Prepare a JSON response for the given exception.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $e
* @return \Illuminate\Http\JsonResponse
*/
protected function prepareJsonResponse($request, Throwable $e)
{
return new JsonResponse(
$this->convertExceptionToArray($e),
$this->isHttpException($e) ? $e->getStatusCode() : 500,
$this->isHttpException($e) ? $e->getHeaders() : [],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
);
}
/**
* Convert the given exception to an array.
*
* @param \Throwable $e
* @return array
*/
protected function convertExceptionToArray(Throwable $e)
{
return config('app.debug') ? [
'message' => $e->getMessage(),
'exception' => get_class($e),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => collect($e->getTrace())->map(function ($trace) {
return Arr::except($trace, ['args']);
})->all(),
] : [
'message' => $this->isHttpException($e) ? $e->getMessage() : 'Server Error',
];
}
/**
* Render an exception to the console.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param \Throwable $e
* @return void
*/
public function renderForConsole($output, Throwable $e)
{
(new ConsoleApplication)->renderThrowable($e, $output);
}
/**
* Determine if the given exception is an HTTP exception.
*
* @param \Throwable $e
* @return bool
*/
protected function isHttpException(Throwable $e)
{
return $e instanceof HttpExceptionInterface;
}
}

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