elmika

Overriding DateTime

Apr 9th, 2014
131
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. namespace BookingNamespace;
  4.  
  5. /**
  6.  * extend DateTime functionalities so that we are able to define what should be considered to be "now"
  7.  *   - set_now allows to define "now"
  8.  *   - modify_now applies the modify function on what is defined as "now"
  9.  *   - reset is for going back to original DateTime behaviour
  10.  *  
  11.  * @author mika
  12.  */
  13. class DateTime extends \DateTime
  14. {
  15.   private static $fake_time=null;
  16.  
  17.   // public static method that extend DateTime functionalities
  18.   public static function reset(){ self::$fake_time = null; }
  19.   public static function set_now($time = "now", DateTimeZone $timezone = null)
  20.   {
  21.     self::$fake_time = new \DateTime($time, $timezone);
  22.   }
  23.   public static function modify_now($modify){ if( ! is_null(self::$fake_time)) self::$fake_time->modify($modify); }
  24.  
  25.   // private methods for the constructor
  26.   private function is_virtual(){ return ! is_null(self::$fake_time); }
  27.   private function is_relative_date($val){ return strtotime($val) != strtotime($val, 0); }
  28.  
  29.   /**
  30.   *   constructor:
  31.   *       - if we work with virtual now, relative times are calculated based on $fake_time
  32.   *       - DateTimeZone is ignored in virtual context (and relative time).
  33.   *       - if we do not work with virtual now, parent constructor is called.
  34.   */
  35.   public function __construct($time = "now", DateTimeZone $timezone = null)
  36.   {
  37.       if($this->is_virtual()&&$this->is_relative_date($time))
  38.       {
  39.           parent::__construct(self::$fake_time->format(DateTime::ISO8601));
  40.           parent::modify($time);        
  41.       }
  42.       else
  43.         parent::__construct($time, $timezone);
  44.   }
  45. }
  46.  
  47. ?>
RAW Paste Data