1
0
Fork 0
mirror of https://github.com/archtechx/airwire.git synced 2025-12-12 10:44:03 +00:00
This commit is contained in:
Samuel Štancl 2021-05-20 20:15:55 +02:00
commit d26fa93f1e
35 changed files with 2388 additions and 0 deletions

View file

@ -0,0 +1,56 @@
<?php
namespace Airwire;
use Airwire\Commands\GenerateDefinitions;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\LazyCollection;
use Illuminate\Support\ServiceProvider;
class AirwireServiceProvider extends ServiceProvider
{
public function boot()
{
$this->commands([GenerateDefinitions::class]);
$this->loadDefaultTransformers();
$this->loadRoutesFrom(__DIR__ . '/../routes/airwire.php');
}
public function loadDefaultTransformers(): void
{
Airwire::typeTransformer(
Model::class,
decode: function (mixed $data, string $model) {
$keyName = $model::make()->getKeyName();
if (is_array($data)) {
if (isset($data[$keyName])) {
if ($instance = $model::find($data[$keyName])) {
return $instance;
}
}
return new $model($data);
} else {
return $model::find($data);
}
},
encode: fn (Model $model) => $model->toArray()
);
Airwire::typeTransformer(
Collection::class,
decode: fn (array $data, string $class) => new $class($data),
encode: fn (Collection $collection) => $collection->toArray(),
);
Airwire::typeTransformer(
LazyCollection::class,
decode: fn (array $data, string $class) => new $class($data),
encode: fn (LazyCollection $collection) => $collection->toArray(),
);
}
}