Skip to content

Commit

Permalink
Fix model observer registering multiple times (#12323)
Browse files Browse the repository at this point in the history
* Fix model observer registering multiple times

* remove unused import
  • Loading branch information
murrant committed Nov 19, 2020
1 parent 1652d17 commit 8ee9d0c
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 8 deletions.
4 changes: 1 addition & 3 deletions LibreNMS/Modules/Nac.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,7 @@ public function poll(OS $os)
{
if ($os instanceof NacPolling) {
// discovery output (but don't install it twice (testing can can do this)
if (! PortsNac::getEventDispatcher()->hasListeners('eloquent.created: App\Models\PortsNac')) {
PortsNac::observe(new ModuleModelObserver());
}
ModuleModelObserver::observe(PortsNac::class);

$nac_entries = $os->pollNac()->keyBy('mac_address');
$existing_entries = $os->getDevice()->portsNac->keyBy('mac_address');
Expand Down
11 changes: 6 additions & 5 deletions LibreNMS/Util/ModuleModelObserver.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,22 @@
namespace LibreNMS\Util;

use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Support\Str;

class ModuleModelObserver
{
/**
* Install observers to output +, -, U for models being created, deleted, and updated
*
* @param string $model The model name including namespace
* @param string|\Illuminate\Database\Eloquent\Model $model The model name including namespace
*/
public static function observe($model)
{
$model = Str::start($model, '\\');
// discovery output (but don't install it twice (testing can can do this)
if (! $model::getEventDispatcher()->hasListeners('eloquent.created: ' . ltrim('\\', $model))) {
static $observed_models = []; // keep track of observed models so we don't duplicate output
$class = ltrim($model, '\\');

if (! in_array($class, $observed_models)) {
$model::observe(new ModuleModelObserver());
$observed_models[] = $class;
}
}

Expand Down

0 comments on commit 8ee9d0c

Please sign in to comment.