Skip to content

Commit

Permalink
Adds unique_site rule
Browse files Browse the repository at this point in the history
  • Loading branch information
daftspunk committed Dec 2, 2024
1 parent 6ab8956 commit da037ee
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Validation/ValidationServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ protected function registerValidationFactory()
$validator->setPresenceVerifier($app['validation.presence']);
}

// Replacers for custom rules in Validator class
$validator->replacer('unique_site', function ($message, $attribute, $rule, $parameters) {
return __('validation.unique', ['attribute' => $attribute]);
});

return $validator;
});
}
Expand Down
46 changes: 46 additions & 0 deletions src/Validation/Validator.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php namespace October\Rain\Validation;

use Site;
use Illuminate\Validation\Rules\Unique;
use Illuminate\Validation\Validator as ValidatorBase;
use October\Rain\Exception\ValidationException;

Expand All @@ -16,4 +18,48 @@ class Validator extends ValidatorBase
* @var string exception to throw upon failure.
*/
protected $exception = ValidationException::class;

/**
* validateUniqueSite validates the uniqueness of an attribute value on a given database table,
* including a site ID condition check.
*/
public function validateUniqueSite($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'unique_site');

[$connection, $table, $idColumn] = $this->parseTable($parameters[0]);

// The second parameter position holds the name of the column that needs to
// be verified as unique. If this parameter isn't specified we will just
// assume that this column to be verified shares the attribute's name.
$column = $this->getQueryColumn($parameters, $attribute);

$id = null;

if (isset($parameters[2])) {
[$idColumn, $id] = $this->getUniqueIds($idColumn, $parameters);

if (!is_null($id)) {
$id = stripslashes($id);
}
}

// The presence verifier is responsible for counting rows within this store
// mechanism which might be a relational database or any other permanent
// data store like Redis, etc. We will use it to determine uniqueness.
$verifier = $this->getPresenceVerifier($connection);

$extra = $this->getUniqueExtra($parameters);

if ($this->currentRule instanceof Unique) {
$extra = array_merge($extra, $this->currentRule->queryCallbacks());
}

// Add the site extra
$extra['site_id'] = Site::getSiteIdFromContext();

return $verifier->getCount(
$table, $column, $value, $id, $idColumn, $extra
) == 0;
}
}

0 comments on commit da037ee

Please sign in to comment.