Skip to content

Commit

Permalink
doctrine fix
Browse files Browse the repository at this point in the history
  • Loading branch information
romalytvynenko committed Mar 9, 2024
1 parent e64dc27 commit 5236f13
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/Support/ResponseExtractor/ModelInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Dedoc\Scramble\Infer\Definition\ClassPropertyDefinition;
use Dedoc\Scramble\Support\ResponseExtractor\ModelInfoProviders\DoctrineProvider;
use Dedoc\Scramble\Support\ResponseExtractor\ModelInfoProviders\ModelInfoProvider;
use Dedoc\Scramble\Support\ResponseExtractor\ModelInfoProviders\NativeProvider;
use Dedoc\Scramble\Support\Type\ArrayType;
use Dedoc\Scramble\Support\Type\BooleanType;
use Dedoc\Scramble\Support\Type\FloatType;
Expand Down Expand Up @@ -178,7 +179,7 @@ private function makeDriver($model): ModelInfoProvider
$schema = $model->getConnection()->getSchemaBuilder();

if (method_exists($schema, 'getColumns')) {
// @todo
return new NativeProvider();
}

return new DoctrineProvider();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,53 @@

namespace Dedoc\Scramble\Support\ResponseExtractor\ModelInfoProviders;

class NativeProvider
use Illuminate\Database\Eloquent\Model;
use UnitEnum;
use BackedEnum;

/**
* All the code here was written by the great Laravel team and community. Cudos to them.
*/
class NativeProvider implements ModelInfoProvider
{
public function getAttributes(Model $model): array
{
$connection = $model->getConnection();
$schema = $connection->getSchemaBuilder();
$table = $model->getTable();
$columns = $schema->getColumns($table);
$indexes = $schema->getIndexes($table);

return collect($columns)
->values()
->map(fn ($column) => [
'name' => $column['name'],
'type' => $column['type'],
'increments' => $column['auto_increment'],
'nullable' => $column['nullable'],
'default' => $this->getColumnDefault($column, $model),
'unique' => $this->columnIsUnique($column['name'], $indexes),
'fillable' => $model->isFillable($column['name']),
'appended' => null,
])
->toArray();
}

private function getColumnDefault($column, Model $model)
{
$attributeDefault = $model->getAttributes()[$column['name']] ?? null;

return match (true) {
$attributeDefault instanceof BackedEnum => $attributeDefault->value,
$attributeDefault instanceof UnitEnum => $attributeDefault->name,
default => $attributeDefault ?? $column['default'],
};
}

private function columnIsUnique($column, array $indexes)
{
return collect($indexes)->contains(
fn ($index) => count($index['columns']) === 1 && $index['columns'][0] === $column && $index['unique']
);
}
}

0 comments on commit 5236f13

Please sign in to comment.