gabrysiak
8/14/2014 - 7:49 PM

PHP - Random number generator class

<?php
/**
 * @author Tom Gabrysiak
 * @version 1.0
 *
 * Compares 2 random generated numbers to see if they are equal
 * 
 * Class needs to be initialized before chaining other methods
 * 
 * Example:
 * Contest::initialize(1)->determineWinner();
 * 
 */

class Contest
{
    /**
     * Number of digits the random number should contain
     * @var int
     */
    private static $_digits;

    /**
     * First random generated number
     * @var mixed
     */
    private static $_firstRoll;

    /**
     * Second random generatednumber
     * @var mixed
     */
    private static $_secondRoll;

    /**
     * Contains result of random number comparison
     * @var bool
     */
    private static $_winner;

    /**
     * mySql formatted timestamp
     * @var mixed
     */
    private static $_timestamp;


    /**
     * Generate our initial number which will be compared against to see if we won
     * @param  int $digits   number of digits the random number should be
     * @return mixed         initial random number
     */
    private static function firstRoll()
    {
        return static::$_firstRoll = str_pad(rand(0, pow(10, static::$_digits)-1), static::$_digits, '0', STR_PAD_LEFT);    
    }


    /**
     * Generate random number and then encrypt it
     * @param  int $digits   number of digits the random number should be
     * @return mixed         encypted initial random number using mCrypt
     */
    public static function initialize($digits)
    {
        static::$_digits = (int)$digits;
        return new static;
    }


    /**
     * Generate our random rolls
     * @param  int $total_rolls total number of rolls you wish to execute
     * @return mixed              Doesnt return anything at the moment but echos your results
     */
    private static function secondRoll()
    {   
        
        return static::$_secondRoll = str_pad(rand(0, pow(10, static::$_digits)-1), static::$_digits, '0', STR_PAD_LEFT);
    
    }

    
    /**
     * Create timestamp incase we need to track time when winner occured
     * @return mixed mysql ready timestamp
     */
    private static function createTimestamp()
    {
        $time = new DateTime('NOW');
        return static::$_timestamp = $time->format('Y-m-d H:i:s');
    }

    
    /**
     * Compare 2 random numbers for equality
     * @return bool if equal return true otherwise return false
     */
    private static function compareNumbers()
    {
        return static::$_winner = (static::firstRoll() == static::secondRoll() ? true : false);
    }

    
    /**
     * Generate 2 random numbers and determine if winner
     */
    public static function determineWinner()
    {
        return static::compareNumbers();
    }

}