Archived
1
0
Fork 0
This repository has been archived on 2026-04-03. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
httpcb/app/library/Mvc/Model/Behavior/RandomId.php
2017-09-01 17:10:27 +02:00

70 lines
1.7 KiB
PHP

<?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;
}
}
}
}
}