storage/logs/.gitignore 0000666 00000000016 13436750035 0011153 0 ustar 00 *
!.gitignore
resources/lang/en/validation.php 0000666 00000013211 13436750035 0012754 0 ustar 00 'The :attribute must be accepted.',
'active_url' => 'The :attribute is not a valid URL.',
'after' => 'The :attribute must be a date after :date.',
'alpha' => 'The :attribute may only contain letters.',
'alpha_dash' => 'The :attribute may only contain letters, numbers, and dashes.',
'alpha_num' => 'The :attribute may only contain letters and numbers.',
'array' => 'The :attribute must be an array.',
'before' => 'The :attribute must be a date before :date.',
'between' => [
'numeric' => 'The :attribute must be between :min and :max.',
'file' => 'The :attribute must be between :min and :max kilobytes.',
'string' => 'The :attribute must be between :min and :max characters.',
'array' => 'The :attribute must have between :min and :max items.',
],
'boolean' => 'The :attribute field must be true or false.',
'confirmed' => 'The :attribute confirmation does not match.',
'date' => 'The :attribute is not a valid date.',
'date_format' => 'The :attribute does not match the format :format.',
'different' => 'The :attribute and :other must be different.',
'digits' => 'The :attribute must be :digits digits.',
'digits_between' => 'The :attribute must be between :min and :max digits.',
'email' => 'The :attribute must be a valid email address.',
'exists' => 'The selected :attribute is invalid.',
'filled' => 'The :attribute field is required.',
'image' => 'The :attribute must be an image.',
'in' => 'The selected :attribute is invalid.',
'integer' => 'The :attribute must be an integer.',
'ip' => 'The :attribute must be a valid IP address.',
'json' => 'The :attribute must be a valid JSON string.',
'max' => [
'numeric' => 'The :attribute may not be greater than :max.',
'file' => 'The :attribute may not be greater than :max kilobytes.',
'string' => 'The :attribute may not be greater than :max characters.',
'array' => 'The :attribute may not have more than :max items.',
],
'mimes' => 'The :attribute must be a file of type: :values.',
'min' => [
'numeric' => 'The :attribute must be at least :min.',
'file' => 'The :attribute must be at least :min kilobytes.',
'string' => 'The :attribute must be at least :min characters.',
'array' => 'The :attribute must have at least :min items.',
],
'not_in' => 'The selected :attribute is invalid.',
'numeric' => 'The :attribute must be a number.',
'regex' => 'The :attribute format is invalid.',
'required' => 'The :attribute field is required.',
'required_if' => 'The :attribute field is required when :other is :value.',
'required_unless' => 'The :attribute field is required unless :other is in :value.',
'required_with' => 'The :attribute field is required when :values is present.',
'required_with_all' => 'The :attribute field is required when :values is present.',
'required_without' => 'The :attribute field is required when :values is not present.',
'required_without_all' => 'The :attribute field is required when none of :values are present.',
'same' => 'The :attribute and :other must match.',
'size' => [
'numeric' => 'The :attribute must be :size.',
'file' => 'The :attribute must be :size kilobytes.',
'string' => 'The :attribute must be :size characters.',
'array' => 'The :attribute must contain :size items.',
],
'string' => 'The :attribute must be a string.',
'timezone' => 'The :attribute must be a valid zone.',
'unique' => 'The :attribute has already been taken.',
'url' => 'The :attribute format is invalid.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => [],
];
phpunit.xml 0000666 00000001360 13436750035 0006767 0 ustar 00
./tests
./src
config/broadcasting.php 0000666 00000002477 13436750035 0011206 0 ustar 00 env('BROADCAST_DRIVER', 'pusher'),
/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_KEY'),
'secret' => env('PUSHER_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
],
];
config/queue.php 0000666 00000005177 13436750035 0007672 0 ustar 00 env('QUEUE_DRIVER', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection information for each server that
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'expire' => 60,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'ttr' => 60,
],
'sqs' => [
'driver' => 'sqs',
'key' => 'your-public-key',
'secret' => 'your-secret-key',
'queue' => 'your-queue-url',
'region' => 'us-east-1',
],
'iron' => [
'driver' => 'iron',
'host' => 'mq-aws-us-east-1.iron.io',
'token' => 'your-token',
'project' => 'your-project-id',
'queue' => 'your-queue-name',
'encrypt' => true,
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'expire' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control which database and table are used to store the jobs that
| have failed. You may change them to any database / table you wish.
|
*/
'failed' => [
'database' => env('DB_CONNECTION', 'mysql'), 'table' => 'failed_jobs',
],
];
config/database.php 0000666 00000010711 13436750035 0010300 0 ustar 00 PDO::FETCH_CLASS,
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'testing' => [
'driver' => 'sqlite',
'database' => ':memory:',
],
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', base_path('database/database.sqlite')),
'prefix' => env('DB_PREFIX', ''),
],
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', 3306),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => env('DB_PREFIX', ''),
'timezone' => env('DB_TIMEZONE', '+00:00'),
'strict' => false,
],
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', 5432),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => env('DB_PREFIX', ''),
'schema' => 'public',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'prefix' => env('DB_PREFIX', ''),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'cluster' => env('REDIS_CLUSTER', false),
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_DATABASE', 0),
'password' => env('REDIS_PASSWORD', null),
],
],
];
config/auth.php 0000666 00000005635 13436750035 0007506 0 ustar 00 [
'guard' => env('AUTH_GUARD', 'api'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'api' => ['driver' => 'api'],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
//
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| Here you may set the options for resetting passwords including the view
| that is your password reset e-mail. You may also set the name of the
| table that maintains all of the reset tokens for your application.
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
//
],
];
config/app.php 0000666 00000002765 13436750035 0007326 0 ustar 00 env('APP_KEY', 'SomeRandomString!!!'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => env('APP_LOCALE', 'en'),
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
];
config/view.php 0000666 00000001774 13436750035 0007517 0 ustar 00 [
realpath(base_path('resources/views')),
],
/*
|--------------------------------------------------------------------------
| Compiled View Path
|--------------------------------------------------------------------------
|
| This option determines where all the compiled Blade templates will be
| stored for your application. Typically, this is within the storage
| directory. However, as usual, you are free to change this value.
|
*/
'compiled' => realpath(storage_path('framework/views')),
];
config/cache.php 0000666 00000004204 13436750035 0007577 0 ustar 00 env('CACHE_DRIVER', 'memcached'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
*/
'stores' => [
'array' => [
'driver' => 'array',
],
'database' => [
'driver' => 'database',
'table' => env('CACHE_DATABASE_TABLE', 'cache'),
'connection' => null,
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache'),
],
'memcached' => [
'driver' => 'memcached',
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'), 'port' => env('MEMCACHED_PORT', 11211), 'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing a RAM based store such as APC or Memcached, there might
| be other applications utilizing the same cache. So, we'll specify a
| value to get prefixed to all our keys so we can avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', 'laravel'),
];
src/Testing/DatabaseMigrations.php 0000666 00000000567 13436750035 0013244 0 ustar 00 artisan('migrate');
$this->beforeApplicationDestroyed(function () {
$this->artisan('migrate:rollback');
});
}
}
src/Testing/Concerns/MakesHttpRequests.php 0000666 00000024051 13436750035 0014703 0 ustar 00 mb_strlen($content, '8bit'),
'CONTENT_TYPE' => 'application/json',
'Accept' => 'application/json',
], $headers);
$this->call(
$method, $uri, [], [], [], $this->transformHeadersToServerVars($headers), $content
);
return $this;
}
/**
* Visit the given URI with a GET request.
*
* @param string $uri
* @param array $headers
* @return $this
*/
public function get($uri, array $headers = [])
{
$server = $this->transformHeadersToServerVars($headers);
$this->call('GET', $uri, [], [], [], $server);
return $this;
}
/**
* Visit the given URI with a POST request.
*
* @param string $uri
* @param array $data
* @param array $headers
* @return $this
*/
public function post($uri, array $data = [], array $headers = [])
{
$server = $this->transformHeadersToServerVars($headers);
$this->call('POST', $uri, $data, [], [], $server);
return $this;
}
/**
* Visit the given URI with a PUT request.
*
* @param string $uri
* @param array $data
* @param array $headers
* @return $this
*/
public function put($uri, array $data = [], array $headers = [])
{
$server = $this->transformHeadersToServerVars($headers);
$this->call('PUT', $uri, $data, [], [], $server);
return $this;
}
/**
* Visit the given URI with a PATCH request.
*
* @param string $uri
* @param array $data
* @param array $headers
* @return $this
*/
public function patch($uri, array $data = [], array $headers = [])
{
$server = $this->transformHeadersToServerVars($headers);
$this->call('PATCH', $uri, $data, [], [], $server);
return $this;
}
/**
* Visit the given URI with a DELETE request.
*
* @param string $uri
* @param array $data
* @param array $headers
* @return $this
*/
public function delete($uri, array $data = [], array $headers = [])
{
$server = $this->transformHeadersToServerVars($headers);
$this->call('DELETE', $uri, $data, [], [], $server);
return $this;
}
/**
* Send the given request through the application.
*
* This method allows you to fully customize the entire Request object.
*
* @param \Illuminate\Http\Request $request
* @return $this
*/
public function handle(Request $request)
{
$this->currentUri = $request->fullUrl();
$this->response = $this->app->prepareResponse($this->app->handle($request));
return $this;
}
/**
* Assert that the response contains JSON.
*
* @param array|null $data
* @return $this
*/
protected function shouldReturnJson(array $data = null)
{
return $this->receiveJson($data);
}
/**
* Assert that the response contains JSON.
*
* @param array|null $data
* @return $this|null
*/
protected function receiveJson($data = null)
{
return $this->seeJson($data);
}
/**
* Assert that the response contains an exact JSON array.
*
* @param array $data
* @return $this
*/
public function seeJsonEquals(array $data)
{
$actual = json_encode(array_sort_recursive(
json_decode($this->response->getContent(), true)
));
$this->assertEquals(json_encode(array_sort_recursive($data)), $actual);
return $this;
}
/**
* Assert that the response contains JSON.
*
* @param array|null $data
* @param bool $negate
* @return $this
*/
public function seeJson(array $data = null, $negate = false)
{
if (is_null($data)) {
$this->assertJson(
$this->response->getContent(), "JSON was not returned from [{$this->currentUri}]."
);
return $this;
}
return $this->seeJsonContains($data, $negate);
}
/**
* Assert that the response doesn't contain JSON.
*
* @param array|null $data
* @return $this
*/
public function dontSeeJson(array $data = null)
{
return $this->seeJson($data, true);
}
/**
* Assert that the JSON response has a given structure.
*
* @param array|null $structure
* @param array|null $responseData
* @return $this
*/
public function seeJsonStructure(array $structure = null, $responseData = null)
{
if (is_null($structure)) {
return $this->seeJson();
}
if (! $responseData) {
$responseData = json_decode($this->response->getContent(), true);
}
foreach ($structure as $key => $value) {
if (is_array($value)) {
$this->assertArrayHasKey($key, $responseData);
$this->seeJsonStructure($structure[$key], $responseData[$key]);
} else {
$this->assertArrayHasKey($value, $responseData);
}
}
}
/**
* Assert that the response contains the given JSON.
*
* @param array $data
* @param bool $negate
* @return $this
*/
protected function seeJsonContains(array $data, $negate = false)
{
$method = $negate ? 'assertFalse' : 'assertTrue';
$actual = json_decode($this->response->getContent(), true);
if (is_null($actual) || $actual === false) {
return $this->fail('Invalid JSON was returned from the route. Perhaps an exception was thrown?');
}
$actual = json_encode(array_sort_recursive(
(array) $actual
));
foreach (array_sort_recursive($data) as $key => $value) {
$expected = $this->formatToExpectedJson($key, $value);
$this->{$method}(
Str::contains($actual, $expected),
($negate ? 'Found unexpected' : 'Unable to find')." JSON fragment [{$expected}] within [{$actual}]."
);
}
return $this;
}
/**
* Format the given key and value into a JSON string for expectation checks.
*
* @param string $key
* @param mixed $value
* @return string
*/
protected function formatToExpectedJson($key, $value)
{
$expected = json_encode([$key => $value]);
if (Str::startsWith($expected, '{')) {
$expected = substr($expected, 1);
}
if (Str::endsWith($expected, '}')) {
$expected = substr($expected, 0, -1);
}
return $expected;
}
/**
* Call the given URI and return the Response.
*
* @param string $method
* @param string $uri
* @param array $parameters
* @param array $cookies
* @param array $files
* @param array $server
* @param string $content
* @return \Illuminate\Http\Response
*/
public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
{
$this->currentUri = $this->prepareUrlForRequest($uri);
$request = Request::create(
$this->currentUri, $method, $parameters,
$cookies, $files, $server, $content
);
return $this->response = $this->app->prepareResponse(
$this->app->handle($request)
);
}
/**
* Turn the given URI into a fully qualified URL.
*
* @param string $uri
* @return string
*/
protected function prepareUrlForRequest($uri)
{
if (Str::startsWith($uri, '/')) {
$uri = substr($uri, 1);
}
if (! Str::startsWith($uri, 'http')) {
$uri = $this->baseUrl.'/'.$uri;
}
return trim($uri, '/');
}
/**
* Transform headers array to array of $_SERVER vars with HTTP_* format.
*
* @param array $headers
* @return array
*/
protected function transformHeadersToServerVars(array $headers)
{
$server = [];
$prefix = 'HTTP_';
foreach ($headers as $name => $value) {
$name = strtr(strtoupper($name), '-', '_');
if (! starts_with($name, $prefix) && $name != 'CONTENT_TYPE') {
$name = $prefix.$name;
}
$server[$name] = $value;
}
return $server;
}
/**
* Assert that the client response has an OK status code.
*
* @return void
*/
public function assertResponseOk()
{
$actual = $this->response->getStatusCode();
return PHPUnit::assertTrue($this->response->isOk(), "Expected status code 200, got {$actual}.");
}
/**
* Assert that the client response has a given code.
*
* @param int $code
* @return void
*/
public function assertResponseStatus($code)
{
$actual = $this->response->getStatusCode();
return PHPUnit::assertEquals($code, $this->response->getStatusCode(), "Expected status code {$code}, got {$actual}.");
}
/**
* Disable middleware for the test.
*
* @return $this
*/
public function withoutMiddleware()
{
$this->app->instance('middleware.disable', true);
return $this;
}
}
src/Testing/TestCase.php 0000666 00000016541 13436750035 0011215 0 ustar 00 app = $this->createApplication();
Facade::clearResolvedInstances();
}
/**
* Setup the test environment.
*
* @return void
*/
public function setUp()
{
if (! $this->app) {
$this->refreshApplication();
}
$this->setUpTraits();
}
/**
* Boot the testing helper traits.
*
* @return void
*/
protected function setUpTraits()
{
$uses = array_flip(class_uses_recursive(get_class($this)));
if (isset($uses[DatabaseTransactions::class])) {
$this->beginDatabaseTransaction();
}
if (isset($uses[DatabaseMigrations::class])) {
$this->runDatabaseMigrations();
}
if (isset($uses[WithoutMiddleware::class])) {
$this->disableMiddlewareForAllTests();
}
if (isset($uses[WithoutEvents::class])) {
$this->disableEventsForAllTests();
}
}
/**
* Clean up the testing environment before the next test.
*
* @return void
*/
public function tearDown()
{
if (class_exists('Mockery')) {
Mockery::close();
}
if ($this->app) {
foreach ($this->beforeApplicationDestroyedCallbacks as $callback) {
call_user_func($callback);
}
$this->app->flush();
$this->app = null;
}
}
/**
* Assert that a given where condition exists in the database.
*
* @param string $table
* @param array $data
* @return $this
*/
protected function seeInDatabase($table, array $data)
{
$count = $this->app->make('db')->table($table)->where($data)->count();
$this->assertGreaterThan(0, $count, sprintf(
'Unable to find row in database table [%s] that matched attributes [%s].', $table, json_encode($data)
));
return $this;
}
/**
* Assert that a given where condition does not exist in the database.
*
* @param string $table
* @param array $data
* @return $this
*/
protected function missingFromDatabase($table, array $data)
{
return $this->notSeeInDatabase($table, $data);
}
/**
* Assert that a given where condition does not exist in the database.
*
* @param string $table
* @param array $data
* @return $this
*/
protected function notSeeInDatabase($table, array $data)
{
$count = $this->app->make('db')->table($table)->where($data)->count();
$this->assertEquals(0, $count, sprintf(
'Found unexpected records in database table [%s] that matched attributes [%s].', $table, json_encode($data)
));
return $this;
}
/**
* Specify a list of events that should be fired for the given operation.
*
* These events will be mocked, so that handlers will not actually be executed.
*
* @param array|string $events
* @return $this
*/
public function expectsEvents($events)
{
$events = is_array($events) ? $events : func_get_args();
$mock = Mockery::spy('Illuminate\Contracts\Events\Dispatcher');
$mock->shouldReceive('fire')->andReturnUsing(function ($called) use (&$events) {
foreach ($events as $key => $event) {
if ((is_string($called) && $called === $event) ||
(is_string($called) && is_subclass_of($called, $event)) ||
(is_object($called) && $called instanceof $event)) {
unset($events[$key]);
}
}
});
$this->beforeApplicationDestroyed(function () use (&$events) {
if ($events) {
throw new Exception(
'The following events were not fired: ['.implode(', ', $events).']'
);
}
});
$this->app->instance('events', $mock);
return $this;
}
/**
* Mock the event dispatcher so all events are silenced.
*
* @return $this
*/
protected function withoutEvents()
{
$mock = Mockery::mock('Illuminate\Contracts\Events\Dispatcher');
$mock->shouldReceive('fire');
$this->app->instance('events', $mock);
return $this;
}
/**
* Specify a list of jobs that should be dispatched for the given operation.
*
* These jobs will be mocked, so that handlers will not actually be executed.
*
* @param array|string $jobs
* @return $this
*/
protected function expectsJobs($jobs)
{
$jobs = is_array($jobs) ? $jobs : func_get_args();
$mock = Mockery::mock('Illuminate\Bus\Dispatcher[dispatch]', [$this->app]);
foreach ($jobs as $job) {
$mock->shouldReceive('dispatch')->atLeast()->once()
->with(Mockery::type($job));
}
$this->app->instance(
'Illuminate\Contracts\Bus\Dispatcher', $mock
);
return $this;
}
/**
* Set the currently logged in user for the application.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param string|null $driver
* @return $this
*/
public function actingAs(Authenticatable $user, $driver = null)
{
$this->be($user, $driver);
return $this;
}
/**
* Set the currently logged in user for the application.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param string|null $driver
* @return void
*/
public function be(Authenticatable $user, $driver = null)
{
$this->app['auth']->guard($driver)->setUser($user);
}
/**
* Call artisan command and return code.
*
* @param string $command
* @param array $parameters
* @return int
*/
public function artisan($command, $parameters = [])
{
return $this->code = $this->app['Illuminate\Contracts\Console\Kernel']->call($command, $parameters);
}
/**
* Register a callback to be run before the application is destroyed.
*
* @param callable $callback
* @return void
*/
protected function beforeApplicationDestroyed(callable $callback)
{
$this->beforeApplicationDestroyedCallbacks[] = $callback;
}
}
src/Testing/DatabaseTransactions.php 0000666 00000000574 13436750035 0013576 0 ustar 00 app->make('db')->beginTransaction();
$this->beforeApplicationDestroyed(function () {
$this->app->make('db')->rollBack();
});
}
}
src/Http/Redirector.php 0000666 00000003533 13436750035 0011103 0 ustar 00 app = $app;
}
/**
* Create a new redirect response to the given path.
*
* @param string $path
* @param int $status
* @param array $headers
* @param bool $secure
* @return \Illuminate\Http\RedirectResponse
*/
public function to($path, $status = 302, $headers = [], $secure = null)
{
$path = $this->app->make('url')->to($path, [], $secure);
return $this->createRedirect($path, $status, $headers);
}
/**
* Create a new redirect response to a named route.
*
* @param string $route
* @param array $parameters
* @param int $status
* @param array $headers
* @return \Illuminate\Http\RedirectResponse
*/
public function route($route, $parameters = [], $status = 302, $headers = [])
{
$path = $this->app->make('url')->route($route, $parameters);
return $this->to($path, $status, $headers);
}
/**
* Create a new redirect response.
*
* @param string $path
* @param int $status
* @param array $headers
* @return \Illuminate\Http\RedirectResponse
*/
protected function createRedirect($path, $status, $headers)
{
$redirect = new RedirectResponse($path, $status, $headers);
$redirect->setRequest($this->app->make('request'));
$redirect->setSession($this->app->make('session.store'));
return $redirect;
}
}
src/Http/ResponseFactory.php 0000666 00000003432 13436750035 0012125 0 ustar 00 toArray();
}
return new JsonResponse($data, $status, $headers, $options);
}
/**
* Create a new file download response.
*
* @param \SplFileInfo|string $file
* @param string $name
* @param array $headers
* @param null|string $disposition
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse
*/
public function download($file, $name = null, array $headers = [], $disposition = 'attachment')
{
$response = new BinaryFileResponse($file, 200, $headers, true, $disposition);
if (! is_null($name)) {
return $response->setContentDisposition($disposition, $name, str_replace('%', '', Str::ascii($name)));
}
return $response;
}
}
src/Console/Kernel.php 0000666 00000010674 13436750035 0010710 0 ustar 00 app = $app;
$this->app->prepareForConsoleCommand();
$this->defineConsoleSchedule();
}
/**
* Define the application's command schedule.
*
* @return void
*/
protected function defineConsoleSchedule()
{
$this->app->instance(
'Illuminate\Console\Scheduling\Schedule', $schedule = new Schedule
);
$this->schedule($schedule);
}
/**
* Run the console application.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return int
*/
public function handle($input, $output = null)
{
try {
return $this->getArtisan()->run($input, $output);
} catch (Exception $e) {
$this->reportException($e);
$this->renderException($output, $e);
return 1;
} catch (Throwable $e) {
$e = new FatalThrowableError($e);
$this->reportException($e);
$this->renderException($output, $e);
return 1;
}
}
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//
}
/**
* Run an Artisan console command by name.
*
* @param string $command
* @param array $parameters
* @return int
*/
public function call($command, array $parameters = [])
{
return $this->getArtisan()->call($command, $parameters);
}
/**
* Queue the given console command.
*
* @param string $command
* @param array $parameters
* @return void
*/
public function queue($command, array $parameters = [])
{
throw new RuntimeException('Queueing Artisan commands is not supported by Lumen.');
}
/**
* Get all of the commands registered with the console.
*
* @return array
*/
public function all()
{
return $this->getArtisan()->all();
}
/**
* Get the output for the last run command.
*
* @return string
*/
public function output()
{
return $this->getArtisan()->output();
}
/**
* 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->app->make('events'), $this->app->version()))
->resolveCommands($this->getCommands());
}
return $this->artisan;
}
/**
* Get the commands to add to the application.
*
* @return array
*/
protected function getCommands()
{
return array_merge($this->commands, [
'Illuminate\Console\Scheduling\ScheduleRunCommand',
]);
}
/**
* Report the exception to the exception handler.
*
* @param \Exception $e
* @return void
*/
protected function reportException(Exception $e)
{
$this->app['Illuminate\Contracts\Debug\ExceptionHandler']->report($e);
}
/**
* Report the exception to the exception handler.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param \Exception $e
* @return void
*/
protected function renderException($output, Exception $e)
{
$this->app['Illuminate\Contracts\Debug\ExceptionHandler']->renderForConsole($output, $e);
}
}
src/Application.php 0000666 00000050235 13436750035 0010326 0 ustar 00 basePath = $basePath;
$this->bootstrapContainer();
$this->registerErrorHandling();
}
/**
* Bootstrap the application container.
*
* @return void
*/
protected function bootstrapContainer()
{
static::setInstance($this);
$this->instance('app', $this);
$this->instance('Laravel\Lumen\Application', $this);
$this->instance('path', $this->path());
$this->registerContainerAliases();
}
/**
* Get the version number of the application.
*
* @return string
*/
public function version()
{
return 'Lumen (5.2.2) (Laravel Components 5.2.*)';
}
/**
* Determine if the application is currently down for maintenance.
*
* @return bool
*/
public function isDownForMaintenance()
{
return false;
}
/**
* Get or check the current application environment.
*
* @param mixed
* @return string
*/
public function environment()
{
$env = env('APP_ENV', 'production');
if (func_num_args() > 0) {
$patterns = is_array(func_get_arg(0)) ? func_get_arg(0) : func_get_args();
foreach ($patterns as $pattern) {
if (Str::is($pattern, $env)) {
return true;
}
}
return false;
}
return $env;
}
/**
* Register a service provider with the application.
*
* @param \Illuminate\Support\ServiceProvider|string $provider
* @param array $options
* @param bool $force
* @return \Illuminate\Support\ServiceProvider
*/
public function register($provider, $options = [], $force = false)
{
if (! $provider instanceof ServiceProvider) {
$provider = new $provider($this);
}
if (array_key_exists($providerName = get_class($provider), $this->loadedProviders)) {
return;
}
$this->loadedProviders[$providerName] = true;
$provider->register();
$provider->boot();
}
/**
* Register a deferred provider and service.
*
* @param string $provider
* @param string|null $service
* @return void
*/
public function registerDeferredProvider($provider, $service = null)
{
return $this->register($provider);
}
/**
* Resolve the given type from the container.
*
* @param string $abstract
* @param array $parameters
* @return mixed
*/
public function make($abstract, array $parameters = [])
{
$abstract = $this->getAlias($this->normalize($abstract));
if (array_key_exists($abstract, $this->availableBindings) &&
! array_key_exists($this->availableBindings[$abstract], $this->ranServiceBinders)) {
$this->{$method = $this->availableBindings[$abstract]}();
$this->ranServiceBinders[$method] = true;
}
return parent::make($abstract, $parameters);
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerAuthBindings()
{
$this->singleton('auth', function () {
return $this->loadComponent('auth', 'Illuminate\Auth\AuthServiceProvider', 'auth');
});
$this->singleton('auth.driver', function () {
return $this->loadComponent('auth', 'Illuminate\Auth\AuthServiceProvider', 'auth.driver');
});
$this->singleton('Illuminate\Contracts\Auth\Access\Gate', function () {
return $this->loadComponent('auth', 'Illuminate\Auth\AuthServiceProvider', 'Illuminate\Contracts\Auth\Access\Gate');
});
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerBroadcastingBindings()
{
$this->singleton('Illuminate\Contracts\Broadcasting\Broadcaster', function () {
$this->configure('broadcasting');
$this->register('Illuminate\Broadcasting\BroadcastServiceProvider');
return $this->make('Illuminate\Contracts\Broadcasting\Broadcaster');
});
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerBusBindings()
{
$this->singleton('Illuminate\Contracts\Bus\Dispatcher', function () {
$this->register('Illuminate\Bus\BusServiceProvider');
return $this->make('Illuminate\Contracts\Bus\Dispatcher');
});
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerCacheBindings()
{
$this->singleton('cache', function () {
return $this->loadComponent('cache', 'Illuminate\Cache\CacheServiceProvider');
});
$this->singleton('cache.store', function () {
return $this->loadComponent('cache', 'Illuminate\Cache\CacheServiceProvider', 'cache.store');
});
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerComposerBindings()
{
$this->singleton('composer', function ($app) {
return new Composer($app->make('files'), $this->basePath());
});
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerConfigBindings()
{
$this->singleton('config', function () {
return new ConfigRepository;
});
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerDatabaseBindings()
{
$this->singleton('db', function () {
return $this->loadComponent(
'database', [
'Illuminate\Database\DatabaseServiceProvider',
'Illuminate\Pagination\PaginationServiceProvider',
], 'db'
);
});
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerEncrypterBindings()
{
$this->singleton('encrypter', function () {
return $this->loadComponent('app', 'Illuminate\Encryption\EncryptionServiceProvider', 'encrypter');
});
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerEventBindings()
{
$this->singleton('events', function () {
$this->register('Illuminate\Events\EventServiceProvider');
return $this->make('events');
});
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerFilesBindings()
{
$this->singleton('files', function () {
return new Filesystem;
});
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerHashBindings()
{
$this->singleton('hash', function () {
$this->register('Illuminate\Hashing\HashServiceProvider');
return $this->make('hash');
});
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerLogBindings()
{
$this->singleton('Psr\Log\LoggerInterface', function () {
if ($this->monologConfigurator) {
return call_user_func($this->monologConfigurator, new Logger('lumen'));
} else {
return new Logger('lumen', [$this->getMonologHandler()]);
}
});
}
/**
* Define a callback to be used to configure Monolog.
*
* @param callable $callback
* @return $this
*/
public function configureMonologUsing(callable $callback)
{
$this->monologConfigurator = $callback;
return $this;
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerQueueBindings()
{
$this->singleton('queue', function () {
return $this->loadComponent('queue', 'Illuminate\Queue\QueueServiceProvider', 'queue');
});
$this->singleton('queue.connection', function () {
return $this->loadComponent('queue', 'Illuminate\Queue\QueueServiceProvider', 'queue.connection');
});
}
/**
* Get the Monolog handler for the application.
*
* @return \Monolog\Handler\AbstractHandler
*/
protected function getMonologHandler()
{
return (new StreamHandler(storage_path('logs/lumen.log'), Logger::DEBUG))
->setFormatter(new LineFormatter(null, null, true, true));
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerRequestBindings()
{
$this->singleton('Illuminate\Http\Request', function () {
return Request::capture()->setUserResolver(function () {
return $this->make('auth')->user();
})->setRouteResolver(function () {
return $this->currentRoute;
});
});
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerTranslationBindings()
{
$this->singleton('translator', function () {
$this->configure('app');
$this->instance('path.lang', $this->getLanguagePath());
$this->register('Illuminate\Translation\TranslationServiceProvider');
return $this->make('translator');
});
}
/**
* Get the path to the application's language files.
*
* @return string
*/
protected function getLanguagePath()
{
if (is_dir($appPath = $this->path().'/resources/lang')) {
return $appPath;
} else {
return __DIR__.'/../resources/lang';
}
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerValidatorBindings()
{
$this->singleton('validator', function () {
$this->register('Illuminate\Validation\ValidationServiceProvider');
return $this->make('validator');
});
}
/**
* Register container bindings for the application.
*
* @return void
*/
protected function registerViewBindings()
{
$this->singleton('view', function () {
return $this->loadComponent('view', 'Illuminate\View\ViewServiceProvider');
});
}
/**
* Configure and load the given component and provider.
*
* @param string $config
* @param array|string $providers
* @param string|null $return
* @return mixed
*/
public function loadComponent($config, $providers, $return = null)
{
$this->configure($config);
foreach ((array) $providers as $provider) {
$this->register($provider);
}
return $this->make($return ?: $config);
}
/**
* Load a configuration file into the application.
*
* @param string $name
* @return void
*/
public function configure($name)
{
if (isset($this->loadedConfigurations[$name])) {
return;
}
$this->loadedConfigurations[$name] = true;
$path = $this->getConfigurationPath($name);
if ($path) {
$this->make('config')->set($name, require $path);
}
}
/**
* Get the path to the given configuration file.
*
* If no name is provided, then we'll return the path to the config folder.
*
* @param string|null $name
* @return string
*/
public function getConfigurationPath($name = null)
{
if (! $name) {
$appConfigDir = $this->basePath('config').'/';
if (file_exists($appConfigDir)) {
return $appConfigDir;
} elseif (file_exists($path = __DIR__.'/../config/')) {
return $path;
}
} else {
$appConfigPath = $this->basePath('config').'/'.$name.'.php';
if (file_exists($appConfigPath)) {
return $appConfigPath;
} elseif (file_exists($path = __DIR__.'/../config/'.$name.'.php')) {
return $path;
}
}
}
/**
* Register the facades for the application.
*
* @return void
*/
public function withFacades()
{
Facade::setFacadeApplication($this);
if (! static::$aliasesRegistered) {
static::$aliasesRegistered = true;
class_alias('Illuminate\Support\Facades\Auth', 'Auth');
class_alias('Illuminate\Support\Facades\Cache', 'Cache');
class_alias('Illuminate\Support\Facades\DB', 'DB');
class_alias('Illuminate\Support\Facades\Event', 'Event');
class_alias('Illuminate\Support\Facades\Gate', 'Gate');
class_alias('Illuminate\Support\Facades\Log', 'Log');
class_alias('Illuminate\Support\Facades\Queue', 'Queue');
class_alias('Illuminate\Support\Facades\Schema', 'Schema');
class_alias('Illuminate\Support\Facades\Validator', 'Validator');
}
}
/**
* Load the Eloquent library for the application.
*
* @return void
*/
public function withEloquent()
{
$this->make('db');
}
/**
* Get the path to the application "app" directory.
*
* @return string
*/
public function path()
{
return $this->basePath.DIRECTORY_SEPARATOR.'app';
}
/**
* Get the base path for the application.
*
* @param string|null $path
* @return string
*/
public function basePath($path = null)
{
if (isset($this->basePath)) {
return $this->basePath.($path ? '/'.$path : $path);
}
if ($this->runningInConsole()) {
$this->basePath = getcwd();
} else {
$this->basePath = realpath(getcwd().'/../');
}
return $this->basePath($path);
}
/**
* Get the database path for the application.
*
* @return string
*/
public function databasePath()
{
return $this->basePath().'/database';
}
/**
* Get the storage path for the application.
*
* @param string|null $path
* @return string
*/
public function storagePath($path = null)
{
return $this->basePath().'/storage'.($path ? '/'.$path : $path);
}
/**
* Determine if the application is running in the console.
*
* @return bool
*/
public function runningInConsole()
{
return php_sapi_name() == 'cli';
}
/**
* Prepare the application to execute a console command.
*
* @return void
*/
public function prepareForConsoleCommand()
{
$this->withFacades();
$this->make('cache');
$this->make('queue');
$this->configure('database');
$this->register('Illuminate\Database\MigrationServiceProvider');
$this->register('Illuminate\Database\SeedServiceProvider');
$this->register('Illuminate\Queue\ConsoleServiceProvider');
}
/**
* Register the core container aliases.
*
* @return void
*/
protected function registerContainerAliases()
{
$this->aliases = [
'Illuminate\Contracts\Foundation\Application' => 'app',
'Illuminate\Contracts\Auth\Factory' => 'auth',
'Illuminate\Contracts\Auth\Guard' => 'auth.driver',
'Illuminate\Contracts\Cache\Factory' => 'cache',
'Illuminate\Contracts\Cache\Repository' => 'cache.store',
'Illuminate\Contracts\Config\Repository' => 'config',
'Illuminate\Container\Container' => 'app',
'Illuminate\Contracts\Container\Container' => 'app',
'Illuminate\Contracts\Encryption\Encrypter' => 'encrypter',
'Illuminate\Contracts\Events\Dispatcher' => 'events',
'Illuminate\Contracts\Hashing\Hasher' => 'hash',
'log' => 'Psr\Log\LoggerInterface',
'Illuminate\Contracts\Queue\Factory' => 'queue',
'Illuminate\Contracts\Queue\Queue' => 'queue.connection',
'request' => 'Illuminate\Http\Request',
'Illuminate\Contracts\View\Factory' => 'view',
];
}
/**
* The available container bindings and their respective load methods.
*
* @var array
*/
public $availableBindings = [
'auth' => 'registerAuthBindings',
'auth.driver' => 'registerAuthBindings',
'Illuminate\Contracts\Auth\Guard' => 'registerAuthBindings',
'Illuminate\Contracts\Auth\Access\Gate' => 'registerAuthBindings',
'Illuminate\Contracts\Broadcasting\Broadcaster' => 'registerBroadcastingBindings',
'Illuminate\Contracts\Bus\Dispatcher' => 'registerBusBindings',
'cache' => 'registerCacheBindings',
'Illuminate\Contracts\Cache\Factory' => 'registerCacheBindings',
'Illuminate\Contracts\Cache\Repository' => 'registerCacheBindings',
'composer' => 'registerComposerBindings',
'config' => 'registerConfigBindings',
'db' => 'registerDatabaseBindings',
'Illuminate\Database\Eloquent\Factory' => 'registerDatabaseBindings',
'encrypter' => 'registerEncrypterBindings',
'Illuminate\Contracts\Encryption\Encrypter' => 'registerEncrypterBindings',
'events' => 'registerEventBindings',
'Illuminate\Contracts\Events\Dispatcher' => 'registerEventBindings',
'files' => 'registerFilesBindings',
'hash' => 'registerHashBindings',
'Illuminate\Contracts\Hashing\Hasher' => 'registerHashBindings',
'log' => 'registerLogBindings',
'Psr\Log\LoggerInterface' => 'registerLogBindings',
'queue' => 'registerQueueBindings',
'queue.connection' => 'registerQueueBindings',
'Illuminate\Contracts\Queue\Factory' => 'registerQueueBindings',
'Illuminate\Contracts\Queue\Queue' => 'registerQueueBindings',
'request' => 'registerRequestBindings',
'Illuminate\Http\Request' => 'registerRequestBindings',
'translator' => 'registerTranslationBindings',
'validator' => 'registerValidatorBindings',
'view' => 'registerViewBindings',
'Illuminate\Contracts\View\Factory' => 'registerViewBindings',
];
}
src/Concerns/RegistersExceptionHandlers.php 0000666 00000007240 13436750035 0015142 0 ustar 00 handleUncaughtException($e);
});
register_shutdown_function(function () {
$this->handleShutdown();
});
}
/**
* Handle the application shutdown routine.
*
* @return void
*/
protected function handleShutdown()
{
if (! is_null($error = error_get_last()) && $this->isFatalError($error['type'])) {
$this->handleUncaughtException(new FatalErrorException(
$error['message'], $error['type'], 0, $error['file'], $error['line']
));
}
}
/**
* Determine if the error type is fatal.
*
* @param int $type
* @return bool
*/
protected function isFatalError($type)
{
$errorCodes = [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE];
if (defined('FATAL_ERROR')) {
$errorCodes[] = FATAL_ERROR;
}
return in_array($type, $errorCodes);
}
/**
* Send the exception to the handler and return the response.
*
* @param \Throwable $e
* @return Response
*/
protected function sendExceptionToHandler($e)
{
$handler = $this->resolveExceptionHandler();
if ($e instanceof Error) {
$e = new FatalThrowableError($e);
}
$handler->report($e);
return $handler->render($this->make('request'), $e);
}
/**
* Handle an uncaught exception instance.
*
* @param \Throwable $e
* @return void
*/
protected function handleUncaughtException($e)
{
$handler = $this->resolveExceptionHandler();
if ($e instanceof Error) {
$e = new FatalThrowableError($e);
}
$handler->report($e);
if ($this->runningInConsole()) {
$handler->renderForConsole(new ConsoleOutput, $e);
} else {
$handler->render($this->make('request'), $e)->send();
}
}
/**
* Get the exception handler from the container.
*
* @return mixed
*/
protected function resolveExceptionHandler()
{
if ($this->bound('Illuminate\Contracts\Debug\ExceptionHandler')) {
return $this->make('Illuminate\Contracts\Debug\ExceptionHandler');
} else {
return $this->make('Laravel\Lumen\Exceptions\Handler');
}
}
}
src/Concerns/RoutesRequests.php 0000666 00000041244 13436750035 0012652 0 ustar 00 groupAttributes;
$this->groupAttributes = $attributes;
call_user_func($callback, $this);
$this->groupAttributes = $parentGroupAttributes;
}
/**
* Register a route with the application.
*
* @param string $uri
* @param mixed $action
* @return $this
*/
public function get($uri, $action)
{
$this->addRoute('GET', $uri, $action);
return $this;
}
/**
* Register a route with the application.
*
* @param string $uri
* @param mixed $action
* @return $this
*/
public function post($uri, $action)
{
$this->addRoute('POST', $uri, $action);
return $this;
}
/**
* Register a route with the application.
*
* @param string $uri
* @param mixed $action
* @return $this
*/
public function put($uri, $action)
{
$this->addRoute('PUT', $uri, $action);
return $this;
}
/**
* Register a route with the application.
*
* @param string $uri
* @param mixed $action
* @return $this
*/
public function patch($uri, $action)
{
$this->addRoute('PATCH', $uri, $action);
return $this;
}
/**
* Register a route with the application.
*
* @param string $uri
* @param mixed $action
* @return $this
*/
public function delete($uri, $action)
{
$this->addRoute('DELETE', $uri, $action);
return $this;
}
/**
* Register a route with the application.
*
* @param string $uri
* @param mixed $action
* @return $this
*/
public function options($uri, $action)
{
$this->addRoute('OPTIONS', $uri, $action);
return $this;
}
/**
* Add a route to the collection.
*
* @param string $method
* @param string $uri
* @param mixed $action
*/
public function addRoute($method, $uri, $action)
{
$action = $this->parseAction($action);
if (isset($this->groupAttributes)) {
if (isset($this->groupAttributes['prefix'])) {
$uri = trim($this->groupAttributes['prefix'], '/').'/'.trim($uri, '/');
}
$action = $this->mergeGroupAttributes($action);
}
$uri = '/'.trim($uri, '/');
if (isset($action['as'])) {
$this->namedRoutes[$action['as']] = $uri;
}
$this->routes[$method.$uri] = ['method' => $method, 'uri' => $uri, 'action' => $action];
}
/**
* Parse the action into an array format.
*
* @param mixed $action
* @return array
*/
protected function parseAction($action)
{
if (is_string($action)) {
return ['uses' => $action];
} elseif (! is_array($action)) {
return [$action];
}
return $action;
}
/**
* Merge the group attributes into the action.
*
* @param array $action
* @return array
*/
protected function mergeGroupAttributes(array $action)
{
return $this->mergeNamespaceGroup(
$this->mergeMiddlewareGroup($action)
);
}
/**
* Merge the namespace group into the action.
*
* @param array $action
* @return array
*/
protected function mergeNamespaceGroup(array $action)
{
if (isset($this->groupAttributes['namespace']) && isset($action['uses'])) {
$action['uses'] = $this->groupAttributes['namespace'].'\\'.$action['uses'];
}
return $action;
}
/**
* Merge the middleware group into the action.
*
* @param array $action
* @return array
*/
protected function mergeMiddlewareGroup($action)
{
if (isset($this->groupAttributes['middleware'])) {
if (isset($action['middleware'])) {
$action['middleware'] = $this->groupAttributes['middleware'].'|'.$action['middleware'];
} else {
$action['middleware'] = $this->groupAttributes['middleware'];
}
}
return $action;
}
/**
* Add new middleware to the application.
*
* @param Closure|array $middleware
* @return $this
*/
public function middleware($middleware)
{
if (! is_array($middleware)) {
$middleware = [$middleware];
}
$this->middleware = array_unique(array_merge($this->middleware, $middleware));
return $this;
}
/**
* Define the route middleware for the application.
*
* @param array $middleware
* @return $this
*/
public function routeMiddleware(array $middleware)
{
$this->routeMiddleware = array_merge($this->routeMiddleware, $middleware);
return $this;
}
/**
* {@inheritdoc}
*/
public function handle(SymfonyRequest $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
return $this->dispatch($request);
}
/**
* Run the application and send the response.
*
* @param SymfonyRequest|null $request
* @return void
*/
public function run($request = null)
{
$response = $this->dispatch($request);
if ($response instanceof SymfonyResponse) {
$response->send();
} else {
echo (string) $response;
}
if (count($this->middleware) > 0) {
$this->callTerminableMiddleware($response);
}
}
/**
* Call the terminable middleware.
*
* @param mixed $response
* @return void
*/
protected function callTerminableMiddleware($response)
{
$response = $this->prepareResponse($response);
foreach ($this->middleware as $middleware) {
if (! is_string($middleware)) {
continue;
}
$instance = $this->make($middleware);
if (method_exists($instance, 'terminate')) {
$instance->terminate($this->make('request'), $response);
}
}
}
/**
* Dispatch the incoming request.
*
* @param SymfonyRequest|null $request
* @return Response
*/
public function dispatch($request = null)
{
list($method, $pathInfo) = $this->parseIncomingRequest($request);
try {
return $this->sendThroughPipeline($this->middleware, function () use ($method, $pathInfo) {
if (isset($this->routes[$method.$pathInfo])) {
return $this->handleFoundRoute([true, $this->routes[$method.$pathInfo]['action'], []]);
}
return $this->handleDispatcherResponse(
$this->createDispatcher()->dispatch($method, $pathInfo)
);
});
} catch (Exception $e) {
return $this->sendExceptionToHandler($e);
} catch (Throwable $e) {
return $this->sendExceptionToHandler($e);
}
}
/**
* Parse the incoming request and return the method and path info.
*
* @return array
*/
protected function parseIncomingRequest($request)
{
if ($request) {
$this->instance('Illuminate\Http\Request', $request);
$this->ranServiceBinders['registerRequestBindings'] = true;
return [$request->getMethod(), $request->getPathInfo()];
} else {
return [$this->getMethod(), $this->getPathInfo()];
}
}
/**
* Create a FastRoute dispatcher instance for the application.
*
* @return Dispatcher
*/
protected function createDispatcher()
{
return $this->dispatcher ?: \FastRoute\simpleDispatcher(function ($r) {
foreach ($this->routes as $route) {
$r->addRoute($route['method'], $route['uri'], $route['action']);
}
});
}
/**
* Set the FastRoute dispatcher instance.
*
* @param \FastRoute\Dispatcher $dispatcher
* @return void
*/
public function setDispatcher(Dispatcher $dispatcher)
{
$this->dispatcher = $dispatcher;
}
/**
* Handle the response from the FastRoute dispatcher.
*
* @param array $routeInfo
* @return mixed
*/
protected function handleDispatcherResponse($routeInfo)
{
switch ($routeInfo[0]) {
case Dispatcher::NOT_FOUND:
throw new NotFoundHttpException;
case Dispatcher::METHOD_NOT_ALLOWED:
throw new MethodNotAllowedHttpException($routeInfo[1]);
case Dispatcher::FOUND:
return $this->handleFoundRoute($routeInfo);
}
}
/**
* Handle a route found by the dispatcher.
*
* @param array $routeInfo
* @return mixed
*/
protected function handleFoundRoute($routeInfo)
{
$this->currentRoute = $routeInfo;
$action = $routeInfo[1];
// Pipe through route middleware...
if (isset($action['middleware'])) {
$middleware = $this->gatherMiddlewareClassNames($action['middleware']);
return $this->prepareResponse($this->sendThroughPipeline($middleware, function () use ($routeInfo) {
return $this->callActionOnArrayBasedRoute($routeInfo);
}));
}
return $this->prepareResponse(
$this->callActionOnArrayBasedRoute($routeInfo)
);
}
/**
* Call the Closure on the array based route.
*
* @param array $routeInfo
* @return mixed
*/
protected function callActionOnArrayBasedRoute($routeInfo)
{
$action = $routeInfo[1];
if (isset($action['uses'])) {
return $this->prepareResponse($this->callControllerAction($routeInfo));
}
foreach ($action as $value) {
if ($value instanceof Closure) {
$closure = $value->bindTo(new RoutingClosure);
break;
}
}
try {
return $this->prepareResponse($this->call($closure, $routeInfo[2]));
} catch (HttpResponseException $e) {
return $e->getResponse();
}
}
/**
* Call a controller based route.
*
* @param array $routeInfo
* @return mixed
*/
protected function callControllerAction($routeInfo)
{
list($controller, $method) = explode('@', $routeInfo[1]['uses']);
if (! method_exists($instance = $this->make($controller), $method)) {
throw new NotFoundHttpException;
}
if ($instance instanceof LumenController) {
return $this->callLumenController($instance, $method, $routeInfo);
} else {
return $this->callControllerCallable(
[$instance, $method], $routeInfo[2]
);
}
}
/**
* Send the request through a Lumen controller.
*
* @param mixed $instance
* @param string $method
* @param array $routeInfo
* @return mixed
*/
protected function callLumenController($instance, $method, $routeInfo)
{
$middleware = $instance->getMiddlewareForMethod($method);
if (count($middleware) > 0) {
return $this->callLumenControllerWithMiddleware(
$instance, $method, $routeInfo, $middleware
);
} else {
return $this->callControllerCallable(
[$instance, $method], $routeInfo[2]
);
}
}
/**
* Send the request through a set of controller middleware.
*
* @param mixed $instance
* @param string $method
* @param array $routeInfo
* @param array $middleware
* @return mixed
*/
protected function callLumenControllerWithMiddleware($instance, $method, $routeInfo, $middleware)
{
$middleware = $this->gatherMiddlewareClassNames($middleware);
return $this->sendThroughPipeline($middleware, function () use ($instance, $method, $routeInfo) {
return $this->callControllerCallable([$instance, $method], $routeInfo[2]);
});
}
/**
* Call a controller callable and return the response.
*
* @param callable $callable
* @param array $parameters
* @return \Illuminate\Http\Response
*/
protected function callControllerCallable(callable $callable, array $parameters = [])
{
try {
return $this->prepareResponse(
$this->call($callable, $parameters)
);
} catch (HttpResponseException $e) {
return $e->getResponse();
}
}
/**
* Gather the full class names for the middleware short-cut string.
*
* @param string $middleware
* @return array
*/
protected function gatherMiddlewareClassNames($middleware)
{
$middleware = is_string($middleware) ? explode('|', $middleware) : (array) $middleware;
return array_map(function ($name) {
list($name, $parameters) = array_pad(explode(':', $name, 2), 2, null);
return array_get($this->routeMiddleware, $name, $name).($parameters ? ':'.$parameters : '');
}, $middleware);
}
/**
* Send the request through the pipeline with the given callback.
*
* @param array $middleware
* @param \Closure $then
* @return mixed
*/
protected function sendThroughPipeline(array $middleware, Closure $then)
{
$shouldSkipMiddleware = $this->bound('middleware.disable') &&
$this->make('middleware.disable') === true;
if (count($middleware) > 0 && ! $shouldSkipMiddleware) {
return (new Pipeline($this))
->send($this->make('request'))
->through($middleware)
->then($then);
}
return $then();
}
/**
* Prepare the response for sending.
*
* @param mixed $response
* @return Response
*/
public function prepareResponse($response)
{
if (! $response instanceof SymfonyResponse) {
$response = new Response($response);
} elseif ($response instanceof BinaryFileResponse) {
$response = $response->prepare(Request::capture());
}
return $response;
}
/**
* Get the current HTTP request method.
*
* @return string
*/
protected function getMethod()
{
if (isset($_POST['_method'])) {
return strtoupper($_POST['_method']);
} else {
return $_SERVER['REQUEST_METHOD'];
}
}
/**
* Get the current HTTP path info.
*
* @return string
*/
protected function getPathInfo()
{
$query = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
return '/'.trim(str_replace('?'.$query, '', $_SERVER['REQUEST_URI']), '/');
}
}
src/Exceptions/Handler.php 0000666 00000010732 13436750035 0011557 0 ustar 00 shouldReport($e)) {
app('Psr\Log\LoggerInterface')->error($e);
}
}
/**
* Determine if the exception should be reported.
*
* @param \Exception $e
* @return bool
*/
public function shouldReport(Exception $e)
{
return ! $this->shouldntReport($e);
}
/**
* Determine if the exception is in the "do not report" list.
*
* @param \Exception $e
* @return bool
*/
protected function shouldntReport(Exception $e)
{
foreach ($this->dontReport as $type) {
if ($e instanceof $type) {
return true;
}
}
return false;
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($e instanceof HttpResponseException) {
return $e->getResponse();
} elseif ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
} elseif ($e instanceof AuthorizationException) {
$e = new HttpException(403, $e->getMessage());
} elseif ($e instanceof ValidationException && $e->getResponse()) {
return $e->getResponse();
}
$fe = FlattenException::create($e);
$handler = new SymfonyExceptionHandler(env('APP_DEBUG', false));
$decorated = $this->decorate($handler->getContent($fe), $handler->getStylesheet($fe));
$response = new Response($decorated, $fe->getStatusCode(), $fe->getHeaders());
$response->exception = $e;
return $response;
}
/**
* Get the html response content.
*
* @param string $content
* @param string $css
* @return string
*/
protected function decorate($content, $css)
{
return <<
$content
EOF;
}
/**
* Render an exception to the console.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param \Exception $e
* @return void
*/
public function renderForConsole($output, Exception $e)
{
(new ConsoleApplication)->renderException($e, $output);
}
}
src/Providers/EventServiceProvider.php 0000666 00000002072 13436750035 0014151 0 ustar 00 listen as $event => $listeners) {
foreach ($listeners as $listener) {
$events->listen($event, $listener);
}
}
foreach ($this->subscribe as $subscriber) {
$events->subscribe($subscriber);
}
}
/**
* {@inheritdoc}
*/
public function register()
{
//
}
/**
* Get the events and handlers.
*
* @return array
*/
public function listens()
{
return $this->listen;
}
}
src/Routing/ProvidesConvenienceMethods.php 0000666 00000011123 13436750035 0014777 0 ustar 00 getValidationFactory()->make($request->all(), $rules, $messages, $customAttributes);
if ($validator->fails()) {
$this->throwValidationException($request, $validator);
}
}
/**
* Throw the failed validation exception.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return void
*/
protected function throwValidationException(Request $request, $validator)
{
throw new ValidationException($validator, $this->buildFailedValidationResponse(
$request, $this->formatValidationErrors($validator)
));
}
/**
* {@inheritdoc}
*/
protected function buildFailedValidationResponse(Request $request, array $errors)
{
if (isset(static::$responseBuilder)) {
return call_user_func(static::$responseBuilder, $request, $errors);
}
return new JsonResponse($errors, 422);
}
/**
* {@inheritdoc}
*/
protected function formatValidationErrors(Validator $validator)
{
if (isset(static::$errorFormatter)) {
return call_user_func(static::$errorFormatter, $validator);
}
return $validator->errors()->getMessages();
}
/**
* Authorize a given action against a set of arguments.
*
* @param mixed $ability
* @param mixed|array $arguments
* @return \Illuminate\Auth\Access\Response
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function authorize($ability, $arguments = [])
{
list($ability, $arguments) = $this->parseAbilityAndArguments($ability, $arguments);
return app(Gate::class)->authorize($ability, $arguments);
}
/**
* Authorize a given action for a user.
*
* @param \Illuminate\Contracts\Auth\Authenticatable|mixed $user
* @param mixed $ability
* @param mixed|array $arguments
* @return \Illuminate\Auth\Access\Response
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function authorizeForUser($user, $ability, $arguments = [])
{
list($ability, $arguments) = $this->parseAbilityAndArguments($ability, $arguments);
return app(Gate::class)->forUser($user)->authorize($ability, $arguments);
}
/**
* Guesses the ability's name if it wasn't provided.
*
* @param mixed $ability
* @param mixed|array $arguments
* @return array
*/
protected function parseAbilityAndArguments($ability, $arguments)
{
if (is_string($ability)) {
return [$ability, $arguments];
}
return [debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2]['function'], $ability];
}
/**
* Dispatch a job to its appropriate handler.
*
* @param mixed $job
* @return mixed
*/
public function dispatch($job)
{
return app('Illuminate\Contracts\Bus\Dispatcher')->dispatch($job);
}
/**
* Get a validation factory instance.
*
* @return \Illuminate\Contracts\Validation\Factory
*/
protected function getValidationFactory()
{
return app('validator');
}
}
src/Routing/Pipeline.php 0000666 00000004336 13436750035 0011260 0 ustar 00 handleException($passable, $e);
} catch (Throwable $e) {
return $this->handleException($passable, new FatalThrowableError($e));
}
};
};
}
/**
* Get the initial slice to begin the stack call.
*
* @param \Closure $destination
* @return \Closure
*/
protected function getInitialSlice(BaseClosure $destination)
{
return function ($passable) use ($destination) {
try {
return call_user_func($destination, $passable);
} catch (Exception $e) {
return $this->handleException($passable, $e);
} catch (Throwable $e) {
return $this->handleException($passable, new FatalThrowableError($e));
}
};
}
/**
* Handle the given exception.
*
* @param \Exception $e
* @return mixed
*/
protected function handleException($passable, Exception $e)
{
if (! $this->container->bound(ExceptionHandler::class) || ! $passable instanceof Request) {
throw $e;
}
$handler = $this->container->make(ExceptionHandler::class);
$handler->report($e);
return $handler->render($passable, $e);
}
}
src/Routing/UrlGenerator.php 0000666 00000020360 13436750035 0012117 0 ustar 00 app = $app;
}
/**
* Get the full URL for the current request.
*
* @return string
*/
public function full()
{
return $this->app->make('request')->fullUrl();
}
/**
* Get the current URL for the request.
*
* @return string
*/
public function current()
{
return $this->to($this->app->make('request')->getPathInfo());
}
/**
* Generate a url for the application.
*
* @param string $path
* @param array $extra
* @param bool $secure
* @return string
*/
public function to($path, $extra = [], $secure = null)
{
// First we will check if the URL is already a valid URL. If it is we will not
// try to generate a new one but will simply return the URL as is, which is
// convenient since developers do not always have to check if it's valid.
if ($this->isValidUrl($path)) {
return $path;
}
$scheme = $this->getSchemeForUrl($secure);
$extra = $this->formatParametersForUrl($extra);
$tail = implode('/', array_map(
'rawurlencode', (array) $extra)
);
// Once we have the scheme we will compile the "tail" by collapsing the values
// into a single string delimited by slashes. This just makes it convenient
// for passing the array of parameters to this URL as a list of segments.
$root = $this->getRootUrl($scheme);
return $this->trimUrl($root, $path, $tail);
}
/**
* Generate a secure, absolute URL to the given path.
*
* @param string $path
* @param array $parameters
* @return string
*/
public function secure($path, $parameters = [])
{
return $this->to($path, $parameters, true);
}
/**
* Generate a URL to an application asset.
*
* @param string $path
* @param bool|null $secure
* @return string
*/
public function asset($path, $secure = null)
{
if ($this->isValidUrl($path)) {
return $path;
}
// Once we get the root URL, we will check to see if it contains an index.php
// file in the paths. If it does, we will remove it since it is not needed
// for asset paths, but only for routes to endpoints in the application.
$root = $this->getRootUrl($this->getScheme($secure));
return $this->removeIndex($root).'/'.trim($path, '/');
}
/**
* Generate a URL to an application asset from a root domain such as CDN etc.
*
* @param string $root
* @param string $path
* @param bool|null $secure
* @return string
*/
public function assetFrom($root, $path, $secure = null)
{
// Once we get the root URL, we will check to see if it contains an index.php
// file in the paths. If it does, we will remove it since it is not needed
// for asset paths, but only for routes to endpoints in the application.
$root = $this->getRootUrl($this->getScheme($secure), $root);
return $this->removeIndex($root).'/'.trim($path, '/');
}
/**
* Remove the index.php file from a path.
*
* @param string $root
* @return string
*/
protected function removeIndex($root)
{
$i = 'index.php';
return str_contains($root, $i) ? str_replace('/'.$i, '', $root) : $root;
}
/**
* Generate a URL to a secure asset.
*
* @param string $path
* @return string
*/
public function secureAsset($path)
{
return $this->asset($path, true);
}
/**
* Get the scheme for a raw URL.
*
* @param bool|null $secure
* @return string
*/
protected function getScheme($secure)
{
if (is_null($secure)) {
return $this->forceSchema ?: $this->app->make('request')->getScheme().'://';
}
return $secure ? 'https://' : 'http://';
}
/**
* Force the schema for URLs.
*
* @param string $schema
* @return void
*/
public function forceSchema($schema)
{
$this->forceSchema = $schema.'://';
}
/**
* Get the URL to a named route.
*
* @param string $name
* @param mixed $parameters
* @return string
*
* @throws \InvalidArgumentException
*/
public function route($name, $parameters = [])
{
if (! isset($this->app->namedRoutes[$name])) {
throw new \InvalidArgumentException("Route [{$name}] not defined.");
}
$uri = $this->app->namedRoutes[$name];
$parameters = $this->formatParametersForUrl($parameters);
$uri = preg_replace_callback('/\{(.*?)(:.*?)?(\{[0-9,]+\})?\}/', function ($m) use (&$parameters) {
return isset($parameters[$m[1]]) ? array_pull($parameters, $m[1]) : $m[0];
}, $uri);
$uri = $this->to($uri, []);
if (! empty($parameters)) {
$uri .= '?'.http_build_query($parameters);
}
return $uri;
}
/**
* Determine if the given path is a valid URL.
*
* @param string $path
* @return bool
*/
protected function isValidUrl($path)
{
if (starts_with($path, ['#', '//', 'mailto:', 'tel:', 'http://', 'https://'])) {
return true;
}
return filter_var($path, FILTER_VALIDATE_URL) !== false;
}
/**
* Get the scheme for a raw URL.
*
* @param bool|null $secure
* @return string
*/
protected function getSchemeForUrl($secure)
{
if (is_null($secure)) {
if (is_null($this->cachedScheme)) {
$this->cachedScheme = $this->app->make('request')->getScheme().'://';
}
return $this->cachedScheme;
}
return $secure ? 'https://' : 'http://';
}
/**
* Format the array of URL parameters.
*
* @param mixed|array $parameters
* @return array
*/
protected function formatParametersForUrl($parameters)
{
return $this->replaceRoutableParametersForUrl($parameters);
}
/**
* Replace UrlRoutable parameters with their route parameter.
*
* @param array $parameters
* @return array
*/
protected function replaceRoutableParametersForUrl($parameters = [])
{
$parameters = is_array($parameters) ? $parameters : [$parameters];
foreach ($parameters as $key => $parameter) {
if ($parameter instanceof UrlRoutable) {
$parameters[$key] = $parameter->getRouteKey();
}
}
return $parameters;
}
/**
* Get the base URL for the request.
*
* @param string $scheme
* @param string $root
* @return string
*/
protected function getRootUrl($scheme, $root = null)
{
if (is_null($root)) {
if (is_null($this->cachedRoot)) {
$this->cachedRoot = $this->app->make('request')->root();
}
$root = $this->cachedRoot;
}
$start = starts_with($root, 'http://') ? 'http://' : 'https://';
return preg_replace('~'.$start.'~', $scheme, $root, 1);
}
/**
* Format the given URL segments into a single URL.
*
* @param string $root
* @param string $path
* @param string $tail
* @return string
*/
protected function trimUrl($root, $path, $tail = '')
{
return trim($root.'/'.trim($path.'/'.$tail, '/'), '/');
}
}
src/Routing/Closure.php 0000666 00000000137 13436750035 0011122 0 ustar 00 middleware[$middleware] = $options;
}
/**
* Get the middleware for a given method.
*
* @param string $method
* @return array
*/
public function getMiddlewareForMethod($method)
{
$middleware = [];
foreach ($this->middleware as $name => $options) {
if (isset($options['only']) && ! in_array($method, (array) $options['only'])) {
continue;
}
if (isset($options['except']) && in_array($method, (array) $options['except'])) {
continue;
}
$middleware[] = $name;
}
return $middleware;
}
}
src/Auth/Authorizable.php 0000666 00000001745 13436750035 0011417 0 ustar 00 forUser($this)->check($ability, $arguments);
}
/**
* Determine if the entity does not have a given ability.
*
* @param string $ability
* @param array|mixed $arguments
* @return bool
*/
public function cant($ability, $arguments = [])
{
return ! $this->can($ability, $arguments);
}
/**
* Determine if the entity does not have a given ability.
*
* @param string $ability
* @param array|mixed $arguments
* @return bool
*/
public function cannot($ability, $arguments = [])
{
return $this->cant($ability, $arguments);
}
}
src/helpers.php 0000666 00000017465 13436750035 0007535 0 ustar 00 abort($code, $message, $headers);
}
}
if (! function_exists('app')) {
/**
* Get the available container instance.
*
* @param string $make
* @param array $parameters
* @return mixed|\Laravel\Lumen\Application
*/
function app($make = null, $parameters = [])
{
if (is_null($make)) {
return Container::getInstance();
}
return Container::getInstance()->make($make, $parameters);
}
}
if (! function_exists('base_path')) {
/**
* Get the path to the base of the install.
*
* @param string $path
* @return string
*/
function base_path($path = '')
{
return app()->basePath().($path ? '/'.$path : $path);
}
}
if (! function_exists('decrypt')) {
/**
* Decrypt the given value.
*
* @param string $value
* @return string
*/
function decrypt($value)
{
return app('encrypter')->decrypt($value);
}
}
if (! function_exists('dispatch')) {
/**
* Dispatch a job to its appropriate handler.
*
* @param mixed $job
* @return mixed
*/
function dispatch($job)
{
return app(Dispatcher::class)->dispatch($job);
}
}
if (! function_exists('config')) {
/**
* Get / set the specified configuration value.
*
* If an array is passed as the key, we will assume you want to set an array of values.
*
* @param array|string $key
* @param mixed $default
* @return mixed
*/
function config($key = null, $default = null)
{
if (is_null($key)) {
return app('config');
}
if (is_array($key)) {
return app('config')->set($key);
}
return app('config')->get($key, $default);
}
}
if (! function_exists('database_path')) {
/**
* Get the path to the database directory of the install.
*
* @param string $path
* @return string
*/
function database_path($path = '')
{
return app()->databasePath().($path ? '/'.$path : $path);
}
}
if (! function_exists('encrypt')) {
/**
* Encrypt the given value.
*
* @param string $value
* @return string
*/
function encrypt($value)
{
return app('encrypter')->encrypt($value);
}
}
if (! function_exists('env')) {
/**
* Gets the value of an environment variable. Supports boolean, empty and null.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
function env($key, $default = null)
{
$value = getenv($key);
if ($value === false) {
return value($default);
}
switch (strtolower($value)) {
case 'true':
case '(true)':
return true;
case 'false':
case '(false)':
return false;
case 'empty':
case '(empty)':
return '';
case 'null':
case '(null)':
return;
}
if (Str::startsWith($value, '"') && Str::endsWith($value, '"')) {
return substr($value, 1, -1);
}
return $value;
}
}
if (! function_exists('event')) {
/**
* Fire an event and call the listeners.
*
* @param string $event
* @param mixed $payload
* @param bool $halt
* @return array|null
*/
function event($event, $payload = [], $halt = false)
{
return app('events')->fire($event, $payload, $halt);
}
}
if (! function_exists('factory')) {
/**
* Create a model factory builder for a given class, name, and amount.
*
* @param dynamic class|class,name|class,amount|class,name,amount
* @return \Illuminate\Database\Eloquent\FactoryBuilder
*/
function factory()
{
app('db');
$factory = app('Illuminate\Database\Eloquent\Factory');
$arguments = func_get_args();
if (isset($arguments[1]) && is_string($arguments[1])) {
return $factory->of($arguments[0], $arguments[1])->times(isset($arguments[2]) ? $arguments[2] : 1);
} elseif (isset($arguments[1])) {
return $factory->of($arguments[0])->times($arguments[1]);
} else {
return $factory->of($arguments[0]);
}
}
}
if (! function_exists('info')) {
/**
* Write some information to the log.
*
* @param string $message
* @param array $context
* @return void
*/
function info($message, $context = [])
{
return app('Psr\Log\LoggerInterface')->info($message, $context);
}
}
if (! function_exists('redirect')) {
/**
* Get an instance of the redirector.
*
* @param string|null $to
* @param int $status
* @param array $headers
* @param bool $secure
* @return \Laravel\Lumen\Http\Redirector|\Illuminate\Http\RedirectResponse
*/
function redirect($to = null, $status = 302, $headers = [], $secure = null)
{
$redirector = new Laravel\Lumen\Http\Redirector(app());
if (is_null($to)) {
return $redirector;
}
return $redirector->to($to, $status, $headers, $secure);
}
}
if (! function_exists('response')) {
/**
* Return a new response from the application.
*
* @param string $content
* @param int $status
* @param array $headers
* @return \Symfony\Component\HttpFoundation\Response|\Laravel\Lumen\Http\ResponseFactory
*/
function response($content = '', $status = 200, array $headers = [])
{
$factory = new Laravel\Lumen\Http\ResponseFactory;
if (func_num_args() === 0) {
return $factory;
}
return $factory->make($content, $status, $headers);
}
}
if (! function_exists('route')) {
/**
* Generate a URL to a named route.
*
* @param string $name
* @param array $parameters
* @return string
*/
function route($name, $parameters = [])
{
return (new Laravel\Lumen\Routing\UrlGenerator(app()))
->route($name, $parameters);
}
}
if (! function_exists('storage_path')) {
/**
* Get the path to the storage folder.
*
* @param string $path
* @return string
*/
function storage_path($path = '')
{
return app()->storagePath($path);
}
}
if (! function_exists('url')) {
/**
* Generate a url for the application.
*
* @param string $path
* @param mixed $parameters
* @param bool $secure
* @return string
*/
function url($path = null, $parameters = [], $secure = null)
{
return (new Laravel\Lumen\Routing\UrlGenerator(app()))
->to($path, $parameters, $secure);
}
}
if (! function_exists('view')) {
/**
* Get the evaluated view contents for the given view.
*
* @param string $view
* @param array $data
* @param array $mergeData
* @return \Illuminate\View\View
*/
function view($view = null, $data = [], $mergeData = [])
{
$factory = app('view');
if (func_num_args() === 0) {
return $factory;
}
return $factory->make($view, $data, $mergeData);
}
}
readme.md 0000666 00000003366 13436750035 0006345 0 ustar 00 ## Lumen Framework (Kernel)
[![Build Status](https://travis-ci.org/laravel/lumen-framework.svg)](https://travis-ci.org/laravel/lumen-framework)
[![Total Downloads](https://poser.pugx.org/laravel/lumen-framework/d/total.svg)](https://packagist.org/packages/laravel/lumen-framework)
[![Latest Stable Version](https://poser.pugx.org/laravel/lumen-framework/v/stable.svg)](https://packagist.org/packages/laravel/lumen-framework)
[![Latest Unstable Version](https://poser.pugx.org/laravel/lumen-framework/v/unstable.svg)](https://packagist.org/packages/laravel/lumen-framework)
[![License](https://poser.pugx.org/laravel/lumen-framework/license.svg)](https://packagist.org/packages/laravel/lumen-framework)
> **Note:** This repository contains the core code of the Laravel Lumen framework. If you want to build an application using Laravel Lumen, visit the main [Lumen repository](https://github.com/laravel/lumen).
## Lumen PHP Framework
Laravel Lumen is a stunningly fast PHP micro-framework for building web applications with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Lumen attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as routing, database abstraction, queueing, and caching.
## Official Documentation
Documentation for the framework can be found on the [Lumen website](http://lumen.laravel.com/docs).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell at taylor@laravel.com. All security vulnerabilities will be promptly addressed.
### License
The Lumen framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT).
composer.json 0000666 00000004034 13436750035 0007301 0 ustar 00 {
"name": "laravel/lumen-framework",
"description": "The Laravel Lumen Framework.",
"keywords": ["framework", "laravel", "lumen"],
"license": "MIT",
"homepage": "http://laravel.com",
"support": {
"issues": "https://github.com/laravel/lumen-framework/issues",
"source": "https://github.com/laravel/lumen-framework"
},
"authors": [
{
"name": "Taylor Otwell",
"email": "taylorotwell@gmail.com"
}
],
"require": {
"php": ">=5.5.9",
"illuminate/auth": "5.2.*",
"illuminate/broadcasting": "5.2.*",
"illuminate/bus": "5.2.*",
"illuminate/cache": "5.2.*",
"illuminate/config": "5.2.*",
"illuminate/container": "5.2.*",
"illuminate/contracts": "5.2.*",
"illuminate/database": "5.2.*",
"illuminate/encryption": "5.2.*",
"illuminate/events": "5.2.*",
"illuminate/filesystem": "5.2.*",
"illuminate/hashing": "5.2.*",
"illuminate/http": "5.2.*",
"illuminate/pagination": "5.2.*",
"illuminate/pipeline": "5.2.*",
"illuminate/queue": "5.2.*",
"illuminate/support": "5.2.*",
"illuminate/translation": "5.2.*",
"illuminate/validation": "~5.2.7",
"illuminate/view": "5.2.*",
"monolog/monolog": "~1.11",
"mtdowling/cron-expression": "~1.0",
"nikic/fast-route": "0.7.*",
"paragonie/random_compat": "~1.1",
"symfony/http-kernel": "2.8.*|3.0.*",
"symfony/http-foundation": "2.8.*|3.0.*"
},
"require-dev": {
"phpunit/phpunit": "~4.0",
"mockery/mockery": "~0.9"
},
"suggest": {
"vlucas/phpdotenv": "Required to use .env files (~2.2)."
},
"autoload": {
"psr-4": {
"Laravel\\Lumen\\": "src/"
},
"files": [
"src/helpers.php"
]
},
"extra": {
"branch-alias": {
"dev-master": "5.2-dev"
}
},
"minimum-stability": "dev",
"prefer-stable": true
}
phpunit.php 0000666 00000001746 13436750035 0006766 0 ustar 00 get('/', function () {
return response('Hello World');
});
$response = $app->handle(Request::create('/', 'GET'));
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Hello World', $response->getContent());
}
public function testRequestWithoutSymfonyClass()
{
$app = new Application;
$app->get('/', function () {
return response('Hello World');
});
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/';
$response = $app->dispatch();
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Hello World', $response->getContent());
unset($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);
}
public function testRequestWithoutSymfonyClassTrailingSlash()
{
$app = new Application;
$app->get('/foo', function () {
return response('Hello World');
});
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/foo/';
$response = $app->dispatch();
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Hello World', $response->getContent());
unset($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);
}
public function testRequestWithParameters()
{
$app = new Application;
$app->get('/foo/{bar}/{baz}', function ($bar, $baz) {
return response($bar.$baz);
});
$response = $app->handle(Request::create('/foo/1/2', 'GET'));
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('12', $response->getContent());
}
public function testCallbackRouteWithDefaultParameter()
{
$app = new Application;
$app->get('/foo-bar/{baz}', function ($baz = 'default-value') {
return response($baz);
});
$response = $app->handle(Request::create('/foo-bar/something', 'GET'));
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('something', $response->getContent());
}
public function testGlobalMiddleware()
{
$app = new Application;
$app->middleware(['LumenTestMiddleware']);
$app->get('/', function () {
return response('Hello World');
});
$response = $app->handle(Request::create('/', 'GET'));
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Middleware', $response->getContent());
}
public function testRouteMiddleware()
{
$app = new Application;
$app->routeMiddleware(['foo' => 'LumenTestMiddleware']);
$app->get('/', function () {
return response('Hello World');
});
$app->get('/foo', ['middleware' => 'foo', function () {
return response('Hello World');
}]);
$response = $app->handle(Request::create('/', 'GET'));
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Hello World', $response->getContent());
$response = $app->handle(Request::create('/foo', 'GET'));
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Middleware', $response->getContent());
}
public function testGlobalMiddlewareParameters()
{
$app = new Application;
$app->middleware(['LumenTestParameterizedMiddleware:foo,bar']);
$app->get('/', function () {
return response('Hello World');
});
$response = $app->handle(Request::create('/', 'GET'));
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Middleware - foo - bar', $response->getContent());
}
public function testRouteMiddlewareParameters()
{
$app = new Application;
$app->routeMiddleware(['foo' => 'LumenTestParameterizedMiddleware']);
$app->get('/', ['middleware' => 'foo:bar,boom', function () {
return response('Hello World');
}]);
$response = $app->handle(Request::create('/', 'GET'));
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Middleware - bar - boom', $response->getContent());
}
public function testWithMiddlewareDisabled()
{
$app = new Application;
$app->middleware(['LumenTestMiddleware']);
$app->instance('middleware.disable', true);
$app->get('/', function () {
return response('Hello World');
});
$response = $app->handle(Request::create('/', 'GET'));
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Hello World', $response->getContent());
}
public function testNotFoundResponse()
{
$app = new Application;
$app->instance('Illuminate\Contracts\Debug\ExceptionHandler', $mock = m::mock('Laravel\Lumen\Exceptions\Handler[report]'));
$mock->shouldIgnoreMissing();
$app->get('/', function () {
return response('Hello World');
});
$response = $app->handle(Request::create('/foo', 'GET'));
$this->assertEquals(404, $response->getStatusCode());
}
public function testMethodNotAllowedResponse()
{
$app = new Application;
$app->instance('Illuminate\Contracts\Debug\ExceptionHandler', $mock = m::mock('Laravel\Lumen\Exceptions\Handler[report]'));
$mock->shouldIgnoreMissing();
$app->post('/', function () {
return response('Hello World');
});
$response = $app->handle(Request::create('/', 'GET'));
$this->assertEquals(405, $response->getStatusCode());
}
public function testGeneratingUrls()
{
$app = new Application;
$app->instance('request', Request::create('http://lumen.laravel.com', 'GET'));
unset($app->availableBindings['request']);
$app->get('/foo-bar', ['as' => 'foo', function () {
//
}]);
$app->get('/foo-bar/{baz}/{boom}', ['as' => 'bar', function () {
//
}]);
$this->assertEquals('http://lumen.laravel.com/something', url('something'));
$this->assertEquals('http://lumen.laravel.com/foo-bar', route('foo'));
$this->assertEquals('http://lumen.laravel.com/foo-bar/1/2', route('bar', ['baz' => 1, 'boom' => 2]));
$this->assertEquals('http://lumen.laravel.com/foo-bar?baz=1&boom=2', route('foo', ['baz' => 1, 'boom' => 2]));
}
public function testGeneratingUrlsForRegexParameters()
{
$app = new Application;
$app->instance('request', Request::create('http://lumen.laravel.com', 'GET'));
unset($app->availableBindings['request']);
$app->get('/foo-bar', ['as' => 'foo', function () {
//
}]);
$app->get('/foo-bar/{baz:[0-9]+}/{boom}', ['as' => 'bar', function () {
//
}]);
$app->get('/foo-bar/{baz:[0-9]+}/{boom:[0-9]+}', ['as' => 'baz', function () {
//
}]);
$app->get('/foo-bar/{baz:[0-9]{2,5}}', ['as' => 'boom', function () {
//
}]);
$this->assertEquals('http://lumen.laravel.com/something', url('something'));
$this->assertEquals('http://lumen.laravel.com/foo-bar', route('foo'));
$this->assertEquals('http://lumen.laravel.com/foo-bar/1/2', route('bar', ['baz' => 1, 'boom' => 2]));
$this->assertEquals('http://lumen.laravel.com/foo-bar/1/2', route('baz', ['baz' => 1, 'boom' => 2]));
$this->assertEquals('http://lumen.laravel.com/foo-bar/{baz:[0-9]+}/{boom:[0-9]+}?ba=1&bo=2', route('baz', ['ba' => 1, 'bo' => 2]));
$this->assertEquals('http://lumen.laravel.com/foo-bar/5', route('boom', ['baz' => 5]));
}
public function testRegisterServiceProvider()
{
$app = new Application;
$provider = new LumenTestServiceProvider($app);
$app->register($provider);
}
public function testUsingCustomDispatcher()
{
$routes = new FastRoute\RouteCollector(new FastRoute\RouteParser\Std, new FastRoute\DataGenerator\GroupCountBased);
$routes->addRoute('GET', '/', [function () {
return response('Hello World');
}]);
$app = new Application;
$app->setDispatcher(new FastRoute\Dispatcher\GroupCountBased($routes->getData()));
$response = $app->handle(Request::create('/', 'GET'));
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Hello World', $response->getContent());
}
public function testMiddlewareReceiveResponsesEvenWhenStringReturned()
{
unset($_SERVER['__middleware.response']);
$app = new Application;
$app->routeMiddleware(['foo' => 'LumenTestPlainMiddleware']);
$app->get('/', ['middleware' => 'foo', function () {
return 'Hello World';
}]);
$response = $app->handle(Request::create('/', 'GET'));
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Hello World', $response->getContent());
$this->assertEquals(true, $_SERVER['__middleware.response']);
}
public function testBasicControllerDispatching()
{
$app = new Application;
$app->get('/show/{id}', 'LumenTestController@show');
$response = $app->handle(Request::create('/show/25', 'GET'));
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('25', $response->getContent());
}
public function testBasicControllerDispatchingWithGroup()
{
$app = new Application;
$app->routeMiddleware(['test' => LumenTestMiddleware::class]);
$app->group(['middleware' => 'test'], function ($app) {
$app->get('/show/{id}', 'LumenTestController@show');
});
$response = $app->handle(Request::create('/show/25', 'GET'));
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Middleware', $response->getContent());
}
public function testBasicControllerDispatchingWithMiddlewareIntercept()
{
$app = new Application;
$app->routeMiddleware(['test' => LumenTestMiddleware::class]);
$app->get('/show/{id}', 'LumenTestControllerWithMiddleware@show');
$response = $app->handle(Request::create('/show/25', 'GET'));
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Middleware', $response->getContent());
}
public function testEnvironmentDetection()
{
$app = new Application;
$this->assertEquals('production', $app->environment());
$this->assertTrue($app->environment('production'));
$this->assertTrue($app->environment(['production']));
}
public function testValidationHelpers()
{
$app = new Application;
$app->get('/', function (Illuminate\Http\Request $request) {
$this->validate($request, ['name' => 'required']);
});
$response = $app->handle(Request::create('/', 'GET'));
$this->assertEquals(422, $response->getStatusCode());
}
}
class LumenTestService
{
}
class LumenTestServiceProvider extends Illuminate\Support\ServiceProvider
{
public function register()
{
}
}
class LumenTestController
{
public function __construct(LumenTestService $service)
{
//
}
public function show($id)
{
return $id;
}
}
class LumenTestControllerWithMiddleware extends Laravel\Lumen\Routing\Controller
{
public function __construct(LumenTestService $service)
{
$this->middleware('test');
}
public function show($id)
{
return $id;
}
}
class LumenTestMiddleware
{
public function handle($request, $next)
{
return response('Middleware');
}
}
class LumenTestPlainMiddleware
{
public function handle($request, $next)
{
$response = $next($request);
$_SERVER['__middleware.response'] = $response instanceof Illuminate\Http\Response;
return $response;
}
}
class LumenTestParameterizedMiddleware
{
public function handle($request, $next, $parameter1, $parameter2)
{
return response("Middleware - $parameter1 - $parameter2");
}
}
LICENSE.txt 0000666 00000002065 13436750035 0006404 0 ustar 00 The MIT License (MIT)
Copyright (c)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
.gitignore 0000666 00000000046 13436750035 0006546 0 ustar 00 /lumen.log
/vendor
composer.lock
.env