id
stringlengths
6
6
text
stringlengths
20
17.2k
title
stringclasses
1 value
193264
public function testImplicitRouteBindingChildHasUlids() { $user = ImplicitBindingUser::create(['name' => 'Michael Nabil']); $post = ImplicitBindingPost::create(['user_id' => $user->id]); $tag = ImplicitBindingTag::create([ 'slug' => 'slug', 'post_id' => $post->id, ]); config(['app.key' => str_repeat('a', 32)]); $function = function (ImplicitBindingPost $post, ImplicitBindingTag $tag) { return [$post, $tag]; }; Route::middleware(['web'])->group(function () use ($function) { Route::get('/post/{post}/tag/{tag}', $function); Route::get('/post/{post}/tag-id/{tag:id}', $function); Route::get('/post/{post}/tag-slug/{tag:slug}', $function); }); $response = $this->getJson("/post/{$post->id}/tag/{$tag->slug}"); $response->assertJsonFragment(['id' => $tag->id]); $response = $this->getJson("/post/{$post->id}/tag-id/{$tag->id}"); $response->assertJsonFragment(['id' => $tag->id]); $response = $this->getJson("/post/{$post->id}/tag-slug/{$tag->slug}"); $response->assertJsonFragment(['id' => $tag->id]); } } class ImplicitBindingUser extends Model { use SoftDeletes; public $table = 'users'; protected $fillable = ['name']; public function posts() { return $this->hasMany(ImplicitBindingPost::class, 'user_id'); } public function comments() { return $this->hasMany(ImplicitBindingComment::class, 'user_id'); } } class ImplicitBindingPost extends Model { public $table = 'posts'; protected $fillable = ['user_id']; public function tags() { return $this->hasMany(ImplicitBindingTag::class, 'post_id'); } } class ImplicitBindingTag extends Model { use HasUlids; public $table = 'tags'; protected $fillable = ['slug', 'post_id']; public function getRouteKeyName() { return 'slug'; } } class ImplicitBindingComment extends Model { use HasUuids; public $table = 'comments'; protected $fillable = ['slug', 'user_id']; public function getRouteKeyName() { return 'slug'; } }
193273
public function testRouteBindingsAreProperlySaved() { $this->routeCollection->add($this->newRoute('GET', 'posts/{post:slug}/show', [ 'uses' => 'FooController@index', 'prefix' => 'profile/{user:username}', 'as' => 'foo', ])); $route = $this->collection()->getByName('foo'); $this->assertSame('profile/{user}/posts/{post}/show', $route->uri()); $this->assertSame(['user' => 'username', 'post' => 'slug'], $route->bindingFields()); } public function testMatchingSlashedRoutes() { $this->routeCollection->add( $route = $this->newRoute('GET', 'foo/bar', ['uses' => 'FooController@index', 'as' => 'foo']) ); $this->assertSame('foo', $this->collection()->match(Request::create('/foo/bar/'))->getName()); } public function testMatchingUriWithQuery() { $this->routeCollection->add( $route = $this->newRoute('GET', 'foo/bar', ['uses' => 'FooController@index', 'as' => 'foo']) ); $this->assertSame('foo', $this->collection()->match(Request::create('/foo/bar/?foo=bar'))->getName()); } public function testMatchingRootUri() { $this->routeCollection->add( $route = $this->newRoute('GET', '/', ['uses' => 'FooController@index', 'as' => 'foo']) ); $this->assertSame('foo', $this->collection()->match(Request::create('http://example.com'))->getName()); } public function testTrailingSlashIsTrimmedWhenMatchingCachedRoutes() { $this->routeCollection->add( $this->newRoute('GET', 'foo/bar', ['uses' => 'FooController@index', 'as' => 'foo']) ); $request = Request::create('/foo/bar/'); // Access to request path info before matching route $request->getPathInfo(); $this->assertSame('foo', $this->collection()->match($request)->getName()); } public function testRouteWithSamePathAndSameMethodButDiffDomainNameWithOptionsMethod() { $routes = [ 'foo_domain' => $this->newRoute('GET', 'same/path', [ 'uses' => 'FooController@index', 'as' => 'foo', 'domain' => 'foo.localhost', ]), 'bar_domain' => $this->newRoute('GET', 'same/path', [ 'uses' => 'BarController@index', 'as' => 'bar', 'domain' => 'bar.localhost', ]), 'no_domain' => $this->newRoute('GET', 'same/path', [ 'uses' => 'BarController@index', 'as' => 'no_domain', ]), ]; $this->routeCollection->add($routes['foo_domain']); $this->routeCollection->add($routes['bar_domain']); $this->routeCollection->add($routes['no_domain']); $expectedMethods = [ 'OPTIONS', ]; $this->assertSame($expectedMethods, $this->collection()->match( Request::create('http://foo.localhost/same/path', 'OPTIONS') )->methods); $this->assertSame($expectedMethods, $this->collection()->match( Request::create('http://bar.localhost/same/path', 'OPTIONS') )->methods); $this->assertSame($expectedMethods, $this->collection()->match( Request::create('http://no.localhost/same/path', 'OPTIONS') )->methods); $this->assertEquals([ 'HEAD' => [ 'foo.localhostsame/path' => $routes['foo_domain'], 'bar.localhostsame/path' => $routes['bar_domain'], 'same/path' => $routes['no_domain'], ], 'GET' => [ 'foo.localhostsame/path' => $routes['foo_domain'], 'bar.localhostsame/path' => $routes['bar_domain'], 'same/path' => $routes['no_domain'], ], ], $this->collection()->getRoutesByMethod()); } /** * Create a new Route object. * * @param array|string $methods * @param string $uri * @param mixed $action * @return \Illuminate\Routing\Route */ protected function newRoute($methods, $uri, $action) { return (new Route($methods, $uri, $action)) ->setRouter($this->router) ->setContainer($this->app); } /** * Create a new fallback Route object. * * @param mixed $action * @return \Illuminate\Routing\Route */ protected function fallbackRoute($action) { $placeholder = 'fallbackPlaceholder'; return $this->newRoute( 'GET', "{{$placeholder}}", $action )->where($placeholder, '.*')->fallback(); } }
193275
<?php namespace Illuminate\Tests\Integration\Routing; use Illuminate\Support\Facades\Route; use Orchestra\Testbench\TestCase; class FluentRoutingTest extends TestCase { public static $value = ''; public function testMiddlewareRunWhenRegisteredAsArrayOrParams() { $controller = function () { return 'Hello World'; }; Route::middleware(Middleware::class, Middleware2::class) ->get('before', $controller); Route::get('after', $controller) ->middleware(Middleware::class, Middleware2::class); Route::middleware([Middleware::class, Middleware2::class]) ->get('before_array', $controller); Route::get('after_array', $controller) ->middleware([Middleware::class, Middleware2::class]); Route::middleware(Middleware::class) ->get('before_after', $controller) ->middleware([Middleware2::class]); Route::middleware(Middleware::class) ->middleware(Middleware2::class) ->get('both_before', $controller); Route::get('both_after', $controller) ->middleware(Middleware::class) ->middleware(Middleware2::class); $this->assertSame('1_2', $this->get('before')->content()); $this->assertSame('1_2', $this->get('after')->content()); $this->assertSame('1_2', $this->get('before_array')->content()); $this->assertSame('1_2', $this->get('after_array')->content()); $this->assertSame('1_2', $this->get('before_after')->content()); $this->assertSame('1_2', $this->get('both_before')->content()); $this->assertSame('1_2', $this->get('both_after')->content()); $this->assertSame('1_2', $this->get('both_after')->content()); } public function testEmptyMiddlewareGroupAreHandledGracefully() { $controller = function () { return 'Hello World'; }; Route::middlewareGroup('public', []); Route::middleware('public') ->get('public', $controller); $this->assertSame('Hello World', $this->get('public')->content()); } } class Middleware { public function handle($request, $next) { FluentRoutingTest::$value = '1'; return $next($request); } } class Middleware2 { public function handle() { return FluentRoutingTest::$value.'_2'; } }
193298
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; class DynamicContentIsShown extends Migration { public function up() { Schema::create('blogs', function (Blueprint $table) { $table->increments('id'); $table->string('url')->nullable(); $table->string('name')->nullable(); }); DB::table('blogs')->insert([ ['url' => 'www.janedoe.com'], ['url' => 'www.johndoe.com'], ]); DB::statement("ALTER TABLE 'pseudo_table_name' MODIFY 'column_name' VARCHAR(191)"); /** @var \Illuminate\Support\Collection $tablesList */ $tablesList = DB::withoutPretending(function () { return DB::table('people')->get(); }); $tablesList->each(function ($person, $key) { DB::table('blogs')->where('blog_id', '=', $person->blog_id)->insert([ 'id' => $key + 1, 'name' => "{$person->name} Blog", ]); }); } }
193299
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; class DynamicContentNotShown extends Migration { public function up() { Schema::create('blogs', function (Blueprint $table) { $table->increments('id'); $table->string('url')->nullable(); $table->string('name')->nullable(); }); DB::table('blogs')->insert([ ['url' => 'www.janedoe.com'], ['url' => 'www.johndoe.com'], ]); DB::statement("ALTER TABLE 'pseudo_table_name' MODIFY 'column_name' VARCHAR(191)"); DB::table('people')->get()->each(function ($person, $key) { DB::table('blogs')->where('blog_id', '=', $person->blog_id)->insert([ 'id' => $key + 1, 'name' => "{$person->name} Blog", ]); }); } }
193315
<?php namespace Illuminate\Tests\Integration\Validation; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Str; use Illuminate\Tests\Integration\Database\DatabaseTestCase; use Illuminate\Translation\ArrayLoader; use Illuminate\Translation\Translator; use Illuminate\Validation\DatabasePresenceVerifier; use Illuminate\Validation\Validator; class ValidatorTest extends DatabaseTestCase { protected function setUp(): void { parent::setUp(); Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('uuid'); $table->string('first_name'); }); User::create(['uuid' => (string) Str::uuid(), 'first_name' => 'John']); User::create(['uuid' => (string) Str::uuid(), 'first_name' => 'Jim']); } public function testExists() { $validator = $this->getValidator(['first_name' => ['John', 'Taylor']], ['first_name' => 'exists:users']); $this->assertFalse($validator->passes()); } public function testUnique() { $validator = $this->getValidator(['first_name' => 'John'], ['first_name' => 'unique:'.User::class]); $this->assertFalse($validator->passes()); $validator = $this->getValidator(['first_name' => 'John'], ['first_name' => 'unique:'.User::class.',first_name,1']); $this->assertTrue($validator->passes()); $validator = $this->getValidator(['first_name' => 'Taylor'], ['first_name' => 'unique:'.User::class]); $this->assertTrue($validator->passes()); } public function testUniqueWithCustomModelKey() { $_SERVER['CUSTOM_MODEL_KEY_NAME'] = 'uuid'; $validator = $this->getValidator(['first_name' => 'John'], ['first_name' => 'unique:'.UserWithUuid::class]); $this->assertFalse($validator->passes()); $user = UserWithUuid::where('first_name', 'John')->first(); $validator = $this->getValidator(['first_name' => 'John'], ['first_name' => 'unique:'.UserWithUuid::class.',first_name,'.$user->uuid]); $this->assertTrue($validator->passes()); $validator = $this->getValidator(['first_name' => 'John'], ['first_name' => 'unique:users,first_name,'.$user->uuid.',uuid']); $this->assertTrue($validator->passes()); $validator = $this->getValidator(['first_name' => 'John'], ['first_name' => 'unique:users,first_name,'.$user->uuid.',id']); $this->assertFalse($validator->passes()); $validator = $this->getValidator(['first_name' => 'Taylor'], ['first_name' => 'unique:'.UserWithUuid::class]); $this->assertTrue($validator->passes()); unset($_SERVER['CUSTOM_MODEL_KEY_NAME']); } public function testImplicitAttributeFormatting() { $translator = new Translator(new ArrayLoader, 'en'); $translator->addLines(['validation.string' => ':attribute must be a string!'], 'en'); $validator = new Validator($translator, [['name' => 1]], ['*.name' => 'string']); $validator->setImplicitAttributesFormatter(function ($attribute) { [$line, $attribute] = explode('.', $attribute); return sprintf('%s at line %d', $attribute, $line + 1); }); $validator->passes(); $this->assertSame('name at line 1 must be a string!', $validator->getMessageBag()->all()[0]); } protected function getValidator(array $data, array $rules) { $translator = new Translator(new ArrayLoader, 'en'); $validator = new Validator($translator, $data, $rules); $validator->setPresenceVerifier(new DatabasePresenceVerifier($this->app['db'])); return $validator; } } class User extends Model { public $timestamps = false; protected $guarded = []; } class UserWithUuid extends Model { protected $table = 'users'; public $timestamps = false; protected $guarded = []; protected $keyType = 'string'; public $incrementing = false; public function getKeyName() { return 'uuid'; } }
193364
protected function cleanAsset($asset) { $path = public_path('build/assets'); unlink($path.$asset); rmdir($path); } protected function makeViteHotFile($path = null) { app()->usePublicPath(__DIR__); $path ??= public_path('hot'); file_put_contents($path, 'http://localhost:3000'); } protected function cleanViteHotFile($path = null) { $path ??= public_path('hot'); if (file_exists($path)) { unlink($path); } } }
193365
<?php namespace Illuminate\Tests\Foundation; use Exception; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Auth\Access\Response; use Illuminate\Container\Container; use Illuminate\Contracts\Translation\Translator; use Illuminate\Contracts\Validation\Factory as ValidationFactoryContract; use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\RedirectResponse; use Illuminate\Routing\Redirector; use Illuminate\Routing\UrlGenerator; use Illuminate\Validation\Factory as ValidationFactory; use Illuminate\Validation\ValidationException; use Mockery as m; use PHPUnit\Framework\TestCase;
193367
protected function createMockRedirector($request) { $redirector = $this->mocks['redirector'] = m::mock(Redirector::class); $redirector->shouldReceive('getUrlGenerator')->zeroOrMoreTimes() ->andReturn($generator = $this->createMockUrlGenerator()); $redirector->shouldReceive('to')->zeroOrMoreTimes() ->andReturn($this->createMockRedirectResponse()); $generator->shouldReceive('previous')->zeroOrMoreTimes() ->andReturn('previous'); return $redirector; } /** * Create a mock URL generator. * * @return \Illuminate\Routing\UrlGenerator */ protected function createMockUrlGenerator() { return $this->mocks['generator'] = m::mock(UrlGenerator::class); } /** * Create a mock redirect response. * * @return \Illuminate\Http\RedirectResponse */ protected function createMockRedirectResponse() { return $this->mocks['redirect'] = m::mock(RedirectResponse::class); } } class FoundationTestFormRequestStub extends FormRequest { public function rules() { return ['name' => 'required']; } public function authorize() { return true; } } class FoundationTestFormRequestNestedStub extends FormRequest { public function rules() { return ['nested.foo' => 'required', 'array.*' => 'integer']; } public function authorize() { return true; } } class FoundationTestFormRequestNestedChildStub extends FormRequest { public function rules() { return ['nested.foo' => 'required']; } public function authorize() { return true; } } class FoundationTestFormRequestNestedArrayStub extends FormRequest { public function rules() { return ['nested.*.bar' => 'required']; } public function authorize() { return true; } } class FoundationTestFormRequestTwiceStub extends FormRequest { public static $count = 0; public function rules() { return ['name' => 'required']; } public function withValidator(Validator $validator) { $validator->after(function ($validator) { self::$count++; }); } public function authorize() { return true; } } class FoundationTestFormRequestForbiddenStub extends FormRequest { public function authorize() { return false; } } class FoundationTestFormRequestHooks extends FormRequest { public function rules() { return ['name' => 'required']; } public function authorize() { return true; } public function prepareForValidation() { $this->replace(['name' => 'Taylor']); } public function passedValidation() { $this->replace(['name' => 'Adam']); } } class FoundationTestFormRequestForbiddenWithResponseStub extends FormRequest { public function authorize() { return Response::deny('foo'); } } class FoundationTestFormRequestPassesWithResponseStub extends FormRequest { public function rules() { return []; } public function authorize() { return Response::allow('baz'); } } class InvokableAfterValidationRule { public function __construct(private $value) { } public function __invoke($validator) { $validator->errors()->add('invokable', $this->value); } } class AfterValidationRule { public function __construct(private $value) { // } public function after($validator) { $validator->errors()->add('after', $this->value); } } class InjectedDependency { public function __construct(public $value) { // } } class FoundationTestFormRequestWithoutRulesMethod extends FormRequest { public function authorize() { return true; } } class FoundationTestFormRequestWithGetRules extends FormRequest { public static $useRuleSet = 'a'; protected function validationRules(): array { if (self::$useRuleSet === 'a') { return [ 'a' => ['required', 'int', 'min:1'], ]; } else { return [ 'a' => ['required', 'int', 'min:2'], ]; } } }
193379
<?php namespace Illuminate\Tests\Foundation; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Auth\Access\Gate; use Illuminate\Auth\Access\Response; use Illuminate\Container\Container; use Illuminate\Contracts\Auth\Access\Gate as GateContract; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use PHPUnit\Framework\TestCase; class FoundationAuthorizesRequestsTraitTest extends TestCase { protected function tearDown(): void { Container::setInstance(null); } public function testBasicGateCheck() { unset($_SERVER['_test.authorizes.trait']); $gate = $this->getBasicGate(); $gate->define('baz', function () { $_SERVER['_test.authorizes.trait'] = true; return true; }); $response = (new FoundationTestAuthorizeTraitClass)->authorize('baz'); $this->assertInstanceOf(Response::class, $response); $this->assertTrue($_SERVER['_test.authorizes.trait']); } public function testExceptionIsThrownIfGateCheckFails() { $this->expectException(AuthorizationException::class); $this->expectExceptionMessage('This action is unauthorized.'); $gate = $this->getBasicGate(); $gate->define('baz', function () { return false; }); (new FoundationTestAuthorizeTraitClass)->authorize('baz'); } public function testPoliciesMayBeCalled() { unset($_SERVER['_test.authorizes.trait.policy']); $gate = $this->getBasicGate(); $gate->policy(FoundationAuthorizesRequestTestClass::class, FoundationAuthorizesRequestTestPolicy::class); $response = (new FoundationTestAuthorizeTraitClass)->authorize('update', new FoundationAuthorizesRequestTestClass); $this->assertInstanceOf(Response::class, $response); $this->assertTrue($_SERVER['_test.authorizes.trait.policy']); } public function testPolicyMethodMayBeGuessedPassingModelInstance() { unset($_SERVER['_test.authorizes.trait.policy']); $gate = $this->getBasicGate(); $gate->policy(FoundationAuthorizesRequestTestClass::class, FoundationAuthorizesRequestTestPolicy::class); $response = (new FoundationTestAuthorizeTraitClass)->authorize(new FoundationAuthorizesRequestTestClass); $this->assertInstanceOf(Response::class, $response); $this->assertTrue($_SERVER['_test.authorizes.trait.policy']); } public function testPolicyMethodMayBeGuessedPassingClassName() { unset($_SERVER['_test.authorizes.trait.policy']); $gate = $this->getBasicGate(); $gate->policy('\\'.FoundationAuthorizesRequestTestClass::class, FoundationAuthorizesRequestTestPolicy::class); $response = (new FoundationTestAuthorizeTraitClass)->authorize('\\'.FoundationAuthorizesRequestTestClass::class); $this->assertInstanceOf(Response::class, $response); $this->assertTrue($_SERVER['_test.authorizes.trait.policy']); } public function testPolicyMethodMayBeGuessedAndNormalized() { unset($_SERVER['_test.authorizes.trait.policy']); $gate = $this->getBasicGate(); $gate->policy(FoundationAuthorizesRequestTestClass::class, FoundationAuthorizesRequestTestPolicy::class); (new FoundationTestAuthorizeTraitClass)->store(new FoundationAuthorizesRequestTestClass); $this->assertTrue($_SERVER['_test.authorizes.trait.policy']); } public function getBasicGate() { $container = Container::setInstance(new Container); $gate = new Gate($container, function () { return (object) ['id' => 1]; }); $container->instance(GateContract::class, $gate); return $gate; } } class FoundationAuthorizesRequestTestClass { // } class FoundationAuthorizesRequestTestPolicy { public function create() { $_SERVER['_test.authorizes.trait.policy'] = true; return true; } public function update() { $_SERVER['_test.authorizes.trait.policy'] = true; return true; } public function testPolicyMethodMayBeGuessedPassingModelInstance() { $_SERVER['_test.authorizes.trait.policy'] = true; return true; } public function testPolicyMethodMayBeGuessedPassingClassName() { $_SERVER['_test.authorizes.trait.policy'] = true; return true; } } class FoundationTestAuthorizeTraitClass { use AuthorizesRequests; public function store($object) { $this->authorize($object); } }
193388
<?php namespace Illuminate\Tests\Foundation\Bootstrap; use Illuminate\Foundation\Application; use Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables; use Mockery as m; use PHPUnit\Framework\TestCase; class LoadEnvironmentVariablesTest extends TestCase { protected function tearDown(): void { unset($_ENV['FOO'], $_SERVER['FOO']); putenv('FOO'); m::close(); } protected function getAppMock($file) { $app = m::mock(Application::class); $app->shouldReceive('configurationIsCached') ->once()->with()->andReturn(false); $app->shouldReceive('runningInConsole') ->once()->with()->andReturn(false); $app->shouldReceive('environmentPath') ->once()->with()->andReturn(__DIR__.'/../fixtures'); $app->shouldReceive('environmentFile') ->once()->with()->andReturn($file); return $app; } public function testCanLoad() { $this->expectOutputString(''); (new LoadEnvironmentVariables)->bootstrap($this->getAppMock('.env')); $this->assertSame('BAR', env('FOO')); $this->assertSame('BAR', getenv('FOO')); $this->assertSame('BAR', $_ENV['FOO']); $this->assertSame('BAR', $_SERVER['FOO']); } public function testCanFailSilent() { $this->expectOutputString(''); (new LoadEnvironmentVariables)->bootstrap($this->getAppMock('BAD_FILE')); } }
193400
<?php namespace Illuminate\Tests\Foundation\Testing\Concerns; use Illuminate\Contracts\Routing\Registrar; use Illuminate\Contracts\Routing\UrlGenerator; use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests; use Illuminate\Http\RedirectResponse; use Orchestra\Testbench\TestCase; class MakesHttpRequestsTest extends TestCase { public function testFromSetsHeaderAndSession() { $this->from('previous/url'); $this->assertSame('previous/url', $this->defaultHeaders['referer']); $this->assertSame('previous/url', $this->app['session']->previousUrl()); } public function testFromRouteSetsHeaderAndSession() { $router = $this->app->make(Registrar::class); $router->get('previous/url', fn () => 'ok')->name('previous-url'); $this->fromRoute('previous-url'); $this->assertSame('http://localhost/previous/url', $this->defaultHeaders['referer']); $this->assertSame('http://localhost/previous/url', $this->app['session']->previousUrl()); } public function testFromRemoveHeader() { $this->withHeader('name', 'Milwad')->from('previous/url'); $this->assertEquals('Milwad', $this->defaultHeaders['name']); $this->withoutHeader('name')->from('previous/url'); $this->assertArrayNotHasKey('name', $this->defaultHeaders); } public function testFromRemoveHeaders() { $this->withHeaders([ 'name' => 'Milwad', 'foo' => 'bar', ])->from('previous/url'); $this->assertEquals('Milwad', $this->defaultHeaders['name']); $this->assertEquals('bar', $this->defaultHeaders['foo']); $this->withoutHeaders(['name', 'foo'])->from('previous/url'); $this->assertArrayNotHasKey('name', $this->defaultHeaders); $this->assertArrayNotHasKey('foo', $this->defaultHeaders); } public function testWithTokenSetsAuthorizationHeader() { $this->withToken('foobar'); $this->assertSame('Bearer foobar', $this->defaultHeaders['Authorization']); $this->withToken('foobar', 'Basic'); $this->assertSame('Basic foobar', $this->defaultHeaders['Authorization']); } public function testWithBasicAuthSetsAuthorizationHeader() { $callback = function ($username, $password) { return base64_encode("$username:$password"); }; $username = 'foo'; $password = 'bar'; $this->withBasicAuth($username, $password); $this->assertSame('Basic '.$callback($username, $password), $this->defaultHeaders['Authorization']); $password = 'buzz'; $this->withBasicAuth($username, $password); $this->assertSame('Basic '.$callback($username, $password), $this->defaultHeaders['Authorization']); } public function testWithoutTokenRemovesAuthorizationHeader() { $this->withToken('foobar'); $this->assertSame('Bearer foobar', $this->defaultHeaders['Authorization']); $this->withoutToken(); $this->assertArrayNotHasKey('Authorization', $this->defaultHeaders); } public function testWithoutAndWithMiddleware() { $this->assertFalse($this->app->has('middleware.disable')); $this->withoutMiddleware(); $this->assertTrue($this->app->has('middleware.disable')); $this->assertTrue($this->app->make('middleware.disable')); $this->withMiddleware(); $this->assertFalse($this->app->has('middleware.disable')); } public function testWithoutAndWithMiddlewareWithParameter() { $next = function ($request) { return $request; }; $this->assertFalse($this->app->has(MyMiddleware::class)); $this->assertSame( 'fooWithMiddleware', $this->app->make(MyMiddleware::class)->handle('foo', $next) ); $this->withoutMiddleware(MyMiddleware::class); $this->assertTrue($this->app->has(MyMiddleware::class)); $this->assertSame( 'foo', $this->app->make(MyMiddleware::class)->handle('foo', $next) ); $this->withMiddleware(MyMiddleware::class); $this->assertFalse($this->app->has(MyMiddleware::class)); $this->assertSame( 'fooWithMiddleware', $this->app->make(MyMiddleware::class)->handle('foo', $next) ); } public function testWithCookieSetCookie() { $this->withCookie('foo', 'bar'); $this->assertCount(1, $this->defaultCookies); $this->assertSame('bar', $this->defaultCookies['foo']); } public function testWithCookiesSetsCookiesAndOverwritesPreviousValues() { $this->withCookie('foo', 'bar'); $this->withCookies([ 'foo' => 'baz', 'new-cookie' => 'new-value', ]); $this->assertCount(2, $this->defaultCookies); $this->assertSame('baz', $this->defaultCookies['foo']); $this->assertSame('new-value', $this->defaultCookies['new-cookie']); } public function testWithUnencryptedCookieSetCookie() { $this->withUnencryptedCookie('foo', 'bar'); $this->assertCount(1, $this->unencryptedCookies); $this->assertSame('bar', $this->unencryptedCookies['foo']); } public function testWithUnencryptedCookiesSetsCookiesAndOverwritesPreviousValues() { $this->withUnencryptedCookie('foo', 'bar'); $this->withUnencryptedCookies([ 'foo' => 'baz', 'new-cookie' => 'new-value', ]); $this->assertCount(2, $this->unencryptedCookies); $this->assertSame('baz', $this->unencryptedCookies['foo']); $this->assertSame('new-value', $this->unencryptedCookies['new-cookie']); } public function testWithoutAndWithCredentials() { $this->encryptCookies = false; $this->assertSame([], $this->prepareCookiesForJsonRequest()); $this->withCredentials(); $this->defaultCookies = ['foo' => 'bar']; $this->assertSame(['foo' => 'bar'], $this->prepareCookiesForJsonRequest()); } public function testFollowingRedirects() { $router = $this->app->make(Registrar::class); $url = $this->app->make(UrlGenerator::class); $router->get('from', function () use ($url) { return new RedirectResponse($url->to('to')); }); $router->get('to', function () { return 'OK'; }); $this->followingRedirects() ->get('from') ->assertOk() ->assertSee('OK'); } public function testFollowingRedirectsTerminatesInExpectedOrder() { $router = $this->app->make(Registrar::class); $url = $this->app->make(UrlGenerator::class); $callOrder = []; TerminatingMiddleware::$callback = function ($request) use (&$callOrder) { $callOrder[] = $request->path(); }; $router->get('from', function () use ($url) { return new RedirectResponse($url->to('to')); })->middleware(TerminatingMiddleware::class); $router->get('to', function () { return 'OK'; })->middleware(TerminatingMiddleware::class); $this->followingRedirects()->get('from'); $this->assertEquals(['from', 'to'], $callOrder); } public function testWithPrecognition() { $this->withPrecognition(); $this->assertSame('true', $this->defaultHeaders['Precognition']); $this->app->make(Registrar::class) ->get('test-route', fn () => 'ok')->middleware(HandlePrecognitiveRequests::class); $this->get('test-route') ->assertStatus(204) ->assertHeader('Precognition', 'true') ->assertHeader('Precognition-Success', 'true'); } } class MyMiddleware { public function handle($request, $next) { return $next($request.'WithMiddleware'); } } class TerminatingMiddleware { public static $callback; public function handle($request, $next) { return $next($request); } public function terminate($request, $response) { call_user_func(static::$callback, $request, $response); } }
193430
<?php namespace Illuminate\Tests\Bus; use Illuminate\Bus\Queueable; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; class QueueableTest extends TestCase { public static function connectionDataProvider(): array { return [ 'uses string' => ['redis', 'redis'], 'uses BackedEnum #1' => [ConnectionEnum::SQS, 'sqs'], 'uses BackedEnum #2' => [ConnectionEnum::REDIS, 'redis'], 'uses null' => [null, null], ]; } #[DataProvider('connectionDataProvider')] public function testOnConnection(mixed $connection, ?string $expected): void { $job = new FakeJob(); $job->onConnection($connection); $this->assertSame($job->connection, $expected); } #[DataProvider('connectionDataProvider')] public function testAllOnConnection(mixed $connection, ?string $expected): void { $job = new FakeJob(); $job->allOnConnection($connection); $this->assertSame($job->connection, $expected); $this->assertSame($job->chainConnection, $expected); } public static function queuesDataProvider(): array { return [ 'uses string' => ['high', 'high'], 'uses BackedEnum #1' => [QueueEnum::DEFAULT, 'default'], 'uses BackedEnum #2' => [QueueEnum::HIGH, 'high'], 'uses null' => [null, null], ]; } #[DataProvider('queuesDataProvider')] public function testOnQueue(mixed $queue, ?string $expected): void { $job = new FakeJob(); $job->onQueue($queue); $this->assertSame($job->queue, $expected); } #[DataProvider('queuesDataProvider')] public function testAllOnQueue(mixed $queue, ?string $expected): void { $job = new FakeJob(); $job->allOnQueue($queue); $this->assertSame($job->queue, $expected); $this->assertSame($job->chainQueue, $expected); } } class FakeJob { use Queueable; } enum ConnectionEnum: string { case SQS = 'sqs'; case REDIS = 'redis'; } enum QueueEnum: string { case HIGH = 'high'; case DEFAULT = 'default'; }
193438
class FilesystemAdapterTest extends TestCase { private $tempDir; private $filesystem; private $adapter; protected function setUp(): void { $this->tempDir = __DIR__.'/tmp'; $this->filesystem = new Filesystem( $this->adapter = new LocalFilesystemAdapter($this->tempDir) ); } protected function tearDown(): void { $filesystem = new Filesystem( $this->adapter = new LocalFilesystemAdapter(dirname($this->tempDir)) ); $filesystem->deleteDirectory(basename($this->tempDir)); m::close(); unset($this->tempDir, $this->filesystem, $this->adapter); } public function testResponse() { $this->filesystem->write('file.txt', 'Hello World'); $files = new FilesystemAdapter($this->filesystem, $this->adapter); $response = $files->response('file.txt'); ob_start(); $response->sendContent(); $content = ob_get_clean(); $this->assertInstanceOf(StreamedResponse::class, $response); $this->assertSame('Hello World', $content); $this->assertSame('inline; filename=file.txt', $response->headers->get('content-disposition')); } public function testMimeTypeIsNotCalledAlreadyProvidedToResponse() { $this->filesystem->write('file.txt', 'Hello World'); $files = m::mock(FilesystemAdapter::class, [$this->filesystem, $this->adapter])->makePartial(); $files->shouldReceive('mimeType')->never(); $files->response('file.txt', null, [ 'Content-Type' => 'text/x-custom', ]); } public function testSizeIsNotCalledAlreadyProvidedToResponse() { $this->filesystem->write('file.txt', 'Hello World'); $files = m::mock(FilesystemAdapter::class, [$this->filesystem, $this->adapter])->makePartial(); $files->shouldReceive('size')->never(); $files->response('file.txt', null, [ 'Content-Length' => 11, ]); } public function testFallbackNameCalledAlreadyProvidedToResponse() { $this->filesystem->write('file.txt', 'Hello World'); $files = m::mock(FilesystemAdapter::class, [$this->filesystem, $this->adapter]) ->shouldAllowMockingProtectedMethods() ->makePartial(); $files->shouldReceive('fallbackName')->never(); $files->response('file.txt', null, [ 'Content-Disposition' => 'attachment', ]); } public function testDownload() { $this->filesystem->write('file.txt', 'Hello World'); $files = new FilesystemAdapter($this->filesystem, $this->adapter); $response = $files->download('file.txt', 'hello.txt'); $this->assertInstanceOf(StreamedResponse::class, $response); $this->assertSame('attachment; filename=hello.txt', $response->headers->get('content-disposition')); } public function testDownloadNonAsciiFilename() { $this->filesystem->write('file.txt', 'Hello World'); $files = new FilesystemAdapter($this->filesystem, $this->adapter); $response = $files->download('file.txt', 'привет.txt'); $this->assertInstanceOf(StreamedResponse::class, $response); $this->assertSame("attachment; filename=privet.txt; filename*=utf-8''%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82.txt", $response->headers->get('content-disposition')); } public function testDownloadNonAsciiEmptyFilename() { $this->filesystem->write('привет.txt', 'Hello World'); $files = new FilesystemAdapter($this->filesystem, $this->adapter); $response = $files->download('привет.txt'); $this->assertInstanceOf(StreamedResponse::class, $response); $this->assertSame('attachment; filename=privet.txt; filename*=utf-8\'\'%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82.txt', $response->headers->get('content-disposition')); } public function testDownloadPercentInFilename() { $this->filesystem->write('Hello%World.txt', 'Hello World'); $files = new FilesystemAdapter($this->filesystem, $this->adapter); $response = $files->download('Hello%World.txt', 'Hello%World.txt'); $this->assertInstanceOf(StreamedResponse::class, $response); $this->assertSame('attachment; filename=HelloWorld.txt; filename*=utf-8\'\'Hello%25World.txt', $response->headers->get('content-disposition')); } public function testExists() { $this->filesystem->write('file.txt', 'Hello World'); $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); $this->assertTrue($filesystemAdapter->exists('file.txt')); $this->assertTrue($filesystemAdapter->fileExists('file.txt')); } public function testMissing() { $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); $this->assertTrue($filesystemAdapter->missing('file.txt')); $this->assertTrue($filesystemAdapter->fileMissing('file.txt')); } public function testDirectoryExists() { $this->filesystem->write('/foo/bar/file.txt', 'Hello World'); $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); $this->assertTrue($filesystemAdapter->directoryExists('/foo/bar')); } public function testDirectoryMissing() { $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); $this->assertTrue($filesystemAdapter->directoryMissing('/foo/bar')); } public function testPath() { $this->filesystem->write('file.txt', 'Hello World'); $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter, [ 'root' => $this->tempDir.DIRECTORY_SEPARATOR, ]); $this->assertEquals($this->tempDir.DIRECTORY_SEPARATOR.'file.txt', $filesystemAdapter->path('file.txt')); } public function testGet() { $this->filesystem->write('file.txt', 'Hello World'); $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); $this->assertSame('Hello World', $filesystemAdapter->get('file.txt')); } public function testGetFileNotFound() { $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); $this->assertNull($filesystemAdapter->get('file.txt')); } public function testJsonReturnsDecodedJsonData() { $this->filesystem->write('file.json', '{"foo": "bar"}'); $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); $this->assertSame(['foo' => 'bar'], $filesystemAdapter->json('file.json')); } public function testJsonReturnsNullIfJsonDataIsInvalid() { $this->filesystem->write('file.json', '{"foo":'); $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); $this->assertNull($filesystemAdapter->json('file.json')); } public function testMimeTypeNotDetected() { $this->filesystem->write('unknown.mime-type', ''); $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); $this->assertFalse($filesystemAdapter->mimeType('unknown.mime-type')); } public function testPut() { $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); $filesystemAdapter->put('file.txt', 'Something inside'); $this->assertStringEqualsFile($this->tempDir.'/file.txt', 'Something inside'); } public function testPrepend() { file_put_contents($this->tempDir.'/file.txt', 'World'); $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); $filesystemAdapter->prepend('file.txt', 'Hello '); $this->assertStringEqualsFile($this->tempDir.'/file.txt', 'Hello '.PHP_EOL.'World'); } public function testAppend() { file_put_contents($this->tempDir.'/file.txt', 'Hello '); $filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter); $filesystemAdapter->append('file.txt', 'Moon'); $this->assertStringEqualsFile($this->tempDir.'/file.txt', 'Hello '.PHP_EOL.'Moon'); } public funct
193555
[DataProvider('collectionClassProvider')] public function testPluckWithArrayAccessValues($collection) { $data = new $collection([ new TestArrayAccessImplementation(['name' => 'taylor', 'email' => 'foo']), new TestArrayAccessImplementation(['name' => 'dayle', 'email' => 'bar']), ]); $this->assertEquals(['taylor' => 'foo', 'dayle' => 'bar'], $data->pluck('email', 'name')->all()); $this->assertEquals(['foo', 'bar'], $data->pluck('email')->all()); } #[DataProvider('collectionClassProvider')] public function testPluckWithDotNotation($collection) { $data = new $collection([ [ 'name' => 'amir', 'skill' => [ 'backend' => ['php', 'python'], ], ], [ 'name' => 'taylor', 'skill' => [ 'backend' => ['php', 'asp', 'java'], ], ], ]); $this->assertEquals([['php', 'python'], ['php', 'asp', 'java']], $data->pluck('skill.backend')->all()); } #[DataProvider('collectionClassProvider')] public function testPluckDuplicateKeysExist($collection) { $data = new $collection([ ['brand' => 'Tesla', 'color' => 'red'], ['brand' => 'Pagani', 'color' => 'white'], ['brand' => 'Tesla', 'color' => 'black'], ['brand' => 'Pagani', 'color' => 'orange'], ]); $this->assertEquals(['Tesla' => 'black', 'Pagani' => 'orange'], $data->pluck('color', 'brand')->all()); } #[DataProvider('collectionClassProvider')] public function testHas($collection) { $data = new $collection(['id' => 1, 'first' => 'Hello', 'second' => 'World']); $this->assertTrue($data->has('first')); $this->assertFalse($data->has('third')); $this->assertTrue($data->has(['first', 'second'])); $this->assertFalse($data->has(['third', 'first'])); $this->assertTrue($data->has('first', 'second')); } #[DataProvider('collectionClassProvider')] public function testHasAny($collection) { $data = new $collection(['id' => 1, 'first' => 'Hello', 'second' => 'World']); $this->assertTrue($data->hasAny('first')); $this->assertFalse($data->hasAny('third')); $this->assertTrue($data->hasAny(['first', 'second'])); $this->assertTrue($data->hasAny(['first', 'fourth'])); $this->assertFalse($data->hasAny(['third', 'fourth'])); $this->assertFalse($data->hasAny('third', 'fourth')); $this->assertFalse($data->hasAny([])); } #[DataProvider('collectionClassProvider')] public function testImplode($collection) { $data = new $collection([['name' => 'taylor', 'email' => 'foo'], ['name' => 'dayle', 'email' => 'bar']]); $this->assertSame('foobar', $data->implode('email')); $this->assertSame('foo,bar', $data->implode('email', ',')); $data = new $collection(['taylor', 'dayle']); $this->assertSame('taylordayle', $data->implode('')); $this->assertSame('taylor,dayle', $data->implode(',')); $data = new $collection([ ['name' => Str::of('taylor'), 'email' => Str::of('foo')], ['name' => Str::of('dayle'), 'email' => Str::of('bar')], ]); $this->assertSame('foobar', $data->implode('email')); $this->assertSame('foo,bar', $data->implode('email', ',')); $data = new $collection([Str::of('taylor'), Str::of('dayle')]); $this->assertSame('taylordayle', $data->implode('')); $this->assertSame('taylor,dayle', $data->implode(',')); $this->assertSame('taylor_dayle', $data->implode('_')); $data = new $collection([['name' => 'taylor', 'email' => 'foo'], ['name' => 'dayle', 'email' => 'bar']]); $this->assertSame('taylor-foodayle-bar', $data->implode(fn ($user) => $user['name'].'-'.$user['email'])); $this->assertSame('taylor-foo,dayle-bar', $data->implode(fn ($user) => $user['name'].'-'.$user['email'], ',')); } #[DataProvider('collectionClassProvider')] public function testTake($collection) { $data = new $collection(['taylor', 'dayle', 'shawn']); $data = $data->take(2); $this->assertEquals(['taylor', 'dayle'], $data->all()); } public function testGetOrPut() { $data = new Collection(['name' => 'taylor', 'email' => 'foo']); $this->assertSame('taylor', $data->getOrPut('name', null)); $this->assertSame('foo', $data->getOrPut('email', null)); $this->assertSame('male', $data->getOrPut('gender', 'male')); $this->assertSame('taylor', $data->get('name')); $this->assertSame('foo', $data->get('email')); $this->assertSame('male', $data->get('gender')); $data = new Collection(['name' => 'taylor', 'email' => 'foo']); $this->assertSame('taylor', $data->getOrPut('name', function () { return null; })); $this->assertSame('foo', $data->getOrPut('email', function () { return null; })); $this->assertSame('male', $data->getOrPut('gender', function () { return 'male'; })); $this->assertSame('taylor', $data->get('name')); $this->assertSame('foo', $data->get('email')); $this->assertSame('male', $data->get('gender')); } public function testPut() { $data = new Collection(['name' => 'taylor', 'email' => 'foo']); $data = $data->put('name', 'dayle'); $this->assertEquals(['name' => 'dayle', 'email' => 'foo'], $data->all()); } public function testPutWithNoKey() { $data = new Collection(['taylor', 'shawn']); $data = $data->put(null, 'dayle'); $this->assertEquals(['taylor', 'shawn', 'dayle'], $data->all()); }
193642
public function testGetWithArrayQueryParamEncodes() { $this->factory->fake(); $this->factory->get('http://foo.com/get', ['foo;bar; space test' => 'laravel']); $this->factory->assertSent(function (Request $request) { return $request->url() === 'http://foo.com/get?foo%3Bbar%3B%20space%20test=laravel' && $request['foo;bar; space test'] === 'laravel'; }); } public function testWithBaseUrl() { $this->factory->fake(); $this->factory->baseUrl('http://foo.com/')->get('get'); $this->factory->assertSent(function (Request $request) { return $request->url() === 'http://foo.com/get'; }); $this->factory->fake(); $this->factory->baseUrl('http://foo.com/')->get('http://bar.com/get'); $this->factory->assertSent(function (Request $request) { return $request->url() === 'http://bar.com/get'; }); } public function testCanConfirmManyHeaders() { $this->factory->fake(); $this->factory->withHeaders([ 'X-Test-Header' => 'foo', 'X-Test-ArrayHeader' => ['bar', 'baz'], ])->post('http://foo.com/json'); $this->factory->assertSent(function (Request $request) { return $request->url() === 'http://foo.com/json' && $request->hasHeaders([ 'X-Test-Header' => 'foo', 'X-Test-ArrayHeader' => ['bar', 'baz'], ]); }); } public function testCanConfirmManyHeadersUsingAString() { $this->factory->fake(); $this->factory->withHeaders([ 'X-Test-Header' => 'foo', 'X-Test-ArrayHeader' => ['bar', 'baz'], ])->post('http://foo.com/json'); $this->factory->assertSent(function (Request $request) { return $request->url() === 'http://foo.com/json' && $request->hasHeaders('X-Test-Header'); }); } public function testItMergesMultipleHeaders() { $this->factory->fake(); $this->factory->withHeaders([ 'X-Test-Header' => 'foo', ])->withHeaders([ 'X-Test-Header' => 'bar', ])->withHeaders([ 'X-Test-Header' => ['baz', 'qux'], ])->post('http://foo.com/json'); $this->factory->assertSent(function (Request $request) { return $request->url() === 'http://foo.com/json' && $request->hasHeaders(['X-Test-Header' => ['foo', 'bar', 'baz', 'qux']]); }); } public function testItCanReplaceHeaders() { $this->factory->fake(); $this->factory->withHeaders([ 'X-Test-Header' => 'foo', ])->replaceHeaders([ 'X-Test-Header' => 'baz', ])->post('http://foo.com/json'); $this->factory->assertSent(function (Request $request) { return $request->url() === 'http://foo.com/json' && $request->hasHeaders(['X-Test-Header' => ['baz']]); }); } public function testItCanReplaceHeadersWhenNoHeadersYetSet() { $this->factory->fake(); $this->factory->replaceHeaders([ 'X-Test-Header' => 'baz', ])->post('http://foo.com/json'); $this->factory->assertSent(function (Request $request) { return $request->url() === 'http://foo.com/json' && $request->hasHeaders(['X-Test-Header' => ['baz']]); }); } public function testCanConfirmSingleStringHeader() { $this->factory->fake(); $this->factory->withHeader('X-Test-Header', 'foo')->post('http://foo.com/json'); $this->factory->assertSent(function (Request $request) { return $request->url() === 'http://foo.com/json' && $request->hasHeaders([ 'X-Test-Header' => 'foo', ]); }); } public function testCanConfirmSingleArrayHeader() { $this->factory->fake(); $this->factory->withHeader('X-Test-ArrayHeader', ['bar', 'baz'])->post('http://foo.com/json'); $this->factory->assertSent(function (Request $request) { return $request->url() === 'http://foo.com/json' && $request->hasHeaders([ 'X-Test-ArrayHeader' => ['bar', 'baz'], ]); }); } public function testExceptionAccessorOnSuccess() { $resp = new Response(new Psr7Response()); $this->assertNull($resp->toException()); } public function testExceptionAccessorOnFailure() { $error = [ 'error' => [ 'code' => 403, 'message' => 'The Request can not be completed', ], ]; $response = new Psr7Response(403, [], json_encode($error)); $resp = new Response($response); $this->assertInstanceOf(RequestException::class, $resp->toException()); } public function testRequestExceptionSummary() { $this->expectException(RequestException::class); $this->expectExceptionMessage('{"error":{"code":403,"message":"The Request can not be completed"}}'); $error = [ 'error' => [ 'code' => 403, 'message' => 'The Request can not be completed', ], ]; $response = new Psr7Response(403, [], json_encode($error)); throw new RequestException(new Response($response)); } public function testRequestExceptionTruncatedSummary() { $this->expectException(RequestException::class); $this->expectExceptionMessage('{"error":{"code":403,"message":"The Request can not be completed because quota limit was exceeded. Please, check our sup (truncated...)'); $error = [ 'error' => [ 'code' => 403, 'message' => 'The Request can not be completed because quota limit was exceeded. Please, check our support team to increase your limit', ], ]; $response = new Psr7Response(403, [], json_encode($error)); throw new RequestException(new Response($response)); } public function testRequestExceptionEmptyBody() { $this->expectException(RequestException::class); $this->expectExceptionMessageMatches('/HTTP request returned status code 403$/'); $response = new Psr7Response(403); throw new RequestException(new Response($response)); } public function testOnErrorDoesntCallClosureOnInformational() { $status = 0; $client = $this->factory->fake([ 'laravel.com' => $this->factory::response('', 101), ]); $response = $client->get('laravel.com') ->onError(function ($response) use (&$status) { $status = $response->status(); }); $this->assertSame(0, $status); $this->assertSame(101, $response->status()); } public function testOnErrorDoesntCallClosureOnSuccess() { $status = 0; $client = $this->factory->fake([ 'laravel.com' => $this->factory::response('', 201), ]); $response = $client->get('laravel.com') ->onError(function ($response) use (&$status) { $status = $response->status(); }); $this->assertSame(0, $status); $this->assertSame(201, $response->status()); } public function testOnErrorDoesntCallClosureOnRedirection() { $status = 0; $client = $this->factory->fake([ 'laravel.com' => $this->factory::response('', 301), ]); $response = $client->get('laravel.com') ->onError(function ($response) use (&$status) { $status = $response->status(); }); $this->assertSame(0, $status); $this->assertSame(301, $response->status()); }
193667
class HttpResponseTest extends TestCase { protected function tearDown(): void { m::close(); } public function testJsonResponsesAreConvertedAndHeadersAreSet() { $response = new Response(new ArrayableStub); $this->assertSame('{"foo":"bar"}', $response->getContent()); $this->assertSame('application/json', $response->headers->get('Content-Type')); $response = new Response(new JsonableStub); $this->assertSame('foo', $response->getContent()); $this->assertSame('application/json', $response->headers->get('Content-Type')); $response = new Response(new ArrayableAndJsonableStub); $this->assertSame('{"foo":"bar"}', $response->getContent()); $this->assertSame('application/json', $response->headers->get('Content-Type')); $response = new Response; $response->setContent(['foo' => 'bar']); $this->assertSame('{"foo":"bar"}', $response->getContent()); $this->assertSame('application/json', $response->headers->get('Content-Type')); $response = new Response(new JsonSerializableStub); $this->assertSame('{"foo":"bar"}', $response->getContent()); $this->assertSame('application/json', $response->headers->get('Content-Type')); $response = new Response(new ArrayableStub); $this->assertSame('{"foo":"bar"}', $response->getContent()); $this->assertSame('application/json', $response->headers->get('Content-Type')); $response->setContent('{"foo": "bar"}'); $this->assertSame('{"foo": "bar"}', $response->getContent()); $this->assertSame('application/json', $response->headers->get('Content-Type')); } public function testRenderablesAreRendered() { $mock = m::mock(Renderable::class); $mock->shouldReceive('render')->once()->andReturn('foo'); $response = new Response($mock); $this->assertSame('foo', $response->getContent()); } public function testHeader() { $response = new Response; $this->assertNull($response->headers->get('foo')); $response->header('foo', 'bar'); $this->assertSame('bar', $response->headers->get('foo')); $response->header('foo', 'baz', false); $this->assertSame('bar', $response->headers->get('foo')); $response->header('foo', 'baz'); $this->assertSame('baz', $response->headers->get('foo')); } public function testWithCookie() { $response = new Response; $this->assertCount(0, $response->headers->getCookies()); $this->assertEquals($response, $response->withCookie(new Cookie('foo', 'bar'))); $cookies = $response->headers->getCookies(); $this->assertCount(1, $cookies); $this->assertSame('foo', $cookies[0]->getName()); $this->assertSame('bar', $cookies[0]->getValue()); } public function testResponseCookiesInheritRequestSecureState() { $cookie = Cookie::create('foo', 'bar'); $response = new Response('foo'); $response->headers->setCookie($cookie); $request = Request::create('/', 'GET'); $response->prepare($request); $this->assertFalse($cookie->isSecure()); $request = Request::create('https://localhost/', 'GET'); $response->prepare($request); $this->assertTrue($cookie->isSecure()); } public function testGetOriginalContent() { $arr = ['foo' => 'bar']; $response = new Response; $response->setContent($arr); $this->assertSame($arr, $response->getOriginalContent()); } public function testGetOriginalContentRetrievesTheFirstOriginalContent() { $previousResponse = new Response(['foo' => 'bar']); $response = new Response($previousResponse); $this->assertSame(['foo' => 'bar'], $response->getOriginalContent()); } public function testSetAndRetrieveStatusCode() { $response = new Response('foo'); $response->setStatusCode(404); $this->assertSame(404, $response->getStatusCode()); } public function testSetStatusCodeAndRetrieveStatusText() { $response = new Response('foo'); $response->setStatusCode(404); $this->assertSame('Not Found', $response->statusText()); } public function testOnlyInputOnRedirect() { $response = new RedirectResponse('foo.bar'); $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26])); $response->setSession($session = m::mock(Store::class)); $session->shouldReceive('flashInput')->once()->with(['name' => 'Taylor']); $response->onlyInput('name'); } public function testExceptInputOnRedirect() { $response = new RedirectResponse('foo.bar'); $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26])); $response->setSession($session = m::mock(Store::class)); $session->shouldReceive('flashInput')->once()->with(['name' => 'Taylor']); $response->exceptInput('age'); } public function testFlashingErrorsOnRedirect() { $response = new RedirectResponse('foo.bar'); $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26])); $response->setSession($session = m::mock(Store::class)); $session->shouldReceive('get')->with('errors', m::type(ViewErrorBag::class))->andReturn(new ViewErrorBag); $session->shouldReceive('flash')->once()->with('errors', m::type(ViewErrorBag::class)); $provider = m::mock(MessageProvider::class); $provider->shouldReceive('getMessageBag')->once()->andReturn(new MessageBag); $response->withErrors($provider); } public function testSettersGettersOnRequest() { $response = new RedirectResponse('foo.bar'); $this->assertNull($response->getRequest()); $this->assertNull($response->getSession()); $request = Request::create('/', 'GET'); $session = m::mock(Store::class); $response->setRequest($request); $response->setSession($session); $this->assertSame($request, $response->getRequest()); $this->assertSame($session, $response->getSession()); } public function testRedirectWithErrorsArrayConvertsToMessageBag() { $response = new RedirectResponse('foo.bar'); $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26])); $response->setSession($session = m::mock(Store::class)); $session->shouldReceive('get')->with('errors', m::type(ViewErrorBag::class))->andReturn(new ViewErrorBag); $session->shouldReceive('flash')->once()->with('errors', m::type(ViewErrorBag::class)); $provider = ['foo' => 'bar']; $response->withErrors($provider); } public function testWithHeaders() { $response = new Response(null, 200, ['foo' => 'bar']); $this->assertSame('bar', $response->headers->get('foo')); $response->withHeaders(['foo' => 'BAR', 'bar' => 'baz']); $this->assertSame('BAR', $response->headers->get('foo')); $this->assertSame('baz', $response->headers->get('bar')); $responseMessageBag = new ResponseHeaderBag(['bar' => 'BAZ', 'titi' => 'toto']); $response->withHeaders($responseMessageBag); $this->assertSame('BAZ', $response->headers->get('bar')); $this->assertSame('toto', $response->headers->get('titi')); $headerBag = new HeaderBag(['bar' => 'BAAA', 'titi' => 'TATA']); $response->withHeaders($headerBag); $this->assertSame('BAAA', $response->headers->get('bar')); $this->assertSame('TATA', $response->headers->get('titi')); } public function testMagicCall() { $response = new RedirectResponse('foo.bar'); $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26])); $response->setSession($session = m::mock(Store::class)); $session->shouldReceive('flash')->once()->with('foo', 'bar'); $response->withFoo('bar'); } public function testMagicCallException() { $this->expectException(BadMethodCallException::class); $this->expectExceptionMessage('Call to undefined method Illuminate\Http\RedirectResponse::doesNotExist()'); $response = new RedirectResponse('foo.bar'); $response->doesNotExist('bar'); } }
193697
<?php namespace Illuminate\Tests\View\Blade; use Illuminate\View\ComponentAttributeBag; class BladePropsTest extends AbstractBladeTestCase { public function testPropsAreCompiled() { $this->assertSame('<?php $attributes ??= new \Illuminate\View\ComponentAttributeBag; $__newAttributes = []; $__propNames = \Illuminate\View\ComponentAttributeBag::extractPropNames(([\'one\' => true, \'two\' => \'string\'])); foreach ($attributes->all() as $__key => $__value) { if (in_array($__key, $__propNames)) { $$__key = $$__key ?? $__value; } else { $__newAttributes[$__key] = $__value; } } $attributes = new \Illuminate\View\ComponentAttributeBag($__newAttributes); unset($__propNames); unset($__newAttributes); foreach (array_filter(([\'one\' => true, \'two\' => \'string\']), \'is_string\', ARRAY_FILTER_USE_KEY) as $__key => $__value) { $$__key = $$__key ?? $__value; } $__defined_vars = get_defined_vars(); foreach ($attributes->all() as $__key => $__value) { if (array_key_exists($__key, $__defined_vars)) unset($$__key); } unset($__defined_vars); ?>', $this->compiler->compileString('@props([\'one\' => true, \'two\' => \'string\'])')); } public function testPropsAreExtractedFromParentAttributesCorrectly() { $test1 = $test2 = $test4 = null; $attributes = new ComponentAttributeBag(['test1' => 'value1', 'test2' => 'value2', 'test3' => 'value3']); $template = $this->compiler->compileString('@props([\'test1\' => \'default\', \'test2\', \'test4\' => \'default\'])'); ob_start(); eval(" ?> $template <?php "); ob_get_clean(); $this->assertSame($test1, 'value1'); $this->assertSame($test2, 'value2'); $this->assertFalse(isset($test3)); $this->assertSame($test4, 'default'); $this->assertNull($attributes->get('test1')); $this->assertNull($attributes->get('test2')); $this->assertSame($attributes->get('test3'), 'value3'); } }
193760
<?php namespace Illuminate\Tests\View\Blade; class BladeSessionTest extends AbstractBladeTestCase { public function testSessionsAreCompiled() { $string = ' @session(\'status\') <span>{{ $value }}</span> @endsession'; $expected = ' <?php $__sessionArgs = [\'status\']; if (session()->has($__sessionArgs[0])) : if (isset($value)) { $__sessionPrevious[] = $value; } $value = session()->get($__sessionArgs[0]); ?> <span><?php echo e($value); ?></span> <?php unset($value); if (isset($__sessionPrevious) && !empty($__sessionPrevious)) { $value = array_pop($__sessionPrevious); } if (isset($__sessionPrevious) && empty($__sessionPrevious)) { unset($__sessionPrevious); } endif; unset($__sessionArgs); ?>'; $this->assertEquals($expected, $this->compiler->compileString($string)); } }
193798
public function testItUtilisesTheNullDriverDuringTestsWhenNullDriverUsed() { $config = $this->app->make('config'); $config->set('logging.default', null); $config->set('logging.channels.null', [ 'driver' => 'monolog', 'handler' => NullHandler::class, ]); $manager = new class($this->app) extends LogManager { protected function createEmergencyLogger() { throw new RuntimeException('Emergency logger was created.'); } }; // In tests, this should not need to create the emergency logger... $manager->info('message'); // we should also be able to forget the null channel... $this->assertCount(1, $manager->getChannels()); $manager->forgetChannel(); $this->assertCount(0, $manager->getChannels()); // However in production we want it to fallback to the emergency logger... $this->app['env'] = 'production'; try { $manager->info('message'); $this->fail('Emergency logger was not created as expected.'); } catch (RuntimeException $exception) { $this->assertSame('Emergency logger was created.', $exception->getMessage()); } } public function testLogManagerCreateSingleDriverWithConfiguredFormatter() { $config = $this->app['config']; $config->set('logging.channels.defaultsingle', [ 'driver' => 'single', 'name' => 'ds', 'path' => storage_path('logs/laravel.log'), 'replace_placeholders' => true, ]); $manager = new LogManager($this->app); // create logger with handler specified from configuration $logger = $manager->channel('defaultsingle'); $handler = $logger->getLogger()->getHandlers()[0]; $formatter = $handler->getFormatter(); $this->assertInstanceOf(StreamHandler::class, $handler); $this->assertInstanceOf(LineFormatter::class, $formatter); $this->assertInstanceOf(PsrLogMessageProcessor::class, $logger->getLogger()->getProcessors()[1]); $config->set('logging.channels.formattedsingle', [ 'driver' => 'single', 'name' => 'fs', 'path' => storage_path('logs/laravel.log'), 'formatter' => HtmlFormatter::class, 'formatter_with' => [ 'dateFormat' => 'Y/m/d--test', ], 'replace_placeholders' => false, ]); $logger = $manager->channel('formattedsingle'); $handler = $logger->getLogger()->getHandlers()[0]; $formatter = $handler->getFormatter(); $this->assertInstanceOf(StreamHandler::class, $handler); $this->assertInstanceOf(HtmlFormatter::class, $formatter); $this->assertCount(1, $logger->getLogger()->getProcessors()); $dateFormat = new ReflectionProperty(get_class($formatter), 'dateFormat'); $this->assertSame('Y/m/d--test', $dateFormat->getValue($formatter)); } public function testLogManagerCreateDailyDriverWithConfiguredFormatter() { $config = $this->app['config']; $config->set('logging.channels.defaultdaily', [ 'driver' => 'daily', 'name' => 'dd', 'path' => storage_path('logs/laravel.log'), 'replace_placeholders' => true, ]); $manager = new LogManager($this->app); // create logger with handler specified from configuration $logger = $manager->channel('defaultdaily'); $handler = $logger->getLogger()->getHandlers()[0]; $formatter = $handler->getFormatter(); $this->assertInstanceOf(StreamHandler::class, $handler); $this->assertInstanceOf(LineFormatter::class, $formatter); $this->assertInstanceOf(PsrLogMessageProcessor::class, $logger->getLogger()->getProcessors()[1]); $config->set('logging.channels.formatteddaily', [ 'driver' => 'daily', 'name' => 'fd', 'path' => storage_path('logs/laravel.log'), 'formatter' => HtmlFormatter::class, 'formatter_with' => [ 'dateFormat' => 'Y/m/d--test', ], 'replace_placeholders' => false, ]); $logger = $manager->channel('formatteddaily'); $handler = $logger->getLogger()->getHandlers()[0]; $formatter = $handler->getFormatter(); $this->assertInstanceOf(StreamHandler::class, $handler); $this->assertInstanceOf(HtmlFormatter::class, $formatter); $this->assertCount(1, $logger->getLogger()->getProcessors()); $dateFormat = new ReflectionProperty(get_class($formatter), 'dateFormat'); $this->assertSame('Y/m/d--test', $dateFormat->getValue($formatter)); } public function testLogManagerCreateSyslogDriverWithConfiguredFormatter() { $config = $this->app['config']; $config->set('logging.channels.defaultsyslog', [ 'driver' => 'syslog', 'name' => 'ds', 'replace_placeholders' => true, ]); $manager = new LogManager($this->app); // create logger with handler specified from configuration $logger = $manager->channel('defaultsyslog'); $handler = $logger->getLogger()->getHandlers()[0]; $formatter = $handler->getFormatter(); $this->assertInstanceOf(SyslogHandler::class, $handler); $this->assertInstanceOf(LineFormatter::class, $formatter); $this->assertInstanceOf(PsrLogMessageProcessor::class, $logger->getLogger()->getProcessors()[1]); $config->set('logging.channels.formattedsyslog', [ 'driver' => 'syslog', 'name' => 'fs', 'formatter' => HtmlFormatter::class, 'formatter_with' => [ 'dateFormat' => 'Y/m/d--test', ], 'replace_placeholders' => false, ]); $logger = $manager->channel('formattedsyslog'); $handler = $logger->getLogger()->getHandlers()[0]; $formatter = $handler->getFormatter(); $this->assertInstanceOf(SyslogHandler::class, $handler); $this->assertInstanceOf(HtmlFormatter::class, $formatter); $this->assertCount(1, $logger->getLogger()->getProcessors()); $dateFormat = new ReflectionProperty(get_class($formatter), 'dateFormat'); $this->assertSame('Y/m/d--test', $dateFormat->getValue($formatter)); } public function testLogManagerPurgeResolvedChannels() { $manager = new LogManager($this->app); $this->assertEmpty($manager->getChannels()); $manager->channel('single')->getLogger(); $this->assertCount(1, $manager->getChannels()); $manager->forgetChannel('single'); $this->assertEmpty($manager->getChannels()); } public function testLogManagerCanBuildOnDemandChannel() { $manager = new LogManager($this->app); $logger = $manager->build([ 'driver' => 'single', 'path' => storage_path('logs/on-demand.log'), ]); $handler = $logger->getLogger()->getHandlers()[0]; $this->assertInstanceOf(StreamHandler::class, $handler); $url = new ReflectionProperty(get_class($handler), 'url'); $this->assertSame(storage_path('logs/on-demand.log'), $url->getValue($handler)); } public function testLogManagerCanUseOnDemandChannelInOnDemandStack() { $manager = new LogManager($this->app); $this->app['config']->set('logging.channels.test', [ 'driver' => 'single', ]); $factory = new class() { public function __invoke() { return new Monolog( 'uuid', [new StreamHandler(storage_path('logs/custom.log'))], [new UidProcessor()] ); } }; $channel = $manager->build([ 'driver' => 'custom', 'via' => get_class($factory), ]); $logger = $manager->stack(['test', $channel]); $handler = $logger->getLogger()->getHandlers()[1]; $processor = $logger->getLogger()->getProcessors()[1]; $this->assertInstanceOf(StreamHandler::class, $handler); $this->assertInstanceOf(UidProcessor::class, $processor); $url = new ReflectionProperty(get_class($handler), 'url'); $this->assertSame(storage_path('logs/custom.log'), $url->getValue($handler)); }
193799
public function testWrappingHandlerInFingersCrossedWhenActionLevelIsUsed() { $config = $this->app['config']; $config->set('logging.channels.fingerscrossed', [ 'driver' => 'monolog', 'handler' => StreamHandler::class, 'level' => 'debug', 'action_level' => 'critical', 'with' => [ 'stream' => 'php://stderr', 'bubble' => false, ], ]); $manager = new LogManager($this->app); // create logger with handler specified from configuration $logger = $manager->channel('fingerscrossed'); $handlers = $logger->getLogger()->getHandlers(); $this->assertInstanceOf(Logger::class, $logger); $this->assertCount(1, $handlers); $expectedFingersCrossedHandler = $handlers[0]; $this->assertInstanceOf(FingersCrossedHandler::class, $expectedFingersCrossedHandler); $activationStrategyProp = new ReflectionProperty(get_class($expectedFingersCrossedHandler), 'activationStrategy'); $activationStrategyValue = $activationStrategyProp->getValue($expectedFingersCrossedHandler); $actionLevelProp = new ReflectionProperty(get_class($activationStrategyValue), 'actionLevel'); $actionLevelValue = $actionLevelProp->getValue($activationStrategyValue); $this->assertEquals(Level::Critical, $actionLevelValue); if (method_exists($expectedFingersCrossedHandler, 'getHandler')) { $expectedStreamHandler = $expectedFingersCrossedHandler->getHandler(); } else { $handlerProp = new ReflectionProperty(get_class($expectedFingersCrossedHandler), 'handler'); $expectedStreamHandler = $handlerProp->getValue($expectedFingersCrossedHandler); } $this->assertInstanceOf(StreamHandler::class, $expectedStreamHandler); $this->assertEquals(Level::Debug, $expectedStreamHandler->getLevel()); } public function testFingersCrossedHandlerStopsRecordBufferingAfterFirstFlushByDefault() { $config = $this->app['config']; $config->set('logging.channels.fingerscrossed', [ 'driver' => 'monolog', 'handler' => StreamHandler::class, 'level' => 'debug', 'action_level' => 'critical', 'with' => [ 'stream' => 'php://stderr', 'bubble' => false, ], ]); $manager = new LogManager($this->app); // create logger with handler specified from configuration $logger = $manager->channel('fingerscrossed'); $handlers = $logger->getLogger()->getHandlers(); $expectedFingersCrossedHandler = $handlers[0]; $stopBufferingProp = new ReflectionProperty(get_class($expectedFingersCrossedHandler), 'stopBuffering'); $stopBufferingValue = $stopBufferingProp->getValue($expectedFingersCrossedHandler); $this->assertTrue($stopBufferingValue); } public function testFingersCrossedHandlerCanBeConfiguredToResumeBufferingAfterFlushing() { $config = $this->app['config']; $config->set('logging.channels.fingerscrossed', [ 'driver' => 'monolog', 'handler' => StreamHandler::class, 'level' => 'debug', 'action_level' => 'critical', 'stop_buffering' => false, 'with' => [ 'stream' => 'php://stderr', 'bubble' => false, ], ]); $manager = new LogManager($this->app); // create logger with handler specified from configuration $logger = $manager->channel('fingerscrossed'); $handlers = $logger->getLogger()->getHandlers(); $expectedFingersCrossedHandler = $handlers[0]; $stopBufferingProp = new ReflectionProperty(get_class($expectedFingersCrossedHandler), 'stopBuffering'); $stopBufferingValue = $stopBufferingProp->getValue($expectedFingersCrossedHandler); $this->assertFalse($stopBufferingValue); } public function testItSharesContextWithAlreadyResolvedChannels() { $manager = new LogManager($this->app); $channel = $manager->channel('single'); $context = null; $channel->listen(function ($message) use (&$context) { $context = $message->context; }); $manager->shareContext([ 'invocation-id' => 'expected-id', ]); $channel->info('xxxx'); $this->assertSame(['invocation-id' => 'expected-id'], $context); } public function testItSharesContextWithFreshlyResolvedChannels() { $manager = new LogManager($this->app); $context = null; $manager->shareContext([ 'invocation-id' => 'expected-id', ]); $manager->channel('single')->listen(function ($message) use (&$context) { $context = $message->context; }); $manager->channel('single')->info('xxxx'); $this->assertSame(['invocation-id' => 'expected-id'], $context); } public function testContextCanBePubliclyAccessedByOtherLoggingSystems() { $manager = new LogManager($this->app); $context = null; $manager->shareContext([ 'invocation-id' => 'expected-id', ]); $this->assertSame($manager->sharedContext(), ['invocation-id' => 'expected-id']); } public function testItSharesContextWithStacksWhenTheyAreResolved() { $manager = new LogManager($this->app); $context = null; $manager->shareContext([ 'invocation-id' => 'expected-id', ]); $stack = $manager->stack(['single']); $stack->listen(function ($message) use (&$context) { $context = $message->context; }); $stack->info('xxxx'); $this->assertSame(['invocation-id' => 'expected-id'], $context); } public function testItMergesSharedContextRatherThanReplacing() { $manager = new LogManager($this->app); $context = null; $manager->shareContext([ 'invocation-id' => 'expected-id', ]); $manager->shareContext([ 'invocation-start' => 1651800456, ]); $manager->channel('single')->listen(function ($message) use (&$context) { $context = $message->context; }); $manager->channel('single')->info('xxxx', [ 'logged' => 'context', ]); $this->assertSame([ 'invocation-id' => 'expected-id', 'invocation-start' => 1651800456, 'logged' => 'context', ], $context); $this->assertSame([ 'invocation-id' => 'expected-id', 'invocation-start' => 1651800456, ], $manager->sharedContext()); } public function testFlushSharedContext() { $manager = new LogManager($this->app); $manager->shareContext($context = ['foo' => 'bar']); $this->assertSame($context, $manager->sharedContext()); $manager->flushSharedContext(); $this->assertEmpty($manager->sharedContext()); } public function testLogManagerCreateCustomFormatterWithTap() { $config = $this->app['config']; $config->set('logging.channels.custom', [ 'driver' => 'single', 'tap' => [CustomizeFormatter::class], ]); $manager = new LogManager($this->app); $logger = $manager->channel('custom'); $handler = $logger->getLogger()->getHandlers()[0]; $formatter = $handler->getFormatter(); $this->assertInstanceOf(LineFormatter::class, $formatter); $format = new ReflectionProperty(get_class($formatter), 'format'); $this->assertEquals( '[%datetime%] %channel%.%level_name%: %message% %context% %extra%', rtrim($format->getValue($formatter))); } public function testDriverUsersPsrLoggerManagerReturnsLogger() { // Given $config = $this->app['config']; $config->set('logging.channels.spy', [ 'driver' => 'spy', ]); $manager = new LogManager($this->app); $loggerSpy = new LoggerSpy(); $manager->extend('spy', fn () => $loggerSpy); // When $logger = $manager->channel('spy'); $logger->alert('some alert'); // Then $this->assertCount(1, $loggerSpy->logs); $this->assertEquals('some alert', $loggerSpy->logs[0]['message']); } }
193815
lic function testRouteMacro() { $router = $this->getRouter(); Route::macro('breadcrumb', function ($breadcrumb) { $this->action['breadcrumb'] = $breadcrumb; return $this; }); $router->get('foo', function () { return 'bar'; })->breadcrumb('fooBreadcrumb')->name('foo'); $router->getRoutes()->refreshNameLookups(); $this->assertSame('fooBreadcrumb', $router->getRoutes()->getByName('foo')->getAction()['breadcrumb']); } public function testClassesCanBeInjectedIntoRoutes() { unset($_SERVER['__test.route_inject']); $router = $this->getRouter(); $router->get('foo/{var}', function (stdClass $foo, $var) { $_SERVER['__test.route_inject'] = func_get_args(); return 'hello'; }); $this->assertSame('hello', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent()); $this->assertInstanceOf(stdClass::class, $_SERVER['__test.route_inject'][0]); $this->assertSame('bar', $_SERVER['__test.route_inject'][1]); unset($_SERVER['__test.route_inject']); } public function testNullValuesCanBeInjectedIntoRoutes() { $container = new Container; $router = new Router(new Dispatcher, $container); $container->instance(Registrar::class, $router); $container->bind(RoutingTestUserModel::class, function () { }); $container->bind(CallableDispatcherContract::class, fn ($app) => new CallableDispatcher($app)); $router->get('foo/{team}/{post}', [ 'middleware' => SubstituteBindings::class, 'uses' => function (?RoutingTestUserModel $userFromContainer, RoutingTestTeamModel $team, $postId) { $this->assertNull($userFromContainer); $this->assertInstanceOf(RoutingTestTeamModel::class, $team); $this->assertSame('bar', $team->value); $this->assertSame('baz', $postId); }, ]); $router->dispatch(Request::create('foo/bar/baz', 'GET'))->getContent(); } public function testOptionsResponsesAreGeneratedByDefault() { $router = $this->getRouter(); $router->get('foo/bar', function () { return 'hello'; }); $router->post('foo/bar', function () { return 'hello'; }); $response = $router->dispatch(Request::create('foo/bar', 'OPTIONS')); $this->assertEquals(200, $response->getStatusCode()); $this->assertSame('GET,HEAD,POST', $response->headers->get('Allow')); } public function testHeadDispatcher() { $router = $this->getRouter(); $router->match(['GET', 'POST'], 'foo', function () { return 'bar'; }); $response = $router->dispatch(Request::create('foo', 'OPTIONS')); $this->assertEquals(200, $response->getStatusCode()); $this->assertSame('GET,HEAD,POST', $response->headers->get('Allow')); $response = $router->dispatch(Request::create('foo', 'HEAD')); $this->assertEquals(200, $response->getStatusCode()); $this->assertEmpty($response->getContent()); $router = $this->getRouter(); $router->match(['GET'], 'foo', function () { return 'bar'; }); $response = $router->dispatch(Request::create('foo', 'OPTIONS')); $this->assertEquals(200, $response->getStatusCode()); $this->assertSame('GET,HEAD', $response->headers->get('Allow')); $router = $this->getRouter(); $router->match(['POST'], 'foo', function () { return 'bar'; }); $response = $router->dispatch(Request::create('foo', 'OPTIONS')); $this->assertEquals(200, $response->getStatusCode()); $this->assertSame('POST', $response->headers->get('Allow')); } public function testNonGreedyMatches() { $route = new Route('GET', 'images/{id}.{ext}', function () { // }); $request1 = Request::create('images/1.png', 'GET'); $this->assertTrue($route->matches($request1)); $route->bind($request1); $this->assertTrue($route->hasParameter('id')); $this->assertFalse($route->hasParameter('foo')); $this->assertSame('1', (string) $route->parameter('id')); $this->assertSame('png', $route->parameter('ext')); $request2 = Request::create('images/12.png', 'GET'); $this->assertTrue($route->matches($request2)); $route->bind($request2); $this->assertSame('12', $route->parameter('id')); $this->assertSame('png', $route->parameter('ext')); // Test parameter() default value $route = new Route('GET', 'foo/{foo?}', function () { // }); $request3 = Request::create('foo', 'GET'); $this->assertTrue($route->matches($request3)); $route->bind($request3); $this->assertSame('bar', $route->parameter('foo', 'bar')); } public function testHasParameters() { $route = new Route('GET', 'images/{id}.{ext}', function () { // }); $request1 = Request::create('images/1.png', 'GET'); $this->assertFalse($route->hasParameters()); $this->assertTrue($route->matches($request1)); $route->bind($request1); $this->assertTrue($route->hasParameters()); } public function testForgetParameter() { $route = new Route('GET', 'images/{id}.{ext}', function () { // }); $request1 = Request::create('images/1.png', 'GET'); $route->bind($request1); $this->assertTrue($route->hasParameter('id')); $this->assertTrue($route->hasParameter('ext')); $route->forgetParameter('id'); $this->assertFalse($route->hasParameter('id')); $this->assertTrue($route->hasParameter('ext')); } public function testParameterNames() { $route = new Route('GET', 'images/{id}.{ext}', function () { // }); $this->assertSame(['id', 'ext'], $route->parameterNames()); $route = new Route('GET', 'foo/{bar?}', function () { // }); $this->assertSame(['bar'], $route->parameterNames()); $route = new Route('GET', '/', function () { // }); $this->assertSame([], $route->parameterNames()); } public function testParametersWithoutNulls() { $route = new Route('GET', 'users/{id?}/{name?}/', function () { // }); $request1 = Request::create('users/12/amir', 'GET'); $route->bind($request1); $this->assertSame(['id' => '12', 'name' => 'amir'], $route->parametersWithoutNulls()); $route = new Route('GET', 'users/{id?}/{name?}/', function () { // }); $request1 = Request::create('users/12', 'GET'); $route->bind($request1); $this->assertSame(['id' => '12'], $route->parametersWithoutNulls()); $route = new Route('GET', 'users/{id?}/{name?}/', function () { // }); $request1 = Request::create('users/', 'GET'); $route->bind($request1); $this->assertSame([], $route->parametersWithoutNulls()); } public function testRouteParametersDefaultValue() { $router = $this->getRouter(); $router->get('foo/{bar?}', ['uses' => RouteTestControllerWithParameterStub::class.'@returnParameter'])->defaults('bar', 'foo'); $this->assertSame('foo', $router->dispatch(Request::create('foo', 'GET'))->getContent()); $router->get('foo/{bar?}', ['uses' => RouteTestControllerWithParameterStub::class.'@returnParameter'])->defaults('bar', 'foo'); $this->assertSame('bar', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent()); $router->get('foo/{bar?}', function ($bar = '') { return $bar; })->defaults('bar', 'foo'); $this->assertSame('foo', $router->dispatch(Request::create('foo', 'GET'))->getContent()); }
193816
lic function testControllerCallActionMethodParameters() { $router = $this->getRouter(); // Has one argument but receives two unset($_SERVER['__test.controller_callAction_parameters']); $router->get(($str = Str::random()).'/{one}/{two}', RouteTestAnotherControllerWithParameterStub::class.'@oneArgument'); $router->dispatch(Request::create($str.'/one/two', 'GET')); $this->assertEquals(['one' => 'one', 'two' => 'two'], $_SERVER['__test.controller_callAction_parameters']); // Has two arguments and receives two unset($_SERVER['__test.controller_callAction_parameters']); $router->get(($str = Str::random()).'/{one}/{two}', RouteTestAnotherControllerWithParameterStub::class.'@twoArguments'); $router->dispatch(Request::create($str.'/one/two', 'GET')); $this->assertEquals(['one' => 'one', 'two' => 'two'], $_SERVER['__test.controller_callAction_parameters']); // Has two arguments but with different names from the ones passed from the route unset($_SERVER['__test.controller_callAction_parameters']); $router->get(($str = Str::random()).'/{one}/{two}', RouteTestAnotherControllerWithParameterStub::class.'@differentArgumentNames'); $router->dispatch(Request::create($str.'/one/two', 'GET')); $this->assertEquals(['one' => 'one', 'two' => 'two'], $_SERVER['__test.controller_callAction_parameters']); // Has two arguments with same name but argument order is reversed unset($_SERVER['__test.controller_callAction_parameters']); $router->get(($str = Str::random()).'/{one}/{two}', RouteTestAnotherControllerWithParameterStub::class.'@reversedArguments'); $router->dispatch(Request::create($str.'/one/two', 'GET')); $this->assertEquals(['one' => 'one', 'two' => 'two'], $_SERVER['__test.controller_callAction_parameters']); // No route parameters while method has parameters unset($_SERVER['__test.controller_callAction_parameters']); $router->get(($str = Str::random()).'', RouteTestAnotherControllerWithParameterStub::class.'@oneArgument'); $router->dispatch(Request::create($str, 'GET')); $this->assertEquals([], $_SERVER['__test.controller_callAction_parameters']); // With model bindings unset($_SERVER['__test.controller_callAction_parameters']); $router->get(($str = Str::random()).'/{user}/{defaultNull?}/{team?}', [ 'middleware' => SubstituteBindings::class, 'uses' => RouteTestAnotherControllerWithParameterStub::class.'@withModels', ]); $router->dispatch(Request::create($str.'/1', 'GET')); $values = array_values($_SERVER['__test.controller_callAction_parameters']); $this->assertInstanceOf(Request::class, $values[0]); $this->assertEquals(1, $values[1]->value); $this->assertNull($values[2]); $this->assertNull($values[3]); } public function testLeadingParamDoesntReceiveForwardSlashOnEmptyPath() { $router = $this->getRouter(); $outer_one = 'abc1234'; // a string that is not one we're testing $router->get('{one?}', [ 'uses' => function ($one = null) use (&$outer_one) { $outer_one = $one; return $one; }, 'where' => ['one' => '(.+)'], ]); $this->assertSame('', $router->dispatch(Request::create(''))->getContent()); $this->assertNull($outer_one); // Expects: '' ($one === null) // Actual: '/' ($one === '/') $this->assertSame('foo', $router->dispatch(Request::create('/foo', 'GET'))->getContent()); $this->assertSame('foo/bar/baz', $router->dispatch(Request::create('/foo/bar/baz', 'GET'))->getContent()); } public function testRoutesDontMatchNonMatchingPathsWithLeadingOptionals() { $this->expectException(NotFoundHttpException::class); $router = $this->getRouter(); $router->get('{baz?}', function ($age = 25) { return $age; }); $this->assertSame('25', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent()); } public function testRoutesDontMatchNonMatchingDomain() { $this->expectException(NotFoundHttpException::class); $router = $this->getRouter(); $router->get('foo/bar', ['domain' => 'api.foo.bar', function () { return 'hello'; }]); $this->assertSame('hello', $router->dispatch(Request::create('http://api.baz.boom/foo/bar', 'GET'))->getContent()); } public function testRouteDomainRegistration() { $router = $this->getRouter(); $router->get('/foo/bar')->domain('api.foo.bar')->uses(function () { return 'hello'; }); $this->assertSame('hello', $router->dispatch(Request::create('http://api.foo.bar/foo/bar', 'GET'))->getContent()); } public function testMatchesMethodAgainstRequests() { /* * Basic */ $request = Request::create('foo/bar', 'GET'); $route = new Route('GET', 'foo/{bar}', function () { // }); $this->assertTrue($route->matches($request)); $request = Request::create('foo/bar', 'GET'); $route = new Route('GET', 'foo', function () { // }); $this->assertFalse($route->matches($request)); /* * Method checks */ $request = Request::create('foo/bar', 'GET'); $route = new Route('GET', 'foo/{bar}', function () { // }); $this->assertTrue($route->matches($request)); $request = Request::create('foo/bar', 'POST'); $route = new Route('GET', 'foo', function () { // }); $this->assertFalse($route->matches($request)); /* * Domain checks */ $request = Request::create('http://something.foo.com/foo/bar', 'GET'); $route = new Route('GET', 'foo/{bar}', ['domain' => '{foo}.foo.com', function () { // }]); $this->assertTrue($route->matches($request)); $request = Request::create('http://something.bar.com/foo/bar', 'GET'); $route = new Route('GET', 'foo/{bar}', ['domain' => '{foo}.foo.com', function () { // }]); $this->assertFalse($route->matches($request)); /* * HTTPS checks */ $request = Request::create('https://foo.com/foo/bar', 'GET'); $route = new Route('GET', 'foo/{bar}', ['https', function () { // }]); $this->assertTrue($route->matches($request)); $request = Request::create('https://foo.com/foo/bar', 'GET'); $route = new Route('GET', 'foo/{bar}', ['https', 'baz' => true, function () { // }]); $this->assertTrue($route->matches($request)); $request = Request::create('http://foo.com/foo/bar', 'GET'); $route = new Route('GET', 'foo/{bar}', ['https', function () { // }]); $this->assertFalse($route->matches($request)); /* * HTTP checks */ $request = Request::create('https://foo.com/foo/bar', 'GET'); $route = new Route('GET', 'foo/{bar}', ['http', function () { // }]); $this->assertFalse($route->matches($request)); $request = Request::create('http://foo.com/foo/bar', 'GET'); $route = new Route('GET', 'foo/{bar}', ['http', function () { // }]); $this->assertTrue($route->matches($request)); $request = Request::create('http://foo.com/foo/bar', 'GET'); $route = new Route('GET', 'foo/{bar}', ['baz' => true, function () { // }]); $this->assertTrue($route->matches($request)); }
193817
lic function testWherePatternsProperlyFilter() { $request = Request::create('foo/123', 'GET'); $route = new Route('GET', 'foo/{bar}', function () { // }); $route->where('bar', '[0-9]+'); $this->assertTrue($route->matches($request)); $request = Request::create('foo/123abc', 'GET'); $route = new Route('GET', 'foo/{bar}', function () { // }); $route->where('bar', '[0-9]+'); $this->assertFalse($route->matches($request)); $request = Request::create('foo/123abc', 'GET'); $route = new Route('GET', 'foo/{bar}', ['where' => ['bar' => '[0-9]+'], function () { // }]); $route->where('bar', '[0-9]+'); $this->assertFalse($route->matches($request)); $request = Request::create('foo/123', 'GET'); $route = new Route('GET', 'foo/{bar}', ['where' => ['bar' => '123|456'], function () { // }]); $route->where('bar', '123|456'); $this->assertTrue($route->matches($request)); $request = Request::create('foo/123abc', 'GET'); $route = new Route('GET', 'foo/{bar}', ['where' => ['bar' => '123|456'], function () { // }]); $route->where('bar', '123|456'); $this->assertFalse($route->matches($request)); /* * Optional */ $request = Request::create('foo/123', 'GET'); $route = new Route('GET', 'foo/{bar?}', function () { // }); $route->where('bar', '[0-9]+'); $this->assertTrue($route->matches($request)); $request = Request::create('foo/123', 'GET'); $route = new Route('GET', 'foo/{bar?}', ['where' => ['bar' => '[0-9]+'], function () { // }]); $route->where('bar', '[0-9]+'); $this->assertTrue($route->matches($request)); $request = Request::create('foo/123', 'GET'); $route = new Route('GET', 'foo/{bar?}/{baz?}', function () { // }); $route->where('bar', '[0-9]+'); $this->assertTrue($route->matches($request)); $request = Request::create('foo/123/foo', 'GET'); $route = new Route('GET', 'foo/{bar?}/{baz?}', function () { // }); $route->where('bar', '[0-9]+'); $this->assertTrue($route->matches($request)); $request = Request::create('foo/123abc', 'GET'); $route = new Route('GET', 'foo/{bar?}', function () { // }); $route->where('bar', '[0-9]+'); $this->assertFalse($route->matches($request)); } public function testRoutePrefixParameterParsing() { $route = new Route('GET', '/foo', ['prefix' => 'profiles/{user:username}/portfolios', 'uses' => function () { // }]); $this->assertSame('profiles/{user}/portfolios/foo', $route->uri()); } public function testDotDoesNotMatchEverything() { $route = new Route('GET', 'images/{id}.{ext}', function () { // }); $request1 = Request::create('images/1.png', 'GET'); $this->assertTrue($route->matches($request1)); $route->bind($request1); $this->assertSame('1', (string) $route->parameter('id')); $this->assertSame('png', $route->parameter('ext')); $request2 = Request::create('images/12.png', 'GET'); $this->assertTrue($route->matches($request2)); $route->bind($request2); $this->assertSame('12', $route->parameter('id')); $this->assertSame('png', $route->parameter('ext')); } public function testRouteBinding() { $router = $this->getRouter(); $router->get('foo/{bar}', ['middleware' => SubstituteBindings::class, 'uses' => function ($name) { return $name; }]); $router->bind('bar', function ($value) { return strtoupper($value); }); $this->assertSame('TAYLOR', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent()); } public function testRouteClassBinding() { $router = $this->getRouter(); $router->get('foo/{bar}', ['middleware' => SubstituteBindings::class, 'uses' => function ($name) { return $name; }]); $router->bind('bar', RouteBindingStub::class); $this->assertSame('TAYLOR', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent()); } public function testRouteClassMethodBinding() { $router = $this->getRouter(); $router->get('foo/{bar}', ['middleware' => SubstituteBindings::class, 'uses' => function ($name) { return $name; }]); $router->bind('bar', RouteBindingStub::class.'@find'); $this->assertSame('dragon', $router->dispatch(Request::create('foo/Dragon', 'GET'))->getContent()); } public function testMiddlewarePrioritySorting() { $middleware = [ Placeholder1::class, SubstituteBindings::class, Placeholder2::class, Authenticate::class, ExampleMiddleware::class, Placeholder3::class, ]; $router = $this->getRouter(); $router->middlewarePriority = [ExampleMiddlewareContract::class, Authenticate::class, SubstituteBindings::class, Authorize::class]; $route = $router->get('foo', ['middleware' => $middleware, 'uses' => function ($name) { return $name; }]); $this->assertEquals([ Placeholder1::class, ExampleMiddleware::class, Authenticate::class, SubstituteBindings::class, Placeholder2::class, Placeholder3::class, ], $router->gatherRouteMiddleware($route)); } public function testModelBinding() { $router = $this->getRouter(); $router->get('foo/{bar}', ['middleware' => SubstituteBindings::class, 'uses' => function ($name) { return $name; }]); $router->model('bar', RouteModelBindingStub::class); $this->assertSame('TAYLOR', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent()); } public function testModelBindingWithNullReturn() { $this->expectException(ModelNotFoundException::class); $this->expectExceptionMessage('No query results for model [Illuminate\Tests\Routing\RouteModelBindingNullStub].'); $router = $this->getRouter(); $router->get('foo/{bar}', ['middleware' => SubstituteBindings::class, 'uses' => function ($name) { return $name; }]); $router->model('bar', RouteModelBindingNullStub::class); $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent(); } public function testModelBindingWithCustomNullReturn() { $router = $this->getRouter(); $router->get('foo/{bar}', ['middleware' => SubstituteBindings::class, 'uses' => function ($name) { return $name; }]); $router->model('bar', RouteModelBindingNullStub::class, function () { return 'missing'; }); $this->assertSame('missing', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent()); } public function testModelBindingWithBindingClosure() { $router = $this->getRouter(); $router->get('foo/{bar}', ['middleware' => SubstituteBindings::class, 'uses' => function ($name) { return $name; }]); $router->model('bar', RouteModelBindingNullStub::class, function ($value) { return (new RouteModelBindingClosureStub)->findAlternate($value); }); $this->assertSame('tayloralt', $router->dispatch(Request::create('foo/TAYLOR', 'GET'))->getContent()); }
193820
lic function testResourceRouting() { $router = $this->getRouter(); $router->resource('foo', 'FooController'); $routes = $router->getRoutes(); $this->assertCount(7, $routes); $router = $this->getRouter(); $router->resource('foo', 'FooController', ['only' => ['update']]); $routes = $router->getRoutes(); $this->assertCount(1, $routes); $router = $this->getRouter(); $router->resource('foo', 'FooController', ['only' => ['show', 'destroy']]); $routes = $router->getRoutes(); $this->assertCount(2, $routes); $router = $this->getRouter(); $router->resource('foo', 'FooController', ['except' => ['show', 'destroy']]); $routes = $router->getRoutes(); $this->assertCount(5, $routes); $router = $this->getRouter(); $router->resource('foo-bars', 'FooController', ['only' => ['show']]); $routes = $router->getRoutes(); $routes = $routes->getRoutes(); $this->assertSame('foo-bars/{foo_bar}', $routes[0]->uri()); $router = $this->getRouter(); $router->resource('foo-bar.foo-baz', 'FooController', ['only' => ['show']]); $routes = $router->getRoutes(); $routes = $routes->getRoutes(); $this->assertSame('foo-bar/{foo_bar}/foo-baz/{foo_baz}', $routes[0]->uri()); $router = $this->getRouter(); $router->resource('foo-bars', 'FooController', ['only' => ['show'], 'as' => 'prefix']); $routes = $router->getRoutes(); $routes = $routes->getRoutes(); $this->assertSame('foo-bars/{foo_bar}', $routes[0]->uri()); $this->assertSame('prefix.foo-bars.show', $routes[0]->getName()); ResourceRegistrar::verbs([ 'create' => 'ajouter', 'edit' => 'modifier', ]); $router = $this->getRouter(); $router->resource('foo', 'FooController'); $routes = $router->getRoutes(); $this->assertSame('foo/ajouter', $routes->getByName('foo.create')->uri()); $this->assertSame('foo/{foo}/modifier', $routes->getByName('foo.edit')->uri()); } public function testResourceRoutingParameters() { ResourceRegistrar::singularParameters(); $router = $this->getRouter(); $router->resource('foos', 'FooController'); $router->resource('foos.bars', 'FooController'); $routes = $router->getRoutes(); $routes = $routes->getRoutes(); $this->assertSame('foos/{foo}', $routes[3]->uri()); $this->assertSame('foos/{foo}/bars/{bar}', $routes[10]->uri()); ResourceRegistrar::setParameters(['foos' => 'oof', 'bazs' => 'b']); $router = $this->getRouter(); $router->resource('bars.foos.bazs', 'FooController'); $routes = $router->getRoutes(); $routes = $routes->getRoutes(); $this->assertSame('bars/{bar}/foos/{oof}/bazs/{b}', $routes[3]->uri()); ResourceRegistrar::setParameters(); ResourceRegistrar::singularParameters(false); $router = $this->getRouter(); $router->resource('foos', 'FooController', ['parameters' => 'singular']); $router->resource('foos.bars', 'FooController')->parameters('singular'); $routes = $router->getRoutes(); $routes = $routes->getRoutes(); $this->assertSame('foos/{foo}', $routes[3]->uri()); $this->assertSame('foos/{foo}/bars/{bar}', $routes[10]->uri()); $router = $this->getRouter(); $router->resource('foos.bars', 'FooController', ['parameters' => ['foos' => 'foo', 'bars' => 'bar']]); $routes = $router->getRoutes(); $routes = $routes->getRoutes(); $this->assertSame('foos/{foo}/bars/{bar}', $routes[3]->uri()); $router = $this->getRouter(); $router->resource('foos.bars', 'FooController')->parameter('foos', 'foo')->parameter('bars', 'bar'); $routes = $router->getRoutes(); $routes = $routes->getRoutes(); $this->assertSame('foos/{foo}/bars/{bar}', $routes[3]->uri()); } public function testResourceRouteNaming() { $router = $this->getRouter(); $router->resource('foo', 'FooController'); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.index')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.show')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.create')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.store')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.edit')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.update')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.destroy')); $router = $this->getRouter(); $router->resource('foo.bar', 'FooController'); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.bar.index')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.bar.show')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.bar.create')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.bar.store')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.bar.edit')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.bar.update')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.bar.destroy')); $router = $this->getRouter(); $router->resource('prefix/foo.bar', 'FooController'); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.bar.index')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.bar.show')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.bar.create')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.bar.store')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.bar.edit')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.bar.update')); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo.bar.destroy')); $router = $this->getRouter(); $router->resource('foo', 'FooController', ['names' => [ 'index' => 'foo', 'show' => 'bar', ]]); $this->assertTrue($router->getRoutes()->hasNamedRoute('foo')); $this->assertTrue($router->getRoutes()->hasNamedRoute('bar')); $router = $this->getRouter(); $router->resource('foo', 'FooController', ['names' => 'bar']); $this->assertTrue($router->getRoutes()->hasNamedRoute('bar.index')); $this->assertTrue($router->getRoutes()->hasNamedRoute('bar.show')); $this->assertTrue($router->getRoutes()->hasNamedRoute('bar.create')); $this->assertTrue($router->getRoutes()->hasNamedRoute('bar.store')); $this->assertTrue($router->getRoutes()->hasNamedRoute('bar.edit')); $this->assertTrue($router->getRoutes()->hasNamedRoute('bar.update')); $this->assertTrue($router->getRoutes()->hasNamedRoute('bar.destroy')); }
193827
nction testControllerRoutesWithADefaultNamespace() { $url = new UrlGenerator( $routes = new RouteCollection, Request::create('http://www.foo.com/') ); $url->setRootControllerNamespace('namespace'); /* * Controller Route Route */ $route = new Route(['GET'], 'foo/bar', ['controller' => 'namespace\foo@bar']); $routes->add($route); $route = new Route(['GET'], 'something/else', ['controller' => 'something\foo@bar']); $routes->add($route); $route = new Route(['GET'], 'foo/invoke', ['controller' => 'namespace\InvokableActionStub']); $routes->add($route); $this->assertSame('http://www.foo.com/foo/bar', $url->action('foo@bar')); $this->assertSame('http://www.foo.com/something/else', $url->action('\something\foo@bar')); $this->assertSame('http://www.foo.com/foo/invoke', $url->action('InvokableActionStub')); } public function testControllerRoutesOutsideOfDefaultNamespace() { $url = new UrlGenerator( $routes = new RouteCollection, Request::create('http://www.foo.com/') ); $url->setRootControllerNamespace('namespace'); $route = new Route(['GET'], 'root/namespace', ['controller' => '\root\namespace@foo']); $routes->add($route); $route = new Route(['GET'], 'invokable/namespace', ['controller' => '\root\namespace\InvokableActionStub']); $routes->add($route); $this->assertSame('http://www.foo.com/root/namespace', $url->action('\root\namespace@foo')); $this->assertSame('http://www.foo.com/invokable/namespace', $url->action('\root\namespace\InvokableActionStub')); } public function testRoutableInterfaceRouting() { $url = new UrlGenerator( $routes = new RouteCollection, Request::create('http://www.foo.com/') ); $route = new Route(['GET'], 'foo/{bar}', ['as' => 'routable']); $routes->add($route); $model = new RoutableInterfaceStub; $model->key = 'routable'; $this->assertSame('/foo/routable', $url->route('routable', [$model], false)); } public function testRoutableInterfaceRoutingWithCustomBindingField() { $url = new UrlGenerator( $routes = new RouteCollection, Request::create('http://www.foo.com/') ); $route = new Route(['GET'], 'foo/{bar:slug}', ['as' => 'routable']); $routes->add($route); $model = new RoutableInterfaceStub; $model->key = 'routable'; $this->assertSame('/foo/test-slug', $url->route('routable', ['bar' => $model], false)); $this->assertSame('/foo/test-slug', $url->route('routable', [$model], false)); } public function testRoutableInterfaceRoutingAsQueryString() { $url = new UrlGenerator( $routes = new RouteCollection, Request::create('http://www.foo.com/') ); $route = new Route(['GET'], 'foo', ['as' => 'query-string']); $routes->add($route); $model = new RoutableInterfaceStub; $model->key = 'routable'; $this->assertSame('/foo?routable', $url->route('query-string', $model, false)); $this->assertSame('/foo?routable', $url->route('query-string', [$model], false)); $this->assertSame('/foo?foo=routable', $url->route('query-string', ['foo' => $model], false)); } /** * @todo Fix bug related to route keys * * @link https://github.com/laravel/framework/pull/42425 */ public function testRoutableInterfaceRoutingWithSeparateBindingFieldOnlyForSecondParameter() { $this->markTestSkipped('See https://github.com/laravel/framework/pull/43255'); $url = new UrlGenerator( $routes = new RouteCollection, Request::create('http://www.foo.com/') ); $route = new Route(['GET'], 'foo/{bar}/{baz:slug}', ['as' => 'routable']); $routes->add($route); $model1 = new RoutableInterfaceStub; $model1->key = 'routable-1'; $model2 = new RoutableInterfaceStub; $model2->key = 'routable-2'; $this->assertSame('/foo/routable-1/test-slug', $url->route('routable', ['bar' => $model1, 'baz' => $model2], false)); $this->assertSame('/foo/routable-1/test-slug', $url->route('routable', [$model1, $model2], false)); } public function testRoutableInterfaceRoutingWithSingleParameter() { $url = new UrlGenerator( $routes = new RouteCollection, Request::create('http://www.foo.com/') ); $route = new Route(['GET'], 'foo/{bar}', ['as' => 'routable']); $routes->add($route); $model = new RoutableInterfaceStub; $model->key = 'routable'; $this->assertSame('/foo/routable', $url->route('routable', $model, false)); } public function testRoutesMaintainRequestScheme() { $url = new UrlGenerator( $routes = new RouteCollection, Request::create('https://www.foo.com/') ); /* * Named Routes */ $route = new Route(['GET'], 'foo/bar', ['as' => 'foo']); $routes->add($route); $this->assertSame('https://www.foo.com/foo/bar', $url->route('foo')); } public function testHttpOnlyRoutes() { $url = new UrlGenerator( $routes = new RouteCollection, Request::create('https://www.foo.com/') ); /* * Named Routes */ $route = new Route(['GET'], 'foo/bar', ['as' => 'foo', 'http']); $routes->add($route); $this->assertSame('http://www.foo.com/foo/bar', $url->route('foo')); } public function testRoutesWithDomains() { $url = new UrlGenerator( $routes = new RouteCollection, Request::create('http://www.foo.com/') ); $route = new Route(['GET'], 'foo/bar', ['as' => 'foo', 'domain' => 'sub.foo.com']); $routes->add($route); /* * Wildcards & Domains... */ $route = new Route(['GET'], 'foo/bar/{baz}', ['as' => 'bar', 'domain' => 'sub.{foo}.com']); $routes->add($route); $this->assertSame('http://sub.foo.com/foo/bar', $url->route('foo')); $this->assertSame('http://sub.taylor.com/foo/bar/otwell', $url->route('bar', ['taylor', 'otwell'])); $this->assertSame('/foo/bar/otwell', $url->route('bar', ['taylor', 'otwell'], false)); } public function testRoutesWithDomainsAndPorts() { $url = new UrlGenerator( $routes = new RouteCollection, Request::create('http://www.foo.com:8080/') ); $route = new Route(['GET'], 'foo/bar', ['as' => 'foo', 'domain' => 'sub.foo.com']); $routes->add($route); /* * Wildcards & Domains... */ $route = new Route(['GET'], 'foo/bar/{baz}', ['as' => 'bar', 'domain' => 'sub.{foo}.com']); $routes->add($route); $this->assertSame('http://sub.foo.com:8080/foo/bar', $url->route('foo')); $this->assertSame('http://sub.taylor.com:8080/foo/bar/otwell', $url->route('bar', ['taylor', 'otwell'])); } pub
193839
public function testCanRegisterGroupWithMiddleware() { $this->router->middleware('group-middleware')->group(function ($router) { $router->get('users', function () { return 'all-users'; }); }); $this->seeResponse('all-users', Request::create('users', 'GET')); $this->seeMiddleware('group-middleware'); } public function testCanRegisterGroupWithoutMiddleware() { $this->router->withoutMiddleware('one')->group(function ($router) { $router->get('users', function () { return 'all-users'; })->middleware(['one', 'two']); }); $this->seeResponse('all-users', Request::create('users', 'GET')); $this->assertEquals(['one'], $this->getRoute()->excludedMiddleware()); } public function testCanRegisterGroupWithStringableMiddleware() { $one = new class implements Stringable { public function __toString() { return 'one'; } }; $this->router->middleware($one)->group(function ($router) { $router->get('users', function () { return 'all-users'; }); }); $this->seeResponse('all-users', Request::create('users', 'GET')); $this->seeMiddleware('one'); } public function testCanRegisterGroupWithNamespace() { $this->router->namespace('App\Http\Controllers')->group(function ($router) { $router->get('users', 'UsersController@index'); }); $this->assertSame( 'App\Http\Controllers\UsersController@index', $this->getRoute()->getAction()['uses'] ); } public function testCanRegisterGroupWithPrefix() { $this->router->prefix('api')->group(function ($router) { $router->get('users', 'UsersController@index'); }); $this->assertSame('api/users', $this->getRoute()->uri()); } public function testCanRegisterGroupWithPrefixAndWhere() { $this->router->prefix('foo/{bar}')->where(['bar' => '[0-9]+'])->group(function ($router) { $router->get('here', function () { return 'good'; }); }); $this->seeResponse('good', Request::create('foo/12345/here', 'GET')); } public function testCanRegisterGroupWithNamePrefix() { $this->router->name('api.')->group(function ($router) { $router->get('users', 'UsersController@index')->name('users'); }); $this->assertSame('api.users', $this->getRoute()->getName()); } public function testCanRegisterGroupWithDomain() { $this->router->domain('{account}.myapp.com')->group(function ($router) { $router->get('users', 'UsersController@index'); }); $this->assertSame('{account}.myapp.com', $this->getRoute()->getDomain()); } public function testCanRegisterGroupWithDomainAndNamePrefix() { $this->router->domain('{account}.myapp.com')->name('api.')->group(function ($router) { $router->get('users', 'UsersController@index')->name('users'); }); $this->assertSame('{account}.myapp.com', $this->getRoute()->getDomain()); $this->assertSame('api.users', $this->getRoute()->getName()); } public function testCanRegisterGroupWithController() { $this->router->controller(RouteRegistrarControllerStub::class)->group(function ($router) { $router->get('users', 'index'); }); $this->assertSame( RouteRegistrarControllerStub::class.'@index', $this->getRoute()->getAction()['uses'] ); } public function testCanOverrideGroupControllerWithStringSyntax() { $this->router->controller(RouteRegistrarControllerStub::class)->group(function ($router) { $router->get('users', 'UserController@index'); }); $this->assertSame( 'UserController@index', $this->getRoute()->getAction()['uses'] ); } public function testCanOverrideGroupControllerWithClosureSyntax() { $this->router->controller(RouteRegistrarControllerStub::class)->group(function ($router) { $router->get('users', function () { return 'hello world'; }); }); $this->seeResponse('hello world', Request::create('users', 'GET')); } public function testCanOverrideGroupControllerWithInvokableControllerSyntax() { $this->router->controller(RouteRegistrarControllerStub::class)->group(function ($router) { $router->get('users', InvokableRouteRegistrarControllerStub::class); }); $this->assertSame( InvokableRouteRegistrarControllerStub::class.'@__invoke', $this->getRoute()->getAction()['uses'] ); } public function testWillUseTheLatestGroupController() { $this->router->controller(RouteRegistrarControllerStub::class)->group(function ($router) { $router->group(['controller' => FooController::class], function ($router) { $router->get('users', 'index'); }); }); $this->assertSame( FooController::class.'@index', $this->getRoute()->getAction()['uses'] ); } public function testCanOverrideGroupControllerWithArraySyntax() { $this->router->controller(RouteRegistrarControllerStub::class)->group(function ($router) { $router->get('users', [FooController::class, 'index']); }); $this->assertSame( FooController::class.'@index', $this->getRoute()->getAction()['uses'] ); } public function testRouteGroupingWithoutPrefix() { $this->router->group([], function ($router) { $router->prefix('bar')->get('baz', ['as' => 'baz', function () { return 'hello'; }]); }); $this->seeResponse('hello', Request::create('bar/baz', 'GET')); } public function testRouteGroupChaining() { $this->router ->group([], function ($router) { $router->get('foo', function () { return 'hello'; }); }) ->group([], function ($router) { $router->get('bar', function () { return 'goodbye'; }); }); $routeCollection = $this->router->getRoutes(); $this->assertInstanceOf(\Illuminate\Routing\Route::class, $routeCollection->match(Request::create('foo', 'GET'))); $this->assertInstanceOf(\Illuminate\Routing\Route::class, $routeCollection->match(Request::create('bar', 'GET'))); } public function testRegisteringNonApprovedAttributesThrows() { $this->expectException(BadMethodCallException::class); $this->expectExceptionMessage('Method Illuminate\Routing\RouteRegistrar::unsupportedMethod does not exist.'); $this->router->domain('foo')->unsupportedMethod('bar')->group(function ($router) { // }); } public function testCanRegisterResource() { $this->router->middleware('resource-middleware') ->resource('users', RouteRegistrarControllerStub::class); $this->seeResponse('deleted', Request::create('users/1', 'DELETE')); $this->seeMiddleware('resource-middleware'); } public function testCanRegisterResourcesWithExceptOption() { $this->router->resources([ 'resource-one' => RouteRegistrarControllerStubOne::class, 'resource-two' => RouteRegistrarControllerStubTwo::class, 'resource-three' => RouteRegistrarControllerStubThree::class, ], ['except' => ['create', 'show']]); $this->assertCount(15, $this->router->getRoutes()); foreach (['one', 'two', 'three'] as $resource) { $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.index')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.store')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.edit')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.update')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.destroy')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.create')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.show')); } }
193840
public function testCanRegisterResourcesWithOnlyOption() { $this->router->resources([ 'resource-one' => RouteRegistrarControllerStubOne::class, 'resource-two' => RouteRegistrarControllerStubTwo::class, 'resource-three' => RouteRegistrarControllerStubThree::class, ], ['only' => ['create', 'show']]); $this->assertCount(6, $this->router->getRoutes()); foreach (['one', 'two', 'three'] as $resource) { $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.create')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.show')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.index')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.store')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.edit')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.update')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.destroy')); } } public function testCanRegisterResourcesWithoutOption() { $this->router->resources([ 'resource-one' => RouteRegistrarControllerStubOne::class, 'resource-two' => RouteRegistrarControllerStubTwo::class, 'resource-three' => RouteRegistrarControllerStubThree::class, ]); $this->assertCount(21, $this->router->getRoutes()); foreach (['one', 'two', 'three'] as $resource) { $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.index')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.create')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.store')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.show')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.edit')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.update')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.destroy')); } } public function testCanRegisterResourceWithMissingOption() { $this->router->middleware('resource-middleware') ->resource('users', RouteRegistrarControllerStub::class) ->missing(function () { return 'missing'; }); $this->assertIsCallable($this->router->getRoutes()->getByName('users.show')->getMissing()); $this->assertIsCallable($this->router->getRoutes()->getByName('users.edit')->getMissing()); $this->assertIsCallable($this->router->getRoutes()->getByName('users.update')->getMissing()); $this->assertIsCallable($this->router->getRoutes()->getByName('users.destroy')->getMissing()); $this->assertNull($this->router->getRoutes()->getByName('users.index')->getMissing()); $this->assertNull($this->router->getRoutes()->getByName('users.create')->getMissing()); $this->assertNull($this->router->getRoutes()->getByName('users.store')->getMissing()); } public function testCanAccessRegisteredResourceRoutesAsRouteCollection() { $resource = $this->router->middleware('resource-middleware') ->resource('users', RouteRegistrarControllerStub::class) ->register(); $this->assertCount(7, $resource->getRoutes()); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.index')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.create')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.store')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.show')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.edit')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.update')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.destroy')); } public function testCanLimitMethodsOnRegisteredResource() { $this->router->resource('users', RouteRegistrarControllerStub::class) ->only('index', 'show', 'destroy'); $this->assertCount(3, $this->router->getRoutes()); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.index')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.show')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.destroy')); } public function testCanExcludeMethodsOnRegisteredResource() { $this->router->resource('users', RouteRegistrarControllerStub::class) ->except(['index', 'create', 'store', 'show', 'edit']); $this->assertCount(2, $this->router->getRoutes()); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.update')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.destroy')); } public function testCanLimitAndExcludeMethodsOnRegisteredResource() { $this->router->resource('users', RouteRegistrarControllerStub::class) ->only('index', 'show', 'destroy') ->except('destroy'); $this->assertCount(2, $this->router->getRoutes()); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.index')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.show')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('users.destroy')); } public function testCanSetShallowOptionOnRegisteredResource() { $this->router->resource('users.tasks', RouteRegistrarControllerStub::class)->shallow(); $this->assertCount(7, $this->router->getRoutes()); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.tasks.index')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('tasks.show')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('users.tasks.show')); } public function testCanSetScopedOptionOnRegisteredResource() { $this->router->resource('users.tasks', RouteRegistrarControllerStub::class)->scoped(); $this->assertSame( ['user' => null], $this->router->getRoutes()->getByName('users.tasks.index')->bindingFields() ); $this->assertSame( ['user' => null, 'task' => null], $this->router->getRoutes()->getByName('users.tasks.show')->bindingFields() ); $this->router->resource('users.tasks', RouteRegistrarControllerStub::class)->scoped([ 'task' => 'slug', ]); $this->assertSame( ['user' => null], $this->router->getRoutes()->getByName('users.tasks.index')->bindingFields() ); $this->assertSame( ['user' => null, 'task' => 'slug'], $this->router->getRoutes()->getByName('users.tasks.show')->bindingFields() ); } public function testCanExcludeMethodsOnRegisteredApiResource() { $this->router->apiResource('users', RouteRegistrarControllerStub::class) ->except(['index', 'show', 'store']); $this->assertCount(2, $this->router->getRoutes()); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.update')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.destroy')); }
193841
public function testCanRegisterApiResourcesWithExceptOption() { $this->router->apiResources([ 'resource-one' => RouteRegistrarControllerStubOne::class, 'resource-two' => RouteRegistrarControllerStubTwo::class, 'resource-three' => RouteRegistrarControllerStubThree::class, ], ['except' => ['create', 'show']]); $this->assertCount(12, $this->router->getRoutes()); foreach (['one', 'two', 'three'] as $resource) { $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.index')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.store')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.update')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.destroy')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.create')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.show')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.edit')); } } public function testCanRegisterApiResourcesWithOnlyOption() { $this->router->apiResources([ 'resource-one' => RouteRegistrarControllerStubOne::class, 'resource-two' => RouteRegistrarControllerStubTwo::class, 'resource-three' => RouteRegistrarControllerStubThree::class, ], ['only' => ['index', 'show']]); $this->assertCount(6, $this->router->getRoutes()); foreach (['one', 'two', 'three'] as $resource) { $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.index')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.show')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.store')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.update')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.destroy')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.create')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.edit')); } } public function testCanRegisterApiResourcesWithoutOption() { $this->router->apiResources([ 'resource-one' => RouteRegistrarControllerStubOne::class, 'resource-two' => RouteRegistrarControllerStubTwo::class, 'resource-three' => RouteRegistrarControllerStubThree::class, ]); $this->assertCount(15, $this->router->getRoutes()); foreach (['one', 'two', 'three'] as $resource) { $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.index')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.show')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.store')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.update')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.destroy')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.create')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('resource-'.$resource.'.edit')); } } public function testUserCanRegisterApiResource() { $this->router->apiResource('users', RouteRegistrarControllerStub::class); $this->assertCount(5, $this->router->getRoutes()); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('users.create')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('users.edit')); } public function testUserCanRegisterApiResourceWithExceptOption() { $this->router->apiResource('users', RouteRegistrarControllerStub::class, [ 'except' => ['destroy'], ]); $this->assertCount(4, $this->router->getRoutes()); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('users.create')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('users.edit')); $this->assertFalse($this->router->getRoutes()->hasNamedRoute('users.destroy')); } public function testUserCanRegisterApiResourceWithOnlyOption() { $this->router->apiResource('users', RouteRegistrarControllerStub::class, [ 'only' => ['index', 'show'], ]); $this->assertCount(2, $this->router->getRoutes()); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.index')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('users.show')); } public function testCanNameRoutesOnRegisteredResource() { $this->router->resource('comments', RouteRegistrarControllerStub::class) ->only('create', 'store')->names('reply'); $this->router->resource('users', RouteRegistrarControllerStub::class) ->only('create', 'store')->names([ 'create' => 'user.build', 'store' => 'user.save', ]); $this->router->resource('posts', RouteRegistrarControllerStub::class) ->only('create', 'destroy') ->name('create', 'posts.make') ->name('destroy', 'posts.remove'); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('reply.create')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('reply.store')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('user.build')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('user.save')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('posts.make')); $this->assertTrue($this->router->getRoutes()->hasNamedRoute('posts.remove')); } public function testCanOverrideParametersOnRegisteredResource() { $this->router->resource('users', RouteRegistrarControllerStub::class) ->parameters(['users' => 'admin_user']); $this->router->resource('posts', RouteRegistrarControllerStub::class) ->parameter('posts', 'topic'); $this->assertStringContainsString('admin_user', $this->router->getRoutes()->getByName('users.show')->uri); $this->assertStringContainsString('topic', $this->router->getRoutes()->getByName('posts.show')->uri); } public function testCanSetMiddlewareOnRegisteredResource() { $this->router->resource('users', RouteRegistrarControllerStub::class) ->middleware(RouteRegistrarMiddlewareStub::class); $this->seeMiddleware(RouteRegistrarMiddlewareStub::class); } public function testResourceWithoutMiddlewareRegistration() { $this->router->resource('users', RouteRegistrarControllerStub::class) ->only('index') ->middleware(['one', 'two']) ->withoutMiddleware('one'); $this->seeResponse('controller', Request::create('users', 'GET')); $this->assertEquals(['one'], $this->getRoute()->excludedMiddleware()); } public function testResourceWithMiddlewareAsStringable() { $one = new class implements Stringable { public function __toString() { return 'one'; } }; $this->router->resource('users', RouteRegistrarControllerStub::class) ->only('index') ->middleware([$one, 'two']) ->withoutMiddleware('one'); $this->seeResponse('controller', Request::create('users', 'GET')); $this->assertEquals(['one', 'two'], $this->getRoute()->middleware()); $this->assertEquals(['one'], $this->getRoute()->excludedMiddleware()); } public function testResourceWheres() { $wheres = [ 'user' => '\d+', 'test' => '[a-z]+', ]; $this->router->resource('users', RouteRegistrarControllerStub::class) ->where($wheres); /** @var \Illuminate\Routing\Route $route */ foreach ($this->router->getRoutes() as $route) { $this->assertEquals($wheres, $route->wheres); } }
193842
public function testWhereNumberRegistration() { $wheres = ['foo' => '[0-9]+', 'bar' => '[0-9]+']; $this->router->get('/{foo}/{bar}')->whereNumber(['foo', 'bar']); $this->router->get('/api/{bar}/{foo}')->whereNumber(['bar', 'foo']); /** @var \Illuminate\Routing\Route $route */ foreach ($this->router->getRoutes() as $route) { $this->assertEquals($wheres, $route->wheres); } } public function testWhereAlphaRegistration() { $wheres = ['foo' => '[a-zA-Z]+', 'bar' => '[a-zA-Z]+']; $this->router->get('/{foo}/{bar}')->whereAlpha(['foo', 'bar']); $this->router->get('/api/{bar}/{foo}')->whereAlpha(['bar', 'foo']); /** @var \Illuminate\Routing\Route $route */ foreach ($this->router->getRoutes() as $route) { $this->assertEquals($wheres, $route->wheres); } } public function testWhereAlphaNumericRegistration() { $wheres = ['1a2b3c' => '[a-zA-Z0-9]+']; $this->router->get('/{foo}')->whereAlphaNumeric(['1a2b3c']); /** @var \Illuminate\Routing\Route $route */ foreach ($this->router->getRoutes() as $route) { $this->assertEquals($wheres, $route->wheres); } } public function testWhereInRegistration() { $wheres = ['foo' => 'one|two', 'bar' => 'one|two']; $this->router->get('/{foo}/{bar}')->whereIn(['foo', 'bar'], ['one', 'two']); $this->router->get('/api/{bar}/{foo}')->whereIn(['bar', 'foo'], ['one', 'two']); /** @var \Illuminate\Routing\Route $route */ foreach ($this->router->getRoutes() as $route) { $this->assertEquals($wheres, $route->wheres); } } public function testWhereInEnumRegistration() { $this->router->get('/posts/{category}')->whereIn('category', CategoryBackedEnum::cases()); $invalidRequest = Request::create('/posts/invalid-value', 'GET'); $this->assertFalse($this->getRoute()->matches($invalidRequest)); foreach (CategoryBackedEnum::cases() as $case) { $request = Request::create('/posts/'.$case->value, 'GET'); $this->assertTrue($this->getRoute()->matches($request)); } } public function testGroupWhereNumberRegistrationOnRouteRegistrar() { $wheres = ['foo' => '[0-9]+', 'bar' => '[0-9]+']; $this->router->prefix('/{foo}/{bar}')->whereNumber(['foo', 'bar'])->group(function ($router) { $router->get('/'); }); $this->router->prefix('/api/{bar}/{foo}')->whereNumber(['bar', 'foo'])->group(function ($router) { $router->get('/'); }); /** @var \Illuminate\Routing\Route $route */ foreach ($this->router->getRoutes() as $route) { $this->assertEquals($wheres, $route->wheres); } } public function testGroupWhereAlphaRegistrationOnRouteRegistrar() { $wheres = ['foo' => '[a-zA-Z]+', 'bar' => '[a-zA-Z]+']; $this->router->prefix('/{foo}/{bar}')->whereAlpha(['foo', 'bar'])->group(function ($router) { $router->get('/'); }); $this->router->prefix('/api/{bar}/{foo}')->whereAlpha(['bar', 'foo'])->group(function ($router) { $router->get('/'); }); /** @var \Illuminate\Routing\Route $route */ foreach ($this->router->getRoutes() as $route) { $this->assertEquals($wheres, $route->wheres); } } public function testGroupWhereAlphaNumericRegistrationOnRouteRegistrar() { $wheres = ['1a2b3c' => '[a-zA-Z0-9]+']; $this->router->prefix('/{foo}')->whereAlphaNumeric(['1a2b3c'])->group(function ($router) { $router->get('/'); }); /** @var \Illuminate\Routing\Route $route */ foreach ($this->router->getRoutes() as $route) { $this->assertEquals($wheres, $route->wheres); } } public function testGroupWhereInRegistrationOnRouteRegistrar() { $wheres = ['foo' => 'one|two', 'bar' => 'one|two']; $this->router->prefix('/{foo}/{bar}')->whereIn(['foo', 'bar'], ['one', 'two'])->group(function ($router) { $router->get('/'); }); $this->router->prefix('/api/{bar}/{foo}')->whereIn(['bar', 'foo'], ['one', 'two'])->group(function ($router) { $router->get('/'); }); /** @var \Illuminate\Routing\Route $route */ foreach ($this->router->getRoutes() as $route) { $this->assertEquals($wheres, $route->wheres); } } public function testGroupWhereNumberRegistrationOnRouter() { $wheres = ['foo' => '[0-9]+', 'bar' => '[0-9]+']; $this->router->whereNumber(['foo', 'bar'])->prefix('/{foo}/{bar}')->group(function ($router) { $router->get('/'); }); $this->router->whereNumber(['bar', 'foo'])->prefix('/api/{bar}/{foo}')->group(function ($router) { $router->get('/'); }); /** @var \Illuminate\Routing\Route $route */ foreach ($this->router->getRoutes() as $route) { $this->assertEquals($wheres, $route->wheres); } } public function testGroupWhereAlphaRegistrationOnRouter() { $wheres = ['foo' => '[a-zA-Z]+', 'bar' => '[a-zA-Z]+']; $this->router->whereAlpha(['foo', 'bar'])->prefix('/{foo}/{bar}')->group(function ($router) { $router->get('/'); }); $this->router->whereAlpha(['bar', 'foo'])->prefix('/api/{bar}/{foo}')->group(function ($router) { $router->get('/'); }); /** @var \Illuminate\Routing\Route $route */ foreach ($this->router->getRoutes() as $route) { $this->assertEquals($wheres, $route->wheres); } } public function testGroupWhereAlphaNumericRegistrationOnRouter() { $wheres = ['1a2b3c' => '[a-zA-Z0-9]+']; $this->router->whereAlphaNumeric(['1a2b3c'])->prefix('/{foo}')->group(function ($router) { $router->get('/'); }); /** @var \Illuminate\Routing\Route $route */ foreach ($this->router->getRoutes() as $route) { $this->assertEquals($wheres, $route->wheres); } } public function testGroupWhereInRegistrationOnRouter() { $wheres = ['foo' => 'one|two', 'bar' => 'one|two']; $this->router->whereIn(['foo', 'bar'], ['one', 'two'])->prefix('/{foo}/{bar}')->group(function ($router) { $router->get('/'); }); $this->router->whereIn(['bar', 'foo'], ['one', 'two'])->prefix('/api/{bar}/{foo}')->group(function ($router) { $router->get('/'); }); /** @var \Illuminate\Routing\Route $route */ foreach ($this->router->getRoutes() as $route) { $this->assertEquals($wheres, $route->wheres); } } public function testCanSetRouteName() { $this->router->as('users.index')->get('users', function () { return 'all-users'; }); $this->seeResponse('all-users', Request::create('users', 'GET')); $this->assertSame('users.index', $this->getRoute()->getName()); } public function testCanSetRouteNameUsingNameAlias() { $this->router->name('users.index')->get('users', function () { return 'all-users'; }); $this->seeResponse('all-users', Request::create('users', 'GET')); $this->assertSame('users.index', $this->getRoute()->getName()); }
193846
<?php use BaseController; class FooController extends BaseController { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @return \Illuminate\Http\Response */ public function store() { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param int $id * @return \Illuminate\Http\Response */ public function update($id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
193847
<?php use BaseController; class FooController extends BaseController { /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @return \Illuminate\Http\Response */ public function store() { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param int $id * @return \Illuminate\Http\Response */ public function update($id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
193869
public function testItChoosesValidRecordsUsingWhereNotRule() { $rule = new Exists('users', 'id'); $rule->whereNot('type', 'baz'); User::create(['id' => '1', 'type' => 'foo']); User::create(['id' => '2', 'type' => 'bar']); User::create(['id' => '3', 'type' => 'baz']); User::create(['id' => '4', 'type' => 'other']); User::create(['id' => '5', 'type' => 'baz']); $trans = $this->getIlluminateArrayTranslator(); $v = new Validator($trans, [], ['id' => $rule]); $v->setPresenceVerifier(new DatabasePresenceVerifier(Eloquent::getConnectionResolver())); $v->setData(['id' => 3]); $this->assertFalse($v->passes()); $v->setData(['id' => 4]); $this->assertTrue($v->passes()); } public function testItIgnoresSoftDeletes() { $rule = new Exists('table'); $rule->withoutTrashed(); $this->assertSame('exists:table,NULL,deleted_at,"NULL"', (string) $rule); $rule = new Exists('table'); $rule->withoutTrashed('softdeleted_at'); $this->assertSame('exists:table,NULL,softdeleted_at,"NULL"', (string) $rule); } public function testItOnlyTrashedSoftDeletes() { $rule = new Exists('table'); $rule->onlyTrashed(); $this->assertSame('exists:table,NULL,deleted_at,"NOT_NULL"', (string) $rule); $rule = new Exists('table'); $rule->onlyTrashed('softdeleted_at'); $this->assertSame('exists:table,NULL,softdeleted_at,"NOT_NULL"', (string) $rule); } protected function createSchema() { $this->schema('default')->create('users', function ($table) { $table->unsignedInteger('id'); $table->string('type'); }); } /** * Get a schema builder instance. * * @return \Illuminate\Database\Schema\Builder */ protected function schema($connection = 'default') { return $this->connection($connection)->getSchemaBuilder(); } /** * Get a database connection instance. * * @return \Illuminate\Database\Connection */ protected function connection($connection = 'default') { return $this->getConnectionResolver()->connection($connection); } /** * Get connection resolver. * * @return \Illuminate\Database\ConnectionResolverInterface */ protected function getConnectionResolver() { return Eloquent::getConnectionResolver(); } /** * Tear down the database schema. * * @return void */ protected function tearDown(): void { $this->schema('default')->drop('users'); } public function getIlluminateArrayTranslator() { return new Translator( new ArrayLoader, 'en' ); } } /** * Eloquent Models. */ class User extends Eloquent { protected $table = 'users'; protected $guarded = []; public $timestamps = false; } class UserWithPrefixedTable extends Eloquent { protected $table = 'public.users'; protected $guarded = []; public $timestamps = false; } class UserWithConnection extends User { protected $connection = 'mysql'; } class NoTableNameModel extends Eloquent { protected $guarded = []; public $timestamps = false; } class ClassWithRequiredConstructorParameters { private $bar; private $baz; public function __construct($bar, $baz) { $this->bar = $bar; $this->baz = $baz; } }
193920
unction testValidateUnique() { $trans = $this->getIlluminateArrayTranslator(); $v = new Validator($trans, ['email' => 'foo'], ['email' => 'Unique:users']); $mock = m::mock(DatabasePresenceVerifierInterface::class); $mock->shouldReceive('setConnection')->once()->with(null); $mock->shouldReceive('getCount')->once()->with('users', 'email', 'foo', null, null, [])->andReturn(0); $v->setPresenceVerifier($mock); $this->assertTrue($v->passes()); $v = new Validator($trans, ['email' => 'foo'], ['email' => 'Unique:connection.users']); $mock = m::mock(DatabasePresenceVerifierInterface::class); $mock->shouldReceive('setConnection')->once()->with('connection'); $mock->shouldReceive('getCount')->once()->with('users', 'email', 'foo', null, null, [])->andReturn(0); $v->setPresenceVerifier($mock); $this->assertTrue($v->passes()); $v = new Validator($trans, ['email' => 'foo'], ['email' => 'Unique:users,email_addr,1']); $mock = m::mock(DatabasePresenceVerifierInterface::class); $mock->shouldReceive('setConnection')->once()->with(null); $mock->shouldReceive('getCount')->once()->with('users', 'email_addr', 'foo', '1', 'id', [])->andReturn(1); $v->setPresenceVerifier($mock); $this->assertFalse($v->passes()); $v = new Validator($trans, ['email' => 'foo'], ['email' => 'Unique:users,email_addr,1,id_col']); $mock = m::mock(DatabasePresenceVerifierInterface::class); $mock->shouldReceive('setConnection')->once()->with(null); $mock->shouldReceive('getCount')->once()->with('users', 'email_addr', 'foo', '1', 'id_col', [])->andReturn(2); $v->setPresenceVerifier($mock); $this->assertFalse($v->passes()); $v = new Validator($trans, ['users' => [['id' => 1, 'email' => 'foo']]], ['users.*.email' => 'Unique:users,email,[users.*.id]']); $mock = m::mock(DatabasePresenceVerifierInterface::class); $mock->shouldReceive('setConnection')->once()->with(null); $mock->shouldReceive('getCount')->once()->with('users', 'email', 'foo', '1', 'id', [])->andReturn(1); $v->setPresenceVerifier($mock); $this->assertFalse($v->passes()); $v = new Validator($trans, ['email' => 'foo'], ['email' => 'Unique:users,email_addr,NULL,id_col,foo,bar']); $mock = m::mock(DatabasePresenceVerifierInterface::class); $mock->shouldReceive('setConnection')->once()->with(null); $mock->shouldReceive('getCount')->once()->withArgs(function () { return func_get_args() === ['users', 'email_addr', 'foo', null, 'id_col', ['foo' => 'bar']]; })->andReturn(2); $v->setPresenceVerifier($mock); $this->assertFalse($v->passes()); } public function testValidateUniqueAndExistsSendsCorrectFieldNameToDBWithArrays() { $trans = $this->getIlluminateArrayTranslator(); $v = new Validator($trans, [['email' => 'foo', 'type' => 'bar']], [ '*.email' => 'unique:users', '*.type' => 'exists:user_types', ]); $mock = m::mock(DatabasePresenceVerifierInterface::class); $mock->shouldReceive('setConnection')->twice()->with(null); $mock->shouldReceive('getCount')->with('users', 'email', 'foo', null, null, [])->andReturn(0); $mock->shouldReceive('getCount')->with('user_types', 'type', 'bar', null, null, [])->andReturn(1); $v->setPresenceVerifier($mock); $this->assertTrue($v->passes()); $trans = $this->getIlluminateArrayTranslator(); $closure = function () { // }; $v = new Validator($trans, [['email' => 'foo', 'type' => 'bar']], [ '*.email' => (new Unique('users'))->where($closure), '*.type' => (new Exists('user_types'))->where($closure), ]); $mock = m::mock(DatabasePresenceVerifierInterface::class); $mock->shouldReceive('setConnection')->twice()->with(null); $mock->shouldReceive('getCount')->with('users', 'email', 'foo', null, 'id', [$closure])->andReturn(0); $mock->shouldReceive('getCount')->with('user_types', 'type', 'bar', null, null, [$closure])->andReturn(1); $v->setPresenceVerifier($mock); $this->assertTrue($v->passes()); } public function testValidationExists() { $trans = $this->getIlluminateArrayTranslator(); $v = new Validator($trans, ['email' => 'foo'], ['email' => 'Exists:users']); $mock = m::mock(DatabasePresenceVerifierInterface::class); $mock->shouldReceive('setConnection')->once()->with(null); $mock->shouldReceive('getCount')->once()->with('users', 'email', 'foo', null, null, [])->andReturn(1); $v->setPresenceVerifier($mock); $this->assertTrue($v->passes()); $trans = $this->getIlluminateArrayTranslator(); $v = new Validator($trans, ['email' => 'foo'], ['email' => 'Exists:users,email,account_id,1,name,taylor']); $mock = m::mock(DatabasePresenceVerifierInterface::class); $mock->shouldReceive('setConnection')->once()->with(null); $mock->shouldReceive('getCount')->once()->with('users', 'email', 'foo', null, null, ['account_id' => 1, 'name' => 'taylor'])->andReturn(1); $v->setPresenceVerifier($mock); $this->assertTrue($v->passes()); $v = new Validator($trans, ['email' => 'foo'], ['email' => 'Exists:users,email_addr']); $mock = m::mock(DatabasePresenceVerifierInterface::class); $mock->shouldReceive('setConnection')->once()->with(null); $mock->shouldReceive('getCount')->once()->with('users', 'email_addr', 'foo', null, null, [])->andReturn(0); $v->setPresenceVerifier($mock); $this->assertFalse($v->passes()); $v = new Validator($trans, ['email' => ['foo']], ['email' => 'Exists:users,email_addr']); $mock = m::mock(DatabasePresenceVerifierInterface::class); $mock->shouldReceive('setConnection')->once()->with(null); $mock->shouldReceive('getMultiCount')->once()->with('users', 'email_addr', ['foo'], [])->andReturn(0); $v->setPresenceVerifier($mock); $this->assertFalse($v->passes()); $v = new Validator($trans, ['email' => 'foo'], ['email' => 'Exists:connection.users']); $mock = m::mock(DatabasePresenceVerifierInterface::class); $mock->shouldReceive('setConnection')->once()->with('connection'); $mock->shouldReceive('getCount')->once()->with('users', 'email', 'foo', null, null, [])->andReturn(1); $v->setPresenceVerifier($mock); $this->assertTrue($v->passes()); $v = new Validator($trans, ['email' => ['foo', 'foo']], ['email' => 'exists:users,email_addr']); $mock = m::mock(DatabasePresenceVerifierInterface::class); $mock->shouldReceive('setConnection')->once()->with(null); $mock->shouldReceive('getMultiCount')->once()->with('users', 'email_addr', ['foo', 'foo'], [])->andReturn(1); $v->setPresenceVerifier($mock); $this->assertTrue($v->passes()); } pu
193934
alse($v->passes()); // Ensure commas are not interpreted as parameter separators $v = new Validator($trans, ['x' => 'a,b'], ['x' => 'Regex:/^a,b$/i']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '12'], ['x' => 'Regex:/^12$/i']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => 12], ['x' => 'Regex:/^12$/i']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => ['y' => ['z' => 'james']]], ['x.*.z' => ['Regex:/^(taylor|james)$/i']]); $this->assertTrue($v->passes()); } public function testValidateNotRegex() { $trans = $this->getIlluminateArrayTranslator(); $v = new Validator($trans, ['x' => 'foo bar'], ['x' => 'NotRegex:/[xyz]/i']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => 'foo xxx bar'], ['x' => 'NotRegex:/[xyz]/i']); $this->assertFalse($v->passes()); // Ensure commas are not interpreted as parameter separators $v = new Validator($trans, ['x' => 'foo bar'], ['x' => 'NotRegex:/x{3,}/i']); $this->assertTrue($v->passes()); } public function testValidateDateAndFormat() { date_default_timezone_set('UTC'); $trans = $this->getIlluminateArrayTranslator(); $v = new Validator($trans, ['x' => '2000-01-01'], ['x' => 'date']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '01/01/2000'], ['x' => 'date']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '1325376000'], ['x' => 'date']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => 'Not a date'], ['x' => 'date']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => ['Not', 'a', 'date']], ['x' => 'date']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => new DateTime], ['x' => 'date']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => new DateTimeImmutable], ['x' => 'date']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '2000-01-01'], ['x' => 'date_format:Y-m-d']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '01/01/2001'], ['x' => 'date_format:Y-m-d']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '22000-01-01'], ['x' => 'date_format:Y-m-d']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '00-01-01'], ['x' => 'date_format:Y-m-d']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => ['Not', 'a', 'date']], ['x' => 'date_format:Y-m-d']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => "Contain null bytes \0"], ['x' => 'date_format:Y-m-d']); $this->assertTrue($v->fails()); // Set current machine date to 31/xx/xxxx $v = new Validator($trans, ['x' => '2013-02'], ['x' => 'date_format:Y-m']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '2000-01-01T00:00:00Atlantic/Azores'], ['x' => 'date_format:Y-m-d\TH:i:se']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '2000-01-01T00:00:00Z'], ['x' => 'date_format:Y-m-d\TH:i:sT']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '2000-01-01T00:00:00+0000'], ['x' => 'date_format:Y-m-d\TH:i:sO']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '2000-01-01T00:00:00+00:30'], ['x' => 'date_format:Y-m-d\TH:i:sP']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '2000-01-01 17:43:59'], ['x' => 'date_format:Y-m-d H:i:s']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '2000-01-01 17:43:59'], ['x' => 'date_format:H:i:s']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '2000-01-01 17:43:59'], ['x' => 'date_format:Y-m-d H:i:s,H:i:s']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '17:43:59'], ['x' => 'date_format:Y-m-d H:i:s,H:i:s']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '17:43:59'], ['x' => 'date_format:H:i:s']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '17:43:59'], ['x' => 'date_format:H:i']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '17:43'], ['x' => 'date_format:H:i']); $this->assertTrue($v->passes()); } public function testDateEquals() { date_default_timezone_set('UTC'); $trans = $this->getIlluminateArrayTranslator(); $v = new Validator($trans, ['x' => '2000-01-01'], ['x' => 'date_equals:2000-01-01']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => new Carbon('2000
193936
> 'Before:2012-01-01']); $this->assertFalse($v->passes()); $v = new Validator($trans, ['x' => new Carbon('2000-01-01')], ['x' => 'Before:2012-01-01']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => [new Carbon('2000-01-01')]], ['x' => 'Before:2012-01-01']); $this->assertFalse($v->passes()); $v = new Validator($trans, ['x' => '2012-01-01'], ['x' => 'After:2000-01-01']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => ['2012-01-01']], ['x' => 'After:2000-01-01']); $this->assertFalse($v->passes()); $v = new Validator($trans, ['x' => new Carbon('2012-01-01')], ['x' => 'After:2000-01-01']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => [new Carbon('2012-01-01')]], ['x' => 'After:2000-01-01']); $this->assertFalse($v->passes()); $v = new Validator($trans, ['start' => '2012-01-01', 'ends' => '2013-01-01'], ['start' => 'After:2000-01-01', 'ends' => 'After:start']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['start' => '2012-01-01', 'ends' => '2000-01-01'], ['start' => 'After:2000-01-01', 'ends' => 'After:start']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['start' => '2012-01-01', 'ends' => '2013-01-01'], ['start' => 'Before:ends', 'ends' => 'After:start']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['start' => '2012-01-01', 'ends' => '2000-01-01'], ['start' => 'Before:ends', 'ends' => 'After:start']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => new DateTime('2000-01-01')], ['x' => 'Before:2012-01-01']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['start' => new DateTime('2012-01-01'), 'ends' => new Carbon('2013-01-01')], ['start' => 'Before:ends', 'ends' => 'After:start']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['start' => '2012-01-01', 'ends' => new DateTime('2013-01-01')], ['start' => 'Before:ends', 'ends' => 'After:start']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['start' => new DateTime('2012-01-01'), 'ends' => new DateTime('2000-01-01')], ['start' => 'After:2000-01-01', 'ends' => 'After:start']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['start' => 'today', 'ends' => 'tomorrow'], ['start' => 'Before:ends', 'ends' => 'After:start']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '2012-01-01 17:43:59'], ['x' => 'Before:2012-01-01 17:44|After:2012-01-01 17:43:58']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '2012-01-01 17:44:01'], ['x' => 'Before:2012-01-01 17:44:02|After:2012-01-01 17:44']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '2012-01-01 17:44'], ['x' => 'Before:2012-01-01 17:44:00']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '2012-01-01 17:44'], ['x' => 'After:2012-01-01 17:44:00']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '17:43:59'], ['x' => 'Before:17:44|After:17:43:58']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '17:44:01'], ['x' => 'Before:17:44:02|After:17:44']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '17:44'], ['x' => 'Before:17:44:00']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '17:44'], ['x' => 'After:17:44:00']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '0001-01-01T00:00'], ['x' => 'before:1970-01-01']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '0001-01-01T00:00'], ['x' => 'after:1970-01-01']); $this->assertTrue($v->fails()); } public function testBeforeAndAfterWithFormat() { date_default_timezone_set('UTC'); $trans = $this->getIlluminateArrayTranslator(); $v = new Validator($trans, ['x' => '31/12/2000'], ['x' => 'before:31/02/2012']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => ['31/12/
193937
], ['x' => 'before:31/02/2012']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '31/12/2000'], ['x' => 'date_format:d/m/Y|before:31/12/2012']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '31/12/2012'], ['x' => 'after:31/12/2000']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => ['31/12/2012']], ['x' => 'after:31/12/2000']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '31/12/2012'], ['x' => 'date_format:d/m/Y|after:31/12/2000']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => '31/12/2013'], ['start' => 'after:01/01/2000', 'ends' => 'after:start']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => '31/12/2013'], ['start' => 'date_format:d/m/Y|after:31/12/2000', 'ends' => 'date_format:d/m/Y|after:start']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => '31/12/2000'], ['start' => 'after:31/12/2000', 'ends' => 'after:start']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => '31/12/2000'], ['start' => 'date_format:d/m/Y|after:31/12/2000', 'ends' => 'date_format:d/m/Y|after:start']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => '31/12/2013'], ['start' => 'before:ends', 'ends' => 'after:start']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => '31/12/2013'], ['start' => 'date_format:d/m/Y|before:ends', 'ends' => 'date_format:d/m/Y|after:start']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => '31/12/2000'], ['start' => 'before:ends', 'ends' => 'after:start']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => '31/12/2000'], ['start' => 'date_format:d/m/Y|before:ends', 'ends' => 'date_format:d/m/Y|after:start']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['start' => 'invalid', 'ends' => 'invalid'], ['start' => 'date_format:d/m/Y|before:ends', 'ends' => 'date_format:d/m/Y|after:start']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => null], ['start' => 'date_format:d/m/Y|before:ends', 'ends' => 'date_format:d/m/Y|after:start']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => null], ['start' => 'date_format:d/m/Y|before:ends', 'ends' => 'nullable|date_format:d/m/Y|after:start']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => null], ['start' => 'before:ends']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['start' => '31/12/2012', 'ends' => null], ['start' => 'before:ends', 'ends' => 'nullable']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => date('d/m/Y')], ['x' => 'date_format:d/m/Y|after:yesterday|before:tomorrow']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => date('d/m/Y')], ['x' => 'date_format:d/m/Y|after:today']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => date('d/m/Y')], ['x' => 'date_format:d/m/Y|before:today']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => date('Y-m-d')], ['x' => 'after:yesterday|before:tomorrow']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => date('Y-m-d')], ['x' => 'after:today']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => date('Y-m-d')], ['x' => 'before:today']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '2012-01-01 17:44:00'], ['x' => 'date_format:Y-m-d H:i:s|before:2012-01-01 17:44:01|after:2012-01-01 17:43:59']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '2012-01-01 17:44:00'], ['x' => 'date_format:Y-m-d H:i:s|before:2012-01-01 17:44:00']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '2012-01-01 17:44:00'], ['x' => 'date_format:Y-m-d H:i:s|after:2012-01-01 17:44:00']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '17:44:00'], ['x' => 'date_format:H:i:s|before:17:44:01|after:17:43:59']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '17:44:00'], ['x' => 'date_format:H:i:s|before:17:44:00']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '17:44:00'], ['x' => 'date_format:H:i:s|after:17:44:00']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '17:44'], ['x' => 'date_format:H:i|before:17:45|after:17:43']); $this->assertTrue($v->passes()); $v = new Validator($trans, ['x' => '17:44'], ['x' => 'date_format:H:i|before:17:44']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '17:44'], ['x' => 'date_format:H:i|after:17:44']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '2038-01-18', '2018-05-12' => '2038-01-19'], ['x' => 'date_format:Y-m-d|before:2018-05-12']); $this->assertTrue($v->fails()); $v = new Validator($trans, ['x' => '1970-01-02', '2018-05-12' => '1970-01-01'], ['x' => 'date_format:Y-m-d|after:2018-05-12']); $this->assertT
194012
class Encrypter implements EncrypterContract, StringEncrypter { /** * The encryption key. * * @var string */ protected $key; /** * The previous / legacy encryption keys. * * @var array */ protected $previousKeys = []; /** * The algorithm used for encryption. * * @var string */ protected $cipher; /** * The supported cipher algorithms and their properties. * * @var array */ private static $supportedCiphers = [ 'aes-128-cbc' => ['size' => 16, 'aead' => false], 'aes-256-cbc' => ['size' => 32, 'aead' => false], 'aes-128-gcm' => ['size' => 16, 'aead' => true], 'aes-256-gcm' => ['size' => 32, 'aead' => true], ]; /** * Create a new encrypter instance. * * @param string $key * @param string $cipher * @return void * * @throws \RuntimeException */ public function __construct($key, $cipher = 'aes-128-cbc') { $key = (string) $key; if (! static::supported($key, $cipher)) { $ciphers = implode(', ', array_keys(self::$supportedCiphers)); throw new RuntimeException("Unsupported cipher or incorrect key length. Supported ciphers are: {$ciphers}."); } $this->key = $key; $this->cipher = $cipher; } /** * Determine if the given key and cipher combination is valid. * * @param string $key * @param string $cipher * @return bool */ public static function supported($key, $cipher) { if (! isset(self::$supportedCiphers[strtolower($cipher)])) { return false; } return mb_strlen($key, '8bit') === self::$supportedCiphers[strtolower($cipher)]['size']; } /** * Create a new encryption key for the given cipher. * * @param string $cipher * @return string */ public static function generateKey($cipher) { return random_bytes(self::$supportedCiphers[strtolower($cipher)]['size'] ?? 32); } /** * Encrypt the given value. * * @param mixed $value * @param bool $serialize * @return string * * @throws \Illuminate\Contracts\Encryption\EncryptException */ public function encrypt(#[\SensitiveParameter] $value, $serialize = true) { $iv = random_bytes(openssl_cipher_iv_length(strtolower($this->cipher))); $value = \openssl_encrypt( $serialize ? serialize($value) : $value, strtolower($this->cipher), $this->key, 0, $iv, $tag ); if ($value === false) { throw new EncryptException('Could not encrypt the data.'); } $iv = base64_encode($iv); $tag = base64_encode($tag ?? ''); $mac = self::$supportedCiphers[strtolower($this->cipher)]['aead'] ? '' // For AEAD-algorithms, the tag / MAC is returned by openssl_encrypt... : $this->hash($iv, $value, $this->key); $json = json_encode(compact('iv', 'value', 'mac', 'tag'), JSON_UNESCAPED_SLASHES); if (json_last_error() !== JSON_ERROR_NONE) { throw new EncryptException('Could not encrypt the data.'); } return base64_encode($json); } /** * Encrypt a string without serialization. * * @param string $value * @return string * * @throws \Illuminate\Contracts\Encryption\EncryptException */ public function encryptString(#[\SensitiveParameter] $value) { return $this->encrypt($value, false); } /** * Decrypt the given value. * * @param string $payload * @param bool $unserialize * @return mixed * * @throws \Illuminate\Contracts\Encryption\DecryptException */ public function decrypt($payload, $unserialize = true) { $payload = $this->getJsonPayload($payload); $iv = base64_decode($payload['iv']); $this->ensureTagIsValid( $tag = empty($payload['tag']) ? null : base64_decode($payload['tag']) ); $foundValidMac = false; // Here we will decrypt the value. If we are able to successfully decrypt it // we will then unserialize it and return it out to the caller. If we are // unable to decrypt this value we will throw out an exception message. foreach ($this->getAllKeys() as $key) { if ( $this->shouldValidateMac() && ! ($foundValidMac = $foundValidMac || $this->validMacForKey($payload, $key)) ) { continue; } $decrypted = \openssl_decrypt( $payload['value'], strtolower($this->cipher), $key, 0, $iv, $tag ?? '' ); if ($decrypted !== false) { break; } } if ($this->shouldValidateMac() && ! $foundValidMac) { throw new DecryptException('The MAC is invalid.'); } if (($decrypted ?? false) === false) { throw new DecryptException('Could not decrypt the data.'); } return $unserialize ? unserialize($decrypted) : $decrypted; } /** * Decrypt the given string without unserialization. * * @param string $payload * @return string * * @throws \Illuminate\Contracts\Encryption\DecryptException */ public function decryptString($payload) { return $this->decrypt($payload, false); } /** * Create a MAC for the given value. * * @param string $iv * @param mixed $value * @param string $key * @return string */ protected function hash(#[\SensitiveParameter] $iv, #[\SensitiveParameter] $value, #[\SensitiveParameter] $key) { return hash_hmac('sha256', $iv.$value, $key); } /** * Get the JSON array from the given payload. * * @param string $payload * @return array * * @throws \Illuminate\Contracts\Encryption\DecryptException */ protected function getJsonPayload($payload) { if (! is_string($payload)) { throw new DecryptException('The payload is invalid.'); } $payload = json_decode(base64_decode($payload), true); // If the payload is not valid JSON or does not have the proper keys set we will // assume it is invalid and bail out of the routine since we will not be able // to decrypt the given value. We'll also check the MAC for this encryption. if (! $this->validPayload($payload)) { throw new DecryptException('The payload is invalid.'); } return $payload; } /** * Verify that the encryption payload is valid. * * @param mixed $payload * @return bool */ protected function validPayload($payload) { if (! is_array($payload)) { return false; } foreach (['iv', 'value', 'mac'] as $item) { if (! isset($payload[$item]) || ! is_string($payload[$item])) { return false; } } if (isset($payload['tag']) && ! is_string($payload['tag'])) { return false; } return strlen(base64_decode($payload['iv'], true)) === openssl_cipher_iv_length(strtolower($this->cipher)); } /** * Determine if the MAC for the given payload is valid for the primary key. * * @param array $payload * @return bool */ protected function validMac(array $payload) { return $this->validMacForKey($payload, $this->key); } /** * Determine if the MAC is valid for the given payload and key. * * @param array $payload * @param string $key * @return bool */ protected function validMacForKey(#[\SensitiveParameter] $payload, $key) { return hash_equals( $this->hash($payload['iv'], $payload['value'], $key), $payload['mac'] ); }
194016
public function select($query, $bindings = [], $useReadPdo = true) { return $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) { if ($this->pretending()) { return []; } // For select statements, we'll simply execute the query and return an array // of the database result set. Each element in the array will be a single // row from the database table, and will either be an array or objects. $statement = $this->prepared( $this->getPdoForSelect($useReadPdo)->prepare($query) ); $this->bindValues($statement, $this->prepareBindings($bindings)); $statement->execute(); return $statement->fetchAll(); }); } /** * Run a select statement against the database and returns all of the result sets. * * @param string $query * @param array $bindings * @param bool $useReadPdo * @return array */ public function selectResultSets($query, $bindings = [], $useReadPdo = true) { return $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) { if ($this->pretending()) { return []; } $statement = $this->prepared( $this->getPdoForSelect($useReadPdo)->prepare($query) ); $this->bindValues($statement, $this->prepareBindings($bindings)); $statement->execute(); $sets = []; do { $sets[] = $statement->fetchAll(); } while ($statement->nextRowset()); return $sets; }); } /** * Run a select statement against the database and returns a generator. * * @param string $query * @param array $bindings * @param bool $useReadPdo * @return \Generator */ public function cursor($query, $bindings = [], $useReadPdo = true) { $statement = $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) { if ($this->pretending()) { return []; } // First we will create a statement for the query. Then, we will set the fetch // mode and prepare the bindings for the query. Once that's done we will be // ready to execute the query against the database and return the cursor. $statement = $this->prepared($this->getPdoForSelect($useReadPdo) ->prepare($query)); $this->bindValues( $statement, $this->prepareBindings($bindings) ); // Next, we'll execute the query against the database and return the statement // so we can return the cursor. The cursor will use a PHP generator to give // back one row at a time without using a bunch of memory to render them. $statement->execute(); return $statement; }); while ($record = $statement->fetch()) { yield $record; } } /** * Configure the PDO prepared statement. * * @param \PDOStatement $statement * @return \PDOStatement */ protected function prepared(PDOStatement $statement) { $statement->setFetchMode($this->fetchMode); $this->event(new StatementPrepared($this, $statement)); return $statement; } /** * Get the PDO connection to use for a select query. * * @param bool $useReadPdo * @return \PDO */ protected function getPdoForSelect($useReadPdo = true) { return $useReadPdo ? $this->getReadPdo() : $this->getPdo(); } /** * Run an insert statement against the database. * * @param string $query * @param array $bindings * @return bool */ public function insert($query, $bindings = []) { return $this->statement($query, $bindings); } /** * Run an update statement against the database. * * @param string $query * @param array $bindings * @return int */ public function update($query, $bindings = []) { return $this->affectingStatement($query, $bindings); } /** * Run a delete statement against the database. * * @param string $query * @param array $bindings * @return int */ public function delete($query, $bindings = []) { return $this->affectingStatement($query, $bindings); } /** * Execute an SQL statement and return the boolean result. * * @param string $query * @param array $bindings * @return bool */ public function statement($query, $bindings = []) { return $this->run($query, $bindings, function ($query, $bindings) { if ($this->pretending()) { return true; } $statement = $this->getPdo()->prepare($query); $this->bindValues($statement, $this->prepareBindings($bindings)); $this->recordsHaveBeenModified(); return $statement->execute(); }); } /** * Run an SQL statement and get the number of rows affected. * * @param string $query * @param array $bindings * @return int */ public function affectingStatement($query, $bindings = []) { 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 = $this->getPdo()->prepare($query); $this->bindValues($statement, $this->prepareBindings($bindings)); $statement->execute(); $this->recordsHaveBeenModified( ($count = $statement->rowCount()) > 0 ); return $count; }); } /** * Run a raw, unprepared query against the PDO connection. * * @param string $query * @return bool */ public function unprepared($query) { return $this->run($query, [], function ($query) { if ($this->pretending()) { return true; } $this->recordsHaveBeenModified( $change = $this->getPdo()->exec($query) !== false ); return $change; }); } /** * Get the number of open connections for the database. * * @return int|null */ public function threadCount() { $query = $this->getQueryGrammar()->compileThreadCount(); return $query ? $this->scalar($query) : null; } /** * Execute the given callback in "dry run" mode. * * @param \Closure $callback * @return array */ public function pretend(Closure $callback) { return $this->withFreshQueryLog(function () use ($callback) { $this->pretending = true; // Basically to make the database connection "pretend", we will just return // the default values for all the query methods, then we will return an // array of queries that were "executed" within the Closure callback. $callback($this); $this->pretending = false; return $this->queryLog; }); } /** * Execute the given callback without "pretending". * * @param \Closure $callback * @return mixed */ public function withoutPretending(Closure $callback) { if (! $this->pretending) { return $callback(); } $this->pretending = false; try { return $callback(); } finally { $this->pretending = true; } } /** * Execute the given callback in "dry run" mode. * * @param \Closure $callback * @return array */
194023
class DatabaseManager implements ConnectionResolverInterface { use Macroable { __call as macroCall; } /** * The application instance. * * @var \Illuminate\Contracts\Foundation\Application */ protected $app; /** * The database connection factory instance. * * @var \Illuminate\Database\Connectors\ConnectionFactory */ protected $factory; /** * The active connection instances. * * @var array<string, \Illuminate\Database\Connection> */ protected $connections = []; /** * The custom connection resolvers. * * @var array<string, callable> */ protected $extensions = []; /** * The callback to be executed to reconnect to a database. * * @var callable */ protected $reconnector; /** * Create a new database manager instance. * * @param \Illuminate\Contracts\Foundation\Application $app * @param \Illuminate\Database\Connectors\ConnectionFactory $factory * @return void */ public function __construct($app, ConnectionFactory $factory) { $this->app = $app; $this->factory = $factory; $this->reconnector = function ($connection) { $this->reconnect($connection->getNameWithReadWriteType()); }; } /** * Get a database connection instance. * * @param string|null $name * @return \Illuminate\Database\Connection */ public function connection($name = null) { $name = $name ?: $this->getDefaultConnection(); [$database, $type] = $this->parseConnectionName($name); // If we haven't created this connection, we'll create it based on the config // provided in the application. Once we've created the connections we will // set the "fetch mode" for PDO which determines the query return types. if (! isset($this->connections[$name])) { $this->connections[$name] = $this->configure( $this->makeConnection($database), $type ); $this->dispatchConnectionEstablishedEvent($this->connections[$name]); } return $this->connections[$name]; } /** * Get a database connection instance from the given configuration. * * @param string $name * @param array $config * @param bool $force * @return \Illuminate\Database\ConnectionInterface */ public function connectUsing(string $name, array $config, bool $force = false) { if ($force) { $this->purge($name); } if (isset($this->connections[$name])) { throw new RuntimeException("Cannot establish connection [$name] because another connection with that name already exists."); } $connection = $this->configure( $this->factory->make($config, $name), null ); $this->dispatchConnectionEstablishedEvent($connection); return tap($connection, fn ($connection) => $this->connections[$name] = $connection); } /** * Parse the connection into an array of the name and read / write type. * * @param string $name * @return array */ protected function parseConnectionName($name) { $name = $name ?: $this->getDefaultConnection(); return Str::endsWith($name, ['::read', '::write']) ? explode('::', $name, 2) : [$name, null]; } /** * Make the database connection instance. * * @param string $name * @return \Illuminate\Database\Connection */ protected function makeConnection($name) { $config = $this->configuration($name); // First we will check by the connection name to see if an extension has been // registered specifically for that connection. If it has we will call the // Closure and pass it the config allowing it to resolve the connection. if (isset($this->extensions[$name])) { return call_user_func($this->extensions[$name], $config, $name); } // Next we will check to see if an extension has been registered for a driver // and will call the Closure if so, which allows us to have a more generic // resolver for the drivers themselves which applies to all connections. if (isset($this->extensions[$driver = $config['driver']])) { return call_user_func($this->extensions[$driver], $config, $name); } return $this->factory->make($config, $name); } /** * Get the configuration for a connection. * * @param string $name * @return array * * @throws \InvalidArgumentException */ protected function configuration($name) { $name = $name ?: $this->getDefaultConnection(); // To get the database connection configuration, we will just pull each of the // connection configurations and get the configurations for the given name. // If the configuration doesn't exist, we'll throw an exception and bail. $connections = $this->app['config']['database.connections']; if (is_null($config = Arr::get($connections, $name))) { throw new InvalidArgumentException("Database connection [{$name}] not configured."); } return (new ConfigurationUrlParser) ->parseConfiguration($config); } /** * Prepare the database connection instance. * * @param \Illuminate\Database\Connection $connection * @param string $type * @return \Illuminate\Database\Connection */ protected function configure(Connection $connection, $type) { $connection = $this->setPdoForType($connection, $type)->setReadWriteType($type); // First we'll set the fetch mode and a few other dependencies of the database // connection. This method basically just configures and prepares it to get // used by the application. Once we're finished we'll return it back out. if ($this->app->bound('events')) { $connection->setEventDispatcher($this->app['events']); } if ($this->app->bound('db.transactions')) { $connection->setTransactionManager($this->app['db.transactions']); } // Here we'll set a reconnector callback. This reconnector can be any callable // so we will set a Closure to reconnect from this manager with the name of // the connection, which will allow us to reconnect from the connections. $connection->setReconnector($this->reconnector); return $connection; } /** * Dispatch the ConnectionEstablished event if the event dispatcher is available. * * @param \Illuminate\Database\Connection $connection * @return void */ protected function dispatchConnectionEstablishedEvent(Connection $connection) { if (! $this->app->bound('events')) { return; } $this->app['events']->dispatch( new ConnectionEstablished($connection) ); } /** * Prepare the read / write mode for database connection instance. * * @param \Illuminate\Database\Connection $connection * @param string|null $type * @return \Illuminate\Database\Connection */ protected function setPdoForType(Connection $connection, $type = null) { if ($type === 'read') { $connection->setPdo($connection->getReadPdo()); } elseif ($type === 'write') { $connection->setReadPdo($connection->getPdo()); } return $connection; } /** * Disconnect from the given database and remove from local cache. * * @param string|null $name * @return void */ public function purge($name = null) { $name = $name ?: $this->getDefaultConnection(); $this->disconnect($name); unset($this->connections[$name]); } /** * Disconnect from the given database. * * @param string|null $name * @return void */ public function disconnect($name = null) { if (isset($this->connections[$name = $name ?: $this->getDefaultConnection()])) { $this->connections[$name]->disconnect(); } } /** * Reconnect to the given database. * * @param string|null $name * @return \Illuminate\Database\Connection */ public function reconnect($name = null) { $this->disconnect($name = $name ?: $this->getDefaultConnection()); if (! isset($this->connections[$name])) { return $this->connection($name); } return $this->refreshPdoConnections($name); }
194025
<?php namespace Illuminate\Database; use Closure; interface ConnectionInterface { /** * Begin a fluent query against a database table. * * @param \Closure|\Illuminate\Database\Query\Builder|string $table * @param string|null $as * @return \Illuminate\Database\Query\Builder */ public function table($table, $as = null); /** * Get a new raw query expression. * * @param mixed $value * @return \Illuminate\Contracts\Database\Query\Expression */ public function raw($value); /** * Run a select statement and return a single result. * * @param string $query * @param array $bindings * @param bool $useReadPdo * @return mixed */ public function selectOne($query, $bindings = [], $useReadPdo = true); /** * Run a select statement and return the first column of the first row. * * @param string $query * @param array $bindings * @param bool $useReadPdo * @return mixed * * @throws \Illuminate\Database\MultipleColumnsSelectedException */ public function scalar($query, $bindings = [], $useReadPdo = true); /** * Run a select statement against the database. * * @param string $query * @param array $bindings * @param bool $useReadPdo * @return array */ public function select($query, $bindings = [], $useReadPdo = true); /** * Run a select statement against the database and returns a generator. * * @param string $query * @param array $bindings * @param bool $useReadPdo * @return \Generator */ public function cursor($query, $bindings = [], $useReadPdo = true); /** * Run an insert statement against the database. * * @param string $query * @param array $bindings * @return bool */ public function insert($query, $bindings = []); /** * Run an update statement against the database. * * @param string $query * @param array $bindings * @return int */ public function update($query, $bindings = []); /** * Run a delete statement against the database. * * @param string $query * @param array $bindings * @return int */ public function delete($query, $bindings = []); /** * Execute an SQL statement and return the boolean result. * * @param string $query * @param array $bindings * @return bool */ public function statement($query, $bindings = []); /** * Run an SQL statement and get the number of rows affected. * * @param string $query * @param array $bindings * @return int */ public function affectingStatement($query, $bindings = []); /** * Run a raw, unprepared query against the PDO connection. * * @param string $query * @return bool */ public function unprepared($query); /** * Prepare the query bindings for execution. * * @param array $bindings * @return array */ public function prepareBindings(array $bindings); /** * Execute a Closure within a transaction. * * @param \Closure $callback * @param int $attempts * @return mixed * * @throws \Throwable */ public function transaction(Closure $callback, $attempts = 1); /** * Start a new database transaction. * * @return void */ public function beginTransaction(); /** * Commit the active database transaction. * * @return void */ public function commit(); /** * Rollback the active database transaction. * * @return void */ public function rollBack(); /** * Get the number of active transactions. * * @return int */ public function transactionLevel(); /** * Execute the given callback in "dry run" mode. * * @param \Closure $callback * @return array */ public function pretend(Closure $callback); /** * Get the name of the connected database. * * @return string */ public function getDatabaseName(); }
194061
<?php namespace Illuminate\Database\Migrations; use Illuminate\Console\View\Components\BulletList; use Illuminate\Console\View\Components\Info; use Illuminate\Console\View\Components\Task; use Illuminate\Console\View\Components\TwoColumnDetail; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Database\ConnectionResolverInterface as Resolver; use Illuminate\Database\Events\MigrationEnded; use Illuminate\Database\Events\MigrationsEnded; use Illuminate\Database\Events\MigrationsStarted; use Illuminate\Database\Events\MigrationStarted; use Illuminate\Database\Events\NoPendingMigrations; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Illuminate\Support\Str; use ReflectionClass; use Symfony\Component\Console\Output\OutputInterface; class Migrator { /** * The event dispatcher instance. * * @var \Illuminate\Contracts\Events\Dispatcher */ protected $events; /** * The migration repository implementation. * * @var \Illuminate\Database\Migrations\MigrationRepositoryInterface */ protected $repository; /** * The filesystem instance. * * @var \Illuminate\Filesystem\Filesystem */ protected $files; /** * The connection resolver instance. * * @var \Illuminate\Database\ConnectionResolverInterface */ protected $resolver; /** * The name of the default connection. * * @var string */ protected $connection; /** * The paths to all of the migration files. * * @var string[] */ protected $paths = []; /** * The paths that have already been required. * * @var array<string, \Illuminate\Database\Migrations\Migration|null> */ protected static $requiredPathCache = []; /** * The output interface implementation. * * @var \Symfony\Component\Console\Output\OutputInterface */ protected $output; /** * Create a new migrator instance. * * @param \Illuminate\Database\Migrations\MigrationRepositoryInterface $repository * @param \Illuminate\Database\ConnectionResolverInterface $resolver * @param \Illuminate\Filesystem\Filesystem $files * @param \Illuminate\Contracts\Events\Dispatcher|null $dispatcher * @return void */ public function __construct(MigrationRepositoryInterface $repository, Resolver $resolver, Filesystem $files, ?Dispatcher $dispatcher = null) { $this->files = $files; $this->events = $dispatcher; $this->resolver = $resolver; $this->repository = $repository; } /** * Run the pending migrations at a given path. * * @param string[]|string $paths * @param array<string, mixed> $options * @return string[] */ public function run($paths = [], array $options = []) { // Once we grab all of the migration files for the path, we will compare them // against the migrations that have already been run for this package then // run each of the outstanding migrations against a database connection. $files = $this->getMigrationFiles($paths); $this->requireFiles($migrations = $this->pendingMigrations( $files, $this->repository->getRan() )); // Once we have all these migrations that are outstanding we are ready to run // we will go ahead and run them "up". This will execute each migration as // an operation against a database. Then we'll return this list of them. $this->runPending($migrations, $options); return $migrations; } /** * Get the migration files that have not yet run. * * @param string[] $files * @param string[] $ran * @return string[] */ protected function pendingMigrations($files, $ran) { return Collection::make($files) ->reject(fn ($file) => in_array($this->getMigrationName($file), $ran)) ->values() ->all(); } /** * Run an array of migrations. * * @param string[] $migrations * @param array<string, mixed> $options * @return void */ public function runPending(array $migrations, array $options = []) { // First we will just make sure that there are any migrations to run. If there // aren't, we will just make a note of it to the developer so they're aware // that all of the migrations have been run against this database system. if (count($migrations) === 0) { $this->fireMigrationEvent(new NoPendingMigrations('up')); $this->write(Info::class, 'Nothing to migrate'); return; } // Next, we will get the next batch number for the migrations so we can insert // correct batch number in the database migrations repository when we store // each migration's execution. We will also extract a few of the options. $batch = $this->repository->getNextBatchNumber(); $pretend = $options['pretend'] ?? false; $step = $options['step'] ?? false; $this->fireMigrationEvent(new MigrationsStarted('up')); $this->write(Info::class, 'Running migrations.'); // Once we have the array of migrations, we will spin through them and run the // migrations "up" so the changes are made to the databases. We'll then log // that the migration was run so we don't repeat it next time we execute. foreach ($migrations as $file) { $this->runUp($file, $batch, $pretend); if ($step) { $batch++; } } $this->fireMigrationEvent(new MigrationsEnded('up')); $this->output?->writeln(''); } /** * Run "up" a migration instance. * * @param string $file * @param int $batch * @param bool $pretend * @return void */ protected function runUp($file, $batch, $pretend) { // First we will resolve a "real" instance of the migration class from this // migration file name. Once we have the instances we can run the actual // command such as "up" or "down", or we can just simulate the action. $migration = $this->resolvePath($file); $name = $this->getMigrationName($file); if ($pretend) { return $this->pretendToRun($migration, 'up'); } $this->write(Task::class, $name, fn () => $this->runMigration($migration, 'up')); // Once we have run a migrations class, we will log that it was run in this // repository so that we don't try to run it next time we do a migration // in the application. A migration repository keeps the migrate order. $this->repository->log($name, $batch); } /** * Rollback the last migration operation. * * @param string[]|string $paths * @param array<string, mixed> $options * @return string[] */ public function rollback($paths = [], array $options = []) { // We want to pull in the last batch of migrations that ran on the previous // migration operation. We'll then reverse those migrations and run each // of them "down" to reverse the last migration "operation" which ran. $migrations = $this->getMigrationsForRollback($options); if (count($migrations) === 0) { $this->fireMigrationEvent(new NoPendingMigrations('down')); $this->write(Info::class, 'Nothing to rollback.'); return []; } return tap($this->rollbackMigrations($migrations, $paths, $options), function () { $this->output?->writeln(''); }); } /** * Get the migrations for a rollback operation. * * @param array<string, mixed> $options * @return array */ protected function getMigrationsForRollback(array $options) { if (($steps = $options['step'] ?? 0) > 0) { return $this->repository->getMigrations($steps); } if (($batch = $options['batch'] ?? 0) > 0) { return $this->repository->getMigrationsByBatch($batch); } return $this->repository->getLast(); } /** * Rollback the given migrations. * * @param array $migrations * @param string[]|string $paths * @param array<string, mixed> $options * @return string[] */
194062
protected function rollbackMigrations(array $migrations, $paths, array $options) { $rolledBack = []; $this->requireFiles($files = $this->getMigrationFiles($paths)); $this->fireMigrationEvent(new MigrationsStarted('down')); $this->write(Info::class, 'Rolling back migrations.'); // Next we will run through all of the migrations and call the "down" method // which will reverse each migration in order. This getLast method on the // repository already returns these migration's names in reverse order. foreach ($migrations as $migration) { $migration = (object) $migration; if (! $file = Arr::get($files, $migration->migration)) { $this->write(TwoColumnDetail::class, $migration->migration, '<fg=yellow;options=bold>Migration not found</>'); continue; } $rolledBack[] = $file; $this->runDown( $file, $migration, $options['pretend'] ?? false ); } $this->fireMigrationEvent(new MigrationsEnded('down')); return $rolledBack; } /** * Rolls all of the currently applied migrations back. * * @param string[]|string $paths * @param bool $pretend * @return array */ public function reset($paths = [], $pretend = false) { // Next, we will reverse the migration list so we can run them back in the // correct order for resetting this database. This will allow us to get // the database back into its "empty" state ready for the migrations. $migrations = array_reverse($this->repository->getRan()); if (count($migrations) === 0) { $this->write(Info::class, 'Nothing to rollback.'); return []; } return tap($this->resetMigrations($migrations, Arr::wrap($paths), $pretend), function () { $this->output?->writeln(''); }); } /** * Reset the given migrations. * * @param string[] $migrations * @param string[] $paths * @param bool $pretend * @return array */ protected function resetMigrations(array $migrations, array $paths, $pretend = false) { // Since the getRan method that retrieves the migration name just gives us the // migration name, we will format the names into objects with the name as a // property on the objects so that we can pass it to the rollback method. $migrations = collect($migrations)->map(fn ($m) => (object) ['migration' => $m])->all(); return $this->rollbackMigrations( $migrations, $paths, compact('pretend') ); } /** * Run "down" a migration instance. * * @param string $file * @param object $migration * @param bool $pretend * @return void */ protected function runDown($file, $migration, $pretend) { // First we will get the file name of the migration so we can resolve out an // instance of the migration. Once we get an instance we can either run a // pretend execution of the migration or we can run the real migration. $instance = $this->resolvePath($file); $name = $this->getMigrationName($file); if ($pretend) { return $this->pretendToRun($instance, 'down'); } $this->write(Task::class, $name, fn () => $this->runMigration($instance, 'down')); // Once we have successfully run the migration "down" we will remove it from // the migration repository so it will be considered to have not been run // by the application then will be able to fire by any later operation. $this->repository->delete($migration); } /** * Run a migration inside a transaction if the database supports it. * * @param object $migration * @param string $method * @return void */ protected function runMigration($migration, $method) { $connection = $this->resolveConnection( $migration->getConnection() ); $callback = function () use ($connection, $migration, $method) { if (method_exists($migration, $method)) { $this->fireMigrationEvent(new MigrationStarted($migration, $method)); $this->runMethod($connection, $migration, $method); $this->fireMigrationEvent(new MigrationEnded($migration, $method)); } }; $this->getSchemaGrammar($connection)->supportsSchemaTransactions() && $migration->withinTransaction ? $connection->transaction($callback) : $callback(); } /** * Pretend to run the migrations. * * @param object $migration * @param string $method * @return void */ protected function pretendToRun($migration, $method) { $name = get_class($migration); $reflectionClass = new ReflectionClass($migration); if ($reflectionClass->isAnonymous()) { $name = $this->getMigrationName($reflectionClass->getFileName()); } $this->write(TwoColumnDetail::class, $name); $this->write( BulletList::class, collect($this->getQueries($migration, $method))->map(fn ($query) => $query['query']) ); } /** * Get all of the queries that would be run for a migration. * * @param object $migration * @param string $method * @return array */ protected function getQueries($migration, $method) { // Now that we have the connections we can resolve it and pretend to run the // queries against the database returning the array of raw SQL statements // that would get fired against the database system for this migration. $db = $this->resolveConnection( $migration->getConnection() ); return $db->pretend(function () use ($db, $migration, $method) { if (method_exists($migration, $method)) { $this->runMethod($db, $migration, $method); } }); } /** * Run a migration method on the given connection. * * @param \Illuminate\Database\Connection $connection * @param object $migration * @param string $method * @return void */ protected function runMethod($connection, $migration, $method) { $previousConnection = $this->resolver->getDefaultConnection(); try { $this->resolver->setDefaultConnection($connection->getName()); $migration->{$method}(); } finally { $this->resolver->setDefaultConnection($previousConnection); } } /** * Resolve a migration instance from a file. * * @param string $file * @return object */ public function resolve($file) { $class = $this->getMigrationClass($file); return new $class; } /** * Resolve a migration instance from a migration path. * * @param string $path * @return object */ protected function resolvePath(string $path) { $class = $this->getMigrationClass($this->getMigrationName($path)); if (class_exists($class) && realpath($path) == (new ReflectionClass($class))->getFileName()) { return new $class; } $migration = static::$requiredPathCache[$path] ??= $this->files->getRequire($path); if (is_object($migration)) { return method_exists($migration, '__construct') ? $this->files->getRequire($path) : clone $migration; } return new $class; } /** * Generate a migration class name based on the migration file name. * * @param string $migrationName * @return string */ protected function getMigrationClass(string $migrationName): string { return Str::studly(implode('_', array_slice(explode('_', $migrationName), 4))); } /** * Get all of the migration files in a given path. * * @param string|array $paths * @return array<string, string> */
194067
<?php namespace Illuminate\Database\Migrations; abstract class Migration { /** * The name of the database connection to use. * * @var string|null */ protected $connection; /** * Enables, if supported, wrapping the migration within a transaction. * * @var bool */ public $withinTransaction = true; /** * Get the migration connection name. * * @return string|null */ public function getConnection() { return $this->connection; } }
194068
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { // } /** * Reverse the migrations. */ public function down(): void { // } };
194073
<?php namespace Illuminate\Database\Eloquent; use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Support\Collection as BaseCollection; /** * @method static \Illuminate\Database\Eloquent\Builder<static> withTrashed(bool $withTrashed = true) * @method static \Illuminate\Database\Eloquent\Builder<static> onlyTrashed() * @method static \Illuminate\Database\Eloquent\Builder<static> withoutTrashed() * @method static static restoreOrCreate(array<string, mixed> $attributes = [], array<string, mixed> $values = []) * @method static static createOrRestore(array<string, mixed> $attributes = [], array<string, mixed> $values = []) * * @mixin \Illuminate\Database\Eloquent\Model */ trait SoftDeletes { /** * Indicates if the model is currently force deleting. * * @var bool */ protected $forceDeleting = false; /** * Boot the soft deleting trait for a model. * * @return void */ public static function bootSoftDeletes() { static::addGlobalScope(new SoftDeletingScope); } /** * Initialize the soft deleting trait for an instance. * * @return void */ public function initializeSoftDeletes() { if (! isset($this->casts[$this->getDeletedAtColumn()])) { $this->casts[$this->getDeletedAtColumn()] = 'datetime'; } } /** * Force a hard delete on a soft deleted model. * * @return bool|null */ public function forceDelete() { if ($this->fireModelEvent('forceDeleting') === false) { return false; } $this->forceDeleting = true; return tap($this->delete(), function ($deleted) { $this->forceDeleting = false; if ($deleted) { $this->fireModelEvent('forceDeleted', false); } }); } /** * Force a hard delete on a soft deleted model without raising any events. * * @return bool|null */ public function forceDeleteQuietly() { return static::withoutEvents(fn () => $this->forceDelete()); } /** * Destroy the models for the given IDs. * * @param \Illuminate\Support\Collection|array|int|string $ids * @return int */ public static function forceDestroy($ids) { if ($ids instanceof EloquentCollection) { $ids = $ids->modelKeys(); } if ($ids instanceof BaseCollection) { $ids = $ids->all(); } $ids = is_array($ids) ? $ids : func_get_args(); if (count($ids) === 0) { return 0; } // We will actually pull the models from the database table and call delete on // each of them individually so that their events get fired properly with a // correct set of attributes in case the developers wants to check these. $key = ($instance = new static)->getKeyName(); $count = 0; foreach ($instance->withTrashed()->whereIn($key, $ids)->get() as $model) { if ($model->forceDelete()) { $count++; } } return $count; } /** * Perform the actual delete query on this model instance. * * @return mixed */ protected function performDeleteOnModel() { if ($this->forceDeleting) { return tap($this->setKeysForSaveQuery($this->newModelQuery())->forceDelete(), function () { $this->exists = false; }); } return $this->runSoftDelete(); } /** * Perform the actual delete query on this model instance. * * @return void */ protected function runSoftDelete() { $query = $this->setKeysForSaveQuery($this->newModelQuery()); $time = $this->freshTimestamp(); $columns = [$this->getDeletedAtColumn() => $this->fromDateTime($time)]; $this->{$this->getDeletedAtColumn()} = $time; if ($this->usesTimestamps() && ! is_null($this->getUpdatedAtColumn())) { $this->{$this->getUpdatedAtColumn()} = $time; $columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time); } $query->update($columns); $this->syncOriginalAttributes(array_keys($columns)); $this->fireModelEvent('trashed', false); } /** * Restore a soft-deleted model instance. * * @return bool */ public function restore() { // If the restoring event does not return false, we will proceed with this // restore operation. Otherwise, we bail out so the developer will stop // the restore totally. We will clear the deleted timestamp and save. if ($this->fireModelEvent('restoring') === false) { return false; } $this->{$this->getDeletedAtColumn()} = null; // Once we have saved the model, we will fire the "restored" event so this // developer will do anything they need to after a restore operation is // totally finished. Then we will return the result of the save call. $this->exists = true; $result = $this->save(); $this->fireModelEvent('restored', false); return $result; } /** * Restore a soft-deleted model instance without raising any events. * * @return bool */ public function restoreQuietly() { return static::withoutEvents(fn () => $this->restore()); } /** * Determine if the model instance has been soft-deleted. * * @return bool */ public function trashed() { return ! is_null($this->{$this->getDeletedAtColumn()}); } /** * Register a "softDeleted" model event callback with the dispatcher. * * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback * @return void */ public static function softDeleted($callback) { static::registerModelEvent('trashed', $callback); } /** * Register a "restoring" model event callback with the dispatcher. * * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback * @return void */ public static function restoring($callback) { static::registerModelEvent('restoring', $callback); } /** * Register a "restored" model event callback with the dispatcher. * * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback * @return void */ public static function restored($callback) { static::registerModelEvent('restored', $callback); } /** * Register a "forceDeleting" model event callback with the dispatcher. * * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback * @return void */ public static function forceDeleting($callback) { static::registerModelEvent('forceDeleting', $callback); } /** * Register a "forceDeleted" model event callback with the dispatcher. * * @param \Illuminate\Events\QueuedClosure|\Closure|string $callback * @return void */ public static function forceDeleted($callback) { static::registerModelEvent('forceDeleted', $callback); } /** * Determine if the model is currently force deleting. * * @return bool */ public function isForceDeleting() { return $this->forceDeleting; } /** * Get the name of the "deleted at" column. * * @return string */ public function getDeletedAtColumn() { return defined(static::class.'::DELETED_AT') ? static::DELETED_AT : 'deleted_at'; } /** * Get the fully qualified "deleted at" column. * * @return string */ public function getQualifiedDeletedAtColumn() { return $this->qualifyColumn($this->getDeletedAtColumn()); } }
194082
/** * Execute the query and get the first result or throw an exception. * * @param array|string $columns * @return TModel * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<TModel> */ public function firstOrFail($columns = ['*']) { if (! is_null($model = $this->first($columns))) { return $model; } throw (new ModelNotFoundException)->setModel(get_class($this->model)); } /** * Execute the query and get the first result or call a callback. * * @template TValue * * @param (\Closure(): TValue)|list<string> $columns * @param (\Closure(): TValue)|null $callback * @return TModel|TValue */ public function firstOr($columns = ['*'], ?Closure $callback = null) { if ($columns instanceof Closure) { $callback = $columns; $columns = ['*']; } if (! is_null($model = $this->first($columns))) { return $model; } return $callback(); } /** * Execute the query and get the first result if it's the sole matching record. * * @param array|string $columns * @return TModel * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<TModel> * @throws \Illuminate\Database\MultipleRecordsFoundException */ public function sole($columns = ['*']) { try { return $this->baseSole($columns); } catch (RecordsNotFoundException) { throw (new ModelNotFoundException)->setModel(get_class($this->model)); } } /** * Get a single column's value from the first result of a query. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @return mixed */ public function value($column) { if ($result = $this->first([$column])) { $column = $column instanceof Expression ? $column->getValue($this->getGrammar()) : $column; return $result->{Str::afterLast($column, '.')}; } } /** * Get a single column's value from the first result of a query if it's the sole matching record. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @return mixed * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<TModel> * @throws \Illuminate\Database\MultipleRecordsFoundException */ public function soleValue($column) { $column = $column instanceof Expression ? $column->getValue($this->getGrammar()) : $column; return $this->sole([$column])->{Str::afterLast($column, '.')}; } /** * Get a single column's value from the first result of the query or throw an exception. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @return mixed * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<TModel> */ public function valueOrFail($column) { $column = $column instanceof Expression ? $column->getValue($this->getGrammar()) : $column; return $this->firstOrFail([$column])->{Str::afterLast($column, '.')}; } /** * Execute the query as a "select" statement. * * @param array|string $columns * @return \Illuminate\Database\Eloquent\Collection<int, TModel> */ public function get($columns = ['*']) { $builder = $this->applyScopes(); // If we actually found models we will also eager load any relationships that // have been specified as needing to be eager loaded, which will solve the // n+1 query issue for the developers to avoid running a lot of queries. if (count($models = $builder->getModels($columns)) > 0) { $models = $builder->eagerLoadRelations($models); } return $this->applyAfterQueryCallbacks( $builder->getModel()->newCollection($models) ); } /** * Get the hydrated models without eager loading. * * @param array|string $columns * @return array<int, TModel> */ public function getModels($columns = ['*']) { return $this->model->hydrate( $this->query->get($columns)->all() )->all(); } /** * Eager load the relationships for the models. * * @param array<int, TModel> $models * @return array<int, TModel> */ public function eagerLoadRelations(array $models) { foreach ($this->eagerLoad as $name => $constraints) { // For nested eager loads we'll skip loading them here and they will be set as an // eager load on the query to retrieve the relation so that they will be eager // loaded on that query, because that is where they get hydrated as models. if (! str_contains($name, '.')) { $models = $this->eagerLoadRelation($models, $name, $constraints); } } return $models; } /** * Eagerly load the relationship on a set of models. * * @param array $models * @param string $name * @param \Closure $constraints * @return array */ protected function eagerLoadRelation(array $models, $name, Closure $constraints) { // First we will "back up" the existing where conditions on the query so we can // add our eager constraints. Then we will merge the wheres that were on the // query back to it in order that any where conditions might be specified. $relation = $this->getRelation($name); $relation->addEagerConstraints($models); $constraints($relation); // Once we have the results, we just match those back up to their parent models // using the relationship instance. Then we just return the finished arrays // of models which have been eagerly hydrated and are readied for return. return $relation->match( $relation->initRelation($models, $name), $relation->getEager(), $name ); } /** * Get the relation instance for the given relation name. * * @param string $name * @return \Illuminate\Database\Eloquent\Relations\Relation<\Illuminate\Database\Eloquent\Model, TModel, *> */ public function getRelation($name) { // We want to run a relationship query without any constrains so that we will // not have to remove these where clauses manually which gets really hacky // and error prone. We don't want constraints because we add eager ones. $relation = Relation::noConstraints(function () use ($name) { try { return $this->getModel()->newInstance()->$name(); } catch (BadMethodCallException) { throw RelationNotFoundException::make($this->getModel(), $name); } }); $nested = $this->relationsNestedUnder($name); // If there are nested relationships set on the query, we will put those onto // the query instances so that they can be handled after this relationship // is loaded. In this way they will all trickle down as they are loaded. if (count($nested) > 0) { $relation->getQuery()->with($nested); } return $relation; } /** * Get the deeply nested relations for a given top-level relation. * * @param string $relation * @return array */ protected function relationsNestedUnder($relation) { $nested = []; // We are basically looking for any relationships that are nested deeper than // the given top-level relationship. We will just check for any relations // that start with the given top relations and adds them to our arrays. foreach ($this->eagerLoad as $name => $constraints) { if ($this->isNestedUnder($relation, $name)) { $nested[substr($name, strlen($relation.'.'))] = $constraints; } } return $nested; } /** * Determine if the relationship is nested. * * @param string $relation * @param string $name * @return bool */ protected function isNestedUnder($relation, $name) { return str_contains($name, '.') && str_starts_with($name, $relation.'.'); } /** * Register a closure to be invoked after the query is executed. * * @param \Closure $callback * @return $this */
194085
/** * Apply the given scope on the current builder instance. * * @param callable $scope * @param array $parameters * @return mixed */ protected function callScope(callable $scope, array $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 = is_null($query->wheres) ? 0 : count($query->wheres); $result = $scope(...$parameters) ?? $this; if (count((array) $query->wheres) > $originalWhereCount) { $this->addNewWheresWithinGroup($query, $originalWhereCount); } return $result; } /** * Apply the given named scope on the current builder instance. * * @param string $scope * @param array $parameters * @return mixed */ protected function callNamedScope($scope, array $parameters = []) { return $this->callScope(function (...$parameters) use ($scope) { return $this->model->callNamedScope($scope, $parameters); }, $parameters); } /** * Nest where conditions by slicing them at the given where count. * * @param \Illuminate\Database\Query\Builder $query * @param int $originalWhereCount * @return void */ 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 // their own sections. This is to prevent any confusing logic order. $allWheres = $query->wheres; $query->wheres = []; $this->groupWhereSliceForScope( $query, array_slice($allWheres, 0, $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 $whereSlice * @return void */ protected function groupWhereSliceForScope(QueryBuilder $query, $whereSlice) { $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(fn ($logicalOperator) => str_contains($logicalOperator, 'or'))) { $query->wheres[] = $this->createNestedWhere( $whereSlice, str_replace(' not', '', $whereBooleans->first()) ); } else { $query->wheres = array_merge($query->wheres, $whereSlice); } } /** * Create a where array with nested where conditions. * * @param array $whereSlice * @param string $boolean * @return array */ protected function createNestedWhere($whereSlice, $boolean = 'and') { $whereGroup = $this->getQuery()->forNestedWhere(); $whereGroup->wheres = $whereSlice; return ['type' => 'Nested', 'query' => $whereGroup, 'boolean' => $boolean]; } /** * Set the relationships that should be eager loaded. * * @param array<array-key, array|(\Closure(\Illuminate\Database\Eloquent\Relations\Relation<*,*,*>): mixed)|string>|string $relations * @param (\Closure(\Illuminate\Database\Eloquent\Relations\Relation<*,*,*>): mixed)|string|null $callback * @return $this */ public function with($relations, $callback = null) { if ($callback instanceof Closure) { $eagerLoad = $this->parseWithRelations([$relations => $callback]); } else { $eagerLoad = $this->parseWithRelations(is_string($relations) ? func_get_args() : $relations); } $this->eagerLoad = array_merge($this->eagerLoad, $eagerLoad); return $this; } /** * Prevent the specified relations from being eager loaded. * * @param mixed $relations * @return $this */ public function without($relations) { $this->eagerLoad = array_diff_key($this->eagerLoad, array_flip( is_string($relations) ? func_get_args() : $relations )); return $this; } /** * Set the relationships that should be eager loaded while removing any previously added eager loading specifications. * * @param array<array-key, array|(\Closure(\Illuminate\Database\Eloquent\Relations\Relation<*,*,*>): mixed)|string>|string $relations * @return $this */ public function withOnly($relations) { $this->eagerLoad = []; return $this->with($relations); } /** * Create a new instance of the model being queried. * * @param array $attributes * @return TModel */ public function newModelInstance($attributes = []) { return $this->model->newInstance($attributes)->setConnection( $this->query->getConnection()->getName() ); } /** * Parse a list of relations into individuals. * * @param array $relations * @return array */ protected function parseWithRelations(array $relations) { if ($relations === []) { return []; } $results = []; foreach ($this->prepareNestedWithRelationships($relations) as $name => $constraints) { // We need to separate out any nested includes, which allows the developers // to load deep relationships using "dots" without stating each level of // the relationship with its own key in the array of eager-load names. $results = $this->addNestedWiths($name, $results); $results[$name] = $constraints; } return $results; } /** * Prepare nested with relationships. * * @param array $relations * @param string $prefix * @return array */ protected function prepareNestedWithRelationships($relations, $prefix = '') { $preparedRelationships = []; if ($prefix !== '') { $prefix .= '.'; } // If any of the relationships are formatted with the [$attribute => array()] // syntax, we shall loop over the nested relations and prepend each key of // this array while flattening into the traditional dot notation format. foreach ($relations as $key => $value) { if (! is_string($key) || ! is_array($value)) { continue; } [$attribute, $attributeSelectConstraint] = $this->parseNameAndAttributeSelectionConstraint($key); $preparedRelationships = array_merge( $preparedRelationships, ["{$prefix}{$attribute}" => $attributeSelectConstraint], $this->prepareNestedWithRelationships($value, "{$prefix}{$attribute}"), ); unset($relations[$key]); } // We now know that the remaining relationships are in a dot notation format // and may be a string or Closure. We'll loop over them and ensure all of // the present Closures are merged + strings are made into constraints. foreach ($relations as $key => $value) { if (is_numeric($key) && is_string($value)) { [$key, $value] = $this->parseNameAndAttributeSelectionConstraint($value); } $preparedRelationships[$prefix.$key] = $this->combineConstraints([ $value, $preparedRelationships[$prefix.$key] ?? static function () { // }, ]); } return $preparedRelationships; } /** * Combine an array of constraints into a single constraint. * * @param array $constraints * @return \Closure */ protected function combineConstraints(array $constraints) { return function ($builder) use ($constraints) { foreach ($constraints as $constraint) { $builder = $constraint($builder) ?? $builder; } return $builder; }; }
194088
<?php namespace Illuminate\Database\Eloquent; interface Scope { /** * Apply the scope to a given Eloquent query builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @param \Illuminate\Database\Eloquent\Model $model * @return void */ public function apply(Builder $builder, Model $model); }
194091
public static function isIgnoringTouch($class = null) { $class = $class ?: static::class; if (! get_class_vars($class)['timestamps'] || ! $class::UPDATED_AT) { return true; } foreach (static::$ignoreOnTouch as $ignoredClass) { if ($class === $ignoredClass || is_subclass_of($class, $ignoredClass)) { return true; } } return false; } /** * Indicate that models should prevent lazy loading, silently discarding attributes, and accessing missing attributes. * * @param bool $shouldBeStrict * @return void */ public static function shouldBeStrict(bool $shouldBeStrict = true) { static::preventLazyLoading($shouldBeStrict); static::preventSilentlyDiscardingAttributes($shouldBeStrict); static::preventAccessingMissingAttributes($shouldBeStrict); } /** * Prevent model relationships from being lazy loaded. * * @param bool $value * @return void */ public static function preventLazyLoading($value = true) { static::$modelsShouldPreventLazyLoading = $value; } /** * Register a callback that is responsible for handling lazy loading violations. * * @param callable|null $callback * @return void */ public static function handleLazyLoadingViolationUsing(?callable $callback) { static::$lazyLoadingViolationCallback = $callback; } /** * Prevent non-fillable attributes from being silently discarded. * * @param bool $value * @return void */ public static function preventSilentlyDiscardingAttributes($value = true) { static::$modelsShouldPreventSilentlyDiscardingAttributes = $value; } /** * Register a callback that is responsible for handling discarded attribute violations. * * @param callable|null $callback * @return void */ public static function handleDiscardedAttributeViolationUsing(?callable $callback) { static::$discardedAttributeViolationCallback = $callback; } /** * Prevent accessing missing attributes on retrieved models. * * @param bool $value * @return void */ public static function preventAccessingMissingAttributes($value = true) { static::$modelsShouldPreventAccessingMissingAttributes = $value; } /** * Register a callback that is responsible for handling missing attribute violations. * * @param callable|null $callback * @return void */ public static function handleMissingAttributeViolationUsing(?callable $callback) { static::$missingAttributeViolationCallback = $callback; } /** * Execute a callback without broadcasting any model events for all model types. * * @param callable $callback * @return mixed */ public static function withoutBroadcasting(callable $callback) { $isBroadcasting = static::$isBroadcasting; static::$isBroadcasting = false; try { return $callback(); } finally { static::$isBroadcasting = $isBroadcasting; } } /** * Fill the model with an array of attributes. * * @param array $attributes * @return $this * * @throws \Illuminate\Database\Eloquent\MassAssignmentException */ public function fill(array $attributes) { $totallyGuarded = $this->totallyGuarded(); $fillable = $this->fillableFromArray($attributes); foreach ($fillable as $key => $value) { // The developers may choose to place some attributes in the "fillable" array // which means only those attributes may be set through mass assignment to // the model, and all others will just get ignored for security reasons. if ($this->isFillable($key)) { $this->setAttribute($key, $value); } elseif ($totallyGuarded || static::preventsSilentlyDiscardingAttributes()) { if (isset(static::$discardedAttributeViolationCallback)) { call_user_func(static::$discardedAttributeViolationCallback, $this, [$key]); } else { throw new MassAssignmentException(sprintf( 'Add [%s] to fillable property to allow mass assignment on [%s].', $key, get_class($this) )); } } } if (count($attributes) !== count($fillable) && static::preventsSilentlyDiscardingAttributes()) { $keys = array_diff(array_keys($attributes), array_keys($fillable)); if (isset(static::$discardedAttributeViolationCallback)) { call_user_func(static::$discardedAttributeViolationCallback, $this, $keys); } else { throw new MassAssignmentException(sprintf( 'Add fillable property [%s] to allow mass assignment on [%s].', implode(', ', $keys), get_class($this) )); } } return $this; } /** * Fill the model with an array of attributes. Force mass assignment. * * @param array $attributes * @return $this */ public function forceFill(array $attributes) { return static::unguarded(fn () => $this->fill($attributes)); } /** * Qualify the given column name by the model's table. * * @param string $column * @return string */ public function qualifyColumn($column) { if (str_contains($column, '.')) { return $column; } return $this->getTable().'.'.$column; } /** * Qualify the given columns with the model's table. * * @param array $columns * @return array */ public function qualifyColumns($columns) { return collect($columns)->map(function ($column) { return $this->qualifyColumn($column); })->all(); } /** * Create a new instance of the given model. * * @param array $attributes * @param bool $exists * @return static */ public function newInstance($attributes = [], $exists = false) { // This method just provides a convenient way for us to generate fresh model // instances of this current model. It is particularly useful during the // hydration of new objects via the Eloquent query builder instances. $model = new static; $model->exists = $exists; $model->setConnection( $this->getConnectionName() ); $model->setTable($this->getTable()); $model->mergeCasts($this->casts); $model->fill((array) $attributes); return $model; } /** * Create a new model instance that is existing. * * @param array $attributes * @param string|null $connection * @return static */ public function newFromBuilder($attributes = [], $connection = null) { $model = $this->newInstance([], true); $model->setRawAttributes((array) $attributes, true); $model->setConnection($connection ?: $this->getConnectionName()); $model->fireModelEvent('retrieved', false); return $model; } /** * Begin querying the model on a given connection. * * @param string|null $connection * @return \Illuminate\Database\Eloquent\Builder<static> */ public static function on($connection = null) { // First we will just create a fresh instance of this model, and then we can set the // connection on the model so that it is used for the queries we execute, as well // as being set on every relation we retrieve without a custom connection name. $instance = new static; $instance->setConnection($connection); return $instance->newQuery(); } /** * Begin querying the model on the write connection. * * @return \Illuminate\Database\Eloquent\Builder<static> */ public static function onWriteConnection() { return static::query()->useWritePdo(); } /** * Get all of the models from the database. * * @param array|string $columns * @return \Illuminate\Database\Eloquent\Collection<int, static> */ public static function all($columns = ['*']) { return static::query()->get( is_array($columns) ? $columns : func_get_args() ); } /** * Begin querying a model with eager loading. * * @param array|string $relations * @return \Illuminate\Database\Eloquent\Builder<static> */ public static function with($relations) { return static::query()->with( is_string($relations) ? func_get_args() : $relations ); }
194094
/** * Set the keys for a select query. * * @param \Illuminate\Database\Eloquent\Builder<static> $query * @return \Illuminate\Database\Eloquent\Builder<static> */ protected function setKeysForSelectQuery($query) { $query->where($this->getKeyName(), '=', $this->getKeyForSelectQuery()); return $query; } /** * Get the primary key value for a select query. * * @return mixed */ protected function getKeyForSelectQuery() { return $this->original[$this->getKeyName()] ?? $this->getKey(); } /** * Set the keys for a save update query. * * @param \Illuminate\Database\Eloquent\Builder<static> $query * @return \Illuminate\Database\Eloquent\Builder<static> */ protected function setKeysForSaveQuery($query) { $query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery()); return $query; } /** * Get the primary key value for a save query. * * @return mixed */ protected function getKeyForSaveQuery() { return $this->original[$this->getKeyName()] ?? $this->getKey(); } /** * Perform a model insert operation. * * @param \Illuminate\Database\Eloquent\Builder<static> $query * @return bool */ protected function performInsert(Builder $query) { if ($this->usesUniqueIds()) { $this->setUniqueIds(); } if ($this->fireModelEvent('creating') === false) { return false; } // First we'll need to create a fresh query instance and touch the creation and // update timestamps on this model, which are maintained by us for developer // convenience. After, we will just continue saving these model instances. if ($this->usesTimestamps()) { $this->updateTimestamps(); } // If the model has an incrementing key, we can use the "insertGetId" method on // the query builder, which will give us back the final inserted ID for this // table from the database. Not all tables have to be incrementing though. $attributes = $this->getAttributesForInsert(); if ($this->getIncrementing()) { $this->insertAndSetId($query, $attributes); } // If the table isn't incrementing we'll simply insert these attributes as they // are. These attribute arrays must contain an "id" column previously placed // there by the developer as the manually determined key for these models. else { if (empty($attributes)) { return true; } $query->insert($attributes); } // We will go ahead and set the exists property to true, so that it is set when // the created event is fired, just in case the developer tries to update it // during the event. This will allow them to do so and run an update here. $this->exists = true; $this->wasRecentlyCreated = true; $this->fireModelEvent('created', false); return true; } /** * Insert the given attributes and set the ID on the model. * * @param \Illuminate\Database\Eloquent\Builder<static> $query * @param array $attributes * @return void */ protected function insertAndSetId(Builder $query, $attributes) { $id = $query->insertGetId($attributes, $keyName = $this->getKeyName()); $this->setAttribute($keyName, $id); } /** * Destroy the models for the given IDs. * * @param \Illuminate\Support\Collection|array|int|string $ids * @return int */ public static function destroy($ids) { if ($ids instanceof EloquentCollection) { $ids = $ids->modelKeys(); } if ($ids instanceof BaseCollection) { $ids = $ids->all(); } $ids = is_array($ids) ? $ids : func_get_args(); if (count($ids) === 0) { return 0; } // We will actually pull the models from the database table and call delete on // each of them individually so that their events get fired properly with a // correct set of attributes in case the developers wants to check these. $key = ($instance = new static)->getKeyName(); $count = 0; foreach ($instance->whereIn($key, $ids)->get() as $model) { if ($model->delete()) { $count++; } } return $count; } /** * Delete the model from the database. * * @return bool|null * * @throws \LogicException */ public function delete() { $this->mergeAttributesFromCachedCasts(); if (is_null($this->getKeyName())) { throw new LogicException('No primary key defined on model.'); } // If the model doesn't exist, there is nothing to delete so we'll just return // immediately and not do anything else. Otherwise, we will continue with a // deletion process on the model, firing the proper events, and so forth. if (! $this->exists) { return; } if ($this->fireModelEvent('deleting') === false) { return false; } // Here, we'll touch the owning models, verifying these timestamps get updated // for the models. This will allow any caching to get broken on the parents // by the timestamp. Then we will go ahead and delete the model instance. $this->touchOwners(); $this->performDeleteOnModel(); // Once the model has been deleted, we will fire off the deleted event so that // the developers may hook into post-delete operations. We will then return // a boolean true as the delete is presumably successful on the database. $this->fireModelEvent('deleted', false); return true; } /** * Delete the model from the database without raising any events. * * @return bool */ public function deleteQuietly() { return static::withoutEvents(fn () => $this->delete()); } /** * Delete the model from the database within a transaction. * * @return bool|null * * @throws \Throwable */ public function deleteOrFail() { if (! $this->exists) { return false; } return $this->getConnection()->transaction(fn () => $this->delete()); } /** * Force a hard delete on a soft deleted model. * * This method protects developers from running forceDelete when the trait is missing. * * @return bool|null */ public function forceDelete() { return $this->delete(); } /** * Force a hard destroy on a soft deleted model. * * This method protects developers from running forceDestroy when the trait is missing. * * @param \Illuminate\Support\Collection|array|int|string $ids * @return bool|null */ public static function forceDestroy($ids) { return static::destroy($ids); } /** * Perform the actual delete query on this model instance. * * @return void */ protected function performDeleteOnModel() { $this->setKeysForSaveQuery($this->newModelQuery())->delete(); $this->exists = false; } /** * Begin querying the model. * * @return \Illuminate\Database\Eloquent\Builder<static> */ public static function query() { return (new static)->newQuery(); } /** * Get a new query builder for the model's table. * * @return \Illuminate\Database\Eloquent\Builder<static> */ public function newQuery() { return $this->registerGlobalScopes($this->newQueryWithoutScopes()); } /** * Get a new query builder that doesn't have any global scopes or eager loading. * * @return \Illuminate\Database\Eloquent\Builder<static> */ public function newModelQuery() { return $this->newEloquentBuilder( $this->newBaseQueryBuilder() )->setModel($this); } /** * Get a new query builder with no relationships loaded. * * @return \Illuminate\Database\Eloquent\Builder<static> */ public function newQueryWithoutRelationships() { return $this->registerGlobalScopes($this->newModelQuery()); } /** * Register the global scopes for this builder instance. * * @param \Illuminate\Database\Eloquent\Builder<static> $builder * @return \Illuminate\Database\Eloquent\Builder<static> */
194095
public function registerGlobalScopes($builder) { foreach ($this->getGlobalScopes() as $identifier => $scope) { $builder->withGlobalScope($identifier, $scope); } return $builder; } /** * Get a new query builder that doesn't have any global scopes. * * @return \Illuminate\Database\Eloquent\Builder<static> */ public function newQueryWithoutScopes() { return $this->newModelQuery() ->with($this->with) ->withCount($this->withCount); } /** * Get a new query instance without a given scope. * * @param \Illuminate\Database\Eloquent\Scope|string $scope * @return \Illuminate\Database\Eloquent\Builder<static> */ public function newQueryWithoutScope($scope) { return $this->newQuery()->withoutGlobalScope($scope); } /** * Get a new query to restore one or more models by their queueable IDs. * * @param array|int $ids * @return \Illuminate\Database\Eloquent\Builder<static> */ public function newQueryForRestoration($ids) { return $this->newQueryWithoutScopes()->whereKey($ids); } /** * Create a new Eloquent query builder for the model. * * @param \Illuminate\Database\Query\Builder $query * @return \Illuminate\Database\Eloquent\Builder<*> */ public function newEloquentBuilder($query) { return new static::$builder($query); } /** * Get a new query builder instance for the connection. * * @return \Illuminate\Database\Query\Builder */ protected function newBaseQueryBuilder() { return $this->getConnection()->query(); } /** * Create a new pivot model instance. * * @param \Illuminate\Database\Eloquent\Model $parent * @param array $attributes * @param string $table * @param bool $exists * @param string|null $using * @return \Illuminate\Database\Eloquent\Relations\Pivot */ public function newPivot(self $parent, array $attributes, $table, $exists, $using = null) { return $using ? $using::fromRawAttributes($parent, $attributes, $table, $exists) : Pivot::fromAttributes($parent, $attributes, $table, $exists); } /** * Determine if the model has a given scope. * * @param string $scope * @return bool */ public function hasNamedScope($scope) { return method_exists($this, 'scope'.ucfirst($scope)); } /** * Apply the given named scope if possible. * * @param string $scope * @param array $parameters * @return mixed */ public function callNamedScope($scope, array $parameters = []) { return $this->{'scope'.ucfirst($scope)}(...$parameters); } /** * Convert the model instance to an array. * * @return array */ public function toArray() { return $this->withoutRecursion( fn () => array_merge($this->attributesToArray(), $this->relationsToArray()), fn () => $this->attributesToArray(), ); } /** * Convert the model instance to JSON. * * @param int $options * @return string * * @throws \Illuminate\Database\Eloquent\JsonEncodingException */ public function toJson($options = 0) { try { $json = json_encode($this->jsonSerialize(), $options | JSON_THROW_ON_ERROR); } catch (JsonException $e) { throw JsonEncodingException::forModel($this, $e->getMessage()); } return $json; } /** * Convert the object into something JSON serializable. * * @return mixed */ public function jsonSerialize(): mixed { return $this->toArray(); } /** * Reload a fresh model instance from the database. * * @param array|string $with * @return static|null */ public function fresh($with = []) { if (! $this->exists) { return; } return $this->setKeysForSelectQuery($this->newQueryWithoutScopes()) ->useWritePdo() ->with(is_string($with) ? func_get_args() : $with) ->first(); } /** * Reload the current model instance with fresh attributes from the database. * * @return $this */ public function refresh() { if (! $this->exists) { return $this; } $this->setRawAttributes( $this->setKeysForSelectQuery($this->newQueryWithoutScopes()) ->useWritePdo() ->firstOrFail() ->attributes ); $this->load(collect($this->relations)->reject(function ($relation) { return $relation instanceof Pivot || (is_object($relation) && in_array(AsPivot::class, class_uses_recursive($relation), true)); })->keys()->all()); $this->syncOriginal(); return $this; } /** * Clone the model into a new, non-existing instance. * * @param array|null $except * @return static */ public function replicate(?array $except = null) { $defaults = array_values(array_filter([ $this->getKeyName(), $this->getCreatedAtColumn(), $this->getUpdatedAtColumn(), ...$this->uniqueIds(), 'laravel_through_key', ])); $attributes = Arr::except( $this->getAttributes(), $except ? array_unique(array_merge($except, $defaults)) : $defaults ); return tap(new static, function ($instance) use ($attributes) { $instance->setRawAttributes($attributes); $instance->setRelations($this->relations); $instance->fireModelEvent('replicating', false); }); } /** * Clone the model into a new, non-existing instance without raising any events. * * @param array|null $except * @return static */ public function replicateQuietly(?array $except = null) { return static::withoutEvents(fn () => $this->replicate($except)); } /** * Determine if two models have the same ID and belong to the same table. * * @param \Illuminate\Database\Eloquent\Model|null $model * @return bool */ public function is($model) { return ! is_null($model) && $this->getKey() === $model->getKey() && $this->getTable() === $model->getTable() && $this->getConnectionName() === $model->getConnectionName(); } /** * Determine if two models are not the same. * * @param \Illuminate\Database\Eloquent\Model|null $model * @return bool */ public function isNot($model) { return ! $this->is($model); } /** * Get the database connection for the model. * * @return \Illuminate\Database\Connection */ public function getConnection() { return static::resolveConnection($this->getConnectionName()); } /** * Get the current connection name for the model. * * @return string|null */ public function getConnectionName() { return $this->connection; } /** * Set the connection associated with the model. * * @param string|null $name * @return $this */ public function setConnection($name) { $this->connection = $name; return $this; } /** * Resolve a connection instance. * * @param string|null $connection * @return \Illuminate\Database\Connection */ public static function resolveConnection($connection = null) { return static::$resolver->connection($connection); } /** * Get the connection resolver instance. * * @return \Illuminate\Database\ConnectionResolverInterface|null */ public static function getConnectionResolver() { return static::$resolver; } /** * Set the connection resolver instance. * * @param \Illuminate\Database\ConnectionResolverInterface $resolver * @return void */ public static function setConnectionResolver(Resolver $resolver) { static::$resolver = $resolver; } /** * Unset the connection resolver for models. * * @return void */ public static function unsetConnectionResolver() { static::$resolver = null; }
194096
/** * Get the table associated with the model. * * @return string */ public function getTable() { return $this->table ?? Str::snake(Str::pluralStudly(class_basename($this))); } /** * Set the table associated with the model. * * @param string $table * @return $this */ public function setTable($table) { $this->table = $table; return $this; } /** * Get the primary key for the model. * * @return string */ public function getKeyName() { return $this->primaryKey; } /** * Set the primary key for the model. * * @param string $key * @return $this */ public function setKeyName($key) { $this->primaryKey = $key; return $this; } /** * Get the table qualified key name. * * @return string */ public function getQualifiedKeyName() { return $this->qualifyColumn($this->getKeyName()); } /** * Get the auto-incrementing key type. * * @return string */ public function getKeyType() { return $this->keyType; } /** * Set the data type for the primary key. * * @param string $type * @return $this */ public function setKeyType($type) { $this->keyType = $type; return $this; } /** * Get the value indicating whether the IDs are incrementing. * * @return bool */ public function getIncrementing() { return $this->incrementing; } /** * Set whether IDs are incrementing. * * @param bool $value * @return $this */ public function setIncrementing($value) { $this->incrementing = $value; return $this; } /** * Get the value of the model's primary key. * * @return mixed */ public function getKey() { return $this->getAttribute($this->getKeyName()); } /** * Get the queueable identity for the entity. * * @return mixed */ public function getQueueableId() { return $this->getKey(); } /** * Get the queueable relationships for the entity. * * @return array */ public function getQueueableRelations() { return $this->withoutRecursion(function () { $relations = []; foreach ($this->getRelations() as $key => $relation) { if (! method_exists($this, $key)) { continue; } $relations[] = $key; if ($relation instanceof QueueableCollection) { foreach ($relation->getQueueableRelations() as $collectionValue) { $relations[] = $key.'.'.$collectionValue; } } if ($relation instanceof QueueableEntity) { foreach ($relation->getQueueableRelations() as $entityValue) { $relations[] = $key.'.'.$entityValue; } } } return array_unique($relations); }, []); } /** * Get the queueable connection for the entity. * * @return string|null */ public function getQueueableConnection() { return $this->getConnectionName(); } /** * Get the value of the model's route key. * * @return mixed */ public function getRouteKey() { return $this->getAttribute($this->getRouteKeyName()); } /** * Get the route key for the model. * * @return string */ public function getRouteKeyName() { return $this->getKeyName(); } /** * Retrieve the model for a bound value. * * @param mixed $value * @param string|null $field * @return \Illuminate\Database\Eloquent\Model|null */ public function resolveRouteBinding($value, $field = null) { return $this->resolveRouteBindingQuery($this, $value, $field)->first(); } /** * Retrieve the model for a bound value. * * @param mixed $value * @param string|null $field * @return \Illuminate\Database\Eloquent\Model|null */ public function resolveSoftDeletableRouteBinding($value, $field = null) { return $this->resolveRouteBindingQuery($this, $value, $field)->withTrashed()->first(); } /** * Retrieve the child model for a bound value. * * @param string $childType * @param mixed $value * @param string|null $field * @return \Illuminate\Database\Eloquent\Model|null */ public function resolveChildRouteBinding($childType, $value, $field) { return $this->resolveChildRouteBindingQuery($childType, $value, $field)->first(); } /** * Retrieve the child model for a bound value. * * @param string $childType * @param mixed $value * @param string|null $field * @return \Illuminate\Database\Eloquent\Model|null */ public function resolveSoftDeletableChildRouteBinding($childType, $value, $field) { return $this->resolveChildRouteBindingQuery($childType, $value, $field)->withTrashed()->first(); } /** * Retrieve the child model query for a bound value. * * @param string $childType * @param mixed $value * @param string|null $field * @return \Illuminate\Database\Eloquent\Relations\Relation<\Illuminate\Database\Eloquent\Model, $this, *> */ protected function resolveChildRouteBindingQuery($childType, $value, $field) { $relationship = $this->{$this->childRouteBindingRelationshipName($childType)}(); $field = $field ?: $relationship->getRelated()->getRouteKeyName(); if ($relationship instanceof HasManyThrough || $relationship instanceof BelongsToMany) { $field = $relationship->getRelated()->getTable().'.'.$field; } return $relationship instanceof Model ? $relationship->resolveRouteBindingQuery($relationship, $value, $field) : $relationship->getRelated()->resolveRouteBindingQuery($relationship, $value, $field); } /** * Retrieve the child route model binding relationship name for the given child type. * * @param string $childType * @return string */ protected function childRouteBindingRelationshipName($childType) { return Str::plural(Str::camel($childType)); } /** * Retrieve the model for a bound value. * * @param \Illuminate\Database\Eloquent\Model|\Illuminate\Contracts\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation $query * @param mixed $value * @param string|null $field * @return \Illuminate\Contracts\Database\Eloquent\Builder */ public function resolveRouteBindingQuery($query, $value, $field = null) { return $query->where($field ?? $this->getRouteKeyName(), $value); } /** * Get the default foreign key name for the model. * * @return string */ public function getForeignKey() { return Str::snake(class_basename($this)).'_'.$this->getKeyName(); } /** * Get the number of models to return per page. * * @return int */ public function getPerPage() { return $this->perPage; } /** * Set the number of models to return per page. * * @param int $perPage * @return $this */ public function setPerPage($perPage) { $this->perPage = $perPage; return $this; } /** * Determine if lazy loading is disabled. * * @return bool */ public static function preventsLazyLoading() { return static::$modelsShouldPreventLazyLoading; } /** * Determine if discarding guarded attribute fills is disabled. * * @return bool */ public static function preventsSilentlyDiscardingAttributes() { return static::$modelsShouldPreventSilentlyDiscardingAttributes; } /** * Determine if accessing missing attributes is disabled. * * @return bool */ public static function preventsAccessingMissingAttributes() { return static::$modelsShouldPreventAccessingMissingAttributes; }
194099
<?php namespace Illuminate\Database\Eloquent; class SoftDeletingScope implements Scope { /** * All of the extensions to be added to the builder. * * @var string[] */ protected $extensions = ['Restore', 'RestoreOrCreate', 'CreateOrRestore', 'WithTrashed', 'WithoutTrashed', 'OnlyTrashed']; /** * Apply the scope to a given Eloquent query builder. * * @template TModel of \Illuminate\Database\Eloquent\Model * * @param \Illuminate\Database\Eloquent\Builder<TModel> $builder * @param TModel $model * @return void */ public function apply(Builder $builder, Model $model) { $builder->whereNull($model->getQualifiedDeletedAtColumn()); } /** * Extend the query builder with the needed functions. * * @param \Illuminate\Database\Eloquent\Builder<*> $builder * @return void */ public function extend(Builder $builder) { foreach ($this->extensions as $extension) { $this->{"add{$extension}"}($builder); } $builder->onDelete(function (Builder $builder) { $column = $this->getDeletedAtColumn($builder); return $builder->update([ $column => $builder->getModel()->freshTimestampString(), ]); }); } /** * Get the "deleted at" column for the builder. * * @param \Illuminate\Database\Eloquent\Builder<*> $builder * @return string */ protected function getDeletedAtColumn(Builder $builder) { if (count((array) $builder->getQuery()->joins) > 0) { return $builder->getModel()->getQualifiedDeletedAtColumn(); } return $builder->getModel()->getDeletedAtColumn(); } /** * Add the restore extension to the builder. * * @param \Illuminate\Database\Eloquent\Builder<*> $builder * @return void */ protected function addRestore(Builder $builder) { $builder->macro('restore', function (Builder $builder) { $builder->withTrashed(); return $builder->update([$builder->getModel()->getDeletedAtColumn() => null]); }); } /** * Add the restore-or-create extension to the builder. * * @param \Illuminate\Database\Eloquent\Builder<*> $builder * @return void */ protected function addRestoreOrCreate(Builder $builder) { $builder->macro('restoreOrCreate', function (Builder $builder, array $attributes = [], array $values = []) { $builder->withTrashed(); return tap($builder->firstOrCreate($attributes, $values), function ($instance) { $instance->restore(); }); }); } /** * Add the create-or-restore extension to the builder. * * @param \Illuminate\Database\Eloquent\Builder<*> $builder * @return void */ protected function addCreateOrRestore(Builder $builder) { $builder->macro('createOrRestore', function (Builder $builder, array $attributes = [], array $values = []) { $builder->withTrashed(); return tap($builder->createOrFirst($attributes, $values), function ($instance) { $instance->restore(); }); }); } /** * Add the with-trashed extension to the builder. * * @param \Illuminate\Database\Eloquent\Builder<*> $builder * @return void */ protected function addWithTrashed(Builder $builder) { $builder->macro('withTrashed', function (Builder $builder, $withTrashed = true) { if (! $withTrashed) { return $builder->withoutTrashed(); } return $builder->withoutGlobalScope($this); }); } /** * Add the without-trashed extension to the builder. * * @param \Illuminate\Database\Eloquent\Builder<*> $builder * @return void */ protected function addWithoutTrashed(Builder $builder) { $builder->macro('withoutTrashed', function (Builder $builder) { $model = $builder->getModel(); $builder->withoutGlobalScope($this)->whereNull( $model->getQualifiedDeletedAtColumn() ); return $builder; }); } /** * Add the only-trashed extension to the builder. * * @param \Illuminate\Database\Eloquent\Builder<*> $builder * @return void */ protected function addOnlyTrashed(Builder $builder) { $builder->macro('onlyTrashed', function (Builder $builder) { $model = $builder->getModel(); $builder->withoutGlobalScope($this)->whereNotNull( $model->getQualifiedDeletedAtColumn() ); return $builder; }); } }
194119
<?php namespace Illuminate\Database\Eloquent\Relations; class MorphPivot extends Pivot { /** * The type of the polymorphic relation. * * Explicitly define this so it's not included in saved attributes. * * @var string */ protected $morphType; /** * The value of the polymorphic relation. * * Explicitly define this so it's not included in saved attributes. * * @var string */ protected $morphClass; /** * Set the keys for a save update query. * * @param \Illuminate\Database\Eloquent\Builder<static> $query * @return \Illuminate\Database\Eloquent\Builder<static> */ protected function setKeysForSaveQuery($query) { $query->where($this->morphType, $this->morphClass); return parent::setKeysForSaveQuery($query); } /** * Set the keys for a select query. * * @param \Illuminate\Database\Eloquent\Builder<static> $query * @return \Illuminate\Database\Eloquent\Builder<static> */ protected function setKeysForSelectQuery($query) { $query->where($this->morphType, $this->morphClass); return parent::setKeysForSelectQuery($query); } /** * Delete the pivot model record from the database. * * @return int */ public function delete() { if (isset($this->attributes[$this->getKeyName()])) { return (int) parent::delete(); } if ($this->fireModelEvent('deleting') === false) { return 0; } $query = $this->getDeleteQuery(); $query->where($this->morphType, $this->morphClass); return tap($query->delete(), function () { $this->exists = false; $this->fireModelEvent('deleted', false); }); } /** * Get the morph type for the pivot. * * @return string */ public function getMorphType() { return $this->morphType; } /** * Set the morph type for the pivot. * * @param string $morphType * @return $this */ public function setMorphType($morphType) { $this->morphType = $morphType; return $this; } /** * Set the morph class for the pivot. * * @param string $morphClass * @return \Illuminate\Database\Eloquent\Relations\MorphPivot */ public function setMorphClass($morphClass) { $this->morphClass = $morphClass; return $this; } /** * Get the queueable identity for the entity. * * @return mixed */ public function getQueueableId() { if (isset($this->attributes[$this->getKeyName()])) { return $this->getKey(); } return sprintf( '%s:%s:%s:%s:%s:%s', $this->foreignKey, $this->getAttribute($this->foreignKey), $this->relatedKey, $this->getAttribute($this->relatedKey), $this->morphType, $this->morphClass ); } /** * Get a new query to restore one or more models by their queueable IDs. * * @param array|int $ids * @return \Illuminate\Database\Eloquent\Builder<static> */ public function newQueryForRestoration($ids) { if (is_array($ids)) { return $this->newQueryForCollectionRestoration($ids); } if (! str_contains($ids, ':')) { return parent::newQueryForRestoration($ids); } $segments = explode(':', $ids); return $this->newQueryWithoutScopes() ->where($segments[0], $segments[1]) ->where($segments[2], $segments[3]) ->where($segments[4], $segments[5]); } /** * Get a new query to restore multiple models by their queueable IDs. * * @param array $ids * @return \Illuminate\Database\Eloquent\Builder<static> */ protected function newQueryForCollectionRestoration(array $ids) { $ids = array_values($ids); if (! str_contains($ids[0], ':')) { return parent::newQueryForRestoration($ids); } $query = $this->newQueryWithoutScopes(); foreach ($ids as $id) { $segments = explode(':', $id); $query->orWhere(function ($query) use ($segments) { return $query->where($segments[0], $segments[1]) ->where($segments[2], $segments[3]) ->where($segments[4], $segments[5]); }); } return $query; } }
194126
public function getForeignKeyName() { return $this->foreignKey; } /** * Get the fully qualified foreign key of the relationship. * * @return string */ public function getQualifiedForeignKeyName() { return $this->child->qualifyColumn($this->foreignKey); } /** * Get the key value of the child's foreign key. * * @return mixed */ public function getParentKey() { return $this->getForeignKeyFrom($this->child); } /** * Get the associated key of the relationship. * * @return string */ public function getOwnerKeyName() { return $this->ownerKey; } /** * Get the fully qualified associated key of the relationship. * * @return string */ public function getQualifiedOwnerKeyName() { return $this->related->qualifyColumn($this->ownerKey); } /** * Get the value of the model's foreign key. * * @param TRelatedModel $model * @return int|string */ protected function getRelatedKeyFrom(Model $model) { return $model->{$this->ownerKey}; } /** * Get the value of the model's foreign key. * * @param TDeclaringModel $model * @return mixed */ protected function getForeignKeyFrom(Model $model) { $foreignKey = $model->{$this->foreignKey}; return enum_value($foreignKey); } /** * Get the name of the relationship. * * @return string */ public function getRelationName() { return $this->relationName; } }
194128
class BelongsToMany extends Relation { use InteractsWithDictionary, InteractsWithPivotTable; /** * The intermediate table for the relation. * * @var string */ protected $table; /** * The foreign key of the parent model. * * @var string */ protected $foreignPivotKey; /** * The associated key of the relation. * * @var string */ protected $relatedPivotKey; /** * The key name of the parent model. * * @var string */ protected $parentKey; /** * The key name of the related model. * * @var string */ protected $relatedKey; /** * The "name" of the relationship. * * @var string */ protected $relationName; /** * The pivot table columns to retrieve. * * @var array<string|\Illuminate\Contracts\Database\Query\Expression> */ protected $pivotColumns = []; /** * Any pivot table restrictions for where clauses. * * @var array */ protected $pivotWheres = []; /** * Any pivot table restrictions for whereIn clauses. * * @var array */ protected $pivotWhereIns = []; /** * Any pivot table restrictions for whereNull clauses. * * @var array */ protected $pivotWhereNulls = []; /** * The default values for the pivot columns. * * @var array */ protected $pivotValues = []; /** * Indicates if timestamps are available on the pivot table. * * @var bool */ public $withTimestamps = false; /** * The custom pivot table column for the created_at timestamp. * * @var string|null */ protected $pivotCreatedAt; /** * The custom pivot table column for the updated_at timestamp. * * @var string|null */ protected $pivotUpdatedAt; /** * The class name of the custom pivot model to use for the relationship. * * @var string */ protected $using; /** * The name of the accessor to use for the "pivot" relationship. * * @var string */ protected $accessor = 'pivot'; /** * Create a new belongs to many relationship instance. * * @param \Illuminate\Database\Eloquent\Builder<TRelatedModel> $query * @param TDeclaringModel $parent * @param string|class-string<TRelatedModel> $table * @param string $foreignPivotKey * @param string $relatedPivotKey * @param string $parentKey * @param string $relatedKey * @param string|null $relationName * @return void */ public function __construct(Builder $query, Model $parent, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName = null) { $this->parentKey = $parentKey; $this->relatedKey = $relatedKey; $this->relationName = $relationName; $this->relatedPivotKey = $relatedPivotKey; $this->foreignPivotKey = $foreignPivotKey; $this->table = $this->resolveTableName($table); parent::__construct($query, $parent); } /** * Attempt to resolve the intermediate table name from the given string. * * @param string $table * @return string */ protected function resolveTableName($table) { if (! str_contains($table, '\\') || ! class_exists($table)) { return $table; } $model = new $table; if (! $model instanceof Model) { return $table; } if (in_array(AsPivot::class, class_uses_recursive($model))) { $this->using($table); } return $model->getTable(); } /** * Set the base constraints on the relation query. * * @return void */ public function addConstraints() { $this->performJoin(); if (static::$constraints) { $this->addWhereConstraints(); } } /** * Set the join clause for the relation query. * * @param \Illuminate\Database\Eloquent\Builder<TRelatedModel>|null $query * @return $this */ protected function performJoin($query = null) { $query = $query ?: $this->query; // We need to join to the intermediate table on the related model's primary // key column with the intermediate table's foreign key for the related // model instance. Then we can set the "where" for the parent models. $query->join( $this->table, $this->getQualifiedRelatedKeyName(), '=', $this->getQualifiedRelatedPivotKeyName() ); return $this; } /** * Set the where clause for the relation query. * * @return $this */ protected function addWhereConstraints() { $this->query->where( $this->getQualifiedForeignPivotKeyName(), '=', $this->parent->{$this->parentKey} ); return $this; } /** @inheritDoc */ public function addEagerConstraints(array $models) { $whereIn = $this->whereInMethod($this->parent, $this->parentKey); $this->whereInEager( $whereIn, $this->getQualifiedForeignPivotKeyName(), $this->getKeys($models, $this->parentKey) ); } /** @inheritDoc */ public function initRelation(array $models, $relation) { foreach ($models as $model) { $model->setRelation($relation, $this->related->newCollection()); } return $models; } /** @inheritDoc */ public function match(array $models, Collection $results, $relation) { $dictionary = $this->buildDictionary($results); // Once we have an array dictionary of child objects we can easily match the // children back to their parent using the dictionary and the keys on the // parent models. Then we should return these hydrated models back out. foreach ($models as $model) { $key = $this->getDictionaryKey($model->{$this->parentKey}); if (isset($dictionary[$key])) { $model->setRelation( $relation, $this->related->newCollection($dictionary[$key]) ); } } return $models; } /** * Build model dictionary keyed by the relation's foreign key. * * @param \Illuminate\Database\Eloquent\Collection<int, TRelatedModel> $results * @return array<array<string, TRelatedModel>> */ protected function buildDictionary(Collection $results) { // First we'll build a dictionary of child models keyed by the foreign key // of the relation so that we will easily and quickly match them to the // parents without having a possibly slow inner loop for every model. $dictionary = []; foreach ($results as $result) { $value = $this->getDictionaryKey($result->{$this->accessor}->{$this->foreignPivotKey}); $dictionary[$value][] = $result; } return $dictionary; } /** * Get the class being used for pivot models. * * @return string */ public function getPivotClass() { return $this->using ?? Pivot::class; } /** * Specify the custom pivot model to use for the relationship. * * @param string $class * @return $this */ public function using($class) { $this->using = $class; return $this; } /** * Specify the custom pivot accessor to use for the relationship. * * @param string $accessor * @return $this */ public function as($accessor) { $this->accessor = $accessor; return $this; } /** * Set a where clause for a pivot table column. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @param mixed $operator * @param mixed $value * @param string $boolean * @return $this */
194129
public function wherePivot($column, $operator = null, $value = null, $boolean = 'and') { $this->pivotWheres[] = func_get_args(); return $this->where($this->qualifyPivotColumn($column), $operator, $value, $boolean); } /** * Set a "where between" clause for a pivot table column. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @param array $values * @param string $boolean * @param bool $not * @return $this */ public function wherePivotBetween($column, array $values, $boolean = 'and', $not = false) { return $this->whereBetween($this->qualifyPivotColumn($column), $values, $boolean, $not); } /** * Set a "or where between" clause for a pivot table column. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @param array $values * @return $this */ public function orWherePivotBetween($column, array $values) { return $this->wherePivotBetween($column, $values, 'or'); } /** * Set a "where pivot not between" clause for a pivot table column. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @param array $values * @param string $boolean * @return $this */ public function wherePivotNotBetween($column, array $values, $boolean = 'and') { return $this->wherePivotBetween($column, $values, $boolean, true); } /** * Set a "or where not between" clause for a pivot table column. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @param array $values * @return $this */ public function orWherePivotNotBetween($column, array $values) { return $this->wherePivotBetween($column, $values, 'or', true); } /** * Set a "where in" clause for a pivot table column. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @param mixed $values * @param string $boolean * @param bool $not * @return $this */ public function wherePivotIn($column, $values, $boolean = 'and', $not = false) { $this->pivotWhereIns[] = func_get_args(); return $this->whereIn($this->qualifyPivotColumn($column), $values, $boolean, $not); } /** * Set an "or where" clause for a pivot table column. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @param mixed $operator * @param mixed $value * @return $this */ public function orWherePivot($column, $operator = null, $value = null) { return $this->wherePivot($column, $operator, $value, 'or'); } /** * Set a where clause for a pivot table column. * * In addition, new pivot records will receive this value. * * @param string|\Illuminate\Contracts\Database\Query\Expression|array<string, string> $column * @param mixed $value * @return $this * * @throws \InvalidArgumentException */ public function withPivotValue($column, $value = null) { if (is_array($column)) { foreach ($column as $name => $value) { $this->withPivotValue($name, $value); } return $this; } if (is_null($value)) { throw new InvalidArgumentException('The provided value may not be null.'); } $this->pivotValues[] = compact('column', 'value'); return $this->wherePivot($column, '=', $value); } /** * Set an "or where in" clause for a pivot table column. * * @param string $column * @param mixed $values * @return $this */ public function orWherePivotIn($column, $values) { return $this->wherePivotIn($column, $values, 'or'); } /** * Set a "where not in" clause for a pivot table column. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @param mixed $values * @param string $boolean * @return $this */ public function wherePivotNotIn($column, $values, $boolean = 'and') { return $this->wherePivotIn($column, $values, $boolean, true); } /** * Set an "or where not in" clause for a pivot table column. * * @param string $column * @param mixed $values * @return $this */ public function orWherePivotNotIn($column, $values) { return $this->wherePivotNotIn($column, $values, 'or'); } /** * Set a "where null" clause for a pivot table column. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @param string $boolean * @param bool $not * @return $this */ public function wherePivotNull($column, $boolean = 'and', $not = false) { $this->pivotWhereNulls[] = func_get_args(); return $this->whereNull($this->qualifyPivotColumn($column), $boolean, $not); } /** * Set a "where not null" clause for a pivot table column. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @param string $boolean * @return $this */ public function wherePivotNotNull($column, $boolean = 'and') { return $this->wherePivotNull($column, $boolean, true); } /** * Set a "or where null" clause for a pivot table column. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @param bool $not * @return $this */ public function orWherePivotNull($column, $not = false) { return $this->wherePivotNull($column, 'or', $not); } /** * Set a "or where not null" clause for a pivot table column. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @return $this */ public function orWherePivotNotNull($column) { return $this->orWherePivotNull($column, true); } /** * Add an "order by" clause for a pivot table column. * * @param string|\Illuminate\Contracts\Database\Query\Expression $column * @param string $direction * @return $this */ public function orderByPivot($column, $direction = 'asc') { return $this->orderBy($this->qualifyPivotColumn($column), $direction); } /** * Find a related model by its primary key or return a new instance of the related model. * * @param mixed $id * @param array $columns * @return ($id is (\Illuminate\Contracts\Support\Arrayable<array-key, mixed>|array<mixed>) ? \Illuminate\Database\Eloquent\Collection<int, TRelatedModel> : TRelatedModel) */ public function findOrNew($id, $columns = ['*']) { if (is_null($instance = $this->find($id, $columns))) { $instance = $this->related->newInstance(); } return $instance; } /** * Get the first related model record matching the attributes or instantiate it. * * @param array $attributes * @param array $values * @return TRelatedModel */
194130
public function firstOrNew(array $attributes = [], array $values = []) { if (is_null($instance = $this->related->where($attributes)->first())) { $instance = $this->related->newInstance(array_merge($attributes, $values)); } return $instance; } /** * Get the first record matching the attributes. If the record is not found, create it. * * @param array $attributes * @param array $values * @param array $joining * @param bool $touch * @return TRelatedModel */ public function firstOrCreate(array $attributes = [], array $values = [], array $joining = [], $touch = true) { if (is_null($instance = (clone $this)->where($attributes)->first())) { if (is_null($instance = $this->related->where($attributes)->first())) { $instance = $this->createOrFirst($attributes, $values, $joining, $touch); } else { try { $this->getQuery()->withSavepointIfNeeded(fn () => $this->attach($instance, $joining, $touch)); } catch (UniqueConstraintViolationException) { // Nothing to do, the model was already attached... } } } return $instance; } /** * Attempt to create the record. If a unique constraint violation occurs, attempt to find the matching record. * * @param array $attributes * @param array $values * @param array $joining * @param bool $touch * @return TRelatedModel */ public function createOrFirst(array $attributes = [], array $values = [], array $joining = [], $touch = true) { try { return $this->getQuery()->withSavePointIfNeeded(fn () => $this->create(array_merge($attributes, $values), $joining, $touch)); } catch (UniqueConstraintViolationException $e) { // ... } try { return tap($this->related->where($attributes)->first() ?? throw $e, function ($instance) use ($joining, $touch) { $this->getQuery()->withSavepointIfNeeded(fn () => $this->attach($instance, $joining, $touch)); }); } catch (UniqueConstraintViolationException $e) { return (clone $this)->useWritePdo()->where($attributes)->first() ?? throw $e; } } /** * Create or update a related record matching the attributes, and fill it with values. * * @param array $attributes * @param array $values * @param array $joining * @param bool $touch * @return TRelatedModel */ public function updateOrCreate(array $attributes, array $values = [], array $joining = [], $touch = true) { return tap($this->firstOrCreate($attributes, $values, $joining, $touch), function ($instance) use ($values) { if (! $instance->wasRecentlyCreated) { $instance->fill($values); $instance->save(['touch' => false]); } }); } /** * Find a related model by its primary key. * * @param mixed $id * @param array $columns * @return ($id is (\Illuminate\Contracts\Support\Arrayable<array-key, mixed>|array<mixed>) ? \Illuminate\Database\Eloquent\Collection<int, TRelatedModel> : TRelatedModel|null) */ public function find($id, $columns = ['*']) { if (! $id instanceof Model && (is_array($id) || $id instanceof Arrayable)) { return $this->findMany($id, $columns); } return $this->where( $this->getRelated()->getQualifiedKeyName(), '=', $this->parseId($id) )->first($columns); } /** * Find multiple related models by their primary keys. * * @param \Illuminate\Contracts\Support\Arrayable|array $ids * @param array $columns * @return \Illuminate\Database\Eloquent\Collection<int, TRelatedModel> */ public function findMany($ids, $columns = ['*']) { $ids = $ids instanceof Arrayable ? $ids->toArray() : $ids; if (empty($ids)) { return $this->getRelated()->newCollection(); } return $this->whereKey( $this->parseIds($ids) )->get($columns); } /** * Find a related model by its primary key or throw an exception. * * @param mixed $id * @param array $columns * @return ($id is (\Illuminate\Contracts\Support\Arrayable<array-key, mixed>|array<mixed>) ? \Illuminate\Database\Eloquent\Collection<int, TRelatedModel> : TRelatedModel) * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<TRelatedModel> */ public function findOrFail($id, $columns = ['*']) { $result = $this->find($id, $columns); $id = $id instanceof Arrayable ? $id->toArray() : $id; if (is_array($id)) { if (count($result) === count(array_unique($id))) { return $result; } } elseif (! is_null($result)) { return $result; } throw (new ModelNotFoundException)->setModel(get_class($this->related), $id); } /** * Find a related model by its primary key or call a callback. * * @template TValue * * @param mixed $id * @param (\Closure(): TValue)|list<string>|string $columns * @param (\Closure(): TValue)|null $callback * @return ( * $id is (\Illuminate\Contracts\Support\Arrayable<array-key, mixed>|array<mixed>) * ? \Illuminate\Database\Eloquent\Collection<int, TRelatedModel>|TValue * : TRelatedModel|TValue * ) */ public function findOr($id, $columns = ['*'], ?Closure $callback = null) { if ($columns instanceof Closure) { $callback = $columns; $columns = ['*']; } $result = $this->find($id, $columns); $id = $id instanceof Arrayable ? $id->toArray() : $id; if (is_array($id)) { if (count($result) === count(array_unique($id))) { return $result; } } elseif (! is_null($result)) { return $result; } return $callback(); } /** * Add a basic where clause to the query, and return the first result. * * @param \Closure|string|array $column * @param mixed $operator * @param mixed $value * @param string $boolean * @return TRelatedModel|null */ public function firstWhere($column, $operator = null, $value = null, $boolean = 'and') { return $this->where($column, $operator, $value, $boolean)->first(); } /** * Execute the query and get the first result. * * @param array $columns * @return TRelatedModel|null */ public function first($columns = ['*']) { $results = $this->take(1)->get($columns); return count($results) > 0 ? $results->first() : null; } /** * Execute the query and get the first result or throw an exception. * * @param array $columns * @return TRelatedModel * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<TRelatedModel> */ public function firstOrFail($columns = ['*']) { if (! is_null($model = $this->first($columns))) { return $model; } throw (new ModelNotFoundException)->setModel(get_class($this->related)); } /** * Execute the query and get the first result or call a callback. * * @template TValue * * @param (\Closure(): TValue)|list<string> $columns * @param (\Closure(): TValue)|null $callback * @return TRelatedModel|TValue */
194140
public function firstOr($columns = ['*'], ?Closure $callback = null) { if ($columns instanceof Closure) { $callback = $columns; $columns = ['*']; } if (! is_null($model = $this->first($columns))) { return $model; } return $callback(); } /** * Find a related model by its primary key. * * @param mixed $id * @param array $columns * @return ($id is (\Illuminate\Contracts\Support\Arrayable<array-key, mixed>|array<mixed>) ? \Illuminate\Database\Eloquent\Collection<int, TRelatedModel> : TRelatedModel|null) */ public function find($id, $columns = ['*']) { if (is_array($id) || $id instanceof Arrayable) { return $this->findMany($id, $columns); } return $this->where( $this->getRelated()->getQualifiedKeyName(), '=', $id )->first($columns); } /** * Find multiple related models by their primary keys. * * @param \Illuminate\Contracts\Support\Arrayable|array $ids * @param array $columns * @return \Illuminate\Database\Eloquent\Collection<int, TRelatedModel> */ public function findMany($ids, $columns = ['*']) { $ids = $ids instanceof Arrayable ? $ids->toArray() : $ids; if (empty($ids)) { return $this->getRelated()->newCollection(); } return $this->whereIn( $this->getRelated()->getQualifiedKeyName(), $ids )->get($columns); } /** * Find a related model by its primary key or throw an exception. * * @param mixed $id * @param array $columns * @return ($id is (\Illuminate\Contracts\Support\Arrayable<array-key, mixed>|array<mixed>) ? \Illuminate\Database\Eloquent\Collection<int, TRelatedModel> : TRelatedModel) * * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<TRelatedModel> */ public function findOrFail($id, $columns = ['*']) { $result = $this->find($id, $columns); $id = $id instanceof Arrayable ? $id->toArray() : $id; if (is_array($id)) { if (count($result) === count(array_unique($id))) { return $result; } } elseif (! is_null($result)) { return $result; } throw (new ModelNotFoundException)->setModel(get_class($this->related), $id); } /** * Find a related model by its primary key or call a callback. * * @template TValue * * @param mixed $id * @param (\Closure(): TValue)|list<string>|string $columns * @param (\Closure(): TValue)|null $callback * @return ( * $id is (\Illuminate\Contracts\Support\Arrayable<array-key, mixed>|array<mixed>) * ? \Illuminate\Database\Eloquent\Collection<int, TRelatedModel>|TValue * : TRelatedModel|TValue * ) */ public function findOr($id, $columns = ['*'], ?Closure $callback = null) { if ($columns instanceof Closure) { $callback = $columns; $columns = ['*']; } $result = $this->find($id, $columns); $id = $id instanceof Arrayable ? $id->toArray() : $id; if (is_array($id)) { if (count($result) === count(array_unique($id))) { return $result; } } elseif (! is_null($result)) { return $result; } return $callback(); } /** @inheritDoc */ public function get($columns = ['*']) { $builder = $this->prepareQueryBuilder($columns); $models = $builder->getModels(); // If we actually found models we will also eager load any relationships that // have been specified as needing to be eager loaded. This will solve the // n + 1 query problem for the developer and also increase performance. if (count($models) > 0) { $models = $builder->eagerLoadRelations($models); } return $this->query->applyAfterQueryCallbacks( $this->related->newCollection($models) ); } /** * Get a paginator for the "select" statement. * * @param int|null $perPage * @param array $columns * @param string $pageName * @param int $page * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) { $this->query->addSelect($this->shouldSelect($columns)); return $this->query->paginate($perPage, $columns, $pageName, $page); } /** * Paginate the given query into a simple paginator. * * @param int|null $perPage * @param array $columns * @param string $pageName * @param int|null $page * @return \Illuminate\Contracts\Pagination\Paginator */ public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) { $this->query->addSelect($this->shouldSelect($columns)); return $this->query->simplePaginate($perPage, $columns, $pageName, $page); } /** * Paginate the given query into a cursor paginator. * * @param int|null $perPage * @param array $columns * @param string $cursorName * @param string|null $cursor * @return \Illuminate\Contracts\Pagination\CursorPaginator */ public function cursorPaginate($perPage = null, $columns = ['*'], $cursorName = 'cursor', $cursor = null) { $this->query->addSelect($this->shouldSelect($columns)); return $this->query->cursorPaginate($perPage, $columns, $cursorName, $cursor); } /** * Set the select clause for the relation query. * * @param array $columns * @return array */ protected function shouldSelect(array $columns = ['*']) { if ($columns == ['*']) { $columns = [$this->related->getTable().'.*']; } return array_merge($columns, [$this->getQualifiedFirstKeyName().' as laravel_through_key']); } /** * Chunk the results of the query. * * @param int $count * @param callable $callback * @return bool */ public function chunk($count, callable $callback) { return $this->prepareQueryBuilder()->chunk($count, $callback); } /** * Chunk the results of a query by comparing numeric IDs. * * @param int $count * @param callable $callback * @param string|null $column * @param string|null $alias * @return bool */ public function chunkById($count, callable $callback, $column = null, $alias = null) { $column ??= $this->getRelated()->getQualifiedKeyName(); $alias ??= $this->getRelated()->getKeyName(); return $this->prepareQueryBuilder()->chunkById($count, $callback, $column, $alias); } /** * Chunk the results of a query by comparing IDs in descending order. * * @param int $count * @param callable $callback * @param string|null $column * @param string|null $alias * @return bool */ public function chunkByIdDesc($count, callable $callback, $column = null, $alias = null) { $column ??= $this->getRelated()->getQualifiedKeyName(); $alias ??= $this->getRelated()->getKeyName(); return $this->prepareQueryBuilder()->chunkByIdDesc($count, $callback, $column, $alias); }
194156
trait InteractsWithPivotTable { /** * Toggles a model (or models) from the parent. * * Each existing model is detached, and non existing ones are attached. * * @param mixed $ids * @param bool $touch * @return array */ public function toggle($ids, $touch = true) { $changes = [ 'attached' => [], 'detached' => [], ]; $records = $this->formatRecordsList($this->parseIds($ids)); // Next, we will determine which IDs should get removed from the join table by // checking which of the given ID/records is in the list of current records // and removing all of those rows from this "intermediate" joining table. $detach = array_values(array_intersect( $this->newPivotQuery()->pluck($this->relatedPivotKey)->all(), array_keys($records) )); if (count($detach) > 0) { $this->detach($detach, false); $changes['detached'] = $this->castKeys($detach); } // Finally, for all of the records which were not "detached", we'll attach the // records into the intermediate table. Then, we will add those attaches to // this change list and get ready to return these results to the callers. $attach = array_diff_key($records, array_flip($detach)); if (count($attach) > 0) { $this->attach($attach, [], false); $changes['attached'] = array_keys($attach); } // Once we have finished attaching or detaching the records, we will see if we // have done any attaching or detaching, and if we have we will touch these // relationships if they are configured to touch on any database updates. if ($touch && (count($changes['attached']) || count($changes['detached']))) { $this->touchIfTouching(); } return $changes; } /** * Sync the intermediate tables with a list of IDs without detaching. * * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids * @return array{attached: array, detached: array, updated: array} */ public function syncWithoutDetaching($ids) { return $this->sync($ids, false); } /** * Sync the intermediate tables with a list of IDs or collection of models. * * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids * @param bool $detaching * @return array{attached: array, detached: array, updated: array} */ public function sync($ids, $detaching = true) { $changes = [ 'attached' => [], 'detached' => [], 'updated' => [], ]; // First we need to attach any of the associated models that are not currently // in this joining table. We'll spin through the given IDs, checking to see // if they exist in the array of current ones, and if not we will insert. $current = $this->getCurrentlyAttachedPivots() ->pluck($this->relatedPivotKey)->all(); $records = $this->formatRecordsList($this->parseIds($ids)); // Next, we will take the differences of the currents and given IDs and detach // all of the entities that exist in the "current" array but are not in the // array of the new IDs given to the method which will complete the sync. if ($detaching) { $detach = array_diff($current, array_keys($records)); if (count($detach) > 0) { $this->detach($detach, false); $changes['detached'] = $this->castKeys($detach); } } // Now we are finally ready to attach the new records. Note that we'll disable // touching until after the entire operation is complete so we don't fire a // ton of touch operations until we are totally done syncing the records. $changes = array_merge( $changes, $this->attachNew($records, $current, false) ); // Once we have finished attaching or detaching the records, we will see if we // have done any attaching or detaching, and if we have we will touch these // relationships if they are configured to touch on any database updates. if (count($changes['attached']) || count($changes['updated']) || count($changes['detached'])) { $this->touchIfTouching(); } return $changes; } /** * Sync the intermediate tables with a list of IDs or collection of models with the given pivot values. * * @param \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array $ids * @param array $values * @param bool $detaching * @return array{attached: array, detached: array, updated: array} */ public function syncWithPivotValues($ids, array $values, bool $detaching = true) { return $this->sync(collect($this->parseIds($ids))->mapWithKeys(function ($id) use ($values) { return [$id => $values]; }), $detaching); } /** * Format the sync / toggle record list so that it is keyed by ID. * * @param array $records * @return array */ protected function formatRecordsList(array $records) { return collect($records)->mapWithKeys(function ($attributes, $id) { if (! is_array($attributes)) { [$id, $attributes] = [$attributes, []]; } if ($id instanceof BackedEnum) { $id = $id->value; } return [$id => $attributes]; })->all(); } /** * Attach all of the records that aren't in the given current records. * * @param array $records * @param array $current * @param bool $touch * @return array */ protected function attachNew(array $records, array $current, $touch = true) { $changes = ['attached' => [], 'updated' => []]; foreach ($records as $id => $attributes) { // If the ID is not in the list of existing pivot IDs, we will insert a new pivot // record, otherwise, we will just update this existing record on this joining // table, so that the developers will easily update these records pain free. if (! in_array($id, $current)) { $this->attach($id, $attributes, $touch); $changes['attached'][] = $this->castKey($id); } // Now we'll try to update an existing pivot record with the attributes that were // given to the method. If the model is actually updated we will add it to the // list of updated pivot records so we return them back out to the consumer. elseif (count($attributes) > 0 && $this->updateExistingPivot($id, $attributes, $touch)) { $changes['updated'][] = $this->castKey($id); } } return $changes; } /** * Update an existing pivot record on the table. * * @param mixed $id * @param array $attributes * @param bool $touch * @return int */ public function updateExistingPivot($id, array $attributes, $touch = true) { if ($this->using && empty($this->pivotWheres) && empty($this->pivotWhereIns) && empty($this->pivotWhereNulls)) { return $this->updateExistingPivotUsingCustomClass($id, $attributes, $touch); } if ($this->hasPivotColumn($this->updatedAt())) { $attributes = $this->addTimestampsToAttachment($attributes, true); } $updated = $this->newPivotStatementForId($this->parseId($id))->update( $this->castAttributes($attributes) ); if ($touch) { $this->touchIfTouching(); } return $updated; } /** * Update an existing pivot record on the table via a custom class. * * @param mixed $id * @param array $attributes * @param bool $touch * @return int */
194157
protected function updateExistingPivotUsingCustomClass($id, array $attributes, $touch) { $pivot = $this->getCurrentlyAttachedPivots() ->where($this->foreignPivotKey, $this->parent->{$this->parentKey}) ->where($this->relatedPivotKey, $this->parseId($id)) ->first(); $updated = $pivot ? $pivot->fill($attributes)->isDirty() : false; if ($updated) { $pivot->save(); } if ($touch) { $this->touchIfTouching(); } return (int) $updated; } /** * Attach a model to the parent. * * @param mixed $id * @param array $attributes * @param bool $touch * @return void */ public function attach($id, array $attributes = [], $touch = true) { if ($this->using) { $this->attachUsingCustomClass($id, $attributes); } else { // Here we will insert the attachment records into the pivot table. Once we have // inserted the records, we will touch the relationships if necessary and the // function will return. We can parse the IDs before inserting the records. $this->newPivotStatement()->insert($this->formatAttachRecords( $this->parseIds($id), $attributes )); } if ($touch) { $this->touchIfTouching(); } } /** * Attach a model to the parent using a custom class. * * @param mixed $id * @param array $attributes * @return void */ protected function attachUsingCustomClass($id, array $attributes) { $records = $this->formatAttachRecords( $this->parseIds($id), $attributes ); foreach ($records as $record) { $this->newPivot($record, false)->save(); } } /** * Create an array of records to insert into the pivot table. * * @param array $ids * @param array $attributes * @return array */ protected function formatAttachRecords($ids, array $attributes) { $records = []; $hasTimestamps = ($this->hasPivotColumn($this->createdAt()) || $this->hasPivotColumn($this->updatedAt())); // To create the attachment records, we will simply spin through the IDs given // and create a new record to insert for each ID. Each ID may actually be a // key in the array, with extra attributes to be placed in other columns. foreach ($ids as $key => $value) { $records[] = $this->formatAttachRecord( $key, $value, $attributes, $hasTimestamps ); } return $records; } /** * Create a full attachment record payload. * * @param int $key * @param mixed $value * @param array $attributes * @param bool $hasTimestamps * @return array */ protected function formatAttachRecord($key, $value, $attributes, $hasTimestamps) { [$id, $attributes] = $this->extractAttachIdAndAttributes($key, $value, $attributes); return array_merge( $this->baseAttachRecord($id, $hasTimestamps), $this->castAttributes($attributes) ); } /** * Get the attach record ID and extra attributes. * * @param mixed $key * @param mixed $value * @param array $attributes * @return array */ protected function extractAttachIdAndAttributes($key, $value, array $attributes) { return is_array($value) ? [$key, array_merge($value, $attributes)] : [$value, $attributes]; } /** * Create a new pivot attachment record. * * @param int $id * @param bool $timed * @return array */ protected function baseAttachRecord($id, $timed) { $record[$this->relatedPivotKey] = $id; $record[$this->foreignPivotKey] = $this->parent->{$this->parentKey}; // If the record needs to have creation and update timestamps, we will make // them by calling the parent model's "freshTimestamp" method which will // provide us with a fresh timestamp in this model's preferred format. if ($timed) { $record = $this->addTimestampsToAttachment($record); } foreach ($this->pivotValues as $value) { $record[$value['column']] = $value['value']; } return $record; } /** * Set the creation and update timestamps on an attach record. * * @param array $record * @param bool $exists * @return array */ protected function addTimestampsToAttachment(array $record, $exists = false) { $fresh = $this->parent->freshTimestamp(); if ($this->using) { $pivotModel = new $this->using; $fresh = $pivotModel->fromDateTime($fresh); } if (! $exists && $this->hasPivotColumn($this->createdAt())) { $record[$this->createdAt()] = $fresh; } if ($this->hasPivotColumn($this->updatedAt())) { $record[$this->updatedAt()] = $fresh; } return $record; } /** * Determine whether the given column is defined as a pivot column. * * @param string $column * @return bool */ public function hasPivotColumn($column) { return in_array($column, $this->pivotColumns); } /** * Detach models from the relationship. * * @param mixed $ids * @param bool $touch * @return int */ public function detach($ids = null, $touch = true) { if ($this->using && ! empty($ids) && empty($this->pivotWheres) && empty($this->pivotWhereIns) && empty($this->pivotWhereNulls)) { $results = $this->detachUsingCustomClass($ids); } else { $query = $this->newPivotQuery(); // If associated IDs were passed to the method we will only delete those // associations, otherwise all of the association ties will be broken. // We'll return the numbers of affected rows when we do the deletes. if (! is_null($ids)) { $ids = $this->parseIds($ids); if (empty($ids)) { return 0; } $query->whereIn($this->getQualifiedRelatedPivotKeyName(), (array) $ids); } // Once we have all of the conditions set on the statement, we are ready // to run the delete on the pivot table. Then, if the touch parameter // is true, we will go ahead and touch all related models to sync. $results = $query->delete(); } if ($touch) { $this->touchIfTouching(); } return $results; } /** * Detach models from the relationship using a custom class. * * @param mixed $ids * @return int */ protected function detachUsingCustomClass($ids) { $results = 0; foreach ($this->parseIds($ids) as $id) { $results += $this->newPivot([ $this->foreignPivotKey => $this->parent->{$this->parentKey}, $this->relatedPivotKey => $id, ], true)->delete(); } return $results; } /** * Get the pivot models that are currently attached. * * @return \Illuminate\Support\Collection */ protected function getCurrentlyAttachedPivots() { return $this->newPivotQuery()->get()->map(function ($record) { $class = $this->using ?: Pivot::class; $pivot = $class::fromRawAttributes($this->parent, (array) $record, $this->getTable(), true); return $pivot->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey); }); }
194158
/** * Create a new pivot model instance. * * @param array $attributes * @param bool $exists * @return \Illuminate\Database\Eloquent\Relations\Pivot */ public function newPivot(array $attributes = [], $exists = false) { $attributes = array_merge(array_column($this->pivotValues, 'value', 'column'), $attributes); $pivot = $this->related->newPivot( $this->parent, $attributes, $this->table, $exists, $this->using ); return $pivot->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey); } /** * Create a new existing pivot model instance. * * @param array $attributes * @return \Illuminate\Database\Eloquent\Relations\Pivot */ public function newExistingPivot(array $attributes = []) { return $this->newPivot($attributes, true); } /** * Get a new plain query builder for the pivot table. * * @return \Illuminate\Database\Query\Builder */ public function newPivotStatement() { return $this->query->getQuery()->newQuery()->from($this->table); } /** * Get a new pivot statement for a given "other" ID. * * @param mixed $id * @return \Illuminate\Database\Query\Builder */ public function newPivotStatementForId($id) { return $this->newPivotQuery()->whereIn($this->relatedPivotKey, $this->parseIds($id)); } /** * Create a new query builder for the pivot table. * * @return \Illuminate\Database\Query\Builder */ public function newPivotQuery() { $query = $this->newPivotStatement(); foreach ($this->pivotWheres as $arguments) { $query->where(...$arguments); } foreach ($this->pivotWhereIns as $arguments) { $query->whereIn(...$arguments); } foreach ($this->pivotWhereNulls as $arguments) { $query->whereNull(...$arguments); } return $query->where($this->getQualifiedForeignPivotKeyName(), $this->parent->{$this->parentKey}); } /** * Set the columns on the pivot table to retrieve. * * @param array|mixed $columns * @return $this */ public function withPivot($columns) { $this->pivotColumns = array_merge( $this->pivotColumns, is_array($columns) ? $columns : func_get_args() ); return $this; } /** * Get all of the IDs from the given mixed value. * * @param mixed $value * @return array */ protected function parseIds($value) { if ($value instanceof Model) { return [$value->{$this->relatedKey}]; } if ($value instanceof Collection) { return $value->pluck($this->relatedKey)->all(); } if ($value instanceof BaseCollection) { return $value->toArray(); } return (array) $value; } /** * Get the ID from the given mixed value. * * @param mixed $value * @return mixed */ protected function parseId($value) { return $value instanceof Model ? $value->{$this->relatedKey} : $value; } /** * Cast the given keys to integers if they are numeric and string otherwise. * * @param array $keys * @return array */ protected function castKeys(array $keys) { return array_map(function ($v) { return $this->castKey($v); }, $keys); } /** * Cast the given key to convert to primary key type. * * @param mixed $key * @return mixed */ protected function castKey($key) { return $this->getTypeSwapValue( $this->related->getKeyType(), $key ); } /** * Cast the given pivot attributes. * * @param array $attributes * @return array */ protected function castAttributes($attributes) { return $this->using ? $this->newPivot()->fill($attributes)->getAttributes() : $attributes; } /** * Converts a given value to a given type value. * * @param string $type * @param mixed $value * @return mixed */ protected function getTypeSwapValue($type, $value) { return match (strtolower($type)) { 'int', 'integer' => (int) $value, 'real', 'float', 'double' => (float) $value, 'string' => (string) $value, default => $value, }; } }
194163
<?php namespace Illuminate\Database\Eloquent\Casts; class Attribute { /** * The attribute accessor. * * @var callable */ public $get; /** * The attribute mutator. * * @var callable */ public $set; /** * Indicates if caching is enabled for this attribute. * * @var bool */ public $withCaching = false; /** * Indicates if caching of objects is enabled for this attribute. * * @var bool */ public $withObjectCaching = true; /** * Create a new attribute accessor / mutator. * * @param callable|null $get * @param callable|null $set * @return void */ public function __construct(?callable $get = null, ?callable $set = null) { $this->get = $get; $this->set = $set; } /** * Create a new attribute accessor / mutator. * * @param callable|null $get * @param callable|null $set * @return static */ public static function make(?callable $get = null, ?callable $set = null): static { return new static($get, $set); } /** * Create a new attribute accessor. * * @param callable $get * @return static */ public static function get(callable $get) { return new static($get); } /** * Create a new attribute mutator. * * @param callable $set * @return static */ public static function set(callable $set) { return new static(null, $set); } /** * Disable object caching for the attribute. * * @return static */ public function withoutObjectCaching() { $this->withObjectCaching = false; return $this; } /** * Enable caching for the attribute. * * @return static */ public function shouldCache() { $this->withCaching = true; return $this; } }
194167
<?php namespace Illuminate\Database\Eloquent\Casts; use Illuminate\Contracts\Database\Eloquent\Castable; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Support\Collection; use InvalidArgumentException; class AsCollection implements Castable { /** * Get the caster class to use when casting from / to this cast target. * * @param array $arguments * @return \Illuminate\Contracts\Database\Eloquent\CastsAttributes<\Illuminate\Support\Collection<array-key, mixed>, iterable> */ public static function castUsing(array $arguments) { return new class($arguments) implements CastsAttributes { public function __construct(protected array $arguments) { } public function get($model, $key, $value, $attributes) { if (! isset($attributes[$key])) { return; } $data = Json::decode($attributes[$key]); $collectionClass = $this->arguments[0] ?? Collection::class; if (! is_a($collectionClass, Collection::class, true)) { throw new InvalidArgumentException('The provided class must extend ['.Collection::class.'].'); } return is_array($data) ? new $collectionClass($data) : null; } public function set($model, $key, $value, $attributes) { return [$key => Json::encode($value)]; } }; } /** * Specify the collection for the cast. * * @param class-string $class * @return string */ public static function using($class) { return static::class.':'.$class; } }
194186
trait QueriesRelationships { /** * Add a relationship count / exists condition to the query. * * @param \Illuminate\Database\Eloquent\Relations\Relation<*, *, *>|string $relation * @param string $operator * @param int $count * @param string $boolean * @param \Closure|null $callback * @return $this * * @throws \RuntimeException */ public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', ?Closure $callback = null) { if (is_string($relation)) { if (str_contains($relation, '.')) { return $this->hasNested($relation, $operator, $count, $boolean, $callback); } $relation = $this->getRelationWithoutConstraints($relation); } if ($relation instanceof MorphTo) { return $this->hasMorph($relation, ['*'], $operator, $count, $boolean, $callback); } // If we only need to check for the existence of the relation, then we can optimize // the subquery to only run a "where exists" clause instead of this full "count" // clause. This will make these queries run much faster compared with a count. $method = $this->canUseExistsForExistenceCheck($operator, $count) ? 'getRelationExistenceQuery' : 'getRelationExistenceCountQuery'; $hasQuery = $relation->{$method}( $relation->getRelated()->newQueryWithoutRelationships(), $this ); // Next we will call any given callback as an "anonymous" scope so they can get the // proper logical grouping of the where clauses if needed by this Eloquent query // builder. Then, we will be ready to finalize and return this query instance. if ($callback) { $hasQuery->callScope($callback); } return $this->addHasWhere( $hasQuery, $relation, $operator, $count, $boolean ); } /** * Add nested relationship count / exists conditions to the query. * * Sets up recursive call to whereHas until we finish the nested relation. * * @param string $relations * @param string $operator * @param int $count * @param string $boolean * @param \Closure|null $callback * @return $this */ protected function hasNested($relations, $operator = '>=', $count = 1, $boolean = 'and', $callback = null) { $relations = explode('.', $relations); $doesntHave = $operator === '<' && $count === 1; if ($doesntHave) { $operator = '>='; $count = 1; } $closure = function ($q) use (&$closure, &$relations, $operator, $count, $callback) { // In order to nest "has", we need to add count relation constraints on the // callback Closure. We'll do this by simply passing the Closure its own // reference to itself so it calls itself recursively on each segment. count($relations) > 1 ? $q->whereHas(array_shift($relations), $closure) : $q->has(array_shift($relations), $operator, $count, 'and', $callback); }; return $this->has(array_shift($relations), $doesntHave ? '<' : '>=', 1, $boolean, $closure); } /** * Add a relationship count / exists condition to the query with an "or". * * @param \Illuminate\Database\Eloquent\Relations\Relation<*, *, *>|string $relation * @param string $operator * @param int $count * @return $this */ public function orHas($relation, $operator = '>=', $count = 1) { return $this->has($relation, $operator, $count, 'or'); } /** * Add a relationship count / exists condition to the query. * * @param \Illuminate\Database\Eloquent\Relations\Relation<*, *, *>|string $relation * @param string $boolean * @param \Closure|null $callback * @return $this */ public function doesntHave($relation, $boolean = 'and', ?Closure $callback = null) { return $this->has($relation, '<', 1, $boolean, $callback); } /** * Add a relationship count / exists condition to the query with an "or". * * @param \Illuminate\Database\Eloquent\Relations\Relation<*, *, *>|string $relation * @return $this */ public function orDoesntHave($relation) { return $this->doesntHave($relation, 'or'); } /** * Add a relationship count / exists condition to the query with where clauses. * * @param \Illuminate\Database\Eloquent\Relations\Relation<*, *, *>|string $relation * @param \Closure|null $callback * @param string $operator * @param int $count * @return $this */ public function whereHas($relation, ?Closure $callback = null, $operator = '>=', $count = 1) { return $this->has($relation, $operator, $count, 'and', $callback); } /** * Add a relationship count / exists condition to the query with where clauses. * * Also load the relationship with same condition. * * @param \Illuminate\Database\Eloquent\Relations\Relation<*, *, *>|string $relation * @param \Closure|null $callback * @param string $operator * @param int $count * @return $this */ public function withWhereHas($relation, ?Closure $callback = null, $operator = '>=', $count = 1) { return $this->whereHas(Str::before($relation, ':'), $callback, $operator, $count) ->with($callback ? [$relation => fn ($query) => $callback($query)] : $relation); } /** * Add a relationship count / exists condition to the query with where clauses and an "or". * * @param \Illuminate\Database\Eloquent\Relations\Relation<*, *, *>|string $relation * @param \Closure|null $callback * @param string $operator * @param int $count * @return $this */ public function orWhereHas($relation, ?Closure $callback = null, $operator = '>=', $count = 1) { return $this->has($relation, $operator, $count, 'or', $callback); } /** * Add a relationship count / exists condition to the query with where clauses. * * @param \Illuminate\Database\Eloquent\Relations\Relation<*, *, *>|string $relation * @param \Closure|null $callback * @return $this */ public function whereDoesntHave($relation, ?Closure $callback = null) { return $this->doesntHave($relation, 'and', $callback); } /** * Add a relationship count / exists condition to the query with where clauses and an "or". * * @param \Illuminate\Database\Eloquent\Relations\Relation<*, *, *>|string $relation * @param \Closure|null $callback * @return $this */ public function orWhereDoesntHave($relation, ?Closure $callback = null) { return $this->doesntHave($relation, 'or', $callback); } /** * Add a polymorphic relationship count / exists condition to the query. * * @param \Illuminate\Database\Eloquent\Relations\MorphTo<*, *>|string $relation * @param string|array $types * @param string $operator * @param int $count * @param string $boolean * @param \Closure|null $callback * @return $this */
194188
/** * Add a polymorphic relationship condition to the query with a where clause. * * @param \Illuminate\Database\Eloquent\Relations\MorphTo<*, *>|string $relation * @param string|array $types * @param \Closure|string|array|\Illuminate\Contracts\Database\Query\Expression $column * @param mixed $operator * @param mixed $value * @return $this */ public function whereMorphRelation($relation, $types, $column, $operator = null, $value = null) { return $this->whereHasMorph($relation, $types, function ($query) use ($column, $operator, $value) { $query->where($column, $operator, $value); }); } /** * Add a polymorphic relationship condition to the query with an "or where" clause. * * @param \Illuminate\Database\Eloquent\Relations\MorphTo<*, *>|string $relation * @param string|array $types * @param \Closure|string|array|\Illuminate\Contracts\Database\Query\Expression $column * @param mixed $operator * @param mixed $value * @return $this */ public function orWhereMorphRelation($relation, $types, $column, $operator = null, $value = null) { return $this->orWhereHasMorph($relation, $types, function ($query) use ($column, $operator, $value) { $query->where($column, $operator, $value); }); } /** * Add a morph-to relationship condition to the query. * * @param \Illuminate\Database\Eloquent\Relations\MorphTo<*, *>|string $relation * @param \Illuminate\Database\Eloquent\Model|string|null $model * @return $this */ public function whereMorphedTo($relation, $model, $boolean = 'and') { if (is_string($relation)) { $relation = $this->getRelationWithoutConstraints($relation); } if (is_null($model)) { return $this->whereNull($relation->qualifyColumn($relation->getMorphType()), $boolean); } if (is_string($model)) { $morphMap = Relation::morphMap(); if (! empty($morphMap) && in_array($model, $morphMap)) { $model = array_search($model, $morphMap, true); } return $this->where($relation->qualifyColumn($relation->getMorphType()), $model, null, $boolean); } return $this->where(function ($query) use ($relation, $model) { $query->where($relation->qualifyColumn($relation->getMorphType()), $model->getMorphClass()) ->where($relation->qualifyColumn($relation->getForeignKeyName()), $model->getKey()); }, null, null, $boolean); } /** * Add a not morph-to relationship condition to the query. * * @param \Illuminate\Database\Eloquent\Relations\MorphTo<*, *>|string $relation * @param \Illuminate\Database\Eloquent\Model|string $model * @return $this */ public function whereNotMorphedTo($relation, $model, $boolean = 'and') { if (is_string($relation)) { $relation = $this->getRelationWithoutConstraints($relation); } if (is_string($model)) { $morphMap = Relation::morphMap(); if (! empty($morphMap) && in_array($model, $morphMap)) { $model = array_search($model, $morphMap, true); } return $this->whereNot($relation->qualifyColumn($relation->getMorphType()), '<=>', $model, $boolean); } return $this->whereNot(function ($query) use ($relation, $model) { $query->where($relation->qualifyColumn($relation->getMorphType()), '<=>', $model->getMorphClass()) ->where($relation->qualifyColumn($relation->getForeignKeyName()), '<=>', $model->getKey()); }, null, null, $boolean); } /** * Add a morph-to relationship condition to the query with an "or where" clause. * * @param \Illuminate\Database\Eloquent\Relations\MorphTo<*, *>|string $relation * @param \Illuminate\Database\Eloquent\Model|string|null $model * @return $this */ public function orWhereMorphedTo($relation, $model) { return $this->whereMorphedTo($relation, $model, 'or'); } /** * Add a not morph-to relationship condition to the query with an "or where" clause. * * @param \Illuminate\Database\Eloquent\Relations\MorphTo<*, *>|string $relation * @param \Illuminate\Database\Eloquent\Model|string $model * @return $this */ public function orWhereNotMorphedTo($relation, $model) { return $this->whereNotMorphedTo($relation, $model, 'or'); } /** * Add a "belongs to" relationship where clause to the query. * * @param \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model> $related * @param string|null $relationshipName * @param string $boolean * @return $this * * @throws \Illuminate\Database\Eloquent\RelationNotFoundException */ public function whereBelongsTo($related, $relationshipName = null, $boolean = 'and') { if (! $related instanceof Collection) { $relatedCollection = $related->newCollection([$related]); } else { $relatedCollection = $related; $related = $relatedCollection->first(); } if ($relatedCollection->isEmpty()) { throw new InvalidArgumentException('Collection given to whereBelongsTo method may not be empty.'); } if ($relationshipName === null) { $relationshipName = Str::camel(class_basename($related)); } try { $relationship = $this->model->{$relationshipName}(); } catch (BadMethodCallException) { throw RelationNotFoundException::make($this->model, $relationshipName); } if (! $relationship instanceof BelongsTo) { throw RelationNotFoundException::make($this->model, $relationshipName, BelongsTo::class); } $this->whereIn( $relationship->getQualifiedForeignKeyName(), $relatedCollection->pluck($relationship->getOwnerKeyName())->toArray(), $boolean, ); return $this; } /** * Add a "BelongsTo" relationship with an "or where" clause to the query. * * @param \Illuminate\Database\Eloquent\Model $related * @param string|null $relationshipName * @return $this * * @throws \RuntimeException */ public function orWhereBelongsTo($related, $relationshipName = null) { return $this->whereBelongsTo($related, $relationshipName, 'or'); } /** * Add subselect queries to include an aggregate value for a relationship. * * @param mixed $relations * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param string $function * @return $this */
194196
protected function newBelongsToMany(Builder $query, Model $parent, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName = null) { return new BelongsToMany($query, $parent, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName); } /** * Define a polymorphic many-to-many relationship. * * @template TRelatedModel of \Illuminate\Database\Eloquent\Model * * @param class-string<TRelatedModel> $related * @param string $name * @param string|null $table * @param string|null $foreignPivotKey * @param string|null $relatedPivotKey * @param string|null $parentKey * @param string|null $relatedKey * @param string|null $relation * @param bool $inverse * @return \Illuminate\Database\Eloquent\Relations\MorphToMany<TRelatedModel, $this> */ public function morphToMany($related, $name, $table = null, $foreignPivotKey = null, $relatedPivotKey = null, $parentKey = null, $relatedKey = null, $relation = null, $inverse = false) { $relation = $relation ?: $this->guessBelongsToManyRelation(); // First, we will need to determine the foreign key and "other key" for the // relationship. Once we have determined the keys we will make the query // instances, as well as the relationship instances we need for these. $instance = $this->newRelatedInstance($related); $foreignPivotKey = $foreignPivotKey ?: $name.'_id'; $relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey(); // Now we're ready to create a new query builder for the related model and // the relationship instances for this relation. This relation will set // appropriate query constraints then entirely manage the hydrations. if (! $table) { $words = preg_split('/(_)/u', $name, -1, PREG_SPLIT_DELIM_CAPTURE); $lastWord = array_pop($words); $table = implode('', $words).Str::plural($lastWord); } return $this->newMorphToMany( $instance->newQuery(), $this, $name, $table, $foreignPivotKey, $relatedPivotKey, $parentKey ?: $this->getKeyName(), $relatedKey ?: $instance->getKeyName(), $relation, $inverse ); } /** * Instantiate a new MorphToMany relationship. * * @template TRelatedModel of \Illuminate\Database\Eloquent\Model * @template TDeclaringModel of \Illuminate\Database\Eloquent\Model * * @param \Illuminate\Database\Eloquent\Builder<TRelatedModel> $query * @param TDeclaringModel $parent * @param string $name * @param string $table * @param string $foreignPivotKey * @param string $relatedPivotKey * @param string $parentKey * @param string $relatedKey * @param string|null $relationName * @param bool $inverse * @return \Illuminate\Database\Eloquent\Relations\MorphToMany<TRelatedModel, TDeclaringModel> */ protected function newMorphToMany(Builder $query, Model $parent, $name, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName = null, $inverse = false) { return new MorphToMany($query, $parent, $name, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName, $inverse); } /** * Define a polymorphic, inverse many-to-many relationship. * * @template TRelatedModel of \Illuminate\Database\Eloquent\Model * * @param class-string<TRelatedModel> $related * @param string $name * @param string|null $table * @param string|null $foreignPivotKey * @param string|null $relatedPivotKey * @param string|null $parentKey * @param string|null $relatedKey * @param string|null $relation * @return \Illuminate\Database\Eloquent\Relations\MorphToMany<TRelatedModel, $this> */ public function morphedByMany($related, $name, $table = null, $foreignPivotKey = null, $relatedPivotKey = null, $parentKey = null, $relatedKey = null, $relation = null) { $foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey(); // For the inverse of the polymorphic many-to-many relations, we will change // the way we determine the foreign and other keys, as it is the opposite // of the morph-to-many method since we're figuring out these inverses. $relatedPivotKey = $relatedPivotKey ?: $name.'_id'; return $this->morphToMany( $related, $name, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relation, true ); } /** * Get the relationship name of the belongsToMany relationship. * * @return string|null */ protected function guessBelongsToManyRelation() { $caller = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), function ($trace) { return ! in_array( $trace['function'], array_merge(static::$manyMethods, ['guessBelongsToManyRelation']) ); }); return ! is_null($caller) ? $caller['function'] : null; } /** * Get the joining table name for a many-to-many relation. * * @param string $related * @param \Illuminate\Database\Eloquent\Model|null $instance * @return string */ public function joiningTable($related, $instance = null) { // The joining table name, by convention, is simply the snake cased models // sorted alphabetically and concatenated with an underscore, so we can // just sort the models and join them together to get the table name. $segments = [ $instance ? $instance->joiningTableSegment() : Str::snake(class_basename($related)), $this->joiningTableSegment(), ]; // Now that we have the model names in an array we can just sort them and // use the implode function to join them together with an underscores, // which is typically used by convention within the database system. sort($segments); return strtolower(implode('_', $segments)); } /** * Get this model's half of the intermediate table name for belongsToMany relationships. * * @return string */ public function joiningTableSegment() { return Str::snake(class_basename($this)); } /** * Determine if the model touches a given relation. * * @param string $relation * @return bool */ public function touches($relation) { return in_array($relation, $this->getTouchedRelations()); } /** * Touch the owning relations of the model. * * @return void */ public function touchOwners() { $this->withoutRecursion(function () { foreach ($this->getTouchedRelations() as $relation) { $this->$relation()->touch(); if ($this->$relation instanceof self) { $this->$relation->fireModelEvent('saved', false); $this->$relation->touchOwners(); } elseif ($this->$relation instanceof Collection) { $this->$relation->each->touchOwners(); } } }); } /** * Get the polymorphic relationship columns. * * @param string $name * @param string $type * @param string $id * @return array */ protected function getMorphs($name, $type, $id) { return [$type ?: $name.'_type', $id ?: $name.'_id']; } /** * Get the class name for polymorphic relations. * * @return string */
194198
<?php namespace Illuminate\Database\Eloquent\Concerns; use BackedEnum; use Brick\Math\BigDecimal; use Brick\Math\Exception\MathException as BrickMathException; use Brick\Math\RoundingMode; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use DateTimeImmutable; use DateTimeInterface; use Illuminate\Contracts\Database\Eloquent\Castable; use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Database\Eloquent\Casts\AsArrayObject; use Illuminate\Database\Eloquent\Casts\AsCollection; use Illuminate\Database\Eloquent\Casts\AsEncryptedArrayObject; use Illuminate\Database\Eloquent\Casts\AsEncryptedCollection; use Illuminate\Database\Eloquent\Casts\AsEnumArrayObject; use Illuminate\Database\Eloquent\Casts\AsEnumCollection; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Casts\Json; use Illuminate\Database\Eloquent\InvalidCastException; use Illuminate\Database\Eloquent\JsonEncodingException; use Illuminate\Database\Eloquent\MissingAttributeException; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\LazyLoadingViolationException; use Illuminate\Support\Arr; use Illuminate\Support\Carbon; use Illuminate\Support\Collection as BaseCollection; use Illuminate\Support\Exceptions\MathException; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; use InvalidArgumentException; use LogicException; use ReflectionClass; use ReflectionMethod; use ReflectionNamedType; use RuntimeException; use ValueError; use function Illuminate\Support\enum_value;
194199
trait HasAttributes { /** * The model's attributes. * * @var array */ protected $attributes = []; /** * The model attribute's original state. * * @var array */ protected $original = []; /** * The changed model attributes. * * @var array */ protected $changes = []; /** * The attributes that should be cast. * * @var array */ protected $casts = []; /** * The attributes that have been cast using custom classes. * * @var array */ protected $classCastCache = []; /** * The attributes that have been cast using "Attribute" return type mutators. * * @var array */ protected $attributeCastCache = []; /** * The built-in, primitive cast types supported by Eloquent. * * @var string[] */ protected static $primitiveCastTypes = [ 'array', 'bool', 'boolean', 'collection', 'custom_datetime', 'date', 'datetime', 'decimal', 'double', 'encrypted', 'encrypted:array', 'encrypted:collection', 'encrypted:json', 'encrypted:object', 'float', 'hashed', 'immutable_date', 'immutable_datetime', 'immutable_custom_datetime', 'int', 'integer', 'json', 'object', 'real', 'string', 'timestamp', ]; /** * The storage format of the model's date columns. * * @var string|null */ protected $dateFormat; /** * The accessors to append to the model's array form. * * @var array */ protected $appends = []; /** * Indicates whether attributes are snake cased on arrays. * * @var bool */ public static $snakeAttributes = true; /** * The cache of the mutated attributes for each class. * * @var array */ protected static $mutatorCache = []; /** * The cache of the "Attribute" return type marked mutated attributes for each class. * * @var array */ protected static $attributeMutatorCache = []; /** * The cache of the "Attribute" return type marked mutated, gettable attributes for each class. * * @var array */ protected static $getAttributeMutatorCache = []; /** * The cache of the "Attribute" return type marked mutated, settable attributes for each class. * * @var array */ protected static $setAttributeMutatorCache = []; /** * The cache of the converted cast types. * * @var array */ protected static $castTypeCache = []; /** * The encrypter instance that is used to encrypt attributes. * * @var \Illuminate\Contracts\Encryption\Encrypter|null */ public static $encrypter; /** * Initialize the trait. * * @return void */ protected function initializeHasAttributes() { $this->casts = $this->ensureCastsAreStringValues( array_merge($this->casts, $this->casts()), ); } /** * Convert the model's attributes to an array. * * @return array */ public function attributesToArray() { // If an attribute is a date, we will cast it to a string after converting it // to a DateTime / Carbon instance. This is so we will get some consistent // formatting while accessing attributes vs. arraying / JSONing a model. $attributes = $this->addDateAttributesToArray( $attributes = $this->getArrayableAttributes() ); $attributes = $this->addMutatedAttributesToArray( $attributes, $mutatedAttributes = $this->getMutatedAttributes() ); // Next we will handle any casts that have been setup for this model and cast // the values to their appropriate type. If the attribute has a mutator we // will not perform the cast on those attributes to avoid any confusion. $attributes = $this->addCastAttributesToArray( $attributes, $mutatedAttributes ); // Here we will grab all of the appended, calculated attributes to this model // as these attributes are not really in the attributes array, but are run // when we need to array or JSON the model for convenience to the coder. foreach ($this->getArrayableAppends() as $key) { $attributes[$key] = $this->mutateAttributeForArray($key, null); } return $attributes; } /** * Add the date attributes to the attributes array. * * @param array $attributes * @return array */ protected function addDateAttributesToArray(array $attributes) { foreach ($this->getDates() as $key) { if (! isset($attributes[$key])) { continue; } $attributes[$key] = $this->serializeDate( $this->asDateTime($attributes[$key]) ); } return $attributes; } /** * Add the mutated attributes to the attributes array. * * @param array $attributes * @param array $mutatedAttributes * @return array */ protected function addMutatedAttributesToArray(array $attributes, array $mutatedAttributes) { foreach ($mutatedAttributes as $key) { // We want to spin through all the mutated attributes for this model and call // the mutator for the attribute. We cache off every mutated attributes so // we don't have to constantly check on attributes that actually change. if (! array_key_exists($key, $attributes)) { continue; } // Next, we will call the mutator for this attribute so that we can get these // mutated attribute's actual values. After we finish mutating each of the // attributes we will return this final array of the mutated attributes. $attributes[$key] = $this->mutateAttributeForArray( $key, $attributes[$key] ); } return $attributes; } /** * Add the casted attributes to the attributes array. * * @param array $attributes * @param array $mutatedAttributes * @return array */ protected function addCastAttributesToArray(array $attributes, array $mutatedAttributes) { foreach ($this->getCasts() as $key => $value) { if (! array_key_exists($key, $attributes) || in_array($key, $mutatedAttributes)) { continue; } // Here we will cast the attribute. Then, if the cast is a date or datetime cast // then we will serialize the date for the array. This will convert the dates // to strings based on the date format specified for these Eloquent models. $attributes[$key] = $this->castAttribute( $key, $attributes[$key] ); // If the attribute cast was a date or a datetime, we will serialize the date as // a string. This allows the developers to customize how dates are serialized // into an array without affecting how they are persisted into the storage. if (isset($attributes[$key]) && in_array($value, ['date', 'datetime', 'immutable_date', 'immutable_datetime'])) { $attributes[$key] = $this->serializeDate($attributes[$key]); } if (isset($attributes[$key]) && ($this->isCustomDateTimeCast($value) || $this->isImmutableCustomDateTimeCast($value))) { $attributes[$key] = $attributes[$key]->format(explode(':', $value, 2)[1]); } if ($attributes[$key] instanceof DateTimeInterface && $this->isClassCastable($key)) { $attributes[$key] = $this->serializeDate($attributes[$key]); } if (isset($attributes[$key]) && $this->isClassSerializable($key)) { $attributes[$key] = $this->serializeClassCastableAttribute($key, $attributes[$key]); } if ($this->isEnumCastable($key) && (! ($attributes[$key] ?? null) instanceof Arrayable)) { $attributes[$key] = isset($attributes[$key]) ? $this->getStorableEnumValue($this->getCasts()[$key], $attributes[$key]) : null; } if ($attributes[$key] instanceof Arrayable) { $attributes[$key] = $attributes[$key]->toArray(); } } return $attributes; } /** * Get an attribute array of all arrayable attributes. * * @return array */ protected function getArrayableAttributes() { return $this->getArrayableItems($this->getAttributes()); }
194200
/** * Get all of the appendable values that are arrayable. * * @return array */ protected function getArrayableAppends() { if (! count($this->appends)) { return []; } return $this->getArrayableItems( array_combine($this->appends, $this->appends) ); } /** * Get the model's relationships in array form. * * @return array */ public function relationsToArray() { $attributes = []; foreach ($this->getArrayableRelations() as $key => $value) { // If the values implement the Arrayable interface we can just call this // toArray method on the instances which will convert both models and // collections to their proper array form and we'll set the values. if ($value instanceof Arrayable) { $relation = $value->toArray(); } // If the value is null, we'll still go ahead and set it in this list of // attributes, since null is used to represent empty relationships if // it has a has one or belongs to type relationships on the models. elseif (is_null($value)) { $relation = $value; } // If the relationships snake-casing is enabled, we will snake case this // key so that the relation attribute is snake cased in this returned // array to the developers, making this consistent with attributes. if (static::$snakeAttributes) { $key = Str::snake($key); } // If the relation value has been set, we will set it on this attributes // list for returning. If it was not arrayable or null, we'll not set // the value on the array because it is some type of invalid value. if (array_key_exists('relation', get_defined_vars())) { // check if $relation is in scope (could be null) $attributes[$key] = $relation ?? null; } unset($relation); } return $attributes; } /** * Get an attribute array of all arrayable relations. * * @return array */ protected function getArrayableRelations() { return $this->getArrayableItems($this->relations); } /** * Get an attribute array of all arrayable values. * * @param array $values * @return array */ protected function getArrayableItems(array $values) { if (count($this->getVisible()) > 0) { $values = array_intersect_key($values, array_flip($this->getVisible())); } if (count($this->getHidden()) > 0) { $values = array_diff_key($values, array_flip($this->getHidden())); } return $values; } /** * Determine whether an attribute exists on the model. * * @param string $key * @return bool */ public function hasAttribute($key) { if (! $key) { return false; } return array_key_exists($key, $this->attributes) || array_key_exists($key, $this->casts) || $this->hasGetMutator($key) || $this->hasAttributeMutator($key) || $this->isClassCastable($key); } /** * Get an attribute from the model. * * @param string $key * @return mixed */ public function getAttribute($key) { if (! $key) { return; } // If the attribute exists in the attribute array or has a "get" mutator we will // get the attribute's value. Otherwise, we will proceed as if the developers // are asking for a relationship's value. This covers both types of values. if ($this->hasAttribute($key)) { return $this->getAttributeValue($key); } // Here we will determine if the model base class itself contains this given key // since we don't want to treat any of those methods as relationships because // they are all intended as helper methods and none of these are relations. if (method_exists(self::class, $key)) { return $this->throwMissingAttributeExceptionIfApplicable($key); } return $this->isRelation($key) || $this->relationLoaded($key) ? $this->getRelationValue($key) : $this->throwMissingAttributeExceptionIfApplicable($key); } /** * Either throw a missing attribute exception or return null depending on Eloquent's configuration. * * @param string $key * @return null * * @throws \Illuminate\Database\Eloquent\MissingAttributeException */ protected function throwMissingAttributeExceptionIfApplicable($key) { if ($this->exists && ! $this->wasRecentlyCreated && static::preventsAccessingMissingAttributes()) { if (isset(static::$missingAttributeViolationCallback)) { return call_user_func(static::$missingAttributeViolationCallback, $this, $key); } throw new MissingAttributeException($this, $key); } return null; } /** * Get a plain attribute (not a relationship). * * @param string $key * @return mixed */ public function getAttributeValue($key) { return $this->transformModelValue($key, $this->getAttributeFromArray($key)); } /** * Get an attribute from the $attributes array. * * @param string $key * @return mixed */ protected function getAttributeFromArray($key) { return $this->getAttributes()[$key] ?? null; } /** * Get a relationship. * * @param string $key * @return mixed */ public function getRelationValue($key) { // If the key already exists in the relationships array, it just means the // relationship has already been loaded, so we'll just return it out of // here because there is no need to query within the relations twice. if ($this->relationLoaded($key)) { return $this->relations[$key]; } if (! $this->isRelation($key)) { return; } if ($this->preventsLazyLoading) { $this->handleLazyLoadingViolation($key); } // If the "attribute" exists as a method on the model, we will just assume // it is a relationship and will load and return results from the query // and hydrate the relationship's value on the "relationships" array. return $this->getRelationshipFromMethod($key); } /** * Determine if the given key is a relationship method on the model. * * @param string $key * @return bool */ public function isRelation($key) { if ($this->hasAttributeMutator($key)) { return false; } return method_exists($this, $key) || $this->relationResolver(static::class, $key); } /** * Handle a lazy loading violation. * * @param string $key * @return mixed */ protected function handleLazyLoadingViolation($key) { if (isset(static::$lazyLoadingViolationCallback)) { return call_user_func(static::$lazyLoadingViolationCallback, $this, $key); } if (! $this->exists || $this->wasRecentlyCreated) { return; } throw new LazyLoadingViolationException($this, $key); } /** * Get a relationship value from a method. * * @param string $method * @return mixed * * @throws \LogicException */ protected function getRelationshipFromMethod($method) { $relation = $this->$method(); if (! $relation instanceof Relation) { if (is_null($relation)) { throw new LogicException(sprintf( '%s::%s must return a relationship instance, but "null" was returned. Was the "return" keyword used?', static::class, $method )); } throw new LogicException(sprintf( '%s::%s must return a relationship instance.', static::class, $method )); } return tap($relation->getResults(), function ($results) use ($method) { $this->setRelation($method, $results); }); } /** * Determine if a get mutator exists for an attribute. * * @param string $key * @return bool */ public function hasGetMutator($key) { return method_exists($this, 'get'.Str::studly($key).'Attribute'); }
194202
protected function getEnumCastableAttributeValue($key, $value) { if (is_null($value)) { return; } $castType = $this->getCasts()[$key]; if ($value instanceof $castType) { return $value; } return $this->getEnumCaseFromValue($castType, $value); } /** * Get the type of cast for a model attribute. * * @param string $key * @return string */ protected function getCastType($key) { $castType = $this->getCasts()[$key]; if (isset(static::$castTypeCache[$castType])) { return static::$castTypeCache[$castType]; } if ($this->isCustomDateTimeCast($castType)) { $convertedCastType = 'custom_datetime'; } elseif ($this->isImmutableCustomDateTimeCast($castType)) { $convertedCastType = 'immutable_custom_datetime'; } elseif ($this->isDecimalCast($castType)) { $convertedCastType = 'decimal'; } elseif (class_exists($castType)) { $convertedCastType = $castType; } else { $convertedCastType = trim(strtolower($castType)); } return static::$castTypeCache[$castType] = $convertedCastType; } /** * Increment or decrement the given attribute using the custom cast class. * * @param string $method * @param string $key * @param mixed $value * @return mixed */ protected function deviateClassCastableAttribute($method, $key, $value) { return $this->resolveCasterClass($key)->{$method}( $this, $key, $value, $this->attributes ); } /** * Serialize the given attribute using the custom cast class. * * @param string $key * @param mixed $value * @return mixed */ protected function serializeClassCastableAttribute($key, $value) { return $this->resolveCasterClass($key)->serialize( $this, $key, $value, $this->attributes ); } /** * Determine if the cast type is a custom date time cast. * * @param string $cast * @return bool */ protected function isCustomDateTimeCast($cast) { return str_starts_with($cast, 'date:') || str_starts_with($cast, 'datetime:'); } /** * Determine if the cast type is an immutable custom date time cast. * * @param string $cast * @return bool */ protected function isImmutableCustomDateTimeCast($cast) { return str_starts_with($cast, 'immutable_date:') || str_starts_with($cast, 'immutable_datetime:'); } /** * Determine if the cast type is a decimal cast. * * @param string $cast * @return bool */ protected function isDecimalCast($cast) { return str_starts_with($cast, 'decimal:'); } /** * Set a given attribute on the model. * * @param string $key * @param mixed $value * @return mixed */ public function setAttribute($key, $value) { // First we will check for the presence of a mutator for the set operation // which simply lets the developers tweak the attribute as it is set on // this model, such as "json_encoding" a listing of data for storage. if ($this->hasSetMutator($key)) { return $this->setMutatedAttributeValue($key, $value); } elseif ($this->hasAttributeSetMutator($key)) { return $this->setAttributeMarkedMutatedAttributeValue($key, $value); } // If an attribute is listed as a "date", we'll convert it from a DateTime // instance into a form proper for storage on the database tables using // the connection grammar's date format. We will auto set the values. elseif (! is_null($value) && $this->isDateAttribute($key)) { $value = $this->fromDateTime($value); } if ($this->isEnumCastable($key)) { $this->setEnumCastableAttribute($key, $value); return $this; } if ($this->isClassCastable($key)) { $this->setClassCastableAttribute($key, $value); return $this; } if (! is_null($value) && $this->isJsonCastable($key)) { $value = $this->castAttributeAsJson($key, $value); } // If this attribute contains a JSON ->, we'll set the proper value in the // attribute's underlying array. This takes care of properly nesting an // attribute in the array's value in the case of deeply nested items. if (str_contains($key, '->')) { return $this->fillJsonAttribute($key, $value); } if (! is_null($value) && $this->isEncryptedCastable($key)) { $value = $this->castAttributeAsEncryptedString($key, $value); } if (! is_null($value) && $this->hasCast($key, 'hashed')) { $value = $this->castAttributeAsHashedString($key, $value); } $this->attributes[$key] = $value; return $this; } /** * Determine if a set mutator exists for an attribute. * * @param string $key * @return bool */ public function hasSetMutator($key) { return method_exists($this, 'set'.Str::studly($key).'Attribute'); } /** * Determine if an "Attribute" return type marked set mutator exists for an attribute. * * @param string $key * @return bool */ public function hasAttributeSetMutator($key) { $class = get_class($this); if (isset(static::$setAttributeMutatorCache[$class][$key])) { return static::$setAttributeMutatorCache[$class][$key]; } if (! method_exists($this, $method = Str::camel($key))) { return static::$setAttributeMutatorCache[$class][$key] = false; } $returnType = (new ReflectionMethod($this, $method))->getReturnType(); return static::$setAttributeMutatorCache[$class][$key] = $returnType instanceof ReflectionNamedType && $returnType->getName() === Attribute::class && is_callable($this->{$method}()->set); } /** * Set the value of an attribute using its mutator. * * @param string $key * @param mixed $value * @return mixed */ protected function setMutatedAttributeValue($key, $value) { return $this->{'set'.Str::studly($key).'Attribute'}($value); } /** * Set the value of a "Attribute" return type marked attribute using its mutator. * * @param string $key * @param mixed $value * @return mixed */ protected function setAttributeMarkedMutatedAttributeValue($key, $value) { $attribute = $this->{Str::camel($key)}(); $callback = $attribute->set ?: function ($value) use ($key) { $this->attributes[$key] = $value; }; $this->attributes = array_merge( $this->attributes, $this->normalizeCastClassResponse( $key, $callback($value, $this->attributes) ) ); if ($attribute->withCaching || (is_object($value) && $attribute->withObjectCaching)) { $this->attributeCastCache[$key] = $value; } else { unset($this->attributeCastCache[$key]); } return $this; } /** * Determine if the given attribute is a date or date castable. * * @param string $key * @return bool */ protected function isDateAttribute($key) { return in_array($key, $this->getDates(), true) || $this->isDateCastable($key); } /** * Set a given JSON attribute on the model. * * @param string $key * @param mixed $value * @return $this */
194204
protected function asDateTime($value) { // If this value is already a Carbon instance, we shall just return it as is. // This prevents us having to re-instantiate a Carbon instance when we know // it already is one, which wouldn't be fulfilled by the DateTime check. if ($value instanceof CarbonInterface) { return Date::instance($value); } // If the value is already a DateTime instance, we will just skip the rest of // these checks since they will be a waste of time, and hinder performance // when checking the field. We will just return the DateTime right away. if ($value instanceof DateTimeInterface) { return Date::parse( $value->format('Y-m-d H:i:s.u'), $value->getTimezone() ); } // If this value is an integer, we will assume it is a UNIX timestamp's value // and format a Carbon object from this timestamp. This allows flexibility // when defining your date fields as they might be UNIX timestamps here. if (is_numeric($value)) { return Date::createFromTimestamp($value, date_default_timezone_get()); } // If the value is in simply year, month, day format, we will instantiate the // Carbon instances from that format. Again, this provides for simple date // fields on the database, while still supporting Carbonized conversion. if ($this->isStandardDateFormat($value)) { return Date::instance(Carbon::createFromFormat('Y-m-d', $value)->startOfDay()); } $format = $this->getDateFormat(); // Finally, we will just assume this date is in the format used by default on // the database connection and use that format to create the Carbon object // that is returned back out to the developers after we convert it here. try { $date = Date::createFromFormat($format, $value); } catch (InvalidArgumentException) { $date = false; } return $date ?: Date::parse($value); } /** * Determine if the given value is a standard date format. * * @param string $value * @return bool */ protected function isStandardDateFormat($value) { return preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value); } /** * Convert a DateTime to a storable string. * * @param mixed $value * @return string|null */ public function fromDateTime($value) { return empty($value) ? $value : $this->asDateTime($value)->format( $this->getDateFormat() ); } /** * Return a timestamp as unix timestamp. * * @param mixed $value * @return int */ protected function asTimestamp($value) { return $this->asDateTime($value)->getTimestamp(); } /** * Prepare a date for array / JSON serialization. * * @param \DateTimeInterface $date * @return string */ protected function serializeDate(DateTimeInterface $date) { return $date instanceof DateTimeImmutable ? CarbonImmutable::instance($date)->toJSON() : Carbon::instance($date)->toJSON(); } /** * Get the attributes that should be converted to dates. * * @return array */ public function getDates() { return $this->usesTimestamps() ? [ $this->getCreatedAtColumn(), $this->getUpdatedAtColumn(), ] : []; } /** * Get the format for database stored dates. * * @return string */ public function getDateFormat() { return $this->dateFormat ?: $this->getConnection()->getQueryGrammar()->getDateFormat(); } /** * Set the date format used by the model. * * @param string $format * @return $this */ public function setDateFormat($format) { $this->dateFormat = $format; return $this; } /** * Determine whether an attribute should be cast to a native type. * * @param string $key * @param array|string|null $types * @return bool */ public function hasCast($key, $types = null) { if (array_key_exists($key, $this->getCasts())) { return $types ? in_array($this->getCastType($key), (array) $types, true) : true; } return false; } /** * Get the attributes that should be cast. * * @return array */ public function getCasts() { if ($this->getIncrementing()) { return array_merge([$this->getKeyName() => $this->getKeyType()], $this->casts); } return $this->casts; } /** * Get the attributes that should be cast. * * @return array<string, string> */ protected function casts() { return []; } /** * Determine whether a value is Date / DateTime castable for inbound manipulation. * * @param string $key * @return bool */ protected function isDateCastable($key) { return $this->hasCast($key, ['date', 'datetime', 'immutable_date', 'immutable_datetime']); } /** * Determine whether a value is Date / DateTime custom-castable for inbound manipulation. * * @param string $key * @return bool */ protected function isDateCastableWithCustomFormat($key) { return $this->hasCast($key, ['custom_datetime', 'immutable_custom_datetime']); } /** * Determine whether a value is JSON castable for inbound manipulation. * * @param string $key * @return bool */ protected function isJsonCastable($key) { return $this->hasCast($key, ['array', 'json', 'object', 'collection', 'encrypted:array', 'encrypted:collection', 'encrypted:json', 'encrypted:object']); } /** * Determine whether a value is an encrypted castable for inbound manipulation. * * @param string $key * @return bool */ protected function isEncryptedCastable($key) { return $this->hasCast($key, ['encrypted', 'encrypted:array', 'encrypted:collection', 'encrypted:json', 'encrypted:object']); } /** * Determine if the given key is cast using a custom class. * * @param string $key * @return bool * * @throws \Illuminate\Database\Eloquent\InvalidCastException */ protected function isClassCastable($key) { $casts = $this->getCasts(); if (! array_key_exists($key, $casts)) { return false; } $castType = $this->parseCasterClass($casts[$key]); if (in_array($castType, static::$primitiveCastTypes)) { return false; } if (class_exists($castType)) { return true; } throw new InvalidCastException($this->getModel(), $key, $castType); } /** * Determine if the given key is cast using an enum. * * @param string $key * @return bool */ protected function isEnumCastable($key) { $casts = $this->getCasts(); if (! array_key_exists($key, $casts)) { return false; } $castType = $casts[$key]; if (in_array($castType, static::$primitiveCastTypes)) { return false; } return enum_exists($castType); } /** * Determine if the key is deviable using a custom class. * * @param string $key * @return bool * * @throws \Illuminate\Database\Eloquent\InvalidCastException */ protected function isClassDeviable($key) { if (! $this->isClassCastable($key)) { return false; } $castType = $this->resolveCasterClass($key); return method_exists($castType::class, 'increment') && method_exists($castType::class, 'decrement'); } /** * Determine if the key is serializable using a custom class. * * @param string $key * @return bool * * @throws \Illuminate\Database\Eloquent\InvalidCastException */
194206
/** * Determine if any of the given attributes were changed when the model was last saved. * * @param array $changes * @param array|string|null $attributes * @return bool */ protected function hasChanges($changes, $attributes = null) { // If no specific attributes were provided, we will just see if the dirty array // already contains any attributes. If it does we will just return that this // count is greater than zero. Else, we need to check specific attributes. if (empty($attributes)) { return count($changes) > 0; } // Here we will spin through every attribute and see if this is in the array of // dirty attributes. If it is, we will return true and if we make it through // all of the attributes for the entire array we will return false at end. foreach (Arr::wrap($attributes) as $attribute) { if (array_key_exists($attribute, $changes)) { return true; } } return false; } /** * Get the attributes that have been changed since the last sync. * * @return array */ public function getDirty() { $dirty = []; foreach ($this->getAttributes() as $key => $value) { if (! $this->originalIsEquivalent($key)) { $dirty[$key] = $value; } } return $dirty; } /** * Get the attributes that have been changed since the last sync for an update operation. * * @return array */ protected function getDirtyForUpdate() { return $this->getDirty(); } /** * Get the attributes that were changed when the model was last saved. * * @return array */ public function getChanges() { return $this->changes; } /** * Determine if the new and old values for a given key are equivalent. * * @param string $key * @return bool */ public function originalIsEquivalent($key) { if (! array_key_exists($key, $this->original)) { return false; } $attribute = Arr::get($this->attributes, $key); $original = Arr::get($this->original, $key); if ($attribute === $original) { return true; } elseif (is_null($attribute)) { return false; } elseif ($this->isDateAttribute($key) || $this->isDateCastableWithCustomFormat($key)) { return $this->fromDateTime($attribute) === $this->fromDateTime($original); } elseif ($this->hasCast($key, ['object', 'collection'])) { return $this->fromJson($attribute) === $this->fromJson($original); } elseif ($this->hasCast($key, ['real', 'float', 'double'])) { if ($original === null) { return false; } return abs($this->castAttribute($key, $attribute) - $this->castAttribute($key, $original)) < PHP_FLOAT_EPSILON * 4; } elseif ($this->isEncryptedCastable($key) && ! empty(static::currentEncrypter()->getPreviousKeys())) { return false; } elseif ($this->hasCast($key, static::$primitiveCastTypes)) { return $this->castAttribute($key, $attribute) === $this->castAttribute($key, $original); } elseif ($this->isClassCastable($key) && Str::startsWith($this->getCasts()[$key], [AsArrayObject::class, AsCollection::class])) { return $this->fromJson($attribute) === $this->fromJson($original); } elseif ($this->isClassCastable($key) && Str::startsWith($this->getCasts()[$key], [AsEnumArrayObject::class, AsEnumCollection::class])) { return $this->fromJson($attribute) === $this->fromJson($original); } elseif ($this->isClassCastable($key) && $original !== null && Str::startsWith($this->getCasts()[$key], [AsEncryptedArrayObject::class, AsEncryptedCollection::class])) { if (empty(static::currentEncrypter()->getPreviousKeys())) { return $this->fromEncryptedString($attribute) === $this->fromEncryptedString($original); } return false; } return is_numeric($attribute) && is_numeric($original) && strcmp((string) $attribute, (string) $original) === 0; } /** * Transform a raw model value using mutators, casts, etc. * * @param string $key * @param mixed $value * @return mixed */ protected function transformModelValue($key, $value) { // If the attribute has a get mutator, we will call that then return what // it returns as the value, which is useful for transforming values on // retrieval from the model to a form that is more useful for usage. if ($this->hasGetMutator($key)) { return $this->mutateAttribute($key, $value); } elseif ($this->hasAttributeGetMutator($key)) { return $this->mutateAttributeMarkedAttribute($key, $value); } // If the attribute exists within the cast array, we will convert it to // an appropriate native PHP type dependent upon the associated value // given with the key in the pair. Dayle made this comment line up. if ($this->hasCast($key)) { if (static::preventsAccessingMissingAttributes() && ! array_key_exists($key, $this->attributes) && ($this->isEnumCastable($key) || in_array($this->getCastType($key), static::$primitiveCastTypes))) { $this->throwMissingAttributeExceptionIfApplicable($key); } return $this->castAttribute($key, $value); } // If the attribute is listed as a date, we will convert it to a DateTime // instance on retrieval, which makes it quite convenient to work with // date fields without having to create a mutator for each property. if ($value !== null && \in_array($key, $this->getDates(), false)) { return $this->asDateTime($value); } return $value; } /** * Append attributes to query when building a query. * * @param array|string $attributes * @return $this */ public function append($attributes) { $this->appends = array_values(array_unique( array_merge($this->appends, is_string($attributes) ? func_get_args() : $attributes) )); return $this; } /** * Get the accessors that are being appended to model arrays. * * @return array */ public function getAppends() { return $this->appends; } /** * Set the accessors to append to model arrays. * * @param array $appends * @return $this */ public function setAppends(array $appends) { $this->appends = $appends; return $this; } /** * Return whether the accessor attribute has been appended. * * @param string $attribute * @return bool */ public function hasAppended($attribute) { return in_array($attribute, $this->appends); } /** * Get the mutated attributes for a given instance. * * @return array */ public function getMutatedAttributes() { if (! isset(static::$mutatorCache[static::class])) { static::cacheMutatedAttributes($this); } return static::$mutatorCache[static::class]; } /** * Extract and cache all the mutated attributes of a class. * * @param object|string $classOrInstance * @return void */
194207
public static function cacheMutatedAttributes($classOrInstance) { $reflection = new ReflectionClass($classOrInstance); $class = $reflection->getName(); static::$getAttributeMutatorCache[$class] = collect($attributeMutatorMethods = static::getAttributeMarkedMutatorMethods($classOrInstance)) ->mapWithKeys(function ($match) { return [lcfirst(static::$snakeAttributes ? Str::snake($match) : $match) => true]; })->all(); static::$mutatorCache[$class] = collect(static::getMutatorMethods($class)) ->merge($attributeMutatorMethods) ->map(function ($match) { return lcfirst(static::$snakeAttributes ? Str::snake($match) : $match); })->all(); } /** * Get all of the attribute mutator methods. * * @param mixed $class * @return array */ protected static function getMutatorMethods($class) { preg_match_all('/(?<=^|;)get([^;]+?)Attribute(;|$)/', implode(';', get_class_methods($class)), $matches); return $matches[1]; } /** * Get all of the "Attribute" return typed attribute mutator methods. * * @param mixed $class * @return array */ protected static function getAttributeMarkedMutatorMethods($class) { $instance = is_object($class) ? $class : new $class; return collect((new ReflectionClass($instance))->getMethods())->filter(function ($method) use ($instance) { $returnType = $method->getReturnType(); if ($returnType instanceof ReflectionNamedType && $returnType->getName() === Attribute::class) { if (is_callable($method->invoke($instance)->get)) { return true; } } return false; })->map->name->values()->all(); } }
194208
<?php namespace Illuminate\Database\Eloquent\Concerns; use Closure; use Illuminate\Database\Eloquent\Attributes\ScopedBy; use Illuminate\Database\Eloquent\Scope; use Illuminate\Support\Arr; use InvalidArgumentException; use ReflectionClass; trait HasGlobalScopes { /** * Boot the has global scopes trait for a model. * * @return void */ public static function bootHasGlobalScopes() { static::addGlobalScopes(static::resolveGlobalScopeAttributes()); } /** * Resolve the global scope class names from the attributes. * * @return array */ public static function resolveGlobalScopeAttributes() { $reflectionClass = new ReflectionClass(static::class); return collect($reflectionClass->getAttributes(ScopedBy::class)) ->map(fn ($attribute) => $attribute->getArguments()) ->flatten() ->all(); } /** * Register a new global scope on the model. * * @param \Illuminate\Database\Eloquent\Scope|\Closure|string $scope * @param \Illuminate\Database\Eloquent\Scope|\Closure|null $implementation * @return mixed * * @throws \InvalidArgumentException */ public static function addGlobalScope($scope, $implementation = null) { if (is_string($scope) && ($implementation instanceof Closure || $implementation instanceof Scope)) { return static::$globalScopes[static::class][$scope] = $implementation; } elseif ($scope instanceof Closure) { return static::$globalScopes[static::class][spl_object_hash($scope)] = $scope; } elseif ($scope instanceof Scope) { return static::$globalScopes[static::class][get_class($scope)] = $scope; } elseif (is_string($scope) && class_exists($scope) && is_subclass_of($scope, Scope::class)) { return static::$globalScopes[static::class][$scope] = new $scope; } throw new InvalidArgumentException('Global scope must be an instance of Closure or Scope or be a class name of a class extending '.Scope::class); } /** * Register multiple global scopes on the model. * * @param array $scopes * @return void */ public static function addGlobalScopes(array $scopes) { foreach ($scopes as $key => $scope) { if (is_string($key)) { static::addGlobalScope($key, $scope); } else { static::addGlobalScope($scope); } } } /** * Determine if a model has a global scope. * * @param \Illuminate\Database\Eloquent\Scope|string $scope * @return bool */ public static function hasGlobalScope($scope) { return ! is_null(static::getGlobalScope($scope)); } /** * Get a global scope registered with the model. * * @param \Illuminate\Database\Eloquent\Scope|string $scope * @return \Illuminate\Database\Eloquent\Scope|\Closure|null */ public static function getGlobalScope($scope) { if (is_string($scope)) { return Arr::get(static::$globalScopes, static::class.'.'.$scope); } return Arr::get( static::$globalScopes, static::class.'.'.get_class($scope) ); } /** * Get all of the global scopes that are currently registered. * * @return array */ public static function getAllGlobalScopes() { return static::$globalScopes; } /** * Set the current global scopes. * * @param array $scopes * @return void */ public static function setAllGlobalScopes($scopes) { static::$globalScopes = $scopes; } /** * Get the global scopes for this class instance. * * @return array */ public function getGlobalScopes() { return Arr::get(static::$globalScopes, static::class, []); } }
194217
<?php namespace Illuminate\Database\Eloquent\Concerns; trait GuardsAttributes { /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = []; /** * The attributes that aren't mass assignable. * * @var array<string>|bool */ protected $guarded = ['*']; /** * Indicates if all mass assignment is enabled. * * @var bool */ protected static $unguarded = false; /** * The actual columns that exist on the database and can be guarded. * * @var array<string> */ protected static $guardableColumns = []; /** * Get the fillable attributes for the model. * * @return array<string> */ public function getFillable() { return $this->fillable; } /** * Set the fillable attributes for the model. * * @param array<string> $fillable * @return $this */ public function fillable(array $fillable) { $this->fillable = $fillable; return $this; } /** * Merge new fillable attributes with existing fillable attributes on the model. * * @param array<string> $fillable * @return $this */ public function mergeFillable(array $fillable) { $this->fillable = array_values(array_unique(array_merge($this->fillable, $fillable))); return $this; } /** * Get the guarded attributes for the model. * * @return array<string> */ public function getGuarded() { return $this->guarded === false ? [] : $this->guarded; } /** * Set the guarded attributes for the model. * * @param array<string> $guarded * @return $this */ public function guard(array $guarded) { $this->guarded = $guarded; return $this; } /** * Merge new guarded attributes with existing guarded attributes on the model. * * @param array<string> $guarded * @return $this */ public function mergeGuarded(array $guarded) { $this->guarded = array_values(array_unique(array_merge($this->guarded, $guarded))); return $this; } /** * Disable all mass assignable restrictions. * * @param bool $state * @return void */ public static function unguard($state = true) { static::$unguarded = $state; } /** * Enable the mass assignment restrictions. * * @return void */ public static function reguard() { static::$unguarded = false; } /** * Determine if the current state is "unguarded". * * @return bool */ public static function isUnguarded() { return static::$unguarded; } /** * Run the given callable while being unguarded. * * @param callable $callback * @return mixed */ public static function unguarded(callable $callback) { if (static::$unguarded) { return $callback(); } static::unguard(); try { return $callback(); } finally { static::reguard(); } } /** * Determine if the given attribute may be mass assigned. * * @param string $key * @return bool */ public function isFillable($key) { if (static::$unguarded) { return true; } // If the key is in the "fillable" array, we can of course assume that it's // a fillable attribute. Otherwise, we will check the guarded array when // we need to determine if the attribute is black-listed on the model. if (in_array($key, $this->getFillable())) { return true; } // If the attribute is explicitly listed in the "guarded" array then we can // return false immediately. This means this attribute is definitely not // fillable and there is no point in going any further in this method. if ($this->isGuarded($key)) { return false; } return empty($this->getFillable()) && ! str_contains($key, '.') && ! str_starts_with($key, '_'); } /** * Determine if the given key is guarded. * * @param string $key * @return bool */ public function isGuarded($key) { if (empty($this->getGuarded())) { return false; } return $this->getGuarded() == ['*'] || ! empty(preg_grep('/^'.preg_quote($key, '/').'$/i', $this->getGuarded())) || ! $this->isGuardableColumn($key); } /** * Determine if the given column is a valid, guardable column. * * @param string $key * @return bool */ protected function isGuardableColumn($key) { if ($this->hasSetMutator($key) || $this->hasAttributeSetMutator($key)) { return true; } if (! isset(static::$guardableColumns[get_class($this)])) { $columns = $this->getConnection() ->getSchemaBuilder() ->getColumnListing($this->getTable()); if (empty($columns)) { return true; } static::$guardableColumns[get_class($this)] = $columns; } return in_array($key, static::$guardableColumns[get_class($this)]); } /** * Determine if the model is totally guarded. * * @return bool */ public function totallyGuarded() { return count($this->getFillable()) === 0 && $this->getGuarded() == ['*']; } /** * Get the fillable attributes of a given array. * * @param array $attributes * @return array */ protected function fillableFromArray(array $attributes) { if (count($this->getFillable()) > 0 && ! static::$unguarded) { return array_intersect_key($attributes, array_flip($this->getFillable())); } return $attributes; } }
194218
<?php namespace Illuminate\Database\Schema; use Closure; use Illuminate\Database\Connection; use Illuminate\Database\Eloquent\Concerns\HasUlids; use Illuminate\Database\Query\Expression; use Illuminate\Database\Schema\Grammars\Grammar; use Illuminate\Database\Schema\Grammars\MySqlGrammar; use Illuminate\Database\Schema\Grammars\SQLiteGrammar; use Illuminate\Support\Fluent; use Illuminate\Support\Traits\Macroable; class Blueprint { use Macroable; /** * The table the blueprint describes. * * @var string */ protected $table; /** * The prefix of the table. * * @var string */ protected $prefix; /** * The columns that should be added to the table. * * @var \Illuminate\Database\Schema\ColumnDefinition[] */ protected $columns = []; /** * The commands that should be run for the table. * * @var \Illuminate\Support\Fluent[] */ protected $commands = []; /** * The storage engine that should be used for the table. * * @var string */ public $engine; /** * The default character set that should be used for the table. * * @var string */ public $charset; /** * The collation that should be used for the table. * * @var string */ public $collation; /** * Whether to make the table temporary. * * @var bool */ public $temporary = false; /** * The column to add new columns after. * * @var string */ public $after; /** * The blueprint state instance. * * @var \Illuminate\Database\Schema\BlueprintState|null */ protected $state; /** * Create a new schema blueprint. * * @param string $table * @param \Closure|null $callback * @param string $prefix * @return void */ public function __construct($table, ?Closure $callback = null, $prefix = '') { $this->table = $table; $this->prefix = $prefix; if (! is_null($callback)) { $callback($this); } } /** * Execute the blueprint against the database. * * @param \Illuminate\Database\Connection $connection * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar * @return void */ public function build(Connection $connection, Grammar $grammar) { foreach ($this->toSql($connection, $grammar) as $statement) { $connection->statement($statement); } } /** * Get the raw SQL statements for the blueprint. * * @param \Illuminate\Database\Connection $connection * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar * @return array */ public function toSql(Connection $connection, Grammar $grammar) { $this->addImpliedCommands($connection, $grammar); $statements = []; // Each type of command has a corresponding compiler function on the schema // grammar which is used to build the necessary SQL statements to build // the blueprint element, so we'll just call that compilers function. $this->ensureCommandsAreValid($connection); foreach ($this->commands as $command) { if ($command->shouldBeSkipped) { continue; } $method = 'compile'.ucfirst($command->name); if (method_exists($grammar, $method) || $grammar::hasMacro($method)) { if ($this->hasState()) { $this->state->update($command); } if (! is_null($sql = $grammar->$method($this, $command, $connection))) { $statements = array_merge($statements, (array) $sql); } } } return $statements; } /** * Ensure the commands on the blueprint are valid for the connection type. * * @param \Illuminate\Database\Connection $connection * @return void * * @throws \BadMethodCallException */ protected function ensureCommandsAreValid(Connection $connection) { // } /** * Get all of the commands matching the given names. * * @deprecated Will be removed in a future Laravel version. * * @param array $names * @return \Illuminate\Support\Collection */ protected function commandsNamed(array $names) { return collect($this->commands)->filter(function ($command) use ($names) { return in_array($command->name, $names); }); } /** * Add the commands that are implied by the blueprint's state. * * @param \Illuminate\Database\Connection $connection * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar * @return void */ protected function addImpliedCommands(Connection $connection, Grammar $grammar) { $this->addFluentIndexes($connection, $grammar); $this->addFluentCommands($connection, $grammar); if (! $this->creating()) { $this->commands = array_map( fn ($command) => $command instanceof ColumnDefinition ? $this->createCommand($command->change ? 'change' : 'add', ['column' => $command]) : $command, $this->commands ); $this->addAlterCommands($connection, $grammar); } } /** * Add the index commands fluently specified on columns. * * @param \Illuminate\Database\Connection $connection * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar * @return void */ protected function addFluentIndexes(Connection $connection, Grammar $grammar) { foreach ($this->columns as $column) { foreach (['primary', 'unique', 'index', 'fulltext', 'fullText', 'spatialIndex'] as $index) { // If the column is supposed to be changed to an auto increment column and // the specified index is primary, there is no need to add a command on // MySQL, as it will be handled during the column definition instead. if ($index === 'primary' && $column->autoIncrement && $column->change && $grammar instanceof MySqlGrammar) { continue 2; } // 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); $column->{$index} = null; continue 2; } // If the index has been specified on the given column, but it equals false // and the column is supposed to be changed, we will call the drop index // method with an array of column to drop it by its conventional name. elseif ($column->{$index} === false && $column->change) { $this->{'drop'.ucfirst($index)}([$column->name]); $column->{$index} = null; continue 2; } // 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}); $column->{$index} = null; continue 2; } } } } /** * Add the fluent commands specified on any columns. * * @param \Illuminate\Database\Connection $connection * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar * @return void */ public function addFluentCommands(Connection $connection, Grammar $grammar) { foreach ($this->columns as $column) { foreach ($grammar->getFluentCommands() as $commandName) { $this->addCommand($commandName, compact('column')); } } } /** * Add the alter commands if whenever needed. * * @param \Illuminate\Database\Connection $connection * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar * @return void */
194220
/** * Indicate that the polymorphic columns should be dropped. * * @param string $name * @param string|null $indexName * @return void */ public function dropMorphs($name, $indexName = null) { $this->dropIndex($indexName ?: $this->createIndexName('index', ["{$name}_type", "{$name}_id"])); $this->dropColumn("{$name}_type", "{$name}_id"); } /** * Rename the table to a given name. * * @param string $to * @return \Illuminate\Support\Fluent */ public function rename($to) { return $this->addCommand('rename', compact('to')); } /** * Specify the primary key(s) for the table. * * @param string|array $columns * @param string|null $name * @param string|null $algorithm * @return \Illuminate\Database\Schema\IndexDefinition */ public function primary($columns, $name = null, $algorithm = null) { return $this->indexCommand('primary', $columns, $name, $algorithm); } /** * Specify a unique index for the table. * * @param string|array $columns * @param string|null $name * @param string|null $algorithm * @return \Illuminate\Database\Schema\IndexDefinition */ public function unique($columns, $name = null, $algorithm = null) { return $this->indexCommand('unique', $columns, $name, $algorithm); } /** * Specify an index for the table. * * @param string|array $columns * @param string|null $name * @param string|null $algorithm * @return \Illuminate\Database\Schema\IndexDefinition */ public function index($columns, $name = null, $algorithm = null) { return $this->indexCommand('index', $columns, $name, $algorithm); } /** * Specify an fulltext for the table. * * @param string|array $columns * @param string|null $name * @param string|null $algorithm * @return \Illuminate\Database\Schema\IndexDefinition */ public function fullText($columns, $name = null, $algorithm = null) { return $this->indexCommand('fulltext', $columns, $name, $algorithm); } /** * Specify a spatial index for the table. * * @param string|array $columns * @param string|null $name * @return \Illuminate\Database\Schema\IndexDefinition */ public function spatialIndex($columns, $name = null) { return $this->indexCommand('spatialIndex', $columns, $name); } /** * Specify a raw index for the table. * * @param string $expression * @param string $name * @return \Illuminate\Database\Schema\IndexDefinition */ public function rawIndex($expression, $name) { return $this->index([new Expression($expression)], $name); } /** * Specify a foreign key for the table. * * @param string|array $columns * @param string|null $name * @return \Illuminate\Database\Schema\ForeignKeyDefinition */ public function foreign($columns, $name = null) { $command = new ForeignKeyDefinition( $this->indexCommand('foreign', $columns, $name)->getAttributes() ); $this->commands[count($this->commands) - 1] = $command; return $command; } /** * Create a new auto-incrementing big integer (8-byte) column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function id($column = 'id') { return $this->bigIncrements($column); } /** * Create a new auto-incrementing integer (4-byte) column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function increments($column) { return $this->unsignedInteger($column, true); } /** * Create a new auto-incrementing integer (4-byte) column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function integerIncrements($column) { return $this->unsignedInteger($column, true); } /** * Create a new auto-incrementing tiny integer (1-byte) column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function tinyIncrements($column) { return $this->unsignedTinyInteger($column, true); } /** * Create a new auto-incrementing small integer (2-byte) column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function smallIncrements($column) { return $this->unsignedSmallInteger($column, true); } /** * Create a new auto-incrementing medium integer (3-byte) column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function mediumIncrements($column) { return $this->unsignedMediumInteger($column, true); } /** * Create a new auto-incrementing big integer (8-byte) column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function bigIncrements($column) { return $this->unsignedBigInteger($column, true); } /** * Create a new char column on the table. * * @param string $column * @param int|null $length * @return \Illuminate\Database\Schema\ColumnDefinition */ public function char($column, $length = null) { $length = ! is_null($length) ? $length : Builder::$defaultStringLength; return $this->addColumn('char', $column, compact('length')); } /** * Create a new string column on the table. * * @param string $column * @param int|null $length * @return \Illuminate\Database\Schema\ColumnDefinition */ public function string($column, $length = null) { $length = $length ?: Builder::$defaultStringLength; return $this->addColumn('string', $column, compact('length')); } /** * Create a new tiny text column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function tinyText($column) { return $this->addColumn('tinyText', $column); } /** * Create a new text column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function text($column) { return $this->addColumn('text', $column); } /** * Create a new medium text column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function mediumText($column) { return $this->addColumn('mediumText', $column); } /** * Create a new long text column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function longText($column) { return $this->addColumn('longText', $column); } /** * Create a new integer (4-byte) column on the table. * * @param string $column * @param bool $autoIncrement * @param bool $unsigned * @return \Illuminate\Database\Schema\ColumnDefinition */ public function integer($column, $autoIncrement = false, $unsigned = false) { return $this->addColumn('integer', $column, compact('autoIncrement', 'unsigned')); }
194221
/** * Create a new tiny integer (1-byte) column on the table. * * @param string $column * @param bool $autoIncrement * @param bool $unsigned * @return \Illuminate\Database\Schema\ColumnDefinition */ public function tinyInteger($column, $autoIncrement = false, $unsigned = false) { return $this->addColumn('tinyInteger', $column, compact('autoIncrement', 'unsigned')); } /** * Create a new small integer (2-byte) column on the table. * * @param string $column * @param bool $autoIncrement * @param bool $unsigned * @return \Illuminate\Database\Schema\ColumnDefinition */ public function smallInteger($column, $autoIncrement = false, $unsigned = false) { return $this->addColumn('smallInteger', $column, compact('autoIncrement', 'unsigned')); } /** * Create a new medium integer (3-byte) column on the table. * * @param string $column * @param bool $autoIncrement * @param bool $unsigned * @return \Illuminate\Database\Schema\ColumnDefinition */ public function mediumInteger($column, $autoIncrement = false, $unsigned = false) { return $this->addColumn('mediumInteger', $column, compact('autoIncrement', 'unsigned')); } /** * Create a new big integer (8-byte) column on the table. * * @param string $column * @param bool $autoIncrement * @param bool $unsigned * @return \Illuminate\Database\Schema\ColumnDefinition */ public function bigInteger($column, $autoIncrement = false, $unsigned = false) { return $this->addColumn('bigInteger', $column, compact('autoIncrement', 'unsigned')); } /** * Create a new unsigned integer (4-byte) column on the table. * * @param string $column * @param bool $autoIncrement * @return \Illuminate\Database\Schema\ColumnDefinition */ public function unsignedInteger($column, $autoIncrement = false) { return $this->integer($column, $autoIncrement, true); } /** * Create a new unsigned tiny integer (1-byte) column on the table. * * @param string $column * @param bool $autoIncrement * @return \Illuminate\Database\Schema\ColumnDefinition */ public function unsignedTinyInteger($column, $autoIncrement = false) { return $this->tinyInteger($column, $autoIncrement, true); } /** * Create a new unsigned small integer (2-byte) column on the table. * * @param string $column * @param bool $autoIncrement * @return \Illuminate\Database\Schema\ColumnDefinition */ public function unsignedSmallInteger($column, $autoIncrement = false) { return $this->smallInteger($column, $autoIncrement, true); } /** * Create a new unsigned medium integer (3-byte) column on the table. * * @param string $column * @param bool $autoIncrement * @return \Illuminate\Database\Schema\ColumnDefinition */ public function unsignedMediumInteger($column, $autoIncrement = false) { return $this->mediumInteger($column, $autoIncrement, true); } /** * Create a new unsigned big integer (8-byte) column on the table. * * @param string $column * @param bool $autoIncrement * @return \Illuminate\Database\Schema\ColumnDefinition */ public function unsignedBigInteger($column, $autoIncrement = false) { return $this->bigInteger($column, $autoIncrement, true); } /** * Create a new unsigned big integer (8-byte) column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ForeignIdColumnDefinition */ public function foreignId($column) { return $this->addColumnDefinition(new ForeignIdColumnDefinition($this, [ 'type' => 'bigInteger', 'name' => $column, 'autoIncrement' => false, 'unsigned' => true, ])); } /** * Create a foreign ID column for the given model. * * @param \Illuminate\Database\Eloquent\Model|string $model * @param string|null $column * @return \Illuminate\Database\Schema\ForeignIdColumnDefinition */ public function foreignIdFor($model, $column = null) { if (is_string($model)) { $model = new $model; } $column = $column ?: $model->getForeignKey(); if ($model->getKeyType() === 'int' && $model->getIncrementing()) { return $this->foreignId($column)->table($model->getTable()); } $modelTraits = class_uses_recursive($model); if (in_array(HasUlids::class, $modelTraits, true)) { return $this->foreignUlid($column, 26)->table($model->getTable()); } return $this->foreignUuid($column)->table($model->getTable()); } /** * Create a new float column on the table. * * @param string $column * @param int $precision * @return \Illuminate\Database\Schema\ColumnDefinition */ public function float($column, $precision = 53) { return $this->addColumn('float', $column, compact('precision')); } /** * Create a new double column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function double($column) { return $this->addColumn('double', $column); } /** * Create a new decimal column on the table. * * @param string $column * @param int $total * @param int $places * @return \Illuminate\Database\Schema\ColumnDefinition */ public function decimal($column, $total = 8, $places = 2) { return $this->addColumn('decimal', $column, compact('total', 'places')); } /** * Create a new boolean column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function boolean($column) { return $this->addColumn('boolean', $column); } /** * Create a new enum column on the table. * * @param string $column * @param array $allowed * @return \Illuminate\Database\Schema\ColumnDefinition */ public function enum($column, array $allowed) { return $this->addColumn('enum', $column, compact('allowed')); } /** * Create a new set column on the table. * * @param string $column * @param array $allowed * @return \Illuminate\Database\Schema\ColumnDefinition */ public function set($column, array $allowed) { return $this->addColumn('set', $column, compact('allowed')); } /** * Create a new json column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function json($column) { return $this->addColumn('json', $column); } /** * Create a new jsonb column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function jsonb($column) { return $this->addColumn('jsonb', $column); } /** * Create a new date column on the table. * * @param string $column * @return \Illuminate\Database\Schema\ColumnDefinition */ public function date($column) { return $this->addColumn('date', $column); } /** * Create a new date-time column on the table. * * @param string $column * @param int|null $precision * @return \Illuminate\Database\Schema\ColumnDefinition */ public function dateTime($column, $precision = 0) { return $this->addColumn('dateTime', $column, compact('precision')); }
194225
<?php namespace Illuminate\Database\Schema; use Illuminate\Support\Fluent; /** * @method $this after(string $column) Place the column "after" another column (MySQL) * @method $this always(bool $value = true) Used as a modifier for generatedAs() (PostgreSQL) * @method $this autoIncrement() Set INTEGER columns as auto-increment (primary key) * @method $this change() Change the column * @method $this charset(string $charset) Specify a character set for the column (MySQL) * @method $this collation(string $collation) Specify a collation for the column * @method $this comment(string $comment) Add a comment to the column (MySQL/PostgreSQL) * @method $this default(mixed $value) Specify a "default" value for the column * @method $this first() Place the column "first" in the table (MySQL) * @method $this from(int $startingValue) Set the starting value of an auto-incrementing field (MySQL / PostgreSQL) * @method $this generatedAs(string|\Illuminate\Contracts\Database\Query\Expression $expression = null) Create a SQL compliant identity column (PostgreSQL) * @method $this index(bool|string $indexName = null) Add an index * @method $this invisible() Specify that the column should be invisible to "SELECT *" (MySQL) * @method $this nullable(bool $value = true) Allow NULL values to be inserted into the column * @method $this persisted() Mark the computed generated column as persistent (SQL Server) * @method $this primary(bool $value = true) Add a primary index * @method $this fulltext(bool|string $indexName = null) Add a fulltext index * @method $this spatialIndex(bool|string $indexName = null) Add a spatial index * @method $this startingValue(int $startingValue) Set the starting value of an auto-incrementing field (MySQL/PostgreSQL) * @method $this storedAs(string|\Illuminate\Contracts\Database\Query\Expression $expression) Create a stored generated column (MySQL/PostgreSQL/SQLite) * @method $this type(string $type) Specify a type for the column * @method $this unique(bool|string $indexName = null) Add a unique index * @method $this unsigned() Set the INTEGER column as UNSIGNED (MySQL) * @method $this useCurrent() Set the TIMESTAMP column to use CURRENT_TIMESTAMP as default value * @method $this useCurrentOnUpdate() Set the TIMESTAMP column to use CURRENT_TIMESTAMP when updating (MySQL) * @method $this virtualAs(string|\Illuminate\Contracts\Database\Query\Expression $expression) Create a virtual generated column (MySQL/PostgreSQL/SQLite) */ class ColumnDefinition extends Fluent { // }
194231
<?php namespace Illuminate\Database\Schema; use Illuminate\Support\Str; class ForeignIdColumnDefinition extends ColumnDefinition { /** * The schema builder blueprint instance. * * @var \Illuminate\Database\Schema\Blueprint */ protected $blueprint; /** * Create a new foreign ID column definition. * * @param \Illuminate\Database\Schema\Blueprint $blueprint * @param array $attributes * @return void */ public function __construct(Blueprint $blueprint, $attributes = []) { parent::__construct($attributes); $this->blueprint = $blueprint; } /** * Create a foreign key constraint on this column referencing the "id" column of the conventionally related table. * * @param string|null $table * @param string|null $column * @param string|null $indexName * @return \Illuminate\Database\Schema\ForeignKeyDefinition */ public function constrained($table = null, $column = 'id', $indexName = null) { $table ??= $this->table; return $this->references($column, $indexName)->on($table ?? Str::of($this->name)->beforeLast('_'.$column)->plural()); } /** * Specify which column this foreign ID references on another table. * * @param string $column * @param string $indexName * @return \Illuminate\Database\Schema\ForeignKeyDefinition */ public function references($column, $indexName = null) { return $this->blueprint->foreign($this->name, $indexName)->references($column); } }
194266
protected function compileCreateEncoding($sql, Connection $connection, Blueprint $blueprint) { // First we will set the character set if one has been set on either the create // blueprint itself or on the root configuration for the connection that the // table is being created on. We will add these to the create table query. if (isset($blueprint->charset)) { $sql .= ' default character set '.$blueprint->charset; } elseif (! is_null($charset = $connection->getConfig('charset'))) { $sql .= ' default character set '.$charset; } // Next we will add the collation to the create table statement if one has been // added to either this create table blueprint or the configuration for this // connection that the query is targeting. We'll add it to this SQL query. if (isset($blueprint->collation)) { $sql .= " collate '{$blueprint->collation}'"; } elseif (! is_null($collation = $connection->getConfig('collation'))) { $sql .= " collate '{$collation}'"; } return $sql; } /** * Append the engine specifications to a command. * * @param string $sql * @param \Illuminate\Database\Connection $connection * @param \Illuminate\Database\Schema\Blueprint $blueprint * @return string */ protected function compileCreateEngine($sql, Connection $connection, Blueprint $blueprint) { if (isset($blueprint->engine)) { return $sql.' engine = '.$blueprint->engine; } elseif (! is_null($engine = $connection->getConfig('engine'))) { return $sql.' engine = '.$engine; } return $sql; } /** * Compile an add column command. * * @param \Illuminate\Database\Schema\Blueprint $blueprint * @param \Illuminate\Support\Fluent $command * @return string */ public function compileAdd(Blueprint $blueprint, Fluent $command) { return sprintf('alter table %s add %s', $this->wrapTable($blueprint), $this->getColumn($blueprint, $command->column) ); } /** * Compile the auto-incrementing column starting values. * * @param \Illuminate\Database\Schema\Blueprint $blueprint * @param \Illuminate\Support\Fluent $command * @return string */ public function compileAutoIncrementStartingValues(Blueprint $blueprint, Fluent $command) { if ($command->column->autoIncrement && $value = $command->column->get('startingValue', $command->column->get('from'))) { return 'alter table '.$this->wrapTable($blueprint).' auto_increment = '.$value; } } /** * Compile a rename column command. * * @param \Illuminate\Database\Schema\Blueprint $blueprint * @param \Illuminate\Support\Fluent $command * @param \Illuminate\Database\Connection $connection * @return array|string */ public function compileRenameColumn(Blueprint $blueprint, Fluent $command, Connection $connection) { $version = $connection->getServerVersion(); if (($connection->isMaria() && version_compare($version, '10.5.2', '<')) || (! $connection->isMaria() && version_compare($version, '8.0.3', '<'))) { return $this->compileLegacyRenameColumn($blueprint, $command, $connection); } return parent::compileRenameColumn($blueprint, $command, $connection); } /** * Compile a rename column command for legacy versions of MySQL. * * @param \Illuminate\Database\Schema\Blueprint $blueprint * @param \Illuminate\Support\Fluent $command * @param \Illuminate\Database\Connection $connection * @return string */ protected function compileLegacyRenameColumn(Blueprint $blueprint, Fluent $command, Connection $connection) { $column = collect($connection->getSchemaBuilder()->getColumns($blueprint->getTable())) ->firstWhere('name', $command->from); $modifiers = $this->addModifiers($column['type'], $blueprint, new ColumnDefinition([ 'change' => true, 'type' => match ($column['type_name']) { 'bigint' => 'bigInteger', 'int' => 'integer', 'mediumint' => 'mediumInteger', 'smallint' => 'smallInteger', 'tinyint' => 'tinyInteger', default => $column['type_name'], }, 'nullable' => $column['nullable'], 'default' => $column['default'] && (str_starts_with(strtolower($column['default']), 'current_timestamp') || $column['default'] === 'NULL') ? new Expression($column['default']) : $column['default'], 'autoIncrement' => $column['auto_increment'], 'collation' => $column['collation'], 'comment' => $column['comment'], 'virtualAs' => ! is_null($column['generation']) && $column['generation']['type'] === 'virtual' ? $column['generation']['expression'] : null, 'storedAs' => ! is_null($column['generation']) && $column['generation']['type'] === 'stored' ? $column['generation']['expression'] : null, ])); return sprintf('alter table %s change %s %s %s', $this->wrapTable($blueprint), $this->wrap($command->from), $this->wrap($command->to), $modifiers ); } /** * 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|string * * @throws \RuntimeException */ public function compileChange(Blueprint $blueprint, Fluent $command, Connection $connection) { $column = $command->column; $sql = sprintf('alter table %s %s %s%s %s', $this->wrapTable($blueprint), is_null($column->renameTo) ? 'modify' : 'change', $this->wrap($column), is_null($column->renameTo) ? '' : ' '.$this->wrap($column->renameTo), $this->getType($column) ); return $this->addModifiers($sql, $blueprint, $column); } /** * Compile a primary key command. * * @param \Illuminate\Database\Schema\Blueprint $blueprint * @param \Illuminate\Support\Fluent $command * @return string */ public function compilePrimary(Blueprint $blueprint, Fluent $command) { return sprintf('alter table %s add primary key %s(%s)', $this->wrapTable($blueprint), $command->algorithm ? 'using '.$command->algorithm : '', $this->columnize($command->columns) ); } /** * Compile a unique key command. * * @param \Illuminate\Database\Schema\Blueprint $blueprint * @param \Illuminate\Support\Fluent $command * @return string */ public function compileUnique(Blueprint $blueprint, Fluent $command) { return $this->compileKey($blueprint, $command, 'unique'); } /** * Compile a plain index key command. * * @param \Illuminate\Database\Schema\Blueprint $blueprint * @param \Illuminate\Support\Fluent $command * @return string */ public function compileIndex(Blueprint $blueprint, Fluent $command) { return $this->compileKey($blueprint, $command, 'index'); } /** * Compile a fulltext index key command. * * @param \Illuminate\Database\Schema\Blueprint $blueprint * @param \Illuminate\Support\Fluent $command * @return string */ public function compileFullText(Blueprint $blueprint, Fluent $command) { return $this->compileKey($blueprint, $command, 'fulltext'); } /** * Compile a spatial index key command. * * @param \Illuminate\Database\Schema\Blueprint $blueprint * @param \Illuminate\Support\Fluent $command * @return string */ public function compileSpatialIndex(Blueprint $blueprint, Fluent $command) { return $this->compileKey($blueprint, $command, 'spatial index'); }
194298
public function where($column, $operator = null, $value = null, $boolean = 'and') { if ($column instanceof ConditionExpression) { $type = 'Expression'; $this->wheres[] = compact('type', 'column', 'boolean'); return $this; } // If the column is an array, we will assume it is an array of key-value pairs // and can add them each as a where clause. We will maintain the boolean we // received when the method was called and pass it into the nested where. if (is_array($column)) { return $this->addArrayOfWheres($column, $boolean); } // Here we will make some assumptions about the operator. If only 2 values are // passed to the method, we will assume that the operator is an equals sign // and keep going. Otherwise, we'll require the operator to be passed in. [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); // If the column is actually a Closure instance, we will assume the developer // wants to begin a nested where statement which is wrapped in parentheses. // We will add that Closure to the query and return back out immediately. if ($column instanceof Closure && is_null($operator)) { return $this->whereNested($column, $boolean); } // If the column is a Closure instance and there is an operator value, we will // assume the developer wants to run a subquery and then compare the result // of that subquery with the given value that was provided to the method. if ($this->isQueryable($column) && ! is_null($operator)) { [$sub, $bindings] = $this->createSub($column); return $this->addBinding($bindings, 'where') ->where(new Expression('('.$sub.')'), $operator, $value, $boolean); } // If the given operator is not found in the list of valid operators we will // assume that the developer is just short-cutting the '=' operators and // we will set the operators to '=' and set the values appropriately. if ($this->invalidOperator($operator)) { [$value, $operator] = [$operator, '=']; } // If the value is a Closure, it means the developer is performing an entire // sub-select within the query and we will need to compile the sub-select // within the where clause to get the appropriate query record results. if ($this->isQueryable($value)) { return $this->whereSub($column, $operator, $value, $boolean); } // If the value is "null", we will just assume the developer wants to add a // where null clause to the query. So, we will allow a short-cut here to // that method for convenience so the developer doesn't have to check. if (is_null($value)) { return $this->whereNull($column, $boolean, $operator !== '='); } $type = 'Basic'; $columnString = ($column instanceof ExpressionContract) ? $this->grammar->getValue($column) : $column; // If the column is making a JSON reference we'll check to see if the value // is a boolean. If it is, we'll add the raw boolean string as an actual // value to the query to ensure this is properly handled by the query. if (str_contains($columnString, '->') && is_bool($value)) { $value = new Expression($value ? 'true' : 'false'); if (is_string($column)) { $type = 'JsonBoolean'; } } if ($this->isBitwiseOperator($operator)) { $type = 'Bitwise'; } // Now that we are working with just a simple query we can put the elements // in our array and add the query binding to our array of bindings that // will be bound to each SQL statements when it is finally executed. $this->wheres[] = compact( 'type', 'column', 'operator', 'value', 'boolean' ); if (! $value instanceof ExpressionContract) { $this->addBinding($this->flattenValue($value), 'where'); } return $this; } /** * Add an array of where clauses to the query. * * @param array $column * @param string $boolean * @param string $method * @return $this */ protected function addArrayOfWheres($column, $boolean, $method = 'where') { return $this->whereNested(function ($query) use ($column, $method, $boolean) { foreach ($column as $key => $value) { if (is_numeric($key) && is_array($value)) { $query->{$method}(...array_values($value), boolean: $boolean); } else { $query->{$method}($key, '=', $value, $boolean); } } }, $boolean); } /** * Prepare the value and operator for a where clause. * * @param string $value * @param string $operator * @param bool $useDefault * @return array * * @throws \InvalidArgumentException */ public function prepareValueAndOperator($value, $operator, $useDefault = false) { if ($useDefault) { return [$operator, '=']; } elseif ($this->invalidOperatorAndValue($operator, $value)) { throw new InvalidArgumentException('Illegal operator and value combination.'); } return [$value, $operator]; } /** * Determine if the given operator and value combination is legal. * * Prevents using Null values with invalid operators. * * @param string $operator * @param mixed $value * @return bool */ protected function invalidOperatorAndValue($operator, $value) { return is_null($value) && in_array($operator, $this->operators) && ! in_array($operator, ['=', '<>', '!=']); } /** * Determine if the given operator is supported. * * @param string $operator * @return bool */ protected function invalidOperator($operator) { return ! is_string($operator) || (! in_array(strtolower($operator), $this->operators, true) && ! in_array(strtolower($operator), $this->grammar->getOperators(), true)); } /** * Determine if the operator is a bitwise operator. * * @param string $operator * @return bool */ protected function isBitwiseOperator($operator) { return in_array(strtolower($operator), $this->bitwiseOperators, true) || in_array(strtolower($operator), $this->grammar->getBitwiseOperators(), true); } /** * Add an "or where" clause to the query. * * @param \Closure|string|array|\Illuminate\Contracts\Database\Query\Expression $column * @param mixed $operator * @param mixed $value * @return $this */ public function orWhere($column, $operator = null, $value = null) { [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); return $this->where($column, $operator, $value, 'or'); } /** * Add a basic "where not" clause to the query. * * @param \Closure|string|array|\Illuminate\Contracts\Database\Query\Expression $column * @param mixed $operator * @param mixed $value * @param string $boolean * @return $this */ public function whereNot($column, $operator = null, $value = null, $boolean = 'and') { if (is_array($column)) { return $this->whereNested(function ($query) use ($column, $operator, $value, $boolean) { $query->where($column, $operator, $value, $boolean); }, $boolean.' not'); } return $this->where($column, $operator, $value, $boolean.' not'); } /** * Add an "or where not" clause to the query. * * @param \Closure|string|array|\Illuminate\Contracts\Database\Query\Expression $column * @param mixed $operator * @param mixed $value * @return $this */
194300
public function orWhereNotIn($column, $values) { return $this->whereNotIn($column, $values, 'or'); } /** * Add a "where in raw" clause for integer values to the query. * * @param string $column * @param \Illuminate\Contracts\Support\Arrayable|array $values * @param string $boolean * @param bool $not * @return $this */ public function whereIntegerInRaw($column, $values, $boolean = 'and', $not = false) { $type = $not ? 'NotInRaw' : 'InRaw'; if ($values instanceof Arrayable) { $values = $values->toArray(); } $values = Arr::flatten($values); foreach ($values as &$value) { $value = (int) ($value instanceof BackedEnum ? $value->value : $value); } $this->wheres[] = compact('type', 'column', 'values', 'boolean'); return $this; } /** * Add an "or where in raw" clause for integer values to the query. * * @param string $column * @param \Illuminate\Contracts\Support\Arrayable|array $values * @return $this */ public function orWhereIntegerInRaw($column, $values) { return $this->whereIntegerInRaw($column, $values, 'or'); } /** * Add a "where not in raw" clause for integer values to the query. * * @param string $column * @param \Illuminate\Contracts\Support\Arrayable|array $values * @param string $boolean * @return $this */ public function whereIntegerNotInRaw($column, $values, $boolean = 'and') { return $this->whereIntegerInRaw($column, $values, $boolean, true); } /** * Add an "or where not in raw" clause for integer values to the query. * * @param string $column * @param \Illuminate\Contracts\Support\Arrayable|array $values * @return $this */ public function orWhereIntegerNotInRaw($column, $values) { return $this->whereIntegerNotInRaw($column, $values, 'or'); } /** * Add a "where null" clause to the query. * * @param string|array|\Illuminate\Contracts\Database\Query\Expression $columns * @param string $boolean * @param bool $not * @return $this */ public function whereNull($columns, $boolean = 'and', $not = false) { $type = $not ? 'NotNull' : 'Null'; foreach (Arr::wrap($columns) as $column) { $this->wheres[] = compact('type', 'column', 'boolean'); } return $this; } /** * Add an "or where null" clause to the query. * * @param string|array|\Illuminate\Contracts\Database\Query\Expression $column * @return $this */ public function orWhereNull($column) { return $this->whereNull($column, 'or'); } /** * Add a "where not null" clause to the query. * * @param string|array|\Illuminate\Contracts\Database\Query\Expression $columns * @param string $boolean * @return $this */ public function whereNotNull($columns, $boolean = 'and') { return $this->whereNull($columns, $boolean, true); } /** * Add a where between statement to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param iterable $values * @param string $boolean * @param bool $not * @return $this */ public function whereBetween($column, iterable $values, $boolean = 'and', $not = false) { $type = 'between'; if ($values instanceof CarbonPeriod) { $values = [$values->getStartDate(), $values->getEndDate()]; } $this->wheres[] = compact('type', 'column', 'values', 'boolean', 'not'); $this->addBinding(array_slice($this->cleanBindings(Arr::flatten($values)), 0, 2), 'where'); return $this; } /** * Add a where between statement using columns to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param array $values * @param string $boolean * @param bool $not * @return $this */ public function whereBetweenColumns($column, array $values, $boolean = 'and', $not = false) { $type = 'betweenColumns'; $this->wheres[] = compact('type', 'column', 'values', 'boolean', 'not'); return $this; } /** * Add an or where between statement to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param iterable $values * @return $this */ public function orWhereBetween($column, iterable $values) { return $this->whereBetween($column, $values, 'or'); } /** * Add an or where between statement using columns to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param array $values * @return $this */ public function orWhereBetweenColumns($column, array $values) { return $this->whereBetweenColumns($column, $values, 'or'); } /** * Add a where not between statement to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param iterable $values * @param string $boolean * @return $this */ public function whereNotBetween($column, iterable $values, $boolean = 'and') { return $this->whereBetween($column, $values, $boolean, true); } /** * Add a where not between statement using columns to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param array $values * @param string $boolean * @return $this */ public function whereNotBetweenColumns($column, array $values, $boolean = 'and') { return $this->whereBetweenColumns($column, $values, $boolean, true); } /** * Add an or where not between statement to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param iterable $values * @return $this */ public function orWhereNotBetween($column, iterable $values) { return $this->whereNotBetween($column, $values, 'or'); } /** * Add an or where not between statement using columns to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param array $values * @return $this */ public function orWhereNotBetweenColumns($column, array $values) { return $this->whereNotBetweenColumns($column, $values, 'or'); } /** * Add an "or where not null" clause to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @return $this */ public function orWhereNotNull($column) { return $this->whereNotNull($column, 'or'); } /** * Add a "where date" statement to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param \DateTimeInterface|string|null $operator * @param \DateTimeInterface|string|null $value * @param string $boolean * @return $this */
194301
public function whereDate($column, $operator, $value = null, $boolean = 'and') { [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); // If the given operator is not found in the list of valid operators we will // assume that the developer is just short-cutting the '=' operators and // we will set the operators to '=' and set the values appropriately. if ($this->invalidOperator($operator)) { [$value, $operator] = [$operator, '=']; } $value = $this->flattenValue($value); if ($value instanceof DateTimeInterface) { $value = $value->format('Y-m-d'); } return $this->addDateBasedWhere('Date', $column, $operator, $value, $boolean); } /** * Add an "or where date" statement to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param \DateTimeInterface|string|null $operator * @param \DateTimeInterface|string|null $value * @return $this */ public function orWhereDate($column, $operator, $value = null) { [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); return $this->whereDate($column, $operator, $value, 'or'); } /** * Add a "where time" statement to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param \DateTimeInterface|string|null $operator * @param \DateTimeInterface|string|null $value * @param string $boolean * @return $this */ public function whereTime($column, $operator, $value = null, $boolean = 'and') { [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); // If the given operator is not found in the list of valid operators we will // assume that the developer is just short-cutting the '=' operators and // we will set the operators to '=' and set the values appropriately. if ($this->invalidOperator($operator)) { [$value, $operator] = [$operator, '=']; } $value = $this->flattenValue($value); if ($value instanceof DateTimeInterface) { $value = $value->format('H:i:s'); } return $this->addDateBasedWhere('Time', $column, $operator, $value, $boolean); } /** * Add an "or where time" statement to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param \DateTimeInterface|string|null $operator * @param \DateTimeInterface|string|null $value * @return $this */ public function orWhereTime($column, $operator, $value = null) { [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); return $this->whereTime($column, $operator, $value, 'or'); } /** * Add a "where day" statement to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param \DateTimeInterface|string|int|null $operator * @param \DateTimeInterface|string|int|null $value * @param string $boolean * @return $this */ public function whereDay($column, $operator, $value = null, $boolean = 'and') { [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); // If the given operator is not found in the list of valid operators we will // assume that the developer is just short-cutting the '=' operators and // we will set the operators to '=' and set the values appropriately. if ($this->invalidOperator($operator)) { [$value, $operator] = [$operator, '=']; } $value = $this->flattenValue($value); if ($value instanceof DateTimeInterface) { $value = $value->format('d'); } if (! $value instanceof ExpressionContract) { $value = sprintf('%02d', $value); } return $this->addDateBasedWhere('Day', $column, $operator, $value, $boolean); } /** * Add an "or where day" statement to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param \DateTimeInterface|string|int|null $operator * @param \DateTimeInterface|string|int|null $value * @return $this */ public function orWhereDay($column, $operator, $value = null) { [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); return $this->whereDay($column, $operator, $value, 'or'); } /** * Add a "where month" statement to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param \DateTimeInterface|string|int|null $operator * @param \DateTimeInterface|string|int|null $value * @param string $boolean * @return $this */ public function whereMonth($column, $operator, $value = null, $boolean = 'and') { [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); // If the given operator is not found in the list of valid operators we will // assume that the developer is just short-cutting the '=' operators and // we will set the operators to '=' and set the values appropriately. if ($this->invalidOperator($operator)) { [$value, $operator] = [$operator, '=']; } $value = $this->flattenValue($value); if ($value instanceof DateTimeInterface) { $value = $value->format('m'); } if (! $value instanceof ExpressionContract) { $value = sprintf('%02d', $value); } return $this->addDateBasedWhere('Month', $column, $operator, $value, $boolean); } /** * Add an "or where month" statement to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param \DateTimeInterface|string|int|null $operator * @param \DateTimeInterface|string|int|null $value * @return $this */ public function orWhereMonth($column, $operator, $value = null) { [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); return $this->whereMonth($column, $operator, $value, 'or'); } /** * Add a "where year" statement to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param \DateTimeInterface|string|int|null $operator * @param \DateTimeInterface|string|int|null $value * @param string $boolean * @return $this */ public function whereYear($column, $operator, $value = null, $boolean = 'and') { [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); // If the given operator is not found in the list of valid operators we will // assume that the developer is just short-cutting the '=' operators and // we will set the operators to '=' and set the values appropriately. if ($this->invalidOperator($operator)) { [$value, $operator] = [$operator, '=']; } $value = $this->flattenValue($value); if ($value instanceof DateTimeInterface) { $value = $value->format('Y'); } return $this->addDateBasedWhere('Year', $column, $operator, $value, $boolean); }
194302
/** * Add an "or where year" statement to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param \DateTimeInterface|string|int|null $operator * @param \DateTimeInterface|string|int|null $value * @return $this */ public function orWhereYear($column, $operator, $value = null) { [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); return $this->whereYear($column, $operator, $value, 'or'); } /** * Add a date based (year, month, day, time) statement to the query. * * @param string $type * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param string $operator * @param mixed $value * @param string $boolean * @return $this */ protected function addDateBasedWhere($type, $column, $operator, $value, $boolean = 'and') { $this->wheres[] = compact('column', 'type', 'boolean', 'operator', 'value'); if (! $value instanceof ExpressionContract) { $this->addBinding($value, 'where'); } return $this; } /** * Add a nested where statement to the query. * * @param \Closure $callback * @param string $boolean * @return $this */ public function whereNested(Closure $callback, $boolean = 'and') { $callback($query = $this->forNestedWhere()); return $this->addNestedWhereQuery($query, $boolean); } /** * Create a new query instance for nested where condition. * * @return \Illuminate\Database\Query\Builder */ public function forNestedWhere() { return $this->newQuery()->from($this->from); } /** * Add another query builder as a nested where to the query builder. * * @param \Illuminate\Database\Query\Builder $query * @param string $boolean * @return $this */ public function addNestedWhereQuery($query, $boolean = 'and') { if (count($query->wheres)) { $type = 'Nested'; $this->wheres[] = compact('type', 'query', 'boolean'); $this->addBinding($query->getRawBindings()['where'], 'where'); } return $this; } /** * Add a full sub-select to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|string $column * @param string $operator * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder<*> $callback * @param string $boolean * @return $this */ protected function whereSub($column, $operator, $callback, $boolean) { $type = 'Sub'; if ($callback instanceof Closure) { // Once we have the query instance we can simply execute it so it can add all // of the sub-select's conditions to itself, and then we can cache it off // in the array of where clauses for the "main" parent query instance. $callback($query = $this->forSubQuery()); } else { $query = $callback instanceof EloquentBuilder ? $callback->toBase() : $callback; } $this->wheres[] = compact( 'type', 'column', 'operator', 'query', 'boolean' ); $this->addBinding($query->getBindings(), 'where'); return $this; } /** * Add an exists clause to the query. * * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder<*> $callback * @param string $boolean * @param bool $not * @return $this */ public function whereExists($callback, $boolean = 'and', $not = false) { if ($callback instanceof Closure) { $query = $this->forSubQuery(); // Similar to the sub-select clause, we will create a new query instance so // the developer may cleanly specify the entire exists query and we will // compile the whole thing in the grammar and insert it into the SQL. $callback($query); } else { $query = $callback instanceof EloquentBuilder ? $callback->toBase() : $callback; } return $this->addWhereExistsQuery($query, $boolean, $not); } /** * Add an or exists clause to the query. * * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder<*> $callback * @param bool $not * @return $this */ public function orWhereExists($callback, $not = false) { return $this->whereExists($callback, 'or', $not); } /** * Add a where not exists clause to the query. * * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder<*> $callback * @param string $boolean * @return $this */ public function whereNotExists($callback, $boolean = 'and') { return $this->whereExists($callback, $boolean, true); } /** * Add a where not exists clause to the query. * * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder<*> $callback * @return $this */ public function orWhereNotExists($callback) { return $this->orWhereExists($callback, true); } /** * Add an exists clause to the query. * * @param \Illuminate\Database\Query\Builder $query * @param string $boolean * @param bool $not * @return $this */ public function addWhereExistsQuery(self $query, $boolean = 'and', $not = false) { $type = $not ? 'NotExists' : 'Exists'; $this->wheres[] = compact('type', 'query', 'boolean'); $this->addBinding($query->getBindings(), 'where'); return $this; } /** * Adds a where condition using row values. * * @param array $columns * @param string $operator * @param array $values * @param string $boolean * @return $this * * @throws \InvalidArgumentException */ public function whereRowValues($columns, $operator, $values, $boolean = 'and') { if (count($columns) !== count($values)) { throw new InvalidArgumentException('The number of columns must match the number of values'); } $type = 'RowValues'; $this->wheres[] = compact('type', 'columns', 'operator', 'values', 'boolean'); $this->addBinding($this->cleanBindings($values)); return $this; } /** * Adds an or where condition using row values. * * @param array $columns * @param string $operator * @param array $values * @return $this */ public function orWhereRowValues($columns, $operator, $values) { return $this->whereRowValues($columns, $operator, $values, 'or'); } /** * Add a "where JSON contains" clause to the query. * * @param string $column * @param mixed $value * @param string $boolean * @param bool $not * @return $this */ public function whereJsonContains($column, $value, $boolean = 'and', $not = false) { $type = 'JsonContains'; $this->wheres[] = compact('type', 'column', 'value', 'boolean', 'not'); if (! $value instanceof ExpressionContract) { $this->addBinding($this->grammar->prepareBindingForJsonContains($value)); } return $this; } /** * Add an "or where JSON contains" clause to the query. * * @param string $column * @param mixed $value * @return $this */
194304
/** * Add a "where fulltext" clause to the query. * * @param string|string[] $columns * @param string $value * @param string $boolean * @return $this */ public function whereFullText($columns, $value, array $options = [], $boolean = 'and') { $type = 'Fulltext'; $columns = (array) $columns; $this->wheres[] = compact('type', 'columns', 'value', 'options', 'boolean'); $this->addBinding($value); return $this; } /** * Add a "or where fulltext" clause to the query. * * @param string|string[] $columns * @param string $value * @return $this */ public function orWhereFullText($columns, $value, array $options = []) { return $this->whereFulltext($columns, $value, $options, 'or'); } /** * Add a "where" clause to the query for multiple columns with "and" conditions between them. * * @param \Illuminate\Contracts\Database\Query\Expression[]|\Closure[]|string[] $columns * @param mixed $operator * @param mixed $value * @param string $boolean * @return $this */ public function whereAll($columns, $operator = null, $value = null, $boolean = 'and') { [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); $this->whereNested(function ($query) use ($columns, $operator, $value) { foreach ($columns as $column) { $query->where($column, $operator, $value, 'and'); } }, $boolean); return $this; } /** * Add an "or where" clause to the query for multiple columns with "and" conditions between them. * * @param \Illuminate\Contracts\Database\Query\Expression[]|\Closure[]|string[] $columns * @param mixed $operator * @param mixed $value * @return $this */ public function orWhereAll($columns, $operator = null, $value = null) { return $this->whereAll($columns, $operator, $value, 'or'); } /** * Add a "where" clause to the query for multiple columns with "or" conditions between them. * * @param \Illuminate\Contracts\Database\Query\Expression[]|\Closure[]|string[] $columns * @param mixed $operator * @param mixed $value * @param string $boolean * @return $this */ public function whereAny($columns, $operator = null, $value = null, $boolean = 'and') { [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); $this->whereNested(function ($query) use ($columns, $operator, $value) { foreach ($columns as $column) { $query->where($column, $operator, $value, 'or'); } }, $boolean); return $this; } /** * Add an "or where" clause to the query for multiple columns with "or" conditions between them. * * @param \Illuminate\Contracts\Database\Query\Expression[]|\Closure[]|string[] $columns * @param mixed $operator * @param mixed $value * @return $this */ public function orWhereAny($columns, $operator = null, $value = null) { return $this->whereAny($columns, $operator, $value, 'or'); } /** * Add a "where not" clause to the query for multiple columns where none of the conditions should be true. * * @param \Illuminate\Contracts\Database\Query\Expression[]|\Closure[]|string[] $columns * @param mixed $operator * @param mixed $value * @param string $boolean * @return $this */ public function whereNone($columns, $operator = null, $value = null, $boolean = 'and') { return $this->whereAny($columns, $operator, $value, $boolean.' not'); } /** * Add an "or where not" clause to the query for multiple columns where none of the conditions should be true. * * @param \Illuminate\Contracts\Database\Query\Expression[]|\Closure[]|string[] $columns * @param mixed $operator * @param mixed $value * @return $this */ public function orWhereNone($columns, $operator = null, $value = null) { return $this->whereNone($columns, $operator, $value, 'or'); } /** * Add a "group by" clause to the query. * * @param array|\Illuminate\Contracts\Database\Query\Expression|string ...$groups * @return $this */ public function groupBy(...$groups) { foreach ($groups as $group) { $this->groups = array_merge( (array) $this->groups, Arr::wrap($group) ); } return $this; } /** * Add a raw groupBy clause to the query. * * @param string $sql * @param array $bindings * @return $this */ public function groupByRaw($sql, array $bindings = []) { $this->groups[] = new Expression($sql); $this->addBinding($bindings, 'groupBy'); return $this; } /** * Add a "having" clause to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|\Closure|string $column * @param string|int|float|null $operator * @param string|int|float|null $value * @param string $boolean * @return $this */ public function having($column, $operator = null, $value = null, $boolean = 'and') { $type = 'Basic'; if ($column instanceof ConditionExpression) { $type = 'Expression'; $this->havings[] = compact('type', 'column', 'boolean'); return $this; } // Here we will make some assumptions about the operator. If only 2 values are // passed to the method, we will assume that the operator is an equals sign // and keep going. Otherwise, we'll require the operator to be passed in. [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); if ($column instanceof Closure && is_null($operator)) { return $this->havingNested($column, $boolean); } // If the given operator is not found in the list of valid operators we will // assume that the developer is just short-cutting the '=' operators and // we will set the operators to '=' and set the values appropriately. if ($this->invalidOperator($operator)) { [$value, $operator] = [$operator, '=']; } if ($this->isBitwiseOperator($operator)) { $type = 'Bitwise'; } $this->havings[] = compact('type', 'column', 'operator', 'value', 'boolean'); if (! $value instanceof ExpressionContract) { $this->addBinding($this->flattenValue($value), 'having'); } return $this; } /** * Add an "or having" clause to the query. * * @param \Illuminate\Contracts\Database\Query\Expression|\Closure|string $column * @param string|int|float|null $operator * @param string|int|float|null $value * @return $this */ public function orHaving($column, $operator = null, $value = null) { [$value, $operator] = $this->prepareValueAndOperator( $value, $operator, func_num_args() === 2 ); return $this->having($column, $operator, $value, 'or'); } /** * Add a nested having statement to the query. * * @param \Closure $callback * @param string $boolean * @return $this */
194307
/** * Execute the query as a "select" statement. * * @param array|string $columns * @return \Illuminate\Support\Collection */ public function get($columns = ['*']) { $items = collect($this->onceWithColumns(Arr::wrap($columns), function () { return $this->processor->processSelect($this, $this->runSelect()); })); return $this->applyAfterQueryCallbacks( isset($this->groupLimit) ? $this->withoutGroupLimitKeys($items) : $items ); } /** * Run the query as a "select" statement against the connection. * * @return array */ protected function runSelect() { return $this->connection->select( $this->toSql(), $this->getBindings(), ! $this->useWritePdo ); } /** * Remove the group limit keys from the results in the collection. * * @param \Illuminate\Support\Collection $items * @return \Illuminate\Support\Collection */ protected function withoutGroupLimitKeys($items) { $keysToRemove = ['laravel_row']; if (is_string($this->groupLimit['column'])) { $column = last(explode('.', $this->groupLimit['column'])); $keysToRemove[] = '@laravel_group := '.$this->grammar->wrap($column); $keysToRemove[] = '@laravel_group := '.$this->grammar->wrap('pivot_'.$column); } $items->each(function ($item) use ($keysToRemove) { foreach ($keysToRemove as $key) { unset($item->$key); } }); return $items; } /** * Paginate the given query into a simple paginator. * * @param int|\Closure $perPage * @param array|string $columns * @param string $pageName * @param int|null $page * @param \Closure|int|null $total * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ public function paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null, $total = null) { $page = $page ?: Paginator::resolveCurrentPage($pageName); $total = value($total) ?? $this->getCountForPagination(); $perPage = $perPage instanceof Closure ? $perPage($total) : $perPage; $results = $total ? $this->forPage($page, $perPage)->get($columns) : collect(); return $this->paginator($results, $total, $perPage, $page, [ 'path' => Paginator::resolveCurrentPath(), 'pageName' => $pageName, ]); } /** * Get a paginator only supporting simple next and previous links. * * This is more efficient on larger data-sets, etc. * * @param int $perPage * @param array|string $columns * @param string $pageName * @param int|null $page * @return \Illuminate\Contracts\Pagination\Paginator */ public function simplePaginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null) { $page = $page ?: Paginator::resolveCurrentPage($pageName); $this->offset(($page - 1) * $perPage)->limit($perPage + 1); return $this->simplePaginator($this->get($columns), $perPage, $page, [ 'path' => Paginator::resolveCurrentPath(), 'pageName' => $pageName, ]); } /** * Get a paginator only supporting simple next and previous links. * * This is more efficient on larger data-sets, etc. * * @param int|null $perPage * @param array|string $columns * @param string $cursorName * @param \Illuminate\Pagination\Cursor|string|null $cursor * @return \Illuminate\Contracts\Pagination\CursorPaginator */ public function cursorPaginate($perPage = 15, $columns = ['*'], $cursorName = 'cursor', $cursor = null) { return $this->paginateUsingCursor($perPage, $columns, $cursorName, $cursor); } /** * Ensure the proper order by required for cursor pagination. * * @param bool $shouldReverse * @return \Illuminate\Support\Collection */ protected function ensureOrderForCursorPagination($shouldReverse = false) { if (empty($this->orders) && empty($this->unionOrders)) { $this->enforceOrderBy(); } $reverseDirection = function ($order) { if (! isset($order['direction'])) { return $order; } $order['direction'] = $order['direction'] === 'asc' ? 'desc' : 'asc'; return $order; }; if ($shouldReverse) { $this->orders = collect($this->orders)->map($reverseDirection)->toArray(); $this->unionOrders = collect($this->unionOrders)->map($reverseDirection)->toArray(); } $orders = ! empty($this->unionOrders) ? $this->unionOrders : $this->orders; return collect($orders) ->filter(fn ($order) => Arr::has($order, 'direction')) ->values(); } /** * Get the count of the total records for the paginator. * * @param array $columns * @return int */ public function getCountForPagination($columns = ['*']) { $results = $this->runPaginationCountQuery($columns); // Once we have run the pagination count query, we will get the resulting count and // take into account what type of query it was. When there is a group by we will // just return the count of the entire results set since that will be correct. if (! isset($results[0])) { return 0; } elseif (is_object($results[0])) { return (int) $results[0]->aggregate; } return (int) array_change_key_case((array) $results[0])['aggregate']; } /** * Run a pagination count query. * * @param array $columns * @return array */ protected function runPaginationCountQuery($columns = ['*']) { if ($this->groups || $this->havings) { $clone = $this->cloneForPaginationCount(); if (is_null($clone->columns) && ! empty($this->joins)) { $clone->select($this->from.'.*'); } return $this->newQuery() ->from(new Expression('('.$clone->toSql().') as '.$this->grammar->wrap('aggregate_table'))) ->mergeBindings($clone) ->setAggregate('count', $this->withoutSelectAliases($columns)) ->get()->all(); } $without = $this->unions ? ['unionOrders', 'unionLimit', 'unionOffset'] : ['columns', 'orders', 'limit', 'offset']; return $this->cloneWithout($without) ->cloneWithoutBindings($this->unions ? ['unionOrder'] : ['select', 'order']) ->setAggregate('count', $this->withoutSelectAliases($columns)) ->get()->all(); } /** * Clone the existing query instance for usage in a pagination subquery. * * @return self */ protected function cloneForPaginationCount() { return $this->cloneWithout(['orders', 'limit', 'offset']) ->cloneWithoutBindings(['order']); } /** * Remove the column aliases since they will break count queries. * * @param array $columns * @return array */ protected function withoutSelectAliases(array $columns) { return array_map(function ($column) { return is_string($column) && ($aliasPosition = stripos($column, ' as ')) !== false ? substr($column, 0, $aliasPosition) : $column; }, $columns); } /** * Get a lazy collection for the given query. * * @return \Illuminate\Support\LazyCollection */
194321
class Grammar extends BaseGrammar { use CompilesJsonPaths; /** * The grammar specific operators. * * @var array */ protected $operators = []; /** * The grammar specific bitwise operators. * * @var array */ protected $bitwiseOperators = []; /** * The components that make up a select clause. * * @var string[] */ protected $selectComponents = [ 'aggregate', 'columns', 'from', 'indexHint', 'joins', 'wheres', 'groups', 'havings', 'orders', 'limit', 'offset', 'lock', ]; /** * Compile a select query into SQL. * * @param \Illuminate\Database\Query\Builder $query * @return string */ public function compileSelect(Builder $query) { if (($query->unions || $query->havings) && $query->aggregate) { return $this->compileUnionAggregate($query); } // If a "group limit" is in place, we will need to compile the SQL to use a // different syntax. This primarily supports limits on eager loads using // Eloquent. We'll also set the columns if they have not been defined. if (isset($query->groupLimit)) { if (is_null($query->columns)) { $query->columns = ['*']; } return $this->compileGroupLimit($query); } // If the query does not have any columns set, we'll set the columns to the // * character to just get all of the columns from the database. Then we // can build the query and concatenate all the pieces together as one. $original = $query->columns; if (is_null($query->columns)) { $query->columns = ['*']; } // To compile the query, we'll spin through each component of the query and // see if that component exists. If it does we'll just call the compiler // function for the component which is responsible for making the SQL. $sql = trim($this->concatenate( $this->compileComponents($query)) ); if ($query->unions) { $sql = $this->wrapUnion($sql).' '.$this->compileUnions($query); } $query->columns = $original; return $sql; } /** * Compile the components necessary for a select clause. * * @param \Illuminate\Database\Query\Builder $query * @return array */ protected function compileComponents(Builder $query) { $sql = []; foreach ($this->selectComponents as $component) { if (isset($query->$component)) { $method = 'compile'.ucfirst($component); $sql[$component] = $this->$method($query, $query->$component); } } return $sql; } /** * Compile an aggregated select clause. * * @param \Illuminate\Database\Query\Builder $query * @param array $aggregate * @return string */ protected function compileAggregate(Builder $query, $aggregate) { $column = $this->columnize($aggregate['columns']); // If the query has a "distinct" constraint and we're not asking for all columns // we need to prepend "distinct" onto the column name so that the query takes // it into account when it performs the aggregating operations on the data. if (is_array($query->distinct)) { $column = 'distinct '.$this->columnize($query->distinct); } elseif ($query->distinct && $column !== '*') { $column = 'distinct '.$column; } return 'select '.$aggregate['function'].'('.$column.') as aggregate'; } /** * Compile the "select *" portion of the query. * * @param \Illuminate\Database\Query\Builder $query * @param array $columns * @return string|null */ protected function compileColumns(Builder $query, $columns) { // If the query is actually performing an aggregating select, we will let that // compiler handle the building of the select clauses, as it will need some // more syntax that is best handled by that function to keep things neat. if (! is_null($query->aggregate)) { return; } if ($query->distinct) { $select = 'select distinct '; } else { $select = 'select '; } return $select.$this->columnize($columns); } /** * Compile the "from" portion of the query. * * @param \Illuminate\Database\Query\Builder $query * @param string $table * @return string */ protected function compileFrom(Builder $query, $table) { return 'from '.$this->wrapTable($table); } /** * Compile the "join" portions of the query. * * @param \Illuminate\Database\Query\Builder $query * @param array $joins * @return string */ protected function compileJoins(Builder $query, $joins) { return collect($joins)->map(function ($join) use ($query) { $table = $this->wrapTable($join->table); $nestedJoins = is_null($join->joins) ? '' : ' '.$this->compileJoins($query, $join->joins); $tableAndNestedJoins = is_null($join->joins) ? $table : '('.$table.$nestedJoins.')'; if ($join instanceof JoinLateralClause) { return $this->compileJoinLateral($join, $tableAndNestedJoins); } return trim("{$join->type} join {$tableAndNestedJoins} {$this->compileWheres($join)}"); })->implode(' '); } /** * Compile a "lateral join" clause. * * @param \Illuminate\Database\Query\JoinLateralClause $join * @param string $expression * @return string * * @throws \RuntimeException */ public function compileJoinLateral(JoinLateralClause $join, string $expression): string { throw new RuntimeException('This database engine does not support lateral joins.'); } /** * Compile the "where" portions of the query. * * @param \Illuminate\Database\Query\Builder $query * @return string */ public function compileWheres(Builder $query) { // Each type of where clause has its own compiler function, which is responsible // for actually creating the where clauses SQL. This helps keep the code nice // and maintainable since each clause has a very small method that it uses. if (is_null($query->wheres)) { return ''; } // If we actually have some where clauses, we will strip off the first boolean // operator, which is added by the query builders for convenience so we can // avoid checking for the first clauses in each of the compilers methods. if (count($sql = $this->compileWheresToArray($query)) > 0) { return $this->concatenateWhereClauses($query, $sql); } return ''; } /** * Get an array of all the where clauses for the query. * * @param \Illuminate\Database\Query\Builder $query * @return array */ protected function compileWheresToArray($query) { return collect($query->wheres)->map(function ($where) use ($query) { return $where['boolean'].' '.$this->{"where{$where['type']}"}($query, $where); })->all(); } /** * Format the where clause statements into one string. * * @param \Illuminate\Database\Query\Builder $query * @param array $sql * @return string */ protected function concatenateWhereClauses($query, $sql) { $conjunction = $query instanceof JoinClause ? 'on' : 'where'; return $conjunction.' '.$this->removeLeadingBoolean(implode(' ', $sql)); } /** * Compile a raw where clause. * * @param \Illuminate\Database\Query\Builder $query * @param array $where * @return string */ protected function whereRaw(Builder $query, $where) { return $where['sql'] instanceof Expression ? $where['sql']->getValue($this) : $where['sql']; }
194345
protected function paginator($items, $total, $perPage, $currentPage, $options) { return Container::getInstance()->makeWith(LengthAwarePaginator::class, compact( 'items', 'total', 'perPage', 'currentPage', 'options' )); } /** * Create a new simple paginator instance. * * @param \Illuminate\Support\Collection $items * @param int $perPage * @param int $currentPage * @param array $options * @return \Illuminate\Pagination\Paginator */ protected function simplePaginator($items, $perPage, $currentPage, $options) { return Container::getInstance()->makeWith(Paginator::class, compact( 'items', 'perPage', 'currentPage', 'options' )); } /** * Create a new cursor paginator instance. * * @param \Illuminate\Support\Collection $items * @param int $perPage * @param \Illuminate\Pagination\Cursor $cursor * @param array $options * @return \Illuminate\Pagination\CursorPaginator */ protected function cursorPaginator($items, $perPage, $cursor, $options) { return Container::getInstance()->makeWith(CursorPaginator::class, compact( 'items', 'perPage', 'cursor', 'options' )); } /** * Pass the query to a given callback. * * @param callable($this): mixed $callback * @return $this */ public function tap($callback) { $callback($this); return $this; } }
194354
#[AsCommand(name: 'model:show')] class ShowModelCommand extends DatabaseInspectionCommand { /** * The console command name. * * @var string */ protected $name = 'model:show {model}'; /** * The console command description. * * @var string */ protected $description = 'Show information about an Eloquent model'; /** * The console command signature. * * @var string */ protected $signature = 'model:show {model : The model to show} {--database= : The database connection to use} {--json : Output the model as JSON}'; /** * The methods that can be called in a model to indicate a relation. * * @var array */ protected $relationMethods = [ 'hasMany', 'hasManyThrough', 'hasOneThrough', 'belongsToMany', 'hasOne', 'belongsTo', 'morphOne', 'morphTo', 'morphMany', 'morphToMany', 'morphedByMany', ]; /** * Execute the console command. * * @return int */ public function handle() { $class = $this->qualifyModel($this->argument('model')); try { $model = $this->laravel->make($class); $class = get_class($model); } catch (BindingResolutionException $e) { $this->components->error($e->getMessage()); return 1; } if ($this->option('database')) { $model->setConnection($this->option('database')); } $this->display( $class, $model->getConnection()->getName(), $model->getConnection()->getTablePrefix().$model->getTable(), $this->getPolicy($model), $this->getAttributes($model), $this->getRelations($model), $this->getEvents($model), $this->getObservers($model), ); return 0; } /** * Get the first policy associated with this model. * * @param \Illuminate\Database\Eloquent\Model $model * @return string */ protected function getPolicy($model) { $policy = Gate::getPolicyFor($model::class); return $policy ? $policy::class : null; } /** * Get the column attributes for the given model. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Support\Collection */ protected function getAttributes($model) { $connection = $model->getConnection(); $schema = $connection->getSchemaBuilder(); $table = $model->getTable(); $columns = $schema->getColumns($table); $indexes = $schema->getIndexes($table); return collect($columns) ->map(fn ($column) => [ 'name' => $column['name'], 'type' => $column['type'], 'increments' => $column['auto_increment'], 'nullable' => $column['nullable'], 'default' => $this->getColumnDefault($column, $model), 'unique' => $this->columnIsUnique($column['name'], $indexes), 'fillable' => $model->isFillable($column['name']), 'hidden' => $this->attributeIsHidden($column['name'], $model), 'appended' => null, 'cast' => $this->getCastType($column['name'], $model), ]) ->merge($this->getVirtualAttributes($model, $columns)); } /** * Get the virtual (non-column) attributes for the given model. * * @param \Illuminate\Database\Eloquent\Model $model * @param array $columns * @return \Illuminate\Support\Collection */ protected function getVirtualAttributes($model, $columns) { $class = new ReflectionClass($model); return collect($class->getMethods()) ->reject( fn (ReflectionMethod $method) => $method->isStatic() || $method->isAbstract() || $method->getDeclaringClass()->getName() === Model::class ) ->mapWithKeys(function (ReflectionMethod $method) use ($model) { if (preg_match('/^get(.+)Attribute$/', $method->getName(), $matches) === 1) { return [Str::snake($matches[1]) => 'accessor']; } elseif ($model->hasAttributeMutator($method->getName())) { return [Str::snake($method->getName()) => 'attribute']; } else { return []; } }) ->reject(fn ($cast, $name) => collect($columns)->contains('name', $name)) ->map(fn ($cast, $name) => [ 'name' => $name, 'type' => null, 'increments' => false, 'nullable' => null, 'default' => null, 'unique' => null, 'fillable' => $model->isFillable($name), 'hidden' => $this->attributeIsHidden($name, $model), 'appended' => $model->hasAppended($name), 'cast' => $cast, ]) ->values(); } /** * Get the relations from the given model. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Support\Collection */ protected function getRelations($model) { return collect(get_class_methods($model)) ->map(fn ($method) => new ReflectionMethod($model, $method)) ->reject( fn (ReflectionMethod $method) => $method->isStatic() || $method->isAbstract() || $method->getDeclaringClass()->getName() === Model::class || $method->getNumberOfParameters() > 0 ) ->filter(function (ReflectionMethod $method) { if ($method->getReturnType() instanceof ReflectionNamedType && is_subclass_of($method->getReturnType()->getName(), Relation::class)) { return true; } $file = new SplFileObject($method->getFileName()); $file->seek($method->getStartLine() - 1); $code = ''; while ($file->key() < $method->getEndLine()) { $code .= trim($file->current()); $file->next(); } return collect($this->relationMethods) ->contains(fn ($relationMethod) => str_contains($code, '$this->'.$relationMethod.'(')); }) ->map(function (ReflectionMethod $method) use ($model) { $relation = $method->invoke($model); if (! $relation instanceof Relation) { return null; } return [ 'name' => $method->getName(), 'type' => Str::afterLast(get_class($relation), '\\'), 'related' => get_class($relation->getRelated()), ]; }) ->filter() ->values(); } /** * Get the Events that the model dispatches. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Support\Collection */ protected function getEvents($model) { return collect($model->dispatchesEvents()) ->map(fn (string $class, string $event) => [ 'event' => $event, 'class' => $class, ])->values(); } /** * Get the Observers watching this model. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Support\Collection */ protected function getObservers($model) { $listeners = $this->getLaravel()->make('events')->getRawListeners(); // Get the Eloquent observers for this model... $listeners = array_filter($listeners, function ($v, $key) use ($model) { return Str::startsWith($key, 'eloquent.') && Str::endsWith($key, $model::class); }, ARRAY_FILTER_USE_BOTH); // Format listeners Eloquent verb => Observer methods... $extractVerb = function ($key) { preg_match('/eloquent.([a-zA-Z]+)\: /', $key, $matches); return $matches[1] ?? '?'; }; $formatted = []; foreach ($listeners as $key => $observerMethods) { $formatted[] = [ 'event' => $extractVerb($key), 'observer' => array_map(fn ($obs) => is_string($obs) ? $obs : 'Closure', $observerMethods), ]; } return collect($formatted); }
194360
<?php namespace Illuminate\Database\Console\Migrations; use Illuminate\Console\ConfirmableTrait; use Illuminate\Contracts\Console\Isolatable; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Database\Events\SchemaLoaded; use Illuminate\Database\Migrations\Migrator; use Illuminate\Database\SQLiteDatabaseDoesNotExistException; use Illuminate\Database\SqlServerConnection; use PDOException; use RuntimeException; use Symfony\Component\Console\Attribute\AsCommand; use Throwable; use function Laravel\Prompts\confirm; #[AsCommand(name: 'migrate')] class MigrateCommand extends BaseCommand implements Isolatable { use ConfirmableTrait; /** * The name and signature of the console command. * * @var string */ protected $signature = 'migrate {--database= : The database connection to use} {--force : Force the operation to run when in production} {--path=* : The path(s) to the migrations files to be executed} {--realpath : Indicate any provided migration file paths are pre-resolved absolute paths} {--schema-path= : The path to a schema dump file} {--pretend : Dump the SQL queries that would be run} {--seed : Indicates if the seed task should be re-run} {--seeder= : The class name of the root seeder} {--step : Force the migrations to be run so they can be rolled back individually} {--graceful : Return a successful exit code even if an error occurs}'; /** * The console command description. * * @var string */ protected $description = 'Run the database migrations'; /** * The migrator instance. * * @var \Illuminate\Database\Migrations\Migrator */ protected $migrator; /** * The event dispatcher instance. * * @var \Illuminate\Contracts\Events\Dispatcher */ protected $dispatcher; /** * Create a new migration command instance. * * @param \Illuminate\Database\Migrations\Migrator $migrator * @param \Illuminate\Contracts\Events\Dispatcher $dispatcher * @return void */ public function __construct(Migrator $migrator, Dispatcher $dispatcher) { parent::__construct(); $this->migrator = $migrator; $this->dispatcher = $dispatcher; } /** * Execute the console command. * * @return int */ public function handle() { if (! $this->confirmToProceed()) { return 1; } try { $this->runMigrations(); } catch (Throwable $e) { if ($this->option('graceful')) { $this->components->warn($e->getMessage()); return 0; } throw $e; } return 0; } /** * Run the pending migrations. * * @return void */ protected function runMigrations() { $this->migrator->usingConnection($this->option('database'), function () { $this->prepareDatabase(); // Next, we will check to see if a path option has been defined. If it has // we will use the path relative to the root of this installation folder // so that migrations may be run for any path within the applications. $this->migrator->setOutput($this->output) ->run($this->getMigrationPaths(), [ 'pretend' => $this->option('pretend'), 'step' => $this->option('step'), ]); // Finally, if the "seed" option has been given, we will re-run the database // seed task to re-populate the database, which is convenient when adding // a migration and a seed at the same time, as it is only this command. if ($this->option('seed') && ! $this->option('pretend')) { $this->call('db:seed', [ '--class' => $this->option('seeder') ?: 'Database\\Seeders\\DatabaseSeeder', '--force' => true, ]); } }); } /** * Prepare the migration database for running. * * @return void */ protected function prepareDatabase() { if (! $this->repositoryExists()) { $this->components->info('Preparing database.'); $this->components->task('Creating migration table', function () { return $this->callSilent('migrate:install', array_filter([ '--database' => $this->option('database'), ])) == 0; }); $this->newLine(); } if (! $this->migrator->hasRunAnyMigrations() && ! $this->option('pretend')) { $this->loadSchemaState(); } } /** * Determine if the migrator repository exists. * * @return bool */ protected function repositoryExists() { return retry(2, fn () => $this->migrator->repositoryExists(), 0, function ($e) { try { if ($e->getPrevious() instanceof SQLiteDatabaseDoesNotExistException) { return $this->createMissingSqliteDatabase($e->getPrevious()->path); } $connection = $this->migrator->resolveConnection($this->option('database')); if ( $e->getPrevious() instanceof PDOException && $e->getPrevious()->getCode() === 1049 && in_array($connection->getDriverName(), ['mysql', 'mariadb'])) { return $this->createMissingMysqlDatabase($connection); } return false; } catch (Throwable) { return false; } }); } /** * Create a missing SQLite database. * * @param string $path * @return bool * * @throws \RuntimeException */ protected function createMissingSqliteDatabase($path) { if ($this->option('force')) { return touch($path); } if ($this->option('no-interaction')) { return false; } $this->components->warn('The SQLite database configured for this application does not exist: '.$path); if (! confirm('Would you like to create it?', default: true)) { $this->components->info('Operation cancelled. No database was created.'); throw new RuntimeException('Database was not created. Aborting migration.'); } return touch($path); } /** * Create a missing MySQL database. * * @return bool * * @throws \RuntimeException */ protected function createMissingMysqlDatabase($connection) { if ($this->laravel['config']->get("database.connections.{$connection->getName()}.database") !== $connection->getDatabaseName()) { return false; } if (! $this->option('force') && $this->option('no-interaction')) { return false; } if (! $this->option('force') && ! $this->option('no-interaction')) { $this->components->warn("The database '{$connection->getDatabaseName()}' does not exist on the '{$connection->getName()}' connection."); if (! confirm('Would you like to create it?', default: true)) { $this->components->info('Operation cancelled. No database was created.'); throw new RuntimeException('Database was not created. Aborting migration.'); } } try { $this->laravel['config']->set("database.connections.{$connection->getName()}.database", null); $this->laravel['db']->purge(); $freshConnection = $this->migrator->resolveConnection($this->option('database')); return tap($freshConnection->unprepared("CREATE DATABASE IF NOT EXISTS `{$connection->getDatabaseName()}`"), function () { $this->laravel['db']->purge(); }); } finally { $this->laravel['config']->set("database.connections.{$connection->getName()}.database", $connection->getDatabaseName()); } } /** * Load the schema state to seed the initial database schema structure. * * @return void */
194394
/** * Load a set of relationships onto the mixed relationship collection. * * @param string $relation * @param array $relations * @return $this */ public function loadMorph($relation, $relations) { $this->getCollection()->loadMorph($relation, $relations); return $this; } /** * Load a set of relationship counts onto the mixed relationship collection. * * @param string $relation * @param array $relations * @return $this */ public function loadMorphCount($relation, $relations) { $this->getCollection()->loadMorphCount($relation, $relations); return $this; } /** * Get the slice of items being paginated. * * @return array */ public function items() { return $this->items->all(); } /** * Transform each item in the slice of items using a callback. * * @param callable $callback * @return $this */ public function through(callable $callback) { $this->items->transform($callback); return $this; } /** * Get the number of items shown per page. * * @return int */ public function perPage() { return $this->perPage; } /** * Get the current cursor being paginated. * * @return \Illuminate\Pagination\Cursor|null */ public function cursor() { return $this->cursor; } /** * Get the query string variable used to store the cursor. * * @return string */ public function getCursorName() { return $this->cursorName; } /** * Set the query string variable used to store the cursor. * * @param string $name * @return $this */ public function setCursorName($name) { $this->cursorName = $name; return $this; } /** * Set the base path to assign to all URLs. * * @param string $path * @return $this */ public function withPath($path) { return $this->setPath($path); } /** * Set the base path to assign to all URLs. * * @param string $path * @return $this */ public function setPath($path) { $this->path = $path; return $this; } /** * Get the base path for paginator generated URLs. * * @return string|null */ public function path() { return $this->path; } /** * Resolve the current cursor or return the default value. * * @param string $cursorName * @return \Illuminate\Pagination\Cursor|null */ public static function resolveCurrentCursor($cursorName = 'cursor', $default = null) { if (isset(static::$currentCursorResolver)) { return call_user_func(static::$currentCursorResolver, $cursorName); } return $default; } /** * Set the current cursor resolver callback. * * @param \Closure $resolver * @return void */ public static function currentCursorResolver(Closure $resolver) { static::$currentCursorResolver = $resolver; } /** * Get an instance of the view factory from the resolver. * * @return \Illuminate\Contracts\View\Factory */ public static function viewFactory() { return Paginator::viewFactory(); } /** * Get an iterator for the items. * * @return \ArrayIterator */ public function getIterator(): Traversable { return $this->items->getIterator(); } /** * Determine if the list of items is empty. * * @return bool */ public function isEmpty() { return $this->items->isEmpty(); } /** * Determine if the list of items is not empty. * * @return bool */ public function isNotEmpty() { return $this->items->isNotEmpty(); } /** * Get the number of items for the current page. * * @return int */ public function count(): int { return $this->items->count(); } /** * Get the paginator's underlying collection. * * @return \Illuminate\Support\Collection */ public function getCollection() { return $this->items; } /** * Set the paginator's underlying collection. * * @param \Illuminate\Support\Collection $collection * @return $this */ public function setCollection(Collection $collection) { $this->items = $collection; return $this; } /** * Get the paginator options. * * @return array */ public function getOptions() { return $this->options; } /** * Determine if the given item exists. * * @param mixed $key * @return bool */ public function offsetExists($key): bool { return $this->items->has($key); } /** * Get the item at the given offset. * * @param mixed $key * @return mixed */ public function offsetGet($key): mixed { return $this->items->get($key); } /** * Set the item at the given offset. * * @param mixed $key * @param mixed $value * @return void */ public function offsetSet($key, $value): void { $this->items->put($key, $value); } /** * Unset the item at the given key. * * @param mixed $key * @return void */ public function offsetUnset($key): void { $this->items->forget($key); } /** * Render the contents of the paginator to HTML. * * @return string */ public function toHtml() { return (string) $this->render(); } /** * Make dynamic calls into the collection. * * @param string $method * @param array $parameters * @return mixed */ public function __call($method, $parameters) { return $this->forwardCallTo($this->getCollection(), $method, $parameters); } /** * Render the contents of the paginator when casting to a string. * * @return string */ public function __toString() { return (string) $this->render(); } }
194429
/** * Retrieve the authenticated user using the configured guard (if any). * * @param \Illuminate\Http\Request $request * @param string $channel * @return mixed */ protected function retrieveUser($request, $channel) { $options = $this->retrieveChannelOptions($channel); $guards = $options['guards'] ?? null; if (is_null($guards)) { return $request->user(); } foreach (Arr::wrap($guards) as $guard) { if ($user = $request->user($guard)) { return $user; } } } /** * Retrieve options for a certain channel. * * @param string $channel * @return array */ protected function retrieveChannelOptions($channel) { foreach ($this->channelOptions as $pattern => $options) { if (! $this->channelNameMatchesPattern($channel, $pattern)) { continue; } return $options; } return []; } /** * Check if the channel name from the request matches a pattern from registered channels. * * @param string $channel * @param string $pattern * @return bool */ protected function channelNameMatchesPattern($channel, $pattern) { return preg_match('/^'.preg_replace('/\{(.*?)\}/', '([^\.]+)', $pattern).'$/', $channel); } /** * Get all of the registered channels. * * @return \Illuminate\Support\Collection */ public function getChannels() { return collect($this->channels); } }
194456
<?php namespace Illuminate\Cache; use Exception; use Illuminate\Contracts\Cache\LockProvider; use Illuminate\Contracts\Cache\Store; use Illuminate\Contracts\Filesystem\LockTimeoutException; use Illuminate\Filesystem\Filesystem; use Illuminate\Filesystem\LockableFile; use Illuminate\Support\InteractsWithTime; class FileStore implements Store, LockProvider { use InteractsWithTime, RetrievesMultipleKeys; /** * The Illuminate Filesystem instance. * * @var \Illuminate\Filesystem\Filesystem */ protected $files; /** * The file cache directory. * * @var string */ protected $directory; /** * The file cache lock directory. * * @var string|null */ protected $lockDirectory; /** * Octal representation of the cache file permissions. * * @var int|null */ protected $filePermission; /** * Create a new file cache store instance. * * @param \Illuminate\Filesystem\Filesystem $files * @param string $directory * @param int|null $filePermission * @return void */ public function __construct(Filesystem $files, $directory, $filePermission = null) { $this->files = $files; $this->directory = $directory; $this->filePermission = $filePermission; } /** * Retrieve an item from the cache by key. * * @param string $key * @return mixed */ public function get($key) { return $this->getPayload($key)['data'] ?? null; } /** * Store an item in the cache for a given number of seconds. * * @param string $key * @param mixed $value * @param int $seconds * @return bool */ public function put($key, $value, $seconds) { $this->ensureCacheDirectoryExists($path = $this->path($key)); $result = $this->files->put( $path, $this->expiration($seconds).serialize($value), true ); if ($result !== false && $result > 0) { $this->ensurePermissionsAreCorrect($path); return true; } return false; } /** * Store an item in the cache if the key doesn't exist. * * @param string $key * @param mixed $value * @param int $seconds * @return bool */ public function add($key, $value, $seconds) { $this->ensureCacheDirectoryExists($path = $this->path($key)); $file = new LockableFile($path, 'c+'); try { $file->getExclusiveLock(); } catch (LockTimeoutException) { $file->close(); return false; } $expire = $file->read(10); if (empty($expire) || $this->currentTime() >= $expire) { $file->truncate() ->write($this->expiration($seconds).serialize($value)) ->close(); $this->ensurePermissionsAreCorrect($path); return true; } $file->close(); return false; } /** * Create the file cache directory if necessary. * * @param string $path * @return void */ protected function ensureCacheDirectoryExists($path) { $directory = dirname($path); if (! $this->files->exists($directory)) { $this->files->makeDirectory($directory, 0777, true, true); // We're creating two levels of directories (e.g. 7e/24), so we check them both... $this->ensurePermissionsAreCorrect($directory); $this->ensurePermissionsAreCorrect(dirname($directory)); } } /** * Ensure the created node has the correct permissions. * * @param string $path * @return void */ protected function ensurePermissionsAreCorrect($path) { if (is_null($this->filePermission) || intval($this->files->chmod($path), 8) == $this->filePermission) { return; } $this->files->chmod($path, $this->filePermission); } /** * Increment the value of an item in the cache. * * @param string $key * @param mixed $value * @return int */ public function increment($key, $value = 1) { $raw = $this->getPayload($key); return tap(((int) $raw['data']) + $value, function ($newValue) use ($key, $raw) { $this->put($key, $newValue, $raw['time'] ?? 0); }); } /** * Decrement the value of an item in the cache. * * @param string $key * @param mixed $value * @return int */ public function decrement($key, $value = 1) { return $this->increment($key, $value * -1); } /** * Store an item in the cache indefinitely. * * @param string $key * @param mixed $value * @return bool */ public function forever($key, $value) { return $this->put($key, $value, 0); } /** * Get a lock instance. * * @param string $name * @param int $seconds * @param string|null $owner * @return \Illuminate\Contracts\Cache\Lock */ public function lock($name, $seconds = 0, $owner = null) { $this->ensureCacheDirectoryExists($this->lockDirectory ?? $this->directory); return new FileLock( new static($this->files, $this->lockDirectory ?? $this->directory, $this->filePermission), $name, $seconds, $owner ); } /** * Restore a lock instance using the owner identifier. * * @param string $name * @param string $owner * @return \Illuminate\Contracts\Cache\Lock */ public function restoreLock($name, $owner) { return $this->lock($name, 0, $owner); } /** * Remove an item from the cache. * * @param string $key * @return bool */ public function forget($key) { if ($this->files->exists($file = $this->path($key))) { return tap($this->files->delete($file), function ($forgotten) use ($key) { if ($forgotten && $this->files->exists($file = $this->path("illuminate:cache:flexible:created:{$key}"))) { $this->files->delete($file); } }); } return false; } /** * Remove all items from the cache. * * @return bool */ public function flush() { if (! $this->files->isDirectory($this->directory)) { return false; } foreach ($this->files->directories($this->directory) as $directory) { $deleted = $this->files->deleteDirectory($directory); if (! $deleted || $this->files->exists($directory)) { return false; } } return true; } /** * Retrieve an item and expiry time from the cache by key. * * @param string $key * @return array */
194503
<?php namespace Illuminate\Translation; use Closure; use Illuminate\Contracts\Translation\Loader; use Illuminate\Contracts\Translation\Translator as TranslatorContract; use Illuminate\Support\Arr; use Illuminate\Support\NamespacedItemResolver; use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; use Illuminate\Support\Traits\ReflectsClosures; use InvalidArgumentException; class Translator extends NamespacedItemResolver implements TranslatorContract { use Macroable, ReflectsClosures; /** * The loader implementation. * * @var \Illuminate\Contracts\Translation\Loader */ protected $loader; /** * The default locale being used by the translator. * * @var string */ protected $locale; /** * The fallback locale used by the translator. * * @var string */ protected $fallback; /** * The array of loaded translation groups. * * @var array */ protected $loaded = []; /** * The message selector. * * @var \Illuminate\Translation\MessageSelector */ protected $selector; /** * The callable that should be invoked to determine applicable locales. * * @var callable */ protected $determineLocalesUsing; /** * The custom rendering callbacks for stringable objects. * * @var array */ protected $stringableHandlers = []; /** * The callback that is responsible for handling missing translation keys. * * @var callable|null */ protected $missingTranslationKeyCallback; /** * Indicates whether missing translation keys should be handled. * * @var bool */ protected $handleMissingTranslationKeys = true; /** * Create a new translator instance. * * @param \Illuminate\Contracts\Translation\Loader $loader * @param string $locale * @return void */ public function __construct(Loader $loader, $locale) { $this->loader = $loader; $this->setLocale($locale); } /** * Determine if a translation exists for a given locale. * * @param string $key * @param string|null $locale * @return bool */ public function hasForLocale($key, $locale = null) { return $this->has($key, $locale, false); } /** * Determine if a translation exists. * * @param string $key * @param string|null $locale * @param bool $fallback * @return bool */ public function has($key, $locale = null, $fallback = true) { $locale = $locale ?: $this->locale; // We should temporarily disable the handling of missing translation keys // while perfroming the existence check. After the check, we will turn // the missing translation keys handling back to its original value. $handleMissingTranslationKeys = $this->handleMissingTranslationKeys; $this->handleMissingTranslationKeys = false; $line = $this->get($key, [], $locale, $fallback); $this->handleMissingTranslationKeys = $handleMissingTranslationKeys; // For JSON translations, the loaded files will contain the correct line. // Otherwise, we must assume we are handling typical translation file // and check if the returned line is not the same as the given key. if (! is_null($this->loaded['*']['*'][$locale][$key] ?? null)) { return true; } return $line !== $key; } /** * Get the translation for the given key. * * @param string $key * @param array $replace * @param string|null $locale * @param bool $fallback * @return string|array */ public function get($key, array $replace = [], $locale = null, $fallback = true) { $locale = $locale ?: $this->locale; // For JSON translations, there is only one file per locale, so we will simply load // that file and then we will be ready to check the array for the key. These are // only one level deep so we do not need to do any fancy searching through it. $this->load('*', '*', $locale); $line = $this->loaded['*']['*'][$locale][$key] ?? null; // If we can't find a translation for the JSON key, we will attempt to translate it // using the typical translation file. This way developers can always just use a // helper such as __ instead of having to pick between trans or __ with views. if (! isset($line)) { [$namespace, $group, $item] = $this->parseKey($key); // Here we will get the locale that should be used for the language line. If one // was not passed, we will use the default locales which was given to us when // the translator was instantiated. Then, we can load the lines and return. $locales = $fallback ? $this->localeArray($locale) : [$locale]; foreach ($locales as $languageLineLocale) { if (! is_null($line = $this->getLine( $namespace, $group, $languageLineLocale, $item, $replace ))) { return $line; } } $key = $this->handleMissingTranslationKey( $key, $replace, $locale, $fallback ); } // If the line doesn't exist, we will return back the key which was requested as // that will be quick to spot in the UI if language keys are wrong or missing // from the application's language files. Otherwise we can return the line. return $this->makeReplacements($line ?: $key, $replace); } /** * Get a translation according to an integer value. * * @param string $key * @param \Countable|int|float|array $number * @param array $replace * @param string|null $locale * @return string */ public function choice($key, $number, array $replace = [], $locale = null) { $line = $this->get( $key, $replace, $locale = $this->localeForChoice($key, $locale) ); // If the given "number" is actually an array or countable we will simply count the // number of elements in an instance. This allows developers to pass an array of // items without having to count it on their end first which gives bad syntax. if (is_countable($number)) { $number = count($number); } $replace['count'] = $number; return $this->makeReplacements( $this->getSelector()->choose($line, $number, $locale), $replace ); } /** * Get the proper locale for a choice operation. * * @param string $key * @param string|null $locale * @return string */ protected function localeForChoice($key, $locale) { $locale = $locale ?: $this->locale; return $this->hasForLocale($key, $locale) ? $locale : $this->fallback; } /** * Retrieve a language line out the loaded array. * * @param string $namespace * @param string $group * @param string $locale * @param string $item * @param array $replace * @return string|array|null */ protected function getLine($namespace, $group, $locale, $item, array $replace) { $this->load($namespace, $group, $locale); $line = Arr::get($this->loaded[$namespace][$group][$locale], $item); if (is_string($line)) { return $this->makeReplacements($line, $replace); } elseif (is_array($line) && count($line) > 0) { array_walk_recursive($line, function (&$value, $key) use ($replace) { $value = $this->makeReplacements($value, $replace); }); return $line; } } /** * Make the place-holder replacements on a line. * * @param string $line * @param array $replace * @return string */
194512
<?php namespace Illuminate\Config; use ArrayAccess; use Illuminate\Contracts\Config\Repository as ConfigContract; use Illuminate\Support\Arr; use Illuminate\Support\Traits\Macroable; use InvalidArgumentException; class Repository implements ArrayAccess, ConfigContract { use Macroable; /** * All of the configuration items. * * @var array */ protected $items = []; /** * Create a new configuration repository. * * @param array $items * @return void */ public function __construct(array $items = []) { $this->items = $items; } /** * Determine if the given configuration value exists. * * @param string $key * @return bool */ public function has($key) { return Arr::has($this->items, $key); } /** * Get the specified configuration value. * * @param array|string $key * @param mixed $default * @return mixed */ public function get($key, $default = null) { if (is_array($key)) { return $this->getMany($key); } return Arr::get($this->items, $key, $default); } /** * Get many configuration values. * * @param array $keys * @return array */ public function getMany($keys) { $config = []; foreach ($keys as $key => $default) { if (is_numeric($key)) { [$key, $default] = [$default, null]; } $config[$key] = Arr::get($this->items, $key, $default); } return $config; } /** * Get the specified string configuration value. * * @param string $key * @param (\Closure():(string|null))|string|null $default * @return string */ public function string(string $key, $default = null): string { $value = $this->get($key, $default); if (! is_string($value)) { throw new InvalidArgumentException( sprintf('Configuration value for key [%s] must be a string, %s given.', $key, gettype($value)) ); } return $value; } /** * Get the specified integer configuration value. * * @param string $key * @param (\Closure():(int|null))|int|null $default * @return int */ public function integer(string $key, $default = null): int { $value = $this->get($key, $default); if (! is_int($value)) { throw new InvalidArgumentException( sprintf('Configuration value for key [%s] must be an integer, %s given.', $key, gettype($value)) ); } return $value; } /** * Get the specified float configuration value. * * @param string $key * @param (\Closure():(float|null))|float|null $default * @return float */ public function float(string $key, $default = null): float { $value = $this->get($key, $default); if (! is_float($value)) { throw new InvalidArgumentException( sprintf('Configuration value for key [%s] must be a float, %s given.', $key, gettype($value)) ); } return $value; } /** * Get the specified boolean configuration value. * * @param string $key * @param (\Closure():(bool|null))|bool|null $default * @return bool */ public function boolean(string $key, $default = null): bool { $value = $this->get($key, $default); if (! is_bool($value)) { throw new InvalidArgumentException( sprintf('Configuration value for key [%s] must be a boolean, %s given.', $key, gettype($value)) ); } return $value; } /** * Get the specified array configuration value. * * @param string $key * @param (\Closure():(array<array-key, mixed>|null))|array<array-key, mixed>|null $default * @return array<array-key, mixed> */ public function array(string $key, $default = null): array { $value = $this->get($key, $default); if (! is_array($value)) { throw new InvalidArgumentException( sprintf('Configuration value for key [%s] must be an array, %s given.', $key, gettype($value)) ); } return $value; } /** * Set a given configuration value. * * @param array|string $key * @param mixed $value * @return void */ public function set($key, $value = null) { $keys = is_array($key) ? $key : [$key => $value]; foreach ($keys as $key => $value) { Arr::set($this->items, $key, $value); } } /** * Prepend a value onto an array configuration value. * * @param string $key * @param mixed $value * @return void */ public function prepend($key, $value) { $array = $this->get($key, []); array_unshift($array, $value); $this->set($key, $array); } /** * Push a value onto an array configuration value. * * @param string $key * @param mixed $value * @return void */ public function push($key, $value) { $array = $this->get($key, []); $array[] = $value; $this->set($key, $array); } /** * Get all of the configuration items for the application. * * @return array */ public function all() { return $this->items; } /** * Determine if the given configuration option exists. * * @param string $key * @return bool */ public function offsetExists($key): bool { return $this->has($key); } /** * Get a configuration option. * * @param string $key * @return mixed */ public function offsetGet($key): mixed { return $this->get($key); } /** * Set a configuration option. * * @param string $key * @param mixed $value * @return void */ public function offsetSet($key, $value): void { $this->set($key, $value); } /** * Unset a configuration option. * * @param string $key * @return void */ public function offsetUnset($key): void { $this->set($key, null); } }
194543
<?php namespace Illuminate\Auth; use Illuminate\Auth\Notifications\VerifyEmail; trait MustVerifyEmail { /** * Determine if the user has verified their email address. * * @return bool */ public function hasVerifiedEmail() { return ! is_null($this->email_verified_at); } /** * Mark the given user's email as verified. * * @return bool */ public function markEmailAsVerified() { return $this->forceFill([ 'email_verified_at' => $this->freshTimestamp(), ])->save(); } /** * Send the email verification notification. * * @return void */ public function sendEmailVerificationNotification() { $this->notify(new VerifyEmail); } /** * Get the email address that should be used for verification. * * @return string */ public function getEmailForVerification() { return $this->email; } }
194551
<?php namespace Illuminate\Auth\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; use Symfony\Component\HttpFoundation\Response; class RedirectIfAuthenticated { /** * The callback that should be used to generate the authentication redirect path. * * @var callable|null */ protected static $redirectToCallback; /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next, string ...$guards): Response { $guards = empty($guards) ? [null] : $guards; foreach ($guards as $guard) { if (Auth::guard($guard)->check()) { return redirect($this->redirectTo($request)); } } return $next($request); } /** * Get the path the user should be redirected to when they are authenticated. */ protected function redirectTo(Request $request): ?string { return static::$redirectToCallback ? call_user_func(static::$redirectToCallback, $request) : $this->defaultRedirectUri(); } /** * Get the default URI the user should be redirected to when they are authenticated. */ protected function defaultRedirectUri(): string { foreach (['dashboard', 'home'] as $uri) { if (Route::has($uri)) { return route($uri); } } $routes = Route::getRoutes()->get('GET'); foreach (['dashboard', 'home'] as $uri) { if (isset($routes[$uri])) { return '/'.$uri; } } return '/'; } /** * Specify the callback that should be used to generate the redirect path. * * @param callable $redirectToCallback * @return void */ public static function redirectUsing(callable $redirectToCallback) { static::$redirectToCallback = $redirectToCallback; } }