Add tests for the StoresMeta Trait and fix the Functional MetaSeo tests
This commit is contained in:
@@ -18,38 +18,64 @@ trait StoresMeta
|
||||
/**
|
||||
* Stores all Meta values of a model.
|
||||
*
|
||||
* @param $meta
|
||||
* @param $type
|
||||
* @param $id
|
||||
*
|
||||
* @throws \Exception
|
||||
* @param array $metaData
|
||||
* @param string $metaType
|
||||
* @param string|int $metaId
|
||||
* @param string $metaModel
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function storeMeta($meta, $type, $id)
|
||||
public function storeMeta($metaData, $metaType, $metaId, $metaModel = Meta::class)
|
||||
{
|
||||
// Validation required instead of type hinting because it could be passed as false or NULL
|
||||
if (!is_array($meta)) {
|
||||
if (!is_array($metaData)) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($meta as $key => $value) {
|
||||
$meta = Meta::firstOrNew([
|
||||
'key' => $key,
|
||||
'meta_type' => $type,
|
||||
'meta_id' => $id,
|
||||
]);
|
||||
foreach ($metaData as $key => $value) {
|
||||
$modelInstance = call_user_func(
|
||||
[$metaModel, 'firstOrNew'],
|
||||
[
|
||||
'key' => $key,
|
||||
'meta_type' => $metaType,
|
||||
'meta_id' => $metaId,
|
||||
]
|
||||
);
|
||||
|
||||
$value = $this->removeEmptyValues($value);
|
||||
if (!empty($value)) {
|
||||
$meta->value = $value;
|
||||
$meta->save();
|
||||
$modelInstance->setAttribute('value', $value);
|
||||
$modelInstance->save();
|
||||
continue;
|
||||
}
|
||||
|
||||
// The value is empty, remove the row
|
||||
if ($meta->exists) {
|
||||
$meta->delete();
|
||||
if ($modelInstance->exists) {
|
||||
$modelInstance->delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a Value is empty.
|
||||
*
|
||||
* @param $values
|
||||
*
|
||||
* @return array|mixed
|
||||
*/
|
||||
protected function removeEmptyValues($values)
|
||||
{
|
||||
if (!is_array($values)) {
|
||||
return empty($values) ? null : $values;
|
||||
}
|
||||
|
||||
foreach ($values as $key => $value) {
|
||||
if (!empty($value)) {
|
||||
continue;
|
||||
}
|
||||
unset($values[$key]);
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user