Skip to content

Commit

Permalink
Merge pull request #42 from xtend-packages/feature/improve-extend-pes…
Browse files Browse the repository at this point in the history
…t-tests

Improve tests + remove service provider
  • Loading branch information
adam-code-labx authored May 13, 2024
2 parents 989aad0 + 1a7ee6b commit 4ebd5b0
Show file tree
Hide file tree
Showing 22 changed files with 307 additions and 93 deletions.
33 changes: 33 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,38 @@
# Changelog for RESTPresenter

## [0.11.0](https://github.com/xtend-packages/rest-presenter/compare/0.10.1...0.11.0) (2024-05-11)


### Features

* auth middleware isAuthenticated property for all resources ([8125c0b](https://github.com/xtend-packages/rest-presenter/commit/8125c0b86d90fd08507236e407c145f35739a8ba))
* Default resource presenters + profile example for user ([03fa2e1](https://github.com/xtend-packages/rest-presenter/commit/03fa2e15f741dbec051f549578bb3c48f7658bba))

## [0.10.1](https://github.com/xtend-packages/rest-presenter/compare/0.10.0...0.10.1) (2024-05-11)


### Bug Fixes

* PEST show tests ([01998f5](https://github.com/xtend-packages/rest-presenter/commit/01998f5b1ac7de76f2d0d1c0daf0d2efe67f1ec7))

## [0.10.0](https://github.com/xtend-packages/rest-presenter/compare/0.9.3...0.10.0) (2024-05-10)


### Features

* Make resource test called directly after generating each resource ([53c95fb](https://github.com/xtend-packages/rest-presenter/commit/53c95fbfa25b0c2c56076e95d3a295fd1c940ef6))
* New test command + stubs to support both pest & phpunit ([59e598b](https://github.com/xtend-packages/rest-presenter/commit/59e598b69d2c9b98201dbffc34b6c35839454c1e))


### Bug Fixes

* phpstan ignore rules ([f2d6689](https://github.com/xtend-packages/rest-presenter/commit/f2d6689a0229814d09af6f4a2954be742357e453))
* Remove ServiceProvider no longer needed + register new test command ([8e5d039](https://github.com/xtend-packages/rest-presenter/commit/8e5d0394aeddd01bb57315d6b79e3f416bc7f0bb))
* Satisfy phpstan ([a5b3379](https://github.com/xtend-packages/rest-presenter/commit/a5b3379664fe31eabef9dd51aa67f41929284c18))
* starter-kit type string ([ea1dfad](https://github.com/xtend-packages/rest-presenter/commit/ea1dfad5b5bb0ca938a78b5f7aa834f4add1434d))
* Test helpers namespace functions ([b665de4](https://github.com/xtend-packages/rest-presenter/commit/b665de44176fc75537707d7566e4b543779d2ac7))
* test workflow composer dump-autoload ([1c424a3](https://github.com/xtend-packages/rest-presenter/commit/1c424a36d870df0f866cdf6bf90533f4b9fc7bc0))

## [0.9.3](https://github.com/xtend-packages/rest-presenter/compare/0.9.2...0.9.3) (2024-05-07)


Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "xtend-packages/rest-presenter",
"version": "0.9.3",
"version": "0.11.0",
"description": "REST API Presenter & Generator for Laravel",
"keywords": [
"code-labx",
Expand Down
2 changes: 0 additions & 2 deletions config/rest-presenter.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@
'ts_types_trailing_semicolon' => env('REST_PRESENTER_GENERATOR_TS_TYPES_TRAILING_SEMICOLON', true),
'test_path' => env('REST_PRESENTER_GENERATOR_TEST_PATH', 'tests/Feature/Api/v1'),
'test_namespace' => env('REST_PRESENTER_GENERATOR_TEST_NAMESPACE', 'Tests\Feature\Api\v1'),
// Currently we only support PEST testing framework. Other testing frameworks will be supported in the future.
'test_framework' => 'pest',
'structure' => [
'actions' => 'Actions',
'concerns' => 'Concerns',
Expand Down
3 changes: 1 addition & 2 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
<phpunit bootstrap="vendor/autoload.php" colors="true" executionOrder="random" failOnWarning="true" failOnRisky="true" failOnEmptyTestSuite="true" beStrictAboutOutputDuringTests="true">
<testsuites>
<testsuite name="RESTPresenter">
<directory>tests/Resources</directory>
<directory>tests/Support</directory>
<directory>tests</directory>
</testsuite>
</testsuites>
<source>
Expand Down
7 changes: 7 additions & 0 deletions src/Commands/Generator/MakeResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,13 @@ function (string $presenter, $presenterKey): string {
->plural()
->value();

if ($presenter === 'xtend') {
$presenterPlural = $presenterKey !== 'profile' ? Str::of($presenterKey)->plural()->studly() : 'Users';
$presenterSingle = Str::of($presenterKey)->singular()->studly();

return "'$presenterKey' => \XtendPackages\RESTPresenter\Resources\\$presenterPlural\\Presenters\\$presenterSingle::class";
}

return "'$presenterKey' => Presenters\\".$presenterNamespace.'\\'.$presenter;
},
)->implode(",\n\t\t\t").',';
Expand Down
2 changes: 2 additions & 0 deletions src/Commands/Generator/stubs/new/resource.controller.php.stub
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ class {{ class }} extends ResourceController
{
protected static string $model = {{ modelClassName }}::class;

public static bool $isAuthenticated = false;

public function index(Request $request): Collection
{
${{ $modelVarPlural }} = $this->getModelQueryInstance()->get();
Expand Down
5 changes: 4 additions & 1 deletion src/Commands/Generator/stubs/tests/resource.pest.php.stub
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ beforeEach(function (): void {
});

describe('{{ modelClassName }}', function (): void {
test('can show a {{ $modelVarSingular }}', function ({{ modelClassName }} ${{ $modelVarSingular }}): void {
test('can show a {{ $modelVarSingular }}', function (): void {

${{ $modelVarSingular }} = $this->{{ $modelVarPlural }}->random();

$response = getJson(
uri: route('api.v1.filament.{{ $modelVarPlural }}.show', ${{ $modelVarSingular }}),
headers: ['x-rest-presenter' => '{{ modelClassName }}'],
Expand Down
2 changes: 1 addition & 1 deletion src/Commands/Generator/stubs/tests/resource.test.php.stub
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class {{ testClassName }} extends TestCase
*/
public function test_can_show_a_{{ $modelVarSingular }}()
{
${{ $modelVarSingular }} = $this->{{ $modelVarPlural }}->first();
${{ $modelVarSingular }} = $this->{{ $modelVarPlural }}->random();

$response = $this->json(
method: 'GET',
Expand Down
61 changes: 33 additions & 28 deletions src/Commands/RESTPresenterSetupCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Symfony\Component\Console\Attribute\AsCommand;
use UnhandledMatchError;
Expand All @@ -28,9 +27,19 @@ public function __construct(protected Filesystem $filesystem)

public function handle(): int
{
if (! $this->firstTimeSetup()) {
$this->components->info('REST Presenter has already been setup. Now checking for updates...');
$this->checkForUpdates();

return self::SUCCESS;
}

$this->initialSetup();
$this->starGitHubRepo();
$this->sponsorThisProject();

if (! app()->runningUnitTests()) {
$this->starGitHubRepo();
$this->sponsorThisProject();
}

$this->components->info('REST Presenter setup completed successfully 🚀');

Expand All @@ -41,13 +50,7 @@ private function initialSetup(): void
{
$this->components->info('Welcome to REST Presenter setup wizard');

if (! $this->firstTimeSetup()) {
$this->components->info('REST Presenter has already been setup. Now checking for updates...');
$this->checkForUpdates();
}

$this->publishingConfig();
$this->publishingServiceProvider();
$this->publishingDefaultResources();
$this->publishStarterKits();
}
Expand Down Expand Up @@ -89,35 +92,37 @@ private function publishingConfig(): void
$this->call('vendor:publish', ['--tag' => 'rest-presenter-config']);
}

private function publishingServiceProvider(): void
{
$this->call('vendor:publish', ['--tag' => 'rest-presenter-provider']);

$providersPath = app()->bootstrapPath('providers.php');
if (! file_exists($providersPath)) {
return;
}

$callable = [ServiceProvider::class, 'addProviderToBootstrapFile'];
call_user_func($callable, 'App\\Providers\\RESTPresenterServiceProvider', $providersPath);
}

private function publishingDefaultResources(): void
{
collect($this->filesystem->directories(__DIR__.'/../Resources'))
->map(fn ($resource) => Str::singular(basename((string) $resource)))
->each(fn ($resource) => $this->call('rest-presenter:make-resource', [
'model' => 'App\\Models\\'.Str::singular($resource),
'name' => $resource,
'type' => 'new',
]));
->each(function ($resource) {
$resourceKey = Str::of($resource)
->kebab()
->value();

$presenters = [$resourceKey => 'xtend'];
if ($resourceKey === 'user') {
$presenters['profile'] = 'xtend';
}

return $this->call('rest-presenter:make-resource', [
'model' => 'App\\Models\\'.Str::singular($resource),
'presenters' => $presenters,
'name' => $resource,
'type' => 'new',
]);
});
}

private function publishStarterKits(): void
{
$starterKitsDirectory = __DIR__.'/../StarterKits';
$generatedKitsDirectory = config('rest-presenter.generator.path').'/StarterKits';
$this->filesystem->ensureDirectoryExists($generatedKitsDirectory);

if (! app()->runningUnitTests()) {
$this->filesystem->ensureDirectoryExists($generatedKitsDirectory);
}

/** @var \Illuminate\Support\Collection<string, string> $unpublishedStarterKits */
$unpublishedStarterKits = collect($this->filesystem->allFiles($starterKitsDirectory))
Expand Down
4 changes: 4 additions & 0 deletions src/Commands/XtendStarterKit.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ public function handle(): int
return self::FAILURE;
}

if (! app()->runningUnitTests()) {
$this->filesystem->ensureDirectoryExists($generatedKitsDirectory.'/'.$kitPath);
}

$this->generateStarterKit($starterKitsDirectory, $kitPath);

return self::SUCCESS;
Expand Down
6 changes: 6 additions & 0 deletions src/Resources/ResourceController.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,17 @@ abstract class ResourceController extends Controller
*/
public array $sorts;

public static bool $isAuthenticated = false;

public function __construct(Request $request, bool $init = true)
{
if ($init) {
$this->init($request);
}

if (static::$isAuthenticated) {
$this->middleware('auth:sanctum');
}
}

protected function init(Request $request): void
Expand Down
4 changes: 4 additions & 0 deletions src/Support/ApiCollection/Exporters/Insomnia/Requests.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@ protected function addItemToGroup(string $method, string $uri, string $group): v
],
'parameters' => [],
'headers' => [
[
'name' => 'Accept',
'value' => 'application/json',
],
[
'name' => config('rest-presenter.api.presenter_header'),
'value' => strtolower(Str::singular($group)),
Expand Down
5 changes: 5 additions & 0 deletions src/Support/ApiCollection/Exporters/Postman/Items.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,11 @@ protected function processRequest(string $method, Stringable $uri, ?string $grou
return collect([
'method' => strtoupper($method),
'header' => collect()
->push([
'key' => 'Accept',
'value' => 'application/json',
'type' => 'text',
])
->push($group !== null && $group !== '' && $group !== '0' ? [
'key' => config('rest-presenter.api.presenter_header'),
'value' => strtolower(Str::singular($group)),
Expand Down
16 changes: 0 additions & 16 deletions src/Support/Tests/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use Illuminate\Support\Str;
use InvalidArgumentException;
use Laravel\Sanctum\Sanctum;
use ReflectionClass;
use XtendPackages\RESTPresenter\Models\User;

if (! function_exists('authenticateApiUser')) {
Expand Down Expand Up @@ -59,21 +58,6 @@ function getApiHeaderPresenterName(): string
}
}

if (! function_exists('invokeNonPublicMethod')) {
/**
* Invoke a non-public method.
*
* @param array<mixed> $parameters
*/
function invokeNonPublicMethod(object $object, string $methodName, array $parameters = []): mixed
{
$reflection = new ReflectionClass($object);
$method = $reflection->getMethod($methodName);

return $method->invokeArgs($object, $parameters);
}
}

if (! function_exists('getValidationRule')) {
/**
* Get a validation rule.
Expand Down
17 changes: 17 additions & 0 deletions src/Support/XtendRouter.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

namespace XtendPackages\RESTPresenter\Support;

use Illuminate\Container\Container;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Routing\PendingResourceRegistration;
use Illuminate\Routing\Router;
use Illuminate\Routing\RouteRegistrar;
Expand All @@ -16,6 +19,20 @@ final class XtendRouter extends Router
{
use WithAutoDiscovery;

public function __construct(Dispatcher $events, ?Container $container = null)
{
parent::__construct($events, $container);

$filesystem = app(Filesystem::class);
if (! $filesystem->isDirectory(app_path('Api'))) {
return;
}
if (! app()->runningUnitTests()) {
return;
}
$filesystem->deleteDirectory(app_path('Api'));
}

public function register(): RouteRegistrar
{
$prefix = config('rest-presenter.api.prefix');
Expand Down
Loading

0 comments on commit 4ebd5b0

Please sign in to comment.