1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
*/ |
4
|
|
|
|
5
|
|
|
class ValidateCodeFieldForObject extends Object |
6
|
|
|
{ |
7
|
|
|
private static $length = 7; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* @var Array |
11
|
|
|
*/ |
12
|
|
|
private $replacements = array( |
13
|
|
|
'/&/u' => '-and-', |
14
|
|
|
'/&/u' => '-and-', |
15
|
|
|
'/\s/u' => '-', // remove whitespace |
16
|
|
|
'/[^A-Za-z0-9.\-_]+/u' => '', // remove non-ASCII chars, only allow alphanumeric, dashes and dots. |
17
|
|
|
'/[\-]{2,}/u' => '-', // remove duplicate dashes |
18
|
|
|
'/[\_]{2,}/u' => '_', // remove duplicate underscores |
19
|
|
|
'/^[\.\-_]/u' => '', // Remove all leading dots, dashes or underscores |
20
|
|
|
); |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* makes sure that code is unique and gets rid of special characters |
24
|
|
|
* should be run in onBeforeWrite |
25
|
|
|
* |
26
|
|
|
* @param DataObject | String $obj |
27
|
|
|
* @param Boolean $createCode |
28
|
|
|
* @param String $field |
29
|
|
|
*/ |
30
|
|
|
|
31
|
|
|
public function checkCode($obj, $createCode = false, $field = "Code") |
|
|
|
|
32
|
|
|
{ |
33
|
|
|
//exception dealing with Strings |
34
|
|
|
$isObject = true; |
35
|
|
|
if (! is_object($obj)) { |
36
|
|
|
$str = $obj; |
37
|
|
|
$obj = new DataObject(); |
38
|
|
|
$obj->$field = strval($str); |
39
|
|
|
$isObject = false; |
40
|
|
|
} |
41
|
|
|
if ($createCode) { |
42
|
|
|
if (!$obj->$field || strlen($obj->$field) != $this->Config()->get("length")) { |
43
|
|
|
$obj->$field = $this->CreateCode(); |
44
|
|
|
} |
45
|
|
|
} else { |
46
|
|
|
$obj->$field = trim($obj->$field); |
47
|
|
|
foreach ($this->replacements as $regex => $replace) { |
48
|
|
|
$obj->$field = preg_replace($regex, $replace, $obj->$field); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
if (!$obj->$field) { |
52
|
|
|
$obj->$field = strtoupper($field)."-NOT-SET"; |
53
|
|
|
} |
54
|
|
|
//make upper-case |
55
|
|
|
$obj->$field = trim(strtoupper($obj->$field)); |
56
|
|
|
//check for other ones. |
57
|
|
|
$count = 0; |
58
|
|
|
$code = $obj->$field; |
|
|
|
|
59
|
|
|
while ( |
60
|
|
|
$isObject && |
61
|
|
|
$obj::get() |
62
|
|
|
->filter([$field => $obj->$field]) |
63
|
|
|
->exclude(["ID" => intval($obj->ID) - 0])->Count() > 0 && |
64
|
|
|
$count < 1000 |
65
|
|
|
) { |
66
|
|
|
$obj->$field = $this->CreateCode(); |
67
|
|
|
$count++; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return $obj->$field; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
public function CreateCode() |
74
|
|
|
{ |
75
|
|
|
$seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'); // and any other characters |
76
|
|
|
$rand = ''; |
77
|
|
|
foreach (array_rand($seed, $this->Config()->get("length")) as $k) { |
78
|
|
|
$rand .= $seed[$k]; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
return $rand; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@return
annotation as described here.