Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 27 additions & 30 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -591,9 +591,17 @@ Do **not** create per-package abstract test case classes (e.g., `EngineTestCase`

A per-package base class is only justified when there is shared setUp logic — e.g., shared container mock setup, shared helpers, or shared test fixtures that multiple test classes in the package need.

### Mockery
### Test doubles

**Always import as `m`:** Use `use Mockery as m;` and call `m::mock()`, `m::spy()`, etc. Never use the full `Mockery::` prefix.
Use Double for test doubles in new tests. When porting, convert direct Mockery mocks and spies to Double regardless of the upstream library; keep upstream PHPUnit doubles. Retain Mockery where required to use or test framework APIs backed by it, such as `$this->mock()`, facade expectations and `Sanctum::actingAs()`. Add `JMac\Testing\Integrations\PHPUnit\VerifiesDoubles` to each test class using Double; it owns verification and cleanup.

Double is lenient by default. Use `expects('method')->never()` to forbid a call, or `unused()` after exercising the code to assert no calls occurred. `allows()->with(...)` neither requires a matching call nor rejects other arguments. `expects()->with(...)` requires the call and rejects unmatched arguments for that method. Use `strict()` when calls to unconfigured methods must fail.

Do not overlap `allows()` stubs with `expects()` constraints when enforcing maximum call counts or `never()`; a matching stub can absorb those calls regardless of registration order.

#### Mockery

Where Mockery is required by a framework integration, import it as `m`.

Framework base test cases own Mockery verification in `tearDown()` so unmet
expectations are attributed to the test that created them. The global
Expand All @@ -620,44 +628,34 @@ public bool $timestamps = false;

**Mock return types must match:**
```php
// Laravel (loose - stdClass works)
$connection = m::mock(stdClass::class);

// Hypervel (strict - use correct type)
$connection = m::mock(PDO::class);
$query = m::mock(QueryBuilder::class);
// Use the native type required by the consumer.
$connection = Double::for(PDO::class);
$query = Double::for(QueryBuilder::class);
```

**Fluent methods need return values:**
```php
// Laravel (null return silently accepted)
$builder->shouldReceive('where')->with(...);
**Fluent return values:**

// Hypervel (must return for chaining)
$builder->shouldReceive('where')->with(...)->andReturnSelf();
```
Double's type-based defaults return the double itself for non-nullable `self`, `static`, or declaring-class return types, and `null` for nullable types. These defaults apply to configured calls without an explicit return and unconfigured calls in lenient mode; unconfigured passthru calls run the real method.

**Mocking methods with `static` return type:**

Methods like `newInstance()` have `static` return type, meaning they must return the same class (or subclass) as the object they're called on. Mockery creates proxy subclasses, so returning the parent class fails:
Methods like `newInstance()` have `static` return type, meaning they must return the same class (or subclass) as the object they're called on. Doubles are generated subclasses, so returning the parent class fails:

```php
// FAILS - mock is Mockery_1_MyModel, returning MyModel fails static type
$this->related = m::mock(MyModel::class);
$this->related->shouldReceive('newInstance')->andReturn(new MyModel);
// Returning the parent class violates the generated subclass's static return type.
$this->related = Double::for(MyModel::class);
$this->related->expects('newInstance')->returns(new MyModel);

// WORKS - use partial mock and andReturnSelf()
$this->related = m::mock(MyModel::class)->makePartial();
$this->related->shouldReceive('newInstance')->andReturnSelf();
// Initialize real model behavior and intentionally return the double itself.
$this->related = Double::for(new MyModel)->passthru();
$this->related->expects('newInstance');

// Test attributes on the mock itself (partial mock has real Model behavior)
// Test attributes on the double itself (passthru keeps real Model behavior)
$result = $relation->getResults();
$this->assertSame('taylor', $result->username);
```

This is a testing-only issue — the strict types are correct and an improvement. In production code, you never mock Models and call `newInstance()`.

**When `andReturnSelf()` isn't enough:**
**When distinct instances are required:**

If a test needs to verify distinct instances (e.g., `makeMany()` returns different objects), use a concrete test stub instead of mocks:

Expand Down Expand Up @@ -685,8 +683,6 @@ $this->assertNotSame($instances[0], $instances[1]);
$this->assertFalse(EloquentHasManyRelatedStub::$saveCalled);
```

Concrete stubs are the correct approach here — they test actual behavior rather than just verifying mocks were called correctly.

### When tests expose source code type errors

If a test fails with a type error, the source code type may be wrong — not the test. Types should be **correct**, not just strict. A narrow type that doesn't cover all valid cases is incorrect.
Expand Down Expand Up @@ -789,6 +785,7 @@ Run full PHPStan checks with `composer analyse`. During implementation, use targ
When porting Laravel packages, whether first-party or third-party, keep them as close to 1:1 with upstream as possible so future changes are easy to merge. The exceptions are:
- Modernizing PHP types, including native parameter, return, property, and class-constant types, plus other appropriate PHP 8.4+ features, strict types, and strict comparisons
- Applying the class-import convention, including its exceptions
- Converting direct Mockery test doubles to Double under [Test doubles](#test-doubles)
- Converting mutable Laravel date construction to Hypervel's immutable date conventions, typing configurable factory output as `CarbonInterface`, and capturing date-modifier return values
- Converting container array access (`$app['events']`) and dynamic service-property access (`$app->events`) in ported code to named container methods, and applying the Configuration rules to ported config and its consumers
- Adding Laravel-style title docblocks to methods (not classes — see Development Conventions)
Expand Down Expand Up @@ -963,8 +960,8 @@ Tests for these features should be **removed** (not commented out) without askin
4. Extend the appropriate test base listed under [Base classes](#base-classes)
5. Ensure `parent::setUp()` is called
6. Add type declarations to model properties
7. Fix mock types (PDO, QueryBuilder, Grammar, etc.)
8. Add `->andReturnSelf()` to chained method mocks
7. Convert direct Mockery doubles to Double (see [Test doubles](#test-doubles)) and double the correct native types (PDO, QueryBuilder, Grammar, etc.)
8. Ensure fluent doubles return the intended object, accounting for Double's automatic self-return
9. Use a test-specific namespace only when helper classes have generic, collision-prone names — already-specific helper names do not need extra namespace ceremony.
10. Remove tests only under the rules in Handling failing tests
11. Run tests and fix any remaining type errors
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@
"fakerphp/faker": "^1.24",
"friendsofphp/php-cs-fixer": "^3.57.2",
"intervention/image": "^4.2",
"jasonmccreary/double": "^1.1.1",
"league/flysystem-ftp": "^3.36",
"league/flysystem-google-cloud-storage": "^3.0",
"league/flysystem-sftp-v3": "^3.36",
Expand Down
19 changes: 12 additions & 7 deletions docs/ai/porting-hyperf.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,12 @@ $result = $container->get(Foo::class); // test setup call

// Hypervel
use Hypervel\Contracts\Container\Container as ContainerContract;
$container = m::mock(ContainerContract::class);
$container->shouldReceive('make')->with(Foo::class)->andReturn(new Foo());
use JMac\Testing\Double;

// The container's instance() method collides with Double's control API.
$containerDouble = Double::for(ContainerContract::class, override: true);
$containerDouble->allows('make')->with(Foo::class)->returns(new Foo);
$container = $containerDouble->instance();
$result = $container->make(Foo::class); // test setup call
```

Expand All @@ -258,10 +262,11 @@ $formatter->shouldReceive('format')->with($exception)->twice()->andReturn('unit'

// Hypervel
use Hypervel\Contracts\Debug\ExceptionHandler as ExceptionHandlerContract;
$container->shouldReceive('has')->with(ExceptionHandlerContract::class)->andReturnTrue();
$container->shouldReceive('make')->with(ExceptionHandlerContract::class)
->andReturn($handler = m::mock(ExceptionHandlerContract::class));
$handler->shouldReceive('report')->with($exception)->twice();

$handler = Double::for(ExceptionHandlerContract::class);
$containerDouble->allows('has')->with(ExceptionHandlerContract::class)->returns(true);
$containerDouble->allows('make')->with(ExceptionHandlerContract::class)->returns($handler);
$handler->expects('report')->with($exception)->times(2);
```

### NonCoroutine tests
Expand All @@ -275,7 +280,7 @@ Hyperf uses `#[Group('NonCoroutine')]` on individual test methods to mark tests
3. Change `Hyperf\` imports to `Hypervel\`
4. Remove Hyperf license header; remove `#[CoversNothing]` and `#[CoversClass(…)]` attributes
5. Extend `Hypervel\Tests\TestCase` (not `PHPUnit\Framework\TestCase`)
6. Change container mock to `Hypervel\Contracts\Container\Container`, all `->get()` to `->make()` (expectations AND direct calls)
6. Convert Mockery doubles to Double per the [test double conventions](../../AGENTS.md#test-doubles); use `Hypervel\Contracts\Container\Container` and change all `->get()` to `->make()` (expectations and direct calls)
7. Change error handler mock to `Hypervel\Contracts\Debug\ExceptionHandler`
8. Extract `#[Group('NonCoroutine')]` methods to separate class with `$runTestsInCoroutine = false`
9. Ensure `parent::setUp()` is called
Expand Down
2 changes: 2 additions & 0 deletions docs/todo.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@

## Framework-wide

- Audit the entire codebase for behavior missing from its contracts, designing them as complete greenfield framework interfaces rather than copying Laravel's omissions. Add methods every conforming implementation must provide, based on real consumers and implementation semantics; keep internal helpers and implementation- or driver-specific capabilities off general contracts. Update implementations, tests and public-contract documentation together.

- In a separate PR, make factory-created dates immutable by contract, removing the application-wide mutable opt-out from `Date` / `DateFactory`, `now()` and `today()`. Audit custom classes, factories, callbacks and consumers; preserve useful timezone, locale and test-clock customization and immutable subclasses. Keep explicit mutable conversion at third-party boundaries. Update runtime enforcement, return types, tests and docs together, then tighten `hypervel/phpstan` typing and discarded-date diagnostics wherever immutability is guaranteed; retain accurate handling of external mutable dates. Review the Laravel API departures before implementation.

- Once a released `nesbot/carbon` version fixes generated fluent return annotations to preserve subclasses, raise the applicable Carbon minimum through Composer and remove the redundant `@method static` overrides from `Hypervel\Support\CarbonImmutable` (`src/support/src/CarbonImmutable.php`). Carbon's `phpdoc.php::compileDoc()` currently emits concrete `CarbonImmutable`/`CarbonInterface` return types for these methods even though runtime preserves the calling class. Retain the existing overrides until a fixed release is verified; do not expand them into a duplicate of Carbon's complete method list. Keep `types/Support/CarbonImmutable.php` as dependency regression coverage, verify further subclasses as well, and remove `SupportCarbonImmutableTest::testMagicModifierMetadataMatchesRuntimeStaticType()` if no local overrides remain.
Expand Down
2 changes: 2 additions & 0 deletions src/contracts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ Documentation: https://hypervel.org/docs/contracts

The `Container` contract also requires `isScoped()`, `isScopedInstance()`, `resolvedShared()`, `forgetInstance()`, `makeTransient()`, `build()`, `buildWith()`, `resolveContextualParameters()`, and `rebinding()`. Custom implementations must provide these methods; extending `Hypervel\Container\Container` supplies them. Lifetime inspection lets consumers cache only the instances the container shares for the worker, instead of caching scoped or fresh services across requests.

The `View` contract also requires `gatherData(): array`, which exposes the data used to render the view, including shared values, for response assertions. The standard `Hypervel\View\View` already provides it.

Ported from: https://github.com/laravel/framework/tree/13.x/src/Illuminate/Contracts
8 changes: 8 additions & 0 deletions src/contracts/src/View/View.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ public function with(string|array $key, mixed $value = null): static;
*/
public function getData(): array;

/**
* Get the data used to render the view.
*
* Unlike Laravel, the contract declares this method because response assertions
* inspect rendering data, including shared values, through the view contract.
*/
public function gatherData(): array;

/**
* Get the path to the view file.
*/
Expand Down
2 changes: 2 additions & 0 deletions src/docs/porting-from-laravel.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,8 @@ Some packages also define package-local contracts, such as `Hypervel\Permission\

`Hypervel\Contracts\Support\MessageBag` extends `Stringable`, so a custom message bag without `__toString()` fails at class declaration rather than later when `ViewErrorBag` renders it.

Custom `Hypervel\Contracts\View\View` implementations must provide `gatherData(): array`, returning the data used to render the view, including any shared values. Extending `Hypervel\View\View` supplies it.

<a name="missing-equivalents"></a>
### Missing Equivalents

Expand Down
3 changes: 2 additions & 1 deletion src/mail/src/Transport/SesV2Transport.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ protected function doSend(SentMessage $message): void
array_merge(
$options,
[
'Source' => $message->getEnvelope()->getSender()->toString(),
// SES v2 drops Laravel's v1-only Source field. Keep the raw sender headers;
// the envelope sender may be a Return-Path, not the FromEmailAddress identity.
'Destination' => [
'ToAddresses' => (new Collection($message->getEnvelope()->getRecipients()))
->map
Expand Down
3 changes: 2 additions & 1 deletion src/queue/src/Console/RetryBatchCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ protected function getBatchJobIds(): array
{
$ids = (array) $this->argument('id');

return array_values(array_filter(array_unique($ids)));
// Nonempty IDs, including "0", must reach the repository for a result or not-found message.
return array_values(array_filter(array_unique($ids), static fn (int|string $id): bool => $id !== ''));
}
}
8 changes: 6 additions & 2 deletions src/queue/src/Console/RetryCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,15 +107,19 @@ protected function getJobIds(): array
return $failer->ids();
}

if ($queue = $this->option('queue')) {
$queue = $this->option('queue');

// A queue named "0" is valid; only an omitted or empty option means no queue.
if ($queue !== null && $queue !== '') {
return $this->getJobIdsByQueue($queue);
}

if ($ranges = (array) $this->option('range')) {
$ids = array_merge($ids, $this->getJobIdsByRanges($ranges));
}

return array_values(array_filter(array_unique($ids)));
// Nonempty IDs, including "0", must reach the provider for a result or not-found message.
return array_values(array_filter(array_unique($ids), static fn (int|string $id): bool => $id !== ''));
}

/**
Expand Down
Loading
Loading