Skip to content

Instantly share code, notes, and snippets.

@SolveSoul
Created September 8, 2023 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SolveSoul/f9db8b9370d96c1aa4273b2280cb9b89 to your computer and use it in GitHub Desktop.
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
[...]
/*
|--------------------------------------------------------------------------
| 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,
],
[...]
<?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