language
stringclasses
1 value
owner
stringlengths
2
15
repo
stringlengths
2
21
sha
stringlengths
45
45
message
stringlengths
7
36.3k
path
stringlengths
1
199
patch
stringlengths
15
102k
is_multipart
bool
2 classes
Other
laravel
framework
75e8cf11296c8754fc16ed118ef7aac7dbbdfcf9.json
Handle array keys with dots, fixes #14384 (#14388)
tests/Validation/ValidationValidatorTest.php
@@ -2425,6 +2425,23 @@ public function testValidateImplicitEachWithAsterisksForRequiredNonExistingKey() $this->assertFalse($v->passes()); } + public function testParsingArrayKeysWithDot() + { + $trans = $this->getRealTranslator(); + + $v = new Validator($trans, ['foo' => ['bar' => ''], 'foo.bar' => 'valid'], ['foo.bar' => 'required']); + $this->assertTrue($v->fails()); + + $v = new Validator($trans, ['foo' => ['bar' => 'valid'], 'foo.bar' => ''], ['foo\.bar' => 'required']); + $this->assertTrue($v->fails()); + + $v = new Validator($trans, ['foo' => ['bar.baz' => '']], ['foo.bar\.baz' => 'required']); + $this->assertTrue($v->fails()); + + $v = new Validator($trans, ['foo' => [['bar.baz' => ''], ['bar.baz' => '']]], ['foo.*.bar\.baz' => 'required']); + $this->assertTrue($v->fails()); + } + public function testImplicitEachWithAsterisksWithArrayValues() { $trans = $this->getRealTranslator();
true
Other
laravel
framework
9dabd7ffab9c45d7558d2fe88dbf740fcc85d43b.json
Fix PHPDoc blocks for responses (#14369)
src/Illuminate/Foundation/Http/FormRequest.php
@@ -156,7 +156,7 @@ public function response(array $errors) /** * Get the response for a forbidden operation. * - * @return \Illuminate\Http\Response + * @return \Symfony\Component\HttpFoundation\Response */ public function forbiddenResponse() {
true
Other
laravel
framework
9dabd7ffab9c45d7558d2fe88dbf740fcc85d43b.json
Fix PHPDoc blocks for responses (#14369)
src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php
@@ -125,8 +125,8 @@ protected function tokensMatch($request) * Add the CSRF token to the response cookies. * * @param \Illuminate\Http\Request $request - * @param \Illuminate\Http\Response $response - * @return \Illuminate\Http\Response + * @param \Symfony\Component\HttpFoundation\Response $response + * @return \Symfony\Component\HttpFoundation\Response */ protected function addCookieToResponse($request, $response) {
true
Other
laravel
framework
9dabd7ffab9c45d7558d2fe88dbf740fcc85d43b.json
Fix PHPDoc blocks for responses (#14369)
src/Illuminate/Foundation/Validation/ValidatesRequests.php
@@ -96,7 +96,7 @@ protected function throwValidationException(Request $request, $validator) * * @param \Illuminate\Http\Request $request * @param array $errors - * @return \Illuminate\Http\Response + * @return \Symfony\Component\HttpFoundation\Response */ protected function buildFailedValidationResponse(Request $request, array $errors) {
true
Other
laravel
framework
9dabd7ffab9c45d7558d2fe88dbf740fcc85d43b.json
Fix PHPDoc blocks for responses (#14369)
src/Illuminate/Http/Middleware/FrameGuard.php
@@ -11,7 +11,7 @@ class FrameGuard * * @param \Illuminate\Http\Request $request * @param \Closure $next - * @return \Illuminate\Http\Response + * @return \Symfony\Component\HttpFoundation\Response */ public function handle($request, Closure $next) {
true
Other
laravel
framework
9dabd7ffab9c45d7558d2fe88dbf740fcc85d43b.json
Fix PHPDoc blocks for responses (#14369)
src/Illuminate/Http/ResponseTrait.php
@@ -30,13 +30,13 @@ public function content() * Set a header on the Response. * * @param string $key - * @param string $value + * @param array|string $values * @param bool $replace * @return $this */ - public function header($key, $value, $replace = true) + public function header($key, $values, $replace = true) { - $this->headers->set($key, $value, $replace); + $this->headers->set($key, $values, $replace); return $this; } @@ -87,7 +87,7 @@ public function withCookie($cookie) /** * Throws the response in a HttpResponseException instance. * - * @throws Illuminate\Http\Exception\HttpResponseException; + * @throws \Illuminate\Http\Exception\HttpResponseException; */ public function throwResponse() {
true
Other
laravel
framework
9dabd7ffab9c45d7558d2fe88dbf740fcc85d43b.json
Fix PHPDoc blocks for responses (#14369)
src/Illuminate/Routing/Middleware/ThrottleRequests.php
@@ -69,7 +69,7 @@ protected function resolveRequestSignature($request) * * @param string $key * @param int $maxAttempts - * @return \Illuminate\Http\Response + * @return \Symfony\Component\HttpFoundation\Response */ protected function buildResponse($key, $maxAttempts) { @@ -91,7 +91,7 @@ protected function buildResponse($key, $maxAttempts) * @param int $maxAttempts * @param int $remainingAttempts * @param int|null $retryAfter - * @return \Illuminate\Http\Response + * @return \Symfony\Component\HttpFoundation\Response */ protected function addHeaders(Response $response, $maxAttempts, $remainingAttempts, $retryAfter = null) {
true
Other
laravel
framework
9dabd7ffab9c45d7558d2fe88dbf740fcc85d43b.json
Fix PHPDoc blocks for responses (#14369)
src/Illuminate/Validation/ValidationException.php
@@ -16,15 +16,15 @@ class ValidationException extends Exception /** * The recommended response to send to the client. * - * @var \Illuminate\Http\Response|null + * @var \Symfony\Component\HttpFoundation\Response|null */ public $response; /** * Create a new exception instance. * * @param \Illuminate\Contracts\Validation\Validator $validator - * @param \Illuminate\Http\Response $response + * @param \Symfony\Component\HttpFoundation\Response $response * @return void */ public function __construct($validator, $response = null)
true
Other
laravel
framework
d059f904aaacf9cf7486c7f8d8443aa07f084709.json
Remove un-needed method overwrites (#14372)
src/Illuminate/Database/Query/Grammars/PostgresGrammar.php
@@ -49,42 +49,6 @@ protected function whereDate(Builder $query, $where) return $this->wrap($where['column']).'::date '.$where['operator'].' '.$value; } - /** - * Compile a "where day" clause. - * - * @param \Illuminate\Database\Query\Builder $query - * @param array $where - * @return string - */ - protected function whereDay(Builder $query, $where) - { - return $this->dateBasedWhere('day', $query, $where); - } - - /** - * Compile a "where month" clause. - * - * @param \Illuminate\Database\Query\Builder $query - * @param array $where - * @return string - */ - protected function whereMonth(Builder $query, $where) - { - return $this->dateBasedWhere('month', $query, $where); - } - - /** - * Compile a "where year" clause. - * - * @param \Illuminate\Database\Query\Builder $query - * @param array $where - * @return string - */ - protected function whereYear(Builder $query, $where) - { - return $this->dateBasedWhere('year', $query, $where); - } - /** * Compile a date based where clause. *
false
Other
laravel
framework
0ca99db6739195971a76df6efd7dc5621698ed4e.json
Add support for testing eloquent model events
src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php
@@ -4,6 +4,7 @@ use Mockery; use Exception; +use Illuminate\Database\Eloquent\Model; use Illuminate\Contracts\Notifications\Dispatcher as NotificationDispatcher; trait MocksApplicationServices @@ -15,6 +16,13 @@ trait MocksApplicationServices */ protected $firedEvents = []; + /** + * All of the fired model events. + * + * @var array + */ + protected $firedModelEvents = []; + /** * All of the dispatched jobs. * @@ -101,6 +109,88 @@ protected function withoutEvents() return $this; } + /** + * Mock the model event dispatcher so all events are silenced and collected. + * + * @return $this + */ + protected function withoutModelEvents() + { + $mock = Mockery::mock('Illuminate\Contracts\Events\Dispatcher'); + + $mock->shouldReceive('fire')->andReturnUsing(function ($called) { + $this->firedModelEvents[] = $called; + }); + + $mock->shouldReceive('until')->andReturnUsing(function ($called) { + $this->firedModelEvents[] = $called; + + return true; + }); + + $mock->shouldReceive('listen')->andReturnUsing(function ($event, $listener, $priority) { + // + }); + + Model::setEventDispatcher($mock); + + 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 + * + * @throws \Exception + */ + public function expectsModelEvents($events) + { + $events = is_array($events) ? $events : func_get_args(); + + $this->withoutModelEvents(); + + $this->beforeApplicationDestroyed(function () use ($events) { + $fired = $this->getFiredModelEvents($events); + + if ($eventsNotFired = array_diff($events, $fired)) { + throw new Exception( + 'These expected events were not fired: ['.implode(', ', $eventsNotFired).']' + ); + } + }); + + return $this; + } + + /** + * Specify a list of events that should not 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 doesntExpectModelEvents($events) + { + $events = is_array($events) ? $events : func_get_args(); + + $this->withoutModelEvents(); + + $this->beforeApplicationDestroyed(function () use ($events) { + if ($fired = $this->getFiredModelEvents($events)) { + throw new Exception( + 'These unexpected events were fired: ['.implode(', ', $fired).']' + ); + } + }); + + return $this; + } + /** * Specify a list of observers that will not run for the given operation. * @@ -131,6 +221,17 @@ protected function getFiredEvents(array $events) return $this->getDispatched($events, $this->firedEvents); } + /** + * Filter the given events against the fired events. + * + * @param array $events + * @return array + */ + protected function getFiredModelEvents(array $events) + { + return $this->getDispatched($events, $this->firedModelEvents); + } + /** * Specify a list of jobs that should be dispatched for the given operation. *
true
Other
laravel
framework
0ca99db6739195971a76df6efd7dc5621698ed4e.json
Add support for testing eloquent model events
src/Illuminate/Foundation/Testing/TestCase.php
@@ -4,6 +4,7 @@ use Mockery; use PHPUnit_Framework_TestCase; +use Illuminate\Database\Eloquent\Model; abstract class TestCase extends PHPUnit_Framework_TestCase { @@ -83,6 +84,7 @@ protected function refreshApplication() putenv('APP_ENV=testing'); $this->app = $this->createApplication(); + Model::setEventDispatcher($this->app['events']); } /**
true
Other
laravel
framework
0ca99db6739195971a76df6efd7dc5621698ed4e.json
Add support for testing eloquent model events
tests/Foundation/FoundationExpectsModelEventsTest.php
@@ -0,0 +1,139 @@ +<?php + +use Illuminate\Events\Dispatcher; +use Mockery\MockInterface as Mock; +use Illuminate\Foundation\Application; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Foundation\Testing\TestCase; +use Illuminate\Database\Capsule\Manager as DB; +use Illuminate\Database\Eloquent\Model as Eloquent; + +class FoundationExpectsModelEventsTest extends TestCase +{ + public function createApplication() + { + $app = new Application; + + $db = new DB; + + $db->addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', + ]); + + $db->bootEloquent(); + $db->setAsGlobal(); + + $this->createSchema(); + + return $app; + } + + /** @test */ + public function a_mock_replaces_the_event_dispatcher_when_calling_expects_model_events() + { + $this->assertInstanceOf(Dispatcher::class, Model::getEventDispatcher()); + + $this->assertNotInstanceOf(Mock::class, Model::getEventDispatcher()); + + $this->expectsModelEvents([]); + + $this->assertNotInstanceOf(Dispatcher::class, Model::getEventDispatcher()); + $this->assertInstanceOf(Mock::class, Model::getEventDispatcher()); + } + + /** @test */ + public function a_mock_does_not_carry_over_between_tests() + { + $this->assertInstanceOf(Dispatcher::class, Model::getEventDispatcher()); + + $this->assertNotInstanceOf(Mock::class, Model::getEventDispatcher()); + } + + /** @test */ + public function fired_events_can_be_checked_for() + { + $this->expectsModelEvents([ + 'eloquent.booting: EloquentTestModel', + 'eloquent.booted: EloquentTestModel', + + 'eloquent.creating: EloquentTestModel', + 'eloquent.created: EloquentTestModel', + + 'eloquent.saving: EloquentTestModel', + 'eloquent.saved: EloquentTestModel', + + 'eloquent.updating: EloquentTestModel', + 'eloquent.updated: EloquentTestModel', + + 'eloquent.deleting: EloquentTestModel', + 'eloquent.deleted: EloquentTestModel', + ]); + + $model = EloquentTestModel::create(['field' => 1]); + $model->field = 2; + $model->save(); + $model->delete(); + } + + /** @test */ + public function observers_do_not_fire_when_mocking_events() + { + $this->expectsModelEvents([ + 'eloquent.saving: EloquentTestModel', + 'eloquent.saved: EloquentTestModel', + ]); + + EloquentTestModel::observe(new EloquentTestModelFailingObserver); + + EloquentTestModel::create(['field' => 1]); + } + + protected function createSchema() + { + $this->schema('default')->create('test', function ($table) { + $table->increments('id'); + $table->string('field'); + $table->timestamps(); + }); + } + + /** + * Get a database connection instance. + * + * @return Connection + */ + protected function connection($connection = 'default') + { + return Eloquent::getConnectionResolver()->connection($connection); + } + + /** + * Get a schema builder instance. + * + * @return Schema\Builder + */ + protected function schema($connection = 'default') + { + return $this->connection($connection)->getSchemaBuilder(); + } +} + +class EloquentTestModel extends Eloquent +{ + protected $guarded = []; + protected $table = 'test'; +} + +class EloquentTestModelFailingObserver +{ + public function saving() + { + PHPUnit_Framework_Assert::fail('The [saving] method should not be called on '.static::class); + } + + public function saved() + { + PHPUnit_Framework_Assert::fail('The [saved] method should not be called on '.static::class); + } +}
true
Other
laravel
framework
85249beed1e4512d71f7ae52474b9a59a80381d2.json
fix console bug, fix redirect response
src/Illuminate/Cache/Console/ClearCommand.php
@@ -50,7 +50,7 @@ public function __construct(CacheManager $cache) */ public function handle() { - $tags = (array) explode(',', $this->option('tags')); + $tags = array_filter(explode(',', $this->option('tags'))); $cache = $this->cache->store($store = $this->argument('store'));
true
Other
laravel
framework
85249beed1e4512d71f7ae52474b9a59a80381d2.json
fix console bug, fix redirect response
src/Illuminate/Http/RedirectResponse.php
@@ -72,15 +72,30 @@ public function withInput(array $input = null) { $input = $input ?: $this->request->input(); - $this->session->flashInput($data = array_filter($input, $callback = function (&$value) use (&$callback) { + $this->session->flashInput($this->removeFilesFromInput($input)); + + return $this; + } + + /** + * Remove all uploaded files form the given input array. + * + * @param array $input + * @return array + */ + protected function removeFilesFromInput(array $input) + { + foreach ($input as $key => $value) { if (is_array($value)) { - $value = array_filter($value, $callback); + $input[$key] = $this->removeFilesFromInput($value); } - return ! $value instanceof SymfonyUploadedFile; - })); + if ($value instanceof SymfonyUploadedFile) { + unset($input[$key]); + } + } - return $this; + return $input; } /**
true
Other
laravel
framework
5ae802f5f2cc37506a68b29eae6b99f16e495d2c.json
Improve Filesystem sharedGet performance (#14319)
src/Illuminate/Filesystem/Filesystem.php
@@ -51,14 +51,16 @@ public function sharedGet($path) { $contents = ''; - $handle = fopen($path, 'r'); + $handle = fopen($path, 'rb'); if ($handle) { try { if (flock($handle, LOCK_SH)) { - while (! feof($handle)) { - $contents .= fread($handle, 1048576); - } + clearstatcache(true, $path); + + $contents = fread($handle, $this->size($path) ?: 1); + + flock($handle, LOCK_UN); } } finally { fclose($handle);
false
Other
laravel
framework
b68603797a57e89f6bd486129e9043503c960e6c.json
Use spread operators (#14348)
src/Illuminate/Auth/Access/Gate.php
@@ -118,7 +118,7 @@ protected function buildAbilityCallback($callback) return function () use ($callback) { list($class, $method) = explode('@', $callback); - return call_user_func_array([$this->resolvePolicy($class), $method], func_get_args()); + return $this->resolvePolicy($class)->{$method}(...func_get_args()); }; } @@ -260,13 +260,9 @@ protected function raw($ability, $arguments = []) */ protected function callAuthCallback($user, $ability, array $arguments) { - $callback = $this->resolveAuthCallback( - $user, $ability, $arguments - ); + $callback = $this->resolveAuthCallback($user, $ability, $arguments); - return call_user_func_array( - $callback, array_merge([$user], $arguments) - ); + return $callback($user, ...$arguments); } /** @@ -282,7 +278,7 @@ protected function callBeforeCallbacks($user, $ability, array $arguments) $arguments = array_merge([$user, $ability], [$arguments]); foreach ($this->beforeCallbacks as $before) { - if (! is_null($result = call_user_func_array($before, $arguments))) { + if (! is_null($result = $before(...$arguments))) { return $result; } } @@ -302,7 +298,7 @@ protected function callAfterCallbacks($user, $ability, array $arguments, $result $arguments = array_merge([$user, $ability, $result], [$arguments]); foreach ($this->afterCallbacks as $after) { - call_user_func_array($after, $arguments); + $after(...$arguments); } } @@ -359,20 +355,11 @@ protected function resolvePolicyCallback($user, $ability, array $arguments) return function () use ($user, $ability, $arguments) { $instance = $this->getPolicyFor($arguments[0]); + // If we receive a non-null result from the before method, we will return it + // as the final result. This will allow developers to override the checks + // in the policy to return a result for all rules defined in the class. if (method_exists($instance, 'before')) { - // We will prepend the user and ability onto the arguments so that the before - // callback can determine which ability is being called. Then we will call - // into the policy before methods with the arguments and get the result. - $beforeArguments = array_merge([$user, $ability], $arguments); - - $result = call_user_func_array( - [$instance, 'before'], $beforeArguments - ); - - // If we received a non-null result from the before method, we will return it - // as the result of a check. This allows developers to override the checks - // in the policy and return a result for all rules defined in the class. - if (! is_null($result)) { + if (! is_null($result = $instance->before($user, $ability, ...$arguments))) { return $result; } } @@ -392,9 +379,7 @@ protected function resolvePolicyCallback($user, $ability, array $arguments) return false; } - return call_user_func_array( - [$instance, $ability], array_merge([$user], $arguments) - ); + return $instance->{$ability}($user, ...$arguments); }; }
true
Other
laravel
framework
b68603797a57e89f6bd486129e9043503c960e6c.json
Use spread operators (#14348)
src/Illuminate/Auth/AuthManager.php
@@ -291,6 +291,6 @@ public function provider($name, Closure $callback) */ public function __call($method, $parameters) { - return call_user_func_array([$this->guard(), $method], $parameters); + return $this->guard()->{$method}(...$parameters); } }
true
Other
laravel
framework
b68603797a57e89f6bd486129e9043503c960e6c.json
Use spread operators (#14348)
src/Illuminate/Auth/Passwords/PasswordBroker.php
@@ -96,7 +96,7 @@ public function reset(array $credentials, Closure $callback) // Once we have called this callback, we will remove this token row from the // table and return the response from this callback so the user gets sent // to the destination given by the developers from the callback return. - call_user_func($callback, $user, $pass); + $callback($user, $pass); $this->tokens->delete($credentials['token']);
true
Other
laravel
framework
b68603797a57e89f6bd486129e9043503c960e6c.json
Use spread operators (#14348)
src/Illuminate/Auth/Passwords/PasswordBrokerManager.php
@@ -138,6 +138,6 @@ public function setDefaultDriver($name) */ public function __call($method, $parameters) { - return call_user_func_array([$this->broker(), $method], $parameters); + return $this->broker()->{$method}(...$parameters); } }
true
Other
laravel
framework
a4d02365f63b3e99c1fb652218c4864de3d5ae41.json
remove some words
src/Illuminate/Foundation/Console/stubs/policy.stub
@@ -11,7 +11,7 @@ class DummyClass use HandlesAuthorization; /** - * Determine whether the given user can view dummyPluralModelName. + * Determine whether the user can view dummyPluralModelName. * * @param DummyRootNamespaceUser $user * @return mixed @@ -22,7 +22,7 @@ class DummyClass } /** - * Determine whether the given user can view the specified dummyModelName. + * Determine whether the user can view the dummyModelName. * * @param DummyRootNamespaceUser $user * @param DummyRootNamespaceDummyModel $dummyModelName @@ -34,7 +34,7 @@ class DummyClass } /** - * Determine whether the given user can create dummyPluralModelName. + * Determine whether the user can create dummyPluralModelName. * * @param DummyRootNamespaceUser $user * @return mixed @@ -45,7 +45,7 @@ class DummyClass } /** - * Determine whether the given user can update dummyPluralModelName. + * Determine whether the user can update dummyPluralModelName. * * @param DummyRootNamespaceUser $user * @return mixed @@ -56,7 +56,7 @@ class DummyClass } /** - * Determine whether the given user can update the specified dummyModelName. + * Determine whether the user can update the dummyModelName. * * @param DummyRootNamespaceUser $user * @param DummyRootNamespaceDummyModel $dummyModelName @@ -68,7 +68,7 @@ class DummyClass } /** - * Determine whether the given user can delete the specified dummyModelName. + * Determine whether the user can delete the dummyModelName. * * @param DummyRootNamespaceUser $user * @param DummyRootNamespaceDummyModel $dummyModelName
false
Other
laravel
framework
8fe1ff6804330d92bae2c376eb8e18e9205c4ca3.json
Fix auth stub.
src/Illuminate/Auth/Console/MakeAuthCommand.php
@@ -60,7 +60,7 @@ public function fire() $this->info('Updated Routes File.'); file_put_contents( - app_path('Http/routes.php'), + base_path('routes/web.php'), file_get_contents(__DIR__.'/stubs/make/routes.stub'), FILE_APPEND );
false
Other
laravel
framework
a4c39aa5f36f02604c64fdcced139b3f73612528.json
Add mode function
src/Illuminate/Support/Collection.php
@@ -111,6 +111,36 @@ public function median($key = null) return (new static([$start, $end]))->average(); } + /** + * Get the mode of a given key. + * + * @param null $key + * @return static|null + */ + public function mode($key = null) + { + $count = $this->count(); + if ($count == 0) { + return; + } + + $collection = isset($key) ? $this->map(function ($value) use ($key) { + return $value->{$key}; + }) : $this; + + $set = new static; + $collection->each(function ($value) use (&$set) { + $set[$value] = isset($set[$value]) ? $set[$value] + 1 : 1; + }); + + $sorted = $set->sort(); + $highestValue = $sorted->last(); + + return $sorted->filter(function ($value) use ($highestValue) { + return $value == $highestValue; + })->sort()->keys(); + } + /** * Collapse the collection of items into a single array. *
true
Other
laravel
framework
a4c39aa5f36f02604c64fdcced139b3f73612528.json
Add mode function
tests/Support/SupportCollectionTest.php
@@ -1315,6 +1315,35 @@ public function testMedianOnEmptyCollectionReturnsNull() $collection = new Collection(); $this->assertNull($collection->median()); } + + public function testModeOnNullCollection() + { + $collection = new Collection(); + $this->assertNull($collection->mode()); + } + + public function testMode() + { + $collection = new Collection([1, 2, 3, 4, 4, 5]); + $this->assertEquals(new Collection([4]), $collection->mode()); + } + + public function testModeValueByKey() + { + $collection = new Collection([ + (object) ['foo' => 1], + (object) ['foo' => 1], + (object) ['foo' => 2], + (object) ['foo' => 4], + ]); + $this->assertEquals(new Collection([1]), $collection->mode('foo')); + } + + public function testWithMultipleModeValues() + { + $collection = new Collection([1, 2, 2, 1]); + $this->assertEquals(new Collection([1, 2]), $collection->mode()); + } } class TestAccessorEloquentTestStub
true
Other
laravel
framework
e011ca3761653d8de194441d4f5e6f6a68f9fc08.json
Add median function
src/Illuminate/Support/Collection.php
@@ -80,6 +80,37 @@ public function average($key = null) return $this->avg($key); } + /** + * Get the median of a given key. + * + * @param null $key + * @return mixed|null + */ + public function median($key = null) + { + $count = $this->count(); + if ($count == 0) { + return; + } + + $collection = isset($key) ? $this->map(function ($value) use ($key) { + return $value->{$key}; + }) : $this; + + $values = $collection->values()->sort(); + $middlePosition = (int) floor($count / 2); + $hasAnOddQuantity = $count % 2; + + if ($hasAnOddQuantity) { + return $values->get($middlePosition); + } + + $start = $values->get($middlePosition - 1); + $end = $values->get($middlePosition); + + return (new static([$start, $end]))->average(); + } + /** * Collapse the collection of items into a single array. *
true
Other
laravel
framework
e011ca3761653d8de194441d4f5e6f6a68f9fc08.json
Add median function
tests/Support/SupportCollectionTest.php
@@ -1282,6 +1282,39 @@ public function testPipe() return $collection->sum(); })); } + + public function testMedianValueWithArrayCollection() + { + $collection = new Collection([1, 2, 2, 4]); + + $this->assertEquals(2, $collection->median()); + } + + public function testMedianValueByKey() + { + $collection = new Collection([ + (object) ['foo' => 1], + (object) ['foo' => 2], + (object) ['foo' => 2], + (object) ['foo' => 4], + ]); + $this->assertEquals(2, $collection->median('foo')); + } + + public function testEvenMedianCollection() + { + $collection = new Collection([ + (object) ['foo' => 0], + (object) ['foo' => 3], + ]); + $this->assertEquals(1.5, $collection->median('foo')); + } + + public function testMedianOnEmptyCollectionReturnsNull() + { + $collection = new Collection(); + $this->assertNull($collection->median()); + } } class TestAccessorEloquentTestStub
true
Other
laravel
framework
87a982916a1d8b90fb5f4f1ef92944a3d1c3664d.json
change flash data key
src/Illuminate/Session/Store.php
@@ -298,11 +298,11 @@ protected function addBagDataToSession() */ public function ageFlashData() { - $this->forget($this->get('flash.old', [])); + $this->forget($this->get('_flash.old', [])); - $this->put('flash.old', $this->get('flash.new', [])); + $this->put('_flash.old', $this->get('_flash.new', [])); - $this->put('flash.new', []); + $this->put('_flash.new', []); } /** @@ -468,7 +468,7 @@ public function flash($key, $value) { $this->put($key, $value); - $this->push('flash.new', $key); + $this->push('_flash.new', $key); $this->removeFromOldFlashData([$key]); } @@ -485,7 +485,7 @@ public function now($key, $value) { $this->put($key, $value); - $this->push('flash.old', $key); + $this->push('_flash.old', $key); } /** @@ -506,9 +506,9 @@ public function flashInput(array $value) */ public function reflash() { - $this->mergeNewFlashes($this->get('flash.old', [])); + $this->mergeNewFlashes($this->get('_flash.old', [])); - $this->put('flash.old', []); + $this->put('_flash.old', []); } /** @@ -534,9 +534,9 @@ public function keep($keys = null) */ protected function mergeNewFlashes(array $keys) { - $values = array_unique(array_merge($this->get('flash.new', []), $keys)); + $values = array_unique(array_merge($this->get('_flash.new', []), $keys)); - $this->put('flash.new', $values); + $this->put('_flash.new', $values); } /** @@ -547,7 +547,7 @@ protected function mergeNewFlashes(array $keys) */ protected function removeFromOldFlashData(array $keys) { - $this->put('flash.old', array_diff($this->get('flash.old', []), $keys)); + $this->put('_flash.old', array_diff($this->get('_flash.old', []), $keys)); } /**
true
Other
laravel
framework
87a982916a1d8b90fb5f4f1ef92944a3d1c3664d.json
change flash data key
tests/Session/EncryptedSessionStoreTest.php
@@ -22,7 +22,7 @@ public function testSessionIsProperlyEncrypted() '_token' => $session->token(), 'foo' => 'bar', 'baz' => 'boom', - 'flash' => [ + '_flash' => [ 'new' => [], 'old' => ['baz'], ],
true
Other
laravel
framework
87a982916a1d8b90fb5f4f1ef92944a3d1c3664d.json
change flash data key
tests/Session/SessionStoreTest.php
@@ -108,7 +108,7 @@ public function testSessionIsProperlySaved() '_token' => $session->token(), 'foo' => 'bar', 'baz' => 'boom', - 'flash' => [ + '_flash' => [ 'new' => [], 'old' => ['baz'], ], @@ -182,33 +182,33 @@ public function testDataMergeNewFlashes() $session = $this->getSession(); $session->flash('foo', 'bar'); $session->set('fu', 'baz'); - $session->set('flash.old', ['qu']); - $this->assertNotFalse(array_search('foo', $session->get('flash.new'))); - $this->assertFalse(array_search('fu', $session->get('flash.new'))); + $session->set('_flash.old', ['qu']); + $this->assertNotFalse(array_search('foo', $session->get('_flash.new'))); + $this->assertFalse(array_search('fu', $session->get('_flash.new'))); $session->keep(['fu', 'qu']); - $this->assertNotFalse(array_search('foo', $session->get('flash.new'))); - $this->assertNotFalse(array_search('fu', $session->get('flash.new'))); - $this->assertNotFalse(array_search('qu', $session->get('flash.new'))); - $this->assertFalse(array_search('qu', $session->get('flash.old'))); + $this->assertNotFalse(array_search('foo', $session->get('_flash.new'))); + $this->assertNotFalse(array_search('fu', $session->get('_flash.new'))); + $this->assertNotFalse(array_search('qu', $session->get('_flash.new'))); + $this->assertFalse(array_search('qu', $session->get('_flash.old'))); } public function testReflash() { $session = $this->getSession(); $session->flash('foo', 'bar'); - $session->set('flash.old', ['foo']); + $session->set('_flash.old', ['foo']); $session->reflash(); - $this->assertNotFalse(array_search('foo', $session->get('flash.new'))); - $this->assertFalse(array_search('foo', $session->get('flash.old'))); + $this->assertNotFalse(array_search('foo', $session->get('_flash.new'))); + $this->assertFalse(array_search('foo', $session->get('_flash.old'))); } public function testReflashWithNow() { $session = $this->getSession(); $session->now('foo', 'bar'); $session->reflash(); - $this->assertNotFalse(array_search('foo', $session->get('flash.new'))); - $this->assertFalse(array_search('foo', $session->get('flash.old'))); + $this->assertNotFalse(array_search('foo', $session->get('_flash.new'))); + $this->assertFalse(array_search('foo', $session->get('_flash.old'))); } public function testReplace()
true
Other
laravel
framework
87c4e23d2d48d0a487432bb9a91e45b8de75dec9.json
Add a withCallback method.
src/Illuminate/Http/JsonResponse.php
@@ -27,6 +27,19 @@ public function __construct($data = null, $status = 200, $headers = [], $options parent::__construct($data, $status, $headers); } + /** + * Sets the JSONP callback. + * + * @param string|null $callback + * @return $this + * + * @throws \InvalidArgumentException + */ + public function withCallback($callback = null) + { + return $this->setCallback($callback); + } + /** * Get the json_decoded data from the response. *
false
Other
laravel
framework
591adba3d00bdd2188a101870ce0acb76757f601.json
Add Eloquent is() method (#14281)
src/Illuminate/Database/Eloquent/Model.php
@@ -3037,6 +3037,17 @@ public function replicate(array $except = null) return $instance->setRelations($this->relations); } + /** + * Determine if the model matches the model passed in. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return bool + */ + public function is(Model $model) + { + return $this->getKey() === $model->getKey() && $this->getTable() === $model->getTable(); + } + /** * Get all of the current attributes on the model. *
true
Other
laravel
framework
591adba3d00bdd2188a101870ce0acb76757f601.json
Add Eloquent is() method (#14281)
tests/Database/DatabaseEloquentModelTest.php
@@ -1349,6 +1349,31 @@ public function testScopesMethod() $this->assertSame($scopes, $model->scopesCalled); } + public function testIsWithTheSameModelInstance() + { + $firstInstance = new EloquentModelStub(['id' => 1]); + $secondInstance = new EloquentModelStub(['id' => 1]); + $result = $firstInstance->is($secondInstance); + $this->assertTrue($result); + } + + public function testIsWithAnotherModelInstance() + { + $firstInstance = new EloquentModelStub(['id' => 1]); + $secondInstance = new EloquentModelStub(['id' => 2]); + $result = $firstInstance->is($secondInstance); + $this->assertFalse($result); + } + + public function testIsWIthAnotherModel() + { + $firstInstance = new EloquentModelStub(['id' => 1]); + $secondInstance = new EloquentModelStub(['id' => 1]); + $secondInstance->setTable('foo'); + $result = $firstInstance->is($secondInstance); + $this->assertFalse($result); + } + protected function addMockConnection($model) { $model->setConnectionResolver($resolver = m::mock('Illuminate\Database\ConnectionResolverInterface'));
true
Other
laravel
framework
1dc956d1674f264f7c8f06f33d1f06b601a04e58.json
allow dynamic arguments
src/Illuminate/Routing/Route.php
@@ -289,7 +289,7 @@ public function middleware($middleware = null) } if (is_string($middleware)) { - $middleware = [$middleware]; + $middleware = func_get_args(); } $this->action['middleware'] = array_merge(
false
Other
laravel
framework
e3fbfc1910b34532308c4203b8fc2cbe11100bd1.json
remove old email
src/Illuminate/Auth/Console/MakeAuthCommand.php
@@ -33,7 +33,6 @@ class MakeAuthCommand extends Command 'auth/register.stub' => 'auth/register.blade.php', 'auth/passwords/email.stub' => 'auth/passwords/email.blade.php', 'auth/passwords/reset.stub' => 'auth/passwords/reset.blade.php', - 'auth/emails/password.stub' => 'auth/emails/password.blade.php', 'layouts/app.stub' => 'layouts/app.blade.php', 'home.stub' => 'home.blade.php', 'welcome.stub' => 'welcome.blade.php',
true
Other
laravel
framework
e3fbfc1910b34532308c4203b8fc2cbe11100bd1.json
remove old email
src/Illuminate/Auth/Console/stubs/make/views/auth/emails/password.stub
@@ -1 +0,0 @@ -Click here to reset your password: <a href="{{ $link = url('password/reset', $token).'?email='.urlencode($user->getEmailForPasswordReset()) }}"> {{ $link }} </a>
true
Other
laravel
framework
256382ffe4a7a84175cde5fe7ba10d2c6959ef59.json
remove font awesome icons
src/Illuminate/Auth/Console/stubs/make/views/auth/login.stub
@@ -51,7 +51,7 @@ <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary"> - <i class="fa fa-btn fa-sign-in"></i> Login + Login </button> <a class="btn btn-link" href="{{ url('/password/reset') }}">Forgot Your Password?</a>
true
Other
laravel
framework
256382ffe4a7a84175cde5fe7ba10d2c6959ef59.json
remove font awesome icons
src/Illuminate/Auth/Console/stubs/make/views/auth/passwords/email.stub
@@ -34,7 +34,7 @@ <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary"> - <i class="fa fa-btn fa-envelope"></i> Send Password Reset Link + Send Password Reset Link </button> </div> </div>
true
Other
laravel
framework
256382ffe4a7a84175cde5fe7ba10d2c6959ef59.json
remove font awesome icons
src/Illuminate/Auth/Console/stubs/make/views/auth/passwords/reset.stub
@@ -57,7 +57,7 @@ <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary"> - <i class="fa fa-btn fa-refresh"></i> Reset Password + Reset Password </button> </div> </div>
true
Other
laravel
framework
256382ffe4a7a84175cde5fe7ba10d2c6959ef59.json
remove font awesome icons
src/Illuminate/Auth/Console/stubs/make/views/auth/register.stub
@@ -69,7 +69,7 @@ <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary"> - <i class="fa fa-btn fa-user"></i> Register + Register </button> </div> </div>
true
Other
laravel
framework
0b4f7985745702fc2e303765a056dd352a7b539c.json
add pipe function (#13899)
src/Illuminate/Support/Collection.php
@@ -604,6 +604,17 @@ public function forPage($page, $perPage) return $this->slice(($page - 1) * $perPage, $perPage); } + /** + * Pass the collection to the given callback and return the result. + * + * @param callable $callback + * @return mixed + */ + public function pipe(callable $callback) + { + return $callback($this); + } + /** * Get and remove the last item from the collection. *
true
Other
laravel
framework
0b4f7985745702fc2e303765a056dd352a7b539c.json
add pipe function (#13899)
tests/Support/SupportCollectionTest.php
@@ -1273,6 +1273,15 @@ public function testRandomThrowsAnExceptionUsingAmountBiggerThanCollectionSize() $data = new Collection([1, 2, 3]); $data->random(4); } + + public function testPipe() + { + $collection = new Collection([1, 2, 3]); + + $this->assertEquals(6, $collection->pipe(function ($collection) { + return $collection->sum(); + })); + } } class TestAccessorEloquentTestStub
true
Other
laravel
framework
d54500eb013d23ada07b563420e55e3712ef88ae.json
Fix MySQL multiple-table DELETE error (#14179) http://dev.mysql.com/doc/refman/5.7/en/delete.html "You cannot use ORDER BY or LIMIT in a multiple-table DELETE."
src/Illuminate/Database/Query/Grammars/MySqlGrammar.php
@@ -111,14 +111,14 @@ public function compileDelete(Builder $query) $sql = trim("delete $table from {$table}{$joins} $where"); } else { $sql = trim("delete from $table $where"); - } - if (isset($query->orders)) { - $sql .= ' '.$this->compileOrders($query, $query->orders); - } + if (isset($query->orders)) { + $sql .= ' '.$this->compileOrders($query, $query->orders); + } - if (isset($query->limit)) { - $sql .= ' '.$this->compileLimit($query, $query->limit); + if (isset($query->limit)) { + $sql .= ' '.$this->compileLimit($query, $query->limit); + } } return $sql;
true
Other
laravel
framework
d54500eb013d23ada07b563420e55e3712ef88ae.json
Fix MySQL multiple-table DELETE error (#14179) http://dev.mysql.com/doc/refman/5.7/en/delete.html "You cannot use ORDER BY or LIMIT in a multiple-table DELETE."
tests/Database/DatabaseQueryBuilderTest.php
@@ -1094,18 +1094,23 @@ public function testDeleteMethod() $builder->getConnection()->shouldReceive('delete')->once()->with('delete from "users" where "id" = ?', [1])->andReturn(1); $result = $builder->from('users')->delete(1); $this->assertEquals(1, $result); + + $builder = $this->getMySqlBuilder(); + $builder->getConnection()->shouldReceive('delete')->once()->with('delete from `users` where `email` = ? order by `id` asc limit 1', ['foo'])->andReturn(1); + $result = $builder->from('users')->where('email', '=', 'foo')->orderBy('id')->take(1)->delete(); + $this->assertEquals(1, $result); } public function testDeleteWithJoinMethod() { $builder = $this->getMySqlBuilder(); $builder->getConnection()->shouldReceive('delete')->once()->with('delete `users` from `users` inner join `contacts` on `users`.`id` = `contacts`.`id` where `email` = ?', ['foo'])->andReturn(1); - $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->where('email', '=', 'foo')->delete(); + $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->where('email', '=', 'foo')->orderBy('id')->limit(1)->delete(); $this->assertEquals(1, $result); $builder = $this->getMySqlBuilder(); $builder->getConnection()->shouldReceive('delete')->once()->with('delete `users` from `users` inner join `contacts` on `users`.`id` = `contacts`.`id` where `id` = ?', [1])->andReturn(1); - $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->delete(1); + $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->orderBy('id')->take(1)->delete(1); $this->assertEquals(1, $result); }
true
Other
laravel
framework
741f29d4693156192d7dee6f30670e989bdf8a9d.json
Make getConnectionName Overridable (#14194) Use function call in newFromBuilder instead of class variable to allow for override of getConnectionName function
src/Illuminate/Database/Eloquent/Model.php
@@ -521,7 +521,7 @@ public function newFromBuilder($attributes = [], $connection = null) $model->setRawAttributes((array) $attributes, true); - $model->setConnection($connection ?: $this->connection); + $model->setConnection($connection ?: $this->getConnectionName()); return $model; }
false
Other
laravel
framework
68a4993372525cb154201ed02592e0086dc70877.json
Allow easy addition of custom drivers.
src/Illuminate/Notifications/ChannelManager.php
@@ -2,6 +2,7 @@ namespace Illuminate\Notifications; +use InvalidArgumentException; use Illuminate\Support\Manager; use Nexmo\Client as NexmoClient; use GuzzleHttp\Client as HttpClient; @@ -158,6 +159,27 @@ protected function createSlackDriver() return new Channels\SlackWebhookChannel(new HttpClient); } + /** + * Create a new driver instance. + * + * @param string $driver + * @return mixed + * + * @throws \InvalidArgumentException + */ + protected function createDriver($driver) + { + try { + return parent::createDriver($driver); + } catch (InvalidArgumentException $e) { + if (class_exists($driver)) { + return $this->app->make($driver); + } + + throw $e; + } + } + /** * Get the default channel driver names. *
false
Other
laravel
framework
08cde109bfc94098fb79bc2b505de6497867c291.json
Fix method name.
tests/Notifications/NotificationSlackChannelTest.php
@@ -9,7 +9,7 @@ public function tearDown() Mockery::close(); } - public function testSmsIsSentViaNexmo() + public function testCorrectPayloadIsSentToSlack() { $notification = new Notification([ $notifiable = new NotificationSlackChannelTestNotifiable,
false
Other
laravel
framework
be61e3e3c86f69cb7713d3af54396c8ee2fa931f.json
Remove test code.
tests/Notifications/NotificationSlackChannelTest.php
@@ -26,10 +26,6 @@ public function testSmsIsSentViaNexmo() $http = Mockery::mock('GuzzleHttp\Client') ); - // $http->shouldReceive('post')->andReturnUsing(function (...$args) { - // dd($args); - // }); - $http->shouldReceive('post')->with('url', [ 'json' => [ 'attachments' => [
false
Other
laravel
framework
8ef07aaab3b34bc804434e1dbf53c23f3382d877.json
Add another test.
tests/Notifications/NotificationChannelManagerTest.php
@@ -3,6 +3,7 @@ use Illuminate\Container\Container; use Illuminate\Notifications\Notification; use Illuminate\Notifications\ChannelManager; +use Illuminate\Contracts\Bus\Dispatcher as Bus; class NotificationChannelManagerTest extends PHPUnit_Framework_TestCase { @@ -32,6 +33,18 @@ public function testNotificationCanBeDispatchedToDriver() $manager->dispatch(new NotificationChannelManagerTestNotifiable, new NotificationChannelManagerTestNotification); } + + public function testNotificationCanBeQueued() + { + $container = new Container; + $container->instance('config', ['app.name' => 'Name', 'app.logo' => 'Logo']); + $container->instance(Bus::class, $bus = Mockery::mock()); + $bus->shouldReceive('dispatch')->with(Mockery::type(Illuminate\Notifications\SendQueuedNotifications::class)); + Container::setInstance($container); + $manager = Mockery::mock(ChannelManager::class.'[driver]', [$container]); + + $manager->dispatch(new NotificationChannelManagerTestNotifiable, new NotificationChannelManagerTestQueuedNotification); + } } class NotificationChannelManagerTestNotifiable @@ -51,3 +64,18 @@ public function message() return $this->line('test')->action('Text', 'url'); } } + +class NotificationChannelManagerTestQueuedNotification extends Notification implements Illuminate\Contracts\Queue\ShouldQueue +{ + use Illuminate\Bus\Queueable; + + public function via() + { + return ['test']; + } + + public function message() + { + return $this->line('test')->action('Text', 'url'); + } +}
false
Other
laravel
framework
8f5c8c4bd2513248133fb95d06c450b9cb4e5a59.json
Improve notification testability.
src/Illuminate/Contracts/Notifications/Factory.php
@@ -5,10 +5,12 @@ interface Factory { /** - * Create a new notification for the given notifiable entities. + * Dispatch the given notification instance to the given notifiable. * - * @param array $notifiables - * @return \Illuminate\Notifications\Notification + * @param mixed $notifiable + * @param mixed $instance + * @param array $channels + * @return void */ - public function to($notifiables); + public function dispatch($notifiable, $instance, array $channels = []); }
true
Other
laravel
framework
8f5c8c4bd2513248133fb95d06c450b9cb4e5a59.json
Improve notification testability.
src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php
@@ -4,6 +4,7 @@ use Mockery; use Exception; +use Illuminate\Contracts\Notifications\Factory as NotificationFactory; trait MocksApplicationServices { @@ -21,6 +22,13 @@ trait MocksApplicationServices */ protected $dispatchedJobs = []; + /** + * All of the dispatched notifications. + * + * @var array + */ + protected $dispatchedNotifications = []; + /** * Specify a list of events that should be fired for the given operation. * @@ -238,4 +246,53 @@ protected function wasDispatched($needle, array $haystack) return false; } + + /** + * Mock the notification dispatcher so all notifications are silenced. + * + * @return $this + */ + protected function withoutNotifications() + { + $mock = Mockery::mock(NotificationFactory::class); + + $mock->shouldReceive('dispatch')->andReturnUsing(function ($notifiable, $instance, $channels = []) { + $this->dispatchedNotifications[] = compact( + 'notifiable', 'instance', 'channels' + ); + }); + + $this->app->instance(NotificationFactory::class, $mock); + + return $this; + } + + /** + * Specify a notification that is expected to be dispatched. + * + * @param mixed $notifiable + * @param string $notification + * @return $this + */ + protected function expectsNotification($notifiable, $notification) + { + $this->withoutNotifications(); + + $this->beforeApplicationDestroyed(function () use ($notifiable, $notification) { + foreach ($this->dispatchedNotifications as $dispatched) { + if (($dispatched['notifiable'] === $notifiable || + $dispatched['notifiable']->getKey() == $notifiable->getKey()) && + get_class($dispatched['instance']) === $notification) { + + return $this; + } + } + + throw new Exception( + 'The following expected notification were not dispatched: ['.$notification.']' + ); + }); + + return $this; + } }
true
Other
laravel
framework
8f5c8c4bd2513248133fb95d06c450b9cb4e5a59.json
Improve notification testability.
src/Illuminate/Notifications/ChannelManager.php
@@ -4,6 +4,8 @@ use Illuminate\Support\Manager; use Nexmo\Client as NexmoClient; +use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Contracts\Bus\Dispatcher as Bus; use Nexmo\Client\Credentials\Basic as NexmoCredentials; use Illuminate\Contracts\Notifications\Factory as FactoryContract; @@ -27,6 +29,52 @@ public function to($notifiables) return new Channels\Notification($this, $notifiables); } + /** + * Dispatch the given notification instance to the given notifiable. + * + * @param mixed $notifiable + * @param mixed $instance + * @param array $channels + * @return void + */ + public function dispatch($notifiable, $instance, array $channels = []) + { + $notifications = $this->notificationsFromInstance( + $notifiable, $instance + ); + + if (count($channels) > 0) { + foreach ($notifications as $notification) { + $notification->via((array) $channels); + } + } + + if ($instance instanceof ShouldQueue) { + return $this->queueNotifications($instance, $notifications); + } + + foreach ($notifications as $notification) { + $this->send($notification); + } + } + + /** + * Queue the given notification instances. + * + * @param mixed $instance + * @param array[\Illuminate\Notifcations\Channels\Notification] + * @return void + */ + protected function queueNotifications($instance, array $notifications) + { + $this->app->make(Bus::class)->dispatch( + (new SendQueuedNotifications($notifications)) + ->onConnection($instance->connection) + ->onQueue($instance->queue) + ->delay($instance->delay) + ); + } + /** * Send the given notification. *
true
Other
laravel
framework
8f5c8c4bd2513248133fb95d06c450b9cb4e5a59.json
Improve notification testability.
src/Illuminate/Notifications/RoutesNotifications.php
@@ -3,7 +3,7 @@ namespace Illuminate\Notifications; use Illuminate\Support\Str; -use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Contracts\Notifications\Factory as NotificationFactory; trait RoutesNotifications { @@ -15,19 +15,7 @@ trait RoutesNotifications */ public function notify($instance) { - $manager = app(ChannelManager::class); - - $notifications = $manager->notificationsFromInstance( - $this, $instance - ); - - if ($instance instanceof ShouldQueue) { - return $this->queueNotifications($instance, $notifications); - } - - foreach ($notifications as $notification) { - $manager->send($notification); - } + app(NotificationFactory::class)->dispatch($this, $instance); } /** @@ -39,40 +27,7 @@ public function notify($instance) */ public function notifyVia($channels, $instance) { - $manager = app(ChannelManager::class); - - $notifications = $manager->notificationsFromInstance( - $this, $instance, (array) $channels - ); - - foreach ($notifications as $notification) { - $notification->via((array) $channels); - } - - if ($instance instanceof ShouldQueue) { - return $this->queueNotifications($instance, $notifications); - } - - foreach ($notifications as $notification) { - $manager->send($notification); - } - } - - /** - * Queue the given notification instances. - * - * @param mixed $instance - * @param array[\Illuminate\Notifcations\Channels\Notification] - * @return void - */ - protected function queueNotifications($instance, array $notifications) - { - dispatch( - (new SendQueuedNotifications($notifications)) - ->onConnection($instance->connection) - ->onQueue($instance->queue) - ->delay($instance->delay) - ); + app(NotificationFactory::class)->dispatch($this, $instance, $channels); } /**
true
Other
laravel
framework
f50be03c8ea7cc9c675aa594fc9392fad1eb38e1.json
Replace actual view. Signed-off-by: crynobone <crynobone@gmail.com>
src/Illuminate/Notifications/Channels/MailChannel.php
@@ -55,7 +55,7 @@ public function send(Notification $notification) $view = data_get($notification, 'options.view', 'notifications::email'); - $this->mailer->send('notifications::email', $data, function ($m) use ($notification, $emails) { + $this->mailer->send($view, $data, function ($m) use ($notification, $emails) { count($notification->notifiables) === 1 ? $m->to($emails) : $m->bcc($emails);
false
Other
laravel
framework
1a4c410edfe723ab7d873392eab165e37fd65e33.json
create factory modifiers
src/Illuminate/Database/Eloquent/Factory.php
@@ -33,6 +33,13 @@ public function __construct(Faker $faker) */ protected $definitions = []; + /** + * The model modifiers in the container. + * + * @var array + */ + protected $modifiers = []; + /** * Create a new factory container. * @@ -73,6 +80,19 @@ public function define($class, callable $attributes, $name = 'default') $this->definitions[$class][$name] = $attributes; } + /** + * Define a modifier with a given set of attributes. + * + * @param string $class + * @param string $name + * @param callable $attributes + * @return void + */ + public function defineModifier($class, $name, callable $attributes) + { + $this->modifiers[$class][$name] = $attributes; + } + /** * Create an instance of the given model and persist it to the database. * @@ -179,7 +199,7 @@ public function raw($class, array $attributes = [], $name = 'default') */ public function of($class, $name = 'default') { - return new FactoryBuilder($class, $name, $this->definitions, $this->faker); + return new FactoryBuilder($class, $name, $this->definitions, $this->faker, $this->modifiers); } /**
true
Other
laravel
framework
1a4c410edfe723ab7d873392eab165e37fd65e33.json
create factory modifiers
src/Illuminate/Database/Eloquent/FactoryBuilder.php
@@ -15,6 +15,13 @@ class FactoryBuilder */ protected $definitions; + /** + * The model modifiers in the container. + * + * @var array + */ + protected $modifiers; + /** * The model being built. * @@ -36,6 +43,13 @@ class FactoryBuilder */ protected $amount = 1; + /** + * The modifiers to apply. + * + * @var array + */ + protected $activeModifiers = []; + /** * The Faker instance for the builder. * @@ -50,14 +64,16 @@ class FactoryBuilder * @param string $name * @param array $definitions * @param \Faker\Generator $faker + * @param array $modifiers * @return void */ - public function __construct($class, $name, array $definitions, Faker $faker) + public function __construct($class, $name, array $definitions, Faker $faker, array $modifiers) { $this->name = $name; $this->class = $class; $this->faker = $faker; $this->definitions = $definitions; + $this->modifiers = $modifiers; } /** @@ -73,6 +89,23 @@ public function times($amount) return $this; } + /** + * Set the active modifiers. + * + * @param array|string $modifiers + * @return $this + */ + public function modifiers($modifiers) + { + if(is_string($modifiers)){ + $modifiers = [$modifiers]; + } + + $this->activeModifiers = $modifiers; + + return $this; + } + /** * Create a collection of models and persist them to the database. * @@ -135,6 +168,19 @@ protected function makeInstance(array $attributes = []) $this->faker, $attributes ); + foreach($this->activeModifiers as $activeModifier){ + if( ! isset($this->modifiers[$this->class][$activeModifier])) { + throw new InvalidArgumentException("Unable to locate factory modifier with name [{$activeModifier}] [{$this->class}]."); + } + + $modifier = call_user_func( + $this->modifiers[$this->class][$activeModifier], + $this->faker, $attributes + ); + + $definition = array_merge($definition, $modifier); + } + $evaluated = $this->callClosureAttributes( array_merge($definition, $attributes) );
true
Other
laravel
framework
b0b042018c326982e6410852c7a757802f1bf650.json
add method to paginator
src/Illuminate/Pagination/Paginator.php
@@ -81,6 +81,18 @@ public function nextPageUrl() } } + /** + * Manually indicate that the paginator does have more pages. + * + * @return $this + */ + public function doesHaveMorePages() + { + $this->hasMore = true; + + return $this; + } + /** * Determine if there are more items in the data source. *
false
Other
laravel
framework
c12e8bfff9958e2c6c5f71737ec3d8600a40e26c.json
Remove optional parameters $true and $false
src/Illuminate/Support/MessageBag.php
@@ -110,38 +110,34 @@ public function has($key = null) * Determine if messages exist for all given keys. * * @param array $keys - * @param mixed $true - * @param mixed $false * @return bool */ - public function hasAll($keys = [], $true = true, $false = false) + public function hasAll($keys = []) { foreach ($keys as $key) { if ($this->first($key) === '') { - return $false; + return false; } } - return $true; + return true; } /** * Determine if messages exist for any given key. * * @param array $keys - * @param mixed $true - * @param mixed $false * @return bool */ - public function hasAny($keys = [], $true = true, $false = false) + public function hasAny($keys = []) { foreach ($keys as $key) { if ($this->first($key) !== '') { - return $true; + return true; } } - return $false; + return false; } /**
false
Other
laravel
framework
a0142e9745f68e3853a26675a5580cb6e63152ac.json
Fix missing space after foreach
src/Illuminate/Support/MessageBag.php
@@ -116,7 +116,7 @@ public function has($key = null) */ public function hasAll($keys = [], $true = true, $false = false) { - foreach($keys as $key) { + foreach ($keys as $key) { if ($this->first($key) === '') { return $false; } @@ -135,7 +135,7 @@ public function hasAll($keys = [], $true = true, $false = false) */ public function hasAny($keys = [], $true = true, $false = false) { - foreach($keys as $key) { + foreach ($keys as $key) { if ($this->first($key) !== '') { return $true; }
false
Other
laravel
framework
9074b557305da710435fe377df6e8c55919bf7ea.json
Add tests for hasAny and hasAll
tests/Support/SupportMessageBagTest.php
@@ -74,6 +74,30 @@ public function testHasIndicatesExistence() $this->assertFalse($container->has('bar')); } + public function testHasAnyIndicatesExistence() + { + $container = new MessageBag; + $container->setFormat(':message'); + $container->add('foo', 'bar'); + $container->add('bar', 'foo'); + $container->add('boom', 'baz'); + $this->assertTrue($container->hasAny(['foo', 'bar'])); + $this->assertTrue($container->hasAny(['boom', 'baz'])); + $this->assertFalse($container->hasAny(['baz'])); + } + + public function testHasAllIndicatesExistence() + { + $container = new MessageBag; + $container->setFormat(':message'); + $container->add('foo', 'bar'); + $container->add('bar', 'foo'); + $container->add('boom', 'baz'); + $this->assertTrue($container->hasAll(['foo', 'bar', 'boom'])); + $this->assertFalse($container->hasAll(['foo', 'bar', 'boom', 'baz'])); + $this->assertFalse($container->hasAll(['foo', 'baz'])); + } + public function testAllReturnsAllMessages() { $container = new MessageBag;
false
Other
laravel
framework
7194f9c5ff6ea6b8f6e794a219ea5902d11f4411.json
Use File::link in storage:link command
src/Illuminate/Foundation/Console/StorageLinkCommand.php
@@ -31,7 +31,7 @@ public function fire() return $this->error('The "public/storage" directory already exists.'); } - symlink(storage_path('app/public'), public_path('storage')); + $this->laravel->make('files')->link(storage_path('app/public'), public_path('storage')); $this->info('The [public/storage] directory has been linked.'); }
false
Other
laravel
framework
e742751f6bad291e0cf714528768e1f120314da2.json
Add tightenco/collect to replace section (#14118) Since tightenco/collect is just standalone illuminate collections from support, this replace should be added.
composer.json
@@ -68,7 +68,8 @@ "illuminate/support": "self.version", "illuminate/translation": "self.version", "illuminate/validation": "self.version", - "illuminate/view": "self.version" + "illuminate/view": "self.version", + "tightenco/collect": "self.version" }, "require-dev": { "aws/aws-sdk-php": "~3.0",
false
Other
laravel
framework
cc3c2366579710c01bbe3ed1caae27a7587c550d.json
Add missing @throws (#14107)
src/Illuminate/Foundation/Exceptions/Handler.php
@@ -50,6 +50,7 @@ public function __construct(Container $container) * Report or log an exception. * * @param \Exception $e + * @throws \Exception $e * @return void */ public function report(Exception $e)
false
Other
laravel
framework
946edc91f77160c0d24d0278a142fbc9de84af01.json
Remove extra method (#14103)
src/Illuminate/Routing/ControllerDispatcher.php
@@ -15,19 +15,6 @@ class ControllerDispatcher * @return mixed */ public function dispatch(Route $route, $controller, $method) - { - return $this->call($route, $controller, $method); - } - - /** - * Call the given controller instance method. - * - * @param \Illuminate\Routing\Route $route - * @param \Illuminate\Routing\Controller $controller - * @param string $method - * @return mixed - */ - protected function call($route, $controller, $method) { $parameters = $this->resolveClassMethodDependencies( $route->parametersWithoutNulls(), $controller, $method @@ -37,7 +24,7 @@ protected function call($route, $controller, $method) return $controller->callAction($method, $parameters); } - return call_user_func_array([$controller, $method], $parameters); + return $controller->$method(...$parameters); } /**
false
Other
laravel
framework
bb83eeb94759803685813daf7436b3013f6b767d.json
Remove duplicate call to prepareResponse
src/Illuminate/Routing/Router.php
@@ -592,9 +592,7 @@ public function dispatch(Request $request) { $this->currentRequest = $request; - $response = $this->dispatchToRoute($request); - - return $this->prepareResponse($request, $response); + return $this->dispatchToRoute($request); } /**
false
Other
laravel
framework
4e7d69f90e5bdf4e1336566a53b33ca48d85e1bb.json
add notifyVia method
src/Illuminate/Notifications/RoutesNotifications.php
@@ -30,6 +30,34 @@ public function notify($instance) } } + /** + * Send the given notification via the given channels. + * + * @param array|string $channels + * @param mixed $instance + * @return void + */ + public function notifyVia($channels, $instance) + { + $manager = app(ChannelManager::class); + + $notifications = Channels\Notification::notificationsFromInstance( + $this, $instance, (array) $channels + ); + + foreach ($notifications as $notification) { + $notification->via((array) $channels); + } + + if ($instance instanceof ShouldQueue) { + return $this->queueNotifications($instance, $notifications); + } + + foreach ($notifications as $notification) { + $manager->send($notification); + } + } + /** * Queue the given notification instances. *
false
Other
laravel
framework
e23e05e9f949e0d21ad7d39f4e028e826e0328ef.json
convert password reminders to notifications
src/Illuminate/Auth/Notifications/ResetPassword.php
@@ -0,0 +1,50 @@ +<?php + +namespace Illuminate\Auth\Notifications; + +use Illuminate\Notifications\Notification; + +class ResetPassword extends Notification +{ + /** + * The password reset token. + * + * @var string + */ + public $token; + + /** + * Create a notification instance. + * + * @param string $token + * @return void + */ + public function __construct($token) + { + $this->token = $token; + } + + /** + * Get the notification's channels. + * + * @param mixed $notifiable + * @return array|string + */ + public function via($notifiable) + { + return ['mail']; + } + + /** + * Get the notification message. + * + * @param mixed $notifiable + * @return array + */ + public function message($notifiable) + { + return $this->line("You are receiving this email because we received a password reset request for your account. Click the button below to reset your password:") + ->action('Reset Password', url('password/reset', $this->token).'?email='.urlencode($notifiable->email)) + ->line("If you did not request a password reset, no further action is required."); + } +}
true
Other
laravel
framework
e23e05e9f949e0d21ad7d39f4e028e826e0328ef.json
convert password reminders to notifications
src/Illuminate/Auth/Passwords/PasswordBroker.php
@@ -6,9 +6,9 @@ use Illuminate\Support\Arr; use UnexpectedValueException; use Illuminate\Contracts\Auth\UserProvider; -use Illuminate\Contracts\Mail\Mailer as MailerContract; use Illuminate\Contracts\Auth\PasswordBroker as PasswordBrokerContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; +use Illuminate\Auth\Notifications\ResetPassword as ResetPasswordNotification; class PasswordBroker implements PasswordBrokerContract { @@ -26,20 +26,6 @@ class PasswordBroker implements PasswordBrokerContract */ protected $users; - /** - * The mailer instance. - * - * @var \Illuminate\Contracts\Mail\Mailer - */ - protected $mailer; - - /** - * The view of the password reset link e-mail. - * - * @var string - */ - protected $emailView; - /** * The custom password validator callback. * @@ -52,19 +38,13 @@ class PasswordBroker implements PasswordBrokerContract * * @param \Illuminate\Auth\Passwords\TokenRepositoryInterface $tokens * @param \Illuminate\Contracts\Auth\UserProvider $users - * @param \Illuminate\Contracts\Mail\Mailer $mailer - * @param string $emailView * @return void */ public function __construct(TokenRepositoryInterface $tokens, - UserProvider $users, - MailerContract $mailer, - $emailView) + UserProvider $users) { $this->users = $users; - $this->mailer = $mailer; $this->tokens = $tokens; - $this->emailView = $emailView; } /** @@ -88,37 +68,17 @@ public function sendResetLink(array $credentials, Closure $callback = null) // Once we have the reset token, we are ready to send the message out to this // user with a link to reset their password. We will then redirect back to // the current URI having nothing set in the session to indicate errors. - $token = $this->tokens->create($user); - - $this->emailResetLink($user, $token, $callback); + if ($callback) { + call_user_func($callback, $user, $this->tokens->create($user)); + } else { + $user->notify(new ResetPasswordNotification( + $this->tokens->create($user) + )); + } return static::RESET_LINK_SENT; } - /** - * Send the password reset link via e-mail. - * - * @param \Illuminate\Contracts\Auth\CanResetPassword $user - * @param string $token - * @param \Closure|null $callback - * @return int - */ - public function emailResetLink(CanResetPasswordContract $user, $token, Closure $callback = null) - { - // We will use the reminder view that was given to the broker to display the - // password reminder e-mail. We'll pass a "token" variable into the views - // so that it may be displayed for an user to click for password reset. - $view = $this->emailView; - - return $this->mailer->send($view, compact('token', 'user'), function ($m) use ($user, $token, $callback) { - $m->to($user->getEmailForPasswordReset()); - - if (! is_null($callback)) { - call_user_func($callback, $m, $user, $token); - } - }); - } - /** * Reset the password for the given token. *
true
Other
laravel
framework
e23e05e9f949e0d21ad7d39f4e028e826e0328ef.json
convert password reminders to notifications
src/Illuminate/Auth/Passwords/PasswordBrokerManager.php
@@ -69,9 +69,7 @@ protected function resolve($name) // aggregate service of sorts providing a convenient interface for resets. return new PasswordBroker( $this->createTokenRepository($config), - $this->app['auth']->createUserProvider($config['provider']), - $this->app['mailer'], - $config['email'] + $this->app['auth']->createUserProvider($config['provider']) ); }
true
Other
laravel
framework
e23e05e9f949e0d21ad7d39f4e028e826e0328ef.json
convert password reminders to notifications
src/Illuminate/Contracts/Notifications/Factory.php
@@ -0,0 +1,14 @@ +<?php + +namespace Illuminate\Contracts\Notifications; + +interface Factory +{ + /** + * Create a new notification for the given notifiable entities. + * + * @param array $notifiables + * @return \Illuminate\Notifications\Notification + */ + public function to($notifiables); +}
true
Other
laravel
framework
e23e05e9f949e0d21ad7d39f4e028e826e0328ef.json
convert password reminders to notifications
src/Illuminate/Foundation/Auth/ResetsPasswords.php
@@ -77,7 +77,7 @@ public function sendResetLinkEmail(Request $request) $response = Password::broker($broker)->sendResetLink( $this->getSendResetLinkEmailCredentials($request), - $this->resetEmailBuilder() + $this->resetNotifier() ); switch ($response) { @@ -112,15 +112,13 @@ protected function getSendResetLinkEmailCredentials(Request $request) } /** - * Get the Closure which is used to build the password reset email message. + * Get the Closure which is used to build the password reset notification. * * @return \Closure */ - protected function resetEmailBuilder() + protected function resetNotifier() { - return function (Message $message) { - $message->subject($this->getEmailSubject()); - }; + // } /**
true
Other
laravel
framework
e23e05e9f949e0d21ad7d39f4e028e826e0328ef.json
convert password reminders to notifications
src/Illuminate/Notifications/ChannelManager.php
@@ -5,8 +5,9 @@ use Illuminate\Support\Manager; use Nexmo\Client as NexmoClient; use Nexmo\Client\Credentials\Basic as NexmoCredentials; +use Illuminate\Contracts\Notifications\Factory as FactoryContract; -class ChannelManager extends Manager +class ChannelManager extends Manager implements FactoryContract { /** * The default channels used to deliver messages.
true
Other
laravel
framework
e23e05e9f949e0d21ad7d39f4e028e826e0328ef.json
convert password reminders to notifications
src/Illuminate/Notifications/Channels/Notification.php
@@ -251,7 +251,7 @@ public static function notificationsFromInstance($notifiable, $instance, $channe $method = static::messageMethod($instance, $channel); - foreach ($instance->{$method}()->elements as $element) { + foreach ($instance->{$method}($notifiable)->elements as $element) { $notification->with($element); } }
true
Other
laravel
framework
e23e05e9f949e0d21ad7d39f4e028e826e0328ef.json
convert password reminders to notifications
src/Illuminate/Notifications/NotificationServiceProvider.php
@@ -3,6 +3,7 @@ namespace Illuminate\Notifications; use Illuminate\Support\ServiceProvider; +use Illuminate\Contracts\Notifications\Factory as FactoryContract; class NotificationServiceProvider extends ServiceProvider { @@ -39,6 +40,10 @@ public function register() $this->app->singleton(ChannelManager::class, function ($app) { return new ChannelManager($app); }); + + $this->app->alias( + ChannelManager::class, FactoryContract::class + ); } /** @@ -49,7 +54,7 @@ public function register() public function provides() { return [ - ChannelManager::class, + ChannelManager::class, FactoryContract::class, ]; } }
true
Other
laravel
framework
838a5bd3b85bcaebd1781e319faa53dc3c73689b.json
Fix scopes methods and add test (#14078)
src/Illuminate/Database/Eloquent/Builder.php
@@ -1158,7 +1158,7 @@ public function scopes(array $scopes) } $builder = $builder->callScope( - 'scope'.ucfirst($scope), (array) $parameters + [$this->model, 'scope'.ucfirst($scope)], (array) $parameters ); }
true
Other
laravel
framework
838a5bd3b85bcaebd1781e319faa53dc3c73689b.json
Fix scopes methods and add test (#14078)
tests/Database/DatabaseEloquentModelTest.php
@@ -2,6 +2,7 @@ use Mockery as m; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Relations\Relation; class DatabaseEloquentModelTest extends PHPUnit_Framework_TestCase @@ -1348,6 +1349,22 @@ public function testStringIdTypePreserved() $this->assertEquals('string id', $model->id); } + public function testScopesMethod() + { + $model = new EloquentModelStub; + $this->addMockConnection($model); + + $scopes = [ + 'published', + 'category' => 'Laravel', + 'framework' => ['Laravel', '5.2'], + ]; + + $this->assertInstanceOf(Builder::class, $model->scopes($scopes)); + + $this->assertSame($scopes, $model->scopesCalled); + } + protected function addMockConnection($model) { $model->setConnectionResolver($resolver = m::mock('Illuminate\Database\ConnectionResolverInterface')); @@ -1371,6 +1388,7 @@ public function saved() class EloquentModelStub extends Model { public $connection; + public $scopesCalled = []; protected $table = 'stub'; protected $guarded = []; protected $morph_to_stub_type = 'EloquentModelSaveStub'; @@ -1429,6 +1447,21 @@ public function getAppendableAttribute() { return 'appended'; } + + public function scopePublished(Builder $builder) + { + $this->scopesCalled[] = 'published'; + } + + public function scopeCategory(Builder $builder, $category) + { + $this->scopesCalled['category'] = $category; + } + + public function scopeFramework(Builder $builder, $framework, $version) + { + $this->scopesCalled['framework'] = [$framework, $version]; + } } class EloquentModelCamelStub extends EloquentModelStub
true
Other
laravel
framework
3c3de796070760abdab101d0d68d690438e75bbe.json
fix policy generator
src/Illuminate/Foundation/Console/PolicyMakeCommand.php
@@ -53,6 +53,16 @@ protected function buildClass($name) */ protected function replaceModel($stub, $model) { + $model = str_replace('/', '\\', $model); + + if (Str::startsWith($model, '\\')) { + $stub = str_replace('NamespacedDummyModel', trim($model, '\\'), $stub); + } else { + $stub = str_replace('NamespacedDummyModel', $this->laravel->getNamespace().$model, $stub); + } + + $model = class_basename(trim($model, '\\')); + $stub = str_replace('DummyModel', $model, $stub); $stub = str_replace('dummyModelName', Str::lower($model), $stub);
true
Other
laravel
framework
3c3de796070760abdab101d0d68d690438e75bbe.json
fix policy generator
src/Illuminate/Foundation/Console/stubs/policy.stub
@@ -3,7 +3,7 @@ namespace DummyNamespace; use DummyRootNamespaceUser; -use DummyRootNamespaceDummyModel; +use NamespacedDummyModel; use Illuminate\Auth\Access\HandlesAuthorization; class DummyClass
true
Other
laravel
framework
76a2f466aff6997f3381f888ba91f8d35ff4fc8f.json
Add full stubbing to policy generator (#13922)
src/Illuminate/Foundation/Console/PolicyMakeCommand.php
@@ -2,7 +2,9 @@ namespace Illuminate\Foundation\Console; +use Illuminate\Support\Str; use Illuminate\Console\GeneratorCommand; +use Symfony\Component\Console\Input\InputOption; class PolicyMakeCommand extends GeneratorCommand { @@ -27,14 +29,49 @@ class PolicyMakeCommand extends GeneratorCommand */ protected $type = 'Policy'; + /** + * Build the class with the given name. + * + * @param string $name + * @return string + */ + protected function buildClass($name) + { + $stub = parent::buildClass($name); + + $model = $this->option('model'); + + return $model ? $this->replaceModel($stub, $model) : $stub; + } + + /** + * Replace the model for the given stub. + * + * @param string $stub + * @param string $model + * @return string + */ + protected function replaceModel($stub, $model) + { + $stub = str_replace('DummyModel', $model, $stub); + + $stub = str_replace('dummyModelName', Str::lower($model), $stub); + + return str_replace('dummyPluralModelName', Str::plural(Str::lower($model)), $stub); + } + /** * Get the stub file for the generator. * * @return string */ protected function getStub() { - return __DIR__.'/stubs/policy.stub'; + if ($this->option('model')) { + return __DIR__.'/stubs/policy.stub'; + } + + return __DIR__.'/stubs/policy.plain.stub'; } /** @@ -47,4 +84,16 @@ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace.'\Policies'; } + + /** + * Get the console command arguments. + * + * @return array + */ + protected function getOptions() + { + return [ + ['model', 'm', InputOption::VALUE_OPTIONAL, 'The model that the policy applies to.'], + ]; + } }
true
Other
laravel
framework
76a2f466aff6997f3381f888ba91f8d35ff4fc8f.json
Add full stubbing to policy generator (#13922)
src/Illuminate/Foundation/Console/stubs/policy.plain.stub
@@ -0,0 +1,21 @@ +<?php + +namespace DummyNamespace; + +use DummyRootNamespaceUser; +use Illuminate\Auth\Access\HandlesAuthorization; + +class DummyClass +{ + use HandlesAuthorization; + + /** + * Create a new policy instance. + * + * @return void + */ + public function __construct() + { + // + } +}
true
Other
laravel
framework
76a2f466aff6997f3381f888ba91f8d35ff4fc8f.json
Add full stubbing to policy generator (#13922)
src/Illuminate/Foundation/Console/stubs/policy.stub
@@ -2,18 +2,79 @@ namespace DummyNamespace; +use DummyRootNamespaceUser; +use DummyRootNamespaceDummyModel; use Illuminate\Auth\Access\HandlesAuthorization; class DummyClass { use HandlesAuthorization; /** - * Create a new policy instance. + * Determine whether the given user can view dummyPluralModelName. * - * @return void + * @param DummyRootNamespaceUser $user + * @return mixed */ - public function __construct() + public function viewAny(User $user) + { + // + } + + /** + * Determine whether the given user can view the specified dummyModelName. + * + * @param DummyRootNamespaceUser $user + * @param DummyRootNamespaceDummyModel $dummyModelName + * @return mixed + */ + public function view(User $user, DummyModel $dummyModelName) + { + // + } + + /** + * Determine whether the given user can create dummyPluralModelName. + * + * @param DummyRootNamespaceUser $user + * @return mixed + */ + public function createAny(User $user) + { + // + } + + /** + * Determine whether the given user can update dummyPluralModelName. + * + * @param DummyRootNamespaceUser $user + * @return mixed + */ + public function updateAny(User $user) + { + // + } + + /** + * Determine whether the given user can update the specified dummyModelName. + * + * @param DummyRootNamespaceUser $user + * @param DummyRootNamespaceDummyModel $dummyModelName + * @return mixed + */ + public function update(User $user, DummyModel $dummyModelName) + { + // + } + + /** + * Determine whether the given user can delete the specified dummyModelName. + * + * @param DummyRootNamespaceUser $user + * @param DummyRootNamespaceDummyModel $dummyModelName + * @return mixed + */ + public function delete(User $user, DummyModel $dummyModelName) { // }
true
Other
laravel
framework
881c6582c58a3bcea69bf4f16e6f1c1539d94661.json
Fix two typos (#14055)
src/Illuminate/Database/Capsule/Manager.php
@@ -33,7 +33,7 @@ public function __construct(Container $container = null) // Once we have the container setup, we will setup the default configuration // options in the container "config" binding. This will make the database - // manager behave correctly since all the correct binding are in place. + // manager behave correctly since all the correct bindings are in place. $this->setupDefaultConfiguration(); $this->setupManager(); @@ -135,7 +135,7 @@ public function bootEloquent() // If we have an event dispatcher instance, we will go ahead and register it // with the Eloquent ORM, allowing for model callbacks while creating and - // updating "model" instances; however, if it not necessary to operate. + // updating "model" instances; however, it is not necessary to operate. if ($dispatcher = $this->getEventDispatcher()) { Eloquent::setEventDispatcher($dispatcher); }
false
Other
laravel
framework
093409654608daa7b28d7c30933bda6f92935014.json
remove unnecessary else (#14036)
src/Illuminate/Queue/Queue.php
@@ -73,7 +73,9 @@ protected function createPayload($job, $data = '', $queue = null) { if ($job instanceof Closure) { return json_encode($this->createClosurePayload($job, $data)); - } elseif (is_object($job)) { + } + + if (is_object($job)) { return json_encode([ 'job' => 'Illuminate\Queue\CallQueuedHandler@call', 'data' => ['commandName' => get_class($job), 'command' => serialize(clone $job)],
false
Other
laravel
framework
5c4595a6727ab9f7b1a8993978a11cdf9de7aacc.json
change method to protected
src/Illuminate/Queue/Queue.php
@@ -222,7 +222,7 @@ public function setEncrypter(EncrypterContract $crypt) * * @throws EncryptException */ - public function getEncrypter() + protected function getEncrypter() { if (null === $this->crypt) { throw new EncryptException('No encrypter set for Queue');
false
Other
laravel
framework
c57765d206c68ef76465f54dd3fe0414f08b0e34.json
ensure encrypter exists
src/Illuminate/Queue/Queue.php
@@ -4,6 +4,7 @@ use Closure; use DateTime; +use Illuminate\Contracts\Encryption\EncryptException; use Illuminate\Support\Arr; use SuperClosure\Serializer; use Illuminate\Container\Container; @@ -19,6 +20,11 @@ abstract class Queue */ protected $container; + /** + * @var \Illuminate\Contracts\Encryption\Encrypter + */ + protected $crypt; + /** * Push a new job onto the queue. * @@ -144,7 +150,7 @@ protected function prepareQueueableEntity($value) */ protected function createClosurePayload($job, $data) { - $closure = $this->crypt->encrypt((new Serializer)->serialize($job)); + $closure = $this->getEncrypter()->encrypt((new Serializer)->serialize($job)); return ['job' => 'IlluminateQueueClosure', 'data' => compact('closure')]; } @@ -210,4 +216,20 @@ public function setEncrypter(EncrypterContract $crypt) { $this->crypt = $crypt; } + + + /** + * @return EncrypterContract + * + * @throws EncryptException + */ + public function getEncrypter() + { + if (null === $this->crypt) { + throw new EncryptException("No encrypter set for Queue"); + } + + return $this->crypt; + } + }
false
Other
laravel
framework
658d1dfb2af301f6c8b02dfd3b6b9dec6e5bee12.json
change comment wording
src/Illuminate/Foundation/Http/FormRequest.php
@@ -85,7 +85,7 @@ protected function getValidatorInstance() } /** - * Get validation data from request. + * Get data to be validated from the request. * * @return array */
false
Other
laravel
framework
acc0c963414c73c264029283cd143218cef63c35.json
Confirm Ajax request is not Pjax (#14024)
src/Illuminate/Foundation/Http/FormRequest.php
@@ -133,7 +133,7 @@ protected function failedAuthorization() */ public function response(array $errors) { - if ($this->ajax() || $this->wantsJson()) { + if (($this->ajax() && ! $this->pjax()) || $this->wantsJson()) { return new JsonResponse($errors, 422); }
false
Other
laravel
framework
997c74052c860a5e41e833a4079d4aeb5c48046d.json
resolve default driver in shouldUse
src/Illuminate/Auth/AuthManager.php
@@ -193,6 +193,8 @@ public function getDefaultDriver() */ public function shouldUse($name) { + $name = $name ?: $this->getDefaultDriver(); + $this->setDefaultDriver($name); $this->userResolver = function ($name = null) {
false
Other
laravel
framework
661bf1413a2fe5c613d4ca8121850d9b029001ff.json
put methods in alpha order... *cough* jeffrey
src/Illuminate/Foundation/helpers.php
@@ -191,6 +191,39 @@ function bcrypt($value, $options = []) } } +if (! function_exists('cache')) { + /** + * Get / set the specified cache value. + * + * If an array is passed, we'll assume you want to put to the cache. + * + * @param dynamic key|key,default|data,expiration|null + * @return mixed + */ + function cache() + { + $arguments = func_get_args(); + + if (empty($arguments)) { + return app('cache'); + } + + if (is_string($arguments[0])) { + return app('cache')->get($arguments[0], isset($arguments[1]) ? $arguments[1] : null); + } + + if (is_array($arguments[0])) { + if (! isset($arguments[1])) { + throw new Exception( + 'You must set an expiration time when putting to the cache.' + ); + } + + return app('cache')->put(key($arguments[0]), reset($arguments[0]), $arguments[1]); + } + } +} + if (! function_exists('config')) { /** * Get / set the specified configuration value. @@ -668,39 +701,6 @@ function session($key = null, $default = null) } } -if (! function_exists('cache')) { - /** - * Get / set the specified cache value. - * - * If an array is passed, we'll assume you want to put to the cache. - * - * @param dynamic key|key,default|data,expiration|null - * @return mixed - */ - function cache() - { - $arguments = func_get_args(); - - if (empty($arguments)) { - return app('cache'); - } - - if (is_string($arguments[0])) { - return app('cache')->get($arguments[0], isset($arguments[1]) ? $arguments[1] : null); - } - - if (is_array($arguments[0])) { - if (! isset($arguments[1])) { - throw new Exception( - 'You must set an expiration time when putting to the cache.' - ); - } - - return app('cache')->put(key($arguments[0]), reset($arguments[0]), $arguments[1]); - } - } -} - if (! function_exists('storage_path')) { /** * Get the path to the storage folder.
false
Other
laravel
framework
f53291b2b6e2d3032b4254e83ca03708dae1ec26.json
Add cache global helper
src/Illuminate/Foundation/helpers.php
@@ -668,6 +668,39 @@ function session($key = null, $default = null) } } +if (! function_exists('cache')) { + /** + * Get / set the specified cache value. + * + * If an array is passed, we'll assume you want to put to the cache. + * + * @param dynamic key|key,default|data,expiration|null + * @return mixed + */ + function cache() + { + $arguments = func_get_args(); + + if (empty($arguments)) { + return app('cache'); + } + + if (is_string($arguments[0])) { + return app('cache')->get($arguments[0], isset($arguments[1]) ? $arguments[1]: null); + } + + if (is_array($arguments[0])) { + if (! isset($arguments[1])) { + throw new Exception( + 'You must set an expiration time when putting to the cache.' + ); + } + + return app('cache')->put(key($arguments[0]), reset($arguments[0]), $arguments[1]); + } + } +} + if (! function_exists('storage_path')) { /** * Get the path to the storage folder.
true
Other
laravel
framework
f53291b2b6e2d3032b4254e83ca03708dae1ec26.json
Add cache global helper
tests/Foundation/FoundationHelpersTest.php
@@ -0,0 +1,40 @@ +<?php + +use Mockery as m; +use Illuminate\Foundation\Application; + +class FoundationHelpersTest extends PHPUnit_Framework_TestCase +{ + public function tearDown() + { + m::close(); + } + + public function testCache() + { + $app = new Application; + $app['cache'] = $cache = m::mock('StdClass'); + + // 1. cache() + $this->assertInstanceOf('StdClass', cache()); + + // 2. cache(['foo' => 'bar'], 1); + $cache->shouldReceive('put')->once()->with('foo', 'bar', 1); + cache(['foo' => 'bar'], 1); + + // 3. cache('foo'); + $cache->shouldReceive('get')->once()->andReturn('bar'); + $this->assertEquals('bar', cache('foo')); + + // 4. cache('baz', 'default'); + $cache->shouldReceive('get')->once()->with('baz', 'default')->andReturn('default'); + $this->assertEquals('default', cache('baz', 'default')); + } + + public function testCacheThrowsAnExceptionIfAnExpirationIsNotProvided() + { + $this->setExpectedException('Exception'); + + cache(['foo' => 'bar']); + } +}
true
Other
laravel
framework
daa49838d9557c526e28abd75f1825f8c05dd998.json
rewrite redis job to one json_decode()
src/Illuminate/Queue/Jobs/RedisJob.php
@@ -17,12 +17,19 @@ class RedisJob extends Job implements JobContract protected $redis; /** - * The Redis job payload. + * The Redis raw job payload. * * @var string */ protected $job; + /** + * The Redis decoded job payload. + * + * @var array + */ + protected $decodedJob; + /** * The Redis job payload inside the reserved queue. * @@ -42,6 +49,7 @@ class RedisJob extends Job implements JobContract public function __construct(Container $container, RedisQueue $redis, $job, $reserved, $queue) { $this->job = $job; + $this->decodedJob = json_decode($job, true); $this->redis = $redis; $this->queue = $queue; $this->reserved = $reserved; @@ -55,7 +63,7 @@ public function __construct(Container $container, RedisQueue $redis, $job, $rese */ public function fire() { - $this->resolveAndFire(json_decode($this->getRawBody(), true)); + $this->resolveAndFire($this->decodedJob); } /** @@ -100,7 +108,7 @@ public function release($delay = 0) */ public function attempts() { - return Arr::get(json_decode($this->job, true), 'attempts'); + return Arr::get($this->decodedJob, 'attempts'); } /** @@ -110,7 +118,7 @@ public function attempts() */ public function getJobId() { - return Arr::get(json_decode($this->job, true), 'id'); + return Arr::get($this->decodedJob, 'id'); } /** @@ -133,16 +141,6 @@ public function getRedisQueue() return $this->redis; } - /** - * Get the underlying Redis job. - * - * @return string - */ - public function getRedisJob() - { - return $this->job; - } - /** * Get the underlying reserved Redis job. *
true
Other
laravel
framework
daa49838d9557c526e28abd75f1825f8c05dd998.json
rewrite redis job to one json_decode()
tests/Queue/RedisQueueIntegrationTest.php
@@ -77,7 +77,7 @@ public function testPopProperlyPopsJobOffOfRedis() $redisJob = $this->queue->pop(); $after = time(); - $this->assertEquals($job, unserialize(json_decode($redisJob->getRedisJob())->data->command)); + $this->assertEquals($job, unserialize(json_decode($redisJob->getRawBody())->data->command)); $this->assertEquals(1, $redisJob->attempts()); $this->assertEquals($job, unserialize(json_decode($redisJob->getReservedJob())->data->command)); $this->assertEquals(2, json_decode($redisJob->getReservedJob())->attempts);
true
Other
laravel
framework
0831312aec47d904a65039e07574f41ab7492418.json
Fix session expiration on several drivers.
src/Illuminate/Session/CookieSessionHandler.php
@@ -2,6 +2,7 @@ namespace Illuminate\Session; +use Carbon\Carbon; use SessionHandlerInterface; use Symfony\Component\HttpFoundation\Request; use Illuminate\Contracts\Cookie\QueueingFactory as CookieJar; @@ -56,15 +57,26 @@ public function close() */ public function read($sessionId) { - return $this->request->cookies->get($sessionId) ?: ''; + $value = $this->request->cookies->get($sessionId) ?: ''; + + if (! is_null($decoded = json_decode($value, true)) && is_array($decoded)) { + if (isset($decoded['expires']) && time() <= $decoded['expires']) { + return $decoded['data']; + } + } + + return ''; } /** * {@inheritdoc} */ public function write($sessionId, $data) { - $this->cookie->queue($sessionId, $data, $this->minutes); + $this->cookie->queue($sessionId, json_encode([ + 'data' => $data, + 'expires' => Carbon::now()->addMinutes($this->minutes)->getTimestamp(), + ]), $this->minutes); } /**
true
Other
laravel
framework
0831312aec47d904a65039e07574f41ab7492418.json
Fix session expiration on several drivers.
src/Illuminate/Session/DatabaseSessionHandler.php
@@ -2,6 +2,7 @@ namespace Illuminate\Session; +use Carbon\Carbon; use SessionHandlerInterface; use Illuminate\Database\ConnectionInterface; @@ -21,6 +22,13 @@ class DatabaseSessionHandler implements SessionHandlerInterface, ExistenceAwareI */ protected $table; + /** + * The number of minutes the session should be valid. + * + * @var int + */ + protected $minutes; + /** * The existence state of the session. * @@ -33,11 +41,13 @@ class DatabaseSessionHandler implements SessionHandlerInterface, ExistenceAwareI * * @param \Illuminate\Database\ConnectionInterface $connection * @param string $table + * @param int $minutes * @return void */ - public function __construct(ConnectionInterface $connection, $table) + public function __construct(ConnectionInterface $connection, $table, $minutes) { $this->table = $table; + $this->minutes = $minutes; $this->connection = $connection; } @@ -64,6 +74,12 @@ public function read($sessionId) { $session = (object) $this->getQuery()->find($sessionId); + if (isset($session->last_activity)) { + if ($session->last_activity < Carbon::now()->subMinutes($this->minutes)->getTimestamp()) { + return; + } + } + if (isset($session->payload)) { $this->exists = true;
true
Other
laravel
framework
0831312aec47d904a65039e07574f41ab7492418.json
Fix session expiration on several drivers.
src/Illuminate/Session/FileSessionHandler.php
@@ -2,6 +2,7 @@ namespace Illuminate\Session; +use Carbon\Carbon; use SessionHandlerInterface; use Symfony\Component\Finder\Finder; use Illuminate\Filesystem\Filesystem; @@ -22,17 +23,26 @@ class FileSessionHandler implements SessionHandlerInterface */ protected $path; + /** + * The number of minutes the session should be valid. + * + * @var int + */ + protected $minutes; + /** * Create a new file driven handler instance. * * @param \Illuminate\Filesystem\Filesystem $files * @param string $path + * @param int $minutes * @return void */ - public function __construct(Filesystem $files, $path) + public function __construct(Filesystem $files, $path, $minutes) { $this->path = $path; $this->files = $files; + $this->minutes = $minutes; } /** @@ -57,7 +67,9 @@ public function close() public function read($sessionId) { if ($this->files->exists($path = $this->path.'/'.$sessionId)) { - return $this->files->get($path); + if (filemtime($path) >= Carbon::now()->subMinutes($this->minutes)->getTimestamp()) { + return $this->files->get($path); + } } return '';
true
Other
laravel
framework
0831312aec47d904a65039e07574f41ab7492418.json
Fix session expiration on several drivers.
src/Illuminate/Session/SessionManager.php
@@ -59,7 +59,9 @@ protected function createNativeDriver() { $path = $this->app['config']['session.files']; - return $this->buildSession(new FileSessionHandler($this->app['files'], $path)); + $lifetime = $this->app['config']['session.lifetime']; + + return $this->buildSession(new FileSessionHandler($this->app['files'], $path, $lifetime)); } /** @@ -73,7 +75,9 @@ protected function createDatabaseDriver() $table = $this->app['config']['session.table']; - return $this->buildSession(new DatabaseSessionHandler($connection, $table)); + $lifetime = $this->app['config']['session.lifetime']; + + return $this->buildSession(new DatabaseSessionHandler($connection, $table, $lifetime)); } /**
true
Other
laravel
framework
453f504c449af9aa77b8b5a13fb065a7d7f06952.json
fix expiration on cookie sessions
src/Illuminate/Session/CookieSessionHandler.php
@@ -2,6 +2,7 @@ namespace Illuminate\Session; +use Carbon\Carbon; use SessionHandlerInterface; use Symfony\Component\HttpFoundation\Request; use Illuminate\Contracts\Cookie\QueueingFactory as CookieJar; @@ -56,15 +57,26 @@ public function close() */ public function read($sessionId) { - return $this->request->cookies->get($sessionId) ?: ''; + $value = $this->request->cookies->get($sessionId) ?: ''; + + if (! is_null($decoded = json_decode($value, true)) && is_array($decoded)) { + if (isset($decoded['expires']) && time() <= $decoded['expires']) { + return $decoded['data']; + } + } + + return $value; } /** * {@inheritdoc} */ public function write($sessionId, $data) { - $this->cookie->queue($sessionId, $data, $this->minutes); + $this->cookie->queue($sessionId, json_encode([ + 'data' => $data, + 'expires' => Carbon::now()->addMinutes($this->minutes)->getTimestamp() + ]), $this->minutes); } /**
false
Other
laravel
framework
0b8f550419baa95c32f5d0f3005023f1cd58a47c.json
add storage:link command.
src/Illuminate/Foundation/Console/StorageLinkCommand.php
@@ -0,0 +1,38 @@ +<?php + +namespace Illuminate\Foundation\Console; + +use Illuminate\Console\Command; + +class StorageLinkCommand extends Command +{ + /** + * The console command signature. + * + * @var string + */ + protected $signature = 'storage:link'; + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Create a symbolic link from "public/storage" to "storage/app/public"'; + + /** + * Execute the console command. + * + * @return void + */ + public function fire() + { + if (file_exists(public_path('storage'))) { + return $this->error('The "public/storage" directory already exists.'); + } + + symlink(storage_path('app/public'), public_path('storage')); + + $this->info('The [public/storage] directory has been successfully linked.'); + } +}
true
Other
laravel
framework
0b8f550419baa95c32f5d0f3005023f1cd58a47c.json
add storage:link command.
src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php
@@ -24,6 +24,7 @@ use Illuminate\Foundation\Console\PolicyMakeCommand; use Illuminate\Foundation\Console\RouteCacheCommand; use Illuminate\Foundation\Console\RouteClearCommand; +use Illuminate\Foundation\Console\StorageLinkCommand; use Illuminate\Routing\Console\ControllerMakeCommand; use Illuminate\Routing\Console\MiddlewareMakeCommand; use Illuminate\Foundation\Console\ConfigCacheCommand; @@ -65,6 +66,7 @@ class ArtisanServiceProvider extends ServiceProvider 'RouteCache' => 'command.route.cache', 'RouteClear' => 'command.route.clear', 'RouteList' => 'command.route.list', + 'StorageLink' => 'command.storage.link', 'Tinker' => 'command.tinker', 'Up' => 'command.up', 'ViewClear' => 'command.view.clear', @@ -428,6 +430,18 @@ protected function registerSessionTableCommand() }); } + /** + * Register the command. + * + * @return void + */ + protected function registerStorageLinkCommand() + { + $this->app->singleton('command.storage.link', function () { + return new StorageLinkCommand; + }); + } + /** * Register the command. *
true
Other
laravel
framework
bc656ad451d99a83432d02b165beb70da51e68c5.json
Add logo support to notification email. Signed-off-by: Taylor Otwell <taylorotwell@gmail.com>
src/Illuminate/Notifications/RoutesNotifications.php
@@ -21,7 +21,9 @@ public function notify($instance) ); foreach ($notifications as $notification) { - $manager->send($notification->application(config('app.name'))); + $manager->send($notification->application( + config('app.name'), config('app.logo') + )); } }
true
Other
laravel
framework
bc656ad451d99a83432d02b165beb70da51e68c5.json
Add logo support to notification email. Signed-off-by: Taylor Otwell <taylorotwell@gmail.com>
src/Illuminate/Notifications/TransportManager.php
@@ -17,7 +17,8 @@ class TransportManager extends Manager public function to($notifiables) { return (new Transports\Notification($this, $notifiables))->application( - $this->app['config']['app.name'] + $this->app['config']['app.name'], + $this->app['config']['app.logo'] ); }
true