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
bc656ad451d99a83432d02b165beb70da51e68c5.json
Add logo support to notification email. Signed-off-by: Taylor Otwell <taylorotwell@gmail.com>
src/Illuminate/Notifications/Transports/Notification.php
@@ -30,6 +30,13 @@ class Notification implements Arrayable */ public $application; + /** + * The URL to the application's logo. + * + * @var string + */ + public $logoUrl; + /** * The "level" of the notification (info, success, error). * @@ -87,11 +94,13 @@ public function __construct($notifiables) * Specify the name of the application sending the notification. * * @param string $application + * @param string $logoUrl * @return $this */ - public function application($application) + public function application($application, $logoUrl = null) { $this->application = $application; + $this->logoUrl = $logoUrl; return $this; } @@ -269,6 +278,7 @@ public function toArray() return [ 'notifiables' => $this->notifiables, 'application' => $this->application, + 'logoUrl' => $this->logoUrl, 'level' => $this->level, 'subject' => $this->subject, 'introLines' => $this->introLines,
true
Other
laravel
framework
bc656ad451d99a83432d02b165beb70da51e68c5.json
Add logo support to notification email. Signed-off-by: Taylor Otwell <taylorotwell@gmail.com>
src/Illuminate/Notifications/resources/views/email.blade.php
@@ -218,8 +218,11 @@ <tr> <td class="email-masthead"> <a class="email-masthead_name" href="{{ url('/') }}" target="_blank"> - <!-- <img src="logo" class="email-logo" /> --> - {{ $application }} + @if (isset($logoUrl)) + <img src="{{ $logoUrl }}" class="email-logo" /> + @else + {{ $application }} + @endif </a> </td> </tr>
true
Other
laravel
framework
76350b6666b31716e240b08b8cb5fb0158f32d65.json
remove parsedown import
src/Illuminate/Notifications/DatabaseNotification.php
@@ -2,7 +2,6 @@ namespace Illuminate\Notifications; -use Parsedown; use Illuminate\Database\Eloquent\Model; class DatabaseNotification extends Model
false
Other
laravel
framework
8dfae2aab8d0371ecfd6ea239e19ce784528e25f.json
remove int check
src/Illuminate/Cache/Repository.php
@@ -196,7 +196,7 @@ public function pull($key, $default = null) */ public function put($key, $value, $minutes = null) { - if (is_array($key) && filter_var($value, FILTER_VALIDATE_FLOAT) !== false) { + if (is_array($key)) { return $this->putMany($key, $value); }
false
Other
laravel
framework
35ab21af36861b27bd3621bccef4e15696aa2e73.json
Remove useless mock
tests/Auth/AuthEloquentUserProviderTest.php
@@ -49,7 +49,6 @@ public function testCredentialValidation() public function testModelsCanBeCreated() { - $conn = m::mock('Illuminate\Database\Connection'); $hasher = m::mock('Illuminate\Contracts\Hashing\Hasher'); $provider = new Illuminate\Auth\EloquentUserProvider($hasher, 'EloquentProviderUserStub'); $model = $provider->createModel();
false
Other
laravel
framework
061e0ffec3f48e920b609c56ce0c99f1c79dd73e.json
Remove extraneous whitespace in docblock
src/Illuminate/Session/SessionInterface.php
@@ -33,7 +33,6 @@ public function setRequestOnHandler(Request $request); * Checks if an attribute exists. * * @param string|array $key - * * @return bool */ public function exists($key);
false
Other
laravel
framework
b3606975fb65f6a65a592dd160f010017b6627dc.json
Add exists method to Session Store Currently, there is no way to test if a session variable exists and its value is null, as the has method will return false for any null value. This PR introduces the exists method into SessionStore, as well as SessionInterface and relevant tests to account for this functionality, which is present in other classes (Request, Arr, etc.)
src/Illuminate/Session/SessionInterface.php
@@ -28,4 +28,13 @@ public function handlerNeedsRequest(); * @return void */ public function setRequestOnHandler(Request $request); + + /** + * Checks if an attribute exists. + * + * @param string|array $key + * + * @return bool + */ + public function exists($key); }
true
Other
laravel
framework
b3606975fb65f6a65a592dd160f010017b6627dc.json
Add exists method to Session Store Currently, there is no way to test if a session variable exists and its value is null, as the has method will return false for any null value. This PR introduces the exists method into SessionStore, as well as SessionInterface and relevant tests to account for this functionality, which is present in other classes (Request, Arr, etc.)
src/Illuminate/Session/Store.php
@@ -321,6 +321,22 @@ public function has($name) return true; } + /** + * {@inheritdoc} + */ + public function exists($key) + { + $keys = is_array($key) ? $key : func_get_args(); + + foreach ($keys as $value) { + if (! Arr::exists($this->attributes, $value)) { + return false; + } + } + + return true; + } + /** * {@inheritdoc} */
true
Other
laravel
framework
b3606975fb65f6a65a592dd160f010017b6627dc.json
Add exists method to Session Store Currently, there is no way to test if a session variable exists and its value is null, as the has method will return false for any null value. This PR introduces the exists method into SessionStore, as well as SessionInterface and relevant tests to account for this functionality, which is present in other classes (Request, Arr, etc.)
tests/Session/SessionStoreTest.php
@@ -296,6 +296,19 @@ public function testName() $this->assertEquals($session->getName(), 'foo'); } + public function testKeyExists() + { + $session = $this->getSession(); + $session->set('foo', 'bar'); + $this->assertTrue($session->exists('foo')); + $session->set('baz', null); + $this->assertFalse($session->has('baz')); + $this->assertTrue($session->exists('baz')); + $this->assertFalse($session->exists('bogus')); + $this->assertTrue($session->exists(['foo', 'baz'])); + $this->assertFalse($session->exists(['foo', 'baz', 'bogus'])); + } + public function getSession() { $reflection = new ReflectionClass('Illuminate\Session\Store');
true
Other
laravel
framework
e54e797432a60f165bea2b8c84c62a65fd7f2ca3.json
add tap helper and test
src/Illuminate/Support/helpers.php
@@ -801,6 +801,21 @@ function studly_case($value) } } +if (! function_exists('tap')) { + /** + * Call the given Closure with a given value then return the value. + * + * @param mixed $value + * @return mixed + */ + function tap($value, $callback) + { + $callback($value); + + return $value; + } +} + if (! function_exists('title_case')) { /** * Convert a value to title case.
true
Other
laravel
framework
e54e797432a60f165bea2b8c84c62a65fd7f2ca3.json
add tap helper and test
tests/Support/SupportHelpersTest.php
@@ -673,6 +673,12 @@ public function testArrayPull() $this->assertEquals('Mövsümov', array_pull($developer, 'surname')); $this->assertEquals(['firstname' => 'Ferid'], $developer); } + + public function testTap() + { + $object = (object) ['id' => 1]; + $this->assertEquals(2, tap($object, function ($object) { $object->id = 2; })->id); + } } trait SupportTestTraitOne
true
Other
laravel
framework
af0080918dd53471916c38a87fcac0568a8deef2.json
remove requirement to have register method.
src/Illuminate/Foundation/Application.php
@@ -551,7 +551,9 @@ public function register($provider, $options = [], $force = false) $provider = $this->resolveProviderClass($provider); } - $this->registerProvider($provider); + if (method_exists($provider, 'register')) { + $provider->register(); + } // Once we have registered the service we will iterate through the options // and set each of them on the application so they will be available on @@ -598,19 +600,6 @@ public function resolveProviderClass($provider) return new $provider($this); } - /** - * Register the given service provider. - * - * @param \Illuminate\Support\ServiceProvider $provider - * @return mixed - */ - protected function registerProvider(ServiceProvider $provider) - { - if (method_exists($provider, 'register')) { - return $this->call([$provider, 'register']); - } - } - /** * Mark the given provider as registered. *
true
Other
laravel
framework
af0080918dd53471916c38a87fcac0568a8deef2.json
remove requirement to have register method.
tests/Foundation/FoundationApplicationTest.php
@@ -25,7 +25,7 @@ public function testSetLocaleSetsLocaleAndFiresLocaleChangedEvent() public function testServiceProvidersAreCorrectlyRegistered() { - $provider = m::mock('Illuminate\Support\ServiceProvider'); + $provider = m::mock('ApplicationBasicServiceProviderStub'); $class = get_class($provider); $provider->shouldReceive('register')->once(); $app = new Application; @@ -34,6 +34,17 @@ public function testServiceProvidersAreCorrectlyRegistered() $this->assertTrue(in_array($class, $app->getLoadedProviders())); } + public function testServiceProvidersAreCorrectlyRegisteredWhenRegisterMethodIsNotPresent() + { + $provider = m::mock('Illuminate\Support\ServiceProvider'); + $class = get_class($provider); + $provider->shouldReceive('register')->never(); + $app = new Application; + $app->register($provider); + + $this->assertTrue(in_array($class, $app->getLoadedProviders())); + } + public function testDeferredServicesMarkedAsBound() { $app = new Application; @@ -159,6 +170,19 @@ public function testAfterBootstrappingAddsClosure() } } +class ApplicationBasicServiceProviderStub extends Illuminate\Support\ServiceProvider +{ + public function boot() + { + // + } + + public function register() + { + // + } +} + class ApplicationDeferredSharedServiceProviderStub extends Illuminate\Support\ServiceProvider { protected $defer = true;
true
Other
laravel
framework
4811209231b3e20886ddaeafcea78c659be5b4af.json
Fix morphTo macro calls (#13828)
src/Illuminate/Database/Eloquent/Relations/MorphTo.php
@@ -2,6 +2,7 @@ namespace Illuminate\Database\Eloquent\Relations; +use BadMethodCallException; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; @@ -29,6 +30,13 @@ class MorphTo extends BelongsTo */ protected $dictionary = []; + /** + * A buffer of dynamic calls to query macros. + * + * @var array + */ + protected $macroBuffer = []; + /** * Create a new morph to relationship instance. * @@ -177,8 +185,9 @@ protected function getResultsByType($type) $eagerLoads = $this->getQuery()->nestedRelations($this->relation); - $query = $instance->newQuery()->setEagerLoads($eagerLoads) - ->mergeModelDefinedRelationConstraints($this->getQuery()); + $query = $this->replayMacros($instance->newQuery()) + ->mergeModelDefinedRelationConstraints($this->getQuery()) + ->setEagerLoads($eagerLoads); return $query->whereIn($key, $this->gatherKeysByType($type)->all())->get(); } @@ -230,4 +239,42 @@ public function getDictionary() { return $this->dictionary; } + + /** + * Replay stored macro calls on the actual related instance. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function replayMacros(Builder $query) + { + foreach ($this->macroBuffer as $macro) { + call_user_func_array([$query, $macro['method']], $macro['parameters']); + } + + return $query; + } + + /** + * Handle dynamic method calls to the relationship. + * + * @param string $method + * @param array $parameters + * @return mixed + */ + public function __call($method, $parameters) + { + try { + return parent::__call($method, $parameters); + } + + // If we tried to call a method that does not exist on the parent Builder instance, + // we'll assume that we want to call a query macro (e.g. withTrashed) that only + // exists on related models. We will just store the call and replay it later. + catch (BadMethodCallException $e) { + $this->macroBuffer[] = compact('method', 'parameters'); + + return $this; + } + } }
true
Other
laravel
framework
4811209231b3e20886ddaeafcea78c659be5b4af.json
Fix morphTo macro calls (#13828)
tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php
@@ -536,6 +536,12 @@ public function testMorphToWithTrashed() }])->first(); $this->assertEquals($abigail->email, $comment->owner->email); + + $comment = TestCommentWithoutSoftDelete::with(['owner' => function ($q) { + $q->withTrashed(); + }])->first(); + + $this->assertEquals($abigail->email, $comment->owner->email); } public function testMorphToWithConstraints() @@ -703,6 +709,20 @@ public function comments() } } +/** + * Eloquent Models... + */ +class TestCommentWithoutSoftDelete extends Eloquent +{ + protected $table = 'comments'; + protected $guarded = []; + + public function owner() + { + return $this->morphTo(); + } +} + /** * Eloquent Models... */
true
Other
laravel
framework
9fa19379ff8c201a9c0d1ad55167337d0c94e3e8.json
allow customization of default views
src/Illuminate/Pagination/AbstractPaginator.php
@@ -80,6 +80,20 @@ abstract class AbstractPaginator implements Htmlable */ protected static $viewFactoryResolver; + /** + * The default pagination view. + * + * @var string + */ + public static $defaultView = 'pagination::bootstrap-3'; + + /** + * The default "simple" pagination view. + * + * @var string + */ + public static $defaultSimpleView = 'pagination::simple-bootstrap-3'; + /** * Determine if the given value is a valid page number. * @@ -374,6 +388,28 @@ public static function viewFactoryResolver(Closure $resolver) static::$viewFactoryResolver = $resolver; } + /** + * Set the default pagination view. + * + * @param string $view + * @return void + */ + public static function defaultView($view) + { + static::$defaultView = $view; + } + + /** + * Set the default "simple" pagination view. + * + * @param string $view + * @return void + */ + public static function defaultSimpleView($view) + { + static::$defaultSimpleView = $view; + } + /** * Get the query string variable used to store the page. *
true
Other
laravel
framework
9fa19379ff8c201a9c0d1ad55167337d0c94e3e8.json
allow customization of default views
src/Illuminate/Pagination/LengthAwarePaginator.php
@@ -127,7 +127,7 @@ public function links($view = null) */ public function render($view = null) { - $view = $view ?: 'pagination::bootstrap-3'; + $view = $view ?: static::$defaultView; $window = UrlWindow::make($this);
true
Other
laravel
framework
9fa19379ff8c201a9c0d1ad55167337d0c94e3e8.json
allow customization of default views
src/Illuminate/Pagination/Paginator.php
@@ -110,9 +110,11 @@ public function links($view = null) */ public function render($view = null) { - return new HtmlString(static::viewFactory()->make($view ?: 'pagination::simple-bootstrap-3', [ - 'paginator' => $this, - ])->render()); + return new HtmlString( + static::viewFactory()->make($view ?: static::$defaultSimpleView, [ + 'paginator' => $this, + ])->render() + ); } /**
true
Other
laravel
framework
883b6db9d3d2b553637b08adefc97f6b22d188f1.json
allow publishing of pagination views
src/Illuminate/Pagination/PaginationServiceProvider.php
@@ -14,6 +14,12 @@ class PaginationServiceProvider extends ServiceProvider public function boot() { $this->loadViewsFrom(__DIR__.'/resources/views', 'pagination'); + + if ($this->app->runningInConsole()) { + $this->publishes([ + __DIR__.'/resources/views' => resource_path('views/vendor/pagination'), + ], 'laravel-pagination'); + } } /**
false
Other
laravel
framework
34b2ed68e2dfe038050d74a28947e1180bb8cb2b.json
add method to commandName
src/Illuminate/Queue/Queue.php
@@ -76,7 +76,10 @@ protected function createPayload($job, $data = '', $queue = null) } elseif (is_object($job)) { return json_encode([ 'job' => 'Illuminate\Queue\CallQueuedHandler@call', - 'data' => ['commandName' => get_class($job), 'command' => serialize(clone $job)], + 'data' => [ + 'commandName' => get_class($job).'@handle', + 'command' => serialize(clone $job), + ], ]); }
false
Other
laravel
framework
5cfe7313ccb65485dc5cf2eb6f3bf0512aebf5e1.json
improve some comments
src/Illuminate/Queue/Worker.php
@@ -182,9 +182,9 @@ public function runNextJob($connectionName, $queue = null, $delay = 0, $sleep = $job = $this->getNextJob($connection, $queue); - // If we're able to pull a job off of the stack, we will process it and - // then immediately return back out. If there is no job on the queue - // we will "sleep" the worker for the specified number of seconds. + // If we're able to pull a job off of the stack, we will process it and then return + // from this method. If there is no job on the queue, we will "sleep" the worker + // for the specified number of seconds, then keep processing jobs after sleep. if (! is_null($job)) { return $this->process( $this->manager->getName($connectionName), $job, $maxTries, $delay @@ -239,9 +239,9 @@ public function process($connection, Job $job, $maxTries = 0, $delay = 0) try { $this->raiseBeforeJobEvent($connection, $job); - // First we will fire off the job. Once it is done we will see if it will be - // automatically deleted after processing and if so we'll fire the delete - // method on the job. Otherwise, we will just keep on running our jobs. + // Here we will fire off the job and let it process. We will catch any exceptions so + // they can be reported to the developers logs, etc. Once the job is finished the + // proper events will be fired to let any listeners know this job has finished. $job->fire(); $this->raiseAfterJobEvent($connection, $job); @@ -265,9 +265,9 @@ public function process($connection, Job $job, $maxTries = 0, $delay = 0) */ protected function handleJobException($connection, Job $job, $delay, $e) { - // If we catch an exception, we will attempt to release the job back onto - // the queue so it is not lost. This will let is be retried at a later - // time by another listener (or the same one). We will do that here. + // If we catch an exception, we will attempt to release the job back onto the queue + // so it is not lost entirely. This'll let the job be retried at a later time by + // another listener (or this same one). We will re-throw this exception after. try { $this->raiseExceptionOccurredJobEvent( $connection, $job, $e
false
Other
laravel
framework
550fe258561e6ef700b5237c1bd1974624542db7.json
Add a point on suggest (#13808)
src/Illuminate/Auth/composer.json
@@ -33,7 +33,7 @@ "suggest": { "illuminate/console": "Required to use the auth:clear-resets command (5.2.*).", "illuminate/queue": "Required to fire login / logout events (5.2.*).", - "illuminate/session": "Required to use the session based guard (5.2.*)" + "illuminate/session": "Required to use the session based guard (5.2.*)." }, "minimum-stability": "dev" }
false
Other
laravel
framework
6c22d54f89d1021306b6dfab1604a06d4c9cc53e.json
remove queue responses. no longer needed
src/Illuminate/Queue/Worker.php
@@ -197,8 +197,6 @@ public function runNextJob($connectionName, $queue = null, $delay = 0, $sleep = } $this->sleep($sleep); - - return ['job' => null, 'failed' => false]; } /** @@ -247,8 +245,6 @@ public function process($connection, Job $job, $maxTries = 0, $delay = 0) $job->fire(); $this->raiseAfterJobEvent($connection, $job); - - return ['job' => $job, 'failed' => false]; } catch (Exception $e) { $this->handleJobException($connection, $job, $delay, $e); } catch (Throwable $e) { @@ -343,17 +339,17 @@ protected function raiseExceptionOccurredJobEvent($connection, Job $job, $except */ protected function logFailedJob($connection, Job $job) { - if ($this->failer) { - $this->failer->log($connection, $job->getQueue(), $job->getRawBody()); + if (! $this->failer) { + return; + } - $job->delete(); + $this->failer->log($connection, $job->getQueue(), $job->getRawBody()); - $job->failed(); + $job->delete(); - $this->raiseFailedJobEvent($connection, $job); - } + $job->failed(); - return ['job' => $job, 'failed' => true]; + $this->raiseFailedJobEvent($connection, $job); } /**
false
Other
laravel
framework
ace7f04ae579146ca3adf1c5992256c50ddc05a8.json
Use events, duh.
src/Illuminate/Queue/Console/WorkCommand.php
@@ -6,6 +6,8 @@ use Illuminate\Queue\Worker; use Illuminate\Console\Command; use Illuminate\Contracts\Queue\Job; +use Illuminate\Queue\Events\JobFailed; +use Illuminate\Queue\Events\JobProcessed; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; @@ -56,6 +58,11 @@ public function fire() return $this->worker->sleep($this->option('sleep')); } + // We'll listen to the processed and failed events so we can write information + // to the console as jobs are processed, which will let the developer watch + // which jobs are coming through a queue and be informed on its progress. + $this->listenForEvents(); + $queue = $this->option('queue'); $delay = $this->option('delay'); @@ -67,16 +74,25 @@ public function fire() $connection = $this->argument('connection'); - $response = $this->runWorker( + $this->runWorker( $connection, $queue, $delay, $memory, $this->option('daemon') ); + } - // If a job was fired by the worker, we'll write the output out to the console - // so that the developer can watch live while the queue runs in the console - // window, which will also of get logged if stdout is logged out to disk. - if (! is_null($response['job'])) { - $this->writeOutput($response['job'], $response['failed']); - } + /** + * Listen for the queue events in order to update the console output. + * + * @return void + */ + protected function listenForEvents() + { + $this->laravel['events']->listen(JobProcessed::class, function ($event) { + $this->writeOutput($event->job, false); + }); + + $this->laravel['events']->listen(JobFailed::class, function ($event) { + $this->writeOutput($event->job, true); + }); } /**
false
Other
laravel
framework
baf62ee5a1b55b62e642c40cee08030faebe1781.json
add collection serialization
src/Illuminate/Queue/SerializesModels.php
@@ -53,6 +53,10 @@ public function __wakeup() */ protected function getSerializedPropertyValue($value) { + if ($value instanceof QueueableCollection) { + return new ModelIdentifier($value->getQueueableClass(), $value->getQueueableIds()); + } + if ($value instanceof QueueableEntity) { return new ModelIdentifier(get_class($value), $value->getQueueableId()); }
false
Other
laravel
framework
d5bbda95a6435fa8cb38b8b640440b38de6b7f83.json
set exception handler even on non daemon
src/Illuminate/Queue/Console/WorkCommand.php
@@ -91,13 +91,13 @@ public function fire() */ protected function runWorker($connection, $queue, $delay, $memory, $daemon = false) { + $this->worker->setDaemonExceptionHandler( + $this->laravel['Illuminate\Contracts\Debug\ExceptionHandler'] + ); + if ($daemon) { $this->worker->setCache($this->laravel['cache']->driver()); - $this->worker->setDaemonExceptionHandler( - $this->laravel['Illuminate\Contracts\Debug\ExceptionHandler'] - ); - return $this->worker->daemon( $connection, $queue, $delay, $memory, $this->option('sleep'), $this->option('tries')
false
Other
laravel
framework
0f66352eb394e5f7ca10cd937bddef2898c49170.json
Use keyBy instead of flatMap (#13777)
src/Illuminate/Database/Eloquent/Relations/MorphTo.php
@@ -194,12 +194,12 @@ protected function getResultsByType($type) */ protected function getEagerLoadsForInstance(Model $instance) { - $eagers = BaseCollection::make($this->query->getEagerLoads()); + $relations = BaseCollection::make($this->query->getEagerLoads()); - return $eagers->filter(function ($constraint, $relation) { + return $relations->filter(function ($constraint, $relation) { return Str::startsWith($relation, $this->relation.'.'); - })->flatMap(function ($constraint, $relation) { - return [Str::replaceFirst($this->relation.'.', '', $relation) => $constraint]; + })->keyBy(function ($constraint, $relation) { + return Str::replaceFirst($this->relation.'.', '', $relation); })->merge($instance->getEagerLoads())->all(); }
false
Other
laravel
framework
bccaf7c179237ca558be5df2d7e8e44ef52136cc.json
Pass the key to the keyBy callback (#13766)
src/Illuminate/Support/Collection.php
@@ -374,8 +374,8 @@ public function keyBy($keyBy) $results = []; - foreach ($this->items as $item) { - $results[$keyBy($item)] = $item; + foreach ($this->items as $key => $item) { + $results[$keyBy($item, $key)] = $item; } return new static($results);
true
Other
laravel
framework
bccaf7c179237ca558be5df2d7e8e44ef52136cc.json
Pass the key to the keyBy callback (#13766)
tests/Support/SupportCollectionTest.php
@@ -961,12 +961,12 @@ public function testKeyByClosure() ['firstname' => 'Taylor', 'lastname' => 'Otwell', 'locale' => 'US'], ['firstname' => 'Lucas', 'lastname' => 'Michot', 'locale' => 'FR'], ]); - $result = $data->keyBy(function ($item) { - return strtolower($item['firstname'].$item['lastname']); + $result = $data->keyBy(function ($item, $key) { + return strtolower($key.'-'.$item['firstname'].$item['lastname']); }); $this->assertEquals([ - 'taylorotwell' => ['firstname' => 'Taylor', 'lastname' => 'Otwell', 'locale' => 'US'], - 'lucasmichot' => ['firstname' => 'Lucas', 'lastname' => 'Michot', 'locale' => 'FR'], + '0-taylorotwell' => ['firstname' => 'Taylor', 'lastname' => 'Otwell', 'locale' => 'US'], + '1-lucasmichot' => ['firstname' => 'Lucas', 'lastname' => 'Michot', 'locale' => 'FR'], ], $result->all()); }
true
Other
laravel
framework
a2c879a8e89fc2f0de989dfd5d0dac32b3a3db38.json
Move the Authorize middleware into Auth (#13767)
src/Illuminate/Auth/Middleware/Authorize.php
@@ -1,10 +1,10 @@ <?php -namespace Illuminate\Foundation\Http\Middleware; +namespace Illuminate\Auth\Middleware; use Closure; use Illuminate\Contracts\Auth\Access\Gate; -use Illuminate\Contracts\Auth\Factory as AuthFactory; +use Illuminate\Contracts\Auth\Factory as Auth; class Authorize { @@ -29,7 +29,7 @@ class Authorize * @param \Illuminate\Contracts\Auth\Access\Gate $gate * @return void */ - public function __construct(AuthFactory $auth, Gate $gate) + public function __construct(Auth $auth, Gate $gate) { $this->auth = $auth; $this->gate = $gate;
true
Other
laravel
framework
a2c879a8e89fc2f0de989dfd5d0dac32b3a3db38.json
Move the Authorize middleware into Auth (#13767)
tests/Auth/AuthorizeMiddlewareTest.php
@@ -6,14 +6,14 @@ use Illuminate\Auth\Access\Gate; use Illuminate\Events\Dispatcher; use Illuminate\Container\Container; +use Illuminate\Auth\Middleware\Authorize; use Illuminate\Contracts\Routing\Registrar; use Illuminate\Contracts\Auth\Factory as Auth; use Illuminate\Auth\Access\AuthorizationException; -use Illuminate\Foundation\Http\Middleware\Authorize; use Illuminate\Routing\Middleware\SubstituteBindings; use Illuminate\Contracts\Auth\Access\Gate as GateContract; -class FoundationAuthorizeMiddlewareTest extends PHPUnit_Framework_TestCase +class AuthorizeMiddlewareTest extends PHPUnit_Framework_TestCase { protected $container; protected $user;
true
Other
laravel
framework
38acdd807faec4b85fd47051341ccaf666499551.json
fix boolean binding for json updates
src/Illuminate/Database/Query/Builder.php
@@ -2067,6 +2067,8 @@ public function update(array $values) $sql = $this->grammar->compileUpdate($this, $values); + $bindings = $this->grammar->prepareBindingsForUpdate($bindings, $values); + return $this->connection->update($sql, $this->cleanBindings($bindings)); }
true
Other
laravel
framework
38acdd807faec4b85fd47051341ccaf666499551.json
fix boolean binding for json updates
src/Illuminate/Database/Query/Grammars/Grammar.php
@@ -776,6 +776,18 @@ public function compileUpdate(Builder $query, $values) return trim("update {$table}{$joins} set $columns $where"); } + /** + * Prepare the bindings for an update statement. + * + * @param array $bindings + * @param array $values + * @return array + */ + public function prepareBindingsForUpdate(array $bindings, array $values) + { + return $bindings; + } + /** * Compile a delete statement into SQL. *
true
Other
laravel
framework
38acdd807faec4b85fd47051341ccaf666499551.json
fix boolean binding for json updates
src/Illuminate/Database/Query/Grammars/MySqlGrammar.php
@@ -157,6 +157,28 @@ protected function compileJsonUpdateColumn($key, JsonExpression $value) return "{$field} = json_set({$field}, {$accessor}, {$value->getValue()})"; } + /** + * Prepare the bindings for an update statement. + * + * @param array $bindings + * @param array $values + * @return array + */ + public function prepareBindingsForUpdate(array $bindings, array $values) + { + $index = 0; + + foreach ($values as $column => $value) { + if ($this->isJsonSelector($column) && is_bool($value)) { + unset($bindings[$index]); + } + + $index++; + } + + return $bindings; + } + /** * Compile a delete statement into SQL. *
true
Other
laravel
framework
73695d9766ff341906664c0f101e85189915a516.json
Remove unnecessary code (#13732)
tests/Database/DatabaseEloquentMorphToTest.php
@@ -83,17 +83,6 @@ protected function getRelationAssociate($parent) public function getRelation($parent = null, $builder = null) { $builder = $builder ?: m::mock('Illuminate\Database\Eloquent\Builder'); - $builder->shouldReceive('toBase')->andReturn($builder); - $builder->shouldReceive('removedScopes')->andReturn([]); - $builder->shouldReceive('withoutGlobalScopes')->with([])->andReturn($builder); - $builder->shouldReceive('getRawBindings')->andReturn([ - 'select' => [], - 'join' => [], - 'where' => [], - 'having' => [], - 'order' => [], - 'union' => [], - ]); $builder->shouldReceive('where')->with('relation.id', '=', 'foreign.value'); $related = m::mock('Illuminate\Database\Eloquent\Model'); $related->shouldReceive('getKeyName')->andReturn('id');
true
Other
laravel
framework
73695d9766ff341906664c0f101e85189915a516.json
Remove unnecessary code (#13732)
tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php
@@ -2,11 +2,11 @@ use Carbon\Carbon; use Illuminate\Database\Connection; -use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Pagination\Paginator; use Illuminate\Database\Query\Builder; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Capsule\Manager as DB; +use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\Model as Eloquent; class DatabaseEloquentSoftDeletesIntegrationTest extends PHPUnit_Framework_TestCase
true
Other
laravel
framework
fb546f8d67a610381ba5ccea6bf873d75d363805.json
Fix tests and cons
CHANGELOG.md
@@ -3,7 +3,7 @@ ## v5.2.33 (2016-05-25) ### Added -- Allow query results to be traverse their via cursor ([#13030](https://github.com/laravel/framework/pull/13030)) +- Allow query results to be traversed using a cursor ([#13030](https://github.com/laravel/framework/pull/13030)) - Added support for log levels ([#13513](https://github.com/laravel/framework/pull/13513)) - Added `inRandomOrder()` method to query builder ([#13642](https://github.com/laravel/framework/pull/13642)) - Added support for custom connection in `PasswordBrokerManager` ([#13646](https://github.com/laravel/framework/pull/13646))
true
Other
laravel
framework
fb546f8d67a610381ba5ccea6bf873d75d363805.json
Fix tests and cons
src/Illuminate/Cache/RedisTaggedCache.php
@@ -9,13 +9,13 @@ class RedisTaggedCache extends TaggedCache * * @var string */ - const REFERENCE_KEY_FOREVER = 'forever'; + const REFERENCE_KEY_FOREVER = 'forever_ref'; /** * Standard reference key. * * @var string */ - const REFERENCE_KEY_STANDARD = 'standard'; + const REFERENCE_KEY_STANDARD = 'standard_ref'; /** * Store an item in the cache.
true
Other
laravel
framework
fb546f8d67a610381ba5ccea6bf873d75d363805.json
Fix tests and cons
src/Illuminate/Database/Eloquent/Builder.php
@@ -731,6 +731,24 @@ protected function isNested($name, $relation) return $dots && Str::startsWith($name, $relation.'.'); } + /** + * Apply the callback's query changes if the given "value" is true. + * + * @param bool $value + * @param \Closure $callback + * @return $this + */ + public function when($value, $callback) + { + $builder = $this; + + if ($value) { + $builder = call_user_func($callback, $builder); + } + + return $builder; + } + /** * Add a basic where clause to the query. *
true
Other
laravel
framework
fb546f8d67a610381ba5ccea6bf873d75d363805.json
Fix tests and cons
src/Illuminate/Database/Eloquent/Relations/MorphTo.php
@@ -29,13 +29,6 @@ class MorphTo extends BelongsTo */ protected $dictionary = []; - /* - * Indicates if soft-deleted model instances should be fetched. - * - * @var bool - */ - protected $withTrashed = false; - /** * Create a new morph to relationship instance. * @@ -182,9 +175,8 @@ protected function getResultsByType($type) $key = $instance->getTable().'.'.$instance->getKeyName(); - $query = $instance->newQuery(); - - $query = $this->useWithTrashed($query); + $query = clone $this->query; + $query->setModel($instance); return $query->whereIn($key, $this->gatherKeysByType($type)->all())->get(); } @@ -237,33 +229,4 @@ public function getDictionary() { return $this->dictionary; } - - /** - * Fetch soft-deleted model instances with query. - * - * @return $this - */ - public function withTrashed() - { - $this->withTrashed = true; - - $this->query = $this->useWithTrashed($this->query); - - return $this; - } - - /** - * Return trashed models with query if told so. - * - * @param \Illuminate\Database\Eloquent\Builder $query - * @return \Illuminate\Database\Eloquent\Builder - */ - protected function useWithTrashed(Builder $query) - { - if ($this->withTrashed && $query->getMacro('withTrashed') !== null) { - return $query->withTrashed(); - } - - return $query; - } }
true
Other
laravel
framework
fb546f8d67a610381ba5ccea6bf873d75d363805.json
Fix tests and cons
src/Illuminate/Database/Query/Builder.php
@@ -535,6 +535,10 @@ public function where($column, $operator = null, $value = null, $boolean = 'and' // will be bound to each SQL statements when it is finally executed. $type = 'Basic'; + if (Str::contains($column, '->') && is_bool($value)) { + $value = new Expression($value ? 'true' : 'false'); + } + $this->wheres[] = compact('type', 'column', 'operator', 'value', 'boolean'); if (! $value instanceof Expression) {
true
Other
laravel
framework
fb546f8d67a610381ba5ccea6bf873d75d363805.json
Fix tests and cons
src/Illuminate/Database/Query/Grammars/MySqlGrammar.php
@@ -4,6 +4,7 @@ use Illuminate\Support\Str; use Illuminate\Database\Query\Builder; +use Illuminate\Database\Query\JsonExpression; class MySqlGrammar extends Grammar { @@ -92,7 +93,40 @@ protected function compileLock(Builder $query, $value) */ public function compileUpdate(Builder $query, $values) { - $sql = parent::compileUpdate($query, $values); + $table = $this->wrapTable($query->from); + + $columns = []; + + // Each one of the columns in the update statements needs to be wrapped in the + // keyword identifiers, also a place-holder needs to be created for each of + // the values in the list of bindings so we can make the sets statements. + foreach ($values as $key => $value) { + if ($this->isJsonSelector($key)) { + $columns[] = $this->compileJsonUpdateColumn( + $key, new JsonExpression($value) + ); + } else { + $columns[] = $this->wrap($key).' = '.$this->parameter($value); + } + } + + $columns = implode(', ', $columns); + + // If the query has any "join" clauses, we will setup the joins on the builder + // and compile them so we can attach them to this update, as update queries + // can get join statements to attach to other tables when they're needed. + if (isset($query->joins)) { + $joins = ' '.$this->compileJoins($query, $query->joins); + } else { + $joins = ''; + } + + // Of course, update queries may also be constrained by where clauses so we'll + // need to compile the where clauses and attach it to the query so only the + // intended records are updated by the SQL statements we generate to run. + $where = $this->compileWheres($query); + + $sql = rtrim("update {$table}{$joins} set $columns $where"); if (isset($query->orders)) { $sql .= ' '.$this->compileOrders($query, $query->orders); @@ -105,6 +139,24 @@ public function compileUpdate(Builder $query, $values) return rtrim($sql); } + /** + * Prepares a JSON column being updated using the JSON_SET function. + * + * @param string $key + * @param \Illuminate\Database\JsonExpression $value + * @return string + */ + protected function compileJsonUpdateColumn($key, JsonExpression $value) + { + $path = explode('->', $key); + + $field = $this->wrapValue(array_shift($path)); + + $accessor = '"$.'.implode('.', $path).'"'; + + return "{$field} = json_set({$field}, {$accessor}, {$value->getValue()})"; + } + /** * Compile a delete statement into SQL. * @@ -148,7 +200,7 @@ protected function wrapValue($value) return $value; } - if (Str::contains($value, '->')) { + if ($this->isJsonSelector($value)) { return $this->wrapJsonSelector($value); } @@ -169,4 +221,15 @@ protected function wrapJsonSelector($value) return $field.'->'.'"$.'.implode('.', $path).'"'; } + + /** + * Determine if the given string is a JSON selector. + * + * @param string $value + * @return bool + */ + protected function isJsonSelector($value) + { + return Str::contains($value, '->'); + } }
true
Other
laravel
framework
fb546f8d67a610381ba5ccea6bf873d75d363805.json
Fix tests and cons
src/Illuminate/Database/Query/JsonExpression.php
@@ -0,0 +1,70 @@ +<?php + +namespace Illuminate\Database\Query; + +use InvalidArgumentException; + +class JsonExpression extends Expression +{ + /** + * The value of the expression. + * + * @var mixed + */ + protected $value; + + /** + * Create a new raw query expression. + * + * @param mixed $value + * @return void + */ + public function __construct($value) + { + $this->value = $this->getJsonBindingParameter($value); + } + + /** + * Translate the given value into the appropriate JSON binding parameter. + * + * @param mixed $value + * @return string + */ + protected function getJsonBindingParameter($value) + { + switch ($type = gettype($value)) { + case 'boolean': + return $value ? 'true' : 'false'; + case 'integer': + case 'double': + return $value; + case 'string': + return '?'; + case 'object': + case 'array': + return '?'; + } + + throw new InvalidArgumentException('JSON value is of illegal type: '.$type); + } + + /** + * Get the value of the expression. + * + * @return mixed + */ + public function getValue() + { + return $this->value; + } + + /** + * Get the value of the expression. + * + * @return string + */ + public function __toString() + { + return (string) $this->getValue(); + } +}
true
Other
laravel
framework
fb546f8d67a610381ba5ccea6bf873d75d363805.json
Fix tests and cons
tests/Cache/CacheTaggedCacheTest.php
@@ -64,8 +64,9 @@ public function testRedisCacheTagsPushForeverKeysCorrectly() $redis = new Illuminate\Cache\RedisTaggedCache($store, $tagSet); $store->shouldReceive('getPrefix')->andReturn('prefix:'); $store->shouldReceive('connection')->andReturn($conn = m::mock('StdClass')); - $conn->shouldReceive('sadd')->once()->with('prefix:foo:forever', 'prefix:'.sha1('foo|bar').':key1'); - $conn->shouldReceive('sadd')->once()->with('prefix:bar:forever', 'prefix:'.sha1('foo|bar').':key1'); + $conn->shouldReceive('sadd')->once()->with('prefix:foo:forever_ref', 'prefix:'.sha1('foo|bar').':key1'); + $conn->shouldReceive('sadd')->once()->with('prefix:bar:forever_ref', 'prefix:'.sha1('foo|bar').':key1'); + $store->shouldReceive('forever')->with(sha1('foo|bar').':key1', 'key1:value'); $redis->forever('key1', 'key1:value'); @@ -80,8 +81,8 @@ public function testRedisCacheTagsPushStandardKeysCorrectly() $redis = new Illuminate\Cache\RedisTaggedCache($store, $tagSet); $store->shouldReceive('getPrefix')->andReturn('prefix:'); $store->shouldReceive('connection')->andReturn($conn = m::mock('StdClass')); - $conn->shouldReceive('sadd')->once()->with('prefix:foo:standard', 'prefix:'.sha1('foo|bar').':key1'); - $conn->shouldReceive('sadd')->once()->with('prefix:bar:standard', 'prefix:'.sha1('foo|bar').':key1'); + $conn->shouldReceive('sadd')->once()->with('prefix:foo:standard_ref', 'prefix:'.sha1('foo|bar').':key1'); + $conn->shouldReceive('sadd')->once()->with('prefix:bar:standard_ref', 'prefix:'.sha1('foo|bar').':key1'); $store->shouldReceive('push')->with(sha1('foo|bar').':key1', 'key1:value'); $redis->put('key1', 'key1:value'); @@ -97,20 +98,20 @@ public function testRedisCacheTagsCanBeFlushed() $store->shouldReceive('connection')->andReturn($conn = m::mock('StdClass')); // Forever tag keys - $conn->shouldReceive('smembers')->once()->with('prefix:foo:forever')->andReturn(['key1', 'key2']); - $conn->shouldReceive('smembers')->once()->with('prefix:bar:forever')->andReturn(['key3']); + $conn->shouldReceive('smembers')->once()->with('prefix:foo:forever_ref')->andReturn(['key1', 'key2']); + $conn->shouldReceive('smembers')->once()->with('prefix:bar:forever_ref')->andReturn(['key3']); $conn->shouldReceive('del')->once()->with('key1', 'key2'); $conn->shouldReceive('del')->once()->with('key3'); - $conn->shouldReceive('del')->once()->with('prefix:foo:forever'); - $conn->shouldReceive('del')->once()->with('prefix:bar:forever'); + $conn->shouldReceive('del')->once()->with('prefix:foo:forever_ref'); + $conn->shouldReceive('del')->once()->with('prefix:bar:forever_ref'); // Standard tag keys - $conn->shouldReceive('smembers')->once()->with('prefix:foo:standard')->andReturn(['key4', 'key5']); - $conn->shouldReceive('smembers')->once()->with('prefix:bar:standard')->andReturn(['key6']); + $conn->shouldReceive('smembers')->once()->with('prefix:foo:standard_ref')->andReturn(['key4', 'key5']); + $conn->shouldReceive('smembers')->once()->with('prefix:bar:standard_ref')->andReturn(['key6']); $conn->shouldReceive('del')->once()->with('key4', 'key5'); $conn->shouldReceive('del')->once()->with('key6'); - $conn->shouldReceive('del')->once()->with('prefix:foo:standard'); - $conn->shouldReceive('del')->once()->with('prefix:bar:standard'); + $conn->shouldReceive('del')->once()->with('prefix:foo:standard_ref'); + $conn->shouldReceive('del')->once()->with('prefix:bar:standard_ref'); $tagSet->shouldReceive('reset')->once();
true
Other
laravel
framework
fb546f8d67a610381ba5ccea6bf873d75d363805.json
Fix tests and cons
tests/Database/DatabaseEloquentBuilderTest.php
@@ -493,9 +493,9 @@ public function testWithCountAndContraintsAndHaving() $builder = $model->where('bar', 'baz'); $builder->withCount(['foo' => function ($q) { $q->where('bam', '>', 'qux'); - }])->having('fooCount', '>=', 1); + }])->having('foo_count', '>=', 1); - $this->assertEquals('select *, (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "bam" > ?) as "foo_count" from "eloquent_builder_test_model_parent_stubs" where "bar" = ? having "fooCount" >= ?', $builder->toSql()); + $this->assertEquals('select *, (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "bam" > ?) as "foo_count" from "eloquent_builder_test_model_parent_stubs" where "bar" = ? having "foo_count" >= ?', $builder->toSql()); $this->assertEquals(['qux', 'baz', 1], $builder->getBindings()); }
true
Other
laravel
framework
fb546f8d67a610381ba5ccea6bf873d75d363805.json
Fix tests and cons
tests/Database/DatabaseEloquentMorphToTest.php
@@ -1,7 +1,6 @@ <?php use Mockery as m; -use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Relations\MorphTo; class DatabaseEloquentMorphToTest extends PHPUnit_Framework_TestCase @@ -37,61 +36,6 @@ public function testLookupDictionaryIsProperlyConstructed() ], $dictionary); } - public function testModelsAreProperlyPulledAndMatched() - { - $relation = $this->getRelation(); - - $one = m::mock('StdClass'); - $one->morph_type = 'morph_type_1'; - $one->foreign_key = 'foreign_key_1'; - - $two = m::mock('StdClass'); - $two->morph_type = 'morph_type_1'; - $two->foreign_key = 'foreign_key_1'; - - $three = m::mock('StdClass'); - $three->morph_type = 'morph_type_2'; - $three->foreign_key = 'foreign_key_2'; - - $relation->addEagerConstraints([$one, $two, $three]); - - $relation->shouldReceive('createModelByType')->once()->with('morph_type_1')->andReturn($firstQuery = m::mock('Illuminate\Database\Eloquent\Builder')); - $relation->shouldReceive('createModelByType')->once()->with('morph_type_2')->andReturn($secondQuery = m::mock('Illuminate\Database\Eloquent\Builder')); - $firstQuery->shouldReceive('getTable')->andReturn('foreign_table_1'); - $firstQuery->shouldReceive('getKeyName')->andReturn('id'); - $secondQuery->shouldReceive('getTable')->andReturn('foreign_table_2'); - $secondQuery->shouldReceive('getKeyName')->andReturn('id'); - - $firstQuery->shouldReceive('newQuery')->once()->andReturn($firstQuery); - $secondQuery->shouldReceive('newQuery')->once()->andReturn($secondQuery); - - $firstQuery->shouldReceive('whereIn')->once()->with('foreign_table_1.id', ['foreign_key_1'])->andReturn($firstQuery); - $firstQuery->shouldReceive('get')->once()->andReturn(Collection::make([$resultOne = m::mock('StdClass')])); - $resultOne->shouldReceive('getKey')->andReturn('foreign_key_1'); - - $secondQuery->shouldReceive('whereIn')->once()->with('foreign_table_2.id', ['foreign_key_2'])->andReturn($secondQuery); - $secondQuery->shouldReceive('get')->once()->andReturn(Collection::make([$resultTwo = m::mock('StdClass')])); - $resultTwo->shouldReceive('getKey')->andReturn('foreign_key_2'); - - $one->shouldReceive('setRelation')->once()->with('relation', $resultOne); - $two->shouldReceive('setRelation')->once()->with('relation', $resultOne); - $three->shouldReceive('setRelation')->once()->with('relation', $resultTwo); - - $relation->getEager(); - } - - public function testModelsWithSoftDeleteAreProperlyPulled() - { - $builder = m::mock('Illuminate\Database\Eloquent\Builder'); - - $relation = $this->getRelation(null, $builder); - - $builder->shouldReceive('getMacro')->once()->with('withTrashed')->andReturn(function () { return true; }); - $builder->shouldReceive('withTrashed')->once(); - - $relation->withTrashed(); - } - public function testAssociateMethodSetsForeignKeyAndTypeOnModel() { $parent = m::mock('Illuminate\Database\Eloquent\Model'); @@ -139,6 +83,17 @@ protected function getRelationAssociate($parent) public function getRelation($parent = null, $builder = null) { $builder = $builder ?: m::mock('Illuminate\Database\Eloquent\Builder'); + $builder->shouldReceive('toBase')->andReturn($builder); + $builder->shouldReceive('removedScopes')->andReturn([]); + $builder->shouldReceive('withoutGlobalScopes')->with([])->andReturn($builder); + $builder->shouldReceive('getRawBindings')->andReturn([ + 'select' => [], + 'join' => [], + 'where' => [], + 'having' => [], + 'order' => [], + 'union' => [], + ]); $builder->shouldReceive('where')->with('relation.id', '=', 'foreign.value'); $related = m::mock('Illuminate\Database\Eloquent\Model'); $related->shouldReceive('getKeyName')->andReturn('id');
true
Other
laravel
framework
fb546f8d67a610381ba5ccea6bf873d75d363805.json
Fix tests and cons
tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php
@@ -2,6 +2,7 @@ use Carbon\Carbon; use Illuminate\Database\Connection; +use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Pagination\Paginator; use Illuminate\Database\Query\Builder; use Illuminate\Database\Eloquent\SoftDeletes; @@ -50,6 +51,8 @@ public function createSchema() $this->schema()->create('comments', function ($table) { $table->increments('id'); + $table->integer('owner_id')->nullable(); + $table->string('owner_type')->nullable(); $table->integer('post_id'); $table->string('body'); $table->timestamps(); @@ -506,6 +509,74 @@ public function testOrWhereWithSoftDeleteConstraint() $this->assertEquals(['abigailotwell@gmail.com'], $users->pluck('email')->all()); } + public function testMorphToWithTrashed() + { + $this->createUsers(); + + $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); + $post1 = $abigail->posts()->create(['title' => 'First Title']); + $post1->comments()->create([ + 'body' => 'Comment Body', + 'owner_type' => SoftDeletesTestUser::class, + 'owner_id' => $abigail->id, + ]); + + $abigail->delete(); + + $comment = SoftDeletesTestCommentWithTrashed::with(['owner' => function ($q) { + $q->withoutGlobalScope(SoftDeletingScope::class); + }])->first(); + + $this->assertEquals($abigail->email, $comment->owner->email); + + $comment = SoftDeletesTestCommentWithTrashed::with(['owner' => function ($q) { + $q->withTrashed(); + }])->first(); + + $this->assertEquals($abigail->email, $comment->owner->email); + } + + public function testMorphToWithConstraints() + { + $this->createUsers(); + + $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); + $post1 = $abigail->posts()->create(['title' => 'First Title']); + $post1->comments()->create([ + 'body' => 'Comment Body', + 'owner_type' => SoftDeletesTestUser::class, + 'owner_id' => $abigail->id, + ]); + + $comment = SoftDeletesTestCommentWithTrashed::with(['owner' => function ($q) { + $q->where('email', 'taylorotwell@gmail.com'); + }])->first(); + + $this->assertEquals(null, $comment->owner); + } + + public function testMorphToWithoutConstraints() + { + $this->createUsers(); + + $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); + $post1 = $abigail->posts()->create(['title' => 'First Title']); + $comment1 = $post1->comments()->create([ + 'body' => 'Comment Body', + 'owner_type' => SoftDeletesTestUser::class, + 'owner_id' => $abigail->id, + ]); + + $comment = SoftDeletesTestCommentWithTrashed::with('owner')->first(); + + $this->assertEquals($abigail->email, $comment->owner->email); + + $abigail->delete(); + $comment = SoftDeletesTestCommentWithTrashed::with('owner')->first(); + + $this->assertEquals(null, $comment->owner); + } + /** * Helpers... */ @@ -606,6 +677,25 @@ class SoftDeletesTestComment extends Eloquent protected $dates = ['deleted_at']; protected $table = 'comments'; protected $guarded = []; + + public function owner() + { + return $this->morphTo(); + } +} + +class SoftDeletesTestCommentWithTrashed extends Eloquent +{ + use SoftDeletes; + + protected $dates = ['deleted_at']; + protected $table = 'comments'; + protected $guarded = []; + + public function owner() + { + return $this->morphTo(); + } } /**
true
Other
laravel
framework
fb546f8d67a610381ba5ccea6bf873d75d363805.json
Fix tests and cons
tests/Database/DatabaseQueryBuilderTest.php
@@ -1256,6 +1256,62 @@ public function testMySqlWrapping() $this->assertEquals('select * from `users`', $builder->toSql()); } + public function testMySqlUpdateWrappingJson() + { + $grammar = new Illuminate\Database\Query\Grammars\MySqlGrammar; + $processor = m::mock('Illuminate\Database\Query\Processors\Processor'); + + // Couldn't get mockery to work + $connection = $this->createMock('Illuminate\Database\ConnectionInterface'); + $connection->expects($this->once()) + ->method('update') + ->with( + $this->equalTo('update `users` set `name` = json_set(`name`, "$.first_name", ?), `name` = json_set(`name`, "$.last_name", ?) where `active` = ?'), + $this->equalTo(['John', 'Doe', 1]) + ); + + $builder = new Builder($connection, $grammar, $processor); + + $result = $builder->from('users')->where('active', '=', 1)->update(['name->first_name' => 'John', 'name->last_name' => 'Doe']); + } + + public function testMySqlWrappingJsonWithString() + { + $builder = $this->getMySqlBuilder(); + $builder->select('*')->from('users')->where('items->sku', '=', 'foo-bar'); + $this->assertEquals('select * from `users` where `items`->"$.sku" = ?', $builder->toSql()); + $this->assertCount(1, $builder->getRawBindings()['where']); + $this->assertEquals('foo-bar', $builder->getRawBindings()['where'][0]); + } + + public function testMySqlWrappingJsonWithInteger() + { + $builder = $this->getMySqlBuilder(); + $builder->select('*')->from('users')->where('items->price', '=', 1); + $this->assertEquals('select * from `users` where `items`->"$.price" = ?', $builder->toSql()); + } + + public function testMySqlWrappingJsonWithDouble() + { + $builder = $this->getMySqlBuilder(); + $builder->select('*')->from('users')->where('items->price', '=', 1.5); + $this->assertEquals('select * from `users` where `items`->"$.price" = ?', $builder->toSql()); + } + + public function testMySqlWrappingJsonWithBoolean() + { + $builder = $this->getMySqlBuilder(); + $builder->select('*')->from('users')->where('items->available', '=', true); + $this->assertEquals('select * from `users` where `items`->"$.available" = true', $builder->toSql()); + } + + public function testMySqlWrappingJsonWithBooleanAndIntegerThatLooksLikeOne() + { + $builder = $this->getMySqlBuilder(); + $builder->select('*')->from('users')->where('items->available', '=', true)->where('items->active', '=', false)->where('items->number_available', '=', 0); + $this->assertEquals('select * from `users` where `items`->"$.available" = true and `items`->"$.active" = false and `items`->"$.number_available" = ?', $builder->toSql()); + } + public function testMySqlWrappingJson() { $builder = $this->getMySqlBuilder();
true
Other
laravel
framework
6ed8b3a3e9a454a0959ea8ecd70a166cc3dbf357.json
Remove the "unauthenticated" method (#13709)
src/Illuminate/Foundation/Exceptions/Handler.php
@@ -181,22 +181,6 @@ protected function convertValidationExceptionToResponse(ValidationException $e, return redirect()->back()->withInput($request->input())->withErrors($errors); } - /** - * Convert an authentication exception into an unauthenticated response. - * - * @param \Illuminate\Http\Request $request - * @param \Illuminate\Auth\AuthenticationException $e - * @return \Symfony\Component\HttpFoundation\Response - */ - protected function unauthenticated($request, AuthenticationException $e) - { - if ($request->ajax() || $request->wantsJson()) { - return response('Unauthorized.', 401); - } else { - return redirect()->guest('login'); - } - } - /** * Create a Symfony response for the given exception. *
false
Other
laravel
framework
c1820b2039f4bb44322c704f9c208fb10341cd38.json
fix style issue
src/Illuminate/Auth/Events/Logout.php
@@ -7,7 +7,6 @@ class Logout { use SerializesModels; - /** * The authenticated user. *
false
Other
laravel
framework
540b1ae0a17ffc5720b678f33795422e8a152ab8.json
write integration tests for migrator
src/Illuminate/Database/Console/Migrations/MigrateCommand.php
@@ -68,9 +68,9 @@ public function fire() if (! is_null($path = $this->input->getOption('path'))) { $paths[] = $this->laravel->basePath().'/'.$path; } else { - $paths[] = $this->getMigrationPath(); - - $paths = array_merge($paths, $this->migrator->paths()); + $paths = array_merge( + [$this->getMigrationPath()], $this->migrator->paths() + ); } $this->migrator->run($paths, [
true
Other
laravel
framework
540b1ae0a17ffc5720b678f33795422e8a152ab8.json
write integration tests for migrator
src/Illuminate/Database/Console/Migrations/ResetCommand.php
@@ -66,9 +66,9 @@ public function fire() $pretend = $this->input->getOption('pretend'); - $paths[] = $this->getMigrationPath(); - - $paths = array_merge($paths, $this->migrator->paths()); + $paths = array_merge( + [$this->getMigrationPath()], $this->migrator->paths() + ); $this->migrator->reset($paths, $pretend);
true
Other
laravel
framework
540b1ae0a17ffc5720b678f33795422e8a152ab8.json
write integration tests for migrator
src/Illuminate/Database/Console/Migrations/RollbackCommand.php
@@ -60,9 +60,9 @@ public function fire() $pretend = $this->input->getOption('pretend'); - $paths[] = $this->getMigrationPath(); - - $paths = array_merge($paths, $this->migrator->paths()); + $paths = array_merge( + [$this->getMigrationPath()], $this->migrator->paths() + ); $this->migrator->rollback($paths, $pretend);
true
Other
laravel
framework
540b1ae0a17ffc5720b678f33795422e8a152ab8.json
write integration tests for migrator
src/Illuminate/Database/Console/Migrations/StatusCommand.php
@@ -57,9 +57,9 @@ public function fire() if (! is_null($path = $this->input->getOption('path'))) { $paths[] = $this->laravel->basePath().'/'.$path; } else { - $paths[] = $this->getMigrationPath(); - - $paths = array_merge($paths, $this->migrator->paths()); + $paths = array_merge( + [$this->getMigrationPath()], $this->migrator->paths() + ); } $ran = $this->migrator->getRepository()->getRan();
true
Other
laravel
framework
540b1ae0a17ffc5720b678f33795422e8a152ab8.json
write integration tests for migrator
src/Illuminate/Database/Migrations/Migrator.php
@@ -4,6 +4,7 @@ use Illuminate\Support\Arr; use Illuminate\Support\Str; +use Illuminate\Support\Collection; use Illuminate\Filesystem\Filesystem; use Illuminate\Database\ConnectionResolverInterface as Resolver; @@ -45,7 +46,7 @@ class Migrator protected $notes = []; /** - * The paths for all migration files. + * The paths to all of the migration files. * * @var array */ @@ -86,13 +87,10 @@ public function run($paths, array $options = []) // run each of the outstanding migrations against a database connection. $ran = $this->repository->getRan(); - $migrations = []; - - foreach ($files as $file) { - if (! in_array($this->getMigrationName($file), $ran)) { - $migrations[] = $file; - } - } + $migrations = Collection::make($files) + ->reject(function ($file) use ($ran) { + return in_array($this->getMigrationName($file), $ran); + })->values()->all(); $this->requireFiles($migrations); @@ -192,16 +190,13 @@ public function rollback($paths, $pretend = false) if ($count === 0) { $this->note('<info>Nothing to rollback.</info>'); } else { - // We need to reverse these migrations so that they are "downed" in reverse - // to what they run on "up". It lets us backtrack through the migrations - // and properly reverse the entire database schema operation that ran. + // Next we will run through all of the migrations and call the "down" method + // which will reverse each migration in order. This getLast method on the + // repository already returns these migration's names in reverse order. $this->requireFiles($files); + foreach ($migrations as $migration) { - foreach ($files as $file) { - if ($this->getMigrationName($file) == $migration->migration) { - $this->runDown($file, (object) $migration, $pretend); - } - } + $this->runDown($files[$migration->migration], (object) $migration, $pretend); } } @@ -221,6 +216,9 @@ public function reset($paths, $pretend = false) $files = $this->getMigrationFiles($paths); + // Next, we will reverse the migration list so we can run them back in the + // correct order for resetting this database. This will allow us to get + // the database back into its "empty" state ready for the migrations. $migrations = array_reverse($this->repository->getRan()); $count = count($migrations); @@ -229,12 +227,12 @@ public function reset($paths, $pretend = false) $this->note('<info>Nothing to rollback.</info>'); } else { $this->requireFiles($files); + + // Next we will run through all of the migrations and call the "down" method + // which will reverse each migration in order. This will get the database + // back to its original "empty" state and will be ready for migrations. foreach ($migrations as $migration) { - foreach ($files as $file) { - if ($this->getMigrationName($file) == $migration) { - $this->runDown($file, (object) ['migration' => $migration], $pretend); - } - } + $this->runDown($files[$migration], (object) ['migration' => $migration], $pretend); } } @@ -280,40 +278,13 @@ protected function runDown($file, $migration, $pretend) */ public function getMigrationFiles($paths) { - $files = []; - - $paths = is_array($paths) ? $paths : [$paths]; - - foreach ($paths as $path) { - $files[] = $this->files->glob($path.'/*_*.php'); - } - - $files = array_flatten($files); - - $files = array_filter($files); - - // Once we have the array of files in the directory we will just remove the - // extension and take the basename of the file which is all we need when - // finding the migrations that haven't been run against the databases. - if (empty($files)) { - return []; - } - - // Now we have a full list of file names we will sort them and because they - // all start with a timestamp this should give us the migrations in the - // order they were actually created in by the application developers. - usort($files, function ($a, $b) { - $a = $this->getMigrationName($a); - $b = $this->getMigrationName($b); - - if ($a == $b) { - return 0; - } - - return ($a < $b) ? -1 : 1; - }); - - return $files; + return Collection::make($paths)->flatMap(function ($path) { + return $this->files->glob($path.'/*_*.php'); + })->filter()->sortBy(function ($file) { + return $this->getMigrationName($file); + })->values()->keyBy(function ($file) { + return $this->getMigrationName($file); + })->all(); } /** @@ -374,13 +345,22 @@ protected function getQueries($migration, $method) */ public function resolve($file) { - $file = implode('_', array_slice(explode('_', $file), 4)); - - $class = Str::studly($file); + $class = Str::studly(implode('_', array_slice(explode('_', $file), 4))); return new $class; } + /** + * Get the name of the migration. + * + * @param string $path + * @return string + */ + public function getMigrationName($path) + { + return str_replace('.php', '', basename($path)); + } + /** * Raise a note event for the migrator. * @@ -413,6 +393,26 @@ public function resolveConnection($connection) return $this->resolver->connection($connection); } + /** + * Set a path which contains migration files. + * + * @param string $path + */ + public function path($path) + { + $this->paths[] = $path; + } + + /** + * Get all custom migration paths. + * + * @return array + */ + public function paths() + { + return $this->paths; + } + /** * Set the default connection name. * @@ -459,29 +459,4 @@ public function getFilesystem() { return $this->files; } - - /** - * Set a path which contains migration files. - * - * @param string $path - */ - public function path($path) - { - $this->paths[] = $path; - } - - /** - * Get all custom migration paths. - * - * @return array - */ - public function paths() - { - return $this->paths; - } - - public function getMigrationName($path) - { - return str_replace('.php', '', basename($path)); - } }
true
Other
laravel
framework
540b1ae0a17ffc5720b678f33795422e8a152ab8.json
write integration tests for migrator
tests/Database/DatabaseMigratorIntegrationTest.php
@@ -0,0 +1,126 @@ +<?php + +use Illuminate\Filesystem\Filesystem; +use Illuminate\Database\Migrations\Migrator; +use Illuminate\Database\Capsule\Manager as DB; +use Illuminate\Database\Migrations\DatabaseMigrationRepository; + +class DatabaseMigratorIntegrationTest extends PHPUnit_Framework_TestCase +{ + protected $db; + + /** + * Bootstrap Eloquent. + * + * @return void + */ + public function setUp() + { + $this->db = $db = new DB; + + $db->addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', + ]); + + $db->setAsGlobal(); + + $this->migrator = new Migrator( + $repository = new DatabaseMigrationRepository($db->getDatabaseManager(), 'migrations'), + $db->getDatabaseManager(), + new Filesystem + ); + + $container = new Illuminate\Container\Container; + $container->instance('db', $db->getDatabaseManager()); + Illuminate\Support\Facades\Facade::setFacadeApplication($container); + + if (! $repository->repositoryExists()) { + $repository->createRepository(); + } + } + + public function tearDown() + { + Illuminate\Support\Facades\Facade::clearResolvedInstances(); + Illuminate\Support\Facades\Facade::setFacadeApplication(null); + } + + public function testBasicMigrationOfSingleFolder() + { + $this->migrator->run([__DIR__.'/migrations/one']); + $this->assertTrue($this->db->schema()->hasTable('users')); + $this->assertTrue($this->db->schema()->hasTable('password_resets')); + } + + public function testMigrationsCanBeRolledBack() + { + $this->migrator->run([__DIR__.'/migrations/one']); + $this->assertTrue($this->db->schema()->hasTable('users')); + $this->assertTrue($this->db->schema()->hasTable('password_resets')); + $this->migrator->rollback([__DIR__.'/migrations/one']); + $this->assertFalse($this->db->schema()->hasTable('users')); + $this->assertFalse($this->db->schema()->hasTable('password_resets')); + } + + public function testMigrationsCanBeReset() + { + $this->migrator->run([__DIR__.'/migrations/one']); + $this->assertTrue($this->db->schema()->hasTable('users')); + $this->assertTrue($this->db->schema()->hasTable('password_resets')); + $this->migrator->reset([__DIR__.'/migrations/one']); + $this->assertFalse($this->db->schema()->hasTable('users')); + $this->assertFalse($this->db->schema()->hasTable('password_resets')); + } + + public function testNoErrorIsThrownWhenNoOutstandingMigrationsExist() + { + $this->migrator->run([__DIR__.'/migrations/one']); + $this->assertTrue($this->db->schema()->hasTable('users')); + $this->assertTrue($this->db->schema()->hasTable('password_resets')); + $this->migrator->run([__DIR__.'/migrations/one']); + } + + public function testNoErrorIsThrownWhenNothingToRollback() + { + $this->migrator->run([__DIR__.'/migrations/one']); + $this->assertTrue($this->db->schema()->hasTable('users')); + $this->assertTrue($this->db->schema()->hasTable('password_resets')); + $this->migrator->rollback([__DIR__.'/migrations/one']); + $this->assertFalse($this->db->schema()->hasTable('users')); + $this->assertFalse($this->db->schema()->hasTable('password_resets')); + $this->migrator->rollback([__DIR__.'/migrations/one']); + } + + public function testMigrationsCanRunAcrossMultiplePaths() + { + $this->migrator->run([__DIR__.'/migrations/one', __DIR__.'/migrations/two']); + $this->assertTrue($this->db->schema()->hasTable('users')); + $this->assertTrue($this->db->schema()->hasTable('password_resets')); + $this->assertTrue($this->db->schema()->hasTable('flights')); + } + + public function testMigrationsCanBeRolledBackAcrossMultiplePaths() + { + $this->migrator->run([__DIR__.'/migrations/one', __DIR__.'/migrations/two']); + $this->assertTrue($this->db->schema()->hasTable('users')); + $this->assertTrue($this->db->schema()->hasTable('password_resets')); + $this->assertTrue($this->db->schema()->hasTable('flights')); + $this->migrator->rollback([__DIR__.'/migrations/one', __DIR__.'/migrations/two']); + $this->assertFalse($this->db->schema()->hasTable('users')); + $this->assertFalse($this->db->schema()->hasTable('password_resets')); + $this->assertFalse($this->db->schema()->hasTable('flights')); + } + + public function testMigrationsCanBeResetAcrossMultiplePaths() + { + $this->migrator->run([__DIR__.'/migrations/one', __DIR__.'/migrations/two']); + $this->assertTrue($this->db->schema()->hasTable('users')); + $this->assertTrue($this->db->schema()->hasTable('password_resets')); + $this->assertTrue($this->db->schema()->hasTable('flights')); + $this->migrator->reset([__DIR__.'/migrations/one', __DIR__.'/migrations/two']); + $this->assertFalse($this->db->schema()->hasTable('users')); + $this->assertFalse($this->db->schema()->hasTable('password_resets')); + $this->assertFalse($this->db->schema()->hasTable('flights')); + } +}
true
Other
laravel
framework
540b1ae0a17ffc5720b678f33795422e8a152ab8.json
write integration tests for migrator
tests/Database/DatabaseMigratorTest.php
@@ -1,302 +0,0 @@ -<?php - -use Mockery as m; - -class DatabaseMigratorTest extends PHPUnit_Framework_TestCase -{ - public function tearDown() - { - m::close(); - } - - public function testMigrationAreRunUpWhenOutstandingMigrationsExist() - { - $migrator = $this->getMockBuilder('Illuminate\Database\Migrations\Migrator')->setMethods(['resolve'])->setConstructorArgs([ - m::mock('Illuminate\Database\Migrations\MigrationRepositoryInterface'), - $resolver = m::mock('Illuminate\Database\ConnectionResolverInterface'), - m::mock('Illuminate\Filesystem\Filesystem'), - ])->getMock(); - $migrator->getFilesystem()->shouldReceive('glob')->once()->with(__DIR__.'/*_*.php')->andReturn([ - __DIR__.'/2_bar.php', - __DIR__.'/1_foo.php', - __DIR__.'/3_baz.php', - ]); - - $migrator->getFilesystem()->shouldReceive('requireOnce')->with(__DIR__.'/2_bar.php'); - $migrator->getFilesystem()->shouldReceive('requireOnce')->with(__DIR__.'/1_foo.php'); - $migrator->getFilesystem()->shouldReceive('requireOnce')->with(__DIR__.'/3_baz.php'); - - $migrator->getRepository()->shouldReceive('getRan')->once()->andReturn([ - '1_foo', - ]); - $migrator->getRepository()->shouldReceive('getNextBatchNumber')->once()->andReturn(1); - $migrator->getRepository()->shouldReceive('log')->once()->with('2_bar', 1); - $migrator->getRepository()->shouldReceive('log')->once()->with('3_baz', 1); - $barMock = m::mock('stdClass'); - $barMock->shouldReceive('up')->once(); - $bazMock = m::mock('stdClass'); - $bazMock->shouldReceive('up')->once(); - $migrator->expects($this->at(0))->method('resolve')->with($this->equalTo('2_bar'))->will($this->returnValue($barMock)); - $migrator->expects($this->at(1))->method('resolve')->with($this->equalTo('3_baz'))->will($this->returnValue($bazMock)); - - $migrator->run(__DIR__); - } - - public function testUpMigrationCanBePretended() - { - $migrator = $this->getMockBuilder('Illuminate\Database\Migrations\Migrator')->setMethods(['resolve'])->setConstructorArgs([ - m::mock('Illuminate\Database\Migrations\MigrationRepositoryInterface'), - $resolver = m::mock('Illuminate\Database\ConnectionResolverInterface'), - m::mock('Illuminate\Filesystem\Filesystem'), - ])->getMock(); - $migrator->getFilesystem()->shouldReceive('glob')->once()->with(__DIR__.'/*_*.php')->andReturn([ - __DIR__.'/2_bar.php', - __DIR__.'/1_foo.php', - __DIR__.'/3_baz.php', - ]); - $migrator->getFilesystem()->shouldReceive('requireOnce')->with(__DIR__.'/2_bar.php'); - $migrator->getFilesystem()->shouldReceive('requireOnce')->with(__DIR__.'/1_foo.php'); - $migrator->getFilesystem()->shouldReceive('requireOnce')->with(__DIR__.'/3_baz.php'); - $migrator->getRepository()->shouldReceive('getRan')->once()->andReturn([ - '1_foo', - ]); - $migrator->getRepository()->shouldReceive('getNextBatchNumber')->once()->andReturn(1); - - $barMock = m::mock('stdClass'); - $barMock->shouldReceive('getConnection')->once()->andReturn(null); - $barMock->shouldReceive('up')->once(); - - $bazMock = m::mock('stdClass'); - $bazMock->shouldReceive('getConnection')->once()->andReturn(null); - $bazMock->shouldReceive('up')->once(); - - $migrator->expects($this->at(0))->method('resolve')->with($this->equalTo('2_bar'))->will($this->returnValue($barMock)); - $migrator->expects($this->at(1))->method('resolve')->with($this->equalTo('3_baz'))->will($this->returnValue($bazMock)); - - $connection = m::mock('stdClass'); - $connection->shouldReceive('pretend')->with(m::type('Closure'))->andReturnUsing(function ($closure) { - $closure(); - - return [['query' => 'foo']]; - }, - function ($closure) { - $closure(); - - return [['query' => 'bar']]; - }); - $resolver->shouldReceive('connection')->with(null)->andReturn($connection); - - $migrator->run(__DIR__, ['pretend' => true]); - } - - public function testNothingIsDoneWhenNoMigrationsAreOutstanding() - { - $migrator = $this->getMockBuilder('Illuminate\Database\Migrations\Migrator')->setMethods(['resolve'])->setConstructorArgs([ - m::mock('Illuminate\Database\Migrations\MigrationRepositoryInterface'), - $resolver = m::mock('Illuminate\Database\ConnectionResolverInterface'), - m::mock('Illuminate\Filesystem\Filesystem'), - ])->getMock(); - $migrator->getFilesystem()->shouldReceive('glob')->once()->with(__DIR__.'/*_*.php')->andReturn([ - __DIR__.'/1_foo.php', - ]); - $migrator->getFilesystem()->shouldReceive('requireOnce')->with(__DIR__.'/1_foo.php'); - $migrator->getRepository()->shouldReceive('getRan')->once()->andReturn([ - '1_foo', - ]); - - $migrator->run(__DIR__); - } - - public function testLastBatchOfMigrationsCanBeRolledBack() - { - $migrator = $this->getMockBuilder('Illuminate\Database\Migrations\Migrator')->setMethods(['resolve'])->setConstructorArgs([ - m::mock('Illuminate\Database\Migrations\MigrationRepositoryInterface'), - $resolver = m::mock('Illuminate\Database\ConnectionResolverInterface'), - m::mock('Illuminate\Filesystem\Filesystem'), - ])->getMock(); - $migrator->getRepository()->shouldReceive('getLast')->once()->andReturn([ - $fooMigration = new MigratorTestMigrationStub('foo'), - $barMigration = new MigratorTestMigrationStub('bar'), - ]); - - $barMock = m::mock('stdClass'); - $barMock->shouldReceive('down')->once(); - - $fooMock = m::mock('stdClass'); - $fooMock->shouldReceive('down')->once(); - - $migrator->expects($this->at(0))->method('resolve')->with($this->equalTo('foo'))->will($this->returnValue($barMock)); - $migrator->expects($this->at(1))->method('resolve')->with($this->equalTo('bar'))->will($this->returnValue($fooMock)); - - $migrator->getRepository()->shouldReceive('delete')->once()->with($barMigration); - $migrator->getRepository()->shouldReceive('delete')->once()->with($fooMigration); - - $migrator->rollback(); - } - - public function testRollbackMigrationsCanBePretended() - { - $migrator = $this->getMockBuilder('Illuminate\Database\Migrations\Migrator')->setMethods(['resolve'])->setConstructorArgs([ - m::mock('Illuminate\Database\Migrations\MigrationRepositoryInterface'), - $resolver = m::mock('Illuminate\Database\ConnectionResolverInterface'), - m::mock('Illuminate\Filesystem\Filesystem'), - ])->getMock(); - $migrator->getRepository()->shouldReceive('getLast')->once()->andReturn([ - $fooMigration = new MigratorTestMigrationStub('foo'), - $barMigration = new MigratorTestMigrationStub('bar'), - ]); - - $barMock = m::mock('stdClass'); - $barMock->shouldReceive('getConnection')->once()->andReturn(null); - $barMock->shouldReceive('down')->once(); - - $fooMock = m::mock('stdClass'); - $fooMock->shouldReceive('getConnection')->once()->andReturn(null); - $fooMock->shouldReceive('down')->once(); - - $migrator->expects($this->at(0))->method('resolve')->with($this->equalTo('foo'))->will($this->returnValue($barMock)); - $migrator->expects($this->at(1))->method('resolve')->with($this->equalTo('bar'))->will($this->returnValue($fooMock)); - - $connection = m::mock('stdClass'); - $connection->shouldReceive('pretend')->with(m::type('Closure'))->andReturnUsing(function ($closure) { - $closure(); - - return [['query' => 'bar']]; - }, - function ($closure) { - $closure(); - - return [['query' => 'foo']]; - }); - $resolver->shouldReceive('connection')->with(null)->andReturn($connection); - - $migrator->rollback(true); - } - - public function testNothingIsRolledBackWhenNothingInRepository() - { - $migrator = $this->getMockBuilder('Illuminate\Database\Migrations\Migrator')->setMethods(['resolve'])->setConstructorArgs([ - m::mock('Illuminate\Database\Migrations\MigrationRepositoryInterface'), - $resolver = m::mock('Illuminate\Database\ConnectionResolverInterface'), - m::mock('Illuminate\Filesystem\Filesystem'), - ])->getMock(); - $migrator->getRepository()->shouldReceive('getLast')->once()->andReturn([]); - - $migrator->rollback(); - } - - public function testResettingMigrationsRollsBackAllMigrations() - { - $migrator = $this->getMockBuilder('Illuminate\Database\Migrations\Migrator')->setMethods(['resolve'])->setConstructorArgs([ - m::mock('Illuminate\Database\Migrations\MigrationRepositoryInterface'), - $resolver = m::mock('Illuminate\Database\ConnectionResolverInterface'), - m::mock('Illuminate\Filesystem\Filesystem'), - ])->getMock(); - - $fooMigration = (object) ['migration' => 'foo']; - $barMigration = (object) ['migration' => 'bar']; - $bazMigration = (object) ['migration' => 'baz']; - - $migrator->getRepository()->shouldReceive('getRan')->once()->andReturn([ - $fooMigration->migration, - $barMigration->migration, - $bazMigration->migration, - ]); - - $barMock = m::mock('stdClass'); - $barMock->shouldReceive('down')->once(); - - $fooMock = m::mock('stdClass'); - $fooMock->shouldReceive('down')->once(); - - $bazMock = m::mock('stdClass'); - $bazMock->shouldReceive('down')->once(); - - $migrator->expects($this->at(0))->method('resolve')->with($this->equalTo('baz'))->will($this->returnValue($bazMock)); - $migrator->expects($this->at(1))->method('resolve')->with($this->equalTo('bar'))->will($this->returnValue($barMock)); - $migrator->expects($this->at(2))->method('resolve')->with($this->equalTo('foo'))->will($this->returnValue($fooMock)); - - $migrator->getRepository()->shouldReceive('delete')->once()->with(m::mustBe($bazMigration)); - $migrator->getRepository()->shouldReceive('delete')->once()->with(m::mustBe($barMigration)); - $migrator->getRepository()->shouldReceive('delete')->once()->with(m::mustBe($fooMigration)); - - $migrator->reset(); - } - - public function testResetMigrationsCanBePretended() - { - $migrator = $this->getMockBuilder('Illuminate\Database\Migrations\Migrator')->setMethods(['resolve'])->setConstructorArgs([ - m::mock('Illuminate\Database\Migrations\MigrationRepositoryInterface'), - $resolver = m::mock('Illuminate\Database\ConnectionResolverInterface'), - m::mock('Illuminate\Filesystem\Filesystem'), - ])->getMock(); - - $fooMigration = (object) ['migration' => 'foo']; - $barMigration = (object) ['migration' => 'bar']; - $bazMigration = (object) ['migration' => 'baz']; - - $migrator->getRepository()->shouldReceive('getRan')->once()->andReturn([ - $fooMigration->migration, - $barMigration->migration, - $bazMigration->migration, - ]); - - $barMock = m::mock('stdClass'); - $barMock->shouldReceive('getConnection')->once()->andReturn(null); - $barMock->shouldReceive('down')->once(); - - $fooMock = m::mock('stdClass'); - $fooMock->shouldReceive('getConnection')->once()->andReturn(null); - $fooMock->shouldReceive('down')->once(); - - $bazMock = m::mock('stdClass'); - $bazMock->shouldReceive('getConnection')->once()->andReturn(null); - $bazMock->shouldReceive('down')->once(); - - $migrator->expects($this->at(0))->method('resolve')->with($this->equalTo('baz'))->will($this->returnValue($bazMock)); - $migrator->expects($this->at(1))->method('resolve')->with($this->equalTo('bar'))->will($this->returnValue($barMock)); - $migrator->expects($this->at(2))->method('resolve')->with($this->equalTo('foo'))->will($this->returnValue($fooMock)); - - $connection = m::mock('stdClass'); - $connection->shouldReceive('pretend')->with(m::type('Closure'))->andReturnUsing(function ($closure) { - $closure(); - - return [['query' => 'baz']]; - }, - function ($closure) { - $closure(); - - return [['query' => 'bar']]; - }, - function ($closure) { - $closure(); - - return [['query' => 'foo']]; - }); - $resolver->shouldReceive('connection')->with(null)->andReturn($connection); - - $migrator->reset(true); - } - - public function testNothingIsResetBackWhenNothingInRepository() - { - $migrator = $this->getMockBuilder('Illuminate\Database\Migrations\Migrator')->setMethods(['resolve'])->setConstructorArgs([ - m::mock('Illuminate\Database\Migrations\MigrationRepositoryInterface'), - $resolver = m::mock('Illuminate\Database\ConnectionResolverInterface'), - m::mock('Illuminate\Filesystem\Filesystem'), - ])->getMock(); - $migrator->getRepository()->shouldReceive('getRan')->once()->andReturn([]); - - $migrator->reset(); - } -} - -class MigratorTestMigrationStub -{ - public function __construct($migration) - { - $this->migration = $migration; - } - - public $migration; -}
true
Other
laravel
framework
540b1ae0a17ffc5720b678f33795422e8a152ab8.json
write integration tests for migrator
tests/Database/migrations/one/2016_01_01_000000_create_users_table.php
@@ -0,0 +1,35 @@ +<?php + +use Illuminate\Support\Facades\Schema; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Database\Migrations\Migration; + +class CreateUsersTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('users', function (Blueprint $table) { + $table->increments('id'); + $table->string('name'); + $table->string('email')->unique(); + $table->string('password'); + $table->rememberToken(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('users'); + } +}
true
Other
laravel
framework
540b1ae0a17ffc5720b678f33795422e8a152ab8.json
write integration tests for migrator
tests/Database/migrations/one/2016_01_01_100000_create_password_resets_table.php
@@ -0,0 +1,32 @@ +<?php + +use Illuminate\Support\Facades\Schema; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Database\Migrations\Migration; + +class CreatePasswordResetsTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('password_resets', function (Blueprint $table) { + $table->string('email')->index(); + $table->string('token')->index(); + $table->timestamp('created_at'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('password_resets'); + } +}
true
Other
laravel
framework
540b1ae0a17ffc5720b678f33795422e8a152ab8.json
write integration tests for migrator
tests/Database/migrations/two/2016_01_01_200000_create_flights_table.php
@@ -0,0 +1,31 @@ +<?php + +use Illuminate\Support\Facades\Schema; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Database\Migrations\Migration; + +class CreateFlightsTable extends Migration +{ + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::create('flights', function ($table) { + $table->increments('id'); + $table->string('name'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::drop('flights'); + } +}
true
Other
laravel
framework
1c1f2f2d87876be86fc1ce98efa0f2bc1a3670f6.json
Fix postgres Schema::hastable (#13008)
src/Illuminate/Database/PostgresConnection.php
@@ -2,13 +2,28 @@ namespace Illuminate\Database; +use Illuminate\Database\Schema\PostgresBuilder; use Doctrine\DBAL\Driver\PDOPgSql\Driver as DoctrineDriver; use Illuminate\Database\Query\Processors\PostgresProcessor; use Illuminate\Database\Query\Grammars\PostgresGrammar as QueryGrammar; use Illuminate\Database\Schema\Grammars\PostgresGrammar as SchemaGrammar; class PostgresConnection extends Connection { + /** + * Get a schema builder instance for the connection. + * + * @return \Illuminate\Database\Schema\PostgresBuilder + */ + public function getSchemaBuilder() + { + if (is_null($this->schemaGrammar)) { + $this->useDefaultSchemaGrammar(); + } + + return new PostgresBuilder($this); + } + /** * Get the default query grammar instance. *
true
Other
laravel
framework
1c1f2f2d87876be86fc1ce98efa0f2bc1a3670f6.json
Fix postgres Schema::hastable (#13008)
src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php
@@ -28,7 +28,7 @@ class PostgresGrammar extends Grammar */ public function compileTableExists() { - return 'select * from information_schema.tables where table_name = ?'; + return 'select * from information_schema.tables where table_schema = ? and table_name = ?'; } /**
true
Other
laravel
framework
1c1f2f2d87876be86fc1ce98efa0f2bc1a3670f6.json
Fix postgres Schema::hastable (#13008)
src/Illuminate/Database/Schema/PostgresBuilder.php
@@ -0,0 +1,23 @@ +<?php + +namespace Illuminate\Database\Schema; + +class PostgresBuilder extends Builder +{ + /** + * Determine if the given table exists. + * + * @param string $table + * @return bool + */ + public function hasTable($table) + { + $sql = $this->grammar->compileTableExists(); + + $schema = $this->connection->getConfig('schema'); + + $table = $this->connection->getTablePrefix().$table; + + return count($this->connection->select($sql, [$schema, $table])) > 0; + } +}
true
Other
laravel
framework
e53d363ea783e7307d9e068cd003078a03021b16.json
Add catch exception when connect and get job
src/Illuminate/Queue/Worker.php
@@ -143,17 +143,24 @@ protected function daemonShouldRun() */ public function pop($connectionName, $queue = null, $delay = 0, $sleep = 3, $maxTries = 0) { - $connection = $this->manager->connection($connectionName); + try { + $connection = $this->manager->connection($connectionName); - $job = $this->getNextJob($connection, $queue); + $job = $this->getNextJob($connection, $queue); - // If we're able to pull a job off of the stack, we will process it and - // then immediately return back out. If there is no job on the queue - // we will "sleep" the worker for the specified number of seconds. - if (! is_null($job)) { - return $this->process( - $this->manager->getName($connectionName), $job, $maxTries, $delay - ); + // If we're able to pull a job off of the stack, we will process it and + // then immediately return back out. If there is no job on the queue + // we will "sleep" the worker for the specified number of seconds. + if (! is_null($job)) { + return $this->process( + $this->manager->getName($connectionName), $job, $maxTries, $delay + ); + } + } catch (Exception $e) { + if ($this->exceptions) { + $this->exceptions->report($e); + } + $this->stop(); } $this->sleep($sleep);
false
Other
laravel
framework
d48e5312550e7df050f63c5040c3043cde96f369.json
fix bugs. add tests
src/Illuminate/Database/Connection.php
@@ -343,12 +343,12 @@ public function select($query, $bindings = [], $useReadPdo = true) } /** - * Run a select statement against the database and returns a cursor. + * Run a select statement against the database and returns a generator. * * @param string $query * @param array $bindings * @param bool $useReadPdo - * @return mixed + * @return \Generator */ public function cursor($query, $bindings = [], $useReadPdo = true) { @@ -357,16 +357,19 @@ public function cursor($query, $bindings = [], $useReadPdo = true) return []; } - // For select statements, we'll simply execute the query and return an array - // of the database result set. Each element in the array will be a single - // row from the database table, and will either be an array or objects. $statement = $this->getPdoForSelect($useReadPdo)->prepare($query); - $statement->setFetchMode($me->getFetchMode()); + if ($me->getFetchMode() === PDO::FETCH_CLASS) { + $statement->setFetchMode($me->getFetchMode(), 'StdClass'); + } else { + $statement->setFetchMode($me->getFetchMode()); + } $statement->execute($me->prepareBindings($bindings)); - return $statement; + while ($record = $statement->fetch()) { + yield $record; + } }); }
true
Other
laravel
framework
d48e5312550e7df050f63c5040c3043cde96f369.json
fix bugs. add tests
src/Illuminate/Database/Eloquent/Builder.php
@@ -304,29 +304,16 @@ public function firstOrFail($columns = ['*']) } /** - * Traverses through a result set using a cursor. + * Get a generator for the given query. * - * @return void + * @return \Generator */ public function cursor() { $builder = $this->applyScopes(); - $statement = $builder->query->cursor(); - - while ($row = $statement->fetch()) { - // On each result set, we will pass them to the callback and then let the - // developer take care of everything within the callback, which allows us to - // keep the memory low for spinning through large result sets for working. - - if ($row === false) { - return; - } - - //Hydrate and yield an Eloquent Model - $model = $this->model->newFromBuilder($row); - - yield $model; + foreach ($builder->query->cursor() as $record) { + yield $this->model->newFromBuilder($record); } }
true
Other
laravel
framework
d48e5312550e7df050f63c5040c3043cde96f369.json
fix bugs. add tests
src/Illuminate/Database/Query/Builder.php
@@ -1693,15 +1693,19 @@ protected function restoreFieldsForCount() } /** - * Execute the query as a "select" statement. + * Get a generator for the given query. * - * @return mixed + * @return \Generator */ public function cursor() { - $results = $this->connection->cursor($this->toSql(), $this->getBindings(), ! $this->useWritePdo); + if (is_null($this->columns)) { + $this->columns = ['*']; + } - return $results; + return $this->connection->cursor( + $this->toSql(), $this->getBindings(), ! $this->useWritePdo + ); } /**
true
Other
laravel
framework
d48e5312550e7df050f63c5040c3043cde96f369.json
fix bugs. add tests
tests/Database/DatabaseEloquentIntegrationTest.php
@@ -112,6 +112,21 @@ public function testBasicModelRetrieval() $collection = EloquentTestUser::find([1, 2, 3]); $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $collection); $this->assertEquals(2, $collection->count()); + + $models = EloquentTestUser::where('id', 1)->cursor(); + foreach ($models as $model) { + $this->assertEquals(1, $model->id); + } + + $records = DB::table('users')->where('id', 1)->cursor(); + foreach ($records as $record) { + $this->assertEquals(1, $record->id); + } + + $records = DB::cursor('select * from users where id = ?', [1]); + foreach ($records as $record) { + $this->assertEquals(1, $record->id); + } } public function testBasicModelCollectionRetrieval()
true
Other
laravel
framework
473910ce1932173a5ed700b9b50dd9f0a6696e0f.json
use injectoin for consistency
src/Illuminate/Foundation/Http/Middleware/Authorize.php
@@ -4,9 +4,17 @@ use Closure; use Illuminate\Contracts\Auth\Access\Gate; +use Illuminate\Contracts\Auth\Factory as AuthFactory; class Authorize { + /** + * The authentication factory instance. + * + * @var \Illuminate\Contracts\Auth\Factory + */ + protected $auth; + /** * The gate instance. * @@ -17,11 +25,13 @@ class Authorize /** * Create a new middleware instance. * + * @param \Illuminate\Contracts\Auth\Factory $auth * @param \Illuminate\Contracts\Auth\Access\Gate $gate * @return void */ - public function __construct(Gate $gate) + public function __construct(AuthFactory $auth, Gate $gate) { + $this->auth = $auth; $this->gate = $gate; } @@ -38,7 +48,7 @@ public function __construct(Gate $gate) */ public function handle($request, Closure $next, $ability, $model = null) { - auth()->authenticate(); + $this->auth->authenticate(); $this->gate->authorize($ability, $this->getGateArguments($request, $model));
true
Other
laravel
framework
473910ce1932173a5ed700b9b50dd9f0a6696e0f.json
use injectoin for consistency
tests/Foundation/FoundationAuthorizeMiddlewareTest.php
@@ -32,7 +32,6 @@ public function setUp() $this->container->singleton(Auth::class, function () { $auth = m::mock(Auth::class); $auth->shouldReceive('authenticate')->once()->andReturn(null); - return $auth; });
true
Other
laravel
framework
33d15865502031195013ee8636731585149dd717.json
fix code style
src/Illuminate/Database/Query/Grammars/Grammar.php
@@ -842,7 +842,7 @@ public function compileSavepointRollBack($name) */ public function compileRandom() { - return "RANDOM()"; + return 'RANDOM()'; } /**
true
Other
laravel
framework
33d15865502031195013ee8636731585149dd717.json
fix code style
src/Illuminate/Database/Query/Grammars/MySqlGrammar.php
@@ -166,6 +166,6 @@ protected function wrapJsonSelector($value) */ public function compileRandom() { - return "RAND()"; + return 'RAND()'; } }
true
Other
laravel
framework
33d15865502031195013ee8636731585149dd717.json
fix code style
src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php
@@ -355,6 +355,6 @@ protected function wrapTableValuedFunction($table) */ public function compileRandom() { - return "NEWID()"; + return 'NEWID()'; } }
true
Other
laravel
framework
354a94ee6a379a4a4fa4fad0b090aea05d795fcb.json
fix code style
src/Illuminate/Database/Query/Grammars/Grammar.php
@@ -840,7 +840,8 @@ public function compileSavepointRollBack($name) * * @return string */ - public function compileRandom(){ + public function compileRandom() + { return "RANDOM()"; }
true
Other
laravel
framework
354a94ee6a379a4a4fa4fad0b090aea05d795fcb.json
fix code style
src/Illuminate/Database/Query/Grammars/MySqlGrammar.php
@@ -164,7 +164,8 @@ protected function wrapJsonSelector($value) * * @return string */ - public function compileRandom(){ + public function compileRandom() + { return "RAND()"; } }
true
Other
laravel
framework
354a94ee6a379a4a4fa4fad0b090aea05d795fcb.json
fix code style
src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php
@@ -353,7 +353,8 @@ protected function wrapTableValuedFunction($table) * * @return string */ - public function compileRandom(){ + public function compileRandom() + { return "NEWID()"; } }
true
Other
laravel
framework
9197863f0a6304afca17f0d88071bee471cbe949.json
add random() function to query builder This function adds sql statements to query to get a number of random records.
src/Illuminate/Database/Query/Builder.php
@@ -1389,6 +1389,17 @@ public function take($value) return $this->limit($value); } + /** + * Add statements to query to get one or many random records. + * + * @param int $value + * @return $this + */ + public function random($value = 1) + { + return $this->orderByRaw('RAND()')->limit($value); + } + /** * Set the limit and offset for a given page. *
false
Other
laravel
framework
9fcceb8e3febc26441be50f62910abe7a03c86bd.json
add connect_timeout:60 to MailgunTransport
src/Illuminate/Mail/Transport/MailgunTransport.php
@@ -75,6 +75,7 @@ public function send(Swift_Mime_Message $message, &$failedRecipients = null) 'message' => new PostFile('message', $message->toString()), ]; } + $options['connect_timeout'] = 60; return $this->client->post($this->url, $options); }
false
Other
laravel
framework
4abb185e5a60148676df2333fe36ed9c31f8f480.json
Add softDeletesIntegration test for withCount
tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php
@@ -461,6 +461,43 @@ public function testWhereHasWithNestedDeletedRelationshipAndWithTrashedCondition $this->assertEquals(1, count($users)); } + /** + * @group test + */ + public function testWithCountWithNestedDeletedRelationshipAndOnlyTrashedCondition() + { + $this->createUsers(); + + $abigail = SoftDeletesTestUser::where('email', 'abigailotwell@gmail.com')->first(); + $post1 = $abigail->posts()->create(['title' => 'First Title']); + $post1->delete(); + $post2 = $abigail->posts()->create(['title' => 'Second Title']); + $post3 = $abigail->posts()->create(['title' => 'Third Title']); + + $user = SoftDeletesTestUser::withCount('posts')->orderBy('postsCount', 'desc')->first(); + $this->assertEquals(2, $user->posts_count); + + $user = SoftDeletesTestUser::withCount(['posts' => function ($q) { + $q->onlyTrashed(); + }])->orderBy('postsCount', 'desc')->first(); + $this->assertEquals(1, $user->posts_count); + + $user = SoftDeletesTestUser::withCount(['posts' => function ($q) { + $q->withTrashed(); + }])->orderBy('postsCount', 'desc')->first(); + $this->assertEquals(3, $user->posts_count); + + $user = SoftDeletesTestUser::withCount(['posts' => function ($q) { + $q->withTrashed()->where('title', 'First Title'); + }])->orderBy('postsCount', 'desc')->first(); + $this->assertEquals(1, $user->posts_count); + + $user = SoftDeletesTestUser::withCount(['posts' => function ($q) { + $q->where('title', 'First Title'); + }])->orderBy('postsCount', 'desc')->first(); + $this->assertEquals(0, $user->posts_count); + } + public function testOrWhereWithSoftDeleteConstraint() { $this->createUsers();
false
Other
laravel
framework
03300b0632d1839b12139022bd0a3aa6055f6ddb.json
Add test for merged wheres in withCount
tests/Database/DatabaseEloquentBuilderTest.php
@@ -477,7 +477,7 @@ public function testWithCountAndMergedWheres() { $model = new EloquentBuilderTestModelParentStub; - $builder = $model->select('id')->withCount(['activeFoo' => function($q){ + $builder = $model->select('id')->withCount(['activeFoo' => function ($q) { $q->where('bam', '>', 'qux'); }]);
false
Other
laravel
framework
356e19914614896e0f7ec940468e24848135d552.json
Add test for merged wheres in withCount
tests/Database/DatabaseEloquentBuilderTest.php
@@ -473,6 +473,18 @@ public function testWithCountAndSelect() $this->assertEquals('select "id", (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_count" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql()); } + public function testWithCountAndMergedWheres() + { + $model = new EloquentBuilderTestModelParentStub; + + $builder = $model->select('id')->withCount(['activeFoo' => function($q){ + $q->where('bam', '>', 'qux'); + }]); + + $this->assertEquals('select "id", (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "active" = ? and "bam" > ?) as "active_foo_count" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql()); + $this->assertEquals([true, 'qux'], $builder->getBindings()); + } + public function testWithCountAndContraintsAndHaving() { $model = new EloquentBuilderTestModelParentStub; @@ -683,6 +695,11 @@ public function foo() { return $this->belongsTo('EloquentBuilderTestModelCloseRelatedStub'); } + + public function activeFoo() + { + return $this->belongsTo('EloquentBuilderTestModelCloseRelatedStub', 'foo_id')->where('active', true); + } } class EloquentBuilderTestModelCloseRelatedStub extends Illuminate\Database\Eloquent\Model
false
Other
laravel
framework
86d46309b0499cbc1b1ab8692a08c627d2e50940.json
Compare user instances in Auth tests (#13588)
tests/Auth/AuthGuardTest.php
@@ -141,7 +141,7 @@ public function testUserMethodReturnsCachedUser() $user = m::mock('Illuminate\Contracts\Auth\Authenticatable'); $mock = $this->getGuard(); $mock->setUser($user); - $this->assertEquals($user, $mock->user()); + $this->assertSame($user, $mock->user()); } public function testNullIsReturnedForUserIfNoUserFound() @@ -157,8 +157,8 @@ public function testUserIsSetToRetrievedUser() $mock->getSession()->shouldReceive('get')->once()->andReturn(1); $user = m::mock('Illuminate\Contracts\Auth\Authenticatable'); $mock->getProvider()->shouldReceive('retrieveById')->once()->with(1)->andReturn($user); - $this->assertEquals($user, $mock->user()); - $this->assertEquals($user, $mock->getUser()); + $this->assertSame($user, $mock->user()); + $this->assertSame($user, $mock->getUser()); } public function testLogoutRemovesSessionTokenAndRememberMeCookie() @@ -259,7 +259,7 @@ public function testLoginUsingIdLogsInWithUser() $guard->getProvider()->shouldReceive('retrieveById')->once()->with(10)->andReturn($user); $guard->shouldReceive('login')->once()->with($user, false); - $this->assertEquals($user, $guard->loginUsingId(10)); + $this->assertSame($user, $guard->loginUsingId(10)); } public function testLoginUsingIdFailure() @@ -282,7 +282,7 @@ public function testOnceUsingIdSetsUser() $guard->getProvider()->shouldReceive('retrieveById')->once()->with(10)->andReturn($user); $guard->shouldReceive('setUser')->once()->with($user); - $this->assertEquals($user, $guard->onceUsingId(10)); + $this->assertSame($user, $guard->onceUsingId(10)); } public function testOnceUsingIdFailure() @@ -308,7 +308,7 @@ public function testUserUsesRememberCookieIfItExists() $user->shouldReceive('getAuthIdentifier')->once()->andReturn('bar'); $guard->getSession()->shouldReceive('set')->with($guard->getName(), 'bar')->once(); $session->shouldReceive('migrate')->once(); - $this->assertEquals($user, $guard->user()); + $this->assertSame($user, $guard->user()); $this->assertTrue($guard->viaRemember()); }
false
Other
laravel
framework
001cffc9b32c764971d825ef6f9c42476d468ef3.json
Correct blank line with no tabs
src/Illuminate/Database/Query/Builder.php
@@ -1418,7 +1418,7 @@ public function forPageAfterId($perPage = 15, $lastId = 0, $column = 'id') } } } - + return $this->where($column, '>', $lastId) ->orderBy($column, 'asc') ->take($perPage);
false
Other
laravel
framework
e4eb25e527fa6696dd599f0a0cb07d07ba29b971.json
Remove blank line
src/Illuminate/Database/Query/Builder.php
@@ -1418,6 +1418,7 @@ public function forPageAfterId($perPage = 15, $lastId = 0, $column = 'id') } } } + return $this->where($column, '>', $lastId) ->orderBy($column, 'asc') ->take($perPage);
false
Other
laravel
framework
18cbc9d197dbc27ee1e502b93dcf03cf02e347fa.json
Remove blank line
src/Illuminate/Database/Query/Builder.php
@@ -1418,7 +1418,6 @@ public function forPageAfterId($perPage = 15, $lastId = 0, $column = 'id') } } } - return $this->where($column, '>', $lastId) ->orderBy($column, 'asc') ->take($perPage);
false
Other
laravel
framework
fcc9a1c231510c3e20d5a406b46211917dd53fa7.json
Remove blank line
src/Illuminate/Database/Query/Builder.php
@@ -1410,7 +1410,6 @@ public function forPage($page, $perPage = 15) */ public function forPageAfterId($perPage = 15, $lastId = 0, $column = 'id') { - // avoid duplicate orders if ($this->orders !== null) { foreach ($this->orders as $key => $order) {
false
Other
laravel
framework
a06e156348dfd932a36758ca1df5062aa4c953d5.json
Simplify join clause
src/Illuminate/Database/Query/Builder.php
@@ -335,30 +335,30 @@ public function from($table) */ public function join($table, $one, $operator = null, $two = null, $type = 'inner', $where = false) { + $join = new JoinClause($type, $table, $this); + // If the first "column" of the join is really a Closure instance the developer // is trying to build a join with a complex "on" clause containing more than // one condition, so we'll add the join and call a Closure with the query. if ($one instanceof Closure) { - $join = new JoinClause($type, $table); - call_user_func($one, $join); $this->joins[] = $join; - $this->addBinding($join->bindings, 'join'); + $this->addBinding($join->getBindings(), 'join'); } // If the column is simply a string, we can assume the join simply has a basic // "on" clause with a single condition. So we will just build the join with // this simple join clauses attached to it. There is not a join callback. else { - $join = new JoinClause($type, $table); + $method = $where ? 'where' : 'on'; - $this->joins[] = $join->on( + $this->joins[] = $join->$method( $one, $operator, $two, 'and', $where ); - $this->addBinding($join->bindings, 'join'); + $this->addBinding($join->getBindings(), 'join'); } return $this; @@ -450,7 +450,7 @@ public function crossJoin($table, $first = null, $operator = null, $second = nul return $this->join($table, $first, $operator, $second, 'cross'); } - $this->joins[] = new JoinClause('cross', $table); + $this->joins[] = new JoinClause('cross', $table, $this); return $this; }
true
Other
laravel
framework
a06e156348dfd932a36758ca1df5062aa4c953d5.json
Simplify join clause
src/Illuminate/Database/Query/Grammars/Grammar.php
@@ -3,6 +3,7 @@ namespace Illuminate\Database\Query\Grammars; use Illuminate\Database\Query\Builder; +use Illuminate\Database\Query\JoinClause; use Illuminate\Database\Grammar as BaseGrammar; class Grammar extends BaseGrammar @@ -145,92 +146,16 @@ protected function compileJoins(Builder $query, $joins) $sql = []; foreach ($joins as $join) { - $table = $this->wrapTable($join->table); - - $type = $join->type; - - // Cross joins generate a cartesian product between this first table and a joined - // table. In case the user didn't specify any "on" clauses on the join we will - // append this SQL and jump right back into the next iteration of this loop. - if ($type === 'cross' && ! $join->clauses) { - $sql[] = "cross join $table"; - - continue; - } + $conditions = $this->compileWheres($join); - // First we need to build all of the "on" clauses for the join. There may be many - // of these clauses so we will need to iterate through each one and build them - // separately, then we'll join them up into a single string when we're done. - $clauses = []; - - foreach ($join->clauses as $clause) { - $clauses[] = $this->compileJoinConstraint($clause); - } - - // Once we have constructed the clauses, we'll need to take the boolean connector - // off of the first clause as it obviously will not be required on that clause - // because it leads the rest of the clauses, thus not requiring any boolean. - $clauses[0] = $this->removeLeadingBoolean($clauses[0]); - - $clauses = implode(' ', $clauses); + $table = $this->wrapTable($join->table); - // Once we have everything ready to go, we will just concatenate all the parts to - // build the final join statement SQL for the query and we can then return the - // final clause back to the callers as a single, stringified join statement. - $sql[] = "$type join $table on $clauses"; + $sql[] = trim("{$join->type} join {$table} {$conditions}"); } return implode(' ', $sql); } - /** - * Create a join clause constraint segment. - * - * @param array $clause - * @return string - */ - protected function compileJoinConstraint(array $clause) - { - if ($clause['nested']) { - return $this->compileNestedJoinConstraint($clause); - } - - $first = $this->wrap($clause['first']); - - if ($clause['where']) { - if ($clause['operator'] === 'in' || $clause['operator'] === 'not in') { - $second = '('.implode(', ', array_fill(0, $clause['second'], '?')).')'; - } else { - $second = '?'; - } - } else { - $second = $this->wrap($clause['second']); - } - - return "{$clause['boolean']} $first {$clause['operator']} $second"; - } - - /** - * Create a nested join clause constraint segment. - * - * @param array $clause - * @return string - */ - protected function compileNestedJoinConstraint(array $clause) - { - $clauses = []; - - foreach ($clause['join']->clauses as $nestedClause) { - $clauses[] = $this->compileJoinConstraint($nestedClause); - } - - $clauses[0] = $this->removeLeadingBoolean($clauses[0]); - - $clauses = implode(' ', $clauses); - - return "{$clause['boolean']} ({$clauses})"; - } - /** * Compile the "where" portions of the query. * @@ -260,7 +185,9 @@ protected function compileWheres(Builder $query) if (count($sql) > 0) { $sql = implode(' ', $sql); - return 'where '.$this->removeLeadingBoolean($sql); + $conjunction = $query instanceof JoinClause ? 'on' : 'where'; + + return $conjunction.' '.$this->removeLeadingBoolean($sql); } return ''; @@ -277,7 +204,9 @@ protected function whereNested(Builder $query, $where) { $nested = $where['query']; - return '('.substr($this->compileWheres($nested), 6).')'; + $offset = $query instanceof JoinClause ? 3 : 6; + + return '('.substr($this->compileWheres($nested), $offset).')'; } /**
true
Other
laravel
framework
a06e156348dfd932a36758ca1df5062aa4c953d5.json
Simplify join clause
src/Illuminate/Database/Query/Grammars/PostgresGrammar.php
@@ -209,8 +209,10 @@ protected function compileUpdateJoinWheres(Builder $query) // all out then implode them. This should give us "where" like syntax after // everything has been built and then we will join it to the real wheres. foreach ($query->joins as $join) { - foreach ($join->clauses as $clause) { - $joinWheres[] = $this->compileJoinConstraint($clause); + foreach ($join->wheres as $where) { + $method = "where{$where['type']}"; + + $joinWheres[] = $where['boolean'].' '.$this->$method($query, $where); } }
true
Other
laravel
framework
a06e156348dfd932a36758ca1df5062aa4c953d5.json
Simplify join clause
src/Illuminate/Database/Query/JoinClause.php
@@ -5,7 +5,7 @@ use Closure; use InvalidArgumentException; -class JoinClause +class JoinClause extends Builder { /** * The type of join being performed. @@ -22,30 +22,29 @@ class JoinClause public $table; /** - * The "on" clauses for the join. + * The parent query builder instance. * - * @var array + * @var \Illuminate\Database\Query\Builder */ - public $clauses = []; - - /** - * The "on" bindings for the join. - * - * @var array - */ - public $bindings = []; + private $parentQuery; /** * Create a new join clause instance. * * @param string $type * @param string $table + * @param \Illuminate\Database\Query\Builder $parentQuery * @return void */ - public function __construct($type, $table) + public function __construct($type, $table, Builder $parentQuery) { $this->type = $type; $this->table = $table; + $this->parentQuery = $parentQuery; + + parent::__construct( + $parentQuery->connection, $parentQuery->grammar, $parentQuery->processor + ); } /** @@ -64,34 +63,17 @@ public function __construct($type, $table) * @param string|null $operator * @param string|null $second * @param string $boolean - * @param bool $where * @return $this * * @throws \InvalidArgumentException */ - public function on($first, $operator = null, $second = null, $boolean = 'and', $where = false) + public function on($first, $operator = null, $second = null, $boolean = 'and') { if ($first instanceof Closure) { - return $this->nest($first, $boolean); - } - - if (func_num_args() < 3) { - throw new InvalidArgumentException('Not enough arguments for the on clause.'); + return $this->whereNested($first, $boolean); } - if ($where) { - $this->bindings[] = $second; - } - - if ($where && ($operator === 'in' || $operator === 'not in') && is_array($second)) { - $second = count($second); - } - - $nested = false; - - $this->clauses[] = compact('first', 'operator', 'second', 'boolean', 'where', 'nested'); - - return $this; + return $this->whereColumn($first, $operator, $second, $boolean); } /** @@ -108,146 +90,12 @@ public function orOn($first, $operator = null, $second = null) } /** - * Add an "on where" clause to the join. + * Get a new instance of the join clause builder. * - * @param \Closure|string $first - * @param string|null $operator - * @param string|null $second - * @param string $boolean * @return \Illuminate\Database\Query\JoinClause */ - public function where($first, $operator = null, $second = null, $boolean = 'and') + public function newQuery() { - return $this->on($first, $operator, $second, $boolean, true); - } - - /** - * Add an "or on where" clause to the join. - * - * @param \Closure|string $first - * @param string|null $operator - * @param string|null $second - * @return \Illuminate\Database\Query\JoinClause - */ - public function orWhere($first, $operator = null, $second = null) - { - return $this->on($first, $operator, $second, 'or', true); - } - - /** - * Add an "on where is null" clause to the join. - * - * @param string $column - * @param string $boolean - * @return \Illuminate\Database\Query\JoinClause - */ - public function whereNull($column, $boolean = 'and') - { - return $this->on($column, 'is', new Expression('null'), $boolean, false); - } - - /** - * Add an "or on where is null" clause to the join. - * - * @param string $column - * @return \Illuminate\Database\Query\JoinClause - */ - public function orWhereNull($column) - { - return $this->whereNull($column, 'or'); - } - - /** - * Add an "on where is not null" clause to the join. - * - * @param string $column - * @param string $boolean - * @return \Illuminate\Database\Query\JoinClause - */ - public function whereNotNull($column, $boolean = 'and') - { - return $this->on($column, 'is', new Expression('not null'), $boolean, false); - } - - /** - * Add an "or on where is not null" clause to the join. - * - * @param string $column - * @return \Illuminate\Database\Query\JoinClause - */ - public function orWhereNotNull($column) - { - return $this->whereNotNull($column, 'or'); - } - - /** - * Add an "on where in (...)" clause to the join. - * - * @param string $column - * @param array $values - * @return \Illuminate\Database\Query\JoinClause - */ - public function whereIn($column, array $values) - { - return $this->on($column, 'in', $values, 'and', true); - } - - /** - * Add an "on where not in (...)" clause to the join. - * - * @param string $column - * @param array $values - * @return \Illuminate\Database\Query\JoinClause - */ - public function whereNotIn($column, array $values) - { - return $this->on($column, 'not in', $values, 'and', true); - } - - /** - * Add an "or on where in (...)" clause to the join. - * - * @param string $column - * @param array $values - * @return \Illuminate\Database\Query\JoinClause - */ - public function orWhereIn($column, array $values) - { - return $this->on($column, 'in', $values, 'or', true); - } - - /** - * Add an "or on where not in (...)" clause to the join. - * - * @param string $column - * @param array $values - * @return \Illuminate\Database\Query\JoinClause - */ - public function orWhereNotIn($column, array $values) - { - return $this->on($column, 'not in', $values, 'or', true); - } - - /** - * Add a nested where statement to the query. - * - * @param \Closure $callback - * @param string $boolean - * @return \Illuminate\Database\Query\JoinClause - */ - public function nest(Closure $callback, $boolean = 'and') - { - $join = new static($this->type, $this->table); - - $callback($join); - - if (count($join->clauses)) { - $nested = true; - - $this->clauses[] = compact('nested', 'join', 'boolean'); - $this->bindings = array_merge($this->bindings, $join->bindings); - } - - return $this; + return new static($this->type, $this->table, $this->parentQuery); } }
true
Other
laravel
framework
a06e156348dfd932a36758ca1df5062aa4c953d5.json
Simplify join clause
tests/Database/DatabaseEloquentBuilderTest.php
@@ -506,7 +506,7 @@ public function testHasWithContraintsAndJoinAndHavingInSubquery() $builder = $model->where('bar', 'baz'); $builder->whereHas('foo', function ($q) { $q->join('quuuux', function ($j) { - $j->on('quuuuux', '=', 'quuuuuux', 'and', true); + $j->where('quuuuux', '=', 'quuuuuux'); }); $q->having('bam', '>', 'qux'); })->where('quux', 'quuux');
true
Other
laravel
framework
0fecd603347b74c954d74d8b7c38658a2c344aa7.json
Fix PHPDoc collection union() return type
src/Illuminate/Support/Collection.php
@@ -557,7 +557,7 @@ public function combine($values) * Union the collection with the given items. * * @param mixed $items - * @return void + * @return static */ public function union($items) {
false
Other
laravel
framework
853300b13201f98b8149acb3992554af25e2232c.json
Add whereColumn clause
src/Illuminate/Database/Query/Builder.php
@@ -550,16 +550,17 @@ public function where($column, $operator = null, $value = null, $boolean = 'and' * * @param array $column * @param string $boolean + * @param string $method * @return $this */ - protected function addArrayOfWheres($column, $boolean) + protected function addArrayOfWheres($column, $boolean, $method = 'where') { - return $this->whereNested(function ($query) use ($column) { + return $this->whereNested(function ($query) use ($column, $method) { foreach ($column as $key => $value) { if (is_numeric($key) && is_array($value)) { - call_user_func_array([$query, 'where'], $value); + call_user_func_array([$query, $method], $value); } else { - $query->where($key, '=', $value); + $query->$method($key, '=', $value); } } }, $boolean); @@ -578,6 +579,52 @@ public function orWhere($column, $operator = null, $value = null) return $this->where($column, $operator, $value, 'or'); } + /** + * Add a "where" clause comparing two columns to the query. + * + * @param string|array $first + * @param string|null $operator + * @param string|null $second + * @param string|null $boolean + * @return \Illuminate\Database\Query\Builder|static + */ + public function whereColumn($first, $operator = null, $second = null, $boolean = 'and') + { + // If the column is an array, we will assume it is an array of key-value pairs + // and can add them each as a where clause. We will maintain the boolean we + // received when the method was called and pass it into the nested where. + if (is_array($first)) { + return $this->addArrayOfWheres($first, $boolean, 'whereColumn'); + } + + // If the given operator is not found in the list of valid operators we will + // assume that the developer is just short-cutting the '=' operators and + // we will set the operators to '=' and set the values appropriately. + if (! in_array(strtolower($operator), $this->operators, true) && + ! in_array(strtolower($operator), $this->grammar->getOperators(), true)) { + list($second, $operator) = [$operator, '=']; + } + + $type = 'Column'; + + $this->wheres[] = compact('type', 'first', 'operator', 'second', 'boolean'); + + return $this; + } + + /** + * Add an "or where" clause comparing two columns to the query. + * + * @param string|array $first + * @param string|null $operator + * @param string|null $second + * @return \Illuminate\Database\Query\Builder|static + */ + public function orWhereColumn($first, $operator = null, $second = null) + { + return $this->whereColumn($first, $operator, $second, 'or'); + } + /** * Determine if the given operator and value combination is legal. *
true
Other
laravel
framework
853300b13201f98b8149acb3992554af25e2232c.json
Add whereColumn clause
src/Illuminate/Database/Query/Grammars/Grammar.php
@@ -308,6 +308,20 @@ protected function whereBasic(Builder $query, $where) return $this->wrap($where['column']).' '.$where['operator'].' '.$value; } + /** + * Compile a where clause comparing two columns.. + * + * @param \Illuminate\Database\Query\Builder $query + * @param array $where + * @return string + */ + protected function whereColumn(Builder $query, $where) + { + $second = $this->wrap($where['second']); + + return $this->wrap($where['first']).' '.$where['operator'].' '.$second; + } + /** * Compile a "between" where clause. *
true
Other
laravel
framework
853300b13201f98b8149acb3992554af25e2232c.json
Add whereColumn clause
tests/Database/DatabaseQueryBuilderTest.php
@@ -341,6 +341,32 @@ public function testEmptyWhereNotIns() $this->assertEquals([0 => 1], $builder->getBindings()); } + public function testBasicWhereColumn() + { + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->whereColumn('first_name', 'last_name')->orWhereColumn('first_name', 'middle_name'); + $this->assertEquals('select * from "users" where "first_name" = "last_name" or "first_name" = "middle_name"', $builder->toSql()); + $this->assertEquals([], $builder->getBindings()); + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->whereColumn('updated_at', '>', 'created_at'); + $this->assertEquals('select * from "users" where "updated_at" > "created_at"', $builder->toSql()); + $this->assertEquals([], $builder->getBindings()); + } + + public function testArrayWhereColumn() + { + $conditions = [ + ['first_name', 'last_name'], + ['updated_at', '>', 'created_at'] + ]; + + $builder = $this->getBuilder(); + $builder->select('*')->from('users')->whereColumn($conditions); + $this->assertEquals('select * from "users" where ("first_name" = "last_name" and "updated_at" > "created_at")', $builder->toSql()); + $this->assertEquals([], $builder->getBindings()); + } + public function testUnions() { $builder = $this->getBuilder();
true
Other
laravel
framework
07177e94983f20d478026dc93278c05f6f18c0dd.json
fix #13527 (#13537)
src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
@@ -189,7 +189,7 @@ public function firstOrFail($columns = ['*']) return $model; } - throw new ModelNotFoundException; + throw (new ModelNotFoundException)->setModel(get_class($this->parent)); } /**
true
Other
laravel
framework
07177e94983f20d478026dc93278c05f6f18c0dd.json
fix #13527 (#13537)
src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php
@@ -244,7 +244,7 @@ public function firstOrFail($columns = ['*']) return $model; } - throw new ModelNotFoundException; + throw (new ModelNotFoundException)->setModel(get_class($this->parent)); } /**
true
Other
laravel
framework
07177e94983f20d478026dc93278c05f6f18c0dd.json
fix #13527 (#13537)
tests/Database/DatabaseEloquentBelongsToManyTest.php
@@ -335,6 +335,38 @@ public function testCreateMethodCreatesNewModelAndInsertsAttachmentRecord() $this->assertEquals($model, $relation->create(['attributes'], ['joining'])); } + public function testFindOrFailThrowsException() + { + $relation = $this->getMock('Illuminate\Database\Eloquent\Relations\BelongsToMany', ['find'], $this->getRelationArguments()); + $relation->expects($this->once())->method('find')->with('foo')->will($this->returnValue(null)); + + $this->setExpectedException(\Illuminate\Database\Eloquent\ModelNotFoundException::class); + + try { + $relation->findOrFail('foo'); + } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { + $this->assertNotEmpty($e->getModel()); + + throw $e; + } + } + + public function testFirstOrFailThrowsException() + { + $relation = $this->getMock('Illuminate\Database\Eloquent\Relations\BelongsToMany', ['first'], $this->getRelationArguments()); + $relation->expects($this->once())->method('first')->with(['id' => 'foo'])->will($this->returnValue(null)); + + $this->setExpectedException(\Illuminate\Database\Eloquent\ModelNotFoundException::class); + + try { + $relation->firstOrFail(['id' => 'foo']); + } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { + $this->assertNotEmpty($e->getModel()); + + throw $e; + } + } + public function testFindOrNewMethodFindsModel() { $relation = $this->getMock('Illuminate\Database\Eloquent\Relations\BelongsToMany', ['find'], $this->getRelationArguments());
true
Other
laravel
framework
07177e94983f20d478026dc93278c05f6f18c0dd.json
fix #13527 (#13537)
tests/Database/DatabaseEloquentHasManyThroughTest.php
@@ -138,6 +138,38 @@ public function testFirstMethod() $this->assertEquals('first', $relation->first()); } + public function testFindOrFailThrowsException() + { + $relation = $this->getMock('Illuminate\Database\Eloquent\Relations\HasManyThrough', ['find'], $this->getRelationArguments()); + $relation->expects($this->once())->method('find')->with('foo')->will($this->returnValue(null)); + + $this->setExpectedException(\Illuminate\Database\Eloquent\ModelNotFoundException::class); + + try { + $relation->findOrFail('foo'); + } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { + $this->assertNotEmpty($e->getModel()); + + throw $e; + } + } + + public function testFirstOrFailThrowsException() + { + $relation = $this->getMock('Illuminate\Database\Eloquent\Relations\HasManyThrough', ['first'], $this->getRelationArguments()); + $relation->expects($this->once())->method('first')->with(['id' => 'foo'])->will($this->returnValue(null)); + + $this->setExpectedException(\Illuminate\Database\Eloquent\ModelNotFoundException::class); + + try { + $relation->firstOrFail(['id' => 'foo']); + } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) { + $this->assertNotEmpty($e->getModel()); + + throw $e; + } + } + public function testFindMethod() { $relation = m::mock('Illuminate\Database\Eloquent\Relations\HasManyThrough[first]', $this->getRelationArguments());
true
Other
laravel
framework
615ba9a6ead3608ef2cf6956c85a6fc71ac37e57.json
Allow multiple folders for migrations
src/Illuminate/Database/Console/Migrations/MigrateCommand.php
@@ -66,12 +66,14 @@ public function fire() // we will use the path relative to the root of this installation folder // so that migrations may be run for any path within the applications. if (! is_null($path = $this->input->getOption('path'))) { - $path = $this->laravel->basePath().'/'.$path; + $paths[] = $this->laravel->basePath().'/'.$path; } else { - $path = $this->getMigrationPath(); + $paths[] = $this->getMigrationPath(); + + $paths = array_merge($paths, $this->migrator->paths()); } - $this->migrator->run($path, [ + $this->migrator->run($paths, [ 'pretend' => $pretend, 'step' => $this->input->getOption('step'), ]);
true