Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace BookingNamespace;
- /**
- * Simulate expiration process with two public methods:
- * - book will return a token
- * - confirm will take a token, and return
- * -> true if called within 5 minutes of corresponding book call
- * -> false if more than 5 minutes have passed
- */
- class MyBookingObject
- {
- private $tokens; // array with tokens as keys, dates as values
- private $timeout_delay; // seconds
- /**
- * Empty tokens, 5 minutes timeout
- */
- public function __construct()
- {
- $this->tokens = array();
- $this->timeout_delay = 5 * 60;
- }
- private function generate_random_string(){ return substr(md5(rand()), 0, 7); }
- private function has_token($token){ return isset($this->tokens[$token]); }
- private function init_token($token){ $this->tokens[$token] = new DateTime(); }
- private function get_booking_date($token){ return $this->tokens[$token]; }
- private function is_over_timeout($seconds){ return $seconds > $this->timeout_delay; }
- /**
- * Our booking time has timed out if it has happened too long ago
- * @return true if $booking_time is too long ago
- * false if we are on time
- */
- private function has_timed_out(DateTime $booking_time)
- {
- $now = new DateTime();
- if($booking_time > $now) throw new Exception("Booking time should be in the past.");
- $diff = $now->getTimestamp() - $booking_time->getTimestamp();
- return $this->is_over_timeout($diff);
- }
- /**
- * @throws Exception if there is more bookings than the system can handle
- * @return string: the token for our booking.
- */
- public function book()
- {
- if(count($this->tokens) > 10000) throw new Exception("That's too many bookings");
- do {
- $token = $this->generate_random_string();
- }
- while($this->has_token($token));
- $this->init_token($token);
- return $token;
- }
- /**
- * @param string $token: the booking token
- * @throws Exception if this token cannot be found
- * @return boolean true if confirmation ok
- * false if confirmation timed out
- */
- public function confirm($token)
- {
- if( ! $this->has_token($token) ) throw new Exception("Incorrect token for confirmation");
- $booking_date = $this->get_booking_date($token);
- if($this->has_timed_out($booking_date)) return false;
- return true;
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement