70 lines
1.7 KiB
PHP
70 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace Httpcb\Mvc\Model\Behavior;
|
|
|
|
use \Phalcon\Mvc\Model\Behavior;
|
|
use \Phalcon\Mvc\Model\BehaviorInterface;
|
|
use \Phalcon\Exception;
|
|
|
|
/**
|
|
* Generates a unique base64 url-safe id for the field specified.
|
|
*
|
|
* Class RandomId
|
|
* @package Mvc\Model\Behavior
|
|
*/
|
|
class RandomId extends Behavior implements BehaviorInterface
|
|
{
|
|
public function __construct($options = null)
|
|
{
|
|
$field = null;
|
|
if (isset($options['field'])) {
|
|
$field = $options['field'];
|
|
}
|
|
|
|
if (isset($options['length'])) {
|
|
if (!is_numeric($options['length'])) {
|
|
throw new Exception("'length' must be a number.");
|
|
}
|
|
} else {
|
|
$options['length'] = 32;
|
|
}
|
|
|
|
if (strlen($field) < 1) {
|
|
throw new Exception("'field' must be set in the option array.");
|
|
}
|
|
parent::__construct($options);
|
|
}
|
|
|
|
public function notify($type, \Phalcon\Mvc\ModelInterface $model)
|
|
{
|
|
switch($type) {
|
|
case 'beforeValidationOnCreate' :
|
|
$this->generateId($model);
|
|
break;
|
|
}
|
|
}
|
|
|
|
public function generateId(\Phalcon\Mvc\ModelInterface $model)
|
|
{
|
|
$field = $this->_options['field'];
|
|
|
|
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']);
|
|
|
|
$count = $model->count(array(
|
|
"$field = ?0",
|
|
'bind' => array($id)
|
|
));
|
|
|
|
if ($count < 1) {
|
|
$model->$field = $id;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|