Skip to content

Commit

Permalink
Fix location_options issue when creating a location #981
Browse files Browse the repository at this point in the history
Signed-off-by: Sam Poyigi <6567634+sampoyigi@users.noreply.github.com>
  • Loading branch information
sampoyigi committed Jun 1, 2022
1 parent e8d8717 commit ccbba69
Showing 1 changed file with 37 additions and 16 deletions.
53 changes: 37 additions & 16 deletions app/admin/models/LocationOption.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,16 @@ class LocationOption extends Model
*/
public $locationContext;

protected $itemsToSaveCache = [];

protected static $cache = [];

public static function onLocation($location = null)
{
$self = new static;
$self->locationContext = $location ?: $self->resolveLocation();
$instance = new static;
$instance->locationContext = $location ?: $instance->resolveLocation();

return $self;
return $instance;
}

public static function findRecord($key, $location = null)
Expand Down Expand Up @@ -76,26 +78,22 @@ public function getAll()

public function setAll($items)
{
if (!$location = $this->locationContext)
if (!$this->locationContext)
return false;

if (!is_array($items))
$items = [];

$records = $this->getAll();
$this->itemsToSaveCache = array_merge($this->itemsToSaveCache, $items);

collect($items)
->filter(function ($value, $key) use ($records) {
return $value != array_get($records, $key);
})
->map(function ($value, $key) use ($location) {
self::updateOrCreate([
'location_id' => $location->location_id,
'item' => $key,
], ['value' => $value]);
if ($this->locationContext->exists) {
$this->updateOptions();
}
elseif ($this->itemsToSaveCache) {
$this->locationContext->bindEventOnce('model.afterSave', function () {
$this->updateOptions();
});

static::$cache[$location->location_id] = $items;
}

return true;
}
Expand Down Expand Up @@ -173,4 +171,27 @@ protected function wrapFieldName($name)

return 'options'.$wrappedName;
}

protected function updateOptions()
{
if (!$location = $this->locationContext)
return false;

$records = $this->getAll();

collect($this->itemsToSaveCache)
->filter(function ($value, $key) use ($records) {
return $value != array_get($records, $key);
})
->each(function ($value, $key) use ($location) {
self::updateOrCreate([
'location_id' => $location->location_id,
'item' => $key,
], ['value' => $value]);
});

static::$cache[$location->location_id] = null;

return true;
}
}

0 comments on commit ccbba69

Please sign in to comment.