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
|
|
|
*/ |
29
|
|
|
|
30
|
|
|
public function checkCode($obj, $createCode = false) |
31
|
|
|
{ |
32
|
|
|
//exception dealing with Strings |
33
|
|
|
$isObject = true; |
34
|
|
|
if (! is_object($obj)) { |
35
|
|
|
$str = $obj; |
36
|
|
|
$obj = new DataObject(); |
37
|
|
|
$obj->Code = strval($str); |
38
|
|
|
$isObject = false; |
39
|
|
|
} |
40
|
|
|
if ($createCode) { |
41
|
|
|
if (!$obj->Code || strlen($obj->Code) != $this->Config()->get("length")) { |
42
|
|
|
$obj->Code = substr(md5(uniqid($obj->ID, true)), 0, $this->Config()->get("length")); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
$obj->Code = trim($obj->Code); |
46
|
|
|
foreach ($this->replacements as $regex => $replace) { |
47
|
|
|
$obj->Code = preg_replace($regex, $replace, $obj->Code); |
48
|
|
|
} |
49
|
|
|
if (!$obj->Code) { |
50
|
|
|
"CODE-NOT-SET"; |
51
|
|
|
} |
52
|
|
|
//make upper-case |
53
|
|
|
$obj->Code = trim(strtoupper($obj->Code)); |
54
|
|
|
//check for other ones. |
55
|
|
|
$count = 2; |
56
|
|
|
$code = $obj->Code; |
57
|
|
|
while ($isObject && $obj::get() |
58
|
|
|
->filter(array("Code" => $obj->Code)) |
59
|
|
|
->exclude(array("ID" => $obj->ID))->Count() |
60
|
|
|
) { |
61
|
|
|
$obj->Code = $code . '-' . $count; |
62
|
|
|
$count++; |
63
|
|
|
} |
64
|
|
|
return $obj->Code; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
You can fix this by adding a namespace to your class:
When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.