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

87 lines
2.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 (isset($this->options['expression'])) {
$expr = 'AND ' . $this->options['expression'];
} else {
$expr = '';
}
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 $expr",
'bind' => array($id)
));
if ($count < 1) {
$model->$field = $id;
break;
}
}
}
}
}