Sequencer.php 2.88 KB
<?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 `wp_sequencer` (
              `prefix` varchar(3) CHARACTER SET latin1 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=InnoDB DEFAULT CHARSET=utf8;
        ";
        $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);");
    }
    
}

?>