initial commit
This commit is contained in:
commit
e869a1cab4
107 changed files with 9029 additions and 0 deletions
70
app/library/Mvc/Model/Behavior/RandomId.php
Normal file
70
app/library/Mvc/Model/Behavior/RandomId.php
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
<?php
|
||||
|
||||
namespace 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in a new issue