Skip to content

Commit

Permalink
perf(memoization): add memoization for build referencable schemas (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
jpedryc authored Dec 9, 2024
1 parent 394a324 commit 7657892
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Concerns/Referencable.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

trait Referencable
{
static $buildReferencableSchemas = [];

public static function ref(?string $objectId = null): Schema
{
$instance = app(static::class);
Expand All @@ -38,6 +40,6 @@ public static function ref(?string $objectId = null): Schema
$baseRef = '#/components/securitySchemes/';
}

return Schema::ref($baseRef.$instance->build()->objectId, $objectId);
return self::$buildReferencableSchemas[static::class . "_{$objectId}"] ??= Schema::ref($baseRef.$instance->build()->objectId, $objectId);
}
}
21 changes: 21 additions & 0 deletions tests/Fixtures/ExampleSchema.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Vyuldashev\LaravelOpenApi\Tests\Fixtures;

use GoldSpecDigital\ObjectOrientedOAS\Contracts\SchemaContract;
use GoldSpecDigital\ObjectOrientedOAS\Objects\Schema;
use Vyuldashev\LaravelOpenApi\Contracts\Reusable;
use Vyuldashev\LaravelOpenApi\Factories\SchemaFactory;

class ExampleSchema extends SchemaFactory implements Reusable
{
public function build(): SchemaContract
{
return Schema::object('ExampleSchema')
->properties(
Schema::string('example_string'),
Schema::integer('example_integer'),
Schema::boolean('example_boolean'),
);
}
}
14 changes: 14 additions & 0 deletions tests/MemoizationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Vyuldashev\LaravelOpenApi\Tests;

use Vyuldashev\LaravelOpenApi\Tests\Fixtures\ExampleSchema;

class MemoizationTest extends TestCase
{
public function testReferencableInstanceBuildOnce(): void
{
self::assertEquals($e1ObjectId = (new ExampleSchema)::ref('e1'), (new ExampleSchema)::ref('e1'));
self::assertNotEquals($e1ObjectId, (new ExampleSchema)::ref('e2'));
}
}

0 comments on commit 7657892

Please sign in to comment.