Skip to content

Commit

Permalink
Merge pull request #32 from dedoc/fix/issue-31
Browse files Browse the repository at this point in the history
Fix circular references in resources and improved `whenLoaded` support
  • Loading branch information
romalytvynenko authored Sep 23, 2022
2 parents 6d5e598 + 6efcf47 commit 811c9ba
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
5 changes: 5 additions & 0 deletions src/Support/Generator/Components.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,9 @@ public static function slug(string $name)
{
return Str::replace('\\', '.', $name);
}

public function removeSchema(string $schemaName): void
{
unset($this->schemas[$schemaName]);
}
}
12 changes: 12 additions & 0 deletions src/Support/Generator/TypeTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Dedoc\Scramble\Support\Generator\Types\NumberType;
use Dedoc\Scramble\Support\Generator\Types\ObjectType;
use Dedoc\Scramble\Support\Generator\Types\StringType;
use Dedoc\Scramble\Support\Generator\Types\UnknownType;
use Dedoc\Scramble\Support\Type\ArrayItemType_;
use Dedoc\Scramble\Support\Type\Type;
use Dedoc\Scramble\Support\Type\Union;
Expand Down Expand Up @@ -166,6 +167,10 @@ function ($acc, $extensionClass) use ($type) {
return $reference;
}

if ($reference) {
$this->components->addSchema($reference->fullName, Schema::fromType(new UnknownType('Reference is being analyzed.')));
}

if ($handledType = $extension->toSchema($type, $acc)) {
if ($reference) {
return $this->components->addSchema($reference->fullName, Schema::fromType($handledType));
Expand All @@ -174,6 +179,13 @@ function ($acc, $extensionClass) use ($type) {
return $handledType;
}

/*
* If we couldn't handle a type, the reference is removed.
*/
if ($reference) {
$this->components->removeSchema($reference->fullName);
}

return $acc;
}
);
Expand Down
5 changes: 3 additions & 2 deletions src/Support/InferExtensions/JsonResourceTypeInfer.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,12 @@ public function getType(Expr $node, Scope $scope): ?Type
}

/*
* new JsonResource($this->whenLoaded)
* new JsonResource($this->whenLoaded('?'))
* JsonResource::make($this->whenLoaded('?'))
* JsonResource::collection($this->whenLoaded('?'))
*/
if (
$node instanceof Node\Expr\ArrayItem
&& $node->value instanceof Node\Expr\New_
&& $scope->getType($node->value)->isInstanceOf(JsonResource::class)
&& $this->isMethodCallToThis(optional($node->value->args[0])->value, ['whenLoaded'])
) {
Expand Down

0 comments on commit 811c9ba

Please sign in to comment.