From a59fc3664e44e6259682d6208a60c35e35fce34a Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sat, 14 Nov 2026 21:36:41 +0000
Subject: [PATCH 01/29] Dispatch MigrationFailed when a migration throws
Port laravel/framework#62342 (fdaba1b7c005dd88e093861bae4017074e43229c) and laravel/docs#11457 from the recorded 13.x targets. Preserve the original exception and the existing optional-listener guard; document the failure event and its exception property.
Retain every upstream migration-event assertion and failing fixture. MigratorEventsTest passes; full static analysis and formatting pass.
---
src/database/src/Events/MigrationFailed.php | 25 ++++++++++++++++
src/database/src/Migrations/Migrator.php | 18 +++++++++---
src/docs/migrations.md | 3 +-
.../2014_10_14_000000_failing_migration.php | 15 ++++++++++
.../Database/MigratorEventsTest.php | 29 +++++++++++++++++++
5 files changed, 85 insertions(+), 5 deletions(-)
create mode 100644 src/database/src/Events/MigrationFailed.php
create mode 100644 tests/Integration/Database/Fixtures/FailingMigrations/2014_10_14_000000_failing_migration.php
diff --git a/src/database/src/Events/MigrationFailed.php b/src/database/src/Events/MigrationFailed.php
new file mode 100644
index 0000000000..61a574da3c
--- /dev/null
+++ b/src/database/src/Events/MigrationFailed.php
@@ -0,0 +1,25 @@
+getSchemaGrammar($connection)->supportsSchemaTransactions()
- && $migration->withinTransaction
- ? $connection->transaction($callback)
- : $callback();
+ try {
+ $this->getSchemaGrammar($connection)->supportsSchemaTransactions()
+ && $migration->withinTransaction
+ ? $connection->transaction($callback)
+ : $callback();
+ } catch (Throwable $exception) {
+ if ($this->hasMigrationEventListeners(MigrationFailed::class)) {
+ $this->fireMigrationEvent(new MigrationFailed($migration, $method, $name, $exception));
+ }
+
+ throw $exception;
+ }
}
/**
diff --git a/src/docs/migrations.md b/src/docs/migrations.md
index 7c655ddfbd..deef9ebcec 100644
--- a/src/docs/migrations.md
+++ b/src/docs/migrations.md
@@ -1887,6 +1887,7 @@ For convenience, each migration operation will dispatch an [event](/docs/{{versi
| `Hypervel\Database\Events\MigrationsEnded` | A batch of migrations has finished. |
| `Hypervel\Database\Events\MigrationStarted` | A single migration is about to be executed. |
| `Hypervel\Database\Events\MigrationEnded` | A single migration has finished. |
+| `Hypervel\Database\Events\MigrationFailed` | A single migration has failed. |
| `Hypervel\Database\Events\MigrationSkipped` | A single migration has been skipped. |
| `Hypervel\Database\Events\NoPendingMigrations` | A migration command found no pending migrations. |
| `Hypervel\Database\Events\SchemaDumped` | A database schema dump has finished. |
@@ -1895,4 +1896,4 @@ For convenience, each migration operation will dispatch an [event](/docs/{{versi
-The `MigrationStarted` and `MigrationEnded` events expose the migration filename through their `$name` property. The `MigrationEnded` event also exposes how long the migration took to run, in milliseconds, through its `$duration` property.
+The `MigrationStarted`, `MigrationEnded`, and `MigrationFailed` events expose the migration filename through their `$name` property. The `MigrationEnded` event also exposes how long the migration took to run, in milliseconds, through its `$duration` property. The `MigrationFailed` event exposes the exception through its `$exception` property.
diff --git a/tests/Integration/Database/Fixtures/FailingMigrations/2014_10_14_000000_failing_migration.php b/tests/Integration/Database/Fixtures/FailingMigrations/2014_10_14_000000_failing_migration.php
new file mode 100644
index 0000000000..e6fafe20a3
--- /dev/null
+++ b/tests/Integration/Database/Fixtures/FailingMigrations/2014_10_14_000000_failing_migration.php
@@ -0,0 +1,15 @@
+name === '2014_10_13_000000_skipped_migration';
});
}
+
+ public function testMigrationFailedEventIsFired(): void
+ {
+ Event::fake();
+
+ try {
+ $this->artisan('migrate', [
+ '--path' => realpath(__DIR__ . '/Fixtures/FailingMigrations'),
+ '--realpath' => true,
+ ]);
+
+ $this->fail('The migration exception was not rethrown.');
+ } catch (RuntimeException $exception) {
+ $this->assertSame('Jack ruined this migration', $exception->getMessage());
+ }
+
+ Event::assertDispatched(MigrationStarted::class, 1);
+ Event::assertNotDispatched(MigrationEnded::class);
+ Event::assertNotDispatched(MigrationsEnded::class);
+
+ Event::assertDispatched(MigrationFailed::class, function (MigrationFailed $event) use ($exception): bool {
+ return $event->method === 'up'
+ && $event->migration instanceof Migration
+ && $event->name === '2014_10_14_000000_failing_migration'
+ && $event->exception === $exception;
+ });
+ }
}
From e3fa451d24308c5ee6c21584db967c8adbe500d5 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sat, 14 Nov 2026 21:36:48 +0000
Subject: [PATCH 02/29] Enforce the email address length limit on both
validation paths
Port laravel/framework#62347 (34de79944fa771b02df74023cbc6f7ec4ae6b191) from the recorded 13.x target. Reject addresses longer than 254 bytes in delegated and compiled validation, and document the limit.
Preserve all upstream boundary inputs and assertions with coverage of both execution paths. ValidationEmailRuleTest, full static analysis and formatting pass.
---
src/docs/validation.md | 2 +-
.../src/Concerns/ValidatesAttributes.php | 8 +++++
tests/Validation/ValidationEmailRuleTest.php | 35 ++++++++++++++++---
3 files changed, 40 insertions(+), 5 deletions(-)
diff --git a/src/docs/validation.md b/src/docs/validation.md
index adc5ff2a26..0e7c9e88d9 100644
--- a/src/docs/validation.md
+++ b/src/docs/validation.md
@@ -2113,7 +2113,7 @@ The field under validation must not end with one of the given values.
#### email
-The field under validation must be formatted as an email address. This validation rule utilizes the [egulias/email-validator](https://github.com/egulias/EmailValidator) package for validating the email address. By default, the `RFCValidation` validator is applied, but you can apply other validation styles as well:
+The field under validation must be formatted as an email address no longer than 254 bytes. This validation rule utilizes the [egulias/email-validator](https://github.com/egulias/EmailValidator) package for validating the email address. By default, the `RFCValidation` validator is applied, but you can apply other validation styles as well:
```php
'email' => ['email:rfc,dns']
diff --git a/src/validation/src/Concerns/ValidatesAttributes.php b/src/validation/src/Concerns/ValidatesAttributes.php
index d203f7b2fe..ac6c9f5cd8 100644
--- a/src/validation/src/Concerns/ValidatesAttributes.php
+++ b/src/validation/src/Concerns/ValidatesAttributes.php
@@ -1006,6 +1006,10 @@ public function validateEmail(string $attribute, mixed $value, mixed $parameters
return false;
}
+ if (strlen((string) $value) > 254) {
+ return false;
+ }
+
if (preg_match('/[\r\n]/', (string) $value) > 0) {
return false;
}
@@ -1041,6 +1045,10 @@ public function validateEmail(string $attribute, mixed $value, mixed $parameters
*/
protected function isValidEmail(string $value): bool
{
+ if (strlen($value) > 254) {
+ return false;
+ }
+
if (preg_match('/[\r\n]/', $value) > 0) {
return false;
}
diff --git a/tests/Validation/ValidationEmailRuleTest.php b/tests/Validation/ValidationEmailRuleTest.php
index f0989baf6f..400a6298d7 100644
--- a/tests/Validation/ValidationEmailRuleTest.php
+++ b/tests/Validation/ValidationEmailRuleTest.php
@@ -105,6 +105,33 @@ public function testBasic(): void
$this->assertSame([], $validator->messages()->toArray());
}
+ #[TestWith(['email'])]
+ #[TestWith(['email:rfc'])]
+ public function testEmailLengthLimit(string $rule): void
+ {
+ $localPart = str_repeat('a', 64);
+ $domainAtMaximumLength = implode('.', [
+ str_repeat('a', 62),
+ str_repeat('b', 62),
+ str_repeat('c', 60),
+ str_repeat('d', 2),
+ ]);
+ $domainOverMaximumLength = implode('.', [
+ str_repeat('a', 62),
+ str_repeat('b', 62),
+ str_repeat('c', 62),
+ 'd',
+ ]);
+
+ $this->passes($rule, $localPart . '@' . $domainAtMaximumLength);
+
+ $this->fails(
+ $rule,
+ $localPart . '@' . $domainOverMaximumLength,
+ ['The ' . self::ATTRIBUTE_REPLACED . ' must be a valid email address.']
+ );
+ }
+
/**
* Assert that values fail the email rule.
*
@@ -112,7 +139,7 @@ public function testBasic(): void
* @param list $expectedMessages
*/
protected function fails(
- Email $rule,
+ Email|string $rule,
array|int|string|null $values,
array $expectedMessages,
?string $customValidationMessage = null
@@ -127,7 +154,7 @@ protected function fails(
* @param list $expectedMessages
*/
protected function assertValidationRules(
- Email $rule,
+ Email|string $rule,
array|int|string|null $values,
bool $expectToPass,
array $expectedMessages = [],
@@ -141,7 +168,7 @@ protected function assertValidationRules(
$validator = new Validator(
$translator,
[self::ATTRIBUTE => $value],
- [self::ATTRIBUTE => clone $rule],
+ [self::ATTRIBUTE => is_object($rule) ? clone $rule : $rule],
$customValidationMessage ? [self::ATTRIBUTE . '.email' => $customValidationMessage] : []
);
@@ -164,7 +191,7 @@ protected function assertValidationRules(
*
* @param null|int|list|string $values
*/
- protected function passes(Email $rule, array|int|string|null $values): void
+ protected function passes(Email|string $rule, array|int|string|null $values): void
{
$this->assertValidationRules($rule, $values, true);
}
From a6fd6c969c3d4d0f20b3f5c0fffaf5a5c1a04414 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sat, 14 Nov 2026 21:37:05 +0000
Subject: [PATCH 03/29] Preserve canonical JSON API identities and association
metadata
Adapt laravel/framework#62360 (aca3cc22f3dcdbff47468ce046a959f71db79fd4) from the recorded 13.x target. Deduplicate included resources and relationship linkage by type and ID without hashing serialized attributes or evaluating lazy values twice. Expose association data through toIdentifierMeta and use separate resources for repeated associations.
Remove pivot attributes only from included clones, preserve original model identities for cycle detection and retain descendant linkage. Protect the internal relationship map and document the approved public differences. Preserve zero IDs, distinguish absent resource classes from constructor failures, and retain resource instances supplied by relationship closures. Optional preload reconstruction remains permissive for resources requiring caller-supplied constructor arguments.
Retain and adapt upstream tests and fixtures, with metadata, cycle, discovery and constructor-state regressions. Related resource tests, full static analysis and formatting pass.
---
.../Traits/TransformsToResourceCollection.php | 3 +-
.../Concerns/TransformsToResource.php | 6 +-
src/docs/eloquent-resources.md | 41 ++++
src/docs/porting-from-laravel.md | 2 +
src/http/README.md | 2 +
.../ResourceClassNotFoundException.php | 18 ++
.../Concerns/ResolvesJsonApiElements.php | 153 +++++++++-----
.../src/Resources/JsonApi/JsonApiResource.php | 8 +
.../Resources/JsonApi/RelationResolver.php | 9 +-
.../Concerns/TransformsToResourceTest.php | 4 +-
.../JsonApi/RelationResolverTest.php | 11 +-
.../TeamWithIdentifierMetaResource.php | 51 +++++
.../TeamWithLazyAttributeResource.php | 35 ++++
.../UserWithArrayRelationshipResource.php | 3 +
.../UserWithIdentifierMetaResource.php | 48 +++++
.../UserWithLazyTeamAttributeResource.php | 36 ++++
.../JsonApi/JsonApiCollectionTest.php | 159 ++++++++++++---
.../Resources/JsonApi/JsonApiResourceTest.php | 189 +++++++++++++++---
.../Http/Resources/JsonApi/TestCase.php | 6 +-
.../TransformsToResourceCollectionTest.php | 3 +-
20 files changed, 664 insertions(+), 123 deletions(-)
create mode 100644 src/http/src/Resources/Exceptions/ResourceClassNotFoundException.php
create mode 100644 tests/Integration/Http/Resources/JsonApi/Fixtures/TeamWithIdentifierMetaResource.php
create mode 100644 tests/Integration/Http/Resources/JsonApi/Fixtures/TeamWithLazyAttributeResource.php
create mode 100644 tests/Integration/Http/Resources/JsonApi/Fixtures/UserWithIdentifierMetaResource.php
create mode 100644 tests/Integration/Http/Resources/JsonApi/Fixtures/UserWithLazyTeamAttributeResource.php
diff --git a/src/collections/src/Traits/TransformsToResourceCollection.php b/src/collections/src/Traits/TransformsToResourceCollection.php
index bdf7bed957..a07fc24528 100644
--- a/src/collections/src/Traits/TransformsToResourceCollection.php
+++ b/src/collections/src/Traits/TransformsToResourceCollection.php
@@ -6,6 +6,7 @@
use Hypervel\Database\Eloquent\Attributes\UseResource;
use Hypervel\Database\Eloquent\Attributes\UseResourceCollection;
+use Hypervel\Http\Resources\Exceptions\ResourceClassNotFoundException;
use Hypervel\Http\Resources\Json\JsonResource;
use Hypervel\Http\Resources\Json\ResourceCollection;
use LogicException;
@@ -81,7 +82,7 @@ protected function guessResourceCollection(): ResourceCollection
}
}
- throw new LogicException(sprintf('Failed to find resource class for model [%s].', $className));
+ throw ResourceClassNotFoundException::forModel($className);
}
/**
diff --git a/src/database/src/Eloquent/Concerns/TransformsToResource.php b/src/database/src/Eloquent/Concerns/TransformsToResource.php
index 6abbc4077f..a3b03042eb 100644
--- a/src/database/src/Eloquent/Concerns/TransformsToResource.php
+++ b/src/database/src/Eloquent/Concerns/TransformsToResource.php
@@ -5,9 +5,9 @@
namespace Hypervel\Database\Eloquent\Concerns;
use Hypervel\Database\Eloquent\Attributes\UseResource;
+use Hypervel\Http\Resources\Exceptions\ResourceClassNotFoundException;
use Hypervel\Http\Resources\Json\JsonResource;
use Hypervel\Support\Str;
-use LogicException;
use ReflectionClass;
/**
@@ -32,7 +32,7 @@ public function toResource(?string $resourceClass = null): JsonResource
/**
* Guess the resource class for the model.
*
- * @throws LogicException
+ * @throws ResourceClassNotFoundException
*/
protected function guessResource(): JsonResource
{
@@ -48,7 +48,7 @@ protected function guessResource(): JsonResource
}
}
- throw new LogicException(sprintf('Failed to find resource class for model [%s].', get_class($this)));
+ throw ResourceClassNotFoundException::forModel(static::class);
}
/**
diff --git a/src/docs/eloquent-resources.md b/src/docs/eloquent-resources.md
index 20906ca565..3bb7a04065 100644
--- a/src/docs/eloquent-resources.md
+++ b/src/docs/eloquent-resources.md
@@ -1315,6 +1315,47 @@ This will add `links` and `meta` keys to the resource object in the response:
}
```
+
+#### Relationship Identifier Metadata
+
+Each JSON:API resource appears once per type and ID, and each relationship lists a related identity once. Included resources omit the pivot relation. To expose data about an association, define `toIdentifierMeta` on the related resource:
+
+```php
+/**
+ * Get metadata for this resource's relationship identifier.
+ */
+public function toIdentifierMeta(Request $request): array
+{
+ return [
+ 'role' => $this->whenPivotLoaded('team_user', fn () => $this->pivot->role),
+ ];
+}
+```
+
+The result appears in the relationship identifier's `meta` object. The pivot is available to this method, and conditional helpers such as `whenPivotLoadedAs` and `mergeWhen` are supported. Returning an empty array omits `meta`.
+
+Identifier metadata describes one association between the parent and related resource. If multiple rows connect the same pair, expose those associations as resources with their own IDs; repeated identifiers with metadata are rejected when encountered. For example, a normal `Membership` model mapped to `team_user` can be exposed through a user's `memberships` relationship:
+
+```php
+use Hypervel\Http\Request;
+use Hypervel\Http\Resources\JsonApi\JsonApiResource;
+
+class MembershipResource extends JsonApiResource
+{
+ public array $relationships = ['team' => TeamResource::class];
+
+ /**
+ * Transform the membership attributes.
+ */
+ public function toAttributes(Request $request): array
+ {
+ return ['role' => $this->role];
+ }
+}
+```
+
+Map `memberships` to this resource on `UserResource`, then request `include=memberships.team`. Each membership retains its own attributes while the shared team appears once. Standard JSON resources retain their usual `whenPivotLoaded` behavior.
+
## Resource Responses
diff --git a/src/docs/porting-from-laravel.md b/src/docs/porting-from-laravel.md
index 957f109db2..1fd3318b24 100644
--- a/src/docs/porting-from-laravel.md
+++ b/src/docs/porting-from-laravel.md
@@ -626,6 +626,8 @@ Mercure applications must configure a standalone HTTP hub. Hypervel runs on Swoo
[Requested relationships](/docs/{{version}}/eloquent-resources#including-jsonapi-relationships) load before attribute callbacks, so a `whenLoaded()` attribute can appear when the client requests that relationship. [Default attributes](/docs/{{version}}/eloquent-resources#defining-jsonapi-attributes) omit `id`, `type`, and declared relationship names; explicit attribute definitions remain under your control.
+Included resources and relationship identifiers are unique by type and ID. Move pivot-dependent included attributes to `toIdentifierMeta()`; expose independently meaningful repeated associations as resources with their own IDs. See [identifier metadata](/docs/{{version}}/eloquent-resources#jsonapi-identifier-meta). Do not write `loadedRelationshipsMap` directly or override `includedResourceHash()`: the map is protected internal state and the hash hook is not provided.
+
### CSRF Protection
diff --git a/src/http/README.md b/src/http/README.md
index 46c5024e17..3195deee0d 100644
--- a/src/http/README.md
+++ b/src/http/README.md
@@ -17,6 +17,8 @@ Hypervel creates requests from Swoole's server request instead of `Request::capt
JSON:API resources load requested relationships before attribute callbacks run; default attributes exclude reserved fields and declared relationship names. See the [porting guide](https://hypervel.org/docs/porting-from-laravel#jsonapi-resources).
+JSON:API resources and relationship identifiers are unique by type and ID. Expose pivot data through `toIdentifierMeta()`; represent repeated associations as separate resources. `loadedRelationshipsMap` is protected internal state, and Laravel's `includedResourceHash()` hook is not provided. See [relationship identifier metadata](https://hypervel.org/docs/eloquent-resources#jsonapi-identifier-meta).
+
Laravel's `Http::pool()` and `Http::batch()` APIs are intentionally not ported. They are built around Guzzle promise concurrency, while Hypervel uses Swoole coroutine-native concurrency through `parallel`, `Hypervel\Coroutine\Parallel`, and `defer`. See the [concurrent requests documentation](https://hypervel.org/docs/http-client#concurrent-requests).
Pending Guzzle promises and active cURL multi-handlers belong to the coroutine that created their work. Create and finish each operation in that coroutine, then share completed results. See [Guzzle promises](https://hypervel.org/docs/http-client#guzzle-promises).
diff --git a/src/http/src/Resources/Exceptions/ResourceClassNotFoundException.php b/src/http/src/Resources/Exceptions/ResourceClassNotFoundException.php
new file mode 100644
index 0000000000..28a801bdaa
--- /dev/null
+++ b/src/http/src/Resources/Exceptions/ResourceClassNotFoundException.php
@@ -0,0 +1,18 @@
+
+ * @internal
+ * @var null|array
*/
- public ?array $loadedRelationshipsMap = null;
+ protected ?array $loadedRelationshipsMap = null;
/**
* Cached loaded relationship identifiers.
@@ -250,7 +252,7 @@ protected function compileResourceRelationshipUsingResolver(
JsonApiRequest $request,
mixed $resource,
RelationResolver $relationResolver,
- Collection|Model|null $relatedModels
+ Collection|JsonApiResource|Model|null $relatedModels
): Generator {
$relationName = $relationResolver->relationName;
$resourceClass = $relationResolver->resourceClass();
@@ -268,40 +270,57 @@ protected function compileResourceRelationshipUsingResolver(
// Default loading stays batched across parents in prepareResourceRelationships().
if (! empty($requestedRelationships) && ! $this->usesDefaultRelationshipLoading()) {
- $this->loadMissingRequestedRelationships($request, $relatedModels, $resourceClass, $requestedRelationships);
+ $this->loadMissingRequestedRelationships(
+ $request,
+ $relatedModels->map(fn ($relatedModel) => $relatedModel instanceof JsonApiResource ? $relatedModel->resource : $relatedModel),
+ $resourceClass,
+ $requestedRelationships,
+ );
}
$relationship = $resource->{$relationName}();
- $isUnique = ! $relationship instanceof BelongsToMany;
+ $pivotAccessor = $relationship instanceof BelongsToMany ? $relationship->getPivotAccessor() : null;
+ $identifiers = [];
+ $seen = [];
- yield $relationName => ['data' => $relatedModels->map(function ($relatedModel) use ($request, $resourceClass, $isUnique, $requestedRelationships) {
- $relatedResource = rescue(fn () => $relatedModel->toResource($resourceClass), new JsonApiResource($relatedModel));
-
- if (! $relatedResource instanceof JsonApiResource) {
- $relatedResource = new JsonApiResource($relatedResource->resource);
- }
+ foreach ($relatedModels as $relatedModel) {
+ $relatedResource = $relatedModel instanceof JsonApiResource ? $relatedModel : $this->makeRelatedResource($relatedModel, $resourceClass);
$relatedResource->requestedRelationships = $requestedRelationships;
- return transform(
- [$relatedResource->resolveResourceType($request), $relatedResource->resolveResourceIdentifier($request)],
- function ($uniqueKey) use ($relatedResource, $isUnique) {
- $this->loadedRelationshipsMap[] = [$relatedResource, ...$uniqueKey, $isUnique];
-
- return [
- 'id' => $uniqueKey[1],
- 'type' => $uniqueKey[0],
- ];
+ $identifier = $relatedResource->resolveResourceIdentifierObject($request);
+ $type = $identifier['type'];
+ $id = $identifier['id'];
+
+ // Duplicate instances can carry different loaded descendants that still need merging.
+ $this->loadedRelationshipsMap[] = [$relatedResource, $type, $id, $pivotAccessor];
+
+ if (isset($seen[$type][$id])) {
+ if ($seen[$type][$id] || isset($identifier['meta'])) {
+ throw new LogicException(sprintf(
+ 'Relationship [%s::%s] contains repeated resource [%s:%s] with identifier metadata. Expose the associations as separate resources.',
+ $resource::class,
+ $relationName,
+ $type,
+ $id,
+ ));
}
- );
- })->all()];
+
+ continue;
+ }
+
+ $seen[$type][$id] = isset($identifier['meta']);
+ $identifiers[] = $identifier;
+ }
+
+ yield $relationName => ['data' => $identifiers];
return;
}
// Relationship is a single model...
- $relatedModel = $relatedModels;
+ $relatedModel = $relatedModels instanceof JsonApiResource ? $relatedModels->resource : $relatedModels;
if (is_null($relatedModel)) {
yield $relationName => null;
@@ -315,25 +334,47 @@ function ($uniqueKey) use ($relatedResource, $isUnique) {
return;
}
- $relatedResource = rescue(fn () => $relatedModel->toResource($resourceClass), new JsonApiResource($relatedModel));
+ $relatedResource = $relatedModels instanceof JsonApiResource ? $relatedModels : $this->makeRelatedResource($relatedModel, $resourceClass);
+
+ $relatedResource->requestedRelationships = $requestedRelationships;
+
+ $identifier = $relatedResource->resolveResourceIdentifierObject($request);
+ $this->loadedRelationshipsMap[] = [$relatedResource, $identifier['type'], $identifier['id'], null];
- if (! $relatedResource instanceof JsonApiResource) {
- $relatedResource = new JsonApiResource($relatedResource->resource);
+ yield $relationName => ['data' => $identifier];
+ }
+
+ /**
+ * Create a resource for the related model.
+ */
+ protected function makeRelatedResource(Model $relatedModel, ?string $resourceClass): JsonApiResource
+ {
+ // Only absent mappings fall back; failures in configured resources must propagate.
+ try {
+ $relatedResource = $relatedModel->toResource($resourceClass);
+ } catch (ResourceClassNotFoundException) {
+ return new JsonApiResource($relatedModel);
}
- $relatedResource->requestedRelationships = $requestedRelationships;
+ return $relatedResource instanceof JsonApiResource ? $relatedResource : new JsonApiResource($relatedResource->resource);
+ }
- yield $relationName => ['data' => transform(
- [$relatedResource->resolveResourceType($request), $relatedResource->resolveResourceIdentifier($request)],
- function ($uniqueKey) use ($relatedResource) {
- $this->loadedRelationshipsMap[] = [$relatedResource, ...$uniqueKey, true];
+ /**
+ * Resolve a relationship identifier and its optional metadata.
+ *
+ * @return array{id: string, type: string, meta?: object}
+ */
+ protected function resolveResourceIdentifierObject(JsonApiRequest $request): array
+ {
+ $type = $this->resolveResourceType($request);
+ $id = $this->resolveResourceIdentifier($request);
+ $meta = $this->filter($this->toIdentifierMeta($request));
- return [
- 'id' => $uniqueKey[1],
- 'type' => $uniqueKey[0],
- ];
- }
- )];
+ return [
+ 'id' => $id,
+ 'type' => $type,
+ ...$meta !== [] ? ['meta' => (object) $meta] : [],
+ ];
}
/**
@@ -369,6 +410,8 @@ protected function loadMissingRequestedRelationships(
): void {
// Eager loading uses the first model's class and connection for the whole group.
$relatedModels->groupBy(fn ($relatedModel) => serialize([$relatedModel::class, $relatedModel->getConnectionName()]))->each(function ($relatedModels) use ($request, $resourceClass, $requestedRelationships) {
+ // Existing resources may need constructor arguments unavailable to this optional preload.
+ // Skip reconstruction failures; actual rendering validates resources and rescue preserves cancellation.
$relatedResource = rescue(fn () => $relatedModels->first()->toResource($resourceClass), report: false);
if (! $relatedResource instanceof JsonApiResource) {
@@ -528,10 +571,7 @@ public function resolveIncludedResourceObjects(JsonApiRequest $request): Collect
$relations = new Collection;
$index = 0;
- // Track visited objects by instance + type to prevent infinite loops from circular
- // references created by "chaperone()". We use object instances rather than type
- // and ID for any possible cases like BelongsToMany with different pivot data.
- // We'll track types to allow the same models with different resource types.
+ // Track original instances and types to stop cycles while retaining distinct loaded descendants.
$visitedObjects = new WeakMap;
$visitedObjects[$this->resource] = [
@@ -539,7 +579,7 @@ public function resolveIncludedResourceObjects(JsonApiRequest $request): Collect
];
while ($index < count($this->loadedRelationshipsMap)) {
- [$resourceInstance, $type, $id, $isUnique] = $this->loadedRelationshipsMap[$index];
+ [$resourceInstance, $type, $id, $pivotAccessor] = $this->loadedRelationshipsMap[$index];
$underlyingResource = $resourceInstance->resource;
@@ -553,21 +593,29 @@ public function resolveIncludedResourceObjects(JsonApiRequest $request): Collect
$visitedObjects[$underlyingResource][$type] = true;
}
+ if ($pivotAccessor !== null) {
+ // Association data belongs on identifiers; preserve the original model for cycle tracking and callers.
+ $resourceInstance = clone $resourceInstance;
+ $resourceInstance->resource = (clone $underlyingResource)->unsetRelation($pivotAccessor);
+ }
+
$relationsData = $resourceInstance
->includePreviouslyLoadedRelationships()
->resolve($request);
array_push($this->loadedRelationshipsMap, ...($resourceInstance->loadedRelationshipsMap ?? []));
- $relations->push(array_filter([
+ $relations->push([
'id' => $id,
'type' => $type,
- '_uniqueKey' => implode(':', $isUnique === true ? [$id, $type] : [$id, $type, (string) Str::random()]),
- 'attributes' => Arr::get($relationsData, 'data.attributes'),
- 'relationships' => Arr::get($relationsData, 'data.relationships'),
- 'links' => Arr::get($relationsData, 'data.links'),
- 'meta' => Arr::get($relationsData, 'data.meta'),
- ]));
+ '_uniqueKey' => $id . ':' . $type,
+ ...array_filter([
+ 'attributes' => Arr::get($relationsData, 'data.attributes'),
+ 'relationships' => Arr::get($relationsData, 'data.relationships'),
+ 'links' => Arr::get($relationsData, 'data.links'),
+ 'meta' => Arr::get($relationsData, 'data.meta'),
+ ]),
+ ]);
++$index;
}
@@ -575,6 +623,8 @@ public function resolveIncludedResourceObjects(JsonApiRequest $request): Collect
return $relations;
}
+ // REMOVED: includedResourceHash; JSON:API type/id defines uniqueness, with association data on identifiers.
+
/**
* Resolve included resources and preserve linkage when combining duplicate identities.
*
@@ -603,8 +653,7 @@ public static function resolveIncludedResources(Collection $resources, JsonApiRe
$relationships = (array) ($entry['relationships'] ?? []);
$root = $roots[$entry['type']][$entry['id']] ?? null;
- // Pivot variants have distinct keys and must retain their own attributes.
- if ($root !== null && $key === $entry['id'] . ':' . $entry['type']) {
+ if ($root !== null) {
$identifiers[$key] ??= [];
static::mergeResourceRelationships($root->loadedRelationshipIdentifiers, $relationships, $identifiers[$key]);
} elseif (isset($positions[$key])) {
diff --git a/src/http/src/Resources/JsonApi/JsonApiResource.php b/src/http/src/Resources/JsonApi/JsonApiResource.php
index 20a5052bea..1193969733 100644
--- a/src/http/src/Resources/JsonApi/JsonApiResource.php
+++ b/src/http/src/Resources/JsonApi/JsonApiResource.php
@@ -143,6 +143,14 @@ public function toMeta(Request $request): array
return $this->jsonApiMeta;
}
+ /**
+ * Get metadata for this resource's relationship identifier.
+ */
+ public function toIdentifierMeta(Request $request): array
+ {
+ return [];
+ }
+
/**
* Get any additional data that should be returned with the resource array.
*/
diff --git a/src/http/src/Resources/JsonApi/RelationResolver.php b/src/http/src/Resources/JsonApi/RelationResolver.php
index 3999c3b6e2..55e4c0d1eb 100644
--- a/src/http/src/Resources/JsonApi/RelationResolver.php
+++ b/src/http/src/Resources/JsonApi/RelationResolver.php
@@ -5,8 +5,8 @@
namespace Hypervel\Http\Resources\JsonApi;
use Closure;
-use Hypervel\Database\Eloquent\Collection;
use Hypervel\Database\Eloquent\Model;
+use Hypervel\Support\Collection;
use InvalidArgumentException;
/**
@@ -56,20 +56,21 @@ public function __construct(public string $relationName, Closure|string|null $re
/**
* Resolve the relation for a resource.
*/
- public function handle(mixed $resource): Collection|Model|null
+ public function handle(mixed $resource): Collection|JsonApiResource|Model|null
{
$resolved = value($this->relationResolver, $resource);
+ // Preserve supplied resources; rebuilding them from models loses constructor state.
if ($resolved instanceof AnonymousResourceCollection) {
$this->relationResourceClass ??= $resolved->collects;
- return new Collection($resolved->collection->map->resource);
+ return $resolved->collection;
}
if ($resolved instanceof JsonApiResource) {
$this->relationResourceClass ??= $resolved::class;
- return $resolved->resource;
+ return $resolved;
}
return $resolved;
diff --git a/tests/Database/Eloquent/Concerns/TransformsToResourceTest.php b/tests/Database/Eloquent/Concerns/TransformsToResourceTest.php
index 482b12b66d..f5a1515c97 100644
--- a/tests/Database/Eloquent/Concerns/TransformsToResourceTest.php
+++ b/tests/Database/Eloquent/Concerns/TransformsToResourceTest.php
@@ -6,11 +6,11 @@
use Hypervel\Database\Eloquent\Attributes\UseResource;
use Hypervel\Database\Eloquent\Model;
+use Hypervel\Http\Resources\Exceptions\ResourceClassNotFoundException;
use Hypervel\Http\Resources\Json\JsonResource;
use Hypervel\Testbench\TestCase;
use Hypervel\Tests\Database\Fixtures\Models\Administration\Billing\TransformsToResourceTestNestedModel;
use Hypervel\Tests\Database\Fixtures\Models\TransformsToResourceTestModelInModelsNamespace;
-use LogicException;
class TransformsToResourceTest extends TestCase
{
@@ -25,7 +25,7 @@ public function testToResourceWithExplicitClass(): void
public function testToResourceThrowsExceptionWhenResourceCannotBeFound(): void
{
- $this->expectException(LogicException::class);
+ $this->expectException(ResourceClassNotFoundException::class);
$this->expectExceptionMessageIs('Failed to find resource class for model [Hypervel\Tests\Database\Eloquent\Concerns\TransformsToResourceTestModel].');
$model = new TransformsToResourceTestModel;
diff --git a/tests/Http/Resources/JsonApi/RelationResolverTest.php b/tests/Http/Resources/JsonApi/RelationResolverTest.php
index 1343a8817c..3f2e518532 100644
--- a/tests/Http/Resources/JsonApi/RelationResolverTest.php
+++ b/tests/Http/Resources/JsonApi/RelationResolverTest.php
@@ -18,24 +18,25 @@ public function testResolvesClosureReturningResourceCollection(): void
$first = new RelationResolverTestModel(['id' => 1]);
$second = new RelationResolverTestModel(['id' => 2]);
- $resolver = new RelationResolver('comments', fn () => RelationResolverTestResource::collection([$first, $second]));
+ $resources = RelationResolverTestResource::collection([$first, $second]);
+ $resolver = new RelationResolver('comments', fn () => $resources);
$resolved = $resolver->handle(new RelationResolverTestModel);
- $this->assertInstanceOf(EloquentCollection::class, $resolved);
- $this->assertSame([$first, $second], $resolved->all());
+ $this->assertSame($resources->collection, $resolved);
$this->assertSame(RelationResolverTestResource::class, $resolver->resourceClass());
}
public function testResolvesClosureReturningSingleResource(): void
{
$model = new RelationResolverTestModel(['id' => 1]);
+ $resource = new RelationResolverTestResource($model);
- $resolver = new RelationResolver('author', fn () => new RelationResolverTestResource($model));
+ $resolver = new RelationResolver('author', fn () => $resource);
$resolved = $resolver->handle(new RelationResolverTestModel);
- $this->assertSame($model, $resolved);
+ $this->assertSame($resource, $resolved);
$this->assertSame(RelationResolverTestResource::class, $resolver->resourceClass());
}
diff --git a/tests/Integration/Http/Resources/JsonApi/Fixtures/TeamWithIdentifierMetaResource.php b/tests/Integration/Http/Resources/JsonApi/Fixtures/TeamWithIdentifierMetaResource.php
new file mode 100644
index 0000000000..d345a085fd
--- /dev/null
+++ b/tests/Integration/Http/Resources/JsonApi/Fixtures/TeamWithIdentifierMetaResource.php
@@ -0,0 +1,51 @@
+ UserWithIdentifierMetaResource::class];
+
+ /**
+ * Get the resource type.
+ */
+ #[Override]
+ public function toType(Request $request): string
+ {
+ return 'teams';
+ }
+
+ /**
+ * Transform the resource attributes.
+ */
+ #[Override]
+ public function toAttributes(Request $request): array
+ {
+ // The cycle regression supplies a guard so a broken traversal fails instead of hanging.
+ if ($guard = $request->attributes->get('jsonapi.resolutionGuard')) {
+ $guard();
+ }
+
+ return [
+ 'name' => $this->name,
+ 'role' => $this->whenPivotLoadedAs('membership', 'team_user', fn (): string => $this->membership->role),
+ ];
+ }
+
+ /**
+ * Get metadata for the team identifier.
+ */
+ #[Override]
+ public function toIdentifierMeta(Request $request): array
+ {
+ return [
+ 'role' => $this->whenPivotLoadedAs('membership', 'team_user', fn (): string => $this->membership->role),
+ ];
+ }
+}
diff --git a/tests/Integration/Http/Resources/JsonApi/Fixtures/TeamWithLazyAttributeResource.php b/tests/Integration/Http/Resources/JsonApi/Fixtures/TeamWithLazyAttributeResource.php
new file mode 100644
index 0000000000..9b86bef946
--- /dev/null
+++ b/tests/Integration/Http/Resources/JsonApi/Fixtures/TeamWithLazyAttributeResource.php
@@ -0,0 +1,35 @@
+ $this->name,
+ 'tags' => LazyCollection::make(fn (): Generator => yield 'php'),
+ ];
+ }
+}
diff --git a/tests/Integration/Http/Resources/JsonApi/Fixtures/UserWithArrayRelationshipResource.php b/tests/Integration/Http/Resources/JsonApi/Fixtures/UserWithArrayRelationshipResource.php
index eab08c9a22..ee470edab4 100644
--- a/tests/Integration/Http/Resources/JsonApi/Fixtures/UserWithArrayRelationshipResource.php
+++ b/tests/Integration/Http/Resources/JsonApi/Fixtures/UserWithArrayRelationshipResource.php
@@ -9,6 +9,9 @@
class UserWithArrayRelationshipResource extends JsonApiResource
{
+ // The TestCase routes inject preloaded resources through this fixture.
+ public ?array $loadedRelationshipsMap = null;
+
public function toType(Request $request): ?string
{
return 'users';
diff --git a/tests/Integration/Http/Resources/JsonApi/Fixtures/UserWithIdentifierMetaResource.php b/tests/Integration/Http/Resources/JsonApi/Fixtures/UserWithIdentifierMetaResource.php
new file mode 100644
index 0000000000..387d96ce42
--- /dev/null
+++ b/tests/Integration/Http/Resources/JsonApi/Fixtures/UserWithIdentifierMetaResource.php
@@ -0,0 +1,48 @@
+ TeamWithIdentifierMetaResource::class,
+ ];
+
+ /**
+ * Get the resource type.
+ */
+ #[Override]
+ public function toType(Request $request): string
+ {
+ return 'users';
+ }
+
+ /**
+ * Transform the resource attributes.
+ */
+ #[Override]
+ public function toAttributes(Request $request): array
+ {
+ return [
+ 'name' => $this->name,
+ 'role' => $this->whenPivotLoadedAs('membership', 'team_user', fn (): string => $this->membership->role),
+ ];
+ }
+
+ /**
+ * Get metadata for the user identifier.
+ */
+ #[Override]
+ public function toIdentifierMeta(Request $request): array
+ {
+ return [
+ $this->mergeWhen($this->hasPivotLoadedAs('membership', 'team_user'), fn (): array => ['role' => $this->membership->role]),
+ ];
+ }
+}
diff --git a/tests/Integration/Http/Resources/JsonApi/Fixtures/UserWithLazyTeamAttributeResource.php b/tests/Integration/Http/Resources/JsonApi/Fixtures/UserWithLazyTeamAttributeResource.php
new file mode 100644
index 0000000000..6ecfb2d640
--- /dev/null
+++ b/tests/Integration/Http/Resources/JsonApi/Fixtures/UserWithLazyTeamAttributeResource.php
@@ -0,0 +1,36 @@
+ TeamWithLazyAttributeResource::class,
+ ];
+
+ /**
+ * Get the resource type.
+ */
+ #[Override]
+ public function toType(Request $request): string
+ {
+ return 'users';
+ }
+
+ /**
+ * Transform the resource attributes.
+ */
+ #[Override]
+ public function toAttributes(Request $request): array
+ {
+ return [
+ 'name' => $this->name,
+ ];
+ }
+}
diff --git a/tests/Integration/Http/Resources/JsonApi/JsonApiCollectionTest.php b/tests/Integration/Http/Resources/JsonApi/JsonApiCollectionTest.php
index 8dfe4cdfe5..36b73308b1 100644
--- a/tests/Integration/Http/Resources/JsonApi/JsonApiCollectionTest.php
+++ b/tests/Integration/Http/Resources/JsonApi/JsonApiCollectionTest.php
@@ -4,6 +4,7 @@
namespace Hypervel\Tests\Integration\Http\Resources\JsonApi;
+use Hypervel\Database\Eloquent\Relations\BelongsToMany;
use Hypervel\Http\Resources\JsonApi\AnonymousResourceCollection;
use Hypervel\Http\Resources\JsonApi\JsonApiRequest;
use Hypervel\Support\Collection;
@@ -16,6 +17,9 @@
use Hypervel\Tests\Integration\Http\Resources\JsonApi\Fixtures\Team;
use Hypervel\Tests\Integration\Http\Resources\JsonApi\Fixtures\User;
use Hypervel\Tests\Integration\Http\Resources\JsonApi\Fixtures\UserResource;
+use Hypervel\Tests\Integration\Http\Resources\JsonApi\Fixtures\UserWithIdentifierMetaResource;
+use Hypervel\Tests\Integration\Http\Resources\JsonApi\Fixtures\UserWithLazyTeamAttributeResource;
+use LogicException;
use Override;
use PHPUnit\Framework\Attributes\TestWith;
@@ -84,8 +88,6 @@ public function testItCanGenerateJsonApiResponseWithEmptyRelationshipsUsingSpars
public function testItCanGenerateJsonApiResponseWithRelationshipsUsingSparseIncluded(): void
{
- $now = $this->freezeSecond();
-
$users = User::factory()->times(4)->create();
$user = User::factory()->create();
@@ -149,7 +151,6 @@ public function testItCanGenerateJsonApiResponseWithRelationshipsUsingSparseIncl
'teams' => [
'data' => [
['id' => (string) $team->getKey(), 'type' => 'teams'],
- ['id' => (string) $team->getKey(), 'type' => 'teams'],
],
],
],
@@ -189,35 +190,141 @@ public function testItCanGenerateJsonApiResponseWithRelationshipsUsingSparseIncl
'user_id' => $team->user_id,
'name' => 'Hypervel Team',
'personal_team' => true,
- 'membership' => [
- 'user_id' => $user->getKey(),
- 'team_id' => $team->getKey(),
- 'role' => 'Admin',
- 'created_at' => $now->toISOString(),
- 'updated_at' => $now->toISOString(),
- ],
- ],
- ],
- [
- 'id' => (string) $team->getKey(),
- 'type' => 'teams',
- 'attributes' => [
- 'user_id' => $team->user_id,
- 'name' => 'Hypervel Team',
- 'personal_team' => true,
- 'membership' => [
- 'user_id' => $user->getKey(),
- 'team_id' => $team->getKey(),
- 'role' => 'Member',
- 'created_at' => $now->toISOString(),
- 'updated_at' => $now->toISOString(),
- ],
],
],
]
);
}
+ #[TestWith([1])]
+ #[TestWith([0])]
+ public function testItIncludesIdenticalBelongsToManyResourcesOnce(int $identifier): void
+ {
+ $users = User::factory()->times(2)->create();
+
+ $team = Team::factory()->create([
+ 'id' => $identifier,
+ 'name' => 'Hypervel Team',
+ ]);
+
+ $users->each(fn ($user) => $user->teams()->attach($team, ['role' => 'Member']));
+
+ $this->getJson('/users?' . http_build_query(['include' => 'teams', 'fields' => ['teams' => 'name']]))
+ ->assertJsonPath('data.0.relationships.teams.data', [['id' => (string) $team->getKey(), 'type' => 'teams']])
+ ->assertJsonPath('data.1.relationships.teams.data', [['id' => (string) $team->getKey(), 'type' => 'teams']])
+ ->assertJsonPath('included', [
+ [
+ 'id' => (string) $team->getKey(),
+ 'type' => 'teams',
+ 'attributes' => [
+ 'name' => 'Hypervel Team',
+ ],
+ ],
+ ]);
+ }
+
+ public function testItIncludesIdenticalBelongsToManyResourcesWithLazyAttributesOnce(): void
+ {
+ $users = User::factory()->times(2)->create();
+
+ $team = Team::factory()->create([
+ 'name' => 'Hypervel Team',
+ ]);
+
+ $users->each(fn ($user) => $user->teams()->attach($team, ['role' => 'Member']));
+
+ Route::get('users-with-lazy-team-attributes', function (): AnonymousResourceCollection {
+ return UserWithLazyTeamAttributeResource::collection(User::all());
+ });
+
+ $this->getJson('/users-with-lazy-team-attributes?' . http_build_query(['include' => 'teams']))
+ ->assertOk()
+ ->assertJsonPath('included', [
+ [
+ 'id' => (string) $team->getKey(),
+ 'type' => 'teams',
+ 'attributes' => [
+ 'name' => 'Hypervel Team',
+ 'tags' => ['php'],
+ ],
+ ],
+ ]);
+ }
+
+ public function testIdentifierMetadataPreservesEachAssociationWhenIncludedResourcesMerge(): void
+ {
+ [$administrator, $member] = User::factory()->count(2)->create();
+ $team = Team::factory()->create(['name' => 'Hypervel Team']);
+ $administrator->teams()->attach($team, ['role' => 'Admin']);
+ $member->teams()->attach($team, ['role' => 'Member']);
+
+ $data = UserWithIdentifierMetaResource::collection([$administrator, $member])
+ ->toResponse(JsonApiRequest::create('/?include=teams.users'))
+ ->getData(true);
+
+ $this->assertSame([
+ ['id' => (string) $team->getKey(), 'type' => 'teams', 'meta' => ['role' => 'Admin']],
+ ], $data['data'][0]['relationships']['teams']['data']);
+ $this->assertSame([
+ ['id' => (string) $team->getKey(), 'type' => 'teams', 'meta' => ['role' => 'Member']],
+ ], $data['data'][1]['relationships']['teams']['data']);
+ $this->assertSame([
+ [
+ 'id' => (string) $team->getKey(),
+ 'type' => 'teams',
+ 'attributes' => ['name' => 'Hypervel Team'],
+ 'relationships' => ['users' => ['data' => [
+ ['id' => (string) $administrator->getKey(), 'type' => 'users', 'meta' => ['role' => 'Admin']],
+ ['id' => (string) $member->getKey(), 'type' => 'users', 'meta' => ['role' => 'Member']],
+ ]]],
+ ],
+ ], $data['included']);
+ $this->assertSame('Admin', $administrator->getRelation('teams')->first()->getRelation('membership')->role);
+ }
+
+ public function testRepeatedAssociationsWithIdentifierMetadataAreRejectedAfterConstrainedLoading(): void
+ {
+ $user = User::factory()->create();
+ $team = Team::factory()->create();
+ $user->teams()->attach($team, ['role' => 'Admin']);
+ $user->teams()->attach($team, ['role' => 'Member']);
+ $user->load(['teams' => fn (BelongsToMany $query): BelongsToMany => $query->wherePivot('role', 'Admin')]);
+
+ $this->expectException(LogicException::class);
+ $this->expectExceptionMessage('Expose the associations as separate resources.');
+
+ (new UserWithIdentifierMetaResource($user))->toResponse(JsonApiRequest::create('/?include=teams.users'));
+ }
+
+ public function testPreviouslyLoadedManyToManyCyclesRetainOriginalModelIdentity(): void
+ {
+ $user = User::factory()->create();
+ $team = Team::factory()->create(['name' => 'Hypervel Team']);
+ $user->setRelation('teams', $user->newCollection([$team]));
+ $team->setRelation('users', $team->newCollection([$user]));
+ $request = JsonApiRequest::create('/');
+ $resolutions = 0;
+ $request->attributes->set('jsonapi.resolutionGuard', function () use (&$resolutions): void {
+ $this->assertLessThan(3, ++$resolutions, 'The included-resource walk did not stop at a visited model.');
+ });
+
+ $data = (new UserWithIdentifierMetaResource($user))
+ ->includePreviouslyLoadedRelationships()
+ ->toResponse($request)
+ ->getData(true);
+
+ $this->assertSame([
+ [
+ 'id' => (string) $team->getKey(),
+ 'type' => 'teams',
+ 'attributes' => ['name' => 'Hypervel Team'],
+ 'relationships' => ['users' => ['data' => [
+ ['id' => (string) $user->getKey(), 'type' => 'users'],
+ ]]],
+ ],
+ ], $data['included']);
+ }
+
public function testItEagerLoadsIncludesForAllResourcesAtOnce(): void
{
$users = User::factory()->times(3)->create();
diff --git a/tests/Integration/Http/Resources/JsonApi/JsonApiResourceTest.php b/tests/Integration/Http/Resources/JsonApi/JsonApiResourceTest.php
index d592b897a6..91c409485f 100644
--- a/tests/Integration/Http/Resources/JsonApi/JsonApiResourceTest.php
+++ b/tests/Integration/Http/Resources/JsonApi/JsonApiResourceTest.php
@@ -7,20 +7,25 @@
use Hypervel\Database\Eloquent\Relations\HasMany;
use Hypervel\Database\Eloquent\Relations\HasOne;
use Hypervel\Http\Request;
+use Hypervel\Http\Resources\JsonApi\AnonymousResourceCollection;
use Hypervel\Http\Resources\JsonApi\JsonApiRequest;
use Hypervel\Http\Resources\JsonApi\JsonApiResource;
+use Hypervel\Support\Collection;
use Hypervel\Support\Facades\DB;
+use Hypervel\Support\Facades\Exceptions;
use Hypervel\Support\Facades\Route;
use Hypervel\Tests\Integration\Http\Resources\JsonApi\Fixtures\ArrayBackedJsonApiResource;
use Hypervel\Tests\Integration\Http\Resources\JsonApi\Fixtures\Comment;
use Hypervel\Tests\Integration\Http\Resources\JsonApi\Fixtures\Post;
use Hypervel\Tests\Integration\Http\Resources\JsonApi\Fixtures\PostResource;
use Hypervel\Tests\Integration\Http\Resources\JsonApi\Fixtures\Profile;
+use Hypervel\Tests\Integration\Http\Resources\JsonApi\Fixtures\ProfileResource;
use Hypervel\Tests\Integration\Http\Resources\JsonApi\Fixtures\Team;
use Hypervel\Tests\Integration\Http\Resources\JsonApi\Fixtures\User;
use Hypervel\Tests\Integration\Http\Resources\JsonApi\Fixtures\UserResource;
use Override;
use PHPUnit\Framework\Attributes\TestWith;
+use RuntimeException;
class JsonApiResourceTest extends TestCase
{
@@ -106,8 +111,6 @@ public function testItCanGenerateJsonApiResponseWithEmptyRelationshipsUsingSpars
public function testItCanGenerateJsonApiResponseWithRelationshipsUsingSparseIncluded(): void
{
- $now = $this->freezeSecond();
-
$user = User::factory()->create();
$profile = Profile::factory()->create([
@@ -153,7 +156,6 @@ public function testItCanGenerateJsonApiResponseWithRelationshipsUsingSparseIncl
'teams' => [
'data' => [
['id' => (string) $team->getKey(), 'type' => 'teams'],
- ['id' => (string) $team->getKey(), 'type' => 'teams'],
],
],
],
@@ -190,29 +192,6 @@ public function testItCanGenerateJsonApiResponseWithRelationshipsUsingSparseIncl
'user_id' => $team->user_id,
'name' => 'Hypervel Team',
'personal_team' => true,
- 'membership' => [
- 'created_at' => $now->toISOString(),
- 'role' => 'Admin',
- 'team_id' => $team->getKey(),
- 'user_id' => $user->getKey(),
- 'updated_at' => $now->toISOString(),
- ],
- ],
- ],
- [
- 'id' => (string) $team->getKey(),
- 'type' => 'teams',
- 'attributes' => [
- 'user_id' => $team->user_id,
- 'name' => 'Hypervel Team',
- 'personal_team' => true,
- 'membership' => [
- 'created_at' => $now->toISOString(),
- 'role' => 'Member',
- 'team_id' => $team->getKey(),
- 'user_id' => $user->getKey(),
- 'updated_at' => $now->toISOString(),
- ],
],
],
],
@@ -355,6 +334,131 @@ public function testItCanResolveRelationshipWithCustomNameAndResourceClass(): vo
->assertJsonMissingPath('jsonapi');
}
+ public function testToOneRelationshipIdentifiersExposeMetadata(): void
+ {
+ $user = User::factory()->create();
+ $profile = Profile::factory()->create(['user_id' => $user->getKey()]);
+ $resource = new class($user) extends UserResource {
+ /**
+ * Get the profile resource with identifier metadata.
+ */
+ #[Override]
+ public function toRelationships(Request $request): array
+ {
+ return ['profile' => function (User $user): ProfileResource {
+ return new class($user->profile) extends ProfileResource {
+ /**
+ * Get the resource type.
+ */
+ #[Override]
+ public function toType(Request $request): string
+ {
+ return 'profiles';
+ }
+
+ /**
+ * Get metadata for the profile identifier.
+ */
+ #[Override]
+ public function toIdentifierMeta(Request $request): array
+ {
+ return ['primary' => true];
+ }
+ };
+ }];
+ }
+ };
+
+ $data = $resource->toResponse(JsonApiRequest::create('/?include=profile'))->getData(true);
+
+ $this->assertSame([
+ 'id' => (string) $profile->getKey(),
+ 'type' => 'profiles',
+ 'meta' => ['primary' => true],
+ ], $data['data']['relationships']['profile']['data']);
+ }
+
+ public function testDefaultRelatedResourcesDoNotReportMissingResourceClasses(): void
+ {
+ Exceptions::fake();
+ $user = User::factory()->create();
+ $team = Team::factory()->create();
+ $user->teams()->attach($team);
+
+ $data = $user->toResource()->toResponse(JsonApiRequest::create('/?include=teams'))->getData(true);
+
+ $this->assertSame((string) $team->getKey(), $data['included'][0]['id']);
+ Exceptions::assertNothingReported();
+ }
+
+ #[TestWith(['profile', false])]
+ #[TestWith(['posts', true])]
+ public function testRelationshipClosuresPreserveResourceConstructorState(string $relationName, bool $many): void
+ {
+ $user = User::factory()->create();
+ $relatedResources = [];
+
+ foreach ($many ? ['first', 'second'] : ['first'] as $label) {
+ $relatedModel = $many
+ ? Post::factory()->create(['user_id' => $user->getKey()])
+ : Profile::factory()->create(['user_id' => $user->getKey()]);
+ $relatedResources[] = new ConstructorStateJsonApiResource($relatedModel, $label);
+
+ if ($many) {
+ Comment::factory()->create(['user_id' => $user->getKey(), 'post_id' => $relatedModel->getKey()]);
+ }
+ }
+
+ $resource = new class($user) extends UserResource {
+ public array $relationships = [];
+
+ public array $loadedModelClasses = [];
+
+ /**
+ * Record the models passed to the custom preload hook.
+ */
+ #[Override]
+ protected function loadMissingRequestedRelationships(
+ JsonApiRequest $request,
+ Collection $relatedModels,
+ ?string $resourceClass,
+ array $requestedRelationships
+ ): void {
+ $this->loadedModelClasses[] = $relatedModels->map(fn ($model) => $model::class)->all();
+
+ parent::loadMissingRequestedRelationships($request, $relatedModels, $resourceClass, $requestedRelationships);
+ }
+ };
+ $resource->relationships = [
+ $relationName => fn () => $many
+ ? new AnonymousResourceCollection($relatedResources, ConstructorStateJsonApiResource::class)
+ : $relatedResources[0],
+ ];
+
+ $data = $resource->toResponse(JsonApiRequest::create('/?include=' . $relationName . ($many ? '.comments' : '')))->getData(true);
+
+ $this->assertSame($many ? ['first', 'second'] : ['first'], array_column(array_column($data['included'], 'attributes'), 'label'));
+
+ if ($many) {
+ $this->assertSame([[Post::class, Post::class]], $resource->loadedModelClasses);
+ $this->assertCount(2, array_filter($data['included'], fn ($entry) => $entry['type'] === 'comments'));
+ }
+ }
+
+ public function testRelatedResourceConstructionErrorsAreNotReplacedWithDefaultResources(): void
+ {
+ $user = User::factory()->create();
+ $team = Team::factory()->create();
+ $user->teams()->attach($team);
+ $resource = new class($user) extends UserResource {
+ protected array $relationships = ['teams' => FailingRelatedJsonApiResource::class];
+ };
+
+ $this->expectExceptionObject(new RuntimeException('The related resource could not be constructed.'));
+
+ $resource->toResponse(JsonApiRequest::create('/?include=teams'));
+ }
+
public function testItCanResolveRelationshipWithNestedRelationship(): void
{
$now = $this->freezeSecond();
@@ -1003,3 +1107,36 @@ public function testSameModelOnDifferentResourcesIsNotDeduplicated(): void
->assertJsonCount(2, 'included');
}
}
+
+class FailingRelatedJsonApiResource extends JsonApiResource
+{
+ /**
+ * Fail while constructing the configured resource.
+ */
+ public function __construct(mixed $resource)
+ {
+ throw new RuntimeException('The related resource could not be constructed.');
+ }
+}
+
+class ConstructorStateJsonApiResource extends JsonApiResource
+{
+ protected array $relationships = ['comments'];
+
+ /**
+ * Create a resource with caller-supplied presentation state.
+ */
+ public function __construct(mixed $resource, private string $label)
+ {
+ parent::__construct($resource);
+ }
+
+ /**
+ * Transform the resource attributes.
+ */
+ #[Override]
+ public function toAttributes(Request $request): array
+ {
+ return ['label' => $this->label];
+ }
+}
diff --git a/tests/Integration/Http/Resources/JsonApi/TestCase.php b/tests/Integration/Http/Resources/JsonApi/TestCase.php
index f94cc08fc1..8d894b6172 100644
--- a/tests/Integration/Http/Resources/JsonApi/TestCase.php
+++ b/tests/Integration/Http/Resources/JsonApi/TestCase.php
@@ -61,7 +61,7 @@ protected function defineRoutes(Router $router): void
$router->get('users/{userId}/with-array-relationship', function ($userId) {
$resource = new UserWithArrayRelationshipResource(User::find($userId));
$resource->loadedRelationshipsMap = [
- [new ArrayBackedJsonApiResource(['id' => 99, 'name' => 'test']), 'things', '99', true],
+ [new ArrayBackedJsonApiResource(['id' => 99, 'name' => 'test']), 'things', '99', null],
];
return $resource;
@@ -73,8 +73,8 @@ protected function defineRoutes(Router $router): void
$resource = new UserWithArrayRelationshipResource(User::find($userId));
$resource->loadedRelationshipsMap = [
- [new UserResource($instance1), 'users', (string) $instance1->getKey(), true],
- [new UserResource($instance2), 'users', (string) $instance2->getKey(), true],
+ [new UserResource($instance1), 'users', (string) $instance1->getKey(), null],
+ [new UserResource($instance2), 'users', (string) $instance2->getKey(), null],
];
return $resource;
diff --git a/tests/Support/Traits/TransformsToResourceCollectionTest.php b/tests/Support/Traits/TransformsToResourceCollectionTest.php
index 3c25641658..c44e3dd4c4 100644
--- a/tests/Support/Traits/TransformsToResourceCollectionTest.php
+++ b/tests/Support/Traits/TransformsToResourceCollectionTest.php
@@ -9,6 +9,7 @@
use Hypervel\Database\Eloquent\Collection as EloquentCollection;
use Hypervel\Database\Eloquent\Concerns\TransformsToResource;
use Hypervel\Database\Eloquent\Model;
+use Hypervel\Http\Resources\Exceptions\ResourceClassNotFoundException;
use Hypervel\Http\Resources\Json\AnonymousResourceCollection;
use Hypervel\Http\Resources\Json\JsonResource;
use Hypervel\Http\Resources\Json\ResourceCollection;
@@ -40,7 +41,7 @@ public function testToResourceCollectionReturnsEmptyCollectionForEmptyInput(): v
public function testToResourceCollectionThrowsExceptionWhenResourceCannotBeFound(): void
{
- $this->expectException(LogicException::class);
+ $this->expectException(ResourceClassNotFoundException::class);
$this->expectExceptionMessageIs('Failed to find resource class for model [Hypervel\Tests\Support\Traits\ResourceCollectionTestModel].');
$model = new ResourceCollectionTestModel;
From f0e824a5cfc275d8a9f720bb7e0d20842cf8e0f3 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sun, 15 Nov 2026 00:03:08 +0000
Subject: [PATCH 04/29] Preserve migration failures when notification listeners
throw
Report MigrationFailed listener errors without replacing the original migration exception. Preserve cancellation behavior through the existing rescue helper.
Follow-up to laravel/framework#62342 (fdaba1b7c005dd88e093861bae4017074e43229c).
Validation: migration-event regression and full static analysis pass.
---
src/database/src/Migrations/Migrator.php | 3 ++-
.../Database/MigratorEventsTest.php | 27 +++++++++++++++++++
2 files changed, 29 insertions(+), 1 deletion(-)
diff --git a/src/database/src/Migrations/Migrator.php b/src/database/src/Migrations/Migrator.php
index 63ed30f2e9..5918104467 100755
--- a/src/database/src/Migrations/Migrator.php
+++ b/src/database/src/Migrations/Migrator.php
@@ -463,7 +463,8 @@ protected function runMigration(object $migration, string $method, ?string $name
: $callback();
} catch (Throwable $exception) {
if ($this->hasMigrationEventListeners(MigrationFailed::class)) {
- $this->fireMigrationEvent(new MigrationFailed($migration, $method, $name, $exception));
+ // Report notification failures without hiding the original migration error.
+ rescue(fn () => $this->fireMigrationEvent(new MigrationFailed($migration, $method, $name, $exception)));
}
throw $exception;
diff --git a/tests/Integration/Database/MigratorEventsTest.php b/tests/Integration/Database/MigratorEventsTest.php
index 28cc44e017..512e8babdb 100644
--- a/tests/Integration/Database/MigratorEventsTest.php
+++ b/tests/Integration/Database/MigratorEventsTest.php
@@ -15,6 +15,7 @@
use Hypervel\Database\Migrations\Migration;
use Hypervel\Foundation\Testing\DatabaseMigrations;
use Hypervel\Support\Facades\Event;
+use Hypervel\Support\Facades\Exceptions;
use Hypervel\Testbench\TestCase;
use RuntimeException;
@@ -222,4 +223,30 @@ public function testMigrationFailedEventIsFired(): void
&& $event->exception === $exception;
});
}
+
+ public function testFailingMigrationListenerDoesNotReplaceTheMigrationException(): void
+ {
+ Exceptions::fake();
+ $listenerException = new RuntimeException('The failure notification could not be delivered.');
+ $migrationException = null;
+
+ Event::listen(MigrationFailed::class, function (MigrationFailed $event) use ($listenerException, &$migrationException): void {
+ $migrationException = $event->exception;
+
+ throw $listenerException;
+ });
+
+ try {
+ $this->artisan('migrate', [
+ '--path' => realpath(__DIR__ . '/Fixtures/FailingMigrations'),
+ '--realpath' => true,
+ ]);
+
+ $this->fail('The migration exception was not rethrown.');
+ } catch (RuntimeException $exception) {
+ $this->assertSame($migrationException, $exception);
+ }
+
+ Exceptions::assertReported(fn (RuntimeException $exception): bool => $exception === $listenerException);
+ }
}
From 68d88dafd3ad015e22cbdca259931bbe787d6f9c Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sun, 15 Nov 2026 00:03:09 +0000
Subject: [PATCH 05/29] Clarify related resource variables in JSON API
resolution
Name relationship values consistently when they may contain either models or already constructed resources.
Follow-up to laravel/framework#62360 (aca3cc22f3dcdbff47468ce046a959f71db79fd4).
Validation: full static analysis passes; behavior is unchanged.
---
.../Resources/JsonApi/Concerns/ResolvesJsonApiElements.php | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/http/src/Resources/JsonApi/Concerns/ResolvesJsonApiElements.php b/src/http/src/Resources/JsonApi/Concerns/ResolvesJsonApiElements.php
index aad11e7922..c9360bbc2e 100644
--- a/src/http/src/Resources/JsonApi/Concerns/ResolvesJsonApiElements.php
+++ b/src/http/src/Resources/JsonApi/Concerns/ResolvesJsonApiElements.php
@@ -272,7 +272,7 @@ protected function compileResourceRelationshipUsingResolver(
if (! empty($requestedRelationships) && ! $this->usesDefaultRelationshipLoading()) {
$this->loadMissingRequestedRelationships(
$request,
- $relatedModels->map(fn ($relatedModel) => $relatedModel instanceof JsonApiResource ? $relatedModel->resource : $relatedModel),
+ $relatedModels->map(fn ($related) => $related instanceof JsonApiResource ? $related->resource : $related),
$resourceClass,
$requestedRelationships,
);
@@ -284,8 +284,8 @@ protected function compileResourceRelationshipUsingResolver(
$identifiers = [];
$seen = [];
- foreach ($relatedModels as $relatedModel) {
- $relatedResource = $relatedModel instanceof JsonApiResource ? $relatedModel : $this->makeRelatedResource($relatedModel, $resourceClass);
+ foreach ($relatedModels as $related) {
+ $relatedResource = $related instanceof JsonApiResource ? $related : $this->makeRelatedResource($related, $resourceClass);
$relatedResource->requestedRelationships = $requestedRelationships;
From a26bd0b157d1f009a46370f4529966af754c5e77 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sun, 15 Nov 2026 00:03:09 +0000
Subject: [PATCH 06/29] Add URI origin inspection
Expose Uri::origin with upstream opaque-origin behavior, including custom UriInterface values. Raise the league/uri minimum to 7.6 and document the helper.
Port laravel/framework#62326 (f8080dd48e34ad9d4bdfa91a38e987db6a3b87b7), reconciled at c980cb5827c6512c12ac44493d172a593b41299a.
Validation: complete URI test class and full static analysis pass.
---
composer.json | 2 +-
src/docs/helpers.md | 3 +++
src/support/composer.json | 2 +-
src/support/src/Uri.php | 12 ++++++++++++
tests/Support/SupportUriTest.php | 21 +++++++++++++++++++++
5 files changed, 38 insertions(+), 2 deletions(-)
diff --git a/composer.json b/composer.json
index d98153b8f2..1b1f703fbb 100644
--- a/composer.json
+++ b/composer.json
@@ -70,7 +70,7 @@
"league/flysystem-path-prefixing": "^3.25.1",
"league/flysystem-read-only": "^3.25.1",
"league/oauth2-server": "^9.4",
- "league/uri": "^7.5.1",
+ "league/uri": "^7.6",
"monolog/monolog": "^3.10",
"nesbot/carbon": "^3.13.1",
"nikic/php-parser": "^5.7",
diff --git a/src/docs/helpers.md b/src/docs/helpers.md
index 8e57afb769..cf288122b5 100644
--- a/src/docs/helpers.md
+++ b/src/docs/helpers.md
@@ -3968,12 +3968,15 @@ $scheme = $uri->scheme();
$authority = $uri->authority();
$host = $uri->host();
$port = $uri->port();
+$origin = $uri->origin();
$path = $uri->path();
$segments = $uri->pathSegments();
$query = $uri->query();
$fragment = $uri->fragment();
```
+The `origin` method returns the URI's scheme, host, and non-default port, without credentials, path, query, or fragment. Relative URIs and opaque origins, such as `mailto:` and `file:`, return `null`.
+
#### Manipulating Query Strings
diff --git a/src/support/composer.json b/src/support/composer.json
index 65d005841a..a7aa75721b 100644
--- a/src/support/composer.json
+++ b/src/support/composer.json
@@ -52,7 +52,7 @@
"hypervel/view": "^0.4",
"laravel/serializable-closure": "^2.0.11",
"league/commonmark": "^2.10.3",
- "league/uri": "^7.5.1",
+ "league/uri": "^7.6",
"nesbot/carbon": "^3.13.1",
"phpoption/phpoption": "^1.9",
"symfony/console": "^8.1.10",
diff --git a/src/support/src/Uri.php b/src/support/src/Uri.php
index cf343a05f0..0e854cebdf 100644
--- a/src/support/src/Uri.php
+++ b/src/support/src/Uri.php
@@ -153,6 +153,18 @@ public function port(): ?int
return $this->uri->getPort();
}
+ /**
+ * Get the URI's origin.
+ *
+ * Opaque origins, such as those of relative or "mailto:" URIs, are returned as null.
+ */
+ public function origin(): ?string
+ {
+ $uri = $this->uri instanceof LeagueUri ? $this->uri : LeagueUri::new($this->value());
+
+ return $uri->getOrigin();
+ }
+
/**
* Get the URI's path.
*
diff --git a/tests/Support/SupportUriTest.php b/tests/Support/SupportUriTest.php
index 0e79490cd9..6fb5296a7b 100644
--- a/tests/Support/SupportUriTest.php
+++ b/tests/Support/SupportUriTest.php
@@ -13,6 +13,7 @@
use Hypervel\Support\Uri;
use Hypervel\Tests\Support\Concerns\TestsInteractsWithDataContract;
use Hypervel\Tests\TestCase;
+use League\Uri\Contracts\UriInterface;
use League\Uri\Uri as LeagueUri;
use Mockery as m;
use stdClass;
@@ -50,6 +51,7 @@ public function testBasicUriInteractions(): void
{
$uri = Uri::of($originalUri = 'https://hypervel.org/docs/installation');
+ $this->assertSame('https://hypervel.org', $uri->origin());
$this->assertSame('https', $uri->scheme());
$this->assertNull($uri->user());
$this->assertNull($uri->password());
@@ -64,6 +66,7 @@ public function testBasicUriInteractions(): void
$uri = Uri::of('https://taylor:password@hypervel.org/docs/installation?version=1#hello');
+ $this->assertSame('https://hypervel.org', $uri->origin());
$this->assertSame('taylor', $uri->user());
$this->assertSame('password', $uri->password());
$this->assertSame('hello', $uri->fragment());
@@ -81,6 +84,24 @@ public function testIsEmptyAndIsNotEmpty(): void
$this->assertTrue(Uri::of('https://hypervel.org')->isNotEmpty());
}
+ public function testOrigin(): void
+ {
+ $this->assertSame('https://github.com:80', Uri::of('https://github.com:80/a/b#x')->origin());
+ $this->assertSame('https://a.com', Uri::of('https://A.com:443/x')->origin());
+ $this->assertSame('http://a.com', Uri::of('http://a.com:80')->origin());
+ $this->assertSame('wss://a.com:8080', Uri::of('wss://a.com:8080/socket')->origin());
+
+ $this->assertNull(Uri::of('/rel')->origin());
+ $this->assertNull(Uri::of('mailto:x@y.z')->origin());
+ $this->assertNull(Uri::of('file:///etc/hosts')->origin());
+ $this->assertNull(Uri::of('')->origin());
+
+ $customUri = m::mock(UriInterface::class);
+ $customUri->shouldReceive('toString')->once()->andReturn('https://example.com:8443/path');
+
+ $this->assertSame('https://example.com:8443', Uri::of($customUri)->origin());
+ }
+
public function testWithoutFragment(): void
{
$uri = Uri::of('https://hypervel.org/docs/installation#introduction');
From 710f1ab6d8319002d951857158f4579709ae636f Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sun, 15 Nov 2026 00:03:09 +0000
Subject: [PATCH 07/29] Cover reconnection after a lost transaction commit
Consolidate the upstream reconnect regression with the existing stronger lost-commit cleanup test. Retain callback and transaction-manager cleanup, original exception identity and rejection of calls on the dead PDO.
Port laravel/framework#62366 (703ffc3617cdea72e626f45e008b3ef1ecf82262). Existing production cleanup already discards both PDO handles.
Validation: the complete PDO connection test class passes.
---
tests/Database/DatabasePdoConnectionTest.php | 16 +++++++++++++---
1 file changed, 13 insertions(+), 3 deletions(-)
diff --git a/tests/Database/DatabasePdoConnectionTest.php b/tests/Database/DatabasePdoConnectionTest.php
index 0305ace137..b8690562d6 100755
--- a/tests/Database/DatabasePdoConnectionTest.php
+++ b/tests/Database/DatabasePdoConnectionTest.php
@@ -994,9 +994,9 @@ public function testExplicitPhysicalCommitFailureLeavesTheTransactionCallerOwned
$connection->rollBack();
}
- public function testLostManagedCommitTerminallyDetachesTransactionState(): void
+ public function testLostConnectionDuringCommitDiscardsPdoSoTheNextTransactionReconnects(): void
{
- $failure = new PDOException('server has gone away');
+ $failure = new PDOException('SQLSTATE[08006] [7] no connection to the server');
$pdo = $this->getMockBuilder(PDOStub::class)
->onlyMethods(['beginTransaction', 'commit', 'inTransaction', 'rollBack'])
->getMock();
@@ -1005,21 +1005,29 @@ public function testLostManagedCommitTerminallyDetachesTransactionState(): void
$pdo->expects($this->never())->method('inTransaction');
$pdo->expects($this->never())->method('rollBack');
+ $freshPdo = $this->getMockBuilder(PDOStub::class)->onlyMethods(['beginTransaction', 'commit'])->getMock();
+ $freshPdo->expects($this->once())->method('beginTransaction');
+ $freshPdo->expects($this->once())->method('commit');
+
$connection = $this->getMockConnection([], $pdo);
+ $connection->setReconnector(fn (PdoConnection $connection) => $connection->setPdo($freshPdo));
$connection->setReadPdo(new PDOStub);
$manager = new DatabaseTransactionsManager;
$connection->setTransactionManager($manager);
$rollbackCallbackCalled = false;
try {
- $connection->transaction(function (Connection $connection) use (&$rollbackCallbackCalled): void {
+ $connection->transaction(function (Connection $connection) use (&$rollbackCallbackCalled): string {
$connection->afterRollBack(function () use (&$rollbackCallbackCalled): void {
$rollbackCallbackCalled = true;
});
+
+ return 'first';
});
$this->fail('Expected the lost commit to fail.');
} catch (PDOException $exception) {
$this->assertSame($failure, $exception);
+ $this->assertSame('SQLSTATE[08006] [7] no connection to the server', $exception->getMessage());
}
$this->assertTrue($rollbackCallbackCalled);
@@ -1028,6 +1036,8 @@ public function testLostManagedCommitTerminallyDetachesTransactionState(): void
$this->assertCount(0, $manager->getCommittedTransactions());
$this->assertNull($connection->getRawPdo());
$this->assertNull($connection->getRawReadPdo());
+
+ $this->assertSame('second', $connection->transaction(fn () => 'second'));
}
#[DataProvider('lostTransactionOperations')]
From ceccbdcb8e9f9789ad18495cfb7711f963eb9335 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sun, 15 Nov 2026 00:03:09 +0000
Subject: [PATCH 08/29] Honor the integer key alias across schema and identity
handling
Treat int and integer consistently in foreign-key columns, route binding, Sanctum token validation, permission pivot normalization and schema inference. Preserve early rejection of invalid integer identifiers and idempotent role assignment.
Port laravel/framework#62365 (4997a3c1607f0fa28b15292b4c4d0c357fbc1a76) and fix the same alias omission in affected consumers.
Validation: reproduced each omission; affected schema, route, token, permission and analyzer tests plus full static analysis pass.
---
src/database/src/Eloquent/Model.php | 2 +-
src/database/src/Schema/Blueprint.php | 2 +-
src/permission/src/Traits/HasPermissions.php | 2 +-
.../src/Properties/SchemaAggregator.php | 2 +-
src/sanctum/src/PersonalAccessToken.php | 2 +-
.../DatabaseEloquentRouteBindingTest.php | 7 ++++--
.../Database/DatabaseSchemaBlueprintTest.php | 14 +++++++++++
.../EloquentModelUsingIntegerKeyType.php | 25 +++++++++++++++++++
tests/PHPStan/Unit/SchemaAggregatorTest.php | 16 ++++++++++++
tests/Permission/Traits/HasRolesTest.php | 15 ++++++++++-
.../Sanctum/PersonalAccessTokenCacheTest.php | 17 ++++++++++---
11 files changed, 92 insertions(+), 12 deletions(-)
create mode 100644 tests/Database/Fixtures/Models/EloquentModelUsingIntegerKeyType.php
diff --git a/src/database/src/Eloquent/Model.php b/src/database/src/Eloquent/Model.php
index 4e250c072d..c3c9008a46 100644
--- a/src/database/src/Eloquent/Model.php
+++ b/src/database/src/Eloquent/Model.php
@@ -2955,7 +2955,7 @@ public function resolveRouteBindingQuery(self|Builder|Relation $query, mixed $va
// Non-incrementing integer keys are validated too: MySQL and MariaDB would
// otherwise coerce a value such as "12abc" and resolve the model with key 12.
- if ($this->getKeyType() === 'int'
+ if (in_array($this->getKeyType(), ['int', 'integer'], true)
&& Str::afterLast($field, '.') === $this->getKeyName()
&& ! $this->isValidIntegerRouteKey($value)) {
$this->handleInvalidRouteKey($value, $field);
diff --git a/src/database/src/Schema/Blueprint.php b/src/database/src/Schema/Blueprint.php
index 9a57451d21..d28942d3f4 100755
--- a/src/database/src/Schema/Blueprint.php
+++ b/src/database/src/Schema/Blueprint.php
@@ -994,7 +994,7 @@ public function foreignIdFor(Model|string $model, ?string $column = null): Forei
$column = $column ?: $model->getForeignKey();
- if ($model->getKeyType() === 'int') {
+ if (in_array($model->getKeyType(), ['int', 'integer'], true)) {
return $this->foreignId($column)
->table($model->getTable())
->referencesModelColumn($model->getKeyName());
diff --git a/src/permission/src/Traits/HasPermissions.php b/src/permission/src/Traits/HasPermissions.php
index 36070ca87c..aaf106cdad 100644
--- a/src/permission/src/Traits/HasPermissions.php
+++ b/src/permission/src/Traits/HasPermissions.php
@@ -1068,7 +1068,7 @@ protected function indexAssignmentIds(array $ids): array
*/
protected function normalizeRelatedPivotId(BelongsToMany $relation, mixed $id): int|string
{
- return $relation->getRelated()->getKeyType() === 'int'
+ return in_array($relation->getRelated()->getKeyType(), ['int', 'integer'], true)
? (int) $id
: (string) $id;
}
diff --git a/src/phpstan/src/Properties/SchemaAggregator.php b/src/phpstan/src/Properties/SchemaAggregator.php
index 51aebc44aa..87baa82a67 100644
--- a/src/phpstan/src/Properties/SchemaAggregator.php
+++ b/src/phpstan/src/Properties/SchemaAggregator.php
@@ -2078,7 +2078,7 @@ private function processStatementAlterMethod(
$type = match (true) {
$method === 'foreignuuidfor' => 'uuid',
$method === 'foreignulidfor' => 'char',
- $model->getKeyType() === 'int' => 'biginteger',
+ in_array($model->getKeyType(), ['int', 'integer'], true) => 'biginteger',
isset(class_uses_recursive($model)[HasUlids::class]) => 'char',
default => 'uuid',
};
diff --git a/src/sanctum/src/PersonalAccessToken.php b/src/sanctum/src/PersonalAccessToken.php
index 865c80e015..d888cc44e5 100644
--- a/src/sanctum/src/PersonalAccessToken.php
+++ b/src/sanctum/src/PersonalAccessToken.php
@@ -111,7 +111,7 @@ public static function findToken(string $token): ?static
return null;
}
- if ((new static)->getKeyType() === 'int'
+ if (in_array((new static)->getKeyType(), ['int', 'integer'], true)
&& (! ctype_digit($id) || filter_var($id, FILTER_VALIDATE_INT) === false)) {
return null;
}
diff --git a/tests/Database/DatabaseEloquentRouteBindingTest.php b/tests/Database/DatabaseEloquentRouteBindingTest.php
index b69133bcb8..68e03ee3cf 100644
--- a/tests/Database/DatabaseEloquentRouteBindingTest.php
+++ b/tests/Database/DatabaseEloquentRouteBindingTest.php
@@ -12,6 +12,7 @@
use Hypervel\Tests\TestCase;
use Mockery as m;
use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\Attributes\TestWith;
use RuntimeException;
class DatabaseEloquentRouteBindingTest extends TestCase
@@ -75,14 +76,16 @@ public static function validIntegerKeyProvider(): array
];
}
- public function testItValidatesQualifiedKeyColumnsFromChildBindings(): void
+ #[TestWith(['int'])]
+ #[TestWith(['integer'])]
+ public function testItValidatesQualifiedKeyColumnsFromChildBindings(string $keyType): void
{
$query = m::mock(Builder::class);
$query->shouldNotReceive('where');
$this->expectException(ModelNotFoundException::class);
- (new RouteBindingIntKeyModel)->resolveRouteBindingQuery($query, 'abc', 'route_binding_int_key_models.id');
+ (new RouteBindingIntKeyModel)->setKeyType($keyType)->resolveRouteBindingQuery($query, 'abc', 'route_binding_int_key_models.id');
}
public function testItDoesNotValidateNonKeyBindingFields(): void
diff --git a/tests/Database/DatabaseSchemaBlueprintTest.php b/tests/Database/DatabaseSchemaBlueprintTest.php
index 34d6cd76f3..434ac52996 100755
--- a/tests/Database/DatabaseSchemaBlueprintTest.php
+++ b/tests/Database/DatabaseSchemaBlueprintTest.php
@@ -17,6 +17,7 @@
use Hypervel\Database\Schema\IndexDefinition;
use Hypervel\Foundation\Auth\User as Authenticatable;
use Hypervel\Support\Fluent;
+use Hypervel\Tests\Database\Fixtures\Models\EloquentModelUsingIntegerKeyType;
use Hypervel\Tests\Database\Fixtures\Models\EloquentModelUsingNonIncrementedInt;
use Hypervel\Tests\Database\Fixtures\Models\EloquentModelUsingUlid;
use Hypervel\Tests\Database\Fixtures\Models\EloquentModelUsingUuid;
@@ -729,6 +730,19 @@ public function testGenerateRelationshipColumnWithNonIncrementalModel(): void
], $getSql('MySql'));
}
+ public function testGenerateRelationshipColumnWithIntegerKeyTypeModel(): void
+ {
+ $getSql = function ($grammar) {
+ return $this->getBlueprint($grammar, 'posts', function ($table) {
+ $table->foreignIdFor(EloquentModelUsingIntegerKeyType::class);
+ })->toSql();
+ };
+
+ $this->assertEquals([
+ 'alter table `posts` add `model_using_integer_key_type_id` bigint unsigned not null',
+ ], $getSql('MySql'));
+ }
+
public function testGenerateRelationshipColumnWithUuidModel(): void
{
$getSql = function ($grammar) {
diff --git a/tests/Database/Fixtures/Models/EloquentModelUsingIntegerKeyType.php b/tests/Database/Fixtures/Models/EloquentModelUsingIntegerKeyType.php
new file mode 100644
index 0000000000..6c2ec19937
--- /dev/null
+++ b/tests/Database/Fixtures/Models/EloquentModelUsingIntegerKeyType.php
@@ -0,0 +1,25 @@
+assertSame([], $this->columns($aggregator, 'compensations'));
}
+ #[Test]
+ public function itResolvesForeignIdsForTheIntegerKeyTypeAlias(): void
+ {
+ $model = EloquentModelUsingIntegerKeyType::class;
+ $aggregator = $this->aggregate(<<foreignIdFor('{$model}');
+ });
+ PHP);
+
+ $this->assertSame([
+ 'model_using_integer_key_type_id' => ['int<0, max>|numeric-string', false],
+ ], $this->columns($aggregator, 'posts'));
+ }
+
/**
* The files a table's columns are read from are its sources, while the files that can change which tables exist
* or which connection a migration runs on are sources of every fact.
diff --git a/tests/Permission/Traits/HasRolesTest.php b/tests/Permission/Traits/HasRolesTest.php
index 940411bb40..4e7ee4b5be 100644
--- a/tests/Permission/Traits/HasRolesTest.php
+++ b/tests/Permission/Traits/HasRolesTest.php
@@ -14,6 +14,8 @@
use Hypervel\Permission\Events\RoleDetachedEvent;
use Hypervel\Permission\Exceptions\GuardDoesNotMatch;
use Hypervel\Permission\Exceptions\RoleDoesNotExist;
+use Hypervel\Permission\Models\Role as BaseRole;
+use Hypervel\Permission\PermissionRegistrar;
use Hypervel\Permission\Traits\HasRoles;
use Hypervel\Support\Facades\DB;
use Hypervel\Support\Facades\Event;
@@ -24,6 +26,7 @@
use Hypervel\Tests\Permission\Fixtures\Models\UserWithoutHasRoles;
use Hypervel\Tests\Permission\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\Attributes\TestWith;
use ReflectionMethod;
use TypeError;
@@ -31,6 +34,11 @@ class HasRolesCustomPivot extends MorphPivot
{
}
+class HasRolesIntegerKeyRole extends BaseRole
+{
+ protected string $keyType = 'integer';
+}
+
class HasRolesCustomPivotUser extends UserWithoutHasRoles
{
use HasRoles {
@@ -322,12 +330,17 @@ public function testItDoesNotRemoveAlreadyAssociatedRolesWhenAssigningNewRoles()
$this->assertTrue($this->testUser->fresh()->hasRole('testRole'));
}
- public function testItDoesNotThrowAnExceptionWhenAssigningARoleThatIsAlreadyAssigned(): void
+ #[TestWith([BaseRole::class])]
+ #[TestWith([HasRolesIntegerKeyRole::class])]
+ public function testItDoesNotThrowAnExceptionWhenAssigningARoleThatIsAlreadyAssigned(string $roleClass): void
{
+ $this->app->make(PermissionRegistrar::class)->setRoleClass($roleClass);
+
$this->testUser->assignRole($this->testUserRole->getKey());
$this->testUser->assignRole($this->testUserRole->getKey());
$this->assertTrue($this->testUser->fresh()->hasRole('testRole'));
+ $this->assertSame(1, $this->testUser->roles()->count());
}
public function testItThrowsAnExceptionWhenAssigningARoleThatDoesNotExist(): void
diff --git a/tests/Sanctum/PersonalAccessTokenCacheTest.php b/tests/Sanctum/PersonalAccessTokenCacheTest.php
index 72d55d253e..82295c7009 100644
--- a/tests/Sanctum/PersonalAccessTokenCacheTest.php
+++ b/tests/Sanctum/PersonalAccessTokenCacheTest.php
@@ -221,11 +221,13 @@ public function testInvalidTokenIdCachesNullResult(): void
$this->assertSame(0, $this->countQueriesForTable('personal_access_tokens'));
}
- public function testNonNumericTokenIdForIntegerKeyModelDoesNotQueryOrCache(): void
+ #[TestWith([PersonalAccessToken::class])]
+ #[TestWith([IntegerKeyPersonalAccessToken::class])]
+ public function testNonNumericTokenIdForIntegerKeyModelDoesNotQueryOrCache(string $modelClass): void
{
DB::enableQueryLog();
- $this->assertNull(PersonalAccessToken::findToken('abc|missing'));
+ $this->assertNull($modelClass::findToken('abc|missing'));
$this->assertSame(0, $this->countQueriesForTable('personal_access_tokens'));
$this->assertNull($this->cacheRepository()->getRaw('sanctum:abc'));
@@ -251,12 +253,14 @@ public function testEmptyPlainTokenDoesNotQueryOrCache(): void
$this->assertNull($this->cacheRepository()->getRaw('sanctum:1'));
}
- public function testOverflowingIntegerTokenIdDoesNotQueryOrCache(): void
+ #[TestWith([PersonalAccessToken::class])]
+ #[TestWith([IntegerKeyPersonalAccessToken::class])]
+ public function testOverflowingIntegerTokenIdDoesNotQueryOrCache(string $modelClass): void
{
$id = PHP_INT_MAX . '0';
DB::enableQueryLog();
- $this->assertNull(PersonalAccessToken::findToken("{$id}|missing"));
+ $this->assertNull($modelClass::findToken("{$id}|missing"));
$this->assertSame(0, $this->countQueriesForTable('personal_access_tokens'));
$this->assertNull($this->cacheRepository()->getRaw("sanctum:{$id}"));
@@ -1810,6 +1814,11 @@ protected function countAllQueriesForTable(string $table): int
}
}
+class IntegerKeyPersonalAccessToken extends PersonalAccessToken
+{
+ protected string $keyType = 'integer';
+}
+
class StringKeyPersonalAccessToken extends PersonalAccessToken
{
protected ?string $table = 'string_key_personal_access_tokens';
From e7c1353817b28ce423ad224b0cd0500cf808bb42 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sun, 15 Nov 2026 00:03:09 +0000
Subject: [PATCH 09/29] Preserve JSON sessions containing invalid UTF-8
Substitute malformed UTF-8 during JSON session encoding while preserving exceptions for other encoding errors and atomic session publication.
Port laravel/framework#62378 (338e44065c0a5b18f1f290605b6253a1e69d8f56).
Validation: session store, encrypted session and array-handler tests plus full static analysis pass.
---
src/session/src/Store.php | 2 +-
tests/Session/SessionStoreTest.php | 18 ++++++++++++++++++
2 files changed, 19 insertions(+), 1 deletion(-)
diff --git a/src/session/src/Store.php b/src/session/src/Store.php
index 41af18a4a7..cd60b83634 100644
--- a/src/session/src/Store.php
+++ b/src/session/src/Store.php
@@ -251,7 +251,7 @@ public function save(): void
$attributesForStorage = $this->prepareErrorBagForSerialization($attributes);
$serialized = $this->serialization === 'json'
- ? json_encode($attributesForStorage, JSON_THROW_ON_ERROR)
+ ? json_encode($attributesForStorage, JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_SUBSTITUTE)
: serialize($attributesForStorage);
$written = $this->handler->write(
diff --git a/tests/Session/SessionStoreTest.php b/tests/Session/SessionStoreTest.php
index 1eba89fc58..965a4e28dc 100644
--- a/tests/Session/SessionStoreTest.php
+++ b/tests/Session/SessionStoreTest.php
@@ -11,6 +11,7 @@
use Hypervel\Contracts\Auth\Factory as AuthFactory;
use Hypervel\Events\Dispatcher;
use Hypervel\Http\Request;
+use Hypervel\Session\ArraySessionHandler;
use Hypervel\Session\CookieSessionHandler;
use Hypervel\Session\SessionId;
use Hypervel\Session\Store;
@@ -1296,6 +1297,23 @@ public function testValidationErrorsCanBeReadAsJson(): void
]], $errors->getBags()['default']->getMessages());
}
+ public function testInvalidUtf8DoesNotEmptyJsonSerializedSession(): void
+ {
+ $session = new Store('name', $handler = new ArraySessionHandler(10), $this->getSessionId(), 'json');
+ $session->start();
+ $session->put('login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d', 1);
+ $session->put('url.intended', "https://hypervel.org/\xB1");
+ $token = $session->token();
+ $session->save();
+
+ $session = new Store('name', $handler, $this->getSessionId(), 'json');
+ $session->start();
+
+ $this->assertSame(1, $session->get('login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d'));
+ $this->assertSame($token, $session->token());
+ $this->assertSame("https://hypervel.org/\u{FFFD}", $session->get('url.intended'));
+ }
+
public function testItIsMacroable(): void
{
$this->getSession()->macro('foo', function () {
From ed427e262040949c682a639805339ab22fe3efee Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sun, 15 Nov 2026 00:03:09 +0000
Subject: [PATCH 10/29] Preserve PostgreSQL extension-owned views and tables
during resets
Exclude extension-owned relations from schema listings used by bulk drops, preserving partition metadata and ordinary schema cleanup.
Port laravel/framework#62395 (c31f733d24caac3170154637879a45dd491a4143) and #62460 (d324cee9e592e12c695e2a9dd0e0c1dca0068157).
Validation: reproduced both extension failures; PostgreSQL integration, schema grammar, builder and partition tests plus full static analysis pass.
---
.../src/Schema/Grammars/PostgresGrammar.php | 2 +
.../Postgres/PostgresSchemaBuilderTest.php | 39 +++++++++++++++++++
2 files changed, 41 insertions(+)
diff --git a/src/database/src/Schema/Grammars/PostgresGrammar.php b/src/database/src/Schema/Grammars/PostgresGrammar.php
index 7be186e61d..1e2433e775 100755
--- a/src/database/src/Schema/Grammars/PostgresGrammar.php
+++ b/src/database/src/Schema/Grammars/PostgresGrammar.php
@@ -88,6 +88,7 @@ public function compileTables(string|array|null $schema): string
. 'join pg_namespace pn on pn.oid = pc.relnamespace '
. 'where c.relispartition and i.inhrelid = c.oid) as partition_of from pg_class c, pg_namespace n '
. "where c.relkind in ('r', 'p') and n.oid = c.relnamespace and "
+ . "not exists (select 1 from pg_depend d where d.objid = c.oid and d.deptype = 'e') and "
. $this->compileSchemaWhereClause($schema, 'n.nspname')
. ' order by n.nspname, c.relname';
}
@@ -98,6 +99,7 @@ public function compileTables(string|array|null $schema): string
public function compileViews(string|array|null $schema): string
{
return 'select viewname as name, schemaname as schema, definition from pg_views where '
+ . "not exists (select 1 from pg_depend d where d.objid = format('%I.%I', schemaname, viewname)::regclass and d.deptype = 'e') and "
. $this->compileSchemaWhereClause($schema, 'schemaname')
. ' order by schemaname, viewname';
}
diff --git a/tests/Integration/Database/Postgres/PostgresSchemaBuilderTest.php b/tests/Integration/Database/Postgres/PostgresSchemaBuilderTest.php
index 6e925673fa..2c10248329 100644
--- a/tests/Integration/Database/Postgres/PostgresSchemaBuilderTest.php
+++ b/tests/Integration/Database/Postgres/PostgresSchemaBuilderTest.php
@@ -553,6 +553,45 @@ public function testCreateIndexesOnline(): void
$this->assertContains('table_raw_index', $indexNames);
}
+ public function testDropAllViewsIgnoresViewsOwnedByExtensions(): void
+ {
+ DB::statement('create extension if not exists pg_stat_statements schema public');
+ DB::statement('create view public.foo (id) as select 1');
+
+ try {
+ $this->assertFalse(Schema::hasView('public.pg_stat_statements'));
+
+ Schema::dropAllViews();
+
+ $this->assertFalse(Schema::hasView('public.foo'));
+ $this->assertTrue((bool) DB::scalar("select exists (select 1 from pg_views where viewname = 'pg_stat_statements')"));
+ } finally {
+ DB::statement('drop extension if exists pg_stat_statements');
+ }
+ }
+
+ public function testDropAllTablesIgnoresTablesOwnedByExtensions(): void
+ {
+ Schema::create('public.table', function (Blueprint $table) {
+ $table->increments('id');
+ });
+
+ DB::statement('create table public.extension_table (id integer)');
+ DB::statement('alter extension plpgsql add table public.extension_table');
+
+ try {
+ Schema::dropAllTables();
+
+ $this->artisan('migrate:install');
+
+ $this->assertFalse(Schema::hasTable('public.table'));
+ $this->assertTrue(Schema::hasTable('public.extension_table'));
+ } finally {
+ DB::statement('alter extension plpgsql drop table public.extension_table');
+ DB::statement('drop table public.extension_table');
+ }
+ }
+
public function testLateSchemaFailureRollsBackTheCompleteBlueprint(): void
{
try {
From 55f9556951e08c7af9819370c26f0b6322037375 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sun, 15 Nov 2026 00:03:36 +0000
Subject: [PATCH 11/29] Preserve validation semantics while retaining safe
database batching
Keep literal database conditions distinct from null and negation sentinels, preserve repeated conditions, and compare integer and boolean inputs as strings. Retain cached plans for lossless native rules and batching for scalar conditions from compiled rules and subclasses. Correct Data rule equivalence and remove obsolete binding distinctions.
Use the shared UndefinedValue sentinel for missing validation input and Testbench environment handling. Reject regex execution failures in both validation paths.
Port laravel/framework#62402 (b79483b42b701783decd0b188dafb63697a3b18b), direct port ba9e21eb9451bab33741be99239baf8ec4ff94ca, #62427 (525a08ad25d48b6a5fd2b0f486d59df5af641a06), #62425 (ef1821b33245d58631784ac2093aed0c5bb91242), #62447 (2b517db47fca33b9bf48a15287af63702ace3f99), #62442 (21e7a4c8715bf66bce5dff4f201d281358b2f05b) and #62459 (b19327914aef8a4a16fc6d79909aa30b0e489f2f), reconciled at c980cb5827c6512c12ac44493d172a593b41299a.
Validation: affected Validation and Data tests, SQLite/PostgreSQL/MySQL presence checks, Testbench package-mode contracts, full static analysis and formatting pass.
---
.../Validation/ValidationAccumulator.php | 12 ++-
.../src}/UndefinedValue.php | 11 +--
.../src/Concerns/CreatesApplication.php | 2 +-
src/testbench/src/Foundation/Application.php | 1 +
src/testbench/src/Foundation/Env.php | 2 +
src/validation/src/BatchDatabaseChecker.php | 31 ++-----
.../src/Concerns/ValidatesAttributes.php | 39 ++++++---
.../src/DatabasePresenceVerifier.php | 18 +++-
src/validation/src/PlanExecutor.php | 2 +-
.../src/PrecomputedPresenceVerifier.php | 34 +++-----
src/validation/src/RuleCompiler.php | 3 +-
src/validation/src/Rules/DatabaseRule.php | 53 ++++++++++--
src/validation/src/ValidationData.php | 5 +-
src/validation/src/ValidationRuleParser.php | 28 ++++--
src/validation/src/Validator.php | 16 ++--
.../Data/Fixtures/DataValidationAsserter.php | 25 ++++--
.../Validation/ValidationAccumulatorTest.php | 12 +++
...ValidationBatchDatabaseCheckerTestCase.php | 86 +++++++++++--------
.../ValidationBatchDatabaseCheckerTest.php | 13 ++-
...ValidationDatabasePresenceVerifierTest.php | 26 ++++++
tests/Validation/ValidationExistsRuleTest.php | 84 ++++++++++++++++++
...idationPrecomputedPresenceVerifierTest.php | 20 +----
tests/Validation/ValidationRuleParserTest.php | 12 +++
tests/Validation/ValidationUniqueRuleTest.php | 12 +++
tests/Validation/ValidationValidatorTest.php | 63 ++++++++++++++
25 files changed, 441 insertions(+), 169 deletions(-)
rename src/{testbench/src/Foundation => support/src}/UndefinedValue.php (58%)
diff --git a/src/data/src/Support/Validation/ValidationAccumulator.php b/src/data/src/Support/Validation/ValidationAccumulator.php
index 11e5d41bf6..3062a88143 100644
--- a/src/data/src/Support/Validation/ValidationAccumulator.php
+++ b/src/data/src/Support/Validation/ValidationAccumulator.php
@@ -142,6 +142,10 @@ protected function rulesEqual(array $rules, array $otherRules): bool
*/
protected function ruleValueEquals(mixed $rule, mixed $otherRule): bool
{
+ if ($rule === $otherRule) {
+ return true;
+ }
+
if (is_array($rule) || is_array($otherRule)) {
return is_array($rule)
&& is_array($otherRule)
@@ -157,16 +161,18 @@ protected function ruleValueEquals(mixed $rule, mixed $otherRule): bool
return $otherRule instanceof Enum && $rule == $otherRule;
}
+ $reducesToString = ValidationRuleParser::ruleReducesToString($rule);
+
if (($rule instanceof Exists || $rule instanceof Unique)
- && $rule->queryCallbacks() !== []
+ && ! $reducesToString
) {
return is_object($otherRule)
&& $otherRule::class === $rule::class
&& (string) $rule === (string) $otherRule
- && $rule->queryCallbacks() === $otherRule->queryCallbacks();
+ && $rule->queryConditions() === $otherRule->queryConditions();
}
- if (ValidationRuleParser::ruleReducesToString($rule)) {
+ if ($reducesToString) {
$rule = (string) $rule;
}
diff --git a/src/testbench/src/Foundation/UndefinedValue.php b/src/support/src/UndefinedValue.php
similarity index 58%
rename from src/testbench/src/Foundation/UndefinedValue.php
rename to src/support/src/UndefinedValue.php
index 2c99b987dc..5111e256dd 100644
--- a/src/testbench/src/Foundation/UndefinedValue.php
+++ b/src/support/src/UndefinedValue.php
@@ -2,27 +2,24 @@
declare(strict_types=1);
-namespace Hypervel\Testbench\Foundation;
+namespace Hypervel\Support;
use JsonSerializable;
-/**
- * @api
- */
-final class UndefinedValue implements JsonSerializable
+class UndefinedValue implements JsonSerializable
{
/**
* Determine if value is equivalent to "undefined" or "null".
*/
public static function equalsTo(mixed $value): bool
{
- return $value instanceof self || $value === null;
+ return $value instanceof UndefinedValue || $value === null;
}
/**
* Get the value for JSON serialization.
*/
- public function jsonSerialize(): mixed
+ public function jsonSerialize(): null
{
return null;
}
diff --git a/src/testbench/src/Concerns/CreatesApplication.php b/src/testbench/src/Concerns/CreatesApplication.php
index 1e594666d8..8de9b43b7f 100644
--- a/src/testbench/src/Concerns/CreatesApplication.php
+++ b/src/testbench/src/Concerns/CreatesApplication.php
@@ -32,6 +32,7 @@
use Hypervel\Support\Composer;
use Hypervel\Support\Facades\Facade;
use Hypervel\Support\Facades\RateLimiter;
+use Hypervel\Support\UndefinedValue;
use Hypervel\Testbench\Attributes\DefineEnvironment;
use Hypervel\Testbench\Attributes\RequiresEnv;
use Hypervel\Testbench\Attributes\RequiresHypervel;
@@ -47,7 +48,6 @@
use Hypervel\Testbench\Foundation\Bootstrap\SyncDatabaseEnvironmentVariables;
use Hypervel\Testbench\Foundation\Env;
use Hypervel\Testbench\Foundation\PackageManifest;
-use Hypervel\Testbench\Foundation\UndefinedValue;
use Hypervel\Testing\ParallelTesting;
use PHPUnit\Framework\TestCase as PHPUnitTestCase;
use Throwable;
diff --git a/src/testbench/src/Foundation/Application.php b/src/testbench/src/Foundation/Application.php
index 87c4319a19..b37fe7fbaa 100644
--- a/src/testbench/src/Foundation/Application.php
+++ b/src/testbench/src/Foundation/Application.php
@@ -8,6 +8,7 @@
use Hypervel\Contracts\Foundation\Application as ApplicationContract;
use Hypervel\Foundation\Bootstrap\LoadEnvironmentVariables;
use Hypervel\Support\Arr;
+use Hypervel\Support\UndefinedValue;
use Hypervel\Testbench\Concerns\CreatesApplication;
use Hypervel\Testbench\Contracts\Config as ConfigContract;
use Hypervel\Testbench\Foundation\Bootstrap\EnsuresDefaultConfiguration;
diff --git a/src/testbench/src/Foundation/Env.php b/src/testbench/src/Foundation/Env.php
index a0b87fd8c3..b1e485dd7f 100644
--- a/src/testbench/src/Foundation/Env.php
+++ b/src/testbench/src/Foundation/Env.php
@@ -4,6 +4,8 @@
namespace Hypervel\Testbench\Foundation;
+use Hypervel\Support\UndefinedValue;
+
/**
* @api
*/
diff --git a/src/validation/src/BatchDatabaseChecker.php b/src/validation/src/BatchDatabaseChecker.php
index c377467075..9b413b7d42 100644
--- a/src/validation/src/BatchDatabaseChecker.php
+++ b/src/validation/src/BatchDatabaseChecker.php
@@ -73,26 +73,15 @@ private static function registerLookup(
$meta,
array_values($representativeValues),
);
- $comparisonIndex = [];
-
- foreach (array_keys($representativeValues) as $bindingKey) {
- $comparisonIndex[substr($bindingKey, 1)][] = $bindingKey;
- }
-
$exactHits = [];
$knownPresent = [];
$provenAbsent = [];
foreach ($stageOneValues as $value) {
- $normalizedValue = PrecomputedPresenceVerifier::normalizeValue($value);
+ $bindingKey = PrecomputedPresenceVerifier::bindingKey($value);
- if ($normalizedValue === null) {
- continue;
- }
-
- // Query success proves each retained PDO binding was accepted. A returned
- // equal string form is therefore exact for every matching submitted binding.
- foreach ($comparisonIndex[$normalizedValue] ?? [] as $bindingKey) {
+ // A returned equal string form proves the normalized presence binding matched.
+ if ($bindingKey !== null && isset($representativeValues[$bindingKey])) {
$exactHits[$bindingKey] = true;
}
}
@@ -111,16 +100,10 @@ private static function registerLookup(
$provenAbsent = array_fill_keys(array_keys($misses), true);
} else {
foreach ($stageTwoValues as $value) {
- $normalizedValue = PrecomputedPresenceVerifier::normalizeValue($value);
-
- if ($normalizedValue === null) {
- continue;
- }
+ $bindingKey = PrecomputedPresenceVerifier::bindingKey($value);
- foreach ($comparisonIndex[$normalizedValue] ?? [] as $bindingKey) {
- if (isset($misses[$bindingKey])) {
- $knownPresent[$bindingKey] = true;
- }
+ if ($bindingKey !== null && isset($misses[$bindingKey])) {
+ $knownPresent[$bindingKey] = true;
}
}
@@ -176,7 +159,7 @@ private static function queryValues(
}
/**
- * Normalize candidates while retaining the first raw SQL binding.
+ * Normalize binding identities while retaining the first candidate value.
*
* An unsupported array item rejects only that concrete array candidate;
* safe siblings in the same query-shape group remain batchable.
diff --git a/src/validation/src/Concerns/ValidatesAttributes.php b/src/validation/src/Concerns/ValidatesAttributes.php
index ac6c9f5cd8..4f1a4a3e7e 100644
--- a/src/validation/src/Concerns/ValidatesAttributes.php
+++ b/src/validation/src/Concerns/ValidatesAttributes.php
@@ -19,6 +19,7 @@
use Exception;
use Hypervel\Container\Container;
use Hypervel\Database\Eloquent\Model;
+use Hypervel\Database\Query\Builder;
use Hypervel\Support\Arr;
use Hypervel\Support\Collection;
use Hypervel\Support\Exceptions\MathException;
@@ -1131,13 +1132,9 @@ protected function getExistCount(mixed $connection, string $table, string $colum
{
$verifier = $this->getPresenceVerifier($connection);
- $extra = $this->getExtraConditions(
- array_values(array_slice($parameters, 2))
- );
-
- if ($this->currentRule instanceof Exists) {
- $extra = array_merge($extra, $this->currentRule->queryCallbacks());
- }
+ $extra = $this->currentRule instanceof Exists
+ ? $this->currentRule->queryConditions()
+ : $this->getExtraConditions(array_values(array_slice($parameters, 2)));
return is_array($value)
? $verifier->getMultiCount($table, $column, $value, $extra)
@@ -1177,11 +1174,9 @@ public function validateUnique(string $attribute, mixed $value, mixed $parameter
// data store like Redis, etc. We will use it to determine uniqueness.
$verifier = $this->getPresenceVerifier($connection);
- $extra = $this->getUniqueExtra($parameters);
-
- if ($this->currentRule instanceof Unique) {
- $extra = array_merge($extra, $this->currentRule->queryCallbacks());
- }
+ $extra = $this->currentRule instanceof Unique
+ ? $this->currentRule->queryConditions()
+ : $this->getUniqueExtra($parameters);
return $verifier->getCount(
$table,
@@ -1303,7 +1298,23 @@ protected function getExtraConditions(array $segments): array
$count = count($segments);
for ($i = 0; $i < $count; $i += 2) {
- $extra[$segments[$i]] = $segments[$i + 1];
+ [$column, $value] = [$segments[$i], $segments[$i + 1]];
+
+ if (! array_key_exists($column, $extra)) {
+ $extra[$column] = $value;
+
+ continue;
+ }
+
+ // Array-form rules keep native parameter types; cast as DatabasePresenceVerifier::addWhere() does.
+ $value = (string) $value;
+
+ $extra[] = fn (Builder $query): Builder => match (true) {
+ $value === 'NULL' => $query->whereNull($column),
+ $value === 'NOT_NULL' => $query->whereNotNull($column),
+ str_starts_with($value, '!') => $query->where($column, '!=', mb_substr($value, 1)),
+ default => $query->where($column, $value),
+ };
}
return $extra;
@@ -2124,7 +2135,7 @@ public function validateNotRegex(string $attribute, mixed $value, mixed $paramet
$this->requireParameterCount(1, $parameters, 'not_regex');
- return preg_match($parameters[0], (string) $value) < 1;
+ return preg_match($parameters[0], (string) $value) === 0;
}
/**
diff --git a/src/validation/src/DatabasePresenceVerifier.php b/src/validation/src/DatabasePresenceVerifier.php
index fdecf20f47..d97f845b4b 100644
--- a/src/validation/src/DatabasePresenceVerifier.php
+++ b/src/validation/src/DatabasePresenceVerifier.php
@@ -30,7 +30,7 @@ public function __construct(
*/
public function getCount(string $collection, string $column, mixed $value, int|string|null $excludeId = null, ?string $idColumn = null, array $extra = []): int
{
- $query = $this->table($collection)->where($column, '=', $value);
+ $query = $this->table($collection)->where($column, '=', $this->prepareValue($value));
if (! is_null($excludeId) && $excludeId !== 'NULL') {
$query->where($idColumn ?: 'id', '<>', $excludeId);
@@ -44,7 +44,7 @@ public function getCount(string $collection, string $column, mixed $value, int|s
*/
public function getMultiCount(string $collection, string $column, array $values, array $extra = []): int
{
- $query = $this->table($collection)->whereIn($column, $values);
+ $query = $this->table($collection)->whereIn($column, array_map($this->prepareValue(...), $values));
return $this->addConditions($query, $extra)->distinct()->count($column);
}
@@ -68,7 +68,7 @@ public function getExistingValues(
$query = $this->db->connection($connection)
->table($collection)
->useWritePdo()
- ->whereIn($column, $values);
+ ->whereIn($column, array_map($this->prepareValue(...), $values));
if (! is_null($excludeId) && $excludeId !== 'NULL') {
$query->where($idColumn ?: 'id', '<>', $excludeId);
@@ -78,6 +78,18 @@ public function getExistingValues(
return $this->addConditions($query, $extra)->distinct()->pluck($column)->all();
}
+ /**
+ * Prepare a value for comparison with a database column.
+ */
+ protected function prepareValue(mixed $value): mixed
+ {
+ return match (true) {
+ is_bool($value) => (string) (int) $value,
+ is_int($value) => (string) $value,
+ default => $value,
+ };
+ }
+
/**
* Add the given conditions to the query.
*/
diff --git a/src/validation/src/PlanExecutor.php b/src/validation/src/PlanExecutor.php
index 6259603434..68a02926bf 100644
--- a/src/validation/src/PlanExecutor.php
+++ b/src/validation/src/PlanExecutor.php
@@ -332,7 +332,7 @@ protected function executeInline(InlineCheck $check, mixed $value, string $attri
CheckType::Regex => (is_string($value) || is_numeric($value))
&& preg_match($check->param, (string) $value) > 0,
CheckType::NotRegex => (is_string($value) || is_numeric($value))
- && preg_match($check->param, (string) $value) < 1,
+ && preg_match($check->param, (string) $value) === 0,
CheckType::StartsWith => (is_string($value) || is_numeric($value))
&& Str::startsWith((string) $value, $check->param),
CheckType::EndsWith => (is_string($value) || is_numeric($value))
diff --git a/src/validation/src/PrecomputedPresenceVerifier.php b/src/validation/src/PrecomputedPresenceVerifier.php
index 3eddf6a314..801b2dd30c 100644
--- a/src/validation/src/PrecomputedPresenceVerifier.php
+++ b/src/validation/src/PrecomputedPresenceVerifier.php
@@ -148,7 +148,7 @@ public function getMultiCount(string $collection, string $column, array $values,
return $this->fallback->getMultiCount($collection, $column, $values, $extra);
}
- $bindingValues = [];
+ $bindingKeys = [];
foreach ($values as $value) {
$bindingKey = self::bindingKey($value);
@@ -157,20 +157,20 @@ public function getMultiCount(string $collection, string $column, array $values,
return $this->fallback->getMultiCount($collection, $column, $values, $extra);
}
- $bindingValues[$bindingKey] = substr($bindingKey, 1);
+ $bindingKeys[$bindingKey] = true;
}
$lookup = $this->lookups[$lookupKey];
- $distinctValueCount = count(array_unique($bindingValues, SORT_STRING));
- $presentValues = [];
+ $distinctValueCount = count($bindingKeys);
+ $presentCount = 0;
- foreach ($bindingValues as $bindingKey => $normalizedValue) {
+ foreach ($bindingKeys as $bindingKey => $_) {
if (isset($lookup['exactHits'][$bindingKey])) {
if (! $lookup['stageOneSingleChunk']) {
return $this->fallback->getMultiCount($collection, $column, $values, $extra);
}
- $presentValues[$normalizedValue] = true;
+ ++$presentCount;
continue;
}
@@ -179,7 +179,7 @@ public function getMultiCount(string $collection, string $column, array $values,
return $this->fallback->getMultiCount($collection, $column, $values, $extra);
}
- $presentValues[$normalizedValue] = true;
+ ++$presentCount;
continue;
}
@@ -188,7 +188,7 @@ public function getMultiCount(string $collection, string $column, array $values,
}
}
- return count($presentValues);
+ return $presentCount;
}
/**
@@ -211,27 +211,15 @@ public function hasLookups(): bool
/**
* Build a key for the PDO binding identity of a supported presence value.
*
- * The one-character prefix preserves integer/string PDO binding identity
- * and prevents PHP from coercing numeric-string array keys to integers.
+ * Presence queries bind integers as strings, so equal string forms share a key.
+ * The prefix prevents PHP from coercing numeric-string array keys to integers.
*/
public static function bindingKey(mixed $value): ?string
- {
- $normalizedValue = self::normalizeValue($value);
-
- return $normalizedValue === null
- ? null
- : (is_int($value) ? 'i' : 's') . $normalizedValue;
- }
-
- /**
- * Normalize a supported presence value for lookup comparisons.
- */
- public static function normalizeValue(mixed $value): ?string
{
if (! is_string($value) && ! is_int($value) && ! is_float($value)) {
return null;
}
- return (string) $value;
+ return 's' . $value;
}
}
diff --git a/src/validation/src/RuleCompiler.php b/src/validation/src/RuleCompiler.php
index 2f1d3795c3..569f0c9109 100644
--- a/src/validation/src/RuleCompiler.php
+++ b/src/validation/src/RuleCompiler.php
@@ -4,6 +4,7 @@
namespace Hypervel\Validation;
+use Closure;
use Hypervel\Contracts\Validation\ParameterizedRule;
use Hypervel\Contracts\Validation\Rule as RuleContract;
use Hypervel\Validation\Enums\CheckType;
@@ -240,7 +241,7 @@ private static function canConsumePrecomputedPresenceLookup(DelegatedCheck $chec
}
return ! (($check->originalRule instanceof Exists || $check->originalRule instanceof Unique)
- && $check->originalRule->queryCallbacks() !== []);
+ && array_any($check->originalRule->queryConditions(), static fn (mixed $condition): bool => $condition instanceof Closure));
}
/**
diff --git a/src/validation/src/Rules/DatabaseRule.php b/src/validation/src/Rules/DatabaseRule.php
index 2cad43ffe4..dd74c244e6 100644
--- a/src/validation/src/Rules/DatabaseRule.php
+++ b/src/validation/src/Rules/DatabaseRule.php
@@ -8,6 +8,7 @@
use Closure;
use Hypervel\Contracts\Support\Arrayable;
use Hypervel\Database\Eloquent\Model;
+use Hypervel\Database\Query\Builder;
use Hypervel\Support\Collection;
use function Hypervel\Support\enum_value;
@@ -89,7 +90,7 @@ public function where(Closure|string $column, mixed $value = null): static
$value = $this->normalizeWhereValue($value);
- $this->wheres[] = ['column' => $column, 'value' => $value];
+ $this->wheres[] = ['column' => $column, 'operator' => '=', 'value' => (string) $value];
return $this;
}
@@ -107,7 +108,9 @@ public function whereNot(string $column, mixed $value): static
$value = $this->normalizeWhereValue($value);
- return $this->where($column, '!' . $value);
+ $this->wheres[] = ['column' => $column, 'operator' => '!=', 'value' => (string) $value];
+
+ return $this;
}
/**
@@ -117,7 +120,9 @@ public function whereNot(string $column, mixed $value): static
*/
public function whereNull(string $column): static
{
- return $this->where($column, 'NULL');
+ $this->wheres[] = ['column' => $column, 'operator' => 'NULL', 'value' => null];
+
+ return $this;
}
/**
@@ -127,7 +132,9 @@ public function whereNull(string $column): static
*/
public function whereNotNull(string $column): static
{
- return $this->where($column, 'NOT_NULL');
+ $this->wheres[] = ['column' => $column, 'operator' => 'NOT_NULL', 'value' => null];
+
+ return $this;
}
/**
@@ -198,6 +205,42 @@ public function queryCallbacks(): array
return $this->using;
}
+ /**
+ * Get the extra conditions for the presence verifier.
+ */
+ public function queryConditions(): array
+ {
+ $conditions = [];
+
+ foreach ($this->wheres as ['column' => $column, 'operator' => $operator, 'value' => $value]) {
+ if ($operator === '=' && ($value === 'NULL' || $value === 'NOT_NULL' || str_starts_with($value, '!'))) {
+ $conditions[] = fn (Builder $query): Builder => $query->where($column, '=', $value);
+ } elseif (array_key_exists($column, $conditions)) {
+ $conditions[] = fn (Builder $query): Builder => match ($operator) {
+ 'NULL' => $query->whereNull($column),
+ 'NOT_NULL' => $query->whereNotNull($column),
+ default => $query->where($column, $operator, $value),
+ };
+ } else {
+ $conditions[$column] = $this->formatWhereValue($operator, $value);
+ }
+ }
+
+ return array_merge($conditions, $this->using);
+ }
+
+ /**
+ * Format a "where" clause value as the presence verifier reads it.
+ */
+ protected function formatWhereValue(string $operator, ?string $value): string
+ {
+ return match ($operator) {
+ '=' => (string) $value,
+ '!=' => '!' . $value,
+ default => $operator,
+ };
+ }
+
/**
* Normalize a where value for string serialization.
*/
@@ -214,7 +257,7 @@ protected function normalizeWhereValue(mixed $value): mixed
protected function formatWheres(): string
{
return (new Collection($this->wheres))
- ->map(fn ($where) => $where['column'] . ',"' . str_replace('"', '""', (string) $where['value']) . '"')
+ ->map(fn ($where) => $where['column'] . ',"' . str_replace('"', '""', $this->formatWhereValue($where['operator'], $where['value'])) . '"')
->implode(',');
}
}
diff --git a/src/validation/src/ValidationData.php b/src/validation/src/ValidationData.php
index 59f622b931..efa8821230 100644
--- a/src/validation/src/ValidationData.php
+++ b/src/validation/src/ValidationData.php
@@ -6,6 +6,7 @@
use Hypervel\Support\Arr;
use Hypervel\Support\Str;
+use Hypervel\Support\UndefinedValue;
class ValidationData
{
@@ -198,9 +199,9 @@ public static function extractDataFromPath(?string $attribute, array $masterData
{
$results = [];
- $value = Arr::get($masterData, $attribute, '__missing__');
+ $value = Arr::get($masterData, $attribute, new UndefinedValue);
- if ($value !== '__missing__') {
+ if (! $value instanceof UndefinedValue) {
Arr::set($results, $attribute, $value);
}
diff --git a/src/validation/src/ValidationRuleParser.php b/src/validation/src/ValidationRuleParser.php
index d7ea0937cf..91fb40fff2 100644
--- a/src/validation/src/ValidationRuleParser.php
+++ b/src/validation/src/ValidationRuleParser.php
@@ -151,14 +151,26 @@ protected function prepareRule(mixed $rule, string $attribute): mixed
*/
public static function ruleReducesToString(mixed $rule): bool
{
- return is_object($rule)
- && ! $rule instanceof Closure
- && ! $rule instanceof ValidationRule
- && ! $rule instanceof RuleContract
- && ! $rule instanceof ParameterizedRule
- && ! $rule instanceof CompilableRules
- && ! (($rule instanceof Exists || $rule instanceof Unique)
- && $rule->queryCallbacks() !== []);
+ if (! is_object($rule)
+ || $rule instanceof Closure
+ || $rule instanceof ValidationRule
+ || $rule instanceof RuleContract
+ || $rule instanceof ParameterizedRule
+ || $rule instanceof CompilableRules
+ ) {
+ return false;
+ }
+
+ if ($rule instanceof Exists || $rule instanceof Unique) {
+ $conditions = $rule->queryConditions();
+
+ // Lossless native rules stay cacheable strings; subclasses may override their conditions.
+ return $conditions === []
+ || (in_array($rule::class, [Exists::class, Unique::class], true)
+ && ! array_any($conditions, static fn (mixed $condition): bool => $condition instanceof Closure));
+ }
+
+ return true;
}
/**
diff --git a/src/validation/src/Validator.php b/src/validation/src/Validator.php
index 35520cc660..7fca779035 100644
--- a/src/validation/src/Validator.php
+++ b/src/validation/src/Validator.php
@@ -22,6 +22,8 @@
use Hypervel\Support\Str;
use Hypervel\Support\StrCache;
use Hypervel\Support\ValidatedInput;
+use Hypervel\Validation\Rules\Exists;
+use Hypervel\Validation\Rules\Unique;
use InvalidArgumentException;
use LogicException;
use RuntimeException;
@@ -823,7 +825,7 @@ protected function maybeBatchDatabaseChecks(
* connection: ?string,
* table: string,
* column: string,
- * wheres: array,
+ * wheres: array,
* ignore: null|int|string,
* idColumn: ?string
* }
@@ -836,9 +838,10 @@ private function extractPresenceRuleMeta(
return null;
}
- if (($check->originalRule instanceof Rules\Exists || $check->originalRule instanceof Rules\Unique)
- && $check->originalRule->queryCallbacks() !== []
- ) {
+ $usesRuleConditions = $check->originalRule instanceof Exists || $check->originalRule instanceof Unique;
+ $wheres = $usesRuleConditions ? $check->originalRule->queryConditions() : [];
+
+ if (array_any($wheres, static fn (mixed $condition): bool => $condition instanceof Closure)) {
return null;
}
@@ -864,10 +867,9 @@ private function extractPresenceRuleMeta(
$ignore = null;
$idColumn = null;
- $wheres = [];
if ($type === 'exists') {
- if (isset($parameters[2])) {
+ if (! $usesRuleConditions && isset($parameters[2])) {
$wheres = $this->getExtraConditions(array_values(array_slice($parameters, 2)));
}
} else {
@@ -885,7 +887,7 @@ private function extractPresenceRuleMeta(
$ignore = (string) $ignore;
}
}
- if (isset($parameters[4])) {
+ if (! $usesRuleConditions && isset($parameters[4])) {
$wheres = $this->getExtraConditions(array_slice($parameters, 4));
}
}
diff --git a/tests/Data/Fixtures/DataValidationAsserter.php b/tests/Data/Fixtures/DataValidationAsserter.php
index 73bb275a10..e23a292892 100644
--- a/tests/Data/Fixtures/DataValidationAsserter.php
+++ b/tests/Data/Fixtures/DataValidationAsserter.php
@@ -4,6 +4,7 @@
namespace Hypervel\Tests\Data\Fixtures;
+use Closure;
use Hypervel\Data\Contracts\ValidateableData;
use Hypervel\Database\Query\Builder;
use Hypervel\Support\Facades\DB;
@@ -157,7 +158,7 @@ protected function validator(array $payload): Validator
}
/**
- * Replace database rules that have query callbacks with the query those callbacks build.
+ * Replace database-rule closures with the queries they build.
*
* Callbacks are closures that cannot be compared, so the query they build shows what they do.
*/
@@ -166,20 +167,26 @@ protected function normalizeDatabaseRules(array $rules): array
return array_map(
static fn (array $fieldRules): array => array_map(
static function (mixed $rule): mixed {
- if (! ($rule instanceof Exists || $rule instanceof Unique) || $rule->queryCallbacks() === []) {
+ if (! ($rule instanceof Exists || $rule instanceof Unique) || ValidationRuleParser::ruleReducesToString($rule)) {
return $rule;
}
- $query = DB::query();
+ $conditions = array_map(static function (mixed $condition): mixed {
+ if (! $condition instanceof Closure) {
+ return $condition;
+ }
- // As DatabasePresenceVerifier does, each callback receives its own nested where group.
- foreach ($rule->queryCallbacks() as $callback) {
- $query->where(static function (Builder $query) use ($callback): void {
- $callback($query);
+ $query = DB::query();
+
+ // Match the nested where group used by DatabasePresenceVerifier.
+ $query->where(static function (Builder $query) use ($condition): void {
+ $condition($query);
});
- }
- return [(string) $rule, $query->toSql(), $query->getBindings()];
+ return [$query->toSql(), $query->getBindings()];
+ }, $rule->queryConditions());
+
+ return [(string) $rule, $conditions];
},
$fieldRules,
),
diff --git a/tests/Data/Support/Validation/ValidationAccumulatorTest.php b/tests/Data/Support/Validation/ValidationAccumulatorTest.php
index cfb55aeb6f..288b8a8131 100644
--- a/tests/Data/Support/Validation/ValidationAccumulatorTest.php
+++ b/tests/Data/Support/Validation/ValidationAccumulatorTest.php
@@ -191,6 +191,18 @@ public function testComparesDatabaseRuleCallbacksByIdentity(): void
];
$this->assertFalse($accumulator->equals($other));
+
+ $literal = (new Exists('users', 'email'))->where('type', 'NULL')->using($callback);
+ $accumulator->rules = ['email' => [$literal]];
+ $other->rules = [
+ 'email' => [(new Exists('users', 'email'))->whereNull('type')->using($callback)],
+ ];
+
+ $this->assertFalse($accumulator->equals($other));
+
+ $other->rules = ['email' => [$literal]];
+
+ $this->assertTrue($accumulator->equals($other));
}
/**
diff --git a/tests/Integration/Validation/Database/ValidationBatchDatabaseCheckerTestCase.php b/tests/Integration/Validation/Database/ValidationBatchDatabaseCheckerTestCase.php
index 4124d32aa6..3ff0ad7c06 100644
--- a/tests/Integration/Validation/Database/ValidationBatchDatabaseCheckerTestCase.php
+++ b/tests/Integration/Validation/Database/ValidationBatchDatabaseCheckerTestCase.php
@@ -9,7 +9,6 @@
use Hypervel\Contracts\Validation\Rule;
use Hypervel\Contracts\Validation\ValidatorAwareRule;
use Hypervel\Database\Eloquent\Model;
-use Hypervel\Database\QueryException;
use Hypervel\Database\Schema\Blueprint;
use Hypervel\Support\Facades\DB;
use Hypervel\Support\Facades\Schema;
@@ -173,6 +172,44 @@ public function testExactPresenceChecksBatchAcrossCachedPlans(): void
));
}
+ #[TestWith([['user1@example.com', 'user2@example.com'], true])]
+ #[TestWith([['user3@example.com', 'user3@example.com'], false])]
+ public function testOverriddenScalarConditionsMatchOrdinaryAndBatchedQueries(array $emails, bool $passes): void
+ {
+ $rule = new class('batch_test_users', 'email') extends Exists {
+ /**
+ * Limit presence checks to active users.
+ */
+ public function queryConditions(): array
+ {
+ return ['status' => 'active'];
+ }
+ };
+
+ foreach ($emails as $email) {
+ $ordinary = $this->makeOrdinaryValidator(['email' => $email], ['email' => $rule]);
+ $this->assertSame($passes, $ordinary->passes());
+ }
+
+ $batched = $this->makeValidator(
+ ['items' => array_map(static fn (string $email): array => ['email' => $email], $emails)],
+ ['items.*.email' => $rule],
+ );
+ $batched->after(function (Validator $validator): void {
+ $this->assertInstanceOf(PrecomputedPresenceVerifier::class, $validator->getPresenceVerifier());
+ });
+
+ DB::flushQueryLog();
+ DB::enableQueryLog();
+
+ try {
+ $this->assertSame($passes, $batched->passes());
+ $this->assertCount(1, DB::getQueryLog());
+ } finally {
+ DB::disableQueryLog();
+ }
+ }
+
public function testExactPresenceChecksBatchDifferentQueryShapesIndependently(): void
{
$validator = $this->makeValidator(
@@ -467,8 +504,7 @@ public function testDateTimeCandidatesUseTheOrdinaryVerifierBindingConversion():
}
}
- #[RequiresDatabase(['mysql', 'mariadb', 'sqlite'])]
- public function testIntegerCandidateAgainstTextUsesOnePrecomputedQueryWhereSupported(): void
+ public function testIntegerCandidateAgainstTextUsesOnePrecomputedQuery(): void
{
foreach (['exists', 'unique'] as $rule) {
$ordinary = $this->makeOrdinaryValidator(
@@ -490,7 +526,8 @@ public function testIntegerCandidateAgainstTextUsesOnePrecomputedQueryWhereSuppo
DB::disableQueryLog();
}
- $this->assertSame($ordinary->passes(), $result);
+ $this->assertSame($rule === 'exists', $ordinary->passes());
+ $this->assertSame($rule === 'exists', $result);
$this->assertCount(1, array_filter(
$queryLog,
static fn (array $entry): bool => str_contains($entry['query'], 'batch_test_users'),
@@ -498,11 +535,12 @@ public function testIntegerCandidateAgainstTextUsesOnePrecomputedQueryWhereSuppo
}
}
- #[RequiresDatabase(['mysql', 'mariadb', 'sqlite'])]
- public function testMixedStringAndIntegerTextCandidatesRetainBothBindings(): void
+ #[TestWith([['1', 1]])]
+ #[TestWith([[1, '1']])]
+ public function testMixedStringAndIntegerTextCandidatesShareOneBinding(array $values): void
{
$validator = $this->makeValidator(
- ['items' => [['value' => '1'], ['value' => 1]]],
+ ['items' => array_map(static fn (int|string $value): array => ['value' => $value], $values)],
['items.*.value' => 'exists:batch_test_users,lookup_value'],
);
@@ -523,11 +561,11 @@ public function testMixedStringAndIntegerTextCandidatesRetainBothBindings(): voi
));
$this->assertCount(1, $presenceQueries);
- $this->assertSame(['1', 1], $presenceQueries[0]['bindings']);
+ $this->assertSame(['1'], $presenceQueries[0]['bindings']);
}
#[RequiresDatabase(['mysql', 'mariadb'])]
- public function testMixedStringAndIntegerCandidatesPreserveOrdinaryMySqlTextComparison(): void
+ public function testMixedStringAndIntegerCandidatesAvoidMySqlNumericCoercion(): void
{
$this->app->make('db')->table('batch_test_users')
->where('external_id', 100)
@@ -543,7 +581,7 @@ public function testMixedStringAndIntegerCandidatesPreserveOrdinaryMySqlTextComp
);
$this->assertFalse($ordinaryString->passes());
- $this->assertTrue($ordinaryInteger->passes());
+ $this->assertFalse($ordinaryInteger->passes());
foreach ([['1', 1], [1, '1']] as $values) {
$validator = $this->makeValidator(
@@ -557,10 +595,7 @@ public function testMixedStringAndIntegerCandidatesPreserveOrdinaryMySqlTextComp
$this->assertFalse($validator->passes());
foreach ($values as $index => $value) {
- $this->assertSame(
- is_string($value),
- $validator->errors()->has("items.{$index}.value"),
- );
+ $this->assertTrue($validator->errors()->has("items.{$index}.value"));
}
}
}
@@ -669,29 +704,6 @@ public function testInvalidTypedValuesFailBeforeAnyPresenceQuery(): void
));
}
- #[RequiresDatabase('pgsql')]
- public function testPostgresPreservesIntegerToTextBindingErrorsOnOrdinaryAndBatchedPaths(): void
- {
- $ordinary = $this->makeOrdinaryValidator(
- ['value' => 1],
- ['value' => 'exists:batch_test_users,lookup_value'],
- );
-
- $this->assertThrows($ordinary->passes(...), QueryException::class);
-
- foreach ([['1', 1], [1, '1']] as $values) {
- $batched = $this->makeValidator(
- ['items' => array_map(
- static fn (int|string $value): array => ['value' => $value],
- $values,
- )],
- ['items.*.value' => 'exists:batch_test_users,lookup_value'],
- );
-
- $this->assertThrows($batched->passes(...), QueryException::class);
- }
- }
-
public function testOriginalPresenceVerifierIsRestoredAfterExceptionDuringBatchedValidation(): void
{
$validator = $this->makeValidator(
diff --git a/tests/Validation/ValidationBatchDatabaseCheckerTest.php b/tests/Validation/ValidationBatchDatabaseCheckerTest.php
index a5e94c4103..dbd6500c4c 100644
--- a/tests/Validation/ValidationBatchDatabaseCheckerTest.php
+++ b/tests/Validation/ValidationBatchDatabaseCheckerTest.php
@@ -15,7 +15,7 @@
class ValidationBatchDatabaseCheckerTest extends TestCase
{
- public function testUsesTheCompleteQueryShapeAndRetainsRawSqlBindings(): void
+ public function testUsesTheCompleteQueryShapeAndRetainsCandidateValues(): void
{
$meta = $this->metadata([
'connection' => 'named',
@@ -28,10 +28,7 @@ public function testUsesTheCompleteQueryShapeAndRetainsRawSqlBindings(): void
->once()
->with('users', 'id', [1, 2.5], 'named', 'ignored', 'uuid', ['status' => 'active'])
->andReturn(['1', '2.5']);
- $presenceVerifier->shouldReceive('getCount')
- ->once()
- ->with('users', 'id', '1', 'ignored', 'uuid', ['status' => 'active'])
- ->andReturn(0);
+ $presenceVerifier->shouldNotReceive('getCount');
$presenceVerifier->shouldReceive('setConnection')->once()->with('named');
$verifier = BatchDatabaseChecker::buildVerifier($this->batchGroups($meta, [1, 2.5]), $presenceVerifier);
@@ -40,7 +37,7 @@ public function testUsesTheCompleteQueryShapeAndRetainsRawSqlBindings(): void
$verifier->setConnection('named');
$this->assertSame(1, $verifier->getCount('users', 'id', 1, 'ignored', 'uuid', ['status' => 'active']));
$this->assertSame(1, $verifier->getCount('users', 'id', 2.5, 'ignored', 'uuid', ['status' => 'active']));
- $this->assertSame(0, $verifier->getCount('users', 'id', '1', 'ignored', 'uuid', ['status' => 'active']));
+ $this->assertSame(1, $verifier->getCount('users', 'id', '1', 'ignored', 'uuid', ['status' => 'active']));
}
public function testNormalizesNativeArraysAndDelegatesStringableValuesWithoutCasting(): void
@@ -114,12 +111,12 @@ public function __toString(): string
$this->assertSame(0, $casts);
}
- public function testEqualLookingIntegerAndStringCandidatesRetainBothBindings(): void
+ public function testEqualLookingIntegerAndStringCandidatesShareOneBinding(): void
{
$presenceVerifier = m::mock(DatabasePresenceVerifier::class);
$presenceVerifier->shouldReceive('getExistingValues')
->once()
- ->with('users', 'id', ['1', 1], null, null, null, [])
+ ->with('users', 'id', ['1'], null, null, null, [])
->andReturn(['1']);
$verifier = BatchDatabaseChecker::buildVerifier(
diff --git a/tests/Validation/ValidationDatabasePresenceVerifierTest.php b/tests/Validation/ValidationDatabasePresenceVerifierTest.php
index 28034eacd5..29a85840f5 100644
--- a/tests/Validation/ValidationDatabasePresenceVerifierTest.php
+++ b/tests/Validation/ValidationDatabasePresenceVerifierTest.php
@@ -86,6 +86,32 @@ public function testGetCountWithValidExcludeId(): void
$this->assertSame(100, $verifier->getCount('table', 'column', 'value', 123, 'id', []));
}
+ public function testIntegersAndBooleansAreComparedAsStrings(): void
+ {
+ $db = m::mock(ConnectionResolverInterface::class);
+ $connection = m::mock(Connection::class);
+ $db->expects('connection')->with('connection')->times(3)->andReturn($connection);
+ $verifier = new DatabasePresenceVerifier($db);
+ $verifier->setConnection('connection');
+ $builder = m::mock(Builder::class);
+ $connection->expects('table')->with('table')->times(3)->andReturn($builder);
+ $builder->expects('useWritePdo')->times(3)->andReturnSelf();
+ $builder->expects('where')->with('column', '=', '0')->andReturnSelf();
+ $builder->expects('count')->withNoArgs()->andReturn(0);
+
+ $this->assertSame(0, $verifier->getCount('table', 'column', 0));
+
+ $builder->expects('whereIn')->with('column', ['0', '1', '7', 'value'])->twice()->andReturnSelf();
+ $builder->expects('distinct')->twice()->andReturnSelf();
+ $builder->expects('count')->with('column')->andReturn(0);
+
+ $this->assertSame(0, $verifier->getMultiCount('table', 'column', [false, true, 7, 'value']));
+
+ $builder->expects('pluck')->with('column')->andReturn(new Collection(['0', '1', '7', 'value']));
+
+ $verifier->getExistingValues('table', 'column', [false, true, 7, 'value'], 'connection');
+ }
+
#[DataProvider('connections')]
public function testGetExistingValuesUsesRequestedConnectionAndReturnsDistinctValues(?string $connection): void
{
diff --git a/tests/Validation/ValidationExistsRuleTest.php b/tests/Validation/ValidationExistsRuleTest.php
index 1adb3bbec8..5a81ea6427 100644
--- a/tests/Validation/ValidationExistsRuleTest.php
+++ b/tests/Validation/ValidationExistsRuleTest.php
@@ -6,12 +6,14 @@
use Hypervel\Database\Eloquent\Model as Eloquent;
use Hypervel\Foundation\Testing\RefreshDatabase;
+use Hypervel\Support\Str;
use Hypervel\Testbench\TestCase;
use Hypervel\Translation\ArrayLoader;
use Hypervel\Translation\Translator;
use Hypervel\Validation\DatabasePresenceVerifier;
use Hypervel\Validation\Rules\Exists;
use Hypervel\Validation\Validator;
+use PHPUnit\Framework\Attributes\DataProvider;
use UnitEnum;
class ValidationExistsRuleTest extends TestCase
@@ -230,6 +232,88 @@ public function testItChoosesValidRecordsUsingWhereNotRule(): void
$this->assertTrue($v->passes());
}
+ public function testItAppliesEveryWhereNotOnTheSameColumn(): void
+ {
+ $rule = new Exists('table', 'id_column');
+
+ $rule->whereNot('type', 'foo')->whereNot('type', 'bar');
+
+ User::create(['id_column' => '1', 'type' => 'foo']);
+ User::create(['id_column' => '2', 'type' => 'bar']);
+ User::create(['id_column' => '3', 'type' => 'baz']);
+
+ $trans = $this->getArrayTranslator();
+ $v = new Validator($trans, [], ['id_column' => $rule]);
+ $v->setPresenceVerifier(new DatabasePresenceVerifier($this->app->make('db')));
+
+ $v->setData(['id_column' => 1]);
+ $this->assertFalse($v->passes());
+
+ $v->setData(['id_column' => 2]);
+ $this->assertFalse($v->passes());
+
+ $v->setData(['id_column' => 3]);
+ $this->assertTrue($v->passes());
+ }
+
+ public function testStringRuleAppliesEveryConditionOnTheSameColumn(): void
+ {
+ User::create(['id_column' => '1', 'type' => 'foo']);
+ User::create(['id_column' => '2', 'type' => 'bar']);
+ User::create(['id_column' => '3', 'type' => 'baz']);
+
+ $trans = $this->getArrayTranslator();
+ $v = new Validator($trans, [], ['id_column' => 'exists:table,id_column,type,!foo,type,!bar']);
+ $v->setPresenceVerifier(new DatabasePresenceVerifier($this->app->make('db')));
+
+ $v->setData(['id_column' => 1]);
+ $this->assertFalse($v->passes());
+
+ $v->setData(['id_column' => 2]);
+ $this->assertFalse($v->passes());
+
+ $v->setData(['id_column' => 3]);
+ $this->assertTrue($v->passes());
+ }
+
+ public function testRepeatedArrayRuleConditionsAcceptNumericValues(): void
+ {
+ User::create(['id_column' => '1', 'type' => '0']);
+
+ $validator = new Validator($this->getArrayTranslator(), ['id_column' => 1], [
+ 'id_column' => [['exists', 'table', 'id_column', 'type', 0, 'type', 0]],
+ ]);
+ $validator->setPresenceVerifier(new DatabasePresenceVerifier($this->app->make('db')));
+
+ $this->assertTrue($validator->passes());
+ }
+
+ #[DataProvider('literalWhereValuesProvider')]
+ public function testWhereComparesValuesLiterally(Exists $rule, int $id, bool $passes): void
+ {
+ User::create(['id_column' => '1', 'type' => 'foo']);
+ User::create(['id_column' => '2', 'type' => 'NOT_NULL']);
+
+ $v = new Validator($this->getArrayTranslator(), ['id_column' => $id], ['id_column' => $rule]);
+ $v->setPresenceVerifier(new DatabasePresenceVerifier($this->app->make('db')));
+
+ $this->assertSame($passes, $v->passes());
+ }
+
+ public static function literalWhereValuesProvider(): array
+ {
+ $breakout = 'x\",id_column,NOT_NULL,type,"';
+
+ return [
+ 'NOT_NULL is not "is not null"' => [(new Exists('table', 'id_column'))->where('type', 'NOT_NULL'), 1, false],
+ 'NOT_NULL matches itself' => [(new Exists('table', 'id_column'))->where('type', 'NOT_NULL'), 2, true],
+ 'leading ! is not "not equal"' => [(new Exists('table', 'id_column'))->where('type', '!bar'), 1, false],
+ 'Stringable NOT_NULL' => [(new Exists('table', 'id_column'))->where('type', Str::of('NOT_NULL')), 1, false],
+ 'backslash cannot override another where' => [(new Exists('table', 'id_column'))->where('id_column', 2)->where('type', $breakout . '!'), 1, false],
+ 'whereNot backslash cannot add wheres' => [(new Exists('table', 'id_column'))->whereNot('type', $breakout . 'foo'), 2, true],
+ ];
+ }
+
public function testItIgnoresSoftDeletes(): void
{
$rule = new Exists('table');
diff --git a/tests/Validation/ValidationPrecomputedPresenceVerifierTest.php b/tests/Validation/ValidationPrecomputedPresenceVerifierTest.php
index 9b63fc1145..d62c25dac9 100644
--- a/tests/Validation/ValidationPrecomputedPresenceVerifierTest.php
+++ b/tests/Validation/ValidationPrecomputedPresenceVerifierTest.php
@@ -75,7 +75,7 @@ public function testScalarFactsUseTheirDatabaseProvenState(): void
$this->assertSame(0, $verifier->getCount('users', 'email', 'missing@example.com'));
}
- public function testFactsRequireTheSubmittedBindingIdentity(): void
+ public function testFactsShareEquivalentBindingsWithoutCastingObjects(): void
{
$casts = 0;
$stringable = new class($casts) implements Stringable {
@@ -95,14 +95,6 @@ public function __toString(): string
->once()
->with('users', 'id', m::on(static fn (mixed $value): bool => $value === $stringable), null, null, [])
->andReturn(1);
- $fallback->shouldReceive('getCount')
- ->once()
- ->with('users', 'id', 1, null, null, [])
- ->andReturn(0);
- $fallback->shouldReceive('getCount')
- ->once()
- ->with('users', 'id', '2', null, null, [])
- ->andReturn(0);
$verifier = new PrecomputedPresenceVerifier($fallback);
$verifier->addLookup(
self::lookupKey(null, 'users', 'id'),
@@ -116,8 +108,8 @@ public function __toString(): string
$this->assertSame(1, $verifier->getCount('users', 'id', 2));
$this->assertSame(1, $verifier->getCount('users', 'id', $stringable));
$this->assertSame(0, $casts);
- $this->assertSame(0, $verifier->getCount('users', 'id', 1));
- $this->assertSame(0, $verifier->getCount('users', 'id', '2'));
+ $this->assertSame(1, $verifier->getCount('users', 'id', 1));
+ $this->assertSame(1, $verifier->getCount('users', 'id', '2'));
}
public function testUnknownScalarFallbackCountsAreMemoizedPerQueryShapeAndValue(): void
@@ -139,10 +131,6 @@ public function testUnknownScalarFallbackCountsAreMemoizedPerQueryShapeAndValue(
->with('users', 'email', m::on(static fn (mixed $value): bool => $value === '1'), null, null, [])
->once()
->andReturn(1);
- $fallback->shouldReceive('getCount')
- ->with('users', 'email', m::on(static fn (mixed $value): bool => $value === 1), null, null, [])
- ->once()
- ->andReturn(0);
$verifier = new PrecomputedPresenceVerifier($fallback);
$verifier->addLookup(self::lookupKey(null, 'users', 'email', extra: ['status' => 'active']), [], [], [], true);
@@ -155,7 +143,7 @@ public function testUnknownScalarFallbackCountsAreMemoizedPerQueryShapeAndValue(
$this->assertSame(0, $verifier->getCount('users', 'email', 'shared', extra: ['status' => 'inactive']));
$this->assertSame(2, $verifier->getCount('admins', 'email', 'shared'));
$this->assertSame(1, $verifier->getCount('users', 'email', '1'));
- $this->assertSame(0, $verifier->getCount('users', 'email', 1));
+ $this->assertSame(1, $verifier->getCount('users', 'email', 1));
}
}
diff --git a/tests/Validation/ValidationRuleParserTest.php b/tests/Validation/ValidationRuleParserTest.php
index cfe1cf6eb5..982594b361 100644
--- a/tests/Validation/ValidationRuleParserTest.php
+++ b/tests/Validation/ValidationRuleParserTest.php
@@ -799,6 +799,18 @@ public function message(): string
$this->assertTrue(ValidationRuleParser::ruleReducesToString(
Rule::exists('users', 'email'),
));
+ $this->assertTrue(ValidationRuleParser::ruleReducesToString(
+ Rule::exists('users', 'email')->where('active', true),
+ ));
+ $this->assertTrue(ValidationRuleParser::ruleReducesToString(
+ Rule::unique('users', 'email')->withoutTrashed(),
+ ));
+ $this->assertFalse(ValidationRuleParser::ruleReducesToString(
+ Rule::exists('users', 'email')->where('type', 'NULL'),
+ ));
+ $this->assertFalse(ValidationRuleParser::ruleReducesToString(
+ Rule::exists('users', 'email')->whereNot('type', 'foo')->whereNot('type', 'bar'),
+ ));
$this->assertTrue(ValidationRuleParser::ruleReducesToString(Rule::date()));
$this->assertFalse(ValidationRuleParser::ruleReducesToString($callbackExists));
$this->assertFalse(ValidationRuleParser::ruleReducesToString(
diff --git a/tests/Validation/ValidationUniqueRuleTest.php b/tests/Validation/ValidationUniqueRuleTest.php
index e1116403fe..3f21da1339 100644
--- a/tests/Validation/ValidationUniqueRuleTest.php
+++ b/tests/Validation/ValidationUniqueRuleTest.php
@@ -229,6 +229,18 @@ public function testItValidatesUniqueRuleWithBooleanWhere(): void
$this->assertFalse($validator->passes());
}
+ public function testItComparesWhereValuesLiterally(): void
+ {
+ EloquentModelStub::create(['id_column' => 1, 'type' => 'admin']);
+
+ $v = new Validator($this->getArrayTranslator(), ['id_column' => 1], [
+ 'id_column' => (new Unique('table', 'id_column'))->where('type', '!user'),
+ ]);
+ $v->setPresenceVerifier(new DatabasePresenceVerifier($this->app->make('db')));
+
+ $this->assertTrue($v->passes());
+ }
+
public function testItValidatesUniqueRuleWithWhereInAndWhereNotIn(): void
{
EloquentModelStub::create(['id_column' => 1, 'type' => 'admin']);
diff --git a/tests/Validation/ValidationValidatorTest.php b/tests/Validation/ValidationValidatorTest.php
index 984caa65e9..68522e2326 100755
--- a/tests/Validation/ValidationValidatorTest.php
+++ b/tests/Validation/ValidationValidatorTest.php
@@ -180,6 +180,57 @@ public function testSometimesWorksOnNestedArrays(): void
$this->assertTrue($v->passes());
}
+ #[DataProvider('nestedSometimesMissingStringProvider')]
+ public function testSometimesValidatesNestedMissingString(array $data, string $attribute, string $failedAttribute, string $rule, string $failedRule): void
+ {
+ $v = new Validator($this->getArrayTranslator(), $data, [$attribute => 'sometimes|' . $rule]);
+
+ $this->assertFalse($v->passes());
+ $this->assertArrayHasKey($failedRule, $v->failed()[$failedAttribute]);
+ }
+
+ public static function nestedSometimesMissingStringProvider(): array
+ {
+ return [
+ 'nested integer' => [['profile' => ['age' => '__missing__']], 'profile.age', 'profile.age', 'integer', 'Integer'],
+ 'nested in' => [['profile' => ['status' => '__missing__']], 'profile.status', 'profile.status', 'in:active,inactive', 'In'],
+ 'wildcard' => [['items' => [['quantity' => '__missing__']]], 'items.*.quantity', 'items.0.quantity', 'integer', 'Integer'],
+ 'terminal wildcard' => [['items' => ['__missing__']], 'items.*', 'items.0', 'integer', 'Integer'],
+ 'multiple wildcards' => [['groups' => [['items' => [['quantity' => '__missing__']]]]], 'groups.*.items.*.quantity', 'groups.0.items.0.quantity', 'integer', 'Integer'],
+ ];
+ }
+
+ #[DataProvider('nestedSometimesMissingStringProvider')]
+ public function testSometimesRejectsInvalidNestedDataFromValidated(array $data, string $attribute, string $failedAttribute, string $rule, string $failedRule): void
+ {
+ $v = new Validator($this->getArrayTranslator(), $data, [$attribute => 'sometimes|' . $rule]);
+
+ $this->expectException(ValidationException::class);
+
+ $v->validated();
+ }
+
+ public function testSometimesAllowsMissingAndValidNestedValues(): void
+ {
+ $data = ['items' => [['quantity' => '__missing__'], [], ['quantity' => null]]];
+ $v = new Validator($this->getArrayTranslator(), $data, [
+ 'items.*.quantity' => 'sometimes|nullable|in:__missing__',
+ ]);
+
+ $this->assertTrue($v->passes());
+ $this->assertSame(['items' => [0 => ['quantity' => '__missing__'], 2 => ['quantity' => null]]], $v->validated());
+ }
+
+ public function testSometimesDistinguishesMissingFromNullNestedValues(): void
+ {
+ $v = new Validator($this->getArrayTranslator(), ['items' => [[], ['quantity' => null]]], [
+ 'items.*.quantity' => 'sometimes|required|integer',
+ ]);
+
+ $this->assertFalse($v->passes());
+ $this->assertSame(['items.1.quantity' => ['Required' => []]], $v->failed());
+ }
+
public function testAfterCallbacksAreCalledWithValidatorInstance(): void
{
$trans = $this->getArrayTranslator();
@@ -6913,6 +6964,11 @@ public function testValidateNotRegex(): void
// Ensure commas are not interpreted as parameter separators
$v = new Validator($trans, ['x' => 'foo bar'], ['x' => 'NotRegex:/x{3,}/i']);
$this->assertTrue($v->passes());
+
+ // Ensure a failed match is not treated as no match
+ $v = new Validator($trans, ['x' => "foo\xFF"], ['x' => 'NotRegex:/foo/u']);
+ $this->assertFalse($v->passes());
+ $this->assertFalse($v->validateNotRegex('x', "foo\xFF", ['/foo/u']));
}
public function testValidateDateAndFormat(): void
@@ -9208,6 +9264,13 @@ public function testExtractDataFromPath(): void
$data = ['cat' => ['cat1' => ['name' => '1', 'price' => 1]], ['cat2' => ['name' => 2]]];
$this->assertEquals(['cat' => ['cat1' => ['name' => '1']]], ValidationData::extractDataFromPath('cat.cat1.name', $data));
+
+ $data = ['cat' => ['name' => '__missing__', 'age' => null]];
+ $this->assertSame(['cat' => ['name' => '__missing__']], ValidationData::extractDataFromPath('cat.name', $data));
+ $this->assertSame(['cat' => ['age' => null]], ValidationData::extractDataFromPath('cat.age', $data));
+ $this->assertSame([], ValidationData::extractDataFromPath('cat.absent', $data));
+ $this->assertSame($data, ValidationData::extractDataFromPath(null, $data));
+ $this->assertSame([], ValidationData::extractDataFromPath(null, []));
}
public function testParsingTablesFromModels(): void
From cb36fb7aa07bffcb1a31fa1f3900ce028c4fcbe1 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sun, 15 Nov 2026 00:52:04 +0000
Subject: [PATCH 12/29] Avoid backtracking in decimal validation
Port laravel/framework#62420 at aeaf7f9bddb349acb0532da1d4b5788080388ba1. Use possessive quantifiers and retain both exponent-rejection cases. Both validation execution paths use the same rule method.
Validation: ValidationValidatorTest (871 tests, 2855 assertions), static analysis and formatting pass.
---
src/validation/src/Concerns/ValidatesAttributes.php | 2 +-
tests/Validation/ValidationValidatorTest.php | 6 ++++++
2 files changed, 7 insertions(+), 1 deletion(-)
diff --git a/src/validation/src/Concerns/ValidatesAttributes.php b/src/validation/src/Concerns/ValidatesAttributes.php
index 4f1a4a3e7e..8ec7a368b6 100644
--- a/src/validation/src/Concerns/ValidatesAttributes.php
+++ b/src/validation/src/Concerns/ValidatesAttributes.php
@@ -696,7 +696,7 @@ public function validateDecimal(string $attribute, mixed $value, mixed $paramete
$matches = [];
- if (preg_match('/^[+-]?\d*\.?(\d*)$/', (string) $value, $matches) !== 1) {
+ if (preg_match('/^[+-]?\d*+\.?+(\d*+)$/', (string) $value, $matches) !== 1) {
return false;
}
diff --git a/tests/Validation/ValidationValidatorTest.php b/tests/Validation/ValidationValidatorTest.php
index 68522e2326..ddec325fa6 100755
--- a/tests/Validation/ValidationValidatorTest.php
+++ b/tests/Validation/ValidationValidatorTest.php
@@ -4116,6 +4116,12 @@ public function testValidateDecimal(): void
$v = new Validator($trans, ['foo' => 1.23], ['foo' => 'Decimal:0,3']);
$this->assertTrue($v->passes());
+
+ $v = new Validator($trans, ['foo' => '1e5'], ['foo' => 'Decimal:0']);
+ $this->assertFalse($v->passes());
+
+ $v = new Validator($trans, ['foo' => '1.5e3'], ['foo' => 'Decimal:0,3']);
+ $this->assertFalse($v->passes());
}
public function testValidateInt(): void
From 425623d38b6ab4f37372522a096542ca3aa38aa1 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sun, 15 Nov 2026 00:52:10 +0000
Subject: [PATCH 13/29] Add blank checks to fluent strings
Port laravel/framework#62415 at 86c0362a41fb377772d7a10434315297b0dcd03f and laravel/docs#11455 at 965d49b75202ef63a121be6e728791b704e22062. Add isBlank and isNotBlank using the existing blank helper, with complete upstream coverage and documentation.
Validation: SupportStringableTest (145 tests, 750 assertions), static analysis and formatting pass.
---
src/docs/strings.md | 40 +++++++++++++++++++++++++
src/support/src/Stringable.php | 16 ++++++++++
tests/Support/SupportStringableTest.php | 29 ++++++++++++++++++
3 files changed, 85 insertions(+)
diff --git a/src/docs/strings.md b/src/docs/strings.md
index 56b6f77cab..3a669b6673 100644
--- a/src/docs/strings.md
+++ b/src/docs/strings.md
@@ -200,6 +200,8 @@ If you need to clear these caches during tests, you may call `StrCache::flushSta
[inlineMarkdown](#method-fluent-str-inline-markdown)
[is](#method-fluent-str-is)
[isAscii](#method-fluent-str-is-ascii)
+[isBlank](#method-fluent-str-is-blank)
+[isNotBlank](#method-fluent-str-is-not-blank)
[isEmpty](#method-fluent-str-is-empty)
[isNotEmpty](#method-fluent-str-is-not-empty)
[isJson](#method-fluent-str-is-json)
@@ -2938,6 +2940,44 @@ $result = Str::of('ü')->isAscii();
// false
```
+
+#### `isBlank` {.collection-method}
+
+The `isBlank` method determines if the given string is blank. A string is considered blank if it is empty or only contains whitespace:
+
+```php
+use Hypervel\Support\Str;
+
+$result = Str::of(' ')->isBlank();
+
+// true
+
+$result = Str::of('
')->stripTags()->isBlank();
+
+// true
+
+$result = Str::of('0')->isBlank();
+
+// false
+```
+
+
+#### `isNotBlank` {.collection-method}
+
+The `isNotBlank` method determines if the given string is not blank:
+
+```php
+use Hypervel\Support\Str;
+
+$result = Str::of(' ')->isNotBlank();
+
+// false
+
+$result = Str::of('Hypervel')->isNotBlank();
+
+// true
+```
+
#### `isEmpty` {.collection-method}
diff --git a/src/support/src/Stringable.php b/src/support/src/Stringable.php
index 531e6b3fdc..a2aee809f4 100644
--- a/src/support/src/Stringable.php
+++ b/src/support/src/Stringable.php
@@ -370,6 +370,22 @@ public function isNotEmpty(): bool
return ! $this->isEmpty();
}
+ /**
+ * Determine if the given string is blank.
+ */
+ public function isBlank(): bool
+ {
+ return blank($this->value);
+ }
+
+ /**
+ * Determine if the given string is not blank.
+ */
+ public function isNotBlank(): bool
+ {
+ return ! $this->isBlank();
+ }
+
/**
* Convert a string to kebab case.
*/
diff --git a/tests/Support/SupportStringableTest.php b/tests/Support/SupportStringableTest.php
index 4e65d90fe8..b68abf647d 100644
--- a/tests/Support/SupportStringableTest.php
+++ b/tests/Support/SupportStringableTest.php
@@ -140,6 +140,35 @@ public function testIsNotEmpty(): void
$this->assertTrue($this->stringable('A')->isNotEmpty());
}
+ public function testIsBlank(): void
+ {
+ $this->assertTrue($this->stringable('')->isBlank());
+ $this->assertTrue($this->stringable(null)->isBlank());
+ $this->assertTrue($this->stringable(' ')->isBlank());
+ $this->assertTrue($this->stringable("\t\n\r\0\x0B")->isBlank());
+ $this->assertTrue(str('
')->stripTags()->isBlank());
+
+ $this->assertFalse($this->stringable('A')->isBlank());
+ $this->assertFalse($this->stringable('0')->isBlank());
+ $this->assertFalse($this->stringable("\u{00A0}")->isBlank());
+ $this->assertFalse($this->stringable("\u{200B}")->isBlank());
+ }
+
+ public function testIsNotBlank(): void
+ {
+ $this->assertFalse($this->stringable('')->isNotBlank());
+ $this->assertFalse($this->stringable(null)->isNotBlank());
+ $this->assertFalse($this->stringable(' ')->isNotBlank());
+ $this->assertFalse($this->stringable("\t\n\r\0\x0B")->isNotBlank());
+ $this->assertFalse(str('
')->stripTags()->isNotBlank());
+
+ $this->assertTrue($this->stringable('A')->isNotBlank());
+ $this->assertTrue($this->stringable('0')->isNotBlank());
+ $this->assertTrue($this->stringable("\u{00A0}")->isNotBlank());
+ $this->assertTrue($this->stringable("\u{200B}")->isNotBlank());
+ $this->assertTrue(str('Hello
')->stripTags()->isNotBlank());
+ }
+
public function testCounted(): void
{
$this->assertSame('1 order', (string) $this->stringable('order')->counted(1));
From 77d2a26ce621e1c57252b58ac331cfa8c895cea0 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sun, 15 Nov 2026 00:52:18 +0000
Subject: [PATCH 14/29] Resolve automatic write columns after applying model
scopes
Port laravel/framework#62412 at a5f102335e824348d024cd0cce256a3e22cb5722. Qualify the default touch timestamp for joined queries. Apply scopes once before selecting automatic columns so scope-added joins and aliases also work for updates, counter writes, soft deletion and restoration.
Preserve builder hooks and explicit-column semantics. Reuse the existing scoped builder without another clone or new API. PostgreSQL updateFrom remains unchanged because its assignment compiler removes qualifiers.
Validation: EloquentUpdateTest passes on MySQL and SQLite (46 tests, 159 assertions each); related builder, soft-delete and PostgreSQL grammar tests pass (304 tests, 846 assertions). Static analysis and formatting pass.
---
src/database/src/Eloquent/Builder.php | 39 ++++++---
.../src/Eloquent/SoftDeletingScope.php | 3 +
.../Database/EloquentUpdateTest.php | 81 +++++++++++++++++++
3 files changed, 113 insertions(+), 10 deletions(-)
diff --git a/src/database/src/Eloquent/Builder.php b/src/database/src/Eloquent/Builder.php
index 680c39c701..75d6c5b9e7 100644
--- a/src/database/src/Eloquent/Builder.php
+++ b/src/database/src/Eloquent/Builder.php
@@ -1316,7 +1316,9 @@ public function forceCreateQuietly(array $attributes = []): Model
*/
public function update(array $values): int
{
- return $this->toBase()->update($this->addUpdatedAtColumn($values));
+ $builder = $this->applyScopes()->withoutGlobalScopes();
+
+ return $builder->toBase()->update($builder->addUpdatedAtColumn($values));
}
/**
@@ -1372,7 +1374,15 @@ public function touch(array|string|null $column = null): false|int
return false;
}
- return $this->toBase()->update([$column => $time]);
+ // Global scopes may add joins or alias the table, so qualify against the scoped builder.
+ $builder = $this->applyScopes()->withoutGlobalScopes();
+ $query = $builder->toBase();
+
+ if (! empty($query->joins)) {
+ $column = $builder->qualifyColumn($column);
+ }
+
+ return $query->update([$column => $time]);
}
/**
@@ -1380,10 +1390,12 @@ public function touch(array|string|null $column = null): false|int
*/
public function increment(Expression|string $column, mixed $amount = 1, array $extra = []): int
{
- return $this->toBase()->increment(
+ $builder = $this->applyScopes()->withoutGlobalScopes();
+
+ return $builder->toBase()->increment(
$column,
$amount,
- $this->addUpdatedAtColumn($extra)
+ $builder->addUpdatedAtColumn($extra)
);
}
@@ -1392,10 +1404,12 @@ public function increment(Expression|string $column, mixed $amount = 1, array $e
*/
public function decrement(Expression|string $column, mixed $amount = 1, array $extra = []): int
{
- return $this->toBase()->decrement(
+ $builder = $this->applyScopes()->withoutGlobalScopes();
+
+ return $builder->toBase()->decrement(
$column,
$amount,
- $this->addUpdatedAtColumn($extra)
+ $builder->addUpdatedAtColumn($extra)
);
}
@@ -1407,9 +1421,11 @@ public function decrement(Expression|string $column, mixed $amount = 1, array $e
*/
public function incrementEach(array $columns, array $extra = []): int
{
- return $this->toBase()->incrementEach(
+ $builder = $this->applyScopes()->withoutGlobalScopes();
+
+ return $builder->toBase()->incrementEach(
$columns,
- $this->addUpdatedAtColumn($extra)
+ $builder->addUpdatedAtColumn($extra)
);
}
@@ -1421,9 +1437,11 @@ public function incrementEach(array $columns, array $extra = []): int
*/
public function decrementEach(array $columns, array $extra = []): int
{
- return $this->toBase()->decrementEach(
+ $builder = $this->applyScopes()->withoutGlobalScopes();
+
+ return $builder->toBase()->decrementEach(
$columns,
- $this->addUpdatedAtColumn($extra)
+ $builder->addUpdatedAtColumn($extra)
);
}
@@ -1439,6 +1457,7 @@ protected function addUpdatedAtColumn(array $values): array
$column = $this->model->getUpdatedAtColumn();
+ // Scopes may alias the table; writes that retain this qualifier must prepare scopes first.
$alias = $this->query->getFromAlias();
// Opaque raw sources cannot safely qualify an automatic timestamp.
diff --git a/src/database/src/Eloquent/SoftDeletingScope.php b/src/database/src/Eloquent/SoftDeletingScope.php
index 42d2f55dac..bdb8192f0b 100644
--- a/src/database/src/Eloquent/SoftDeletingScope.php
+++ b/src/database/src/Eloquent/SoftDeletingScope.php
@@ -41,6 +41,7 @@ public function extend(Builder $builder): void
}
$builder->onDelete(function (Builder $builder) {
+ $builder = $builder->applyScopes()->withoutGlobalScopes();
$column = $this->getDeletedAtColumn($builder);
return $builder->update([
@@ -56,6 +57,7 @@ public function extend(Builder $builder): void
*/
protected function getDeletedAtColumn(Builder $builder): string
{
+ // Scopes may add joins or aliases, so callers pass the scope-prepared builder.
if ((array) $builder->getQuery()->joins !== []) {
return $builder->qualifyColumn($builder->getModel()->getQualifiedDeletedAtColumn());
}
@@ -72,6 +74,7 @@ protected function addRestore(Builder $builder): void
{
$builder->macro('restore', function (Builder $builder) {
$builder->withTrashed();
+ $builder = $builder->applyScopes()->withoutGlobalScopes();
return $builder->update([$this->getDeletedAtColumn($builder) => null]);
});
diff --git a/tests/Integration/Database/EloquentUpdateTest.php b/tests/Integration/Database/EloquentUpdateTest.php
index 4ed3d00531..130fe1b4ad 100644
--- a/tests/Integration/Database/EloquentUpdateTest.php
+++ b/tests/Integration/Database/EloquentUpdateTest.php
@@ -6,6 +6,7 @@
use Closure;
use Hypervel\Contracts\Database\Eloquent\CastsAttributes;
+use Hypervel\Database\Eloquent\Builder;
use Hypervel\Database\Eloquent\Casts\AsEncryptedCollection;
use Hypervel\Database\Eloquent\Model;
use Hypervel\Database\Eloquent\SoftDeletes;
@@ -15,6 +16,7 @@
use Hypervel\Support\Facades\Schema;
use Hypervel\Support\Str;
use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\Attributes\TestWith;
use RuntimeException;
class EloquentUpdateTest extends DatabaseTestCase
@@ -97,6 +99,64 @@ public function testUpdatedAtWithJoins(): void
$this->assertSame('Engineer: Abdul', $record->job . ': ' . $record->name);
}
+ #[TestWith([false])]
+ #[TestWith([true])]
+ public function testTouchQualifiesUpdatedAtColumnOnQueriesWithJoins(bool $scoped): void
+ {
+ TestUpdateModel2::forceCreate([
+ 'name' => Str::random(),
+ 'updated_at' => '2000-01-01 00:00:00',
+ ]);
+
+ TestUpdateModel3::forceCreate([
+ 'counter' => 1,
+ 'updated_at' => '2000-01-01 00:00:00',
+ ]);
+
+ $query = TestUpdateModel2::query();
+ $join = static fn (Builder $builder) => $builder->join('test_model3', 'test_model3.id', '=', 'test_model2.id');
+
+ if ($scoped) {
+ $query->withGlobalScope('joined', $join);
+ } else {
+ $join($query);
+ }
+
+ $affected = $query->touch();
+
+ $this->assertSame(1, $affected);
+ $this->assertNotSame('2000-01-01 00:00:00', TestUpdateModel2::find(1)->updated_at->toDateTimeString());
+ $this->assertSame('2000-01-01 00:00:00', TestUpdateModel3::find(1)->updated_at->toDateTimeString());
+ }
+
+ #[TestWith(['touch', [], 2])]
+ #[TestWith(['update', [['counter' => 3]], 3])]
+ #[TestWith(['increment', ['counter'], 3])]
+ #[TestWith(['decrement', ['counter'], 1])]
+ #[TestWith(['incrementEach', [['counter' => 1]], 3])]
+ #[TestWith(['decrementEach', [['counter' => 1]], 1])]
+ public function testWritesUseTableAliasAddedByGlobalScope(string $method, array $arguments, int $counter): void
+ {
+ TestUpdateModel1::create(['name' => 'access', 'title' => 'allowed']);
+ TestUpdateModel3::forceCreate(['counter' => 2, 'updated_at' => '2000-01-01 00:00:00']);
+ $scopeCalls = 0;
+
+ $query = TestUpdateModel3::withoutGlobalScopes()
+ ->withGlobalScope('access', function (Builder $query) use (&$scopeCalls): void {
+ ++$scopeCalls;
+ $query->from('test_model3', 'target')
+ ->join('test_model1', 'test_model1.id', '=', 'target.id')
+ ->where('test_model1.title', 'allowed');
+ });
+
+ $affected = $query->{$method}(...$arguments);
+
+ $this->assertSame(1, $affected);
+ $this->assertSame(1, $scopeCalls);
+ $this->assertSame($counter, TestUpdateModel3::find(1)->counter);
+ $this->assertNotSame('2000-01-01 00:00:00', TestUpdateModel3::find(1)->updated_at->toDateTimeString());
+ }
+
public function testSoftDeleteWithJoins(): void
{
TestUpdateModel1::create([
@@ -116,6 +176,27 @@ public function testSoftDeleteWithJoins(): void
$this->assertCount(0, TestUpdateModel2::all());
}
+ #[TestWith([false])]
+ #[TestWith([true])]
+ public function testSoftDeleteAndRestoreWithScopedJoins(bool $restore): void
+ {
+ TestUpdateModel2::forceCreate([
+ 'name' => 'target',
+ 'deleted_at' => $restore ? '2000-01-01 00:00:00' : null,
+ ]);
+ TestUpdateModel3::create(['counter' => 1]);
+ $scopeCalls = 0;
+ $query = TestUpdateModel2::query()->withGlobalScope('joined', function (Builder $query) use (&$scopeCalls): void {
+ ++$scopeCalls;
+ $query->join('test_model3', 'test_model3.id', '=', 'test_model2.id');
+ });
+
+ $this->assertSame(1, $restore ? $query->restore() : $query->delete());
+ $this->assertSame(1, $scopeCalls);
+ $this->assertSame(! $restore, TestUpdateModel2::withTrashed()->find(1)->trashed());
+ $this->assertFalse(TestUpdateModel3::find(1)->trashed());
+ }
+
public function testIncrement(): void
{
TestUpdateModel3::create([
From f29db78b4bf0e4d8443684a472bef62aedcf442f Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sun, 15 Nov 2026 00:52:30 +0000
Subject: [PATCH 15/29] Protect literal PHAR archive boundaries on POSIX
Reconcile laravel/framework#62413 at d604d5bc03b0f63561729ddc217e6089d0d398b5. Keep literal path comparison: normalizing backslashes on supported POSIX platforms can admit a separate archive whose filename begins with the running archive name.
Port the nested archive read and all upstream boundary cases with POSIX expectations. Add a real foreign-archive fixture proving native PHP can read the crafted path while Filesystem rejects it.
Validation: FilesystemTest passes (91 tests, 233 assertions); formatting passes. Production behavior is unchanged.
---
src/filesystem/src/Filesystem.php | 1 +
tests/Filesystem/FilesystemTest.php | 42 ++++++++++++++++++++++++++---
2 files changed, 39 insertions(+), 4 deletions(-)
diff --git a/src/filesystem/src/Filesystem.php b/src/filesystem/src/Filesystem.php
index abdae95f89..6f7182f9a5 100644
--- a/src/filesystem/src/Filesystem.php
+++ b/src/filesystem/src/Filesystem.php
@@ -547,6 +547,7 @@ protected function hasDangerousStreamWrapper(string $path): bool
$running = class_exists(Phar::class, false) ? Phar::running() : '';
+ // On POSIX, normalizing backslashes could allow a separate archive named app.phar\other.phar.
return $running === '' || ! str_starts_with($path, $running . '/');
}
diff --git a/tests/Filesystem/FilesystemTest.php b/tests/Filesystem/FilesystemTest.php
index 346d494fe1..533a95b8ed 100755
--- a/tests/Filesystem/FilesystemTest.php
+++ b/tests/Filesystem/FilesystemTest.php
@@ -352,20 +352,53 @@ public function testFilesInsideTheRunningPharCanBeRead(): void
$phar = $this->tempDir . '/app.phar';
file_put_contents($this->tempDir . '/run.php', 'get(Phar::running()."/file.txt"), "|", var_export($files->exists("phar:///some/archive.phar/entry"), true);
+ $files = new class extends Filesystem
+ {
+ /**
+ * Determine whether the path passes the archive boundary check.
+ */
+ public function allows(string $path): bool
+ {
+ return ! $this->hasDangerousStreamWrapper($path);
+ }
+ };
+
+ $running = Phar::running();
+
+ echo $files->get($running."/file.txt"), "|", $files->get($running."/dir/file.txt"), "|", json_encode([
+ $files->allows($running."\\\file.txt"),
+ $files->allows($running."\\\dir/file.txt"),
+ $files->allows($running."\\\dir\\\file.txt"),
+ $files->allows($running.".evil/file.txt"),
+ $files->allows($running."X/file.txt"),
+ $files->allows($running."X\\\file.txt"),
+ $files->exists("phar:///some/archive.phar/entry"),
+ ]);
+
+ $foreign = $running."\\\foreign.phar/file.txt";
+ echo "|", file_get_contents($foreign), "|", var_export($files->exists($foreign), true);
');
file_put_contents($this->tempDir . '/build.php', 'addFile(' . var_export(realpath(__DIR__ . '/../../src/filesystem/src/Filesystem.php'), true) . ', "Filesystem.php");
$phar->addFile(' . var_export($this->tempDir . '/run.php', true) . ', "run.php");
$phar->addFromString("file.txt", "Hello from phar");
+ $phar->addFromString("dir/file.txt", "Hello from nested");
$phar->setStub(\'tempDir . '/foreign.phar', true) . ');
+ $foreign->addFromString("file.txt", "Hello from foreign");
+ copy(' . var_export($this->tempDir . '/foreign.phar', true) . ', ' . var_export($phar . '\foreign.phar', true) . ');
');
(new Process([PHP_BINARY, '-d', 'phar.readonly=0', $this->tempDir . '/build.php'], timeout: 10))->mustRun();
@@ -373,7 +406,8 @@ public function testFilesInsideTheRunningPharCanBeRead(): void
$process = new Process([PHP_BINARY, $phar], timeout: 10);
$process->mustRun();
- $this->assertSame('Hello from phar|false', $process->getOutput());
+ // Unlike upstream's Windows normalization, POSIX backslashes remain literal filename characters.
+ $this->assertSame('Hello from phar|Hello from nested|[false,false,false,false,false,false,false]|Hello from foreign|false', $process->getOutput());
}
#[RequiresPhpExtension('phar')]
From d53e27d8e0ab4c2d9ad1d63cf53352a635899829 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sun, 15 Nov 2026 00:52:30 +0000
Subject: [PATCH 16/29] Avoid reporting manually failed jobs as successful
Port laravel/framework#62377 at c33d357a57f1db1cb562104bd367a9ff3ebbe1d5. Suppress success output for jobs already marked failed, preserving coroutine-owned command selection. Include the complete upstream manual-failure regression and job fixture.
Validation: queue integration tests pass (22 tests, 77 assertions), related Queue and Horizon command tests pass (20 tests, 97 assertions), and static analysis and formatting pass.
---
src/queue/src/Console/WorkCommand.php | 4 +++
tests/Integration/Queue/WorkCommandTest.php | 29 +++++++++++++++++++++
2 files changed, 33 insertions(+)
diff --git a/src/queue/src/Console/WorkCommand.php b/src/queue/src/Console/WorkCommand.php
index 48ab59476d..2e07a45100 100644
--- a/src/queue/src/Console/WorkCommand.php
+++ b/src/queue/src/Console/WorkCommand.php
@@ -186,6 +186,10 @@ protected function listenForEvents(): void
});
$events->listen(JobProcessed::class, static function (JobProcessed $event): void {
+ if ($event->job->hasFailed()) {
+ return;
+ }
+
static::currentCommand()?->writeOutput($event->job, 'success');
});
diff --git a/tests/Integration/Queue/WorkCommandTest.php b/tests/Integration/Queue/WorkCommandTest.php
index 8871ef0f06..67163607f9 100644
--- a/tests/Integration/Queue/WorkCommandTest.php
+++ b/tests/Integration/Queue/WorkCommandTest.php
@@ -379,6 +379,20 @@ public function testReleasedJobIsWrittenAsReleased(): void
->assertExitCode(0);
}
+ public function testManuallyFailedJobIsOnlyWrittenAsFailed(): void
+ {
+ $this->markTestSkippedWhenUsingQueueDrivers(['beanstalkd']);
+
+ Queue::push(new ManuallyFailingJob);
+
+ $this->artisan('queue:work', [
+ '--once' => true,
+ '--memory' => 1024,
+ ])->expectsOutputToContain('FAIL')
+ ->doesntExpectOutputToContain('DONE')
+ ->assertExitCode(0);
+ }
+
public function testStopReasonIsWritten(): void
{
Queue::push(new FirstJob);
@@ -513,6 +527,21 @@ public function handle(): void
}
}
+class ManuallyFailingJob implements ShouldQueue
+{
+ use Dispatchable;
+ use InteractsWithQueue;
+ use Queueable;
+
+ /**
+ * Mark the job as failed without throwing.
+ */
+ public function handle(): void
+ {
+ $this->fail('Manually failed.');
+ }
+}
+
class JobWillFail implements ShouldQueue
{
use Dispatchable;
From 12951e95ae98d01f7f134dd69ccbb65435f011f3 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Sun, 15 Nov 2026 01:13:42 +0000
Subject: [PATCH 17/29] Avoid unnecessary hashing work and real waits in tests
Complete laravel/framework#62443 at 49b6ca1ceaeb3436b94078e2b7c81073f0c0f9c3. Use shared bcrypt test settings and fake sleeps while retaining configured authentication timeboxes, HTTP retry delays and limiter expiry checks.
Remove duplicate test-specific bcrypt settings and update Testbench expectations for the shared environment in direct and package modes. Preserve deliberate hashing-cost differences and existing assertions.
Validation: every changed test class, related hashing and rehash tests, the Testbench package suite and repository formatting pass. No production code changes.
---
phpunit.xml.dist | 1 +
tests/Auth/AuthDatabaseUserProviderTest.php | 4 ++--
tests/Auth/AuthPasswordBrokerTest.php | 13 +++++++++++++
tests/Cache/ConcurrencyLimiterTest.php | 13 +++++++++++--
tests/Http/HttpClientTest.php | 12 +++++++++---
tests/Integration/Auth/AuthenticationTest.php | 14 ++++++++++++--
tests/Integration/Auth/ForgotPasswordTest.php | 17 +++++++++++++++--
.../ForgotPasswordWithoutDefaultRoutesTest.php | 14 ++++++++++++--
.../Database/EloquentModelHashedCastingTest.php | 4 ++--
.../Sqlite/UserSessionLifecycleTest.php | 1 -
tests/Testbench/DefaultConfigurationTest.php | 3 ++-
11 files changed, 79 insertions(+), 17 deletions(-)
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index facf0d6b18..a39713c97d 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -31,6 +31,7 @@
+