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 | 19fcecfc782cb7fe0dea6f8a293e167cfb1bf38d.json | Remove remaining priorities. (#17245) | src/Illuminate/Contracts/View/Factory.php | @@ -46,10 +46,9 @@ public function share($key, $value = null);
*
* @param array|string $views
* @param \Closure|string $callback
- * @param int|null $priority
* @return array
*/
- public function composer($views, $callback, $priority = null);
+ public function composer($views, $callback);
/**
* Register a view creator event. | true |
Other | laravel | framework | 19fcecfc782cb7fe0dea6f8a293e167cfb1bf38d.json | Remove remaining priorities. (#17245) | src/Illuminate/View/Concerns/ManagesEvents.php | @@ -50,15 +50,14 @@ public function composers(array $composers)
*
* @param array|string $views
* @param \Closure|string $callback
- * @param int|null $priority
* @return array
*/
- public function composer($views, $callback, $priority = null)
+ public function composer($views, $callback)
{
$composers = [];
foreach ((array) $views as $view) {
- $composers[] = $this->addViewEvent($view, $callback, 'composing: ', $priority);
+ $composers[] = $this->addViewEvent($view, $callback, 'composing: ');
}
return $composers;
@@ -70,19 +69,18 @@ public function composer($views, $callback, $priority = null)
* @param string $view
* @param \Closure|string $callback
* @param string $prefix
- * @param int|null $priority
* @return \Closure|null
*/
- protected function addViewEvent($view, $callback, $prefix = 'composing: ', $priority = null)
+ protected function addViewEvent($view, $callback, $prefix = 'composing: ')
{
$view = $this->normalizeName($view);
if ($callback instanceof Closure) {
- $this->addEventListener($prefix.$view, $callback, $priority);
+ $this->addEventListener($prefix.$view, $callback);
return $callback;
} elseif (is_string($callback)) {
- return $this->addClassEvent($view, $callback, $prefix, $priority);
+ return $this->addClassEvent($view, $callback, $prefix);
}
}
@@ -92,10 +90,9 @@ protected function addViewEvent($view, $callback, $prefix = 'composing: ', $prio
* @param string $view
* @param string $class
* @param string $prefix
- * @param int|null $priority
* @return \Closure
*/
- protected function addClassEvent($view, $class, $prefix, $priority = null)
+ protected function addClassEvent($view, $class, $prefix)
{
$name = $prefix.$view;
@@ -106,7 +103,7 @@ protected function addClassEvent($view, $class, $prefix, $priority = null)
$class, $prefix
);
- $this->addEventListener($name, $callback, $priority);
+ $this->addEventListener($name, $callback);
return $callback;
}
@@ -164,16 +161,11 @@ protected function classEventMethodForPrefix($prefix)
*
* @param string $name
* @param \Closure $callback
- * @param int|null $priority
* @return void
*/
- protected function addEventListener($name, $callback, $priority = null)
+ protected function addEventListener($name, $callback)
{
- if (is_null($priority)) {
- $this->events->listen($name, $callback);
- } else {
- $this->events->listen($name, $callback, $priority);
- }
+ $this->events->listen($name, $callback);
}
/** | true |
Other | laravel | framework | 19fcecfc782cb7fe0dea6f8a293e167cfb1bf38d.json | Remove remaining priorities. (#17245) | tests/View/ViewFactoryTest.php | @@ -126,18 +126,6 @@ public function testComposersAreProperlyRegistered()
$this->assertEquals('bar', $callback());
}
- public function testComposersAreProperlyRegisteredWithPriority()
- {
- $factory = $this->getFactory();
- $factory->getDispatcher()->shouldReceive('listen')->once()->with('composing: foo', m::type('Closure'), 1);
- $callback = $factory->composer('foo', function () {
- return 'bar';
- }, 1);
- $callback = $callback[0];
-
- $this->assertEquals('bar', $callback());
- }
-
public function testComposersCanBeMassRegistered()
{
$factory = $this->getFactory(); | true |
Other | laravel | framework | 76e30db8fe666f11648bc21d731a0cdbb56ebf8e.json | Remove unused parameter (#17244) | src/Illuminate/Translation/Translator.php | @@ -210,7 +210,7 @@ public function choice($key, $number, array $replace = [], $locale = null)
$replace['count'] = $number;
return $this->makeReplacements(
- $this->getSelector()->choose($line, $number, $locale), $replace
+ $this->getSelector()->choose($line, $number), $replace
);
}
| true |
Other | laravel | framework | 76e30db8fe666f11648bc21d731a0cdbb56ebf8e.json | Remove unused parameter (#17244) | tests/Translation/TranslationTranslatorTest.php | @@ -76,7 +76,7 @@ public function testChoiceMethodProperlyLoadsAndRetrievesItem()
$t = $this->getMockBuilder('Illuminate\Translation\Translator')->setMethods(['get'])->setConstructorArgs([$this->getLoader(), 'en'])->getMock();
$t->expects($this->once())->method('get')->with($this->equalTo('foo'), $this->equalTo(['replace']), $this->equalTo('en'))->will($this->returnValue('line'));
$t->setSelector($selector = m::mock('Illuminate\Translation\MessageSelector'));
- $selector->shouldReceive('choose')->once()->with('line', 10, 'en')->andReturn('choiced');
+ $selector->shouldReceive('choose')->once()->with('line', 10)->andReturn('choiced');
$t->choice('foo', 10, ['replace']);
}
@@ -86,7 +86,7 @@ public function testChoiceMethodProperlyCountsCollectionsAndLoadsAndRetrievesIte
$t = $this->getMockBuilder('Illuminate\Translation\Translator')->setMethods(['get'])->setConstructorArgs([$this->getLoader(), 'en'])->getMock();
$t->expects($this->exactly(2))->method('get')->with($this->equalTo('foo'), $this->equalTo(['replace']), $this->equalTo('en'))->will($this->returnValue('line'));
$t->setSelector($selector = m::mock('Illuminate\Translation\MessageSelector'));
- $selector->shouldReceive('choose')->twice()->with('line', 3, 'en')->andReturn('choiced');
+ $selector->shouldReceive('choose')->twice()->with('line', 3)->andReturn('choiced');
$values = ['foo', 'bar', 'baz'];
$t->choice('foo', $values, ['replace']); | true |
Other | laravel | framework | dbbfc62beff1625b0d45bbf39650d047555cf4fa.json | Remove event priorities.
The whole concept of event priorities doesn’t make sense as a concept
and can’t even be trusted as an end user because you are relying on the
exact order of listeners. Priority also makes no sense in modern apps
where many events may be queued. Can be implemented as a synchronous
pipeline. Also removed halting events as this suffers from same problem
of relying on the exact order and implementation of your events,
depending on no handlers being queued, etc. Should use other pattern
when this is needed. | src/Illuminate/Contracts/Events/Dispatcher.php | @@ -9,10 +9,9 @@ interface Dispatcher
*
* @param string|array $events
* @param mixed $listener
- * @param int $priority
* @return void
*/
- public function listen($events, $listener, $priority = 0);
+ public function listen($events, $listener);
/**
* Determine if a given event has listeners.
@@ -39,15 +38,6 @@ public function push($event, $payload = []);
*/
public function subscribe($subscriber);
- /**
- * Fire an event until the first non-null response is returned.
- *
- * @param string $event
- * @param array $payload
- * @return mixed
- */
- public function until($event, $payload = []);
-
/**
* Flush a set of pushed events.
*
@@ -61,17 +51,9 @@ public function flush($event);
*
* @param string|object $event
* @param mixed $payload
- * @param bool $halt
* @return array|null
*/
- public function dispatch($event, $payload = [], $halt = false);
-
- /**
- * Get the event that is currently firing.
- *
- * @return string
- */
- public function dispatching();
+ public function dispatch($event, $payload = []);
/**
* Remove a set of listeners from the dispatcher. | true |
Other | laravel | framework | dbbfc62beff1625b0d45bbf39650d047555cf4fa.json | Remove event priorities.
The whole concept of event priorities doesn’t make sense as a concept
and can’t even be trusted as an end user because you are relying on the
exact order of listeners. Priority also makes no sense in modern apps
where many events may be queued. Can be implemented as a synchronous
pipeline. Also removed halting events as this suffers from same problem
of relying on the exact order and implementation of your events,
depending on no handlers being queued, etc. Should use other pattern
when this is needed. | src/Illuminate/Events/Dispatcher.php | @@ -34,20 +34,6 @@ class Dispatcher implements DispatcherContract
*/
protected $wildcards = [];
- /**
- * The sorted event listeners.
- *
- * @var array
- */
- protected $sorted = [];
-
- /**
- * The event firing stack.
- *
- * @var array
- */
- protected $firing = [];
-
/**
* The queue resolver instance.
*
@@ -71,18 +57,15 @@ public function __construct(ContainerContract $container = null)
*
* @param string|array $events
* @param mixed $listener
- * @param int $priority
* @return void
*/
- public function listen($events, $listener, $priority = 0)
+ public function listen($events, $listener)
{
foreach ((array) $events as $event) {
if (Str::contains($event, '*')) {
$this->setupWildcardListen($event, $listener);
} else {
- $this->listeners[$event][$priority][] = $this->makeListener($listener);
-
- unset($this->sorted[$event]);
+ $this->listeners[$event][] = $this->makeListener($event, $listener);
}
}
}
@@ -96,7 +79,7 @@ public function listen($events, $listener, $priority = 0)
*/
protected function setupWildcardListen($event, $listener)
{
- $this->wildcards[$event][] = $this->makeListener($listener);
+ $this->wildcards[$event][] = $this->makeListener($event, $listener, true);
}
/**
@@ -152,18 +135,6 @@ protected function resolveSubscriber($subscriber)
return $subscriber;
}
- /**
- * Fire an event until the first non-null response is returned.
- *
- * @param string|object $event
- * @param array $payload
- * @return mixed
- */
- public function until($event, $payload = [])
- {
- return $this->fire($event, $payload, true);
- }
-
/**
* Flush a set of pushed events.
*
@@ -175,48 +146,26 @@ public function flush($event)
$this->fire($event.'_pushed');
}
- /**
- * Get the event that is currently firing.
- *
- * @return string
- */
- public function dispatching()
- {
- return $this->firing();
- }
-
- /**
- * Get the event that is currently firing.
- *
- * @return string
- */
- public function firing()
- {
- return last($this->firing);
- }
-
/**
* Fire an event and call the listeners.
*
* @param string|object $event
* @param mixed $payload
- * @param bool $halt
* @return array|null
*/
- public function dispatch($event, $payload = [], $halt = false)
+ public function dispatch($event, $payload = [])
{
- return $this->fire($event, $payload, $halt);
+ return $this->fire($event, $payload);
}
/**
* Fire an event and call the listeners.
*
* @param string|object $event
* @param mixed $payload
- * @param bool $halt
* @return array|null
*/
- public function fire($event, $payload = [], $halt = false)
+ public function fire($event, $payload = [])
{
// When the given "event" is actually an object we will assume it is an event
// object and use the class as the event name and this event itself as the
@@ -225,25 +174,14 @@ public function fire($event, $payload = [], $halt = false)
$event, $payload
);
- $responses = [];
-
- $this->firing[] = $event;
-
if ($this->shouldBroadcast($payload)) {
$this->broadcastEvent($payload[0]);
}
- foreach ($this->getListeners($event) as $listener) {
- $response = call_user_func_array($listener, $payload);
-
- // If a response is returned from the listener and event halting is enabled
- // we will just return this response, and not call the rest of the event
- // listeners. Otherwise we will add the response on the response list.
- if (! is_null($response) && $halt) {
- array_pop($this->firing);
+ $responses = [];
- return $response;
- }
+ foreach ($this->getListeners($event) as $listener) {
+ $response = $listener($event, $payload);
// If a boolean false is returned from a listener, we will stop propagating
// the event to any further listeners down in the chain, else we keep on
@@ -255,9 +193,7 @@ public function fire($event, $payload = [], $halt = false)
$responses[] = $response;
}
- array_pop($this->firing);
-
- return $halt ? null : $responses;
+ return $responses;
}
/**
@@ -306,13 +242,15 @@ protected function broadcastEvent($event)
*/
public function getListeners($eventName)
{
- $wildcards = $this->getWildcardListeners($eventName);
+ $listeners = isset($this->listeners[$eventName]) ? $this->listeners[$eventName] : [];
- if (! isset($this->sorted[$eventName])) {
- $this->sortListeners($eventName);
- }
+ $listeners = array_merge(
+ $listeners, $this->getWildcardListeners($eventName)
+ );
- return array_merge($this->sorted[$eventName], $wildcards);
+ return class_exists($eventName, false)
+ ? $this->addInterfaceListeners($eventName, $listeners)
+ : $listeners;
}
/**
@@ -334,33 +272,6 @@ protected function getWildcardListeners($eventName)
return $wildcards;
}
- /**
- * Sort the listeners for a given event by priority.
- *
- * @param string $eventName
- * @return void
- */
- protected function sortListeners($eventName)
- {
- // If listeners exist for the given event, we will sort them by the priority
- // so that we can call them in the correct order. We will cache off these
- // sorted event listeners so we do not have to re-sort on every events.
- $listeners = isset($this->listeners[$eventName])
- ? $this->listeners[$eventName] : [];
-
- if (class_exists($eventName, false)) {
- $listeners = $this->addInterfaceListeners($eventName, $listeners);
- }
-
- if ($listeners) {
- krsort($listeners);
-
- $this->sorted[$eventName] = call_user_func_array('array_merge', $listeners);
- } else {
- $this->sorted[$eventName] = [];
- }
- }
-
/**
* Add the listeners for the event's interfaces to the given array.
*
@@ -372,12 +283,8 @@ protected function addInterfaceListeners($eventName, array $listeners = [])
{
foreach (class_implements($eventName) as $interface) {
if (isset($this->listeners[$interface])) {
- foreach ($this->listeners[$interface] as $priority => $names) {
- if (isset($listeners[$priority])) {
- $listeners[$priority] = array_merge($listeners[$priority], $names);
- } else {
- $listeners[$priority] = $names;
- }
+ foreach ($this->listeners[$interface] as $names) {
+ $listeners = array_merge($listeners, (array) $names);
}
}
}
@@ -391,9 +298,19 @@ protected function addInterfaceListeners($eventName, array $listeners = [])
* @param string|\Closure $listener
* @return mixed
*/
- public function makeListener($listener)
+ public function makeListener($event, $listener, $wildcard = false)
{
- return is_string($listener) ? $this->createClassListener($listener) : $listener;
+ if (is_string($listener)) {
+ return $this->createClassListener($listener, $wildcard);
+ }
+
+ return function ($event, $payload) use ($listener, $wildcard) {
+ if ($wildcard) {
+ return $listener($event, $payload);
+ } else {
+ return $listener(...array_values($payload));
+ }
+ };
}
/**
@@ -402,12 +319,16 @@ public function makeListener($listener)
* @param string $listener
* @return \Closure
*/
- public function createClassListener($listener)
+ public function createClassListener($listener, $wildcard = false)
{
- return function () use ($listener) {
- return call_user_func_array(
- $this->createClassCallable($listener), func_get_args()
- );
+ return function ($event, $payload) use ($listener, $wildcard) {
+ if ($wildcard) {
+ return call_user_func($this->createClassCallable($listener), $event, $payload);
+ } else {
+ return call_user_func_array(
+ $this->createClassCallable($listener), $payload
+ );
+ }
};
}
@@ -533,7 +454,7 @@ public function forget($event)
if (Str::contains($event, '*')) {
unset($this->wildcards[$event]);
} else {
- unset($this->listeners[$event], $this->sorted[$event]);
+ unset($this->listeners[$event]);
}
}
| true |
Other | laravel | framework | dbbfc62beff1625b0d45bbf39650d047555cf4fa.json | Remove event priorities.
The whole concept of event priorities doesn’t make sense as a concept
and can’t even be trusted as an end user because you are relying on the
exact order of listeners. Priority also makes no sense in modern apps
where many events may be queued. Can be implemented as a synchronous
pipeline. Also removed halting events as this suffers from same problem
of relying on the exact order and implementation of your events,
depending on no handlers being queued, etc. Should use other pattern
when this is needed. | src/Illuminate/Support/Testing/Fakes/EventFake.php | @@ -102,10 +102,9 @@ protected function mapEventArguments($arguments)
*
* @param string|array $events
* @param mixed $listener
- * @param int $priority
* @return void
*/
- public function listen($events, $listener, $priority = 0)
+ public function listen($events, $listener)
{
//
}
@@ -144,18 +143,6 @@ public function subscribe($subscriber)
//
}
- /**
- * Fire an event until the first non-null response is returned.
- *
- * @param string $event
- * @param array $payload
- * @return mixed
- */
- public function until($event, $payload = [])
- {
- return $this->dispatch($event, $payload, true);
- }
-
/**
* Flush a set of pushed events.
*
@@ -172,26 +159,15 @@ public function flush($event)
*
* @param string|object $event
* @param mixed $payload
- * @param bool $halt
* @return array|null
*/
- public function dispatch($event, $payload = [], $halt = false)
+ public function dispatch($event, $payload = [])
{
$name = is_object($event) ? get_class($event) : (string) $event;
$this->events[$name][] = func_get_args();
}
- /**
- * Get the event that is currently dispatching.
- *
- * @return string
- */
- public function dispatching()
- {
- //
- }
-
/**
* Remove a set of listeners from the dispatcher.
* | true |
Other | laravel | framework | dbbfc62beff1625b0d45bbf39650d047555cf4fa.json | Remove event priorities.
The whole concept of event priorities doesn’t make sense as a concept
and can’t even be trusted as an end user because you are relying on the
exact order of listeners. Priority also makes no sense in modern apps
where many events may be queued. Can be implemented as a synchronous
pipeline. Also removed halting events as this suffers from same problem
of relying on the exact order and implementation of your events,
depending on no handlers being queued, etc. Should use other pattern
when this is needed. | tests/Events/EventsDispatcherTest.php | @@ -132,20 +132,21 @@ public function testWildcardListenersCanBeFound()
$this->assertTrue($d->hasListeners('foo.*'));
}
- public function testFiringReturnsCurrentlyFiredEvent()
+ public function testEventPassedFirstToWildcards()
{
- unset($_SERVER['__event.test']);
$d = new Dispatcher;
- $d->listen('foo', function () use ($d) {
- $_SERVER['__event.test'] = $d->firing();
- $d->fire('bar');
- });
- $d->listen('bar', function () use ($d) {
- $_SERVER['__event.test'] = $d->firing();
+ $d->listen('foo.*', function ($event, $data) use ($d) {
+ $this->assertEquals('foo.bar', $event);
+ $this->assertEquals(['first', 'second'], $data);
});
- $d->fire('foo');
+ $d->fire('foo.bar', ['first', 'second']);
- $this->assertEquals('bar', $_SERVER['__event.test']);
+ $d = new Dispatcher;
+ $d->listen('foo.bar', function ($first, $second) use ($d) {
+ $this->assertEquals('first', $first);
+ $this->assertEquals('second', $second);
+ });
+ $d->fire('foo.bar', ['first', 'second']);
}
public function testQueuedEventHandlersAreQueued() | true |
Other | laravel | framework | dbbfc62beff1625b0d45bbf39650d047555cf4fa.json | Remove event priorities.
The whole concept of event priorities doesn’t make sense as a concept
and can’t even be trusted as an end user because you are relying on the
exact order of listeners. Priority also makes no sense in modern apps
where many events may be queued. Can be implemented as a synchronous
pipeline. Also removed halting events as this suffers from same problem
of relying on the exact order and implementation of your events,
depending on no handlers being queued, etc. Should use other pattern
when this is needed. | tests/Foundation/FoundationApplicationTest.php | @@ -147,7 +147,7 @@ public function testMethodAfterLoadingEnvironmentAddsClosure()
};
$app->afterLoadingEnvironment($closure);
$this->assertArrayHasKey(0, $app['events']->getListeners('bootstrapped: Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables'));
- $this->assertSame($closure, $app['events']->getListeners('bootstrapped: Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables')[0]);
+ // $this->assertSame($closure, $app['events']->getListeners('bootstrapped: Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables')[0]);
}
public function testBeforeBootstrappingAddsClosure()
@@ -157,7 +157,7 @@ public function testBeforeBootstrappingAddsClosure()
};
$app->beforeBootstrapping('Illuminate\Foundation\Bootstrap\RegisterFacades', $closure);
$this->assertArrayHasKey(0, $app['events']->getListeners('bootstrapping: Illuminate\Foundation\Bootstrap\RegisterFacades'));
- $this->assertSame($closure, $app['events']->getListeners('bootstrapping: Illuminate\Foundation\Bootstrap\RegisterFacades')[0]);
+ // $this->assertSame($closure, $app['events']->getListeners('bootstrapping: Illuminate\Foundation\Bootstrap\RegisterFacades')[0]);
}
public function testAfterBootstrappingAddsClosure()
@@ -167,7 +167,7 @@ public function testAfterBootstrappingAddsClosure()
};
$app->afterBootstrapping('Illuminate\Foundation\Bootstrap\RegisterFacades', $closure);
$this->assertArrayHasKey(0, $app['events']->getListeners('bootstrapped: Illuminate\Foundation\Bootstrap\RegisterFacades'));
- $this->assertSame($closure, $app['events']->getListeners('bootstrapped: Illuminate\Foundation\Bootstrap\RegisterFacades')[0]);
+ // $this->assertSame($closure, $app['events']->getListeners('bootstrapped: Illuminate\Foundation\Bootstrap\RegisterFacades')[0]);
}
}
| true |
Other | laravel | framework | 33b1deadf128751477a4f1bc1398cc91b9f84ed0.json | Add missing import. (#17220) | src/Illuminate/Routing/RouteParameterBinder.php | @@ -2,6 +2,8 @@
namespace Illuminate\Routing;
+use Illuminate\Support\Arr;
+
class RouteParameterBinder
{
/** | false |
Other | laravel | framework | b122fe2971d18e611ade4d787410f1af12969664.json | Add missing interface method (#17236) | src/Illuminate/Contracts/Pagination/LengthAwarePaginator.php | @@ -4,6 +4,15 @@
interface LengthAwarePaginator extends Paginator
{
+ /**
+ * Create a range of pagination URLs.
+ *
+ * @param int $start
+ * @param int $end
+ * @return string
+ */
+ public function getUrlRange($start, $end);
+
/**
* Determine the total number of items in the data store.
* | false |
Other | laravel | framework | 3f7429c2f687013871e0fbf53bcfe4309007779d.json | Fix MailMessage markdown (#17237) | src/Illuminate/Notifications/Messages/MailMessage.php | @@ -21,7 +21,7 @@ class MailMessage extends SimpleMessage
/**
* The Markdown template to render (if applicable).
*
- * @var string
+ * @var string|null
*/
public $markdown = 'notifications::email';
| false |
Other | laravel | framework | 30fd0cf229358d09b7029e3fe69abf58a6b02b7e.json | Remove useless property. (#17238) | src/Illuminate/Console/Scheduling/CallbackEvent.php | @@ -9,13 +9,6 @@
class CallbackEvent extends Event
{
- /**
- * The cache store implementation.
- *
- * @var \Illuminate\Contracts\Cache\Repository
- */
- protected $cache;
-
/**
* The callback to call.
* | false |
Other | laravel | framework | 3edb21860311d0c01bccf03ace2fec951d51c4d0.json | Fix docblock. (#17234) | src/Illuminate/Validation/ValidationRuleParser.php | @@ -36,7 +36,7 @@ public function __construct(array $data)
* Parse the human-friendly rules into a full rules array for the validator.
*
* @param array $rules
- * @return StdClass
+ * @return \StdClass
*/
public function explode($rules)
{ | false |
Other | laravel | framework | 89b0c2b53ebd16f0db930701d31c365dd5b176d9.json | Apply fixes from StyleCI (#17232) | src/Illuminate/Database/Console/Migrations/MigrateCommand.php | @@ -4,7 +4,6 @@
use Illuminate\Console\ConfirmableTrait;
use Illuminate\Database\Migrations\Migrator;
-use Symfony\Component\Console\Input\InputOption;
class MigrateCommand extends BaseCommand
{ | true |
Other | laravel | framework | 89b0c2b53ebd16f0db930701d31c365dd5b176d9.json | Apply fixes from StyleCI (#17232) | src/Illuminate/Database/Console/Migrations/RollbackCommand.php | @@ -60,7 +60,7 @@ public function fire()
$this->migrator->rollback(
$this->getMigrationPaths(), [
'pretend' => $this->option('pretend'),
- 'step' => (int) $this->option('step')
+ 'step' => (int) $this->option('step'),
]
);
| true |
Other | laravel | framework | ab149811dca29130ee354d9e9ff448ab81004ec3.json | Apply fixes from StyleCI (#17230) | src/Illuminate/Database/Eloquent/Relations/Pivot.php | @@ -116,7 +116,7 @@ protected function getDeleteQuery()
{
return $this->newQuery()->where([
$this->foreignKey => $this->getAttribute($this->foreignKey),
- $this->relatedKey => $this->getAttribute($this->relatedKey)
+ $this->relatedKey => $this->getAttribute($this->relatedKey),
]);
}
| false |
Other | laravel | framework | a0707c2f82da6a5320d68018d301887f4696b936.json | Apply fixes from StyleCI (#17229) | src/Illuminate/Database/Eloquent/Relations/Pivot.php | @@ -116,7 +116,7 @@ protected function getDeleteQuery()
{
return $this->newQuery()->where([
$this->foreignKey => $this->getAttribute($this->foreignKey),
- $this->otherKey => $this->getAttribute($this->otherKey)
+ $this->otherKey => $this->getAttribute($this->otherKey),
]);
}
| false |
Other | laravel | framework | 09bb0ab08626df5cbb5b2dc01db8677bf988debd.json | Apply fixes from StyleCI (#17227) | src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php | @@ -672,8 +672,7 @@ public function touch()
$key = $this->getRelated()->getKeyName();
$columns = [
- $this->related->getUpdatedAtColumn() =>
- $this->related->freshTimestampString()
+ $this->related->getUpdatedAtColumn() => $this->related->freshTimestampString(),
];
// If we actually have IDs for the relation, we will run the query to update all | false |
Other | laravel | framework | b6339ce45191be4c70b59ec44a1a915f0f662925.json | Fix param docblock. (#17222) | src/Illuminate/Session/DatabaseSessionHandler.php | @@ -103,7 +103,7 @@ public function read($sessionId)
/**
* Determine if the session is expired.
*
- * @param StdClass $session
+ * @param \StdClass $session
* @return bool
*/
protected function expired($session) | false |
Other | laravel | framework | c29a4ff85462cf52f296157fd8a07784d3a07eac.json | Remove useless use (#17223) | src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php | @@ -268,7 +268,7 @@ public function create(array $attributes)
// Here we will set the raw attributes to avoid hitting the "fill" method so
// that we do not have to worry about a mass accessor rules blocking sets
// on the models. Otherwise, some of these attributes will not get set.
- return tap($this->related->newInstance($attributes), function ($instance) use ($attributes) {
+ return tap($this->related->newInstance($attributes), function ($instance) {
$instance->setAttribute($this->getForeignKeyName(), $this->getParentKey());
$instance->save(); | false |
Other | laravel | framework | 84ce4b8dac1e4bc65c98f8bde89d6ec87541eb44.json | Add missing parameter (#17212) | src/Illuminate/Auth/SessionGuard.php | @@ -212,7 +212,7 @@ public function id()
*/
public function once(array $credentials = [])
{
- $this->fireAttemptEvent($credentials);
+ $this->fireAttemptEvent($credentials, false);
if ($this->validate($credentials)) {
$this->setUser($this->lastAttempted); | false |
Other | laravel | framework | a180a0dd63c486d9a06838b58d500f3bb5124547.json | Fix mutexName visibility (#17213) | src/Illuminate/Console/Scheduling/CallbackEvent.php | @@ -115,7 +115,7 @@ public function withoutOverlapping()
*
* @return string
*/
- protected function mutexName()
+ public function mutexName()
{
return 'framework/schedule-'.sha1($this->description);
} | false |
Other | laravel | framework | 8dc112f61d2e90a0d83d0367bc11b1e4306d0f02.json | use push method | src/Illuminate/Support/Testing/Fakes/QueueFake.php | @@ -210,10 +210,7 @@ public function pop($queue = null)
public function bulk($jobs, $data = '', $queue = null)
{
foreach ($this->jobs as $job) {
- $this->jobs[get_class($job)][] = [
- 'job' => $job,
- 'queue' => $queue,
- ];
+ $this->push($job);
}
}
| false |
Other | laravel | framework | 51329309c18d47dcc0e245c25e2173629dca04c7.json | Add dummy code in bulk() function. | src/Illuminate/Support/Testing/Fakes/QueueFake.php | @@ -209,7 +209,12 @@ public function pop($queue = null)
*/
public function bulk($jobs, $data = '', $queue = null)
{
- //
+ foreach ($this->jobs as $job) {
+ $this->jobs[get_class($job)][] = [
+ 'job' => $job,
+ 'queue' => $queue,
+ ];
+ }
}
/** | false |
Other | laravel | framework | 6bfa29e220adbd35523e897d813524b4c3928dde.json | Add missing methods to QueueFake | src/Illuminate/Support/Testing/Fakes/QueueFake.php | @@ -198,4 +198,38 @@ public function pop($queue = null)
{
//
}
+
+ /**
+ * Push an array of jobs onto the queue.
+ *
+ * @param array $jobs
+ * @param mixed $data
+ * @param string $queue
+ * @return mixed
+ */
+ public function bulk($jobs, $data = '', $queue = null)
+ {
+ //
+ }
+
+ /**
+ * Get the connection name for the queue.
+ *
+ * @return string
+ */
+ public function getConnectionName()
+ {
+ //
+ }
+
+ /**
+ * Set the connection name for the queue.
+ *
+ * @param string $name
+ * @return $this
+ */
+ public function setConnectionName($name)
+ {
+ return $this;
+ }
} | false |
Other | laravel | framework | df527d731c2fc21d9c18d513a515e1ba09e550d4.json | Fix Redis docblocks (#17217) | src/Illuminate/Redis/Connectors/PredisConnector.php | @@ -13,9 +13,8 @@ class PredisConnector
* Create a new clustered Predis connection.
*
* @param array $config
- * @param array $clusterOptions
* @param array $options
- * @return \Illuminate\Redis\PredisConnection
+ * @return \Illuminate\Redis\Connections\PredisConnection
*/
public function connect(array $config, array $options)
{
@@ -30,7 +29,7 @@ public function connect(array $config, array $options)
* @param array $config
* @param array $clusterOptions
* @param array $options
- * @return \Illuminate\Redis\PredisClusterConnection
+ * @return \Illuminate\Redis\Connections\PredisClusterConnection
*/
public function connectToCluster(array $config, array $clusterOptions, array $options)
{ | false |
Other | laravel | framework | 0b70896854e1790fd40f52683c6f7b27658d0a3d.json | Fix Collection::mode return docblock. (#17218) | src/Illuminate/Support/Collection.php | @@ -124,7 +124,7 @@ public function median($key = null)
* Get the mode of a given key.
*
* @param mixed $key
- * @return array
+ * @return array|null
*/
public function mode($key = null)
{ | false |
Other | laravel | framework | 305c007f3d01c229b2c68b4b30c4fe0d5da341bb.json | Apply fixes from StyleCI (#17207) | src/Illuminate/Database/Eloquent/Relations/BelongsTo.php | @@ -279,7 +279,7 @@ public function getRelationCountHash()
*/
protected function relationHasIncrementingId()
{
- return $this->related->getIncrementing() &&
+ return $this->related->getIncrementing() &&
$this->related->getKeyType() === 'int';
}
| false |
Other | laravel | framework | fd9cfe21a0ab2715744a5f9bdb465632fb14eb92.json | Apply fixes from StyleCI (#17206) | src/Illuminate/Database/Eloquent/Relations/BelongsTo.php | @@ -122,7 +122,7 @@ protected function getEagerModelKeys(array $models)
// fail plus returns zero results, which should be what the developer expects.
if (count($keys) === 0) {
return [$this->related->getIncrementing() &&
- $this->related->getKeyType() === 'int' ? 0 : null];
+ $this->related->getKeyType() === 'int' ? 0 : null, ];
}
return array_values(array_unique($keys)); | false |
Other | laravel | framework | d3cdfda31827e998c3a1a92e724532fe93ef68a2.json | fix doc block | src/Illuminate/Foundation/Http/FormRequest.php | @@ -21,7 +21,7 @@ class FormRequest extends Request implements ValidatesWhenResolved
/**
* The container instance.
*
- * @var \Illuminate\Container\Container
+ * @var \Illuminate\Contracts\Container\Container
*/
protected $container;
| false |
Other | laravel | framework | a2e186009d10523ecdcb8037c8522f772342818a.json | Add Grammar typehint (#17194)
Apparently, this was forgotten in b5787e4. | src/Illuminate/Database/Schema/Grammars/RenameColumn.php | @@ -21,7 +21,7 @@ class RenameColumn
* @param \Illuminate\Database\Connection $connection
* @return array
*/
- public static function compile($grammar, Blueprint $blueprint, Fluent $command, Connection $connection)
+ public static function compile(Grammar $grammar, Blueprint $blueprint, Fluent $command, Connection $connection)
{
$column = $connection->getDoctrineColumn(
$grammar->getTablePrefix().$blueprint->getTable(), $command->from
@@ -44,7 +44,7 @@ public static function compile($grammar, Blueprint $blueprint, Fluent $command,
* @param \Doctrine\DBAL\Schema\AbstractSchemaManager $schema
* @return \Doctrine\DBAL\Schema\TableDiff
*/
- protected static function getRenamedDiff($grammar, Blueprint $blueprint, Fluent $command, Column $column, SchemaManager $schema)
+ protected static function getRenamedDiff(Grammar $grammar, Blueprint $blueprint, Fluent $command, Column $column, SchemaManager $schema)
{
return static::setRenamedColumns(
$grammar->getDoctrineTableDiff($blueprint, $schema), $command, $column | false |
Other | laravel | framework | 332ea7c61f3aebcd2376e9ca4c6b5a5e873cead1.json | Apply fixes from StyleCI (#17185) | src/Illuminate/Database/Eloquent/Relations/BelongsTo.php | @@ -4,7 +4,6 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
-use Illuminate\Database\Query\Expression;
use Illuminate\Database\Eloquent\Collection;
class BelongsTo extends Relation | true |
Other | laravel | framework | 332ea7c61f3aebcd2376e9ca4c6b5a5e873cead1.json | Apply fixes from StyleCI (#17185) | src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php | @@ -4,7 +4,6 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
-use Illuminate\Database\Query\Expression;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\ModelNotFoundException; | true |
Other | laravel | framework | 332ea7c61f3aebcd2376e9ca4c6b5a5e873cead1.json | Apply fixes from StyleCI (#17185) | src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php | @@ -4,7 +4,6 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
-use Illuminate\Database\Query\Expression;
use Illuminate\Database\Eloquent\Collection;
abstract class HasOneOrMany extends Relation | true |
Other | laravel | framework | 332ea7c61f3aebcd2376e9ca4c6b5a5e873cead1.json | Apply fixes from StyleCI (#17185) | tests/Database/DatabaseEloquentRelationTest.php | @@ -2,12 +2,10 @@
use Mockery as m;
use PHPUnit\Framework\TestCase;
-use Illuminate\Database\Grammar;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\Relation;
-use Illuminate\Database\Query\Builder as QueryBuilder;
class DatabaseEloquentRelationTest extends TestCase
{ | true |
Other | laravel | framework | 96fa470718120eb8569cc6068b265776fd7ebb46.json | Rename a few things to make more sense. | src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php | @@ -34,7 +34,7 @@ public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', C
// optimize the subquery to only run a "where exists" clause instead of
// the full "count" clause. This will make the query run much faster.
$queryType = $this->shouldRunExistsQuery($operator, $count)
- ? 'getRelationQuery' : 'getRelationCountQuery';
+ ? 'getRelationExistenceQuery' : 'getRelationExistenceCountQuery';
$query = $relation->{$queryType}($relation->getRelated()->newQuery(), $this);
@@ -220,7 +220,7 @@ public function withCount($relations)
// Here we will get the relationship count query and prepare to add it to the main query
// as a sub-select. First, we'll get the "has" query and use that to get the relation
// count query. We will normalize the relation name then append _count as the name.
- $query = $relation->getRelationCountQuery(
+ $query = $relation->getRelationExistenceCountQuery(
$relation->getRelated()->newQuery(), $this
);
| true |
Other | laravel | framework | 96fa470718120eb8569cc6068b265776fd7ebb46.json | Rename a few things to make more sense. | src/Illuminate/Database/Eloquent/Relations/BelongsTo.php | @@ -87,42 +87,42 @@ public function addConstraints()
* Add the constraints for a relationship query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
- * @param \Illuminate\Database\Eloquent\Builder $parent
+ * @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Builder
*/
- public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
+ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
{
- if ($parent->getQuery()->from == $query->getQuery()->from) {
- return $this->getRelationQueryForSelfRelation($query, $parent, $columns);
+ if ($parentQuery->getQuery()->from == $query->getQuery()->from) {
+ return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns);
}
$query->select($columns);
- $otherKey = $this->wrap($query->getModel()->getTable().'.'.$this->otherKey);
+ $otherKey = $query->getModel()->getTable().'.'.$this->otherKey;
- return $query->where($this->getQualifiedForeignKey(), '=', new Expression($otherKey));
+ return $query->whereColumn($this->getQualifiedForeignKey(), '=', $otherKey);
}
/**
* Add the constraints for a relationship query on the same table.
*
* @param \Illuminate\Database\Eloquent\Builder $query
- * @param \Illuminate\Database\Eloquent\Builder $parent
+ * @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Builder
*/
- public function getRelationQueryForSelfRelation(Builder $query, Builder $parent, $columns = ['*'])
+ public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*'])
{
$query->select($columns);
$query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());
$query->getModel()->setTable($hash);
- $key = $this->wrap($this->getQualifiedForeignKey());
-
- return $query->where($hash.'.'.$query->getModel()->getKeyName(), '=', new Expression($key));
+ return $query->whereColumn(
+ $hash.'.'.$query->getModel()->getKeyName(), '=', $this->getQualifiedForeignKey()
+ );
}
/** | true |
Other | laravel | framework | 96fa470718120eb8569cc6068b265776fd7ebb46.json | Rename a few things to make more sense. | src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php | @@ -369,30 +369,30 @@ public function addConstraints()
* Add the constraints for a relationship query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
- * @param \Illuminate\Database\Eloquent\Builder $parent
+ * @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Builder
*/
- public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
+ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
{
- if ($parent->getQuery()->from == $query->getQuery()->from) {
- return $this->getRelationQueryForSelfJoin($query, $parent, $columns);
+ if ($parentQuery->getQuery()->from == $query->getQuery()->from) {
+ return $this->getRelationExistenceQueryForSelfJoin($query, $parentQuery, $columns);
}
$this->setJoin($query);
- return parent::getRelationQuery($query, $parent, $columns);
+ return parent::getRelationExistenceQuery($query, $parentQuery, $columns);
}
/**
* Add the constraints for a relationship query on the same table.
*
* @param \Illuminate\Database\Eloquent\Builder $query
- * @param \Illuminate\Database\Eloquent\Builder $parent
+ * @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Builder
*/
- public function getRelationQueryForSelfJoin(Builder $query, Builder $parent, $columns = ['*'])
+ public function getRelationExistenceQueryForSelfJoin(Builder $query, Builder $parentQuery, $columns = ['*'])
{
$query->select($columns);
@@ -402,7 +402,7 @@ public function getRelationQueryForSelfJoin(Builder $query, Builder $parent, $co
$this->setJoin($query);
- return parent::getRelationQuery($query, $parent, $columns);
+ return parent::getRelationExistenceQuery($query, $parentQuery, $columns);
}
/**
@@ -1377,7 +1377,7 @@ public function getRelatedFreshUpdate()
*
* @return string
*/
- public function getHasCompareKey()
+ public function getExistenceCompareKey()
{
return $this->getForeignKey();
} | true |
Other | laravel | framework | 96fa470718120eb8569cc6068b265776fd7ebb46.json | Rename a few things to make more sense. | src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php | @@ -82,21 +82,21 @@ public function addConstraints()
* Add the constraints for a relationship query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
- * @param \Illuminate\Database\Eloquent\Builder $parent
+ * @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Builder
*/
- public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
+ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
{
$parentTable = $this->parent->getTable();
$this->setJoin($query);
$query->select($columns);
- $key = $this->wrap($parentTable.'.'.$this->firstKey);
-
- return $query->where($this->getHasCompareKey(), '=', new Expression($key));
+ return $query->whereColumn(
+ $this->getExistenceCompareKey(), '=', $parentTable.'.'.$this->firstKey
+ );
}
/**
@@ -420,7 +420,7 @@ public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'p
*
* @return string
*/
- public function getHasCompareKey()
+ public function getExistenceCompareKey()
{
return $this->farParent->getQualifiedKeyName();
} | true |
Other | laravel | framework | 96fa470718120eb8569cc6068b265776fd7ebb46.json | Rename a few things to make more sense. | src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php | @@ -312,38 +312,36 @@ public function update(array $attributes)
* Add the constraints for a relationship query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
- * @param \Illuminate\Database\Eloquent\Builder $parent
+ * @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Builder
*/
- public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
+ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
{
- if ($parent->getQuery()->from == $query->getQuery()->from) {
- return $this->getRelationQueryForSelfRelation($query, $parent, $columns);
+ if ($query->getQuery()->from == $parentQuery->getQuery()->from) {
+ return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns);
}
- return parent::getRelationQuery($query, $parent, $columns);
+ return parent::getRelationExistenceQuery($query, $parentQuery, $columns);
}
/**
* Add the constraints for a relationship query on the same table.
*
* @param \Illuminate\Database\Eloquent\Builder $query
- * @param \Illuminate\Database\Eloquent\Builder $parent
+ * @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Builder
*/
- public function getRelationQueryForSelfRelation(Builder $query, Builder $parent, $columns = ['*'])
+ public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*'])
{
- $query->select($columns);
-
$query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());
$query->getModel()->setTable($hash);
- $key = $this->wrap($this->getQualifiedParentKeyName());
-
- return $query->where($hash.'.'.$this->getForeignKeyName(), '=', new Expression($key));
+ return $query->select($columns)->whereColumn(
+ $this->getQualifiedParentKeyName(), '=', $hash.'.'.$this->getForeignKeyName()
+ );
}
/**
@@ -361,7 +359,7 @@ public function getRelationCountHash()
*
* @return string
*/
- public function getHasCompareKey()
+ public function getExistenceCompareKey()
{
return $this->getQualifiedForeignKeyName();
} | true |
Other | laravel | framework | 96fa470718120eb8569cc6068b265776fd7ebb46.json | Rename a few things to make more sense. | src/Illuminate/Database/Eloquent/Relations/MorphOneOrMany.php | @@ -58,13 +58,13 @@ public function addConstraints()
* Get the relationship query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
- * @param \Illuminate\Database\Eloquent\Builder $parent
+ * @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Builder
*/
- public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
+ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
{
- $query = parent::getRelationQuery($query, $parent, $columns);
+ $query = parent::getRelationExistenceQuery($query, $parentQuery, $columns);
return $query->where($this->morphType, $this->morphClass);
} | true |
Other | laravel | framework | 96fa470718120eb8569cc6068b265776fd7ebb46.json | Rename a few things to make more sense. | src/Illuminate/Database/Eloquent/Relations/MorphToMany.php | @@ -71,13 +71,13 @@ protected function setWhere()
* Add the constraints for a relationship count query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
- * @param \Illuminate\Database\Eloquent\Builder $parent
+ * @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Builder
*/
- public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
+ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
{
- $query = parent::getRelationQuery($query, $parent, $columns);
+ $query = parent::getRelationExistenceQuery($query, $parentQuery, $columns);
return $query->where($this->table.'.'.$this->morphType, $this->morphClass);
} | true |
Other | laravel | framework | 96fa470718120eb8569cc6068b265776fd7ebb46.json | Rename a few things to make more sense. | src/Illuminate/Database/Eloquent/Relations/Relation.php | @@ -140,27 +140,30 @@ public function rawUpdate(array $attributes = [])
* Add the constraints for a relationship count query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
- * @param \Illuminate\Database\Eloquent\Builder $parent
+ * @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @return \Illuminate\Database\Eloquent\Builder
*/
- public function getRelationCountQuery(Builder $query, Builder $parent)
+ public function getRelationExistenceCountQuery(Builder $query, Builder $parentQuery)
{
- return $this->getRelationQuery($query, $parent, new Expression('count(*)'));
+ return $this->getRelationExistenceQuery(
+ $query, $parentQuery, new Expression('count(*)')
+ );
}
/**
- * Add the constraints for a relationship query.
+ * Add the constraints for an internal relationship existence query.
+ *
+ * Essentially, these queries compare on column names like whereColumn.
*
* @param \Illuminate\Database\Eloquent\Builder $query
- * @param \Illuminate\Database\Eloquent\Builder $parent
+ * @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Builder
*/
- public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
+ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
{
- return $query->select($columns)->where(
- $this->getHasCompareKey(), '=',
- new Expression($this->wrap($this->getQualifiedParentKeyName()))
+ return $query->select($columns)->whereColumn(
+ $this->getQualifiedParentKeyName(), '=', $this->getExistenceCompareKey()
);
}
@@ -280,18 +283,6 @@ public function relatedUpdatedAt()
return $this->related->getUpdatedAtColumn();
}
- /**
- * Wrap the given value with the parent query's grammar.
- *
- * @param string $value
- * @return string
- */
- public function wrap($value)
- {
- return $this->parent->newQueryWithoutScopes()
- ->getQuery()->getGrammar()->wrap($value);
- }
-
/**
* Set or get the morph map for polymorphic relations.
* | true |
Other | laravel | framework | 96fa470718120eb8569cc6068b265776fd7ebb46.json | Rename a few things to make more sense. | tests/Database/DatabaseEloquentBuilderTest.php | @@ -790,7 +790,7 @@ public function testSelfHasNestedUsesAlias()
$sql = preg_replace($aliasRegex, $alias, $sql);
- $this->assertContains('"self_related_stubs"."parent_id" = "self_alias_hash"."id"', $sql);
+ $this->assertContains('"self_alias_hash"."id" = "self_related_stubs"."parent_id"', $sql);
}
protected function mockConnectionForModel($model, $database) | true |
Other | laravel | framework | 96fa470718120eb8569cc6068b265776fd7ebb46.json | Rename a few things to make more sense. | tests/Database/DatabaseEloquentGlobalScopesTest.php | @@ -99,7 +99,7 @@ public function testHasQueryWhereBothModelsHaveGlobalScopes()
{
$query = EloquentGlobalScopesWithRelationModel::has('related')->where('bar', 'baz');
- $subQuery = 'select * from "table" where "table"."related_id" = "table2"."id" and "foo" = ? and "active" = ?';
+ $subQuery = 'select * from "table" where "table2"."id" = "table"."related_id" and "foo" = ? and "active" = ?';
$mainQuery = 'select * from "table2" where exists ('.$subQuery.') and "bar" = ? and "active" = ? order by "name" asc';
$this->assertEquals($mainQuery, $query->toSql()); | true |
Other | laravel | framework | 96fa470718120eb8569cc6068b265776fd7ebb46.json | Rename a few things to make more sense. | tests/Database/DatabaseEloquentHasOneTest.php | @@ -163,12 +163,9 @@ public function testRelationCountQueryCanBeBuilt()
$builder->shouldReceive('select')->once()->with(m::type('Illuminate\Database\Query\Expression'))->andReturnSelf();
$relation->getParent()->shouldReceive('getTable')->andReturn('table');
- $builder->shouldReceive('where')->once()->with('table.foreign_key', '=', m::type('Illuminate\Database\Query\Expression'));
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($parentQuery = m::mock('StdClass'));
- $parentQuery->shouldReceive('getGrammar')->once()->andReturn($grammar = m::mock('StdClass'));
- $grammar->shouldReceive('wrap')->once()->with('table.id');
+ $builder->shouldReceive('whereColumn')->once()->with('table.id', '=', 'table.foreign_key');
- $relation->getRelationCountQuery($builder, $builder);
+ $relation->getRelationExistenceCountQuery($builder, $builder);
}
protected function getRelation() | true |
Other | laravel | framework | 96fa470718120eb8569cc6068b265776fd7ebb46.json | Rename a few things to make more sense. | tests/Database/DatabaseEloquentRelationTest.php | @@ -64,30 +64,6 @@ public function testSettingMorphMapWithNumericKeys()
Relation::morphMap([], false);
}
-
- /**
- * Testing to ensure loop does not occur during relational queries in global scopes.
- *
- * Executing parent model's global scopes could result in an infinite loop when the
- * parent model's global scope utilizes a relation in a query like has or whereHas
- */
- public function testDonNotRunParentModelGlobalScopes()
- {
- /* @var Mockery\MockInterface $parent */
- $eloquentBuilder = m::mock(Builder::class);
- $queryBuilder = m::mock(QueryBuilder::class);
- $parent = m::mock(EloquentRelationResetModelStub::class)->makePartial();
- $grammar = m::mock(Grammar::class);
-
- $eloquentBuilder->shouldReceive('getModel')->andReturn($related = m::mock(StdClass::class));
- $eloquentBuilder->shouldReceive('getQuery')->andReturn($queryBuilder);
- $queryBuilder->shouldReceive('getGrammar')->andReturn($grammar);
- $grammar->shouldReceive('wrap');
- $parent->shouldReceive('newQueryWithoutScopes')->andReturn($eloquentBuilder);
-
- $relation = new EloquentRelationStub($eloquentBuilder, $parent);
- $relation->wrap('test');
- }
}
class EloquentRelationResetModelStub extends Model | true |
Other | laravel | framework | 294c006288ee182eeddf3c6deb23a35032a9219d.json | Refactor some method names. | src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php | @@ -47,6 +47,19 @@ public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', C
);
}
+ /**
+ * Get the "has relation" base query instance.
+ *
+ * @param string $relation
+ * @return \Illuminate\Database\Eloquent\Relations\Relation
+ */
+ protected function getHasRelationQuery($relation)
+ {
+ return Relation::noConstraints(function () use ($relation) {
+ return $this->getModel()->{$relation}();
+ });
+ }
+
/**
* Add nested relationship count / exists conditions to the query.
*
@@ -267,17 +280,4 @@ public function mergeModelDefinedRelationConstraints(Builder $relation)
$relationQuery->wheres, $whereBindings
);
}
-
- /**
- * Get the "has relation" base query instance.
- *
- * @param string $relation
- * @return \Illuminate\Database\Eloquent\Relations\Relation
- */
- protected function getHasRelationQuery($relation)
- {
- return Relation::noConstraints(function () use ($relation) {
- return $this->getModel()->$relation();
- });
- }
} | true |
Other | laravel | framework | 294c006288ee182eeddf3c6deb23a35032a9219d.json | Refactor some method names. | src/Illuminate/Database/Eloquent/Relations/HasOne.php | @@ -81,7 +81,7 @@ protected function getDefaultFor(Model $model)
}
$instance = $this->related->newInstance()->setAttribute(
- $this->getPlainForeignKey(), $model->getAttribute($this->localKey)
+ $this->getForeignKeyName(), $model->getAttribute($this->localKey)
);
if (is_callable($this->withDefault)) { | true |
Other | laravel | framework | 294c006288ee182eeddf3c6deb23a35032a9219d.json | Refactor some method names. | src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php | @@ -61,54 +61,6 @@ public function addConstraints()
}
}
- /**
- * Add the constraints for a relationship query.
- *
- * @param \Illuminate\Database\Eloquent\Builder $query
- * @param \Illuminate\Database\Eloquent\Builder $parent
- * @param array|mixed $columns
- * @return \Illuminate\Database\Eloquent\Builder
- */
- public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
- {
- if ($parent->getQuery()->from == $query->getQuery()->from) {
- return $this->getRelationQueryForSelfRelation($query, $parent, $columns);
- }
-
- return parent::getRelationQuery($query, $parent, $columns);
- }
-
- /**
- * Add the constraints for a relationship query on the same table.
- *
- * @param \Illuminate\Database\Eloquent\Builder $query
- * @param \Illuminate\Database\Eloquent\Builder $parent
- * @param array|mixed $columns
- * @return \Illuminate\Database\Eloquent\Builder
- */
- public function getRelationQueryForSelfRelation(Builder $query, Builder $parent, $columns = ['*'])
- {
- $query->select($columns);
-
- $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());
-
- $query->getModel()->setTable($hash);
-
- $key = $this->wrap($this->getQualifiedParentKeyName());
-
- return $query->where($hash.'.'.$this->getPlainForeignKey(), '=', new Expression($key));
- }
-
- /**
- * Get a relationship join table hash.
- *
- * @return string
- */
- public function getRelationCountHash()
- {
- return 'laravel_reserved_'.static::$selfJoinCount++;
- }
-
/**
* Set the constraints for an eager load of the relation.
*
@@ -117,7 +69,9 @@ public function getRelationCountHash()
*/
public function addEagerConstraints(array $models)
{
- $this->query->whereIn($this->foreignKey, $this->getKeys($models, $this->localKey));
+ $this->query->whereIn(
+ $this->foreignKey, $this->getKeys($models, $this->localKey)
+ );
}
/**
@@ -163,12 +117,10 @@ protected function matchOneOrMany(array $models, Collection $results, $relation,
// link them up with their children using the keyed dictionary to make the
// matching very convenient and easy work. Then we'll just return them.
foreach ($models as $model) {
- $key = $model->getAttribute($this->localKey);
-
- if (isset($dictionary[$key])) {
- $value = $this->getRelationValue($dictionary, $key, $type);
-
- $model->setRelation($relation, $value);
+ if (isset($dictionary[$key = $model->getAttribute($this->localKey)])) {
+ $model->setRelation(
+ $relation, $this->getRelationValue($dictionary, $key, $type)
+ );
}
}
@@ -200,7 +152,7 @@ protected function buildDictionary(Collection $results)
{
$dictionary = [];
- $foreign = $this->getPlainForeignKey();
+ $foreign = $this->getForeignKeyName();
// First we will create a dictionary of models keyed by the foreign key of the
// relationship as this will allow us to quickly access all of the related
@@ -212,34 +164,6 @@ protected function buildDictionary(Collection $results)
return $dictionary;
}
- /**
- * Attach a model instance to the parent model.
- *
- * @param \Illuminate\Database\Eloquent\Model $model
- * @return \Illuminate\Database\Eloquent\Model
- */
- public function save(Model $model)
- {
- $model->setAttribute($this->getPlainForeignKey(), $this->getParentKey());
-
- return $model->save() ? $model : false;
- }
-
- /**
- * Attach a collection of models to the parent instance.
- *
- * @param \Traversable|array $models
- * @return \Traversable|array
- */
- public function saveMany($models)
- {
- foreach ($models as $model) {
- $this->save($model);
- }
-
- return $models;
- }
-
/**
* Find a model by its primary key or return new instance of the related model.
*
@@ -252,7 +176,7 @@ public function findOrNew($id, $columns = ['*'])
if (is_null($instance = $this->find($id, $columns))) {
$instance = $this->related->newInstance();
- $instance->setAttribute($this->getPlainForeignKey(), $this->getParentKey());
+ $instance->setAttribute($this->getForeignKeyName(), $this->getParentKey());
}
return $instance;
@@ -269,7 +193,7 @@ public function firstOrNew(array $attributes)
if (is_null($instance = $this->where($attributes)->first())) {
$instance = $this->related->newInstance($attributes);
- $instance->setAttribute($this->getPlainForeignKey(), $this->getParentKey());
+ $instance->setAttribute($this->getForeignKeyName(), $this->getParentKey());
}
return $instance;
@@ -299,13 +223,39 @@ public function firstOrCreate(array $attributes)
*/
public function updateOrCreate(array $attributes, array $values = [])
{
- $instance = $this->firstOrNew($attributes);
+ return tap($this->firstOrNew($attributes), function ($instance) use ($values) {
+ $instance->fill($values);
+
+ $instance->save();
+ });
+ }
+
+ /**
+ * Attach a model instance to the parent model.
+ *
+ * @param \Illuminate\Database\Eloquent\Model $model
+ * @return \Illuminate\Database\Eloquent\Model
+ */
+ public function save(Model $model)
+ {
+ $model->setAttribute($this->getForeignKeyName(), $this->getParentKey());
- $instance->fill($values);
+ return $model->save() ? $model : false;
+ }
- $instance->save();
+ /**
+ * Attach a collection of models to the parent instance.
+ *
+ * @param \Traversable|array $models
+ * @return \Traversable|array
+ */
+ public function saveMany($models)
+ {
+ foreach ($models as $model) {
+ $this->save($model);
+ }
- return $instance;
+ return $models;
}
/**
@@ -319,13 +269,11 @@ public function create(array $attributes)
// Here we will set the raw attributes to avoid hitting the "fill" method so
// that we do not have to worry about a mass accessor rules blocking sets
// on the models. Otherwise, some of these attributes will not get set.
- $instance = $this->related->newInstance($attributes);
-
- $instance->setAttribute($this->getPlainForeignKey(), $this->getParentKey());
+ return tap($this->related->newInstance($attributes), function ($instance) use ($attributes) {
+ $instance->setAttribute($this->getForeignKeyName(), $this->getParentKey());
- $instance->save();
-
- return $instance;
+ $instance->save();
+ });
}
/**
@@ -361,35 +309,61 @@ public function update(array $attributes)
}
/**
- * Get the key for comparing against the parent key in "has" query.
+ * Add the constraints for a relationship query.
*
- * @return string
+ * @param \Illuminate\Database\Eloquent\Builder $query
+ * @param \Illuminate\Database\Eloquent\Builder $parent
+ * @param array|mixed $columns
+ * @return \Illuminate\Database\Eloquent\Builder
*/
- public function getHasCompareKey()
+ public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
{
- return $this->getForeignKey();
+ if ($parent->getQuery()->from == $query->getQuery()->from) {
+ return $this->getRelationQueryForSelfRelation($query, $parent, $columns);
+ }
+
+ return parent::getRelationQuery($query, $parent, $columns);
}
/**
- * Get the foreign key for the relationship.
+ * Add the constraints for a relationship query on the same table.
*
- * @return string
+ * @param \Illuminate\Database\Eloquent\Builder $query
+ * @param \Illuminate\Database\Eloquent\Builder $parent
+ * @param array|mixed $columns
+ * @return \Illuminate\Database\Eloquent\Builder
*/
- public function getForeignKey()
+ public function getRelationQueryForSelfRelation(Builder $query, Builder $parent, $columns = ['*'])
{
- return $this->foreignKey;
+ $query->select($columns);
+
+ $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());
+
+ $query->getModel()->setTable($hash);
+
+ $key = $this->wrap($this->getQualifiedParentKeyName());
+
+ return $query->where($hash.'.'.$this->getForeignKeyName(), '=', new Expression($key));
}
/**
- * Get the plain foreign key.
+ * Get a relationship join table hash.
*
* @return string
*/
- public function getPlainForeignKey()
+ public function getRelationCountHash()
{
- $segments = explode('.', $this->getForeignKey());
+ return 'laravel_reserved_'.static::$selfJoinCount++;
+ }
- return $segments[count($segments) - 1];
+ /**
+ * Get the key for comparing against the parent key in "has" query.
+ *
+ * @return string
+ */
+ public function getHasCompareKey()
+ {
+ return $this->getQualifiedForeignKeyName();
}
/**
@@ -411,4 +385,26 @@ public function getQualifiedParentKeyName()
{
return $this->parent->getTable().'.'.$this->localKey;
}
+
+ /**
+ * Get the plain foreign key.
+ *
+ * @return string
+ */
+ public function getForeignKeyName()
+ {
+ $segments = explode('.', $this->getQualifiedForeignKeyName());
+
+ return $segments[count($segments) - 1];
+ }
+
+ /**
+ * Get the foreign key for the relationship.
+ *
+ * @return string
+ */
+ public function getQualifiedForeignKeyName()
+ {
+ return $this->foreignKey;
+ }
} | true |
Other | laravel | framework | 294c006288ee182eeddf3c6deb23a35032a9219d.json | Refactor some method names. | src/Illuminate/Database/Eloquent/Relations/MorphOneOrMany.php | @@ -197,7 +197,7 @@ public function create(array $attributes)
*/
protected function setForeignAttributesForCreate(Model $model)
{
- $model->{$this->getPlainForeignKey()} = $this->getParentKey();
+ $model->{$this->getForeignKeyName()} = $this->getParentKey();
$model->{last(explode('.', $this->morphType))} = $this->morphClass;
} | true |
Other | laravel | framework | 294c006288ee182eeddf3c6deb23a35032a9219d.json | Refactor some method names. | src/Illuminate/Database/Eloquent/Relations/Relation.php | @@ -158,11 +158,10 @@ public function getRelationCountQuery(Builder $query, Builder $parent)
*/
public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
{
- $query->select($columns);
-
- $key = $this->wrap($this->getQualifiedParentKeyName());
-
- return $query->where($this->getHasCompareKey(), '=', new Expression($key));
+ return $query->select($columns)->where(
+ $this->getHasCompareKey(), '=',
+ new Expression($this->wrap($this->getQualifiedParentKeyName()))
+ );
}
/**
@@ -181,12 +180,10 @@ public static function noConstraints(Closure $callback)
// off of the bindings, leaving only the constraints that the developers put
// as "extra" on the relationships, and not original relation constraints.
try {
- $results = call_user_func($callback);
+ return call_user_func($callback);
} finally {
static::$constraints = $previous;
}
-
- return $results;
}
/**
@@ -198,9 +195,9 @@ public static function noConstraints(Closure $callback)
*/
protected function getKeys(array $models, $key = null)
{
- return array_unique(array_values(array_map(function ($value) use ($key) {
+ return collect($models)->map(function ($value) use ($key) {
return $key ? $value->getAttribute($key) : $value->getKey();
- }, $models)));
+ })->values()->unique()->all();
}
/**
@@ -291,7 +288,8 @@ public function relatedUpdatedAt()
*/
public function wrap($value)
{
- return $this->parent->newQueryWithoutScopes()->getQuery()->getGrammar()->wrap($value);
+ return $this->parent->newQueryWithoutScopes()
+ ->getQuery()->getGrammar()->wrap($value);
}
/**
@@ -325,11 +323,9 @@ protected static function buildMorphMapFromModels(array $models = null)
return $models;
}
- $tables = array_map(function ($model) {
+ return array_combine(array_map(function ($model) {
return (new $model)->getTable();
- }, $models);
-
- return array_combine($tables, $models);
+ }, $models), $models);
}
/** | true |
Other | laravel | framework | 294c006288ee182eeddf3c6deb23a35032a9219d.json | Refactor some method names. | tests/Database/DatabaseEloquentHasOneTest.php | @@ -161,7 +161,7 @@ public function testRelationCountQueryCanBeBuilt()
$builder->shouldReceive('getQuery')->once()->andReturn($baseQuery);
$builder->shouldReceive('getQuery')->once()->andReturn($parentQuery);
- $builder->shouldReceive('select')->once()->with(m::type('Illuminate\Database\Query\Expression'));
+ $builder->shouldReceive('select')->once()->with(m::type('Illuminate\Database\Query\Expression'))->andReturnSelf();
$relation->getParent()->shouldReceive('getTable')->andReturn('table');
$builder->shouldReceive('where')->once()->with('table.foreign_key', '=', m::type('Illuminate\Database\Query\Expression'));
$relation->getQuery()->shouldReceive('getQuery')->andReturn($parentQuery = m::mock('StdClass')); | true |
Other | laravel | framework | 294c006288ee182eeddf3c6deb23a35032a9219d.json | Refactor some method names. | tests/Database/DatabaseEloquentModelTest.php | @@ -907,12 +907,12 @@ public function testHasOneCreatesProperRelation()
$model = new EloquentModelStub;
$this->addMockConnection($model);
$relation = $model->hasOne('EloquentModelSaveStub');
- $this->assertEquals('save_stub.eloquent_model_stub_id', $relation->getForeignKey());
+ $this->assertEquals('save_stub.eloquent_model_stub_id', $relation->getQualifiedForeignKeyName());
$model = new EloquentModelStub;
$this->addMockConnection($model);
$relation = $model->hasOne('EloquentModelSaveStub', 'foo');
- $this->assertEquals('save_stub.foo', $relation->getForeignKey());
+ $this->assertEquals('save_stub.foo', $relation->getQualifiedForeignKeyName());
$this->assertSame($model, $relation->getParent());
$this->assertInstanceOf('EloquentModelSaveStub', $relation->getQuery()->getModel());
}
@@ -922,7 +922,7 @@ public function testMorphOneCreatesProperRelation()
$model = new EloquentModelStub;
$this->addMockConnection($model);
$relation = $model->morphOne('EloquentModelSaveStub', 'morph');
- $this->assertEquals('save_stub.morph_id', $relation->getForeignKey());
+ $this->assertEquals('save_stub.morph_id', $relation->getQualifiedForeignKeyName());
$this->assertEquals('save_stub.morph_type', $relation->getMorphType());
$this->assertEquals('EloquentModelStub', $relation->getMorphClass());
}
@@ -944,12 +944,12 @@ public function testHasManyCreatesProperRelation()
$model = new EloquentModelStub;
$this->addMockConnection($model);
$relation = $model->hasMany('EloquentModelSaveStub');
- $this->assertEquals('save_stub.eloquent_model_stub_id', $relation->getForeignKey());
+ $this->assertEquals('save_stub.eloquent_model_stub_id', $relation->getQualifiedForeignKeyName());
$model = new EloquentModelStub;
$this->addMockConnection($model);
$relation = $model->hasMany('EloquentModelSaveStub', 'foo');
- $this->assertEquals('save_stub.foo', $relation->getForeignKey());
+ $this->assertEquals('save_stub.foo', $relation->getQualifiedForeignKeyName());
$this->assertSame($model, $relation->getParent());
$this->assertInstanceOf('EloquentModelSaveStub', $relation->getQuery()->getModel());
}
@@ -959,7 +959,7 @@ public function testMorphManyCreatesProperRelation()
$model = new EloquentModelStub;
$this->addMockConnection($model);
$relation = $model->morphMany('EloquentModelSaveStub', 'morph');
- $this->assertEquals('save_stub.morph_id', $relation->getForeignKey());
+ $this->assertEquals('save_stub.morph_id', $relation->getQualifiedForeignKeyName());
$this->assertEquals('save_stub.morph_type', $relation->getMorphType());
$this->assertEquals('EloquentModelStub', $relation->getMorphClass());
} | true |
Other | laravel | framework | 86ded5744cea21fceec75607d1b053770530c6a1.json | add comments and clarity | src/Illuminate/Database/Eloquent/Builder.php | @@ -972,7 +972,7 @@ protected function parseNestedWith($name, $results)
}
/**
- * Add the given scopes to the current builder instance.
+ * Call the given local model scopes.
*
* @param array $scopes
* @return mixed
@@ -982,12 +982,19 @@ public function scopes(array $scopes)
$builder = $this;
foreach ($scopes as $scope => $parameters) {
+ // If the scope key is an integer, then the scope was passed as the value and
+ // the parameter list is empty, so we will format the scope name and these
+ // parameters here. Then, we'll be ready to call the scope on the model.
if (is_int($scope)) {
list($scope, $parameters) = [$parameters, []];
}
+ // Next we'll pass the scope callback to the callScope method which will take
+ // care of groping the "wheres" correctly so the logical order doesn't get
+ // messed up when adding scopes. Then we'll return back out the builder.
$builder = $builder->callScope(
- [$this->model, 'scope'.ucfirst($scope)], (array) $parameters
+ [$this->model, 'scope'.ucfirst($scope)],
+ (array) $parameters
);
}
@@ -1009,9 +1016,17 @@ public function applyScopes()
foreach ($this->scopes as $scope) {
$builder->callScope(function (Builder $builder) use ($scope) {
+ // If the scope is a Closure we will just go ahead and call the scope with the
+ // builder instance. The "callScope" method will properly group the clauses
+ // that are added to this query so "where" clauses maintain proper logic.
if ($scope instanceof Closure) {
$scope($builder);
- } elseif ($scope instanceof Scope) {
+ }
+
+ // If the scope is a scope object, we will call the apply method on this scope
+ // passing in the builder and the model instance. After we run all of these
+ // scopes we will return back the builder instance to the outside caller.
+ if ($scope instanceof Scope) {
$scope->apply($builder, $this->getModel());
}
});
@@ -1041,10 +1056,10 @@ protected function callScope(callable $scope, $parameters = [])
$result = $scope(...array_values($parameters)) ?: $this;
if (count($query->wheres) > $originalWhereCount) {
- $this->nestWheresForScope($query, $originalWhereCount);
+ $this->addNewWheresWithinGroup($query, $originalWhereCount);
}
- return $result;
+ return $this;
}
/**
@@ -1054,7 +1069,7 @@ protected function callScope(callable $scope, $parameters = [])
* @param int $originalWhereCount
* @return void
*/
- protected function nestWheresForScope(QueryBuilder $query, $originalWhereCount)
+ protected function addNewWheresWithinGroup(QueryBuilder $query, $originalWhereCount)
{
// Here, we totally remove all of the where clauses since we are going to
// rebuild them as nested queries by slicing the groups of wheres into
@@ -1063,35 +1078,33 @@ protected function nestWheresForScope(QueryBuilder $query, $originalWhereCount)
$query->wheres = [];
- $this->addNestedWhereSlice(
- $query, $allWheres, 0, $originalWhereCount
+ $this->groupWhereSliceForScope(
+ $query, array_slice($allWheres, 0, $originalWhereCount)
);
- $this->addNestedWhereSlice(
- $query, $allWheres, $originalWhereCount
+ $this->groupWhereSliceForScope(
+ $query, array_slice($allWheres, $originalWhereCount)
);
}
/**
* Slice where conditions at the given offset and add them to the query as a nested condition.
*
* @param \Illuminate\Database\Query\Builder $query
- * @param array $wheres
- * @param int $offset
- * @param int $length
+ * @param array $whereSlice
* @return void
*/
- protected function addNestedWhereSlice(QueryBuilder $query, $wheres, $offset, $length = null)
+ protected function groupWhereSliceForScope(QueryBuilder $query, $whereSlice)
{
- $whereSlice = array_slice($wheres, $offset, $length);
-
$whereBooleans = collect($whereSlice)->pluck('boolean');
// Here we'll check if the given subset of where clauses contains any "or"
// booleans and in this case create a nested where expression. That way
// we don't add any unnecessary nesting thus keeping the query clean.
if ($whereBooleans->contains('or')) {
- $query->wheres[] = $this->nestWhereSlice($whereSlice, $whereBooleans->first());
+ $query->wheres[] = $this->createNestedWhere(
+ $whereSlice, $whereBooleans->first()
+ );
} else {
$query->wheres = array_merge($query->wheres, $whereSlice);
}
@@ -1104,7 +1117,7 @@ protected function addNestedWhereSlice(QueryBuilder $query, $wheres, $offset, $l
* @param string $boolean
* @return array
*/
- protected function nestWhereSlice($whereSlice, $boolean = 'and')
+ protected function createNestedWhere($whereSlice, $boolean = 'and')
{
$whereGroup = $this->getQuery()->forNestedWhere();
| false |
Other | laravel | framework | a8a171128a889a33ddd8c8c8fafab1930de00255.json | Adjust method location. | src/Illuminate/Database/Eloquent/Builder.php | @@ -994,33 +994,6 @@ public function scopes(array $scopes)
return $builder;
}
- /**
- * Apply the given scope on the current builder instance.
- *
- * @param callable $scope
- * @param array $parameters
- * @return mixed
- */
- protected function callScope(callable $scope, $parameters = [])
- {
- array_unshift($parameters, $this);
-
- $query = $this->getQuery();
-
- // We will keep track of how many wheres are on the query before running the
- // scope so that we can properly group the added scope constraints in the
- // query as their own isolated nested where statement and avoid issues.
- $originalWhereCount = count($query->wheres);
-
- $result = $scope(...array_values($parameters)) ?: $this;
-
- if ($this->shouldNestWheresForScope($query, $originalWhereCount)) {
- $this->nestWheresForScope($query, $originalWhereCount);
- }
-
- return $result;
- }
-
/**
* Apply the scopes to the Eloquent builder instance and return it.
*
@@ -1048,15 +1021,30 @@ public function applyScopes()
}
/**
- * Determine if the scope added after the given offset should be nested.
+ * Apply the given scope on the current builder instance.
*
- * @param \Illuminate\Database\Query\Builder $query
- * @param int $originalWhereCount
- * @return bool
+ * @param callable $scope
+ * @param array $parameters
+ * @return mixed
*/
- protected function shouldNestWheresForScope(QueryBuilder $query, $originalWhereCount)
+ protected function callScope(callable $scope, $parameters = [])
{
- return count($query->wheres) > $originalWhereCount;
+ array_unshift($parameters, $this);
+
+ $query = $this->getQuery();
+
+ // We will keep track of how many wheres are on the query before running the
+ // scope so that we can properly group the added scope constraints in the
+ // query as their own isolated nested where statement and avoid issues.
+ $originalWhereCount = count($query->wheres);
+
+ $result = $scope(...array_values($parameters)) ?: $this;
+
+ if (count($query->wheres) > $originalWhereCount) {
+ $this->nestWheresForScope($query, $originalWhereCount);
+ }
+
+ return $result;
}
/** | false |
Other | laravel | framework | 8f363c0e54661f5ea4fdd0dfca5e906b23db5667.json | Apply fixes from StyleCI (#17181) | src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php | @@ -5,8 +5,8 @@
use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
-use Illuminate\Database\Query\Expression;
use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Database\Query\Expression;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder as QueryBuilder;
| false |
Other | laravel | framework | 067f6a5173c1527ae6e109f0ba891b104392f7a9.json | Use a tap. | src/Illuminate/Database/Eloquent/Builder.php | @@ -206,7 +206,9 @@ public function findOrFail($id, $columns = ['*'])
return $result;
}
- throw (new ModelNotFoundException)->setModel(get_class($this->model), $id);
+ throw (new ModelNotFoundException)->setModel(
+ get_class($this->model), $id
+ );
}
/**
@@ -276,11 +278,9 @@ public function firstOrCreate(array $attributes, array $values = [])
*/
public function updateOrCreate(array $attributes, array $values = [])
{
- $instance = $this->firstOrNew($attributes);
-
- $instance->fill($values)->save();
-
- return $instance;
+ return tap($this->firstOrNew($attributes), function ($instance) use ($values) {
+ $instance->fill($values)->save();
+ });
}
/** | false |
Other | laravel | framework | c2f800d4974b06e580b320b1664d2396492a4512.json | Apply fixes from StyleCI (#17169) | src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php | @@ -152,7 +152,7 @@ public function isFillable($key)
}
return empty($this->getFillable()) &&
- ! Str::startsWith($key, '_');
+ ! Str::startsWith($key, '_');
}
/** | true |
Other | laravel | framework | c2f800d4974b06e580b320b1664d2396492a4512.json | Apply fixes from StyleCI (#17169) | src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php | @@ -39,7 +39,7 @@ trait HasRelationships
*/
public static $manyMethods = [
'belongsToMany', 'morphToMany', 'morphedByMany',
- 'guessBelongsToManyRelation', 'findFirstMethodThatIsntRelation'
+ 'guessBelongsToManyRelation', 'findFirstMethodThatIsntRelation',
];
/**
@@ -402,7 +402,7 @@ public function joiningTable($related)
// just sort the models and join them together to get the table name.
$models = [
Str::snake(class_basename($related)),
- Str::snake(class_basename($this))
+ Str::snake(class_basename($this)),
];
// Now that we have the model names in an array we can just sort them and | true |
Other | laravel | framework | c0f3538710d3fb8501a78cae7f4a7cf0aa70ad22.json | Add comment for empty functions. (#17162) | src/Illuminate/Http/RedirectResponse.php | @@ -161,6 +161,7 @@ protected function parseErrors($provider)
*/
public function getOriginalContent()
{
+ //
}
/** | false |
Other | laravel | framework | bafd2c423dca3b88d721b55f2f7f83acc4591321.json | Fix issue #17140 match only APP_KEY in replace
Changed str_replace to preg_replace to ensure no clashes with other
environment variables | src/Illuminate/Foundation/Console/KeyGenerateCommand.php | @@ -51,8 +51,8 @@ public function fire()
*/
protected function setKeyInEnvironmentFile($key)
{
- file_put_contents($this->laravel->environmentFilePath(), str_replace(
- 'APP_KEY='.$this->laravel['config']['app.key'],
+ file_put_contents($this->laravel->environmentFilePath(), preg_replace(
+ $this->getAppKeyPattern(),
'APP_KEY='.$key,
file_get_contents($this->laravel->environmentFilePath())
));
@@ -69,4 +69,16 @@ protected function generateRandomKey()
$this->laravel['config']['app.cipher'] == 'AES-128-CBC' ? 16 : 32
));
}
+
+ /**
+ * Get a regex pattern that will match env APP_KEY with any random key
+ *
+ * @return string
+ */
+ protected function getAppKeyPattern()
+ {
+ $escapedKey = preg_quote('='.$this->laravel['config']['app.key'], '/');
+
+ return "/^APP_KEY$escapedKey/m";
+ }
} | false |
Other | laravel | framework | 003c4cb6d91b32af79ac1721bf191d24cf27504e.json | Apply fixes from StyleCI (#17147) | src/Illuminate/Http/RedirectResponse.php | @@ -161,7 +161,6 @@ protected function parseErrors($provider)
*/
public function getOriginalContent()
{
- return;
}
/** | false |
Other | laravel | framework | 5cd45bf3f173740b8987895701932986253987e6.json | Apply fixes from StyleCI (#17146) | src/Illuminate/Database/Schema/Grammars/SqlServerGrammar.php | @@ -82,7 +82,7 @@ public function compileAdd(Blueprint $blueprint, Fluent $command)
*/
public function compilePrimary(Blueprint $blueprint, Fluent $command)
{
- return sprintf("alter table %s add constraint %s primary key (%s)",
+ return sprintf('alter table %s add constraint %s primary key (%s)',
$this->wrapTable($blueprint),
$this->wrap($command->index),
$this->columnize($command->columns)
@@ -98,7 +98,7 @@ public function compilePrimary(Blueprint $blueprint, Fluent $command)
*/
public function compileUnique(Blueprint $blueprint, Fluent $command)
{
- return sprintf("create unique index %s on %s (%s)",
+ return sprintf('create unique index %s on %s (%s)',
$this->wrap($command->index),
$this->wrapTable($blueprint),
$this->columnize($command->columns)
@@ -114,7 +114,7 @@ public function compileUnique(Blueprint $blueprint, Fluent $command)
*/
public function compileIndex(Blueprint $blueprint, Fluent $command)
{
- return sprintf("create index %s on %s (%s)",
+ return sprintf('create index %s on %s (%s)',
$this->wrap($command->index),
$this->wrapTable($blueprint),
$this->columnize($command->columns) | false |
Other | laravel | framework | 915c93d093323496446003bace29ce16d2e52da7.json | Apply fixes from StyleCI (#17144) | src/Illuminate/Database/Schema/Grammars/SQLiteGrammar.php | @@ -103,7 +103,7 @@ protected function getForeignKey($foreign)
// We need to columnize the columns that the foreign key is being defined for
// so that it is a properly formatted list. Once we have done this, we can
// return the foreign key SQL declaration to the calling method for use.
- return sprintf(", foreign key(%s) references %s(%s)",
+ return sprintf(', foreign key(%s) references %s(%s)',
$this->columnize($foreign->columns),
$this->wrapTable($foreign->on),
$this->columnize((array) $foreign->references)
@@ -148,7 +148,7 @@ public function compileAdd(Blueprint $blueprint, Fluent $command)
*/
public function compileUnique(Blueprint $blueprint, Fluent $command)
{
- return sprintf("create unique index %s on %s (%s)",
+ return sprintf('create unique index %s on %s (%s)',
$this->wrap($command->index),
$this->wrapTable($blueprint),
$this->columnize($command->columns)
@@ -164,7 +164,7 @@ public function compileUnique(Blueprint $blueprint, Fluent $command)
*/
public function compileIndex(Blueprint $blueprint, Fluent $command)
{
- return sprintf("create index %s on %s (%s)",
+ return sprintf('create index %s on %s (%s)',
$this->wrap($command->index),
$this->wrapTable($blueprint),
$this->columnize($command->columns) | false |
Other | laravel | framework | 01a4d896dd5e767dc8405dd28daf240fd8c2b9db.json | Apply fixes from StyleCI (#17143) | src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php | @@ -103,7 +103,7 @@ public function compilePrimary(Blueprint $blueprint, Fluent $command)
*/
public function compileUnique(Blueprint $blueprint, Fluent $command)
{
- return sprintf("alter table %s add constraint %s unique (%s)",
+ return sprintf('alter table %s add constraint %s unique (%s)',
$this->wrapTable($blueprint),
$this->wrap($command->index),
$this->columnize($command->columns)
@@ -119,7 +119,7 @@ public function compileUnique(Blueprint $blueprint, Fluent $command)
*/
public function compileIndex(Blueprint $blueprint, Fluent $command)
{
- return sprintf("create index %s on %s%s (%s)",
+ return sprintf('create index %s on %s%s (%s)',
$this->wrap($command->index),
$this->wrapTable($blueprint),
$command->algorithm ? ' using '.$command->algorithm : '', | false |
Other | laravel | framework | 86e9e051e8b6ec8ae72b33535a485938c170b756.json | Apply fixes from StyleCI (#17142) | src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php | @@ -203,7 +203,7 @@ public function compileIndex(Blueprint $blueprint, Fluent $command)
*/
protected function compileKey(Blueprint $blueprint, Fluent $command, $type)
{
- return sprintf("alter table %s add %s %s%s(%s)",
+ return sprintf('alter table %s add %s %s%s(%s)',
$this->wrapTable($blueprint),
$type,
$this->wrap($command->index), | false |
Other | laravel | framework | e147f579eb64a9897ba58182331a49bf0bcc784b.json | Apply fixes from StyleCI (#17141) | src/Illuminate/Database/Schema/Grammars/Grammar.php | @@ -62,15 +62,15 @@ public function compileForeign(Blueprint $blueprint, Fluent $command)
// We need to prepare several of the elements of the foreign key definition
// before we can create the SQL, such as wrapping the tables and convert
// an array of columns to comma-delimited strings for the SQL queries.
- $sql = sprintf("alter table %s add constraint %s ",
+ $sql = sprintf('alter table %s add constraint %s ',
$this->wrapTable($blueprint),
$this->wrap($command->index)
);
// Once we have the initial portion of the SQL statement we will add on the
// key name, table name, and referenced columns. These will complete the
// main portion of the SQL statement and this SQL will almost be done.
- $sql .= sprintf("foreign key (%s) references %s (%s)",
+ $sql .= sprintf('foreign key (%s) references %s (%s)',
$this->columnize($command->columns),
$this->wrapTable($command->on),
$this->columnize((array) $command->references) | false |
Other | laravel | framework | 32fa8266a8431305d6e57ccdb205ed1704be62cd.json | extract change column | src/Illuminate/Database/Schema/Grammars/ChangeColumn.php | @@ -0,0 +1,206 @@
+<?php
+
+namespace Illuminate\Database\Schema\Grammars;
+
+use RuntimeException;
+use Doctrine\DBAL\Types\Type;
+use Illuminate\Support\Fluent;
+use Doctrine\DBAL\Schema\Table;
+use Doctrine\DBAL\Schema\Column;
+use Illuminate\Database\Connection;
+use Doctrine\DBAL\Schema\Comparator;
+use Illuminate\Database\Schema\Blueprint;
+use Doctrine\DBAL\Schema\AbstractSchemaManager as SchemaManager;
+
+class ChangeColumn
+{
+ /**
+ * Compile a change column command into a series of SQL statements.
+ *
+ * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar
+ * @param \Illuminate\Database\Schema\Blueprint $blueprint
+ * @param \Illuminate\Support\Fluent $command
+ * @param \Illuminate\Database\Connection $connection
+ * @return array
+ *
+ * @throws \RuntimeException
+ */
+ public static function compile($grammar, Blueprint $blueprint, Fluent $command, Connection $connection)
+ {
+ if (! $connection->isDoctrineAvailable()) {
+ throw new RuntimeException(sprintf(
+ 'Changing columns for table "%s" requires Doctrine DBAL; install "doctrine/dbal".',
+ $blueprint->getTable()
+ ));
+ }
+
+ $tableDiff = static::getChangedDiff(
+ $grammar, $blueprint, $schema = $connection->getDoctrineSchemaManager()
+ );
+
+ if ($tableDiff !== false) {
+ return (array) $schema->getDatabasePlatform()->getAlterTableSQL($tableDiff);
+ }
+
+ return [];
+ }
+
+ /**
+ * Get the Doctrine table difference for the given changes.
+ *
+ * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar
+ * @param \Illuminate\Database\Schema\Blueprint $blueprint
+ * @param \Doctrine\DBAL\Schema\AbstractSchemaManager $schema
+ * @return \Doctrine\DBAL\Schema\TableDiff|bool
+ */
+ protected static function getChangedDiff($grammar, Blueprint $blueprint, SchemaManager $schema)
+ {
+ $current = $schema->listTableDetails($grammar->getTablePrefix().$blueprint->getTable());
+
+ return (new Comparator)->diffTable(
+ $current, static::getTableWithColumnChanges($blueprint, $current)
+ );
+ }
+
+ /**
+ * Get a copy of the given Doctrine table after making the column changes.
+ *
+ * @param \Illuminate\Database\Schema\Blueprint $blueprint
+ * @param \Doctrine\DBAL\Schema\Table $table
+ * @return \Doctrine\DBAL\Schema\TableDiff
+ */
+ protected static function getTableWithColumnChanges(Blueprint $blueprint, Table $table)
+ {
+ $table = clone $table;
+
+ foreach ($blueprint->getChangedColumns() as $fluent) {
+ $column = static::getDoctrineColumn($table, $fluent);
+
+ // Here we will spin through each fluent column definition and map it to the proper
+ // Doctrine column definitions - which is necessary because Laravel and Doctrine
+ // use some different terminology for various column attributes on the tables.
+ foreach ($fluent->getAttributes() as $key => $value) {
+ if (! is_null($option = static::mapFluentOptionToDoctrine($key))) {
+ if (method_exists($column, $method = 'set'.ucfirst($option))) {
+ $column->{$method}(static::mapFluentValueToDoctrine($option, $value));
+ }
+ }
+ }
+ }
+
+ return $table;
+ }
+
+ /**
+ * Get the Doctrine column instance for a column change.
+ *
+ * @param \Doctrine\DBAL\Schema\Table $table
+ * @param \Illuminate\Support\Fluent $fluent
+ * @return \Doctrine\DBAL\Schema\Column
+ */
+ protected static function getDoctrineColumn(Table $table, Fluent $fluent)
+ {
+ return $table->changeColumn(
+ $fluent['name'], static::getDoctrineColumnChangeOptions($fluent)
+ )->getColumn($fluent['name']);
+ }
+
+ /**
+ * Get the Doctrine column change options.
+ *
+ * @param \Illuminate\Support\Fluent $fluent
+ * @return array
+ */
+ protected static function getDoctrineColumnChangeOptions(Fluent $fluent)
+ {
+ $options = ['type' => static::getDoctrineColumnType($fluent['type'])];
+
+ if (in_array($fluent['type'], ['text', 'mediumText', 'longText'])) {
+ $options['length'] = static::calculateDoctrineTextLength($fluent['type']);
+ }
+
+ return $options;
+ }
+
+ /**
+ * Get the doctrine column type.
+ *
+ * @param string $type
+ * @return \Doctrine\DBAL\Types\Type
+ */
+ protected static function getDoctrineColumnType($type)
+ {
+ $type = strtolower($type);
+
+ switch ($type) {
+ case 'biginteger':
+ $type = 'bigint';
+ break;
+ case 'smallinteger':
+ $type = 'smallint';
+ break;
+ case 'mediumtext':
+ case 'longtext':
+ $type = 'text';
+ break;
+ case 'binary':
+ $type = 'blob';
+ break;
+ }
+
+ return Type::getType($type);
+ }
+
+ /**
+ * Calculate the proper column length to force the Doctrine text type.
+ *
+ * @param string $type
+ * @return int
+ */
+ protected static function calculateDoctrineTextLength($type)
+ {
+ switch ($type) {
+ case 'mediumText':
+ return 65535 + 1;
+ case 'longText':
+ return 16777215 + 1;
+ default:
+ return 255 + 1;
+ }
+ }
+
+ /**
+ * Get the matching Doctrine option for a given Fluent attribute name.
+ *
+ * @param string $attribute
+ * @return string|null
+ */
+ protected static function mapFluentOptionToDoctrine($attribute)
+ {
+ switch ($attribute) {
+ case 'type':
+ case 'name':
+ return;
+ case 'nullable':
+ return 'notnull';
+ case 'total':
+ return 'precision';
+ case 'places':
+ return 'scale';
+ default:
+ return $attribute;
+ }
+ }
+
+ /**
+ * Get the matching Doctrine value for a given Fluent attribute.
+ *
+ * @param string $option
+ * @param mixed $value
+ * @return mixed
+ */
+ protected static function mapFluentValueToDoctrine($option, $value)
+ {
+ return $option == 'notnull' ? ! $value : $value;
+ }
+} | true |
Other | laravel | framework | 32fa8266a8431305d6e57ccdb205ed1704be62cd.json | extract change column | src/Illuminate/Database/Schema/Grammars/Grammar.php | @@ -2,14 +2,12 @@
namespace Illuminate\Database\Schema\Grammars;
-use RuntimeException;
use Doctrine\DBAL\Types\Type;
use Illuminate\Support\Fluent;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\TableDiff;
use Illuminate\Database\Connection;
-use Doctrine\DBAL\Schema\Comparator;
use Illuminate\Database\Query\Expression;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Grammar as BaseGrammar;
@@ -37,6 +35,21 @@ public function compileRenameColumn(Blueprint $blueprint, Fluent $command, Conne
return RenameColumn::compile($this, $blueprint, $command, $connection);
}
+ /**
+ * Compile a change column command into a series of SQL statements.
+ *
+ * @param \Illuminate\Database\Schema\Blueprint $blueprint
+ * @param \Illuminate\Support\Fluent $command
+ * @param \Illuminate\Database\Connection $connection
+ * @return array
+ *
+ * @throws \RuntimeException
+ */
+ public function compileChange(Blueprint $blueprint, Fluent $command, Connection $connection)
+ {
+ return ChangeColumn::compile($this, $blueprint, $command, $connection);
+ }
+
/**
* Compile a foreign key command.
*
@@ -187,7 +200,11 @@ public function wrapTable($table)
}
/**
- * {@inheritdoc}
+ * Wrap a value in keyword identifiers.
+ *
+ * @param \Illuminate\Database\Query\Expression|string $value
+ * @param bool $prefixAlias
+ * @return string
*/
public function wrap($value, $prefixAlias = false)
{
@@ -231,192 +248,6 @@ public function getDoctrineTableDiff(Blueprint $blueprint, SchemaManager $schema
});
}
- /**
- * Compile a change column command into a series of SQL statements.
- *
- * @param \Illuminate\Database\Schema\Blueprint $blueprint
- * @param \Illuminate\Support\Fluent $command
- * @param \Illuminate\Database\Connection $connection
- * @return array
- *
- * @throws \RuntimeException
- */
- public function compileChange(Blueprint $blueprint, Fluent $command, Connection $connection)
- {
- if (! $connection->isDoctrineAvailable()) {
- throw new RuntimeException(sprintf(
- 'Changing columns for table "%s" requires Doctrine DBAL; install "doctrine/dbal".',
- $blueprint->getTable()
- ));
- }
-
- $schema = $connection->getDoctrineSchemaManager();
-
- $tableDiff = $this->getChangedDiff($blueprint, $schema);
-
- if ($tableDiff !== false) {
- return (array) $schema->getDatabasePlatform()->getAlterTableSQL($tableDiff);
- }
-
- return [];
- }
-
- /**
- * Get the Doctrine table difference for the given changes.
- *
- * @param \Illuminate\Database\Schema\Blueprint $blueprint
- * @param \Doctrine\DBAL\Schema\AbstractSchemaManager $schema
- * @return \Doctrine\DBAL\Schema\TableDiff|bool
- */
- protected function getChangedDiff(Blueprint $blueprint, SchemaManager $schema)
- {
- $table = $schema->listTableDetails($this->getTablePrefix().$blueprint->getTable());
-
- return (new Comparator)->diffTable($table, $this->getTableWithColumnChanges($blueprint, $table));
- }
-
- /**
- * Get a copy of the given Doctrine table after making the column changes.
- *
- * @param \Illuminate\Database\Schema\Blueprint $blueprint
- * @param \Doctrine\DBAL\Schema\Table $table
- * @return \Doctrine\DBAL\Schema\TableDiff
- */
- protected function getTableWithColumnChanges(Blueprint $blueprint, Table $table)
- {
- $table = clone $table;
-
- foreach ($blueprint->getChangedColumns() as $fluent) {
- $column = $this->getDoctrineColumnForChange($table, $fluent);
-
- // Here we will spin through each fluent column definition and map it to the proper
- // Doctrine column definitions - which is necessary because Laravel and Doctrine
- // use some different terminology for various column attributes on the tables.
- foreach ($fluent->getAttributes() as $key => $value) {
- if (! is_null($option = $this->mapFluentOptionToDoctrine($key))) {
- if (method_exists($column, $method = 'set'.ucfirst($option))) {
- $column->{$method}($this->mapFluentValueToDoctrine($option, $value));
- }
- }
- }
- }
-
- return $table;
- }
-
- /**
- * Get the Doctrine column instance for a column change.
- *
- * @param \Doctrine\DBAL\Schema\Table $table
- * @param \Illuminate\Support\Fluent $fluent
- * @return \Doctrine\DBAL\Schema\Column
- */
- protected function getDoctrineColumnForChange(Table $table, Fluent $fluent)
- {
- return $table->changeColumn(
- $fluent['name'], $this->getDoctrineColumnChangeOptions($fluent)
- )->getColumn($fluent['name']);
- }
-
- /**
- * Get the Doctrine column change options.
- *
- * @param \Illuminate\Support\Fluent $fluent
- * @return array
- */
- protected function getDoctrineColumnChangeOptions(Fluent $fluent)
- {
- $options = ['type' => $this->getDoctrineColumnType($fluent['type'])];
-
- if (in_array($fluent['type'], ['text', 'mediumText', 'longText'])) {
- $options['length'] = $this->calculateDoctrineTextLength($fluent['type']);
- }
-
- return $options;
- }
-
- /**
- * Get the doctrine column type.
- *
- * @param string $type
- * @return \Doctrine\DBAL\Types\Type
- */
- protected function getDoctrineColumnType($type)
- {
- $type = strtolower($type);
-
- switch ($type) {
- case 'biginteger':
- $type = 'bigint';
- break;
- case 'smallinteger':
- $type = 'smallint';
- break;
- case 'mediumtext':
- case 'longtext':
- $type = 'text';
- break;
- case 'binary':
- $type = 'blob';
- break;
- }
-
- return Type::getType($type);
- }
-
- /**
- * Calculate the proper column length to force the Doctrine text type.
- *
- * @param string $type
- * @return int
- */
- protected function calculateDoctrineTextLength($type)
- {
- switch ($type) {
- case 'mediumText':
- return 65535 + 1;
- case 'longText':
- return 16777215 + 1;
- default:
- return 255 + 1;
- }
- }
-
- /**
- * Get the matching Doctrine option for a given Fluent attribute name.
- *
- * @param string $attribute
- * @return string|null
- */
- protected function mapFluentOptionToDoctrine($attribute)
- {
- switch ($attribute) {
- case 'type':
- case 'name':
- return;
- case 'nullable':
- return 'notnull';
- case 'total':
- return 'precision';
- case 'places':
- return 'scale';
- default:
- return $attribute;
- }
- }
-
- /**
- * Get the matching Doctrine value for a given Fluent attribute.
- *
- * @param string $option
- * @param mixed $value
- * @return mixed
- */
- protected function mapFluentValueToDoctrine($option, $value)
- {
- return $option == 'notnull' ? ! $value : $value;
- }
-
/**
* Check if this Grammar supports schema changes wrapped in a transaction.
* | true |
Other | laravel | framework | 32fa8266a8431305d6e57ccdb205ed1704be62cd.json | extract change column | src/Illuminate/Database/Schema/Grammars/RenameColumn.php | @@ -37,6 +37,7 @@ public static function compile($grammar, Blueprint $blueprint, Fluent $command,
/**
* Get a new column instance with the new column name.
*
+ * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
* @param \Doctrine\DBAL\Schema\Column $column | true |
Other | laravel | framework | 562b869f0fff57fa463ea0ec61b5d0c7de887f35.json | Apply fixes from StyleCI (#17139) | src/Illuminate/Database/Schema/Grammars/RenameColumn.php | @@ -61,7 +61,7 @@ protected static function getRenamedDiff($grammar, Blueprint $blueprint, Fluent
protected static function setRenamedColumns(TableDiff $tableDiff, Fluent $command, Column $column)
{
$tableDiff->renamedColumns = [
- $command->from => new Column($command->to, $column->getType(), $column->toArray())
+ $command->from => new Column($command->to, $column->getType(), $column->toArray()),
];
return $tableDiff; | false |
Other | laravel | framework | 391d7d755c3678ab67c196c7a225176d4f0d8d41.json | Apply fixes from StyleCI (#17138) | src/Illuminate/Database/Schema/Grammars/RenameColumn.php | @@ -61,7 +61,7 @@ protected static function getRenamedDiff($grammar, Blueprint $blueprint, Fluent
protected static function setRenamedColumns(TableDiff $tableDiff, Fluent $command, Column $column)
{
$tableDiff->renamedColumns = [
- $command->from => new Column($command->to, $column->getType(), $column->toArray())
+ $command->from => new Column($command->to, $column->getType(), $column->toArray()),
];
return $tableDiff; | false |
Other | laravel | framework | ab1627d4c08ad9437419f669ab4858f2683d7a1c.json | Continue work on grammars. | src/Illuminate/Database/Grammar.php | @@ -32,11 +32,11 @@ public function wrapArray(array $values)
*/
public function wrapTable($table)
{
- if ($this->isExpression($table)) {
- return $this->getValue($table);
+ if (! $this->isExpression($table)) {
+ return $this->wrap($this->tablePrefix.$table, true);
}
- return $this->wrap($this->tablePrefix.$table, true);
+ return $this->getValue($table);
}
/**
@@ -56,31 +56,48 @@ public function wrap($value, $prefixAlias = false)
// the pieces so we can wrap each of the segments of the expression on it
// own, and then joins them both back together with the "as" connector.
if (strpos(strtolower($value), ' as ') !== false) {
- $segments = explode(' ', $value);
-
- if ($prefixAlias) {
- $segments[2] = $this->tablePrefix.$segments[2];
- }
-
- return $this->wrap($segments[0]).' as '.$this->wrapValue($segments[2]);
+ return $this->wrapAliasedValue($value, $prefixAlias);
}
- $wrapped = [];
+ return $this->wrapSegments(explode('.', $value));
+ }
- $segments = explode('.', $value);
+ /**
+ * Wrap a value that has an alias.
+ *
+ * @param string $value
+ * @param bool $prefixAlias
+ * @return string
+ */
+ protected function wrapAliasedValue($value, $prefixAlias = false)
+ {
+ $segments = explode(' ', $value);
- // If the value is not an aliased table expression, we'll just wrap it like
- // normal, so if there is more than one segment, we will wrap the first
- // segments as if it was a table and the rest as just regular values.
- foreach ($segments as $key => $segment) {
- if ($key == 0 && count($segments) > 1) {
- $wrapped[] = $this->wrapTable($segment);
- } else {
- $wrapped[] = $this->wrapValue($segment);
- }
+ // If we are wrapping a table we need to prefix the alias with the table prefix
+ // as well in order to generate proper syntax. If this is a column of course
+ // no prefix is necessary. The condition will be true when from wrapTable.
+ if ($prefixAlias) {
+ $segments[2] = $this->tablePrefix.$segments[2];
}
- return implode('.', $wrapped);
+ return $this->wrap(
+ $segments[0]).' as '.$this->wrapValue($segments[2]
+ );
+ }
+
+ /**
+ * Wrap the given value segments.
+ *
+ * @param array $segments
+ * @return string
+ */
+ protected function wrapSegments($segments)
+ {
+ return collect($segments)->map(function ($segment, $key) use ($segments) {
+ return $key == 0 && count($segments) > 1
+ ? $this->wrapTable($segment)
+ : $this->wrapValue($segment);
+ })->implode('.');
}
/**
@@ -91,11 +108,11 @@ public function wrap($value, $prefixAlias = false)
*/
protected function wrapValue($value)
{
- if ($value === '*') {
- return $value;
+ if ($value !== '*') {
+ return '"'.str_replace('"', '""', $value).'"';
}
- return '"'.str_replace('"', '""', $value).'"';
+ return $value;
}
/**
@@ -132,25 +149,25 @@ public function parameter($value)
}
/**
- * Get the value of a raw expression.
+ * Determine if the given value is a raw expression.
*
- * @param \Illuminate\Database\Query\Expression $expression
- * @return string
+ * @param mixed $value
+ * @return bool
*/
- public function getValue($expression)
+ public function isExpression($value)
{
- return $expression->getValue();
+ return $value instanceof Expression;
}
/**
- * Determine if the given value is a raw expression.
+ * Get the value of a raw expression.
*
- * @param mixed $value
- * @return bool
+ * @param \Illuminate\Database\Query\Expression $expression
+ * @return string
*/
- public function isExpression($value)
+ public function getValue($expression)
{
- return $value instanceof Expression;
+ return $expression->getValue();
}
/** | true |
Other | laravel | framework | ab1627d4c08ad9437419f669ab4858f2683d7a1c.json | Continue work on grammars. | src/Illuminate/Database/Schema/Blueprint.php | @@ -114,7 +114,7 @@ public function toSql(Connection $connection, Grammar $grammar)
}
/**
- * Add the commands that are implied by the blueprint.
+ * Add the commands that are implied by the blueprint's state.
*
* @return void
*/
@@ -140,20 +140,20 @@ protected function addFluentIndexes()
{
foreach ($this->columns as $column) {
foreach (['primary', 'unique', 'index'] as $index) {
- // If the index has been specified on the given column, but is simply
- // equal to "true" (boolean), no name has been specified for this
- // index, so we will simply call the index methods without one.
- if ($column->$index === true) {
- $this->$index($column->name);
+ // If the index has been specified on the given column, but is simply equal
+ // to "true" (boolean), no name has been specified for this index so the
+ // index method can be called without a name and it will generate one.
+ if ($column->{$index} === true) {
+ $this->{$index}($column->name);
continue 2;
}
- // If the index has been specified on the column and it is something
- // other than boolean true, we will assume a name was provided on
- // the index specification, and pass in the name to the method.
- elseif (isset($column->$index)) {
- $this->$index($column->name, $column->$index);
+ // If the index has been specified on the given column, and it has a string
+ // value, we'll go ahead and call the index method and pass the name for
+ // the index since the developer specified the explicit name for this.
+ elseif (isset($column->{$index})) {
+ $this->{$index}($column->name, $column->{$index});
continue 2;
}
@@ -168,13 +168,9 @@ protected function addFluentIndexes()
*/
protected function creating()
{
- foreach ($this->commands as $command) {
- if ($command->name == 'create') {
- return true;
- }
- }
-
- return false;
+ return collect($this->commands)->contains(function ($command) {
+ return $command->name == 'create';
+ });
}
/**
@@ -565,51 +561,51 @@ public function bigInteger($column, $autoIncrement = false, $unsigned = false)
}
/**
- * Create a new unsigned tiny integer (1-byte) column on the table.
+ * Create a new unsigned integer (4-byte) column on the table.
*
* @param string $column
* @param bool $autoIncrement
* @return \Illuminate\Support\Fluent
*/
- public function unsignedTinyInteger($column, $autoIncrement = false)
+ public function unsignedInteger($column, $autoIncrement = false)
{
- return $this->tinyInteger($column, $autoIncrement, true);
+ return $this->integer($column, $autoIncrement, true);
}
/**
- * Create a new unsigned small integer (2-byte) column on the table.
+ * Create a new unsigned tiny integer (1-byte) column on the table.
*
* @param string $column
* @param bool $autoIncrement
* @return \Illuminate\Support\Fluent
*/
- public function unsignedSmallInteger($column, $autoIncrement = false)
+ public function unsignedTinyInteger($column, $autoIncrement = false)
{
- return $this->smallInteger($column, $autoIncrement, true);
+ return $this->tinyInteger($column, $autoIncrement, true);
}
/**
- * Create a new unsigned medium integer (3-byte) column on the table.
+ * Create a new unsigned small integer (2-byte) column on the table.
*
* @param string $column
* @param bool $autoIncrement
* @return \Illuminate\Support\Fluent
*/
- public function unsignedMediumInteger($column, $autoIncrement = false)
+ public function unsignedSmallInteger($column, $autoIncrement = false)
{
- return $this->mediumInteger($column, $autoIncrement, true);
+ return $this->smallInteger($column, $autoIncrement, true);
}
/**
- * Create a new unsigned integer (4-byte) column on the table.
+ * Create a new unsigned medium integer (3-byte) column on the table.
*
* @param string $column
* @param bool $autoIncrement
* @return \Illuminate\Support\Fluent
*/
- public function unsignedInteger($column, $autoIncrement = false)
+ public function unsignedMediumInteger($column, $autoIncrement = false)
{
- return $this->integer($column, $autoIncrement, true);
+ return $this->mediumInteger($column, $autoIncrement, true);
}
/**
@@ -788,25 +784,25 @@ public function timestampTz($column)
/**
* Add nullable creation and update timestamps to the table.
*
- * Alias for self::timestamps().
- *
* @return void
*/
- public function nullableTimestamps()
+ public function timestamps()
{
- $this->timestamps();
+ $this->timestamp('created_at')->nullable();
+
+ $this->timestamp('updated_at')->nullable();
}
/**
* Add nullable creation and update timestamps to the table.
*
+ * Alias for self::timestamps().
+ *
* @return void
*/
- public function timestamps()
+ public function nullableTimestamps()
{
- $this->timestamp('created_at')->nullable();
-
- $this->timestamp('updated_at')->nullable();
+ $this->timestamps();
}
/**
@@ -927,6 +923,29 @@ public function rememberToken()
return $this->string('remember_token', 100)->nullable();
}
+ /**
+ * Add a new index command to the blueprint.
+ *
+ * @param string $type
+ * @param string|array $columns
+ * @param string $index
+ * @param string|null $algorithm
+ * @return \Illuminate\Support\Fluent
+ */
+ protected function indexCommand($type, $columns, $index, $algorithm = null)
+ {
+ $columns = (array) $columns;
+
+ // If no name was specified for this index, we will create one using a basic
+ // convention of the table name, followed by the columns, followed by an
+ // index type, such as primary or index, which makes the index unique.
+ $index = $index ?: $this->createIndexName($type, $columns);
+
+ return $this->addCommand(
+ $type, compact('index', 'columns', 'algorithm')
+ );
+ }
+
/**
* Create a new drop index command on the blueprint.
*
@@ -943,37 +962,12 @@ protected function dropIndexCommand($command, $type, $index)
// to drop an index merely by specifying the columns involved without the
// conventional name, so we will build the index name from the columns.
if (is_array($index)) {
- $columns = $index;
-
- $index = $this->createIndexName($type, $columns);
+ $index = $this->createIndexName($type, $columns = $index);
}
return $this->indexCommand($command, $columns, $index);
}
- /**
- * Add a new index command to the blueprint.
- *
- * @param string $type
- * @param string|array $columns
- * @param string $index
- * @param string|null $algorithm
- * @return \Illuminate\Support\Fluent
- */
- protected function indexCommand($type, $columns, $index, $algorithm = null)
- {
- $columns = (array) $columns;
-
- // If no name was specified for this index, we will create one using a basic
- // convention of the table name, followed by the columns, followed by an
- // index type, such as primary or index, which makes the index unique.
- if (is_null($index)) {
- $index = $this->createIndexName($type, $columns);
- }
-
- return $this->addCommand($type, compact('index', 'columns', 'algorithm'));
- }
-
/**
* Create a default index name for the table.
*
@@ -998,9 +992,9 @@ protected function createIndexName($type, array $columns)
*/
public function addColumn($type, $name, array $parameters = [])
{
- $attributes = array_merge(compact('type', 'name'), $parameters);
-
- $this->columns[] = $column = new Fluent($attributes);
+ $this->columns[] = $column = new Fluent(
+ array_merge(compact('type', 'name'), $parameters)
+ );
return $column;
} | true |
Other | laravel | framework | ab1627d4c08ad9437419f669ab4858f2683d7a1c.json | Continue work on grammars. | src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php | @@ -791,10 +791,10 @@ protected function modifyComment(Blueprint $blueprint, Fluent $column)
*/
protected function wrapValue($value)
{
- if ($value === '*') {
- return $value;
+ if ($value !== '*') {
+ return '`'.str_replace('`', '``', $value).'`';
}
- return '`'.str_replace('`', '``', $value).'`';
+ return $value;
}
} | true |
Other | laravel | framework | f91f0191c8c7e909400413517459a208fc941529.json | Apply fixes from StyleCI (#17132) | src/Illuminate/Database/Query/Grammars/PostgresGrammar.php | @@ -75,7 +75,7 @@ protected function compileLock(Builder $query, $value)
*/
public function compileInsertGetId(Builder $query, $values, $sequence)
{
- if (!is_null($sequence)) {
+ if (! is_null($sequence)) {
$sequence = 'id';
}
| false |
Other | laravel | framework | f637c2f9f32cc47209bb877de94d1c7489367b60.json | Apply fixes from StyleCI (#17126) | tests/Bus/BusDispatcherTest.php | @@ -78,31 +78,31 @@ public function testDispatcherCanDispatchStandAloneHandler()
$this->assertInstanceOf(StandAloneCommand::class, $response);
}
- public function testOnConnectionOnJobWhenDispatching()
- {
- $container = new Container;
- $container->singleton('config', function () {
- return new Config([
- 'queue' => [
- 'default' => 'null',
- 'connections' => [
- 'null' => ['driver' => 'null'],
- ],
- ],
- ]);
- });
-
- $dispatcher = new Dispatcher($container, function () {
- $mock = m::mock('Illuminate\Contracts\Queue\Queue');
- $mock->shouldReceive('push')->once();
-
- return $mock;
- });
-
- $job = (new ShouldNotBeDispatched)->onConnection('null');
-
- $dispatcher->dispatch($job);
- }
+ public function testOnConnectionOnJobWhenDispatching()
+ {
+ $container = new Container;
+ $container->singleton('config', function () {
+ return new Config([
+ 'queue' => [
+ 'default' => 'null',
+ 'connections' => [
+ 'null' => ['driver' => 'null'],
+ ],
+ ],
+ ]);
+ });
+
+ $dispatcher = new Dispatcher($container, function () {
+ $mock = m::mock('Illuminate\Contracts\Queue\Queue');
+ $mock->shouldReceive('push')->once();
+
+ return $mock;
+ });
+
+ $job = (new ShouldNotBeDispatched)->onConnection('null');
+
+ $dispatcher->dispatch($job);
+ }
}
class BusInjectionStub
@@ -152,11 +152,11 @@ public function handle(StandAloneCommand $command)
class ShouldNotBeDispatched implements Illuminate\Contracts\Queue\ShouldQueue
{
- use Illuminate\Bus\Queueable,
- Illuminate\Queue\InteractsWithQueue;
+ use Illuminate\Bus\Queueable,
+ Illuminate\Queue\InteractsWithQueue;
- public function handle()
- {
- throw new RuntimeException('This should not be run');
- }
+ public function handle()
+ {
+ throw new RuntimeException('This should not be run');
+ }
} | false |
Other | laravel | framework | dd305791c6520d2932922c2b2cdac072c899c0f3.json | Factorize cache events. | src/Illuminate/Cache/Events/AbstractCacheEvent.php | @@ -0,0 +1,46 @@
+<?php
+
+namespace Illuminate\Cache\Events;
+
+abstract class AbstractCacheEvent
+{
+ /**
+ * The key of the event.
+ *
+ * @var string
+ */
+ public $key;
+
+ /**
+ * The tags that were assigned to the key.
+ *
+ * @var array
+ */
+ public $tags;
+
+ /**
+ * Create a new event instance.
+ *
+ * @param string $key
+ * @param array $tags
+ * @return void
+ */
+ public function __construct($key, array $tags = [])
+ {
+ $this->key = $key;
+ $this->tags = $tags;
+ }
+
+ /**
+ * Set the tags for the cache event.
+ *
+ * @param array $tags
+ * @return $this
+ */
+ public function setTags($tags)
+ {
+ $this->tags = $tags;
+
+ return $this;
+ }
+} | true |
Other | laravel | framework | dd305791c6520d2932922c2b2cdac072c899c0f3.json | Factorize cache events. | src/Illuminate/Cache/Events/CacheEvent.php | @@ -1,19 +0,0 @@
-<?php
-
-namespace Illuminate\Cache\Events;
-
-class CacheEvent
-{
- /**
- * Set the tags for the cache event.
- *
- * @param array $tags
- * @return $this
- */
- public function setTags($tags)
- {
- $this->tags = $tags;
-
- return $this;
- }
-} | true |
Other | laravel | framework | dd305791c6520d2932922c2b2cdac072c899c0f3.json | Factorize cache events. | src/Illuminate/Cache/Events/CacheHit.php | @@ -2,29 +2,15 @@
namespace Illuminate\Cache\Events;
-class CacheHit extends CacheEvent
+class CacheHit extends AbstractCacheEvent
{
- /**
- * The key that was hit.
- *
- * @var string
- */
- public $key;
-
/**
* The value that was retrieved.
*
* @var mixed
*/
public $value;
- /**
- * The tags that were assigned to the key.
- *
- * @var array
- */
- public $tags;
-
/**
* Create a new event instance.
*
@@ -35,8 +21,7 @@ class CacheHit extends CacheEvent
*/
public function __construct($key, $value, array $tags = [])
{
- $this->key = $key;
- $this->tags = $tags;
+ parent::__construct($key, $tags);
$this->value = $value;
}
} | true |
Other | laravel | framework | dd305791c6520d2932922c2b2cdac072c899c0f3.json | Factorize cache events. | src/Illuminate/Cache/Events/CacheMissed.php | @@ -2,32 +2,7 @@
namespace Illuminate\Cache\Events;
-class CacheMissed extends CacheEvent
+class CacheMissed extends AbstractCacheEvent
{
- /**
- * The key that was missed.
- *
- * @var string
- */
- public $key;
-
- /**
- * The tags that were assigned to the key.
- *
- * @var array
- */
- public $tags;
-
- /**
- * Create a new event instance.
- *
- * @param string $key
- * @param array $tags
- * @return void
- */
- public function __construct($key, array $tags = [])
- {
- $this->key = $key;
- $this->tags = $tags;
- }
+ //
} | true |
Other | laravel | framework | dd305791c6520d2932922c2b2cdac072c899c0f3.json | Factorize cache events. | src/Illuminate/Cache/Events/KeyForgotten.php | @@ -2,32 +2,7 @@
namespace Illuminate\Cache\Events;
-class KeyForgotten extends CacheEvent
+class KeyForgotten extends AbstractCacheEvent
{
- /**
- * The key that was forgotten.
- *
- * @var string
- */
- public $key;
-
- /**
- * The tags that were assigned to the key.
- *
- * @var array
- */
- public $tags;
-
- /**
- * Create a new event instance.
- *
- * @param string $key
- * @param array $tags
- * @return void
- */
- public function __construct($key, $tags = [])
- {
- $this->key = $key;
- $this->tags = $tags;
- }
+ //
} | true |
Other | laravel | framework | dd305791c6520d2932922c2b2cdac072c899c0f3.json | Factorize cache events. | src/Illuminate/Cache/Events/KeyWritten.php | @@ -2,15 +2,8 @@
namespace Illuminate\Cache\Events;
-class KeyWritten extends CacheEvent
+class KeyWritten extends AbstractCacheEvent
{
- /**
- * The key that was written.
- *
- * @var string
- */
- public $key;
-
/**
* The value that was written.
*
@@ -25,13 +18,6 @@ class KeyWritten extends CacheEvent
*/
public $minutes;
- /**
- * The tags that were assigned to the key.
- *
- * @var array
- */
- public $tags;
-
/**
* Create a new event instance.
*
@@ -43,8 +29,7 @@ class KeyWritten extends CacheEvent
*/
public function __construct($key, $value, $minutes, $tags = [])
{
- $this->key = $key;
- $this->tags = $tags;
+ parent::__construct($key, $tags);
$this->value = $value;
$this->minutes = $minutes;
} | true |
Other | laravel | framework | 602efbadde06601577904c66608829087f2ce771.json | Remove unnecessary variable (#17113) | tests/Broadcasting/BroadcasterTest.php | @@ -63,7 +63,7 @@ public function testNotFoundThrowsHttpException()
$broadcaster = new FakeBroadcaster();
$callback = function ($user, BroadcasterTestEloquentModelNotFoundStub $model) {
};
- $parameters = $broadcaster->extractAuthParameters('asd.{model}', 'asd.1', $callback);
+ $broadcaster->extractAuthParameters('asd.{model}', 'asd.1', $callback);
}
}
| false |
Other | laravel | framework | e9ed2169c1420197fb14f1e9e49a5b0884804e02.json | Allow float value as expiration (#17106) | src/Illuminate/Cache/MemcachedStore.php | @@ -199,7 +199,7 @@ public function flush()
*/
protected function toTimestamp($minutes)
{
- return $minutes > 0 ? Carbon::now()->addMinutes($minutes)->getTimestamp() : 0;
+ return $minutes > 0 ? Carbon::now()->addSeconds($minutes * 60)->getTimestamp() : 0;
}
/** | false |
Other | laravel | framework | fbf68a431f65ccbdb1b16c9eec6e878e7e6d645c.json | Simplify method (#17111) | src/Illuminate/Auth/Access/Gate.php | @@ -197,12 +197,10 @@ public function denies($ability, $arguments = [])
public function check($ability, $arguments = [])
{
try {
- $result = $this->raw($ability, $arguments);
+ return (bool) $this->raw($ability, $arguments);
} catch (AuthorizationException $e) {
return false;
}
-
- return (bool) $result;
}
/** | false |
Other | laravel | framework | 118d50b7eee0f86849b866f055d1e3c823f9f431.json | Remove unused variable (#17109) | tests/Container/ContainerTest.php | @@ -121,7 +121,6 @@ public function testBindingsCanBeOverridden()
{
$container = new Container;
$container['foo'] = 'bar';
- $foo = $container['foo'];
$container['foo'] = 'baz';
$this->assertEquals('baz', $container['foo']);
} | false |
Other | laravel | framework | 82a2b1773cc3cd16beea4a2205a7cc9620867fab.json | Apply fixes from StyleCI (#17089) | src/Illuminate/Database/Connection.php | @@ -5,7 +5,6 @@
use PDO;
use Closure;
use Exception;
-use Throwable;
use LogicException;
use DateTimeInterface;
use Illuminate\Support\Arr;
@@ -479,7 +478,7 @@ public function unprepared($query)
*/
public function pretend(Closure $callback)
{
- return $this->withFreshQueryLog(function() use ($callback) {
+ return $this->withFreshQueryLog(function () use ($callback) {
$this->pretending = true;
// Basically to make the database connection "pretend", we will just return
@@ -783,7 +782,6 @@ protected function event($event)
if (isset($this->events)) {
$this->events->fire($event);
}
-
}
/** | false |
Other | laravel | framework | 88c745afb24aef1feeb4aaa76c4f87d0cf49ec47.json | Remove unneeded variable. | src/Illuminate/Database/Connection.php | @@ -297,7 +297,7 @@ public function selectFromWriteConnection($query, $bindings = [])
*/
public function select($query, $bindings = [], $useReadPdo = true)
{
- return $this->run($query, $bindings, function ($me, $query, $bindings) use ($useReadPdo) {
+ return $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) {
if ($this->pretending()) {
return [];
}
@@ -325,8 +325,8 @@ public function select($query, $bindings = [], $useReadPdo = true)
*/
public function cursor($query, $bindings = [], $useReadPdo = true)
{
- $statement = $this->run($query, $bindings, function ($me, $query, $bindings) use ($useReadPdo) {
- if ($me->pretending()) {
+ $statement = $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) {
+ if ($this->pretending()) {
return [];
}
@@ -338,8 +338,8 @@ public function cursor($query, $bindings = [], $useReadPdo = true)
$statement->setFetchMode($this->fetchMode);
- $me->bindValues(
- $statement, $me->prepareBindings($bindings)
+ $this->bindValues(
+ $statement, $this->prepareBindings($bindings)
);
// Next, we'll execute the query against the database and return the statement
@@ -428,14 +428,14 @@ public function delete($query, $bindings = [])
*/
public function statement($query, $bindings = [])
{
- return $this->run($query, $bindings, function ($me, $query, $bindings) {
- if ($me->pretending()) {
+ return $this->run($query, $bindings, function ($query, $bindings) {
+ if ($this->pretending()) {
return true;
}
$statement = $this->getPdo()->prepare($query);
- $this->bindValues($statement, $me->prepareBindings($bindings));
+ $this->bindValues($statement, $this->prepareBindings($bindings));
return $statement->execute();
});
@@ -450,17 +450,17 @@ public function statement($query, $bindings = [])
*/
public function affectingStatement($query, $bindings = [])
{
- return $this->run($query, $bindings, function ($me, $query, $bindings) {
- if ($me->pretending()) {
+ return $this->run($query, $bindings, function ($query, $bindings) {
+ if ($this->pretending()) {
return 0;
}
// For update or delete statements, we want to get the number of rows affected
// by the statement and return that back to the developer. We'll first need
// to execute the statement and then we'll use PDO to fetch the affected.
- $statement = $me->getPdo()->prepare($query);
+ $statement = $this->getPdo()->prepare($query);
- $this->bindValues($statement, $me->prepareBindings($bindings));
+ $this->bindValues($statement, $this->prepareBindings($bindings));
$statement->execute();
@@ -476,12 +476,12 @@ public function affectingStatement($query, $bindings = [])
*/
public function unprepared($query)
{
- return $this->run($query, [], function ($me, $query) {
- if ($me->pretending()) {
+ return $this->run($query, [], function ($query) {
+ if ($this->pretending()) {
return true;
}
- return (bool) $me->getPdo()->exec($query);
+ return (bool) $this->getPdo()->exec($query);
});
}
@@ -729,7 +729,7 @@ protected function runQueryCallback($query, $bindings, Closure $callback)
// run the SQL against the PDO connection. Then we can calculate the time it
// took to execute and log the query SQL, bindings and time in our memory.
try {
- $result = $callback($this, $query, $bindings);
+ $result = $callback($query, $bindings);
}
// If an exception occurs when attempting to run a query, we'll format the error | false |
Other | laravel | framework | ace9702a1a7b17cb33b2f61eb46973de5e4111e6.json | Refactor the MySQL connector. | src/Illuminate/Database/Connectors/MySqlConnector.php | @@ -27,33 +27,61 @@ public function connect(array $config)
$connection->exec("use `{$config['database']}`;");
}
- $collation = $config['collation'];
+ $this->configureEncoding($connection, $config);
- // Next we will set the "names" and "collation" on the clients connections so
- // a correct character set will be used by this client. The collation also
- // is set on the server but needs to be set here on this client objects.
- if (isset($config['charset'])) {
- $charset = $config['charset'];
-
- $names = "set names '{$charset}'".
- (! is_null($collation) ? " collate '{$collation}'" : '');
-
- $connection->prepare($names)->execute();
- }
// Next, we will check to see if a timezone has been specified in this config
// and if it has we will issue a statement to modify the timezone with the
// database. Setting this DB timezone is an optional configuration item.
- if (isset($config['timezone'])) {
- $connection->prepare(
- 'set time_zone="'.$config['timezone'].'"'
- )->execute();
- }
+ $this->configureTimezone($connection, $config);
$this->setModes($connection, $config);
return $connection;
}
+ /**
+ * Set the connection character set and collation.
+ *
+ * @param \PDO $connection
+ * @param array $config
+ * @return void
+ */
+ protected function configureEncoding($connection, array $config)
+ {
+ if (! isset($config['charset'])) {
+ return $connection;
+ }
+
+ $connection->prepare(
+ "set names '{$config['charset']}'".$this->getCollation($config)
+ )->execute();
+ }
+
+ /**
+ * Get the collation for the configuration.
+ *
+ * @param array $config
+ * @return string
+ */
+ protected function getCollation(array $config)
+ {
+ return ! is_null($config['collation']) ? " collate '{$config['collation']}'" : '';
+ }
+
+ /**
+ * Set the timezone on the connection.
+ *
+ * @param \PDO $connection
+ * @param array $config
+ * @return void
+ */
+ protected function configureTimezone($connection, array $config)
+ {
+ if (isset($config['timezone'])) {
+ $connection->prepare('set time_zone="'.$config['timezone'].'"')->execute();
+ }
+ }
+
/**
* Create a DSN string from a configuration.
*
@@ -64,7 +92,9 @@ public function connect(array $config)
*/
protected function getDsn(array $config)
{
- return $this->configHasSocket($config) ? $this->getSocketDsn($config) : $this->getHostDsn($config);
+ return $this->hasSocket($config)
+ ? $this->getSocketDsn($config)
+ : $this->getHostDsn($config);
}
/**
@@ -73,7 +103,7 @@ protected function getDsn(array $config)
* @param array $config
* @return bool
*/
- protected function configHasSocket(array $config)
+ protected function hasSocket(array $config)
{
return isset($config['unix_socket']) && ! empty($config['unix_socket']);
}
@@ -100,8 +130,8 @@ protected function getHostDsn(array $config)
extract($config, EXTR_SKIP);
return isset($port)
- ? "mysql:host={$host};port={$port};dbname={$database}"
- : "mysql:host={$host};dbname={$database}";
+ ? "mysql:host={$host};port={$port};dbname={$database}"
+ : "mysql:host={$host};dbname={$database}";
}
/**
@@ -114,15 +144,37 @@ protected function getHostDsn(array $config)
protected function setModes(PDO $connection, array $config)
{
if (isset($config['modes'])) {
- $modes = implode(',', $config['modes']);
-
- $connection->prepare("set session sql_mode='{$modes}'")->execute();
+ $this->setCustomModes($connection, $config);
} elseif (isset($config['strict'])) {
if ($config['strict']) {
- $connection->prepare("set session sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'")->execute();
+ $connection->prepare($this->strictMode())->execute();
} else {
$connection->prepare("set session sql_mode='NO_ENGINE_SUBSTITUTION'")->execute();
}
}
}
+
+ /**
+ * Set the custom modes on the connection.
+ *
+ * @param \PDO $connection
+ * @param array $config
+ * @return void
+ */
+ protected function setCustomModes(PDO $connection, array $config)
+ {
+ $modes = implode(',', $config['modes']);
+
+ $connection->prepare("set session sql_mode='{$modes}'")->execute();
+ }
+
+ /**
+ * Get the query to enable strict mode.
+ *
+ * @return string
+ */
+ protected function strictMode()
+ {
+ return "set session sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'";
+ }
} | false |
Other | laravel | framework | bfa6e3c948ec2aaf41486da6021061d1ea09e24c.json | Apply fixes from StyleCI (#17081) | src/Illuminate/Foundation/Testing/TestResponse.php | @@ -3,7 +3,6 @@
namespace Illuminate\Foundation\Testing;
use Closure;
-use Illuminate\Support\Str;
use Illuminate\Http\Response;
use Illuminate\Contracts\View\View;
use PHPUnit_Framework_Assert as PHPUnit; | false |
Other | laravel | framework | feb52bf966c0ea517ec0cf688b5a2534b50a8268.json | improve facade loading | src/Illuminate/Foundation/AliasLoader.php | @@ -18,6 +18,13 @@ class AliasLoader
*/
protected $registered = false;
+ /**
+ * The namespace for all real-time facades.
+ *
+ * @var string
+ */
+ protected static $facadeNamespace = 'Facades\\';
+
/**
* The singleton instance of the loader.
*
@@ -62,11 +69,69 @@ public static function getInstance(array $aliases = [])
*/
public function load($alias)
{
+ if (static::$facadeNamespace && strpos($alias, static::$facadeNamespace) === 0) {
+ $this->loadFacade($alias);
+
+ return true;
+ }
+
if (isset($this->aliases[$alias])) {
return class_alias($this->aliases[$alias], $alias);
}
}
+ /**
+ * Load a real-time facade for the given alias.
+ *
+ * @param string $alias
+ * @return bool
+ */
+ protected function loadFacade($alias)
+ {
+ tap($this->ensureFacadeExists($alias), function ($path) {
+ require $path;
+ });
+ }
+
+ /**
+ * Ensure that the given alias has an existing real-time facade class.
+ *
+ * @param string $class
+ * @return string
+ */
+ protected function ensureFacadeExists($alias)
+ {
+ if (file_exists($path = base_path('bootstrap/cache/facade-'.sha1($alias).'.php'))) {
+ return $path;
+ }
+
+ file_put_contents($path, $this->formatFacadeStub(
+ $alias, file_get_contents(__DIR__.'/stubs/facade.stub')
+ ));
+
+ return $path;
+ }
+
+ /**
+ * Format the facade stub with the proper namespace and class.
+ *
+ * @param string $alias
+ * @param string $stub
+ * @return string
+ */
+ protected function formatFacadeStub($alias, $stub)
+ {
+ $replacements = [
+ str_replace('/', '\\', dirname(str_replace('\\', '/', $alias))),
+ class_basename($alias),
+ substr($alias, strlen(static::$facadeNamespace)),
+ ];
+
+ return str_replace(
+ ['DummyNamespace', 'DummyClass', 'DummyTarget'], $replacements, $stub
+ );
+ }
+
/**
* Add an alias to the loader.
*
@@ -145,6 +210,17 @@ public function setRegistered($value)
$this->registered = $value;
}
+ /**
+ * Set the real-time facade namespace.
+ *
+ * @param string $namespace
+ * @return void
+ */
+ public static function setFacadeNamespace($namespace)
+ {
+ static::$facadeNamespace = rtrim($namespace, '\\').'\\';
+ }
+
/**
* Set the value of the singleton alias loader.
* | true |
Other | laravel | framework | feb52bf966c0ea517ec0cf688b5a2534b50a8268.json | improve facade loading | src/Illuminate/Foundation/Application.php | @@ -820,6 +820,16 @@ public function shouldSkipMiddleware()
$this->make('middleware.disable') === true;
}
+ /**
+ * Get the path to the cached services.php file.
+ *
+ * @return string
+ */
+ public function getCachedServicesPath()
+ {
+ return $this->bootstrapPath().'/cache/services.php';
+ }
+
/**
* Determine if the application configuration is cached.
*
@@ -860,16 +870,6 @@ public function getCachedRoutesPath()
return $this->bootstrapPath().'/cache/routes.php';
}
- /**
- * Get the path to the cached services.php file.
- *
- * @return string
- */
- public function getCachedServicesPath()
- {
- return $this->bootstrapPath().'/cache/services.php';
- }
-
/**
* Determine if the application is currently down for maintenance.
*
@@ -977,6 +977,17 @@ public function isDeferredService($service)
return isset($this->deferredServices[$service]);
}
+ /**
+ * Configure the real-time facade namespace.
+ *
+ * @param string $namespace
+ * @return void
+ */
+ public function provideFacades($namespace)
+ {
+ AliasLoader::setFacadeNamespace($namespace);
+ }
+
/**
* Define a callback to be used to configure Monolog.
* | true |
Other | laravel | framework | feb52bf966c0ea517ec0cf688b5a2534b50a8268.json | improve facade loading | src/Illuminate/Foundation/stubs/facade.stub | @@ -0,0 +1,21 @@
+<?php
+
+namespace DummyNamespace;
+
+use Illuminate\Support\Facades\Facade;
+
+/**
+ * @see \DummyTarget
+ */
+class DummyClass extends Facade
+{
+ /**
+ * Get the registered name of the component.
+ *
+ * @return string
+ */
+ protected static function getFacadeAccessor()
+ {
+ return 'DummyTarget';
+ }
+} | true |
Other | laravel | framework | d25de019447e66fe44376a13dbf09956cdadd354.json | Remove 2 duplicate RouteCollection tests. (#17057) | tests/Routing/RouteCollectionTest.php | @@ -41,24 +41,6 @@ public function testRouteCollectionAddReturnsTheRoute()
$this->assertEquals($inputRoute, $outputRoute);
}
- public function testRouteCollectionAddRouteChangesCount()
- {
- $this->routeCollection->add(new Route('GET', 'foo', [
- 'uses' => 'FooController@index',
- 'as' => 'foo_index',
- ]));
- $this->assertCount(1, $this->routeCollection);
- }
-
- public function testRouteCollectionIsCountable()
- {
- $this->routeCollection->add(new Route('GET', 'foo', [
- 'uses' => 'FooController@index',
- 'as' => 'foo_index',
- ]));
- $this->assertCount(1, $this->routeCollection);
- }
-
public function testRouteCollectionCanRetrieveByName()
{
$this->routeCollection->add($routeIndex = new Route('GET', 'foo/index', [ | false |
Other | laravel | framework | 712b99df85c7a9daf8fb9f0a9a34fa90cbe99f44.json | Remove accessors that are never used. | src/Illuminate/Queue/Worker.php | @@ -512,25 +512,4 @@ public function setCache(CacheContract $cache)
{
$this->cache = $cache;
}
-
- /**
- * Get the queue manager instance.
- *
- * @return \Illuminate\Queue\QueueManager
- */
- public function getManager()
- {
- return $this->manager;
- }
-
- /**
- * Set the queue manager instance.
- *
- * @param \Illuminate\Queue\QueueManager $manager
- * @return void
- */
- public function setManager(QueueManager $manager)
- {
- $this->manager = $manager;
- }
} | false |
Other | laravel | framework | a82a25f58252eab6831a0efde35a17403710abdc.json | add listener optinos | src/Illuminate/Queue/Console/ListenCommand.php | @@ -4,8 +4,7 @@
use Illuminate\Queue\Listener;
use Illuminate\Console\Command;
-use Symfony\Component\Console\Input\InputOption;
-use Symfony\Component\Console\Input\InputArgument;
+use Illuminate\Queue\ListenerOptions;
class ListenCommand extends Command
{
@@ -14,7 +13,14 @@ class ListenCommand extends Command
*
* @var string
*/
- protected $name = 'queue:listen';
+ protected $signature = 'queue:listen
+ {connection? : The name of connection}
+ {--queue= : The queue to listen on}
+ {--delay=0 : Amount of time to delay failed jobs}
+ {--memory=128 : The memory limit in megabytes}
+ {--sleep=3 : Number of seconds to sleep when no job is available}
+ {--timeout=60 : The number of seconds a child process can run}
+ {--tries=0 : Number of times to attempt a job before logging it failed}';
/**
* The console command description.
@@ -40,7 +46,7 @@ public function __construct(Listener $listener)
{
parent::__construct();
- $this->listener = $listener;
+ $this->setOutputHandler($this->listener = $listener);
}
/**
@@ -50,26 +56,15 @@ public function __construct(Listener $listener)
*/
public function fire()
{
- $this->setListenerOptions();
-
- $connection = $this->input->getArgument('connection');
-
- // The memory limit is the amount of memory we will allow the script to occupy
- // before killing it and letting a process manager restart it for us, which
- // is to protect us against any memory leaks that will be in the scripts.
- $memory = $this->input->getOption('memory');
-
- $timeout = $this->input->getOption('timeout');
-
- $delay = $this->input->getOption('delay');
-
// We need to get the right queue for the connection which is set in the queue
// configuration file for the application. We will pull it based on the set
// connection being run for the queue operation currently being executed.
- $queue = $this->getQueue($connection);
+ $queue = $this->getQueue(
+ $connection = $this->input->getArgument('connection')
+ );
$this->listener->listen(
- $connection, $queue, $delay, $memory, $timeout
+ $connection, $queue, $this->gatherOptions()
);
}
@@ -81,66 +76,36 @@ public function fire()
*/
protected function getQueue($connection)
{
- if (is_null($connection)) {
- $connection = $this->laravel['config']['queue.default'];
- }
+ $connection = $connection ?: $this->laravel['config']['queue.default'];
- $queue = $this->laravel['config']->get(
+ return $this->input->getOption('queue') ?: $this->laravel['config']->get(
"queue.connections.{$connection}.queue", 'default'
);
-
- return $this->input->getOption('queue') ?: $queue;
}
/**
- * Set the options on the queue listener.
+ * Get the listener options for the command.
*
- * @return void
+ * @return \Illuminate\Queue\ListenerOptions
*/
- protected function setListenerOptions()
+ protected function gatherOptions()
{
- $this->listener->setEnvironment($this->laravel->environment());
-
- $this->listener->setSleep($this->option('sleep'));
-
- $this->listener->setMaxTries($this->option('tries'));
-
- $this->listener->setOutputHandler(function ($type, $line) {
- $this->output->write($line);
- });
- }
-
- /**
- * Get the console command arguments.
- *
- * @return array
- */
- protected function getArguments()
- {
- return [
- ['connection', InputArgument::OPTIONAL, 'The name of connection'],
- ];
+ return new ListenerOptions(
+ $this->option('env'), $this->option('delay'),
+ $this->option('memory'), $this->option('timeout')
+ );
}
/**
- * Get the console command options.
+ * Set the options on the queue listener.
*
- * @return array
+ * @param \Illuminate\Queue\Listener $listener
+ * @return void
*/
- protected function getOptions()
+ protected function setOutputHandler(Listener $listener)
{
- return [
- ['queue', null, InputOption::VALUE_OPTIONAL, 'The queue to listen on', null],
-
- ['delay', null, InputOption::VALUE_OPTIONAL, 'Amount of time to delay failed jobs', 0],
-
- ['memory', null, InputOption::VALUE_OPTIONAL, 'The memory limit in megabytes', 128],
-
- ['timeout', null, InputOption::VALUE_OPTIONAL, 'Seconds a job may run before timing out', 60],
-
- ['sleep', null, InputOption::VALUE_OPTIONAL, 'Seconds to wait before checking queue for jobs', 3],
-
- ['tries', null, InputOption::VALUE_OPTIONAL, 'Number of times to attempt a job before logging it failed', 0],
- ];
+ $listener->setOutputHandler(function ($type, $line) {
+ $this->output->write($line);
+ });
}
} | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.