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
4d09a3c46aac7e765710d51dfea3e800ea978a13.json
Allow easy extension of user providers.
src/Illuminate/Auth/AuthManager.php
@@ -207,7 +207,7 @@ public function viaRequest($name, callable $callback) /** * Register a custom driver creator Closure. * - * @param string $driver + * @param string $driver * @param \Closure $callback * @return $this */ @@ -218,11 +218,25 @@ public function extend($driver, Closure $callback) return $this; } + /** + * Register a custom provider creator Closure. + * + * @param string $name + * @param \Closure $callback + * @return $this + */ + public function provider($name, Closure $callback) + { + $this->customProviderCreators[$name] = $callback; + + return $this; + } + /** * Dynamically call the default driver instance. * * @param string $method - * @param array $parameters + * @param array $parameters * @return mixed */ public function __call($method, $parameters)
true
Other
laravel
framework
4d09a3c46aac7e765710d51dfea3e800ea978a13.json
Allow easy extension of user providers.
src/Illuminate/Auth/CreatesUserProviders.php
@@ -6,6 +6,13 @@ trait CreatesUserProviders { + /** + * The registered custom provider creators. + * + * @var array + */ + protected $customProviderCreators = []; + /** * Create the user provider implementation for the driver. * @@ -18,6 +25,12 @@ protected function createUserProvider($provider) { $config = $this->app['config']['auth.sources.'.$provider]; + if (isset($this->customProviderCreators[$provider])) { + return call_user_func( + $this->customProviderCreators[$provider], $this->app, $config + ); + } + switch ($config['driver']) { case 'database': return $this->createDatabaseProvider($config);
true
Other
laravel
framework
e271b486d86f4b7c428371a800e64050692fd606.json
Remove some customization.
src/Illuminate/Auth/AuthManager.php
@@ -137,8 +137,6 @@ public function createTokenDriver($name, $config) $guard = new TokenGuard( $this->createUserProvider($config['source']), $this->app['request'], - Arr::get($config, 'input', 'api_token'), - Arr::get($config, 'token', 'api_token') ); $this->app->refresh('request', $guard, 'setRequest');
true
Other
laravel
framework
e271b486d86f4b7c428371a800e64050692fd606.json
Remove some customization.
src/Illuminate/Auth/TokenGuard.php
@@ -36,19 +36,15 @@ class TokenGuard implements Guard * * @param \Illuminate\Contracts\Auth\UserProvider $provider * @param \Symfony\Component\HttpFoundation\Request $request - * @param string $inputKey - * @param string $storageKey * @return void */ public function __construct(UserProvider $provider, - Request $request, - $inputKey = 'api_token', - $storageKey = 'api_token') + Request $request) { $this->request = $request; $this->provider = $provider; - $this->inputKey = $inputKey; - $this->storageKey = $storageKey; + $this->inputKey = 'api_token'; + $this->storageKey = 'api_token'; } /**
true
Other
laravel
framework
ec4f6ae66e7792e3703d82b47eefb96fced0890e.json
Write tests for token guard.
tests/Auth/AuthTokenGuardTest.php
@@ -0,0 +1,92 @@ +<?php + +use Illuminate\Http\Request; +use Illuminate\Auth\TokenGuard; +use Illuminate\Contracts\Auth\UserProvider; + +class AuthTokenGuardTest extends PHPUnit_Framework_TestCase +{ + public function tearDown() + { + Mockery::close(); + } + + public function testUserCanBeRetrievedByQueryStringVariable() + { + $provider = Mockery::mock(UserProvider::class); + $user = new AuthTokenGuardTestUser; + $user->id = 1; + $provider->shouldReceive('retrieveByCredentials')->once()->with(['api_token' => 'foo'])->andReturn($user); + $request = Request::create('/', 'GET', ['api_token' => 'foo']); + + $guard = new TokenGuard($provider, $request); + + $user = $guard->user(); + + $this->assertEquals(1, $user->id); + $this->assertTrue($guard->check()); + $this->assertFalse($guard->guest()); + $this->assertEquals(1, $guard->id()); + } + + public function testUserCanBeRetrievedByAuthHeaders() + { + $provider = Mockery::mock(UserProvider::class); + $provider->shouldReceive('retrieveByCredentials')->once()->with(['api_token' => 'foo'])->andReturn((object) ['id' => 1]); + $request = Request::create('/', 'GET', [], [], [], ['PHP_AUTH_USER' => 'foo', 'PHP_AUTH_PW' => 'foo']); + + $guard = new TokenGuard($provider, $request); + + $user = $guard->user(); + + $this->assertEquals(1, $user->id); + } + + public function testUserCanBeRetrievedByBearerToken() + { + $provider = Mockery::mock(UserProvider::class); + $provider->shouldReceive('retrieveByCredentials')->once()->with(['api_token' => 'foo'])->andReturn((object) ['id' => 1]); + $request = Request::create('/', 'GET', [], [], [], ['HTTP_AUTHORIZATION' => 'Bearer foo']); + + $guard = new TokenGuard($provider, $request); + + $user = $guard->user(); + + $this->assertEquals(1, $user->id); + } + + public function testValidateCanDetermineIfCredentialsAreValid() + { + $provider = Mockery::mock(UserProvider::class); + $user = new AuthTokenGuardTestUser; + $user->id = 1; + $provider->shouldReceive('retrieveByCredentials')->once()->with(['api_token' => 'foo'])->andReturn($user); + $request = Request::create('/', 'GET', ['api_token' => 'foo']); + + $guard = new TokenGuard($provider, $request); + + $this->assertTrue($guard->validate(['api_token' => 'foo'])); + } + + public function testValidateCanDetermineIfCredentialsAreInvalid() + { + $provider = Mockery::mock(UserProvider::class); + $user = new AuthTokenGuardTestUser; + $user->id = 1; + $provider->shouldReceive('retrieveByCredentials')->once()->with(['api_token' => 'foo'])->andReturn(null); + $request = Request::create('/', 'GET', ['api_token' => 'foo']); + + $guard = new TokenGuard($provider, $request); + + $this->assertFalse($guard->validate(['api_token' => 'foo'])); + } +} + +class AuthTokenGuardTestUser +{ + public $id; + public function getAuthIdentifier() + { + return $this->id; + } +}
false
Other
laravel
framework
9f5050bab13d40f62a2c1db9c98c659bf1bd25c7.json
Fix bug in validate
src/Illuminate/Auth/TokenGuard.php
@@ -156,12 +156,10 @@ public function id() */ public function validate(array $credentials = []) { - if (! is_null($token)) { - $credentials = [$this->storageKey => $credentials[$this->inputKey]]; + $credentials = [$this->storageKey => $credentials[$this->inputKey]]; - if ($this->provider->retrieveByCredentials($credentials)) { - return true; - } + if ($this->provider->retrieveByCredentials($credentials)) { + return true; } return false;
false
Other
laravel
framework
939cc94812c1f2e6be155410681de1ddbd7d6b82.json
Allow various methods of passing token.
src/Illuminate/Auth/TokenGuard.php
@@ -2,6 +2,7 @@ namespace Illuminate\Auth; +use Illuminate\Support\Str; use Illuminate\Http\Request; use Illuminate\Contracts\Auth\Guard; use Illuminate\Contracts\Auth\UserProvider; @@ -100,9 +101,9 @@ public function user() $user = null; - $token = $this->request->input($this->inputKey); + $token = $this->getTokenForRequest(); - if (! is_null($token)) { + if (! empty($token)) { $user = $this->provider->retrieveByCredentials( [$this->storageKey => $token] ); @@ -111,6 +112,30 @@ public function user() return $this->user = $user; } + /** + * Get the token for the current request. + * + * @return string + */ + protected function getTokenForRequest() + { + $token = $this->request->input($this->inputKey); + + if (empty($token)) { + $token = $this->request->getPassword(); + } + + if (empty($token)) { + $header = $this->request->header('Authorization'); + + if (Str::startsWith($header, 'Bearer ')) { + $token = Str::substr($header, 7); + } + } + + return $token; + } + /** * Get the ID for the currently authenticated user. *
false
Other
laravel
framework
b44d34056e932898a295e7e58b8c48ce6057324d.json
fix timeout and sleep
src/Illuminate/Queue/Console/ListenCommand.php
@@ -2,6 +2,7 @@ namespace Illuminate\Queue\Console; +use InvalidArgumentException; use Illuminate\Queue\Listener; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; @@ -63,6 +64,12 @@ public function fire() $timeout = $this->input->getOption('timeout'); + if ($timeout <= $this->input->getOption('sleep')) { + throw new InvalidArgumentException( + "Job timeout must be greater than 'sleep' option value." + ); + } + // We need to get the right queue for the connection which is set in the queue // configuration file for the application. We will pull it based on the set // connection being run for the queue operation currently being executed.
false
Other
laravel
framework
7b6600ba4fc97fd1eb6549913961cd0020d02e56.json
Fix cache events not being fired when using tags.
src/Illuminate/Cache/RedisTaggedCache.php
@@ -13,9 +13,9 @@ class RedisTaggedCache extends TaggedCache */ public function forever($key, $value) { - $this->pushForeverKeys($namespace = $this->tags->getNamespace(), $key); + $this->pushForeverKeys($this->tags->getNamespace(), $key); - $this->store->forever(sha1($namespace).':'.$key, $value); + parent::forever($key, $value); } /**
true
Other
laravel
framework
7b6600ba4fc97fd1eb6549913961cd0020d02e56.json
Fix cache events not being fired when using tags.
src/Illuminate/Cache/Repository.php
@@ -6,6 +6,7 @@ use DateTime; use ArrayAccess; use Carbon\Carbon; +use BadMethodCallException; use Illuminate\Contracts\Cache\Store; use Illuminate\Support\Traits\Macroable; use Illuminate\Contracts\Events\Dispatcher; @@ -255,6 +256,43 @@ public function forget($key) return $success; } + /** + * Begin executing a new tags operation if the store supports it. + * + * @param string $name + * @return \Illuminate\Cache\TaggedCache + * + * @deprecated since version 5.1. Use tags instead. + */ + public function section($name) + { + return $this->tags($name); + } + + /** + * Begin executing a new tags operation if the store supports it. + * + * @param array|mixed $names + * @return \Illuminate\Cache\TaggedCache + * + * @throws \BadMethodCallException + */ + public function tags($names) + { + if (method_exists($this->store, 'tags')) { + $taggedCache = $this->store->tags($names); + + if (! is_null($this->events)) { + $taggedCache->setEventDispatcher($this->events); + } + $taggedCache->setDefaultCacheTime($this->default); + + return $taggedCache; + } + + throw BadMethodCallException('The current cache store does not support tagging.'); + } + /** * Get the default cache time. *
true
Other
laravel
framework
7b6600ba4fc97fd1eb6549913961cd0020d02e56.json
Fix cache events not being fired when using tags.
src/Illuminate/Cache/TagSet.php
@@ -97,4 +97,14 @@ public function tagKey($name) { return 'tag:'.$name.':key'; } + + /** + * Get all of the names in the set. + * + * @return array + */ + public function getNames() + { + return $this->names; + } }
true
Other
laravel
framework
7b6600ba4fc97fd1eb6549913961cd0020d02e56.json
Fix cache events not being fired when using tags.
src/Illuminate/Cache/TaggedCache.php
@@ -2,20 +2,10 @@ namespace Illuminate\Cache; -use Closure; -use DateTime; -use Carbon\Carbon; use Illuminate\Contracts\Cache\Store; -class TaggedCache implements Store +class TaggedCache extends Repository { - /** - * The cache store implementation. - * - * @var \Illuminate\Contracts\Cache\Store - */ - protected $store; - /** * The tag set instance. * @@ -32,69 +22,50 @@ class TaggedCache implements Store */ public function __construct(Store $store, TagSet $tags) { + parent::__construct($store); + $this->tags = $tags; - $this->store = $store; } /** - * Determine if an item exists in the cache. - * - * @param string $key - * @return bool + * {@inheritdoc} */ - public function has($key) + protected function fireCacheEvent($event, $payload) { - return ! is_null($this->get($key)); + if (preg_match('/^'.sha1($this->tags->getNamespace()).':(.*)$/', $payload[0], $matches) === 1) { + $payload[0] = $matches[1]; + } + $payload[] = $this->tags->getNames(); + + parent::fireCacheEvent($event, $payload); } /** - * Retrieve an item from the cache by key. - * - * @param string $key - * @param mixed $default - * @return mixed + * {@inheritdoc} */ public function get($key, $default = null) { - $value = $this->store->get($this->taggedItemKey($key)); - - return ! is_null($value) ? $value : value($default); + return parent::get($this->taggedItemKey($key), $default); } /** - * Store an item in the cache for a given number of minutes. - * - * @param string $key - * @param mixed $value - * @param \DateTime|int $minutes - * @return void + * {@inheritdoc} */ public function put($key, $value, $minutes) { - $minutes = $this->getMinutes($minutes); - - if (! is_null($minutes)) { - $this->store->put($this->taggedItemKey($key), $value, $minutes); - } + parent::put($this->taggedItemKey($key), $value, $minutes); } /** - * Store an item in the cache if the key does not exist. - * - * @param string $key - * @param mixed $value - * @param \DateTime|int $minutes - * @return bool + * {@inheritdoc} */ public function add($key, $value, $minutes) { - if (is_null($this->get($key))) { - $this->put($key, $value, $minutes); - - return true; + if (method_exists($this->store, 'add')) { + $key = $this->taggedItemKey($key); } - return false; + return parent::add($key, $value, $minutes); } /** @@ -122,26 +93,19 @@ public function decrement($key, $value = 1) } /** - * Store an item in the cache indefinitely. - * - * @param string $key - * @param mixed $value - * @return void + * {@inheritdoc} */ public function forever($key, $value) { - $this->store->forever($this->taggedItemKey($key), $value); + parent::forever($this->taggedItemKey($key), $value); } /** - * Remove an item from the cache. - * - * @param string $key - * @return bool + * {@inheritdoc} */ public function forget($key) { - return $this->store->forget($this->taggedItemKey($key)); + return parent::forget($this->taggedItemKey($key)); } /** @@ -154,61 +118,6 @@ public function flush() $this->tags->reset(); } - /** - * Get an item from the cache, or store the default value. - * - * @param string $key - * @param \DateTime|int $minutes - * @param \Closure $callback - * @return mixed - */ - public function remember($key, $minutes, Closure $callback) - { - // If the item exists in the cache we will just return this immediately - // otherwise we will execute the given Closure and cache the result - // of that execution for the given number of minutes in storage. - if (! is_null($value = $this->get($key))) { - return $value; - } - - $this->put($key, $value = $callback(), $minutes); - - return $value; - } - - /** - * Get an item from the cache, or store the default value forever. - * - * @param string $key - * @param \Closure $callback - * @return mixed - */ - public function sear($key, Closure $callback) - { - return $this->rememberForever($key, $callback); - } - - /** - * Get an item from the cache, or store the default value forever. - * - * @param string $key - * @param \Closure $callback - * @return mixed - */ - public function rememberForever($key, Closure $callback) - { - // If the item exists in the cache we will just return this immediately - // otherwise we will execute the given Closure and cache the result - // of that execution for an indefinite amount of time. It's easy. - if (! is_null($value = $this->get($key))) { - return $value; - } - - $this->forever($key, $value = $callback()); - - return $value; - } - /** * Get a fully qualified key for a tagged item. * @@ -219,31 +128,4 @@ public function taggedItemKey($key) { return sha1($this->tags->getNamespace()).':'.$key; } - - /** - * Get the cache key prefix. - * - * @return string - */ - public function getPrefix() - { - return $this->store->getPrefix(); - } - - /** - * Calculate the number of minutes with the given duration. - * - * @param \DateTime|int $duration - * @return int|null - */ - protected function getMinutes($duration) - { - if ($duration instanceof DateTime) { - $fromNow = Carbon::now()->diffInMinutes(Carbon::instance($duration), false); - - return $fromNow > 0 ? $fromNow : null; - } - - return is_string($duration) ? (int) $duration : $duration; - } }
true
Other
laravel
framework
7b6600ba4fc97fd1eb6549913961cd0020d02e56.json
Fix cache events not being fired when using tags.
tests/Cache/CacheEventsTest.php
@@ -0,0 +1,163 @@ +<?php + +use Mockery as m; + +class CacheEventTest extends PHPUnit_Framework_TestCase +{ + public function tearDown() + { + m::close(); + } + + public function testHasTriggersEvents() + { + $dispatcher = $this->getDispatcher(); + $repository = $this->getRepository($dispatcher); + + $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo']); + $this->assertFalse($repository->has('foo')); + + $dispatcher->shouldReceive('fire')->once()->with('cache.hit', ['baz', 'qux']); + $this->assertTrue($repository->has('baz')); + + $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo', ['taylor']]); + $dispatcher->shouldReceive('fire')->never(); + $this->assertFalse($repository->tags('taylor')->has('foo')); + + $dispatcher->shouldReceive('fire')->once()->with('cache.hit', ['baz', 'qux', ['taylor']]); + $this->assertTrue($repository->tags('taylor')->has('baz')); + } + + public function testGetTriggersEvents() + { + $dispatcher = $this->getDispatcher(); + $repository = $this->getRepository($dispatcher); + + $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo']); + $this->assertNull($repository->get('foo')); + + $dispatcher->shouldReceive('fire')->once()->with('cache.hit', ['baz', 'qux']); + $this->assertEquals('qux', $repository->get('baz')); + + $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo', ['taylor']]); + $this->assertNull($repository->tags('taylor')->get('foo')); + + $dispatcher->shouldReceive('fire')->once()->with('cache.hit', ['baz', 'qux', ['taylor']]); + $this->assertEquals('qux', $repository->tags('taylor')->get('baz')); + } + + public function testPullTriggersEvents() + { + $dispatcher = $this->getDispatcher(); + $repository = $this->getRepository($dispatcher); + + $dispatcher->shouldReceive('fire')->once()->with('cache.hit', ['baz', 'qux']); + $dispatcher->shouldReceive('fire')->once()->with('cache.delete', ['baz']); + $this->assertEquals('qux', $repository->pull('baz')); + + $dispatcher->shouldReceive('fire')->once()->with('cache.hit', ['baz', 'qux', ['taylor']]); + $dispatcher->shouldReceive('fire')->once()->with('cache.delete', ['baz', ['taylor']]); + $this->assertEquals('qux', $repository->tags('taylor')->pull('baz')); + } + + public function testPutTriggersEvents() + { + $dispatcher = $this->getDispatcher(); + $repository = $this->getRepository($dispatcher); + + $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 99]); + $repository->put('foo', 'bar', 99); + + $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 99, ['taylor']]); + $repository->tags('taylor')->put('foo', 'bar', 99); + } + + public function testAddTriggersEvents() + { + $dispatcher = $this->getDispatcher(); + $repository = $this->getRepository($dispatcher); + + $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo']); + $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 99]); + $this->assertTrue($repository->add('foo', 'bar', 99)); + + $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo', ['taylor']]); + $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 99, ['taylor']]); + $this->assertTrue($repository->tags('taylor')->add('foo', 'bar', 99)); + } + + public function testForeverTriggersEvents() + { + $dispatcher = $this->getDispatcher(); + $repository = $this->getRepository($dispatcher); + + $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 0]); + $repository->forever('foo', 'bar'); + + $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 0, ['taylor']]); + $repository->tags('taylor')->forever('foo', 'bar'); + } + + public function testRememberTriggersEvents() + { + $dispatcher = $this->getDispatcher(); + $repository = $this->getRepository($dispatcher); + + $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo']); + $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 99]); + $this->assertEquals('bar', $repository->remember('foo', 99, function () { + return 'bar'; + })); + + $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo', ['taylor']]); + $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 99, ['taylor']]); + $this->assertEquals('bar', $repository->tags('taylor')->remember('foo', 99, function () { + return 'bar'; + })); + } + + public function testRememberForeverTriggersEvents() + { + $dispatcher = $this->getDispatcher(); + $repository = $this->getRepository($dispatcher); + + $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo']); + $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 0]); + $this->assertEquals('bar', $repository->rememberForever('foo', function () { + return 'bar'; + })); + + $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo', ['taylor']]); + $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 0, ['taylor']]); + $this->assertEquals('bar', $repository->tags('taylor')->rememberForever('foo', function () { + return 'bar'; + })); + } + + public function testForgetTriggersEvents() + { + $dispatcher = $this->getDispatcher(); + $repository = $this->getRepository($dispatcher); + + $dispatcher->shouldReceive('fire')->once()->with('cache.delete', ['baz']); + $this->assertTrue($repository->forget('baz')); + + // $dispatcher->shouldReceive('fire')->once()->with('cache.delete', ['baz', ['taylor']]); + // $this->assertTrue($repository->tags('taylor')->forget('baz')); + } + + protected function getDispatcher() + { + return m::mock('Illuminate\Events\Dispatcher'); + } + + protected function getRepository($dispatcher) + { + $repository = new \Illuminate\Cache\Repository(new \Illuminate\Cache\ArrayStore()); + $repository->put('baz', 'qux', 99); + $repository->tags('taylor')->put('baz', 'qux', 99); + $repository->setEventDispatcher($dispatcher); + + return $repository; + } +}
true
Other
laravel
framework
7b6600ba4fc97fd1eb6549913961cd0020d02e56.json
Fix cache events not being fired when using tags.
tests/Cache/CacheTaggedCacheTest.php
@@ -70,6 +70,7 @@ public function testRedisCacheTagsPushForeverKeysCorrectly() $store = m::mock('Illuminate\Contracts\Cache\Store'); $tagSet = m::mock('Illuminate\Cache\TagSet', [$store, ['foo', 'bar']]); $tagSet->shouldReceive('getNamespace')->andReturn('foo|bar'); + $tagSet->shouldReceive('getNames')->andReturn(['foo', 'bar']); $redis = new Illuminate\Cache\RedisTaggedCache($store, $tagSet); $store->shouldReceive('getPrefix')->andReturn('prefix:'); $store->shouldReceive('connection')->andReturn($conn = m::mock('StdClass'));
true
Other
laravel
framework
6b5571b08d7696b02844f8b211fa2cd52c46c585.json
Escape path in sendOutputTo()
src/Illuminate/Console/Scheduling/Event.php
@@ -9,6 +9,7 @@ use GuzzleHttp\Client as HttpClient; use Illuminate\Contracts\Mail\Mailer; use Symfony\Component\Process\Process; +use Symfony\Component\Process\ProcessUtils; use Illuminate\Contracts\Container\Container; use Illuminate\Contracts\Foundation\Application; @@ -652,7 +653,7 @@ public function skip(Closure $callback) */ public function sendOutputTo($location, $append = false) { - $this->output = $location; + $this->output = ProcessUtils::escapeArgument($location); $this->shouldAppendOutput = $append;
true
Other
laravel
framework
6b5571b08d7696b02844f8b211fa2cd52c46c585.json
Escape path in sendOutputTo()
tests/Console/Scheduling/EventTest.php
@@ -12,11 +12,24 @@ public function testBuildCommand() $this->assertSame("php -i > {$defaultOutput} 2>&1 &", $event->buildCommand()); } + public function testBuildCommandSendOutputTo() + { + $event = new Event('php -i'); + + $event->sendOutputTo('/dev/null'); + $this->assertSame("php -i > '/dev/null' 2>&1 &", $event->buildCommand()); + + $event = new Event('php -i'); + + $event->sendOutputTo('/my folder/foo.log'); + $this->assertSame("php -i > '/my folder/foo.log' 2>&1 &", $event->buildCommand()); + } + public function testBuildCommandAppendOutput() { $event = new Event('php -i'); $event->appendOutputTo('/dev/null'); - $this->assertSame('php -i >> /dev/null 2>&1 &', $event->buildCommand()); + $this->assertSame("php -i >> '/dev/null' 2>&1 &", $event->buildCommand()); } }
true
Other
laravel
framework
38d5d28b1afe33f22fde12c4c463b703f8461285.json
Remove 5.5 bug workaround
src/Illuminate/Database/Eloquent/Model.php
@@ -459,13 +459,8 @@ public function fill(array $attributes) */ public function forceFill(array $attributes) { - // Since some versions of PHP have a bug that prevents it from properly - // binding the late static context in a closure, we will first store - // the model in a variable, which we will then use in the closure. - $model = $this; - - return static::unguarded(function () use ($model, $attributes) { - return $model->fill($attributes); + return static::unguarded(function () use ($attributes) { + return $this->fill($attributes); }); } @@ -579,13 +574,8 @@ public static function create(array $attributes = []) */ public static function forceCreate(array $attributes) { - // Since some versions of PHP have a bug that prevents it from properly - // binding the late static context in a closure, we will first store - // the model in a variable, which we will then use in the closure. - $model = new static; - - return static::unguarded(function () use ($model, $attributes) { - return $model->create($attributes); + return static::unguarded(function () use ($attributes) { + return (new static)->create($attributes); }); }
false
Other
laravel
framework
32654386eb4a6b000931b93582139e762a9fa7e4.json
remove file that doesn't exist
src/Illuminate/Foundation/Console/Optimize/config.php
@@ -84,7 +84,6 @@ $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php', $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Bus/DispatchesJobs.php', $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Providers/FoundationServiceProvider.php', - $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Providers/FormRequestServiceProvider.php', $basePath.'/vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php', $basePath.'/vendor/laravel/framework/src/Illuminate/Pagination/PaginationServiceProvider.php', $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Support/Providers/AuthServiceProvider.php',
false
Other
laravel
framework
bed1159e201d5126e7246497e9265e37d2270932.json
Use isset() to improve consistency
src/Illuminate/Auth/SessionGuard.php
@@ -412,7 +412,7 @@ protected function hasValidCredentials($user, $credentials) */ protected function fireAttemptEvent(array $credentials, $remember, $login) { - if ($this->events) { + if (isset($this->events)) { $this->events->fire(new Events\Attempting( $credentials, $remember, $login )); @@ -427,7 +427,7 @@ protected function fireAttemptEvent(array $credentials, $remember, $login) */ public function attempting($callback) { - if ($this->events) { + if (isset($this->events)) { $this->events->listen(Events\Attempting::class, $callback); } }
false
Other
laravel
framework
7310ce44efc018a157ddbaf3aa2b8b768b617cab.json
Return sqlsrv in place of dblib driver
src/Illuminate/Database/DatabaseManager.php
@@ -270,7 +270,7 @@ public function setDefaultConnection($name) */ public function supportedDrivers() { - return ['mysql', 'pgsql', 'sqlite', 'dblib', 'sqlsrv']; + return ['mysql', 'pgsql', 'sqlite', 'sqlsrv']; } /** @@ -280,7 +280,7 @@ public function supportedDrivers() */ public function availableDrivers() { - return array_intersect($this->supportedDrivers(), PDO::getAvailableDrivers()); + return array_intersect($this->supportedDrivers(), str_replace('dblib', 'sqlsrv', PDO::getAvailableDrivers())); } /**
false
Other
laravel
framework
3249c620a19cb97f6f2ff55b9712ac4d3326996a.json
Use routable key name.
src/Illuminate/Routing/Router.php
@@ -801,10 +801,14 @@ protected function substituteImplicitBindings($route) if (array_key_exists($parameter->name, $parameters) && ! $route->getParameter($parameter->name) instanceof Model) { - $method = $parameter->isDefaultValueAvailable() ? 'find' : 'findOrFail'; + $method = $parameter->isDefaultValueAvailable() ? 'first' : 'firstOrFail'; + + $model = $class->newInstance(); $route->setParameter( - $parameter->name, $class->newInstance()->{$method}($parameters[$parameter->name]) + $parameter->name, $model->where( + $model->getRouteKeyName(), $parameters[$parameter->name] + )->{$method}() ); } }
false
Other
laravel
framework
12a9358b0aedb323ee4fd0bba4a30af6c6342e00.json
Fix undefined index
src/Illuminate/Database/Eloquent/Model.php
@@ -379,7 +379,7 @@ public static function hasGlobalScope($scope) */ public static function getGlobalScope($scope) { - $modelScopes = static::$globalScopes[get_called_class()]; + $modelScopes = Arr::get(static::$globalScopes, get_called_class(), []); if (is_string($scope)) { return isset($modelScopes[$scope]) ? $modelScopes[$scope] : null;
false
Other
laravel
framework
c711448531244bb2b6d619469d145e12134a96a4.json
Extend pipeline at routing layer.
src/Illuminate/Pipeline/Pipeline.php
@@ -3,12 +3,7 @@ namespace Illuminate\Pipeline; use Closure; -use Exception; -use Throwable; -use Illuminate\Http\Request; use Illuminate\Contracts\Container\Container; -use Illuminate\Contracts\Debug\ExceptionHandler; -use Symfony\Component\Debug\Exception\FatalThrowableError; use Illuminate\Contracts\Pipeline\Pipeline as PipelineContract; class Pipeline implements PipelineContract @@ -41,13 +36,6 @@ class Pipeline implements PipelineContract */ protected $method = 'handle'; - /** - * Indicates if exceptions should be caught and handled. - * - * @var bool - */ - protected $handleExceptions = false; - /** * Create a new class instance. * @@ -127,19 +115,13 @@ protected function getSlice() // If the pipe is an instance of a Closure, we will just call it directly but // otherwise we'll resolve the pipes out of the container and call it with // the appropriate method and arguments, returning the results back out. - try { - if ($pipe instanceof Closure) { - return call_user_func($pipe, $passable, $stack); - } else { - list($name, $parameters) = $this->parsePipeString($pipe); - - return call_user_func_array([$this->container->make($name), $this->method], - array_merge([$passable, $stack], $parameters)); - } - } catch (Exception $e) { - return $this->handleException($passable, $e); - } catch (Throwable $e) { - return $this->handleException($passable, new FatalThrowableError($e)); + if ($pipe instanceof Closure) { + return call_user_func($pipe, $passable, $stack); + } else { + list($name, $parameters) = $this->parsePipeString($pipe); + + return call_user_func_array([$this->container->make($name), $this->method], + array_merge([$passable, $stack], $parameters)); } }; }; @@ -158,29 +140,6 @@ protected function getInitialSlice(Closure $destination) }; } - /** - * Handle the given exception if an exception handler is bound. - * - * Exception only handled when passable is HTTP request and handling is enabled. - * - * @param \Exception $e - * @return mixed - */ - protected function handleException($passable, Exception $e) - { - if (! $this->handleExceptions || - ! $this->container->bound(ExceptionHandler::class) || - ! $passable instanceof Request) { - throw $e; - } - - $handler = $this->container->make(ExceptionHandler::class); - - $handler->report($e); - - return $handler->render($passable, $e); - } - /** * Parse full pipe string to get name and parameters. * @@ -197,16 +156,4 @@ protected function parsePipeString($pipe) return [$name, $parameters]; } - - /** - * Indicate that exceptions should be handled. - * - * @return $this - */ - public function handleExceptions() - { - $this->handleExceptions = true; - - return $this; - } }
true
Other
laravel
framework
c711448531244bb2b6d619469d145e12134a96a4.json
Extend pipeline at routing layer.
src/Illuminate/Pipeline/composer.json
@@ -28,8 +28,5 @@ "dev-master": "5.2-dev" } }, - "suggest": { - "symfony/debug": "Required to handle Throwables during exception handling (2.8.*|3.0.*).", - }, "minimum-stability": "dev" }
true
Other
laravel
framework
c711448531244bb2b6d619469d145e12134a96a4.json
Extend pipeline at routing layer.
src/Illuminate/Routing/ControllerDispatcher.php
@@ -3,7 +3,6 @@ namespace Illuminate\Routing; use Illuminate\Http\Request; -use Illuminate\Pipeline\Pipeline; use Illuminate\Support\Collection; use Illuminate\Container\Container; @@ -85,7 +84,6 @@ protected function callWithinStack($instance, $route, $request, $method) $this->container->make('middleware.disable') === true; return (new Pipeline($this->container)) - ->handleExceptions() ->send($request) ->through($shouldSkipMiddleware ? [] : $middleware) ->then(function ($request) use ($instance, $route, $method) {
true
Other
laravel
framework
c711448531244bb2b6d619469d145e12134a96a4.json
Extend pipeline at routing layer.
src/Illuminate/Routing/Pipeline.php
@@ -0,0 +1,52 @@ +<?php + +namespace Illuminate\Routing; + +use Exception; +use Illuminate\Http\Request; +use Illuminate\Contracts\Debug\ExceptionHandler; +use Illuminate\Pipeline\Pipeline as BasePipeline; +use Symfony\Component\Debug\Exception\FatalThrowableError; + +class Pipeline extends BasePipeline +{ + /** + * Get a Closure that represents a slice of the application onion. + * + * @return \Closure + */ + protected function getSlice() + { + return function ($stack, $pipe) { + return function ($passable) use ($stack, $pipe) { + try { + return call_user_func(parent::getSlice()($stack, $pipe), $passable); + } catch (Exception $e) { + return $this->handleException($passable, $e); + } catch (Throwable $e) { + return $this->handleException($passable, new FatalThrowableError($e)); + } + }; + }; + } + + /** + * Handle the given exception. + * + * @param \Exception $e + * @return mixed + */ + protected function handleException($passable, Exception $e) + { + if (! $this->container->bound(ExceptionHandler::class) || + ! $passable instanceof Request) { + throw $e; + } + + $handler = $this->container->make(ExceptionHandler::class); + + $handler->report($e); + + return $handler->render($passable, $e); + } +}
true
Other
laravel
framework
c711448531244bb2b6d619469d145e12134a96a4.json
Extend pipeline at routing layer.
src/Illuminate/Routing/Router.php
@@ -7,7 +7,6 @@ use Illuminate\Support\Str; use Illuminate\Http\Request; use Illuminate\Http\Response; -use Illuminate\Pipeline\Pipeline; use Illuminate\Support\Collection; use Illuminate\Container\Container; use Illuminate\Database\Eloquent\Model; @@ -696,7 +695,6 @@ protected function runRouteWithinStack(Route $route, Request $request) $middleware = $shouldSkipMiddleware ? [] : $this->gatherRouteMiddlewares($route); return (new Pipeline($this->container)) - ->handleExceptions() ->send($request) ->through($middleware) ->then(function ($request) use ($route) {
true
Other
laravel
framework
c711448531244bb2b6d619469d145e12134a96a4.json
Extend pipeline at routing layer.
src/Illuminate/Routing/composer.json
@@ -21,6 +21,7 @@ "illuminate/pipeline": "5.2.*", "illuminate/session": "5.2.*", "illuminate/support": "5.2.*", + "symfony/debug": "2.8.*|3.0.*", "symfony/http-foundation": "2.8.*|3.0.*", "symfony/http-kernel": "2.8.*|3.0.*", "symfony/routing": "2.8.*|3.0.*"
true
Other
laravel
framework
03980778c030736702454ae65aa6c60433b5d4cc.json
fix basic auth middleware.
src/Illuminate/Auth/Middleware/AuthenticateWithBasicAuth.php
@@ -3,24 +3,24 @@ namespace Illuminate\Auth\Middleware; use Closure; -use Illuminate\Contracts\Auth\Guard; +use Illuminate\Contracts\Auth\Factory as AuthFactory; class AuthenticateWithBasicAuth { /** - * The guard instance. + * The guard factory instance. * - * @var \Illuminate\Contracts\Auth\Guard + * @var \Illuminate\Contracts\Auth\Factory */ protected $auth; /** * Create a new middleware instance. * - * @param \Illuminate\Contracts\Auth\Guard $auth + * @param \Illuminate\Contracts\Auth\Factory $auth * @return void */ - public function __construct(Guard $auth) + public function __construct(AuthFactory $auth) { $this->auth = $auth; } @@ -30,10 +30,11 @@ public function __construct(Guard $auth) * * @param \Illuminate\Http\Request $request * @param \Closure $next + * @param string|null $guard * @return mixed */ - public function handle($request, Closure $next) + public function handle($request, Closure $next, $guard = null) { - return $this->auth->basic() ?: $next($request); + return $this->auth->guard($guard)->basic() ?: $next($request); } }
false
Other
laravel
framework
bcb8a98e22e270824cca8b7c7898acefd537aedb.json
Remove unused variable
src/Illuminate/Auth/SessionGuard.php
@@ -413,8 +413,6 @@ protected function hasValidCredentials($user, $credentials) protected function fireAttemptEvent(array $credentials, $remember, $login) { if ($this->events) { - $payload = [$credentials, $remember, $login]; - $this->events->fire(new Events\Attempting( $credentials, $remember, $login ));
false
Other
laravel
framework
6884c5442095175cc042f42ef2066204c0d35a96.json
Add missing docblock
src/Illuminate/Auth/CreatesUserProviders.php
@@ -11,6 +11,8 @@ trait CreatesUserProviders * * @param string $provider * @return \Illuminate\Contracts\Auth\UserProvider + * + * @throws \InvalidArgumentException */ protected function createUserProvider($provider) {
false
Other
laravel
framework
737ee84cc2f5a71ae359a1fc7c5ced6d741e901d.json
Add support for middleware groups.
src/Illuminate/Foundation/Http/Kernel.php
@@ -49,6 +49,13 @@ class Kernel implements KernelContract */ protected $middleware = []; + /** + * The application's route middleware groups. + * + * @var array + */ + protected $middlewareGroups = []; + /** * The application's route middleware. * @@ -68,6 +75,10 @@ public function __construct(Application $app, Router $router) $this->app = $app; $this->router = $router; + foreach ($this->middlewareGroups as $key => $middleware) { + $router->middlewareGroup($key, $middleware); + } + foreach ($this->routeMiddleware as $key => $middleware) { $router->middleware($key, $middleware); }
true
Other
laravel
framework
737ee84cc2f5a71ae359a1fc7c5ced6d741e901d.json
Add support for middleware groups.
src/Illuminate/Routing/ControllerDispatcher.php
@@ -4,6 +4,7 @@ use Illuminate\Http\Request; use Illuminate\Pipeline\Pipeline; +use Illuminate\Support\Collection; use Illuminate\Container\Container; class ControllerDispatcher @@ -102,15 +103,15 @@ protected function callWithinStack($instance, $route, $request, $method) */ protected function getMiddleware($instance, $method) { - $results = []; + $results = new Collection; foreach ($instance->getMiddleware() as $name => $options) { if (! $this->methodExcludedByOptions($method, $options)) { $results[] = $this->router->resolveMiddlewareClassName($name); } } - return $results; + return $results->flatten()->all(); } /**
true
Other
laravel
framework
737ee84cc2f5a71ae359a1fc7c5ced6d741e901d.json
Add support for middleware groups.
src/Illuminate/Routing/Router.php
@@ -65,6 +65,13 @@ class Router implements RegistrarContract */ protected $middleware = []; + /** + * All of the middleware groups. + * + * @var array + */ + protected $middlewareGroups = []; + /** * The registered route value binders. * @@ -708,24 +715,35 @@ protected function runRouteWithinStack(Route $route, Request $request) public function gatherRouteMiddlewares(Route $route) { return Collection::make($route->middleware())->map(function ($name) { + if (isset($this->middlewareGroups[$name])) { + return $this->middlewareGroups[$name]; + } + return Collection::make($this->resolveMiddlewareClassName($name)); }) ->collapse()->all(); } /** - * Resolve the middleware name to a class name preserving passed parameters. + * Resolve the middleware name to a class name(s) preserving passed parameters. * * @param string $name - * @return string + * @return string|array */ public function resolveMiddlewareClassName($name) { $map = $this->middleware; - list($name, $parameters) = array_pad(explode(':', $name, 2), 2, null); + if (isset($this->middlewareGroups[$name])) { + return $this->middlewareGroups[$name]; + } elseif (isset($map[$name]) && $map[$name] instanceof Closure) { + return $map[$name]; + } else { + list($name, $parameters) = array_pad(explode(':', $name, 2), 2, null); - return (isset($map[$name]) ? $map[$name] : $name).($parameters !== null ? ':'.$parameters : ''); + return (isset($map[$name]) ? $map[$name] : $name). + ($parameters !== null ? ':'.$parameters : ''); + } } /** @@ -834,6 +852,20 @@ public function middleware($name, $class) return $this; } + /** + * Register a group of middleware. + * + * @param string $name + * @param array $middleware + * @return $this + */ + public function middlewareGroup($name, array $middleware) + { + $this->middlewareGroups[$name] = $middleware; + + return $this; + } + /** * Register a model binder for a wildcard. *
true
Other
laravel
framework
737ee84cc2f5a71ae359a1fc7c5ced6d741e901d.json
Add support for middleware groups.
tests/Routing/RoutingRouteTest.php
@@ -92,6 +92,38 @@ public function testBasicDispatchingOfRoutes() $this->assertEquals('closure', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent()); } + public function testClosureMiddleware() + { + $router = $this->getRouter(); + $router->get('foo/bar', ['middleware' => 'foo', function () { return 'hello'; }]); + $router->middleware('foo', function ($request, $next) { + return 'caught'; + }); + $this->assertEquals('caught', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent()); + } + + public function testMiddlewareGroups() + { + unset($_SERVER['__middleware.group']); + $router = $this->getRouter(); + $router->get('foo/bar', ['middleware' => 'web', function () { return 'hello'; }]); + + $router->middlewareGroup('web', [ + function ($request, $next) { + $_SERVER['__middleware.group'] = true; + return $next($request); + }, + function ($request, $next) { + return 'caught'; + }, + ]); + + $this->assertEquals('caught', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent()); + $this->assertTrue($_SERVER['__middleware.group']); + + unset($_SERVER['__middleware.group']); + } + public function testFluentRouteNamingWithinAGroup() { $router = $this->getRouter(); @@ -709,11 +741,7 @@ public function testControllerRouting() $_SERVER['route.test.controller.middleware.parameters.one'], $_SERVER['route.test.controller.middleware.parameters.two'] ); - $router = new Router(new Illuminate\Events\Dispatcher, $container = new Illuminate\Container\Container); - - $container->singleton('illuminate.route.dispatcher', function ($container) use ($router) { - return new Illuminate\Routing\ControllerDispatcher($router, $container); - }); + $router = $this->getRouter(); $router->get('foo/bar', 'RouteTestControllerStub@index'); @@ -725,6 +753,27 @@ public function testControllerRouting() $this->assertFalse(isset($_SERVER['route.test.controller.except.middleware'])); } + public function testControllerMiddlewareGroups() + { + unset( + $_SERVER['route.test.controller.middleware'], + $_SERVER['route.test.controller.middleware.class'] + ); + + $router = $this->getRouter(); + + $router->middlewareGroup('web', [ + 'RouteTestControllerMiddleware', + 'RouteTestControllerMiddlewareTwo', + ]); + + $router->get('foo/bar', 'RouteTestControllerMiddlewareGroupStub@index'); + + $this->assertEquals('caught', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent()); + $this->assertTrue($_SERVER['route.test.controller.middleware']); + $this->assertEquals('Illuminate\Http\Response', $_SERVER['route.test.controller.middleware.class']); + } + public function testControllerInspection() { $router = $this->getRouter(); @@ -754,6 +803,19 @@ public function index() } } +class RouteTestControllerMiddlewareGroupStub extends Illuminate\Routing\Controller +{ + public function __construct() + { + $this->middleware('web'); + } + + public function index() + { + return 'Hello World'; + } +} + class RouteTestControllerMiddleware { public function handle($request, $next) @@ -766,6 +828,14 @@ public function handle($request, $next) } } +class RouteTestControllerMiddlewareTwo +{ + public function handle($request, $next) + { + return new \Illuminate\Http\Response('caught'); + } +} + class RouteTestControllerParameterizedMiddlewareOne { public function handle($request, $next, $parameter)
true
Other
laravel
framework
b28b995337c20aae42f0847bdca36e581f41eb5e.json
Remove class from compilation.
src/Illuminate/Foundation/Console/Optimize/config.php
@@ -76,7 +76,6 @@ $basePath.'/vendor/laravel/framework/src/Illuminate/Support/ServiceProvider.php', $basePath.'/vendor/laravel/framework/src/Illuminate/Support/AggregateServiceProvider.php', $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/RoutingServiceProvider.php', - $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/ControllerServiceProvider.php', $basePath.'/vendor/laravel/framework/src/Illuminate/Events/EventServiceProvider.php', $basePath.'/vendor/laravel/framework/src/Illuminate/Validation/ValidationServiceProvider.php', $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Validation/ValidatesRequests.php',
false
Other
laravel
framework
ecd54a9ad42423e66ff7e55bb1ad7095e5c63977.json
Use the variable.
src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php
@@ -38,8 +38,8 @@ public function bootstrap(Application $app) $this->loadConfigurationFiles($app, $config); } - $app->detectEnvironment(function () { - return config('app.env', 'production'); + $app->detectEnvironment(function () use ($config) { + return $config->get('app.env', 'production'); }); date_default_timezone_set($config['app.timezone']);
false
Other
laravel
framework
2a4acfb65f8fb69cec32cd9f4ccda4566524d5e2.json
Use sha1 rather than md5
src/Illuminate/Auth/SessionGuard.php
@@ -760,7 +760,7 @@ public function getLastAttempted() */ public function getName() { - return 'login_'.$this->name.'_'.md5(get_class($this)); + return 'login_'.$this->name.'_'.sha1(get_class($this)); } /** @@ -770,7 +770,7 @@ public function getName() */ public function getRecallerName() { - return 'remember_'.$this->name.'_'.md5(get_class($this)); + return 'remember_'.$this->name.'_'.sha1(get_class($this)); } /**
true
Other
laravel
framework
2a4acfb65f8fb69cec32cd9f4ccda4566524d5e2.json
Use sha1 rather than md5
src/Illuminate/Cache/FileStore.php
@@ -198,7 +198,7 @@ public function flush() */ protected function path($key) { - $parts = array_slice(str_split($hash = md5($key), 2), 0, 2); + $parts = array_slice(str_split($hash = sha1($key), 2), 0, 2); return $this->directory.'/'.implode('/', $parts).'/'.$hash; }
true
Other
laravel
framework
2a4acfb65f8fb69cec32cd9f4ccda4566524d5e2.json
Use sha1 rather than md5
src/Illuminate/Console/Scheduling/CallbackEvent.php
@@ -103,7 +103,7 @@ public function withoutOverlapping() */ protected function mutexPath() { - return storage_path('framework/schedule-'.md5($this->description)); + return storage_path('framework/schedule-'.sha1($this->description)); } /**
true
Other
laravel
framework
2a4acfb65f8fb69cec32cd9f4ccda4566524d5e2.json
Use sha1 rather than md5
src/Illuminate/Console/Scheduling/Event.php
@@ -228,7 +228,7 @@ public function buildCommand() */ protected function mutexPath() { - return storage_path('framework/schedule-'.md5($this->expression.$this->command)); + return storage_path('framework/schedule-'.sha1($this->expression.$this->command)); } /**
true
Other
laravel
framework
2a4acfb65f8fb69cec32cd9f4ccda4566524d5e2.json
Use sha1 rather than md5
src/Illuminate/View/Compilers/Compiler.php
@@ -41,7 +41,7 @@ public function __construct(Filesystem $files, $cachePath) */ public function getCompiledPath($path) { - return $this->cachePath.'/'.md5($path).'.php'; + return $this->cachePath.'/'.sha1($path).'.php'; } /**
true
Other
laravel
framework
2a4acfb65f8fb69cec32cd9f4ccda4566524d5e2.json
Use sha1 rather than md5
tests/Cache/CacheFileStoreTest.php
@@ -17,10 +17,10 @@ public function testNullIsReturnedIfFileDoesntExist() public function testPutCreatesMissingDirectories() { $files = $this->mockFilesystem(); - $md5 = md5('foo'); - $full_dir = __DIR__.'/'.substr($md5, 0, 2).'/'.substr($md5, 2, 2); + $hash = sha1('foo'); + $full_dir = __DIR__.'/'.substr($hash, 0, 2).'/'.substr($hash, 2, 2); $files->expects($this->once())->method('makeDirectory')->with($this->equalTo($full_dir), $this->equalTo(0777), $this->equalTo(true)); - $files->expects($this->once())->method('put')->with($this->equalTo($full_dir.'/'.$md5)); + $files->expects($this->once())->method('put')->with($this->equalTo($full_dir.'/'.$hash)); $store = new FileStore($files, __DIR__); $store->put('foo', '0000000000', 0); } @@ -51,19 +51,19 @@ public function testStoreItemProperlyStoresValues() $store = $this->getMock('Illuminate\Cache\FileStore', ['expiration'], [$files, __DIR__]); $store->expects($this->once())->method('expiration')->with($this->equalTo(10))->will($this->returnValue(1111111111)); $contents = '1111111111'.serialize('Hello World'); - $md5 = md5('foo'); - $cache_dir = substr($md5, 0, 2).'/'.substr($md5, 2, 2); - $files->expects($this->once())->method('put')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$md5), $this->equalTo($contents)); + $hash = sha1('foo'); + $cache_dir = substr($hash, 0, 2).'/'.substr($hash, 2, 2); + $files->expects($this->once())->method('put')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$hash), $this->equalTo($contents)); $store->put('foo', 'Hello World', 10); } public function testForeversAreStoredWithHighTimestamp() { $files = $this->mockFilesystem(); $contents = '9999999999'.serialize('Hello World'); - $md5 = md5('foo'); - $cache_dir = substr($md5, 0, 2).'/'.substr($md5, 2, 2); - $files->expects($this->once())->method('put')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$md5), $this->equalTo($contents)); + $hash = sha1('foo'); + $cache_dir = substr($hash, 0, 2).'/'.substr($hash, 2, 2); + $files->expects($this->once())->method('put')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$hash), $this->equalTo($contents)); $store = new FileStore($files, __DIR__); $store->forever('foo', 'Hello World', 10); } @@ -82,22 +82,22 @@ public function testForeversAreNotRemovedOnIncrement() public function testRemoveDeletesFileDoesntExist() { $files = $this->mockFilesystem(); - $md5 = md5('foobull'); - $cache_dir = substr($md5, 0, 2).'/'.substr($md5, 2, 2); - $files->expects($this->once())->method('exists')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$md5))->will($this->returnValue(false)); + $hash = sha1('foobull'); + $cache_dir = substr($hash, 0, 2).'/'.substr($hash, 2, 2); + $files->expects($this->once())->method('exists')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$hash))->will($this->returnValue(false)); $store = new FileStore($files, __DIR__); $store->forget('foobull'); } public function testRemoveDeletesFile() { $files = $this->mockFilesystem(); - $md5 = md5('foobar'); - $cache_dir = substr($md5, 0, 2).'/'.substr($md5, 2, 2); + $hash = sha1('foobar'); + $cache_dir = substr($hash, 0, 2).'/'.substr($hash, 2, 2); $store = new FileStore($files, __DIR__); $store->put('foobar', 'Hello Baby', 10); - $files->expects($this->once())->method('exists')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$md5))->will($this->returnValue(true)); - $files->expects($this->once())->method('delete')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$md5)); + $files->expects($this->once())->method('exists')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$hash))->will($this->returnValue(true)); + $files->expects($this->once())->method('delete')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$hash)); $store->forget('foobar'); }
true
Other
laravel
framework
2a4acfb65f8fb69cec32cd9f4ccda4566524d5e2.json
Use sha1 rather than md5
tests/Database/DatabaseEloquentModelTest.php
@@ -54,8 +54,11 @@ public function testCalculatedAttributes() // ensure password attribute was not set to null $this->assertArrayNotHasKey('password', $attributes); $this->assertEquals('******', $model->password); - $this->assertEquals('5ebe2294ecd0e0f08eab7690d2a6ee69', $attributes['password_hash']); - $this->assertEquals('5ebe2294ecd0e0f08eab7690d2a6ee69', $model->password_hash); + + $hash = 'e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4'; + + $this->assertEquals($hash, $attributes['password_hash']); + $this->assertEquals($hash, $model->password_hash); } public function testNewInstanceReturnsNewInstanceWithAttributesSet() @@ -1314,7 +1317,7 @@ public function getPasswordAttribute() public function setPasswordAttribute($value) { - $this->attributes['password_hash'] = md5($value); + $this->attributes['password_hash'] = sha1($value); } public function publicIncrement($column, $amount = 1)
true
Other
laravel
framework
2a4acfb65f8fb69cec32cd9f4ccda4566524d5e2.json
Use sha1 rather than md5
tests/View/ViewBladeCompilerTest.php
@@ -13,7 +13,7 @@ public function tearDown() public function testIsExpiredReturnsTrueIfCompiledFileDoesntExist() { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->shouldReceive('exists')->once()->with(__DIR__.'/'.md5('foo').'.php')->andReturn(false); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.sha1('foo').'.php')->andReturn(false); $this->assertTrue($compiler->isExpired('foo')); } @@ -27,31 +27,31 @@ public function testIsExpiredReturnsTrueIfCachePathIsNull() public function testIsExpiredReturnsTrueWhenModificationTimesWarrant() { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); - $files->shouldReceive('exists')->once()->with(__DIR__.'/'.md5('foo').'.php')->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.sha1('foo').'.php')->andReturn(true); $files->shouldReceive('lastModified')->once()->with('foo')->andReturn(100); - $files->shouldReceive('lastModified')->once()->with(__DIR__.'/'.md5('foo').'.php')->andReturn(0); + $files->shouldReceive('lastModified')->once()->with(__DIR__.'/'.sha1('foo').'.php')->andReturn(0); $this->assertTrue($compiler->isExpired('foo')); } public function testCompilePathIsProperlyCreated() { $compiler = new BladeCompiler($this->getFiles(), __DIR__); - $this->assertEquals(__DIR__.'/'.md5('foo').'.php', $compiler->getCompiledPath('foo')); + $this->assertEquals(__DIR__.'/'.sha1('foo').'.php', $compiler->getCompiledPath('foo')); } public function testCompileCompilesFileAndReturnsContents() { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); - $files->shouldReceive('put')->once()->with(__DIR__.'/'.md5('foo').'.php', 'Hello World'); + $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', 'Hello World'); $compiler->compile('foo'); } public function testCompileCompilesAndGetThePath() { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); - $files->shouldReceive('put')->once()->with(__DIR__.'/'.md5('foo').'.php', 'Hello World'); + $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', 'Hello World'); $compiler->compile('foo'); $this->assertEquals('foo', $compiler->getPath()); } @@ -67,7 +67,7 @@ public function testCompileWithPathSetBefore() { $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); - $files->shouldReceive('put')->once()->with(__DIR__.'/'.md5('foo').'.php', 'Hello World'); + $files->shouldReceive('put')->once()->with(__DIR__.'/'.sha1('foo').'.php', 'Hello World'); // set path before compilation $compiler->setPath('foo'); // trigger compilation with null $path
true
Other
laravel
framework
af31256a55b36a8576a6c8f4ea3ed39c97bdc2c8.json
fix logic as per comment from @GrahamCampbell
src/Illuminate/Validation/Validator.php
@@ -1235,11 +1235,11 @@ protected function validateUrl($attribute, $value) */ protected function validateActiveUrl($attribute, $value) { - if (! ($url = parse_url($value, PHP_URL_HOST))) { - return false; + if ($url = parse_url($value, PHP_URL_HOST)) { + return checkdnsrr($url, 'A'); } - return checkdnsrr($url, 'A'); + return false; } /**
false
Other
laravel
framework
255f63be82208a86ab280464638861df38f0b279.json
Use random_int rather than mt_rand
src/Illuminate/Session/Middleware/StartSession.php
@@ -159,7 +159,7 @@ protected function collectGarbage(SessionInterface $session) */ protected function configHitsLottery(array $config) { - return mt_rand(1, $config['lottery'][1]) <= $config['lottery'][0]; + return random_int(1, $config['lottery'][1]) <= $config['lottery'][0]; } /**
false
Other
laravel
framework
70052b2f5eec8859f1fdb0a84b7705ed464a74de.json
Move method to trait.
src/Illuminate/Http/Response.php
@@ -54,21 +54,6 @@ public function setContent($content) return parent::setContent($content); } - /** - * Add an array of headers to the response. - * - * @param array $headers - * @return $this - */ - public function withHeaders(array $headers) - { - foreach ($headers as $key => $value) { - $this->headers->set($key, $value); - } - - return $this; - } - /** * Morph the given content into JSON. *
true
Other
laravel
framework
70052b2f5eec8859f1fdb0a84b7705ed464a74de.json
Move method to trait.
src/Illuminate/Http/ResponseTrait.php
@@ -39,6 +39,21 @@ public function header($key, $value, $replace = true) return $this; } + /** + * Add an array of headers to the response. + * + * @param array $headers + * @return $this + */ + public function withHeaders(array $headers) + { + foreach ($headers as $key => $value) { + $this->headers->set($key, $value); + } + + return $this; + } + /** * Add a cookie to the response. *
true
Other
laravel
framework
be225adf0c54f87f14a686141d1bf8126cfad9d1.json
fix problems with rate limiter
src/Illuminate/Foundation/Auth/ThrottlesLogins.php
@@ -17,7 +17,7 @@ trait ThrottlesLogins protected function hasTooManyLoginAttempts(Request $request) { return app(RateLimiter::class)->tooManyAttempts( - $request->input($this->loginUsername()).$request->ip(), + $this->getThrottleKey($request), $this->maxLoginAttempts(), $this->lockoutTime() / 60 ); } @@ -31,7 +31,7 @@ protected function hasTooManyLoginAttempts(Request $request) protected function incrementLoginAttempts(Request $request) { app(RateLimiter::class)->hit( - $request->input($this->loginUsername()).$request->ip() + $this->getThrottleKey($request) ); } @@ -44,7 +44,7 @@ protected function incrementLoginAttempts(Request $request) protected function retriesLeft(Request $request) { $attempts = app(RateLimiter::class)->attempts( - $request->input($this->loginUsername()).$request->ip() + $this->getThrottleKey($request) ); return $this->maxLoginAttempts() - $attempts + 1; @@ -59,10 +59,10 @@ protected function retriesLeft(Request $request) protected function sendLockoutResponse(Request $request) { $seconds = app(RateLimiter::class)->availableIn( - $request->input($this->loginUsername()).$request->ip() + $this->getThrottleKey($request) ); - return redirect($this->loginPath()) + return redirect()->back() ->withInput($request->only($this->loginUsername(), 'remember')) ->withErrors([ $this->loginUsername() => $this->getLockoutErrorMessage($seconds), @@ -91,10 +91,21 @@ protected function getLockoutErrorMessage($seconds) protected function clearLoginAttempts(Request $request) { app(RateLimiter::class)->clear( - $request->input($this->loginUsername()).$request->ip() + $this->getThrottleKey($request) ); } + /** + * Get the throttle key for the given request. + * + * @param \Illuminate\Http\Request $request + * @return string + */ + protected function getThrottleKey(Request $request) + { + return mb_strtolower($request->input($this->loginUsername())).'|'.$request->ip(); + } + /** * Get the maximum number of login attempts for delaying further attempts. *
false
Other
laravel
framework
83ad23cbd3b7d1b3930cd68d57776aae331ce7f5.json
fix bug in pagination page resolution
src/Illuminate/Pagination/PaginationServiceProvider.php
@@ -18,7 +18,13 @@ public function register() }); Paginator::currentPageResolver(function ($pageName = 'page') { - return $this->app['request']->input($pageName); + $page = $this->app['request']->input($pageName); + + if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int) $page >= 1) { + return $page; + } + + return 1; }); } }
false
Other
laravel
framework
a38e4201e19b7e7e7ec7356031d3f12abb381e6f.json
fix bad tests
tests/Database/DatabaseEloquentModelTest.php
@@ -1162,115 +1162,115 @@ public function testModelAttributesAreCastedWhenPresentInCastsArray() { $model = new EloquentModelCastingStub; $model->setDateFormat('Y-m-d H:i:s'); - $model->first = '3'; - $model->second = '4.0'; - $model->third = 2.5; - $model->fourth = 1; - $model->fifth = 0; - $model->sixth = ['foo' => 'bar']; + $model->intAttribute = '3'; + $model->floatAttribute = '4.0'; + $model->stringAttribute = 2.5; + $model->boolAttribute = 1; + $model->booleanAttribute = 0; + $model->objectAttribute = ['foo' => 'bar']; $obj = new StdClass; $obj->foo = 'bar'; - $model->seventh = $obj; - $model->eighth = ['foo' => 'bar']; - $model->ninth = '1969-07-20'; - $model->tenth = '1969-07-20 22:56:00'; - $model->eleventh = '1969-07-20 22:56:00'; - - $this->assertInternalType('int', $model->first); - $this->assertInternalType('float', $model->second); - $this->assertInternalType('string', $model->third); - $this->assertInternalType('boolean', $model->fourth); - $this->assertInternalType('boolean', $model->fifth); - $this->assertInternalType('object', $model->sixth); - $this->assertInternalType('array', $model->seventh); - $this->assertInternalType('array', $model->eighth); - $this->assertTrue($model->fourth); - $this->assertFalse($model->fifth); - $this->assertEquals($obj, $model->sixth); - $this->assertEquals(['foo' => 'bar'], $model->seventh); - $this->assertEquals(['foo' => 'bar'], $model->eighth); - $this->assertEquals('{"foo":"bar"}', $model->eighthAttributeValue()); - $this->assertInstanceOf('Carbon\Carbon', $model->ninth); - $this->assertInstanceOf('Carbon\Carbon', $model->tenth); - $this->assertEquals('1969-07-20', $model->ninth->toDateString()); - $this->assertEquals('1969-07-20 22:56:00', $model->tenth->toDateTimeString()); - $this->assertEquals(-14173440, $model->eleventh); + $model->arrayAttribute = $obj; + $model->jsonAttribute = ['foo' => 'bar']; + $model->dateAttribute = '1969-07-20'; + $model->datetimeAttribute = '1969-07-20 22:56:00'; + $model->timestampAttribute = '1969-07-20 22:56:00'; + + $this->assertInternalType('int', $model->intAttribute); + $this->assertInternalType('float', $model->floatAttribute); + $this->assertInternalType('string', $model->stringAttribute); + $this->assertInternalType('boolean', $model->boolAttribute); + $this->assertInternalType('boolean', $model->booleanAttribute); + $this->assertInternalType('object', $model->objectAttribute); + $this->assertInternalType('array', $model->arrayAttribute); + $this->assertInternalType('array', $model->jsonAttribute); + $this->assertTrue($model->boolAttribute); + $this->assertFalse($model->booleanAttribute); + $this->assertEquals($obj, $model->objectAttribute); + $this->assertEquals(['foo' => 'bar'], $model->arrayAttribute); + $this->assertEquals(['foo' => 'bar'], $model->jsonAttribute); + $this->assertEquals('{"foo":"bar"}', $model->jsonAttributeValue()); + $this->assertInstanceOf('Carbon\Carbon', $model->dateAttribute); + $this->assertInstanceOf('Carbon\Carbon', $model->datetimeAttribute); + $this->assertEquals('1969-07-20', $model->dateAttribute->toDateString()); + $this->assertEquals('1969-07-20 22:56:00', $model->datetimeAttribute->toDateTimeString()); + $this->assertEquals(-14173440, $model->timestampAttribute); $arr = $model->toArray(); - $this->assertInternalType('int', $arr['first']); - $this->assertInternalType('float', $arr['second']); - $this->assertInternalType('string', $arr['third']); - $this->assertInternalType('boolean', $arr['fourth']); - $this->assertInternalType('boolean', $arr['fifth']); - $this->assertInternalType('object', $arr['sixth']); - $this->assertInternalType('array', $arr['seventh']); - $this->assertInternalType('array', $arr['eighth']); - $this->assertTrue($arr['fourth']); - $this->assertFalse($arr['fifth']); - $this->assertEquals($obj, $arr['sixth']); - $this->assertEquals(['foo' => 'bar'], $arr['seventh']); - $this->assertEquals(['foo' => 'bar'], $arr['eighth']); - $this->assertInstanceOf('Carbon\Carbon', $arr['ninth']); - $this->assertInstanceOf('Carbon\Carbon', $arr['tenth']); - $this->assertEquals('1969-07-20', $arr['ninth']->toDateString()); - $this->assertEquals('1969-07-20 22:56:00', $arr['tenth']->toDateTimeString()); - $this->assertEquals(-14173440, $arr['eleventh']); + $this->assertInternalType('int', $arr['intAttribute']); + $this->assertInternalType('float', $arr['floatAttribute']); + $this->assertInternalType('string', $arr['stringAttribute']); + $this->assertInternalType('boolean', $arr['boolAttribute']); + $this->assertInternalType('boolean', $arr['booleanAttribute']); + $this->assertInternalType('object', $arr['objectAttribute']); + $this->assertInternalType('array', $arr['arrayAttribute']); + $this->assertInternalType('array', $arr['jsonAttribute']); + $this->assertTrue($arr['boolAttribute']); + $this->assertFalse($arr['booleanAttribute']); + $this->assertEquals($obj, $arr['objectAttribute']); + $this->assertEquals(['foo' => 'bar'], $arr['arrayAttribute']); + $this->assertEquals(['foo' => 'bar'], $arr['jsonAttribute']); + $this->assertInstanceOf('Carbon\Carbon', $arr['dateAttribute']); + $this->assertInstanceOf('Carbon\Carbon', $arr['datetimeAttribute']); + $this->assertEquals('1969-07-20', $arr['dateAttribute']->toDateString()); + $this->assertEquals('1969-07-20 22:56:00', $arr['datetimeAttribute']->toDateTimeString()); + $this->assertEquals(-14173440, $arr['timestampAttribute']); } public function testModelAttributeCastingPreservesNull() { $model = new EloquentModelCastingStub; - $model->first = null; - $model->second = null; - $model->third = null; - $model->fourth = null; - $model->fifth = null; - $model->sixth = null; - $model->seventh = null; - $model->eighth = null; - $model->ninth = null; - $model->tenth = null; - $model->eleventh = null; + $model->intAttribute = null; + $model->floatAttribute = null; + $model->stringAttribute = null; + $model->boolAttribute = null; + $model->booleanAttribute = null; + $model->objectAttribute = null; + $model->arrayAttribute = null; + $model->jsonAttribute = null; + $model->dateAttribute = null; + $model->datetimeAttribute = null; + $model->timestampAttribute = null; $attributes = $model->getAttributes(); - $this->assertNull($attributes['first']); - $this->assertNull($attributes['second']); - $this->assertNull($attributes['third']); - $this->assertNull($attributes['fourth']); - $this->assertNull($attributes['fifth']); - $this->assertNull($attributes['sixth']); - $this->assertNull($attributes['seventh']); - $this->assertNull($attributes['eighth']); - $this->assertNull($attributes['ninth']); - $this->assertNull($attributes['tenth']); - $this->assertNull($attributes['eleventh']); - - $this->assertNull($model->first); - $this->assertNull($model->second); - $this->assertNull($model->third); - $this->assertNull($model->fourth); - $this->assertNull($model->fifth); - $this->assertNull($model->sixth); - $this->assertNull($model->seventh); - $this->assertNull($model->eighth); - $this->assertNull($model->ninth); - $this->assertNull($model->tenth); - $this->assertNull($model->eleventh); + $this->assertNull($attributes['intAttribute']); + $this->assertNull($attributes['floatAttribute']); + $this->assertNull($attributes['stringAttribute']); + $this->assertNull($attributes['boolAttribute']); + $this->assertNull($attributes['booleanAttribute']); + $this->assertNull($attributes['objectAttribute']); + $this->assertNull($attributes['arrayAttribute']); + $this->assertNull($attributes['jsonAttribute']); + $this->assertNull($attributes['dateAttribute']); + $this->assertNull($attributes['datetimeAttribute']); + $this->assertNull($attributes['timestampAttribute']); + + $this->assertNull($model->intAttribute); + $this->assertNull($model->floatAttribute); + $this->assertNull($model->stringAttribute); + $this->assertNull($model->boolAttribute); + $this->assertNull($model->booleanAttribute); + $this->assertNull($model->objectAttribute); + $this->assertNull($model->arrayAttribute); + $this->assertNull($model->jsonAttribute); + $this->assertNull($model->dateAttribute); + $this->assertNull($model->datetimeAttribute); + $this->assertNull($model->timestampAttribute); $array = $model->toArray(); - $this->assertNull($array['first']); - $this->assertNull($array['second']); - $this->assertNull($array['third']); - $this->assertNull($array['fourth']); - $this->assertNull($array['fifth']); - $this->assertNull($array['sixth']); - $this->assertNull($array['seventh']); - $this->assertNull($array['eighth']); - $this->assertNull($array['ninth']); - $this->assertNull($array['tenth']); - $this->assertNull($array['eleventh']); + $this->assertNull($array['intAttribute']); + $this->assertNull($array['floatAttribute']); + $this->assertNull($array['stringAttribute']); + $this->assertNull($array['boolAttribute']); + $this->assertNull($array['booleanAttribute']); + $this->assertNull($array['objectAttribute']); + $this->assertNull($array['arrayAttribute']); + $this->assertNull($array['jsonAttribute']); + $this->assertNull($array['dateAttribute']); + $this->assertNull($array['datetimeAttribute']); + $this->assertNull($array['timestampAttribute']); } protected function addMockConnection($model) @@ -1512,22 +1512,22 @@ public function doNotGetFourthInvalidAttributeEither() class EloquentModelCastingStub extends Model { protected $casts = [ - 'first' => 'int', - 'second' => 'float', - 'third' => 'string', - 'fourth' => 'bool', - 'fifth' => 'boolean', - 'sixth' => 'object', - 'seventh' => 'array', - 'eighth' => 'json', - 'ninth' => 'date', - 'tenth' => 'datetime', - 'eleventh' => 'timestamp', + 'intAttribute' => 'int', + 'floatAttribute' => 'float', + 'stringAttribute' => 'string', + 'boolAttribute' => 'bool', + 'booleanAttribute' => 'boolean', + 'objectAttribute' => 'object', + 'arrayAttribute' => 'array', + 'jsonAttribute' => 'json', + 'dateAttribute' => 'date', + 'datetimeAttribute' => 'datetime', + 'timestampAttribute' => 'timestamp', ]; - public function eighthAttributeValue() + public function jsonAttributeValue() { - return $this->attributes['eighth']; + return $this->attributes['jsonAttribute']; } }
false
Other
laravel
framework
52b3b29aff760e93ef85017fc51e0e6db0419a2b.json
add methods for supported and available drivers.
src/Illuminate/Database/DatabaseManager.php
@@ -2,6 +2,7 @@ namespace Illuminate\Database; +use PDO; use Illuminate\Support\Arr; use Illuminate\Support\Str; use InvalidArgumentException; @@ -262,6 +263,26 @@ public function setDefaultConnection($name) $this->app['config']['database.default'] = $name; } + /** + * Get all of the support drivers. + * + * @return array[string] + */ + public function supportedDrivers() + { + return ['mysql', 'pgsql', 'sqlite', 'dblib', 'sqlsrv']; + } + + /** + * Get all of the drivers that are actually available. + * + * @return array + */ + public function availableDrivers() + { + return array_intersect($this->supportedDrivers(), PDO::getAvailableDrivers()); + } + /** * Register an extension connection resolver. *
false
Other
laravel
framework
e70d9d51351bded6e90e81d883bad203c3759a9c.json
fix line length
src/Illuminate/Routing/Router.php
@@ -773,7 +773,8 @@ protected function substituteImplicitBindings($route) foreach ($route->signatureParameters(Model::class) as $parameter) { $class = $parameter->getClass(); - if (array_key_exists($parameter->name, $parameters) && ! $route->getParameter($parameter->name) instanceof Model) { + if (array_key_exists($parameter->name, $parameters) && + ! $route->getParameter($parameter->name) instanceof Model) { $method = $parameter->isDefaultValueAvailable() ? 'find' : 'findOrFail'; $route->setParameter(
false
Other
laravel
framework
e78906081007c9a35db575bc2bc46e163199179f.json
Fix implicit binding logic
src/Illuminate/Routing/Router.php
@@ -773,7 +773,7 @@ protected function substituteImplicitBindings($route) foreach ($route->signatureParameters(Model::class) as $parameter) { $class = $parameter->getClass(); - if (array_key_exists($parameter->name, $parameters)) { + if (array_key_exists($parameter->name, $parameters) && ! $route->getParameter($parameter->name) instanceof Model) { $method = $parameter->isDefaultValueAvailable() ? 'find' : 'findOrFail'; $route->setParameter(
false
Other
laravel
framework
de1ff69da097f8c37e41b32fbb494f8a40aacebc.json
remove extraneous word
src/Illuminate/Foundation/Console/ListenerMakeCommand.php
@@ -103,7 +103,7 @@ protected function getDefaultNamespace($rootNamespace) protected function getOptions() { return [ - ['event', null, InputOption::VALUE_REQUIRED, 'The event class the being listened for.'], + ['event', null, InputOption::VALUE_REQUIRED, 'The event class being listened for.'], ['queued', null, InputOption::VALUE_NONE, 'Indicates the event listener should be queued.'], ];
false
Other
laravel
framework
5367c5df186aa29a0bf2b3a590f6a697d5e0ae1e.json
add session to suggestions on auth
src/Illuminate/Auth/composer.json
@@ -17,7 +17,6 @@ "php": ">=5.5.9", "illuminate/contracts": "5.2.*", "illuminate/http": "5.2.*", - "illuminate/session": "5.2.*", "illuminate/support": "5.2.*", "nesbot/carbon": "~1.20" }, @@ -32,7 +31,8 @@ } }, "suggest": { - "illuminate/console": "Required to use the auth:clear-resets command (5.2.*)." + "illuminate/console": "Required to use the auth:clear-resets command (5.2.*).", + "illuminate/session": "Required to use the session based guard (5.2.)" }, "minimum-stability": "dev" }
false
Other
laravel
framework
96cc81037f25b99c4a3e9dc3ff7194277240a9f3.json
update auth helper
src/Illuminate/Foundation/helpers.php
@@ -3,10 +3,10 @@ use Illuminate\Support\Str; use Illuminate\Support\HtmlString; use Illuminate\Container\Container; -use Illuminate\Contracts\Auth\Guard; use Illuminate\Contracts\Auth\Access\Gate; use Illuminate\Contracts\Routing\UrlGenerator; use Illuminate\Contracts\Routing\ResponseFactory; +use Illuminate\Contracts\Auth\Factory as AuthFactory; use Illuminate\Contracts\View\Factory as ViewFactory; use Illuminate\Contracts\Cookie\Factory as CookieFactory; use Illuminate\Database\Eloquent\Factory as EloquentFactory; @@ -93,11 +93,11 @@ function asset($path, $secure = null) /** * Get the available auth instance. * - * @return \Illuminate\Contracts\Auth\Guard + * @return \Illuminate\Contracts\Auth\Factory */ function auth() { - return app(Guard::class); + return app(AuthFactory::class); } }
false
Other
laravel
framework
38420603d81b6f5cd763f602eb35d7a30f24726c.json
add contract for BC
src/Illuminate/Contracts/Bus/SelfHandling.php
@@ -0,0 +1,11 @@ +<?php + +namespace Illuminate\Contracts\Bus; + +/** + * @deprecated since version 5.2. Remove from jobs since self-handling is default. + */ +interface SelfHandling +{ + // +}
false
Other
laravel
framework
4a70fd555b6dd0c81acf5a45955c1b7e82ea375b.json
Apply scopes on increment/decrement
src/Illuminate/Database/Eloquent/Builder.php
@@ -385,7 +385,7 @@ public function increment($column, $amount = 1, array $extra = []) { $extra = $this->addUpdatedAtColumn($extra); - return $this->query->increment($column, $amount, $extra); + return $this->toBase()->increment($column, $amount, $extra); } /** @@ -400,7 +400,7 @@ public function decrement($column, $amount = 1, array $extra = []) { $extra = $this->addUpdatedAtColumn($extra); - return $this->query->decrement($column, $amount, $extra); + return $this->toBase()->decrement($column, $amount, $extra); } /**
true
Other
laravel
framework
4a70fd555b6dd0c81acf5a45955c1b7e82ea375b.json
Apply scopes on increment/decrement
tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php
@@ -113,6 +113,9 @@ public function testSoftDeletesAreNotRetrievedFromBuilderHelpers() $query = SoftDeletesTestUser::query(); $this->assertCount(1, $query->simplePaginate(2)->all()); + + $this->assertEquals(0, SoftDeletesTestUser::where('email', 'taylorotwell@gmail.com')->increment('id')); + $this->assertEquals(0, SoftDeletesTestUser::where('email', 'taylorotwell@gmail.com')->decrement('id')); } public function testWithTrashedReturnsAllRecords()
true
Other
laravel
framework
5d4a492e5816227389de4e42fbe8e12e89ce2c7d.json
Fix scopes on Builder helpers
src/Illuminate/Database/Eloquent/Builder.php
@@ -282,7 +282,7 @@ public function chunk($count, callable $callback) */ public function pluck($column, $key = null) { - $results = $this->query->pluck($column, $key); + $results = $this->toBase()->pluck($column, $key); // If the model has a mutator for the requested column, we will spin through // the results and mutate the values so that the mutated version of these @@ -325,9 +325,11 @@ public function lists($column, $key = null) */ public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) { - $total = $this->query->getCountForPagination(); + $query = $this->toBase(); - $this->query->forPage( + $total = $query->getCountForPagination(); + + $query->forPage( $page = $page ?: Paginator::resolveCurrentPage($pageName), $perPage = $perPage ?: $this->model->getPerPage() );
true
Other
laravel
framework
5d4a492e5816227389de4e42fbe8e12e89ce2c7d.json
Fix scopes on Builder helpers
tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php
@@ -2,6 +2,7 @@ use Carbon\Carbon; use Illuminate\Database\Connection; +use Illuminate\Pagination\Paginator; use Illuminate\Database\Query\Builder; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Capsule\Manager as DB; @@ -91,6 +92,29 @@ public function testSoftDeletesAreNotRetrievedFromBaseQuery() $this->assertCount(1, $query->get()); } + public function testSoftDeletesAreNotRetrievedFromBuilderHelpers() + { + $this->createUsers(); + + $count = 0; + $query = SoftDeletesTestUser::query(); + $query->chunk(2, function ($user) use (&$count) { + $count += count($user); + }); + $this->assertEquals(1, $count); + + $query = SoftDeletesTestUser::query(); + $this->assertCount(1, $query->pluck('email')->all()); + + Paginator::currentPageResolver(function () { return 1; }); + + $query = SoftDeletesTestUser::query(); + $this->assertCount(1, $query->paginate(2)->all()); + + $query = SoftDeletesTestUser::query(); + $this->assertCount(1, $query->simplePaginate(2)->all()); + } + public function testWithTrashedReturnsAllRecords() { $this->createUsers(); @@ -212,11 +236,9 @@ public function testWhereHasWithNestedDeletedRelationship() public function testOrWhereWithSoftDeleteConstraint() { $this->createUsers(); - SoftDeletesTestUser::create(['id' => 3, 'email' => 'something@else.com']); - $users = SoftDeletesTestUser::where('email', 'something@else.com')->orWhere('email', 'abigailotwell@gmail.com'); - $this->assertEquals(2, count($users->get())); - $this->assertEquals(['abigailotwell@gmail.com', 'something@else.com'], $users->orderBy('id')->pluck('email')->all()); + $users = SoftDeletesTestUser::where('email', 'taylorotwell@gmail.com')->orWhere('email', 'abigailotwell@gmail.com'); + $this->assertEquals(['abigailotwell@gmail.com'], $users->pluck('email')->all()); } /**
true
Other
laravel
framework
6982865171c67d73ec0bdf60182c4f75c74180fd.json
Newline all the things
src/Illuminate/Bus/Dispatcher.php
@@ -105,6 +105,7 @@ protected function commandShouldBeQueued($command) public function dispatchToQueue($command) { $connection = isset($command->connection) ? $command->connection : null; + $queue = call_user_func($this->queueResolver, $connection); if (! $queue instanceof Queue) {
false
Other
laravel
framework
f00fb8c92285f1e9eeb087d25f8058f173159f5e.json
Make line shorter
src/Illuminate/Bus/Dispatcher.php
@@ -104,7 +104,8 @@ protected function commandShouldBeQueued($command) */ public function dispatchToQueue($command) { - $queue = call_user_func($this->queueResolver, isset($command->connection) ? $command->connection : null); + $connection = isset($command->connection) ? $command->connection : null; + $queue = call_user_func($this->queueResolver, $connection); if (! $queue instanceof Queue) { throw new RuntimeException('Queue resolver did not return a Queue implementation.');
false
Other
laravel
framework
777efcdf458edaffbe759cb633ab847788a336fa.json
Add missing import. Signed-off-by: crynobone <crynobone@gmail.com>
src/Illuminate/Database/Eloquent/Model.php
@@ -4,6 +4,7 @@ use DateTime; use Exception; +use Throwable; use ArrayAccess; use Carbon\Carbon; use LogicException;
false
Other
laravel
framework
478076b1c61a637acfee137cbfc3862f22cc573c.json
show all commands in dev
src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php
@@ -106,9 +106,9 @@ public function register() { $this->registerCommands($this->commands); - if (! $this->app->environment('production')) { + //if (! $this->app->environment('production')) { $this->registerCommands($this->devCommands); - } + //} } /**
false
Other
laravel
framework
19958d826c6e8a83dc50dc256f6ce669424f3410.json
Add toBase method to the eloquent builder
src/Illuminate/Database/Eloquent/Builder.php
@@ -920,6 +920,16 @@ public function getQuery() return $this->query; } + /** + * Get a base query builder instance. + * + * @return \Illuminate\Database\Query\Builder + */ + public function toBase() + { + return $this->applyScopes()->getQuery(); + } + /** * Set the underlying query builder instance. *
true
Other
laravel
framework
19958d826c6e8a83dc50dc256f6ce669424f3410.json
Add toBase method to the eloquent builder
tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php
@@ -2,6 +2,7 @@ use Carbon\Carbon; use Illuminate\Database\Connection; +use Illuminate\Database\Query\Builder; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Capsule\Manager as DB; use Illuminate\Database\Eloquent\Model as Eloquent; @@ -80,6 +81,16 @@ public function testSoftDeletesAreNotRetrieved() $this->assertNull(SoftDeletesTestUser::find(1)); } + public function testSoftDeletesAreNotRetrievedFromBaseQuery() + { + $this->createUsers(); + + $query = SoftDeletesTestUser::query()->toBase(); + + $this->assertInstanceOf(Builder::class, $query); + $this->assertCount(1, $query->get()); + } + public function testWithTrashedReturnsAllRecords() { $this->createUsers();
true
Other
laravel
framework
528e4381af27a16eb59082b53c0e21a30e42dc1a.json
Avoid unexpected removal of items with null key.
src/Illuminate/Support/Arr.php
@@ -197,20 +197,20 @@ public static function forget(&$array, $keys) foreach ($keys as $key) { $parts = explode('.', $key); + // clean up before each pass + $array = &$original; + while (count($parts) > 1) { $part = array_shift($parts); if (isset($array[$part]) && is_array($array[$part])) { $array = &$array[$part]; } else { - $parts = []; + break(2); } } unset($array[array_shift($parts)]); - - // clean up after each pass - $array = &$original; } }
true
Other
laravel
framework
528e4381af27a16eb59082b53c0e21a30e42dc1a.json
Avoid unexpected removal of items with null key.
tests/Support/SupportArrTest.php
@@ -307,5 +307,9 @@ public function testForget() $array = ['products' => ['desk' => ['price' => ['original' => 50, 'taxes' => 60]]]]; Arr::forget($array, 'products.desk.final.taxes'); $this->assertEquals(['products' => ['desk' => ['price' => ['original' => 50, 'taxes' => 60]]]], $array); + + $array = ['products' => ['desk' => ['price' => 50], null => 'something']]; + Arr::forget($array, 'products.amount.all'); + $this->assertEquals(['products' => ['desk' => ['price' => 50], null => 'something']], $array); } }
true
Other
laravel
framework
59afdd44acda9ab4960e0819ed1ddc7364877806.json
fix bug in user provider creator.
src/Illuminate/Auth/CreatesUserProviders.php
@@ -14,15 +14,15 @@ trait CreatesUserProviders */ protected function createUserProvider($provider) { - $config = $this->app['config']['auth.providers.'.$provider]; + $config = $this->app['config']['auth.sources.'.$provider]; switch ($config['driver']) { case 'database': return $this->createDatabaseProvider($config); case 'eloquent': return $this->createEloquentProvider($config); default: - throw new InvalidArgumentException("Authentication user provider [{$config['driver']}] is not defined."); + throw new InvalidArgumentException("Authentication user source [{$config['driver']}] is not defined."); } }
false
Other
laravel
framework
19e4b7da688b2ea3aa2110a82d037ec2e72a69e2.json
fix wrong method
src/Illuminate/Auth/AuthServiceProvider.php
@@ -42,7 +42,7 @@ protected function registerAuthenticator() }); $this->app->singleton('auth.driver', function ($app) { - return $app['auth']->driver(); + return $app['auth']->guard(); }); }
false
Other
laravel
framework
104e138f4dd65e9cd0d4cc6fc6c3f6d5327880af.json
remove old drivers
src/Illuminate/Cache/CacheManager.php
@@ -168,28 +168,6 @@ protected function createNullDriver() return $this->repository(new NullStore); } - /** - * Create an instance of the WinCache cache driver. - * - * @param array $config - * @return \Illuminate\Cache\WinCacheStore - */ - protected function createWincacheDriver(array $config) - { - return $this->repository(new WinCacheStore($this->getPrefix($config))); - } - - /** - * Create an instance of the XCache cache driver. - * - * @param array $config - * @return \Illuminate\Cache\WinCacheStore - */ - protected function createXcacheDriver(array $config) - { - return $this->repository(new XCacheStore($this->getPrefix($config))); - } - /** * Create an instance of the Redis cache driver. *
false
Other
laravel
framework
7b586da6619b043fa79b6711c08a1c17cdca5a76.json
break guard into two interfaces
src/Illuminate/Contracts/Auth/Guard.php
@@ -2,44 +2,8 @@ namespace Illuminate\Contracts\Auth; -interface Guard +interface Guard extends StatelessGuard { - /** - * Determine if the current user is authenticated. - * - * @return bool - */ - public function check(); - - /** - * Determine if the current user is a guest. - * - * @return bool - */ - public function guest(); - - /** - * Get the currently authenticated user. - * - * @return \Illuminate\Contracts\Auth\Authenticatable|null - */ - public function user(); - - /** - * Get the ID for the currently authenticated user. - * - * @return int|null - */ - public function id(); - - /** - * Log a user into the application without sessions or cookies. - * - * @param array $credentials - * @return bool - */ - public function once(array $credentials = []); - /** * Attempt to authenticate a user using the given credentials. * @@ -58,22 +22,6 @@ public function attempt(array $credentials = [], $remember = false, $login = tru */ public function basic($field = 'email'); - /** - * Perform a stateless HTTP Basic login attempt. - * - * @param string $field - * @return \Symfony\Component\HttpFoundation\Response|null - */ - public function onceBasic($field = 'email'); - - /** - * Validate a user's credentials. - * - * @param array $credentials - * @return bool - */ - public function validate(array $credentials = []); - /** * Log a user into the application. * @@ -83,14 +31,6 @@ public function validate(array $credentials = []); */ public function login(Authenticatable $user, $remember = false); - /** - * Log the given user ID into the application without sessions or cookies. - * - * @param mixed $id - * @return bool - */ - public function onceUsingId($id); - /** * Log the given user ID into the application. *
true
Other
laravel
framework
7b586da6619b043fa79b6711c08a1c17cdca5a76.json
break guard into two interfaces
src/Illuminate/Contracts/Auth/StatelessGuard.php
@@ -0,0 +1,66 @@ +<?php + +namespace Illuminate\Contracts\Auth; + +interface StatelessGuard +{ + /** + * Determine if the current user is authenticated. + * + * @return bool + */ + public function check(); + + /** + * Determine if the current user is a guest. + * + * @return bool + */ + public function guest(); + + /** + * Get the currently authenticated user. + * + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function user(); + + /** + * Get the ID for the currently authenticated user. + * + * @return int|null + */ + public function id(); + + /** + * Log a user into the application without sessions or cookies. + * + * @param array $credentials + * @return bool + */ + public function once(array $credentials = []); + + /** + * Perform a stateless HTTP Basic login attempt. + * + * @param string $field + * @return \Symfony\Component\HttpFoundation\Response|null + */ + public function onceBasic($field = 'email'); + + /** + * Validate a user's credentials. + * + * @param array $credentials + * @return bool + */ + public function validate(array $credentials = []); + + /** + * Log the given user ID into the application without sessions or cookies. + * + * @param mixed $id + * @return bool + */ + public function onceUsingId($id); +}
true
Other
laravel
framework
7e446b5056013af842e4fa6f26c45e762eedc997.json
check length in env function.
src/Illuminate/Foundation/helpers.php
@@ -322,7 +322,7 @@ function env($key, $default = null) return; } - if (Str::startsWith($value, '"') && Str::endsWith($value, '"')) { + if (strlen($value) > 1 && Str::startsWith($value, '"') && Str::endsWith($value, '"')) { return substr($value, 1, -1); }
false
Other
laravel
framework
491fdb07e78325b50f805df55c6c428718117a71.json
add new integration test to soft deletes
tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php
@@ -3,48 +3,47 @@ use Carbon\Carbon; use Illuminate\Database\Connection; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Capsule\Manager as DB; use Illuminate\Database\Eloquent\Model as Eloquent; class DatabaseEloquentSoftDeletesIntegrationTest extends PHPUnit_Framework_TestCase { - /** - * Bootstrap Eloquent. - * - * @return void - */ - public static function setUpBeforeClass() + public function setUp() { - Eloquent::setConnectionResolver( - new SoftDeletesDatabaseIntegrationTestConnectionResolver - ); + $db = new DB; - Eloquent::setEventDispatcher( - new Illuminate\Events\Dispatcher - ); - } + $db->addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', + ]); - /** - * Tear down Eloquent. - */ - public static function tearDownAfterClass() - { - Eloquent::unsetEventDispatcher(); - Eloquent::unsetConnectionResolver(); + $db->bootEloquent(); + $db->setAsGlobal(); + + $this->createSchema(); } /** * Setup the database schema. * * @return void */ - public function setUp() + public function createSchema() { $this->schema()->create('users', function ($table) { $table->increments('id'); $table->string('email')->unique(); $table->timestamps(); $table->softDeletes(); }); + + $this->schema()->create('posts', function ($table) { + $table->increments('id'); + $table->integer('user_id'); + $table->string('title'); + $table->timestamps(); + $table->softDeletes(); + }); } /** @@ -132,6 +131,19 @@ public function testFirstOrNewIgnoresSoftDelete() $this->assertEquals('taylorotwell@gmail.com', $taylor->email); } + public function testWhereHasWithDeletedRelationship() + { + $this->createUsers(); + + $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); + $post = $abigail->posts()->create(['title' => 'First Title']); + $post->delete(); + + $users = SoftDeletesTestUser::has('posts')->get(); + + $this->assertEquals(0, count($users)); + } + /** * Helpers... */ @@ -174,31 +186,21 @@ class SoftDeletesTestUser extends Eloquent protected $dates = ['deleted_at']; protected $table = 'users'; protected $guarded = []; + + public function posts() + { + return $this->hasMany(SoftDeletesTestPost::class, 'user_id'); + } } /** - * Connection Resolver. + * Eloquent Models... */ -class SoftDeletesDatabaseIntegrationTestConnectionResolver implements Illuminate\Database\ConnectionResolverInterface +class SoftDeletesTestPost extends Eloquent { - protected $connection; - - public function connection($name = null) - { - if (isset($this->connection)) { - return $this->connection; - } - - return $this->connection = new Illuminate\Database\SQLiteConnection(new PDO('sqlite::memory:')); - } - - public function getDefaultConnection() - { - return 'default'; - } + use SoftDeletes; - public function setDefaultConnection($name) - { - // - } + protected $dates = ['deleted_at']; + protected $table = 'posts'; + protected $guarded = []; }
false
Other
laravel
framework
59ed03c2c1ecb50cf1c6a10c4506d06535ebe3a4.json
Simplify global scopes
src/Illuminate/Database/Eloquent/Builder.php
@@ -58,6 +58,13 @@ class Builder 'exists', 'count', 'min', 'max', 'avg', 'sum', ]; + /** + * Applied global scopes. + * + * @var array + */ + protected $scopes = []; + /** * Create a new Eloquent query builder instance. * @@ -69,6 +76,55 @@ public function __construct(QueryBuilder $query) $this->query = $query; } + /** + * Register a new global scope. + * + * @param string $identifier + * @param \Illuminate\Database\Eloquent\ScopeInterface|\Closure $scope + * @return $this + */ + public function applyGlobalScope($identifier, $scope) + { + $this->scopes[$identifier] = $scope; + + return $this; + } + + /** + * Remove a registered global scope. + * + * @param \Illuminate\Database\Eloquent\ScopeInterface|string $scope + * @return $this + */ + public function removeGlobalScope($scope) + { + if (is_string($scope)) { + unset($this->scopes[$scope]); + + return $this; + } + + foreach ($this->scopes as $key => $value) { + if ($scope instanceof $value) { + unset($this->scopes[$key]); + } + } + + return $this; + } + + /** + * Remove all registered global scopes. + * + * @return $this + */ + public function removeGlobalScopes() + { + $this->scopes = []; + + return $this; + } + /** * Find a model by its primary key. * @@ -405,7 +461,7 @@ public function onDelete(Closure $callback) */ public function getModels($columns = ['*']) { - $results = $this->query->get($columns); + $results = $this->getQueryWithScopes()->get($columns); $connection = $this->model->getConnectionName(); @@ -828,6 +884,32 @@ protected function callScope($scope, $parameters) return call_user_func_array([$this->model, $scope], $parameters) ?: $this; } + /** + * Get the underlying query builder instance with applied global scopes. + * + * @return \Illuminate\Database\Query\Builder|static + */ + public function getQueryWithScopes() + { + if (! $this->scopes) { + return $this->getQuery(); + } + + $builder = clone $this; + + foreach ($this->scopes as $scope) { + if ($scope instanceof Closure) { + $scope($builder); + } + + if ($scope instanceof ScopeInterface) { + $scope->apply($builder, $this->getModel()); + } + } + + return $builder->getQuery(); + } + /** * Get the underlying query builder instance. * @@ -935,13 +1017,19 @@ public function __call($method, $parameters) array_unshift($parameters, $this); return call_user_func_array($this->macros[$method], $parameters); - } elseif (method_exists($this->model, $scope = 'scope'.ucfirst($method))) { + } + + if (method_exists($this->model, $scope = 'scope'.ucfirst($method))) { return $this->callScope($scope, $parameters); } - $result = call_user_func_array([$this->query, $method], $parameters); + if (in_array($method, $this->passthru)) { + return call_user_func_array([$this->getQueryWithScopes(), $method], $parameters); + } + + call_user_func_array([$this->query, $method], $parameters); - return in_array($method, $this->passthru) ? $result : $this; + return $this; } /**
true
Other
laravel
framework
59ed03c2c1ecb50cf1c6a10c4506d06535ebe3a4.json
Simplify global scopes
src/Illuminate/Database/Eloquent/Model.php
@@ -2,6 +2,7 @@ namespace Illuminate\Database\Eloquent; +use Closure; use DateTime; use Exception; use ArrayAccess; @@ -10,6 +11,7 @@ use JsonSerializable; use Illuminate\Support\Arr; use Illuminate\Support\Str; +use InvalidArgumentException; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Contracts\Support\Arrayable; @@ -335,18 +337,31 @@ public static function clearBootedModels() /** * Register a new global scope on the model. * - * @param \Illuminate\Database\Eloquent\ScopeInterface $scope + * @param \Illuminate\Database\Eloquent\ScopeInterface|\Closure|string $scope + * @param \Closure|null $implementation * @return void */ - public static function addGlobalScope(ScopeInterface $scope) + public static function addGlobalScope($scope, Closure $implementation = null) { - static::$globalScopes[get_called_class()][get_class($scope)] = $scope; + if (is_string($scope) && $implementation) { + return static::$globalScopes[get_called_class()][$scope] = $implementation; + } + + if ($scope instanceof Closure) { + return static::$globalScopes[get_called_class()][uniqid('scope')] = $scope; + } + + if ($scope instanceof ScopeInterface) { + return static::$globalScopes[get_called_class()][get_class($scope)] = $scope; + } + + throw new InvalidArgumentException('Global scope must be an instance of Closure or ScopeInterface'); } /** * Determine if a model has a global scope. * - * @param \Illuminate\Database\Eloquent\ScopeInterface $scope + * @param \Illuminate\Database\Eloquent\ScopeInterface|string $scope * @return bool */ public static function hasGlobalScope($scope) @@ -357,12 +372,18 @@ public static function hasGlobalScope($scope) /** * Get a global scope registered with the model. * - * @param \Illuminate\Database\Eloquent\ScopeInterface $scope - * @return \Illuminate\Database\Eloquent\ScopeInterface|null + * @param \Illuminate\Database\Eloquent\ScopeInterface|string $scope + * @return \Illuminate\Database\Eloquent\ScopeInterface|\Closure|null */ public static function getGlobalScope($scope) { - return Arr::first(static::$globalScopes[get_called_class()], function ($key, $value) use ($scope) { + $modelScopes = static::$globalScopes[get_called_class()]; + + if (is_string($scope)) { + return isset($modelScopes[$scope]) ? $modelScopes[$scope] : null; + } + + return Arr::first($modelScopes, function ($key, $value) use ($scope) { return $scope instanceof $value; }); } @@ -1839,14 +1860,14 @@ public function newQuery() /** * Get a new query instance without a given scope. * - * @param \Illuminate\Database\Eloquent\ScopeInterface $scope + * @param \Illuminate\Database\Eloquent\ScopeInterface|string $scope * @return \Illuminate\Database\Eloquent\Builder */ public function newQueryWithoutScope($scope) { - $this->getGlobalScope($scope)->remove($builder = $this->newQuery(), $this); + $builder = $this->newQuery(); - return $builder; + return $builder->removeGlobalScope($scope); } /** @@ -1874,8 +1895,8 @@ public function newQueryWithoutScopes() */ public function applyGlobalScopes($builder) { - foreach ($this->getGlobalScopes() as $scope) { - $scope->apply($builder, $this); + foreach ($this->getGlobalScopes() as $identifier => $scope) { + $builder->applyGlobalScope($identifier, $scope); } return $builder; @@ -1889,11 +1910,7 @@ public function applyGlobalScopes($builder) */ public function removeGlobalScopes($builder) { - foreach ($this->getGlobalScopes() as $scope) { - $scope->remove($builder, $this); - } - - return $builder; + return $builder->removeGlobalScopes(); } /**
true
Other
laravel
framework
59ed03c2c1ecb50cf1c6a10c4506d06535ebe3a4.json
Simplify global scopes
src/Illuminate/Database/Eloquent/ScopeInterface.php
@@ -12,14 +12,4 @@ interface ScopeInterface * @return void */ public function apply(Builder $builder, Model $model); - - /** - * Remove the scope from the given Eloquent query builder. - * - * @param \Illuminate\Database\Eloquent\Builder $builder - * @param \Illuminate\Database\Eloquent\Model $model - * - * @return void - */ - public function remove(Builder $builder, Model $model); }
true
Other
laravel
framework
59ed03c2c1ecb50cf1c6a10c4506d06535ebe3a4.json
Simplify global scopes
src/Illuminate/Database/Eloquent/SoftDeletingScope.php
@@ -25,24 +25,6 @@ public function apply(Builder $builder, Model $model) $this->extend($builder); } - /** - * Remove the scope from the given Eloquent query builder. - * - * @param \Illuminate\Database\Eloquent\Builder $builder - * @param \Illuminate\Database\Eloquent\Model $model - * @return void - */ - public function remove(Builder $builder, Model $model) - { - $column = $model->getQualifiedDeletedAtColumn(); - - $query = $builder->getQuery(); - - $query->wheres = collect($query->wheres)->reject(function ($where) use ($column) { - return $this->isSoftDeleteConstraint($where, $column); - })->values()->all(); - } - /** * Extend the query builder with the needed functions. * @@ -116,9 +98,7 @@ protected function addRestore(Builder $builder) protected function addWithTrashed(Builder $builder) { $builder->macro('withTrashed', function (Builder $builder) { - $this->remove($builder, $builder->getModel()); - - return $builder; + return $builder->removeGlobalScope($this); }); } @@ -133,23 +113,9 @@ protected function addOnlyTrashed(Builder $builder) $builder->macro('onlyTrashed', function (Builder $builder) { $model = $builder->getModel(); - $this->remove($builder, $model); - - $builder->getQuery()->whereNotNull($model->getQualifiedDeletedAtColumn()); + $builder->removeGlobalScope($this)->getQuery()->whereNotNull($model->getQualifiedDeletedAtColumn()); return $builder; }); } - - /** - * Determine if the given where clause is a soft delete constraint. - * - * @param array $where - * @param string $column - * @return bool - */ - protected function isSoftDeleteConstraint(array $where, $column) - { - return $where['type'] == 'Null' && $where['column'] == $column; - } }
true
Other
laravel
framework
59ed03c2c1ecb50cf1c6a10c4506d06535ebe3a4.json
Simplify global scopes
tests/Database/DatabaseEloquentBuilderTest.php
@@ -399,7 +399,7 @@ public function testRealNestedWhereWithScopes() $model = new EloquentBuilderTestNestedStub; $this->mockConnectionForModel($model, 'SQLite'); $query = $model->newQuery()->where('foo', '=', 'bar')->where(function ($query) { $query->where('baz', '>', 9000); }); - $this->assertEquals('select * from "table" where "table"."deleted_at" is null and "foo" = ? and ("baz" > ?)', $query->toSql()); + $this->assertEquals('select * from "table" where "foo" = ? and ("baz" > ?) and "table"."deleted_at" is null', $query->toSql()); $this->assertEquals(['bar', 9000], $query->getBindings()); }
true
Other
laravel
framework
59ed03c2c1ecb50cf1c6a10c4506d06535ebe3a4.json
Simplify global scopes
tests/Database/DatabaseEloquentGlobalScopesTest.php
@@ -0,0 +1,107 @@ +<?php + +use Mockery as m; + +class DatabaseEloquentGlobalScopesTest extends PHPUnit_Framework_TestCase +{ + public function tearDown() + { + m::close(); + } + + public function testGlobalScopeIsApplied() + { + $model = new EloquentGlobalScopesTestModel(); + $query = $model->newQuery(); + $this->assertEquals('select * from "table" where "active" = ?', $query->toSql()); + $this->assertEquals([1], $query->getBindings()); + } + + public function testGlobalScopeCanBeRemoved() + { + $model = new EloquentGlobalScopesTestModel(); + $query = $model->newQuery()->removeGlobalScope(ActiveScope::class); + $this->assertEquals('select * from "table"', $query->toSql()); + $this->assertEquals([], $query->getBindings()); + } + + public function testClosureGlobalScopeIsApplied() + { + $model = new EloquentClosureGlobalScopesTestModel(); + $query = $model->newQuery(); + $this->assertEquals('select * from "table" where "active" = ? order by "name" asc', $query->toSql()); + $this->assertEquals([1], $query->getBindings()); + } + + public function testClosureGlobalScopeCanBeRemoved() + { + $model = new EloquentClosureGlobalScopesTestModel(); + $query = $model->newQuery()->removeGlobalScope('active_scope'); + $this->assertEquals('select * from "table" order by "name" asc', $query->toSql()); + $this->assertEquals([], $query->getBindings()); + } + + public function testGlobalScopeCanBeRemovedAfterTheQueryIsExecuted() + { + $model = new EloquentClosureGlobalScopesTestModel(); + $query = $model->newQuery(); + $this->assertEquals('select * from "table" where "active" = ? order by "name" asc', $query->toSql()); + $this->assertEquals([1], $query->getBindings()); + + $query->removeGlobalScope('active_scope'); + $this->assertEquals('select * from "table" order by "name" asc', $query->toSql()); + $this->assertEquals([], $query->getBindings()); + } + + public function testAllGlobalScopesCanBeRemoved() + { + $model = new EloquentClosureGlobalScopesTestModel(); + $query = $model->newQuery()->removeGlobalScopes(); + $this->assertEquals('select * from "table"', $query->toSql()); + $this->assertEquals([], $query->getBindings()); + + $model = new EloquentClosureGlobalScopesTestModel(); + $query = $model->newQuery(); + $model->removeGlobalScopes($query); + $this->assertEquals('select * from "table"', $query->toSql()); + $this->assertEquals([], $query->getBindings()); + } +} + +class EloquentClosureGlobalScopesTestModel extends Illuminate\Database\Eloquent\Model +{ + protected $table = 'table'; + + public static function boot() + { + static::addGlobalScope('active_scope', function ($query) { + $query->where('active', 1); + }); + + static::addGlobalScope(function ($query) { + $query->orderBy('name'); + }); + + parent::boot(); + } +} + +class EloquentGlobalScopesTestModel extends Illuminate\Database\Eloquent\Model +{ + protected $table = 'table'; + + public static function boot() + { + static::addGlobalScope(new ActiveScope); + + parent::boot(); + } +} + +class ActiveScope implements \Illuminate\Database\Eloquent\ScopeInterface +{ + public function apply(\Illuminate\Database\Eloquent\Builder $builder, \Illuminate\Database\Eloquent\Model $model) + { + return $builder->where('active', 1); + } +}
true
Other
laravel
framework
59ed03c2c1ecb50cf1c6a10c4506d06535ebe3a4.json
Simplify global scopes
tests/Database/DatabaseSoftDeletingScopeTest.php
@@ -21,20 +21,6 @@ public function testApplyingScopeToABuilder() $scope->apply($builder, $model); } - public function testScopeCanRemoveDeletedAtConstraints() - { - $scope = new Illuminate\Database\Eloquent\SoftDeletingScope; - $builder = m::mock('Illuminate\Database\Eloquent\Builder'); - $model = m::mock('Illuminate\Database\Eloquent\Model'); - $builder->shouldReceive('getModel')->andReturn($model); - $model->shouldReceive('getQualifiedDeletedAtColumn')->andReturn('table.deleted_at'); - $builder->shouldReceive('getQuery')->andReturn($query = m::mock('StdClass')); - $query->wheres = [['type' => 'Null', 'column' => 'foo'], ['type' => 'Null', 'column' => 'table.deleted_at']]; - $scope->remove($builder, $model); - - $this->assertEquals($query->wheres, [['type' => 'Null', 'column' => 'foo']]); - } - public function testForceDeleteExtension() { $builder = m::mock('Illuminate\Database\Eloquent\Builder'); @@ -74,7 +60,7 @@ public function testWithTrashedExtension() $callback = $builder->getMacro('withTrashed'); $givenBuilder = m::mock('Illuminate\Database\Eloquent\Builder'); $givenBuilder->shouldReceive('getModel')->andReturn($model = m::mock('Illuminate\Database\Eloquent\Model')); - $scope->shouldReceive('remove')->once()->with($givenBuilder, $model); + $givenBuilder->shouldReceive('removeGlobalScope')->with($scope)->andReturn($givenBuilder); $result = $callback($givenBuilder); $this->assertEquals($givenBuilder, $result); @@ -90,9 +76,9 @@ public function testOnlyTrashedExtension() $scope->extend($builder); $callback = $builder->getMacro('onlyTrashed'); $givenBuilder = m::mock('Illuminate\Database\Eloquent\Builder'); - $scope->shouldReceive('remove')->once()->with($givenBuilder, $model); $givenBuilder->shouldReceive('getQuery')->andReturn($query = m::mock('StdClass')); $givenBuilder->shouldReceive('getModel')->andReturn($model); + $givenBuilder->shouldReceive('removeGlobalScope')->with($scope)->andReturn($givenBuilder); $model->shouldReceive('getQualifiedDeletedAtColumn')->andReturn('table.deleted_at'); $query->shouldReceive('whereNotNull')->once()->with('table.deleted_at'); $result = $callback($givenBuilder);
true
Other
laravel
framework
eb762a14227924d16f8af5a6b4bb27cd5917135c.json
fix a bunch of boo boo tests.
tests/Database/DatabaseEloquentIntegrationTest.php
@@ -1,10 +1,10 @@ <?php use Illuminate\Database\Connection; +use Illuminate\Database\Capsule\Manager as DB; use Illuminate\Database\Eloquent\Model as Eloquent; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Pagination\AbstractPaginator as Paginator; -use Illuminate\Database\Capsule\Manager as DB; class DatabaseEloquentIntegrationTest extends PHPUnit_Framework_TestCase { @@ -16,38 +16,52 @@ class DatabaseEloquentIntegrationTest extends PHPUnit_Framework_TestCase public function setUp() { $db = new DB; + $db->addConnection([ 'driver' => 'sqlite', 'database' => ':memory:', ]); + + $db->addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', + ], 'second_connection'); + $db->bootEloquent(); $db->setAsGlobal(); - $this->schema()->create('users', function ($table) { - $table->increments('id'); - $table->string('email')->unique(); - $table->timestamps(); - }); + $this->createSchema(); + } - $this->schema()->create('friends', function ($table) { - $table->integer('user_id'); - $table->integer('friend_id'); - }); + protected function createSchema() + { + foreach (['default', 'second_connection'] as $connection) { + $this->schema($connection)->create('users', function ($table) { + $table->increments('id'); + $table->string('email'); + $table->timestamps(); + }); - $this->schema()->create('posts', function ($table) { - $table->increments('id'); - $table->integer('user_id'); - $table->integer('parent_id')->nullable(); - $table->string('name'); - $table->timestamps(); - }); + $this->schema($connection)->create('friends', function ($table) { + $table->integer('user_id'); + $table->integer('friend_id'); + }); - $this->schema()->create('photos', function ($table) { - $table->increments('id'); - $table->morphs('imageable'); - $table->string('name'); - $table->timestamps(); - }); + $this->schema($connection)->create('posts', function ($table) { + $table->increments('id'); + $table->integer('user_id'); + $table->integer('parent_id')->nullable(); + $table->string('name'); + $table->timestamps(); + }); + + $this->schema($connection)->create('photos', function ($table) { + $table->increments('id'); + $table->morphs('imageable'); + $table->string('name'); + $table->timestamps(); + }); + } } /** @@ -57,10 +71,12 @@ public function setUp() */ public function tearDown() { - $this->schema()->drop('users'); - $this->schema()->drop('friends'); - $this->schema()->drop('posts'); - $this->schema()->drop('photos'); + foreach (['default', 'second_connection'] as $connection) { + $this->schema($connection)->drop('users'); + $this->schema($connection)->drop('friends'); + $this->schema($connection)->drop('posts'); + $this->schema($connection)->drop('photos'); + } Relation::morphMap([], false); } @@ -227,15 +243,20 @@ public function testOneToManyRelationship() public function testBasicModelHydration() { - EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']); - EloquentTestUser::create(['email' => 'abigailotwell@gmail.com']); + $user = new EloquentTestUser(['email' => 'taylorotwell@gmail.com']); + $user->setConnection('second_connection'); + $user->save(); + + $user = new EloquentTestUser(['email' => 'abigailotwell@gmail.com']); + $user->setConnection('second_connection'); + $user->save(); - $models = EloquentTestUser::hydrateRaw('SELECT * FROM users WHERE email = ?', ['abigailotwell@gmail.com'], 'foo_connection'); + $models = EloquentTestUser::hydrateRaw('SELECT * FROM users WHERE email = ?', ['abigailotwell@gmail.com'], 'second_connection'); $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $models); $this->assertInstanceOf('EloquentTestUser', $models[0]); $this->assertEquals('abigailotwell@gmail.com', $models[0]->email); - $this->assertEquals('foo_connection', $models[0]->getConnectionName()); + $this->assertEquals('second_connection', $models[0]->getConnectionName()); $this->assertEquals(1, $models->count()); } @@ -405,7 +426,7 @@ public function testMorphMapOverwritesCurrentMap() public function testEmptyMorphToRelationship() { - $photo = EloquentTestPhoto::create(['name' => 'Avatar 1']); + $photo = new EloquentTestPhoto; $this->assertNull($photo->imageable); } @@ -492,19 +513,19 @@ public function testToArrayIncludesCustomFormattedTimestamps() * * @return Connection */ - protected function connection() + protected function connection($connection = 'default') { - return Eloquent::getConnectionResolver()->connection(); + return Eloquent::getConnectionResolver()->connection($connection); } /** * Get a schema builder instance. * * @return Schema\Builder */ - protected function schema() + protected function schema($connection = 'default') { - return $this->connection()->getSchemaBuilder(); + return $this->connection($connection)->getSchemaBuilder(); } }
true
Other
laravel
framework
eb762a14227924d16f8af5a6b4bb27cd5917135c.json
fix a bunch of boo boo tests.
tests/Database/DatabaseEloquentIntegrationWithTablePrefixTest.php
@@ -1,23 +1,78 @@ <?php +use Illuminate\Database\Capsule\Manager as DB; use Illuminate\Database\Eloquent\Model as Eloquent; -class DatabaseEloquentIntegrationWithTablePrefixTest extends DatabaseEloquentIntegrationTest +class DatabaseEloquentIntegrationWithTablePrefixTest { /** * Bootstrap Eloquent. * * @return void */ - public static function setUpBeforeClass() + public function setUp() { - $resolver = new DatabaseIntegrationTestConnectionResolver; - $resolver->connection()->setTablePrefix('prefix_'); - Eloquent::setConnectionResolver($resolver); + $db = new DB; - Eloquent::setEventDispatcher( - new Illuminate\Events\Dispatcher - ); + $db->addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', + ]); + + $db->bootEloquent(); + $db->setAsGlobal(); + + Eloquent::getConnectionResolver()->connection()->setTablePrefix('prefix_'); + + $this->createSchema(); + } + + protected function createSchema() + { + foreach (['default'] as $connection) { + $this->schema($connection)->create('users', function ($table) { + $table->increments('id'); + $table->string('email'); + $table->timestamps(); + }); + + $this->schema($connection)->create('friends', function ($table) { + $table->integer('user_id'); + $table->integer('friend_id'); + }); + + $this->schema($connection)->create('posts', function ($table) { + $table->increments('id'); + $table->integer('user_id'); + $table->integer('parent_id')->nullable(); + $table->string('name'); + $table->timestamps(); + }); + + $this->schema($connection)->create('photos', function ($table) { + $table->increments('id'); + $table->morphs('imageable'); + $table->string('name'); + $table->timestamps(); + }); + } + } + + /** + * Tear down the database schema. + * + * @return void + */ + public function tearDown() + { + foreach (['default'] as $connection) { + $this->schema($connection)->drop('users'); + $this->schema($connection)->drop('friends'); + $this->schema($connection)->drop('posts'); + $this->schema($connection)->drop('photos'); + } + + Relation::morphMap([], false); } public function testBasicModelHydration()
true
Other
laravel
framework
8fc1942fcb11fdd5f501a959accd23f3c10ca1e7.json
fix merge conflicts
src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php
@@ -106,12 +106,18 @@ protected function runningUnitTests() */ protected function tokensMatch($request) { + $sessionToken = $request->session()->token(); + $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN'); if (! $token && $header = $request->header('X-XSRF-TOKEN')) { $token = $this->encrypter->decrypt($header); } + if (! is_string($sessionToken) || ! is_string($token)) { + return false; + } + return hash_equals((string) $request->session()->token(), (string) $token); }
true
Other
laravel
framework
8fc1942fcb11fdd5f501a959accd23f3c10ca1e7.json
fix merge conflicts
src/Illuminate/Queue/Connectors/SqsConnector.php
@@ -16,18 +16,31 @@ class SqsConnector implements ConnectorInterface */ public function connect(array $config) { - $config = array_merge([ + $config = $this->getDefaultConfiguration($config); + + if ($config['key'] && $config['secret']) { + $config['credentials'] = Arr::only($config, ['key', 'secret']); + } + + return new SqsQueue( + new SqsClient($config), $config['queue'], Arr::get($config, 'prefix', '') + ); + } + + /** + * Get the default configuration for SQS. + * + * @param array $config + * @return array + */ + protected function getDefaultConfiguration(array $config) + { + return array_merge([ 'version' => 'latest', 'http' => [ 'timeout' => 60, 'connect_timeout' => 60, ], ], $config); - - if ($config['key'] && $config['secret']) { - $config['credentials'] = Arr::only($config, ['key', 'secret']); - } - - return new SqsQueue(new SqsClient($config), $config['queue']); } }
true
Other
laravel
framework
8fc1942fcb11fdd5f501a959accd23f3c10ca1e7.json
fix merge conflicts
src/Illuminate/Queue/SqsQueue.php
@@ -22,6 +22,13 @@ class SqsQueue extends Queue implements QueueContract */ protected $default; + /** + * The sqs prefix url. + * + * @var string + */ + protected $prefix; + /** * The job creator callback. * @@ -34,11 +41,13 @@ class SqsQueue extends Queue implements QueueContract * * @param \Aws\Sqs\SqsClient $sqs * @param string $default + * @param string $prefix * @return void */ - public function __construct(SqsClient $sqs, $default) + public function __construct(SqsClient $sqs, $default, $prefix = '') { $this->sqs = $sqs; + $this->prefix = $prefix; $this->default = $default; } @@ -136,7 +145,11 @@ public function createJobsUsing(callable $callback) */ public function getQueue($queue) { - return $queue ?: $this->default; + if (filter_var($queue, FILTER_VALIDATE_URL) !== false) { + return $queue; + } + + return rtrim($this->prefix, '/').'/'.($queue ?: $this->default); } /**
true
Other
laravel
framework
8fc1942fcb11fdd5f501a959accd23f3c10ca1e7.json
fix merge conflicts
tests/Queue/QueueSqsQueueTest.php
@@ -97,4 +97,12 @@ public function testPushProperlyPushesJobOntoSqs() $id = $queue->push($this->mockedJob, $this->mockedData, $this->queueName); $this->assertEquals($this->mockedMessageId, $id); } + + public function testGetQueueProperlyResolvesName() + { + $queue = new Illuminate\Queue\SqsQueue($this->sqs, $this->queueName, $this->baseUrl.'/'.$this->account.'/'); + $this->assertEquals($this->queueUrl, $queue->getQueue($this->queueName)); + $queueUrl = $this->baseUrl.'/'.$this->account.'/test'; + $this->assertEquals($queueUrl, $queue->getQueue($queueUrl)); + } }
true
Other
laravel
framework
334f1580e21439808567f6ecb200adf3a3670fb0.json
remove unneeded import.
src/Illuminate/Foundation/Bus/DispatchesJobs.php
@@ -2,7 +2,6 @@ namespace Illuminate\Foundation\Bus; -use ArrayAccess; use Illuminate\Contracts\Bus\Dispatcher; trait DispatchesJobs
false
Other
laravel
framework
9a4c071fb2a50b364b3cc0128364bc35bc84d9d7.json
Remove unintentional whitespace from docblocks
src/Illuminate/Session/Store.php
@@ -307,7 +307,7 @@ public function ageFlashData() /** * Remove data that was flashed on last request - * + * * @return void */ public function removeFlashNowData() @@ -438,7 +438,7 @@ public function flash($key, $value) /** * Flash a key / value pair to the session * for immediate use - * + * * @param string $key * @param mixed $value * @return void
false
Other
laravel
framework
2aecef2e625be2e93bc05874feaf24041a8eafab.json
Add flashNow functionality Useful for writing flash data without redirecting.
src/Illuminate/Session/Store.php
@@ -95,6 +95,8 @@ public function start() $this->regenerateToken(); } + $this->removeFlashNowData(); + return $this->started = true; } @@ -303,6 +305,20 @@ public function ageFlashData() $this->put('flash.new', []); } + /** + * Remove data that was flashed on last request + * + * @return void + */ + public function removeFlashNowData() + { + foreach ($this->get('flash.now', []) as $old) { + $this->forget($old); + } + + $this->remove('flash.now'); + } + /** * {@inheritdoc} */ @@ -419,6 +435,21 @@ public function flash($key, $value) $this->removeFromOldFlashData([$key]); } + /** + * Flash a key / value pair to the session + * for immediate use + * + * @param string $key + * @param mixed $value + * @return void + */ + public function flashNow($key, $value) + { + $this->put($key, $value); + + $this->push('flash.now', $key); + } + /** * Flash an input array to the session. *
true
Other
laravel
framework
2aecef2e625be2e93bc05874feaf24041a8eafab.json
Add flashNow functionality Useful for writing flash data without redirecting.
tests/Session/SessionStoreTest.php
@@ -160,6 +160,22 @@ public function testDataFlashing() $this->assertNull($session->get('foo')); } + public function testDataFlashingNow() + { + $session = $this->getSession(); + $session->flashNow('foo', 'bar'); + $session->flashNow('bar', 0); + + $this->assertTrue($session->has('foo')); + $this->assertEquals('bar', $session->get('foo')); + $this->assertEquals(0, $session->get('bar')); + + $session->removeFlashNowData(); + + $this->assertFalse($session->has('foo')); + $this->assertNull($session->get('foo')); + } + public function testDataMergeNewFlashes() { $session = $this->getSession();
true
Other
laravel
framework
46c8180b8e248fe18d7a39063080f25fd8874fec.json
Remove a useless isset
src/Illuminate/Bus/Dispatcher.php
@@ -254,7 +254,7 @@ public function dispatchToQueue($command) */ protected function pushCommandToQueue($queue, $command) { - if (isset($command->queue) && isset($command->delay)) { + if (isset($command->queue, $command->delay)) { return $queue->laterOn($command->queue, $command->delay, $command); }
false
Other
laravel
framework
b106c76dee0f7f2a40ab7c46428d2e69ed4b4fba.json
Use expectedException annotations in the tests
tests/Cache/ClearCommandTest.php
@@ -45,6 +45,9 @@ public function testClearWithStoreOption() $this->runCommand($command, ['store' => 'foo']); } + /** + * @expectedException InvalidArgumentException + */ public function testClearWithInvalidStoreOption() { $command = new ClearCommandTestStub( @@ -56,9 +59,8 @@ public function testClearWithInvalidStoreOption() $app = new Application(); $command->setLaravel($app); - $cacheManager->shouldReceive('store')->once()->with('bar')->andThrow('\InvalidArgumentException'); + $cacheManager->shouldReceive('store')->once()->with('bar')->andThrow('InvalidArgumentException'); $cacheRepository->shouldReceive('flush')->never(); - $this->setExpectedException('InvalidArgumentException'); $this->runCommand($command, ['store' => 'bar']); }
true
Other
laravel
framework
b106c76dee0f7f2a40ab7c46428d2e69ed4b4fba.json
Use expectedException annotations in the tests
tests/Container/ContainerTest.php
@@ -318,12 +318,14 @@ public function testCreatingBoundConcreteClassPassesParameters() $this->assertEquals($parameters, $instance->receivedParameters); } + /** + * @expectedException Illuminate\Contracts\Container\BindingResolutionException + * @expectedExceptionMessage Unresolvable dependency resolving [Parameter #0 [ <required> $first ]] in class ContainerMixedPrimitiveStub + */ public function testInternalClassWithDefaultParameters() { - $this->setExpectedException('Illuminate\Contracts\Container\BindingResolutionException', 'Unresolvable dependency resolving [Parameter #0 [ <required> $first ]] in class ContainerMixedPrimitiveStub'); $container = new Container; - $parameters = []; - $container->make('ContainerMixedPrimitiveStub', $parameters); + $container->make('ContainerMixedPrimitiveStub', []); } public function testCallWithDependencies()
true
Other
laravel
framework
b106c76dee0f7f2a40ab7c46428d2e69ed4b4fba.json
Use expectedException annotations in the tests
tests/Http/HttpRedirectResponseTest.php
@@ -116,9 +116,11 @@ public function testMagicCall() $response->withFoo('bar'); } + /** + * @expectedException BadMethodCallException + */ public function testMagicCallException() { - $this->setExpectedException('BadMethodCallException'); $response = new RedirectResponse('foo.bar'); $response->doesNotExist('bar'); }
true
Other
laravel
framework
b106c76dee0f7f2a40ab7c46428d2e69ed4b4fba.json
Use expectedException annotations in the tests
tests/Http/HttpRequestTest.php
@@ -507,9 +507,11 @@ public function testFormatReturnsAcceptsCharset() $this->assertTrue($request->accepts('application/baz+json')); } + /** + * @expectedException RuntimeException + */ public function testSessionMethod() { - $this->setExpectedException('RuntimeException'); $request = Request::create('/', 'GET'); $request->session(); }
true