8000 Get default attributes for schemas and hydrators from model filleable… · volldigital/laravel-json-api@6b71b84 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6b71b84

Browse files
Get default attributes for schemas and hydrators from model filleable attribute
1 parent 8e89370 commit 6b71b84

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

src/Hydrator/EloquentHydrator.php

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,32 @@ public function __construct(HttpServiceInterface $service)
115115
{
116116
$this->service = $service;
117117
}
118+
119+
/**
120+
* @param StandardObjectInterface $attributes
121+
* @param $record
122+
* @return void
123+
*/
124+
protected function defaultHydrateAttributes(StandardObjectInterface $attributes, $record)
125+
{
126+
$hydratorAttributes = $this->attributes;
127+
if(empty($hydratorAttributes))
128+
{
129+
$hydratorAttributes = [];
130+
foreach($record->getFillable() as $attribute)
131+
{
132+
if(strpos($attribute, '_') !== false)
133+
{
134+
$hydratorAttributes[str_replace('_', '-', $attribute)] = $attribute;
135+
}
136+
else
137+
{
138+
$hydratorAttributes[] = $attribute;
139+
}
140+
}
141+
}
142+
return $hydratorAttributes;
143+
}
118144

119145
/**
120146
* @inheritDoc
@@ -127,7 +153,7 @@ protected function hydrateAttributes(StandardObjectInterface $attributes, $recor
127153

128154
$data = [];
129155

130-
foreach ($this->attributes as $resourceKey => $modelKey) {
156+
foreach ($this->defaultHydrateAttributes($attributes, $record) as $resourceKey => $modelKey) {
131157
if (is_numeric($resourceKey)) {
132158
$resourceKey = $modelKey;
133159
$modelKey = $this->keyForAttribute($modelKey, $record);

src/Schema/EloquentSchema.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,23 @@ protected function getDefaultAttributes(Model $model)
154154
return $defaults;
155155
}
156156

157+
/**
158+
* Get attributes for the provided model using fillable attribute.
159+
*
160+
* @param Model $model
161+
* @return array
162+
*/
163+
protected function getDefaultModelAttributes(Model $model)
164+
{
165+
$schemaAttributes = $this->attributes;
166+
if(empty($schemaAttributes))
167+
{
168+
$schemaAttributes = $model->getFillable();
169+
}
170+
return $schemaAttributes;
171+
}
172+
173+
157174
/**
158175
* Get attributes for the provided model.
159176
*
@@ -164,7 +181,7 @@ protected function getModelAttributes(Model $model)
164181
{
165182
$attributes = [];
166183

167-
foreach ($this->attributes as $modelKey => $attributeKey) {
184+
foreach ($this->getDefaultModelAttributes($model) as $modelKey => $attributeKey) {
168185
if (is_numeric($modelKey)) {
169186
$modelKey = $attributeKey;
170187
$attributeKey = $this->keyForAttribute($attributeKey);

0 commit comments

Comments
 (0)
0