Sequencer.php
2.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
/**
* ID Sequencer
*
* Generates a unique ID, based on a prefix code and a 7 digit zero-filled number in sequencial order
*
* @package WordPress
* @subpackage Sequencer
* @author Tenzing Communications Inc.
* @link http://www.gotenzing.com
*/
namespace Tz\WordPress\Tools\Sequencer;
use Tz, Tz\Common, Tz\WordPress\Tools;
use Exception;
call_user_func(function() {
Tools\add_actions(__NAMESPACE__ . '\Actions');
});
/**
* Generate New ID
*
* @param (String) Prefix (EVT, NCE, GRP)
* @return (String) ID
*/
function generate($prefix = "") {
global $wpdb;
$row = $wpdb->get_row("SELECT `current`,`end` FROM `".$wpdb->prefix."sequencer` WHERE `prefix`='".$prefix."'");
if (!empty($row)) {
$current = (int) $row->current;
$end = (int) $row->end;
$next = ($current + 1);
$allowable_length = 7;
if ($next >= $end) {
throw new Exception("The prefix [$prefix] has reached it's limit of: ".$end);
} else {
$length = strlen($next);
$zeros = $allowable_length - $length;
$return = "";
if ($zeros > 0) {
for($i=0; $i < $zeros; $i++) {
$return .= "0";
}
} else {
$return = "";
}
$wpdb->query("UPDATE `".$wpdb->prefix."sequencer` SET `current`=$next WHERE `prefix`='$prefix' LIMIT 1");
return $prefix.$return.$next;
}
} else {
$wpdb->query("INSERT INTO `".$wpdb->prefix."sequencer` (`prefix`,`start`,`end`,`current`) VALUES ('$prefix',0,9999999,0)");
generate($prefix);
}
}
/**
* Standard Action Class for WordPress
*
* Checks to see if the table exists in the database, if not, creates it.
*/
class Actions {
// Does the Sequencer table exist? If not, create it.
public static function init() {
global $wpdb;
$create_table_statement = "
CREATE TABLE IF NOT EXISTS `".$wpdb->prefix."sequencer` (
`prefix` varchar(3) NOT NULL,
`start` int(7) unsigned zerofill NOT NULL DEFAULT '0000000',
`end` int(7) unsigned zerofill NOT NULL DEFAULT '9999999',
`current` int(7) unsigned zerofill DEFAULT '0000000',
`last_used` int(16) NOT NULL DEFAULT '0',
PRIMARY KEY (`prefix`),
UNIQUE KEY `prefix` (`prefix`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
";
$wpdb->query($create_table_statement);
//$wpdb->query("INSERT INTO `wp_sequencer` (`prefix`, `start`, `end`, `current`, `last_used`) VALUES ('EVT', 0000000, 9999999, 0000000, 0),('NTC', 0000000, 9999999, 0000000, 0),('CEH', 0000000, 9999999, 0000000, 0);");
}
}
?>