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