Skip to content

Commit

Permalink
Merge pull request #30 from tonysm/turbo-native-request-macro
Browse files Browse the repository at this point in the history
Adds the wasFromTurboNative request macro
  • Loading branch information
tonysm authored Jul 23, 2021
2 parents e83d033 + 22f6b4b commit b1f3314
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -697,13 +697,21 @@ Alternatively, you can check if it's not a Turbo Native visit using the `@unless
@endunlessturbonative
```

You may also check if the request was made from a Turbo Native visit using the TurboFacade, like so:
You may also check if the request was made from a Turbo Native visit using the request macro:

```php
if (request()->wasFromTurboNative()) {
// ...
}
```

Or the Turbo Facade directly, like so:

```php
use Tonysm\TurboLaravel\Facades\Turbo;

if (Turbo::isTurboNativeVisit()) {
// Do something for mobile specific requests.
// ...
}
```

Expand Down
4 changes: 4 additions & 0 deletions src/TurboServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ private function bindRequestAndResponseMacros(): void
Request::macro('wantsTurboStream', function () {
return Str::contains($this->header('Accept'), Turbo::TURBO_STREAM_FORMAT);
});

Request::macro('wasFromTurboNative', function () {
return TurboFacade::isTurboNativeVisit();
});
}

protected function bindTestResponseMacros()
Expand Down
11 changes: 11 additions & 0 deletions tests/Http/RequestMacrosTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Tonysm\TurboLaravel\Tests\Http;

use Illuminate\Http\Request;
use Tonysm\TurboLaravel\Facades\Turbo as TurboFacade;
use Tonysm\TurboLaravel\Tests\TestCase;
use Tonysm\TurboLaravel\Turbo;

Expand All @@ -20,4 +21,14 @@ public function wants_turbo_stream()
]);
$this->assertTrue($request->wantsTurboStream(), 'Expected request to want a turbo stream response, but it did not.');
}

/** @test */
public function was_from_turbo_native()
{
$request = Request::create('/hello');
$this->assertFalse($request->wasFromTurboNative());

TurboFacade::setVisitingFromTurboNative();
$this->assertTrue($request->wasFromTurboNative());
}
}

0 comments on commit b1f3314

Please sign in to comment.