Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detect data from collection #812

Merged
merged 17 commits into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from 10 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
23 changes: 23 additions & 0 deletions docs/as-a-data-transfer-object/nesting.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,29 @@ class AlbumData extends Data
}
```

If the collection is well-annotated, the `Data` class doesn't need to use annotations:

```php
/**
* @template TKey of array-key
* @template TData of \App\Data\SongData
*
* @extends \Illuminate\Support\Collection<TKey, TData>
*/
class SongDataCollection extends Collection
{
}

class AlbumData extends Data
{
public function __construct(
public string $title,
public SongDataCollection $songs,
) {
}
}
```

You can also use an attribute to define the type of data objects that will be stored within a collection:

```php
Expand Down
13 changes: 13 additions & 0 deletions src/Support/Annotations/CollectionAnnotation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Spatie\LaravelData\Support\Annotations;

class CollectionAnnotation
{
public function __construct(
public string $type,
public bool $isData,
public string $keyType = 'array-key',
) {
}
}
143 changes: 143 additions & 0 deletions src/Support/Annotations/CollectionAnnotationReader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
<?php

namespace Spatie\LaravelData\Support\Annotations;

use Iterator;
use IteratorAggregate;
use phpDocumentor\Reflection\DocBlock\Tags\Generic;
use phpDocumentor\Reflection\DocBlockFactory;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\Context;
use phpDocumentor\Reflection\Types\ContextFactory;
use ReflectionClass;
use Spatie\LaravelData\Data;

class CollectionAnnotationReader
{
public function __construct(
protected readonly TypeResolver $typeResolver,
protected readonly ContextFactory $contextFactory,
) {
}

protected Context $context;
clementbirkle marked this conversation as resolved.
Show resolved Hide resolved

public function getForClass(ReflectionClass $class): ?CollectionAnnotation
{
if (! $this->isCollection($class)) {
return null;
}

$type = $this->getCollectionReturnType($class);

if ($type === null || $type['valueType'] === null) {
return null;
}

$isData = false;

if (is_subclass_of($type['valueType'], Data::class)) {
$isData = true;
}

return new CollectionAnnotation(
type: $type['valueType'],
isData: $isData,
keyType: $type['keyType'] ?? 'array-key',
);
}

/**
* @return array{keyType: string|null, valueType: string|null}|null
*/
protected function getCollectionReturnType(ReflectionClass $class): ?array
{
// Initialize TypeResolver and DocBlockFactory
$docBlockFactory = DocBlockFactory::createInstance();

// Extract the namespace and uses from the file content
$namespace = $class->getNamespaceName();
$fileContent = file_get_contents($class->getFileName());
$this->context = $this->contextFactory->createForNamespace($namespace, $fileContent);

// Get the PHPDoc comment of the class
$docComment = $class->getDocComment();
if ($docComment === false) {
return null;
}

// Create the DocBlock instance
$docBlock = $docBlockFactory->create($docComment, $this->context);

// Initialize variables
$templateTypes = [];
$keyType = null;
$valueType = null;

foreach ($docBlock->getTags() as $tag) {

if (! $tag instanceof Generic) {
continue;
}

if ($tag->getName() === 'template') {
$description = $tag->getDescription();

if (preg_match('/^(\w+)\s+of\s+([^\s]+)/', $description, $matches)) {
$templateTypes[$matches[1]] = $this->resolve($matches[2]);
}

continue;
}

if ($tag->getName() === 'extends') {
$description = $tag->getDescription();

if (preg_match('/<\s*([^,\s]+)?\s*(?:,\s*([^>\s]+))?\s*>/', $description, $matches)) {

if (count($matches) === 3) {
$keyType = $templateTypes[$matches[1]] ?? $this->resolve($matches[1]);
$valueType = $templateTypes[$matches[2]] ?? $this->resolve($matches[2]);
} else {
$keyType = null;
$valueType = $templateTypes[$matches[1]] ?? $this->resolve($matches[1]);
}

$keyType = $keyType ? explode('|', $keyType)[0] : null;
$valueType = explode('|', $valueType)[0];

return [
'keyType' => $keyType,
'valueType' => $valueType,
];
}
}
}

return null;
}

protected function isCollection(ReflectionClass $class): bool
{
// Check if the class implements common collection interfaces
$collectionInterfaces = [
Iterator::class,
IteratorAggregate::class,
];

foreach ($collectionInterfaces as $interface) {
if ($class->implementsInterface($interface)) {
return true;
}
}

return false;
}

protected function resolve(string $type): ?string
{
$type = (string) $this->typeResolver->resolve($type, $this->context);

return $type ? ltrim($type, '\\') : null;
}
}
13 changes: 13 additions & 0 deletions src/Support/Factories/DataTypeFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Spatie\LaravelData\Exceptions\CannotFindDataClass;
use Spatie\LaravelData\Lazy;
use Spatie\LaravelData\Optional;
use Spatie\LaravelData\Support\Annotations\CollectionAnnotationReader;
use Spatie\LaravelData\Support\Annotations\DataIterableAnnotation;
use Spatie\LaravelData\Support\Annotations\DataIterableAnnotationReader;
use Spatie\LaravelData\Support\DataPropertyType;
Expand All @@ -36,6 +37,7 @@ class DataTypeFactory
{
public function __construct(
protected DataIterableAnnotationReader $iterableAnnotationReader,
protected CollectionAnnotationReader $collectionAnnotationReader,
) {
}

Expand Down Expand Up @@ -354,6 +356,17 @@ protected function inferPropertiesForNamedType(
$iterableKeyType = $annotation->keyType;
}

if (
clementbirkle marked this conversation as resolved.
Show resolved Hide resolved
$iterableItemType === null
&& $typeable instanceof ReflectionProperty
&& class_exists($name)
&& $annotation = $this->collectionAnnotationReader->getForClass(new ReflectionClass($name))
) {
$isData = $annotation->isData;
$iterableItemType = $annotation->type;
$iterableKeyType = $annotation->keyType;
}

$kind = $isData
? $kind->getDataRelatedEquivalent()
: $kind;
Expand Down
15 changes: 15 additions & 0 deletions tests/Fakes/Collections/SimpleDataCollectionWithAnotations.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Spatie\LaravelData\Tests\Fakes\Collections;

use Illuminate\Support\Collection;

/**
* @template TKey of array-key
* @template TData of \Spatie\LaravelData\Tests\Fakes\SimpleData
*
* @extends \Illuminate\Support\Collection<TKey, TData>
*/
class SimpleDataCollectionWithAnotations extends Collection
{
}
Loading
Loading