Skip to content

Commit

Permalink
Fixed snipe#8252 - circular references in location parents
Browse files Browse the repository at this point in the history
  • Loading branch information
travismiller committed Jul 22, 2020
1 parent af06e42 commit 4d7a42b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
3 changes: 2 additions & 1 deletion app/Models/Location.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ class Location extends SnipeModel
'address' => 'max:80|nullable',
'address2' => 'max:80|nullable',
'zip' => 'min:3|max:10|nullable',
'manager_id' => 'exists:users,id|nullable'
'manager_id' => 'exists:users,id|nullable',
'parent_id' => 'non_circular:locations,id'
);

/**
Expand Down
38 changes: 38 additions & 0 deletions app/Providers/ValidationServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,44 @@ public function boot()
});


// Prevent circular references
//
// Example usage in Location model where parent_id references another Location:
//
// protected $rules = array(
// 'parent_id' => 'non_circular:locations,id'
// );
//
Validator::extend('non_circular', function ($attribute, $value, $parameters, $validator) {
if (count($parameters) < 2) {
throw new \Exception('Required validator parameters: <table>:<primary key>');
}

// Parameters from the rule implementation ($pk will likely be 'id')
list($table, $pk) = $parameters;

// Data from the edited model
$data = $validator->getData();

// The primary key value from the edited model
$data_pk = array_get($data, $pk);
$value_pk = $value;

// If we’re editing an existing model and there is a parent value set…
while ($data_pk && $value_pk) {
// It’s not valid for any parent id to be equel to the existing model’s id
if ($data_pk == $value_pk) {
return false;
}

// Traverse up the parents to get the next parent id
$value_pk = DB::table($table)->select($attribute)->where($pk, '=', $value_pk)->value($attribute);
}

return true;
});


// Yo dawg. I heard you like validators.
// This validates the custom validator regex in custom fields.
// We're just checking that the regex won't throw an exception, not
Expand Down

0 comments on commit 4d7a42b

Please sign in to comment.