Created
September 8, 2023 08:24
-
-
Save SolveSoul/f9db8b9370d96c1aa4273b2280cb9b89 to your computer and use it in GitHub Desktop.
A hook to use the barryvdh/laravel-ide-helper in combination with the spatie/laravel-translatable package
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[...] | |
/* | |
|-------------------------------------------------------------------------- | |
| Models hooks | |
|-------------------------------------------------------------------------- | |
| | |
| Define which hook classes you want to run for models to add custom information | |
| | |
| Hooks should implement Barryvdh\LaravelIdeHelper\Contracts\ModelHookInterface. | |
| | |
*/ | |
'model_hooks' => [ | |
App\Support\TranslatableModelIdeHelperHook::class, | |
], | |
[...] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Support; | |
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand; | |
use Barryvdh\LaravelIdeHelper\Contracts\ModelHookInterface; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Support\Arr; | |
use ReflectionClass; | |
use Spatie\Translatable\HasTranslations; | |
/** | |
* This hook helps to fix typings for translatable attributes on models. | |
* | |
* For more information, see this thread: https://github.com/spatie/laravel-translatable/discussions/365 | |
*/ | |
class TranslatableModelIdeHelperHook implements ModelHookInterface | |
{ | |
public function run(ModelsCommand $command, Model $model): void | |
{ | |
if (!in_array(HasTranslations::class, class_uses_recursive($model))) { | |
return; | |
} | |
// @phpstan-ignore-next-line | |
foreach ($model->getTranslatableAttributes() as $attribute) { | |
$types = ['array', 'string']; | |
$nullableColumns = $this->getNullableColumns($command); | |
if (Arr::get($nullableColumns, $attribute, false)) { | |
$types[] = 'null'; | |
} | |
$command->setProperty($attribute, implode('|', $types)); | |
} | |
} | |
protected function getNullableColumns(ModelsCommand $command): array | |
{ | |
return $this->getProtectedProperty($command, 'nullableColumns'); | |
} | |
protected function getProtectedProperty(object|string $obj, string $prop): mixed | |
{ | |
$reflection = new ReflectionClass($obj); | |
$property = $reflection->getProperty($prop); | |
return $property->getValue($obj); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @SolveSoul Thanks for this 🙌
PHPStan complains about the param type for
getProtectedProperty()
. Seems instead it should be...