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 mutators #13

Merged
merged 5 commits into from
Sep 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
61 changes: 42 additions & 19 deletions src/Attributes/AttributeFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -181,47 +181,70 @@ protected function getVirtualAttributes(Model $model, array $columns): Collectio
$class = new ReflectionClass($model);

return collect($class->getMethods())
->reject(fn (ReflectionMethod $method) => $method->isStatic()
|| $method->isAbstract()
|| $method->getDeclaringClass()->getName() !== get_class($model)
->reject(
fn (ReflectionMethod $method) => $method->isStatic()
|| $method->isAbstract()
|| $method->getDeclaringClass()->getName() !== get_class($model)
)
->mapWithKeys(function (ReflectionMethod $method) use ($model) {
->map(function (ReflectionMethod $method) use ($model) {
if (preg_match('/^get(.*)Attribute$/', $method->getName(), $matches) === 1) {
return [
Str::snake($matches[1]) => [
'cast_type' => 'accessor',
'php_type' => $method->getReturnType()?->getName(),
],
'name' => Str::snake($matches[1]),
'cast_type' => 'accessor',
'php_type' => $method->getReturnType()?->getName(),
];
}

if (preg_match('/^set(.*)Attribute$/', $method->getName(), $matches) === 1) {
return [
'name' => Str::snake($matches[1]),
'cast_type' => 'mutator',
'php_type' => collect($method->getParameters())->firstWhere('name', 'value')?->getType()?->__toString(),
];
}

if ($model->hasAttributeMutator($method->getName())) {
return [
Str::snake($method->getName()) => [
'cast_type' => 'attribute',
'php_type' => null,
],
'name' => Str::snake($method->getName()),
'cast_type' => 'attribute',
'php_type' => null,
];
}

return [];
})
->reject(fn ($cast, $name) => collect($columns)->has($name))
->map(fn ($cast, $name) => new Attribute(
name: $name,
->reject(fn ($cast) => ! isset($cast['name']) || collect($columns)->has($cast['name']))
->map(fn ($cast) => new Attribute(
name: $cast['name'],
phpType: $cast['php_type'] ?? null,
type: null,
increments: false,
nullable: null,
default: null,
primary: null,
unique: null,
fillable: $model->isFillable($name),
appended: $model->hasAppended($name),
fillable: $model->isFillable($cast['name']),
appended: $model->hasAppended($cast['name']),
cast: $cast['cast_type'],
virtual: true,
hidden: $this->attributeIsHidden($name, $model)
hidden: $this->attributeIsHidden($cast['name'], $model)
))
->values();
// Convert duplicate entries for accessor-mutator combinations
->groupBy('name')
->flatMap(function (Collection $items) {
if ($items->count() !== 2) {
return $items;
}

if (! $items->firstWhere('cast', 'accessor') || ! $items->firstWhere('cast', 'mutator')) {
return $items;
}

$attribute = $items->first();
$attribute->phpType = $items[0]->phpType ?? $items[1]->phpType;
$attribute->cast = 'attribute';

return [$attribute];
});
}
}
64 changes: 59 additions & 5 deletions tests/AttributeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,74 @@
it('can get the attributes of a model', function () {
$attributes = AttributeFinder::forModel(new TestModel());

expect($attributes)->toHaveCount(7);
expect($attributes)->toHaveCount(11);

matchesAttributesSnapshot($attributes);
});

it('can get virtual attribute php types of a model', function () {
/**
* @see https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor
*/
it('can get the accessor attributes of a model', function () {
$attributes = AttributeFinder::forModel(new TestModel());

$titleUppercaseAttr = $attributes->first(fn ($attr) => $attr->name === 'title_uppercase');
$titleWithoutReturnTypeAttr = $attributes->first(fn ($attr) => $attr->name === 'title_without_return_type');

$this->assertNotNull($titleUppercaseAttr);
$this->assertEquals('string', $titleUppercaseAttr->phpType);
$this->assertEquals(null, $titleWithoutReturnTypeAttr->phpType);
expect($titleUppercaseAttr)
->cast->toBe('accessor')
->not()->toBeNull()
->phpType->toBe('string');
expect($titleWithoutReturnTypeAttr)
->cast->toBe('accessor')
->not()->toBeNull()
->phpType->toBeNull();
});

/**
* @see https://laravel.com/docs/8.x/eloquent-mutators#defining-a-mutator
*/
it('can get the mutator attributes of a model', function () {
$attributes = AttributeFinder::forModel(new TestModel());

$passwordMutatorAttr = $attributes->first(fn ($attr) => $attr->name === 'encrypted_password');
$passwordMutatorWithoutTypeHintAttr = $attributes->first(fn ($attr) => $attr->name === 'trimmed_and_encrypted_password');

expect($passwordMutatorAttr)
->cast->toBe('mutator')
->not()->toBeNull()
->phpType->toBe('string');
expect($passwordMutatorWithoutTypeHintAttr)
->cast->toBe('mutator')
->not()->toBeNull()
->phpType->toBeNull();
});

it('can handle accessor-mutator combinations', function () {
$attributes = AttributeFinder::forModel(new TestModel());

$dottedNameAttr = $attributes->first(fn ($attr) => $attr->name === 'dotted_name');

expect($dottedNameAttr)
->cast->toBe('attribute')
->not()->toBeNull()
->phpType->toBe('string');
expect($attributes->where('name', 'dotted_name')->count())
->toBe(1);
});

/**
* @see https://laravel.com/docs/9.x/eloquent-mutators#accessors-and-mutators
*/
it('can handle virtual attributes of a model', function () {
$attributes = AttributeFinder::forModel(new TestModel());

$titleLowercaseAttr = $attributes->first(fn ($attr) => $attr->name === 'title_lowercase');

expect($titleLowercaseAttr)
->cast->toBe('attribute')
->not()->toBeNull()
->phpType->toBeNull();
});

it('can get extended column types for a model', function () {
Expand Down
28 changes: 28 additions & 0 deletions tests/TestSupport/Models/TestModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Spatie\ModelInfo\Tests\TestSupport\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

class TestModel extends Model
Expand All @@ -19,4 +20,31 @@ public function getTitleWithoutReturnTypeAttribute()
{
return $this->title;
}

public function setEncryptedPasswordAttribute(string $value)
{
$this->password = bcrypt($value);
}

public function setTrimmedAndEncryptedPasswordAttribute($value)
{
$this->password = bcrypt(trim($value));
}

public function titleLowercase(): Attribute
{
return Attribute::make(
get: fn ($value) => strtolower($value)
);
}

public function getDottedNameAttribute(): string
{
return str_replace(' ', '.', $this->name);
}

public function setDottedNameAttribute(string $value)
{
$this->name = str_replace('.', ' ', $value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,59 @@
cast: accessor
virtual: true
hidden: false
-
name: encrypted_password
phpType: string
type: null
increments: false
nullable: null
default: null
primary: null
unique: null
fillable: false
appended: false
cast: mutator
virtual: true
hidden: false
-
name: trimmed_and_encrypted_password
phpType: null
type: null
increments: false
nullable: null
default: null
primary: null
unique: null
fillable: false
appended: false
cast: mutator
virtual: true
hidden: false
-
name: title_lowercase
phpType: null
type: null
increments: false
nullable: null
default: null
primary: null
unique: null
fillable: false
appended: false
cast: attribute
virtual: true
hidden: false
-
name: dotted_name
phpType: string
type: null
increments: false
nullable: null
default: null
primary: null
unique: null
fillable: false
appended: false
cast: attribute
virtual: true
hidden: false