mirror of
https://github.com/archtechx/airwire.git
synced 2025-12-12 10:44:03 +00:00
initial
This commit is contained in:
commit
d26fa93f1e
35 changed files with 2388 additions and 0 deletions
56
src/AirwireServiceProvider.php
Normal file
56
src/AirwireServiceProvider.php
Normal 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(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue