Archived
1
0
Fork 0

app/library/Mvc/Model/Behavior/RandomId.php; minor stuff.

This commit is contained in:
Henrik Hautakoski 2018-06-11 08:45:05 +02:00
parent df261d968e
commit 0e3fb9a6e8

View file

@ -2,9 +2,9 @@
namespace Httpcb\Mvc\Model\Behavior;
use \Phalcon\Mvc\Model\Behavior;
use \Phalcon\Mvc\Model\BehaviorInterface;
use \Phalcon\Exception;
use Phalcon\Mvc\Model\Behavior,
Phalcon\Mvc\Model\BehaviorInterface,
Phalcon\Mvc\Model\Exception;
/**
* Generates a unique base64 url-safe id for the field specified.
@ -14,11 +14,16 @@ use \Phalcon\Exception;
*/
class RandomId extends Behavior implements BehaviorInterface
{
/**
* Constructor.
*
* @param array|null $options
* @throws Exception
*/
public function __construct($options = null)
{
$field = null;
if (isset($options['field'])) {
$field = $options['field'];
if (!isset($options['field']) || strlen($options['field']) < 1) {
throw new Exception("'field' must be set in the option array.");
}
if (isset($options['length'])) {
@ -29,12 +34,14 @@ class RandomId extends Behavior implements BehaviorInterface
$options['length'] = 32;
}
if (strlen($field) < 1) {
throw new Exception("'field' must be set in the option array.");
}
parent::__construct($options);
}
/**
* @param string $type
* @param \Phalcon\Mvc\ModelInterface $model
* @throws \Phalcon\Security\Exception
*/
public function notify($type, \Phalcon\Mvc\ModelInterface $model)
{
switch($type) {
@ -44,16 +51,20 @@ class RandomId extends Behavior implements BehaviorInterface
}
}
/**
* @param \Phalcon\Mvc\ModelInterface $model
* @throws \Phalcon\Security\Exception
*/
public function generateId(\Phalcon\Mvc\ModelInterface $model)
{
$field = $this->_options['field'];
$len = $this->_options['length'];
if ($model->$field === null) {
$random = new \Phalcon\Security\Random();
for($i = 0; $i < 3; $i++) {
$id = $random->base64Safe();
$id = substr($id, 0, $this->_options['length']);
$id = substr($random->base64Safe(), 0, $len);
$count = $model->count(array(
"$field = ?0",