Converted tabs to spaces.
This commit is contained in:
parent
3e08d173a1
commit
617eb21614
60 changed files with 9220 additions and 9277 deletions
|
@ -22,33 +22,32 @@
|
||||||
*/
|
*/
|
||||||
class API_AYAH
|
class API_AYAH
|
||||||
{
|
{
|
||||||
public static function getHTML()
|
public static function getHTML()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
|
|
||||||
if (!$config->api['ayah'])
|
if (!$config->api['ayah'])
|
||||||
{
|
{
|
||||||
throw new Exception('Missing API configuration.');
|
throw new Exception('Missing API configuration.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$ayah = new AYAH($config->api['ayah']);
|
$ayah = new AYAH($config->api['ayah']);
|
||||||
|
|
||||||
return $ayah->getPublisherHTML();
|
return $ayah->getPublisherHTML();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function isHuman()
|
public static function isHuman()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
|
|
||||||
if (!$config->api['ayah'])
|
if (!$config->api['ayah'])
|
||||||
{
|
{
|
||||||
throw new Exception('Missing API configuration.');
|
throw new Exception('Missing API configuration.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$ayah = new AYAH($config->api['ayah']);
|
$ayah = new AYAH($config->api['ayah']);
|
||||||
|
|
||||||
return $ayah->scoreResult();
|
return $ayah->scoreResult();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -20,30 +20,29 @@
|
||||||
*/
|
*/
|
||||||
class API_Google_Profanity
|
class API_Google_Profanity
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Check
|
* Check
|
||||||
*
|
*
|
||||||
* Checks if a word is considered profanity.
|
* Checks if a word is considered profanity.
|
||||||
*
|
*
|
||||||
* @usage API_Google_Profanity::check('fuck'); // returns true
|
* @usage API_Google_Profanity::check('fuck'); // returns true
|
||||||
* @param string $word word to check
|
* @param string $word word to check
|
||||||
* @param string $endpoint the endpoint to call (helps testing)
|
* @param string $endpoint the endpoint to call (helps testing)
|
||||||
* @return boolean whether or not the word is profanity
|
* @return boolean whether or not the word is profanity
|
||||||
*/
|
*/
|
||||||
public static function check($word, $endpoint = 'http://www.wdyl.com/profanity?q=')
|
public static function check($word, $endpoint = 'http://www.wdyl.com/profanity?q=')
|
||||||
{
|
{
|
||||||
$response = json_decode(file_get_contents($endpoint . $word), true);
|
$response = json_decode(file_get_contents($endpoint . $word), true);
|
||||||
|
|
||||||
if ($response == null || !isset($response['response'])
|
if ($response == null || !isset($response['response'])
|
||||||
|| !in_array($response['response'], ['true', 'false']))
|
|| !in_array($response['response'], ['true', 'false']))
|
||||||
{
|
{
|
||||||
throw new Exception('Invalid response from API.');
|
throw new Exception('Invalid response from API.');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
return $response['response'] == 'true';
|
return $response['response'] == 'true';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -22,78 +22,77 @@
|
||||||
*/
|
*/
|
||||||
class API_Gravatar
|
class API_Gravatar
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Hash
|
* Hash
|
||||||
*
|
*
|
||||||
* Generates a hash from the passed string that can then be used for
|
* Generates a hash from the passed string that can then be used for
|
||||||
* fetching an image or profile from Gravatar.com
|
* fetching an image or profile from Gravatar.com
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $string string to hash, should be an email address
|
* @param string $string string to hash, should be an email address
|
||||||
* @return string resulting hash
|
* @return string resulting hash
|
||||||
*/
|
*/
|
||||||
public static function hash($string)
|
public static function hash($string)
|
||||||
{
|
{
|
||||||
// Trims whitespace, lowers the case then applies MD5
|
// Trims whitespace, lowers the case then applies MD5
|
||||||
return md5(strtolower(trim($string)));
|
return md5(strtolower(trim($string)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* img
|
* img
|
||||||
*
|
*
|
||||||
* Generates an img tag requesting a Gravatar based on the parameters.
|
* Generates an img tag requesting a Gravatar based on the parameters.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $email address to use for the hash
|
* @param string $email address to use for the hash
|
||||||
* @param integer $size optional size of the image requested
|
* @param integer $size optional size of the image requested
|
||||||
* @param string $default optional default style or image to generate
|
* @param string $default optional default style or image to generate
|
||||||
* @param string $rating optional filter by a certain rating
|
* @param string $rating optional filter by a certain rating
|
||||||
* @param boolean $force optional force the default avatar
|
* @param boolean $force optional force the default avatar
|
||||||
* @param boolean $secure optional whether to use the SSL URL
|
* @param boolean $secure optional whether to use the SSL URL
|
||||||
* @param array $attributes optional any additional parameters to include
|
* @param array $attributes optional any additional parameters to include
|
||||||
* @return string an img tag requesting a Gravatar
|
* @return string an img tag requesting a Gravatar
|
||||||
*/
|
*/
|
||||||
public static function img($email, $size = 80, $default = 'gravatar', $rating = 'g', $force = false, $secure = false, $attributes = false)
|
public static function img($email, $size = 80, $default = 'gravatar', $rating = 'g', $force = false, $secure = false, $attributes = false)
|
||||||
{
|
{
|
||||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
|
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
|
||||||
{
|
{
|
||||||
throw new Exception('Invalid email address.');
|
throw new Exception('Invalid email address.');
|
||||||
}
|
}
|
||||||
elseif ($size < 1 || $size > 2048)
|
elseif ($size < 1 || $size > 2048)
|
||||||
{
|
{
|
||||||
throw new Exception('Invalid size parameter, expecting an integer between 1 and 2048.');
|
throw new Exception('Invalid size parameter, expecting an integer between 1 and 2048.');
|
||||||
}
|
}
|
||||||
elseif (!in_array($default, ['gravatar', '404', 'mm', 'identicon', 'monsterid', 'wavatar', 'retro', 'blank'])
|
elseif (!in_array($default, ['gravatar', '404', 'mm', 'identicon', 'monsterid', 'wavatar', 'retro', 'blank'])
|
||||||
&& !filter_var($default, FILTER_VALIDATE_URL))
|
&& !filter_var($default, FILTER_VALIDATE_URL))
|
||||||
{
|
{
|
||||||
throw new Exception('Invalid default parameter, expecting gravatar, 404, mm, identicon, monsterid, wavatar, retro, blank or a valid URL.');
|
throw new Exception('Invalid default parameter, expecting gravatar, 404, mm, identicon, monsterid, wavatar, retro, blank or a valid URL.');
|
||||||
}
|
}
|
||||||
elseif (!in_array($rating, ['g', 'pg', 'r', 'x']))
|
elseif (!in_array($rating, ['g', 'pg', 'r', 'x']))
|
||||||
{
|
{
|
||||||
throw new Exception('Invalid rating parameter, expecting g, pg, r or x.');
|
throw new Exception('Invalid rating parameter, expecting g, pg, r or x.');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$default = $default == 'gravatar' ? false : urlencode($default);
|
$default = $default == 'gravatar' ? false : urlencode($default);
|
||||||
|
|
||||||
$html = '<img src="'
|
$html = '<img src="'
|
||||||
. ($secure ? 'https://secure' : 'http://www') . '.gravatar.com/avatar/' . self::hash($email)
|
. ($secure ? 'https://secure' : 'http://www') . '.gravatar.com/avatar/' . self::hash($email)
|
||||||
. sprintf('?s=%s&d=%s&r=%s', $size, urlencode($default), $rating, $force)
|
. sprintf('?s=%s&d=%s&r=%s', $size, urlencode($default), $rating, $force)
|
||||||
. ($force ? '&f=y' : '') . '"';
|
. ($force ? '&f=y' : '') . '"';
|
||||||
|
|
||||||
if (is_array($attributes))
|
if (is_array($attributes))
|
||||||
{
|
{
|
||||||
foreach ($attributes as $attribute => $value)
|
foreach ($attributes as $attribute => $value)
|
||||||
{
|
{
|
||||||
$html .= sprintf(' %s="%s"', $attribute, $value);
|
$html .= sprintf(' %s="%s"', $attribute, $value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$html .= '>';
|
$html .= '>';
|
||||||
|
|
||||||
return $html;
|
return $html;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -22,86 +22,85 @@
|
||||||
*/
|
*/
|
||||||
class API_PlaceholdIt extends Object
|
class API_PlaceholdIt extends Object
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* URL
|
* URL
|
||||||
*
|
*
|
||||||
* Generates a Placehold.it URL based on the passed parameters.
|
* Generates a Placehold.it URL based on the passed parameters.
|
||||||
*
|
*
|
||||||
* @param integer $width width of the image
|
* @param integer $width width of the image
|
||||||
* @param integer $height optional height of the image
|
* @param integer $height optional height of the image
|
||||||
* @param string $format optional format of the image
|
* @param string $format optional format of the image
|
||||||
* @param string $background optional background color of the image
|
* @param string $background optional background color of the image
|
||||||
* @param string $foreground optional foreground color of the image
|
* @param string $foreground optional foreground color of the image
|
||||||
* @param string $text optional text to display in the image
|
* @param string $text optional text to display in the image
|
||||||
* @return string Placehold.it URL
|
* @return string Placehold.it URL
|
||||||
*/
|
*/
|
||||||
public function url($width, $height = null, $format = 'gif', $background = null, $foreground = null, $text = null)
|
public function url($width, $height = null, $format = 'gif', $background = null, $foreground = null, $text = null)
|
||||||
{
|
{
|
||||||
// Checks if the format is valid
|
// Checks if the format is valid
|
||||||
if (!in_array($format, ['gif', 'jpeg', 'jpg', 'png']))
|
if (!in_array($format, ['gif', 'jpeg', 'jpg', 'png']))
|
||||||
{
|
{
|
||||||
throw new Exception('Invalid format. Valid formats: gif, jpeg, jpg and png.');
|
throw new Exception('Invalid format. Valid formats: gif, jpeg, jpg and png.');
|
||||||
}
|
}
|
||||||
// Checks if foreground is present without background
|
// Checks if foreground is present without background
|
||||||
elseif ($foreground && !$background)
|
elseif ($foreground && !$background)
|
||||||
{
|
{
|
||||||
throw new Exception('You must specify a background color if you wish to specify a foreground color.');
|
throw new Exception('You must specify a background color if you wish to specify a foreground color.');
|
||||||
}
|
}
|
||||||
// Checks the background color's length
|
// Checks the background color's length
|
||||||
elseif ($background && strlen($background) < 6)
|
elseif ($background && strlen($background) < 6)
|
||||||
{
|
{
|
||||||
throw new Exception('The background color must be a 6 character hex code.');
|
throw new Exception('The background color must be a 6 character hex code.');
|
||||||
}
|
}
|
||||||
// Checks the foreground color's length
|
// Checks the foreground color's length
|
||||||
elseif ($foreground && strlen($foreground) < 6)
|
elseif ($foreground && strlen($foreground) < 6)
|
||||||
{
|
{
|
||||||
throw new Exception('The foreground color must be a 6 character hex code.');
|
throw new Exception('The foreground color must be a 6 character hex code.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$url = 'http://placehold.it/' . $width;
|
$url = 'http://placehold.it/' . $width;
|
||||||
|
|
||||||
if ($height)
|
if ($height)
|
||||||
{
|
{
|
||||||
$url .= 'x' . $height;
|
$url .= 'x' . $height;
|
||||||
}
|
}
|
||||||
|
|
||||||
$url .= '.' . $format;
|
$url .= '.' . $format;
|
||||||
|
|
||||||
if ($background)
|
if ($background)
|
||||||
{
|
{
|
||||||
$url .= '/' . $background;
|
$url .= '/' . $background;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($foreground)
|
if ($foreground)
|
||||||
{
|
{
|
||||||
$url .= '/' . $foreground;
|
$url .= '/' . $foreground;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($text)
|
if ($text)
|
||||||
{
|
{
|
||||||
$url .= '&text=' . urlencode($text);
|
$url .= '&text=' . urlencode($text);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $url;
|
return $url;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* URL
|
* URL
|
||||||
*
|
*
|
||||||
* Generates a Placehold.it <img> tag based on the passed parameters.
|
* Generates a Placehold.it <img> tag based on the passed parameters.
|
||||||
*
|
*
|
||||||
* @param integer $width width of the image
|
* @param integer $width width of the image
|
||||||
* @param integer $height optional height of the image
|
* @param integer $height optional height of the image
|
||||||
* @param string $format optional format of the image
|
* @param string $format optional format of the image
|
||||||
* @param string $background optional background color of the image
|
* @param string $background optional background color of the image
|
||||||
* @param string $foreground optional foreground color of the image
|
* @param string $foreground optional foreground color of the image
|
||||||
* @param string $text optional text to display in the image
|
* @param string $text optional text to display in the image
|
||||||
* @return string <img> tag with the Placehold.it URL
|
* @return string <img> tag with the Placehold.it URL
|
||||||
*/
|
*/
|
||||||
public function img($width, $height = null, $format = 'gif', $background = null, $foreground = null, $text = null)
|
public function img($width, $height = null, $format = 'gif', $background = null, $foreground = null, $text = null)
|
||||||
{
|
{
|
||||||
return '<img src="' . $this->url($width, $height, $format, $background, $foreground, $text) . '">';
|
return '<img src="' . $this->url($width, $height, $format, $background, $foreground, $text) . '">';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -23,266 +23,265 @@
|
||||||
*/
|
*/
|
||||||
class Browser extends Object
|
class Browser extends Object
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Attributes
|
* Attributes
|
||||||
*
|
*
|
||||||
* Variables passed on the query string as /var:value/
|
* Variables passed on the query string as /var:value/
|
||||||
*
|
*
|
||||||
* @access private
|
* @access private
|
||||||
* @var array
|
* @var array
|
||||||
*/
|
*/
|
||||||
private $attributes = [];
|
private $attributes = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get instance of the object
|
* Get instance of the object
|
||||||
*
|
*
|
||||||
* Let's the parent class do all the work
|
* Let's the parent class do all the work
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $class name of the class to instantiate
|
* @param string $class name of the class to instantiate
|
||||||
* @return object self::$instance instance of the Config class
|
* @return object self::$instance instance of the Config class
|
||||||
*/
|
*/
|
||||||
public static function getInstance($class = 'Browser')
|
public static function getInstance($class = 'Browser')
|
||||||
{
|
{
|
||||||
return parent::getInstance($class);
|
return parent::getInstance($class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set browser variable
|
* Set browser variable
|
||||||
*
|
*
|
||||||
* Sets a variable in the attributes array for easier access later.
|
* Sets a variable in the attributes array for easier access later.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $variable name of the variable to set
|
* @param string $variable name of the variable to set
|
||||||
* @param mixed $value the value to set to the variable
|
* @param mixed $value the value to set to the variable
|
||||||
* @return boolean true
|
* @return boolean true
|
||||||
*/
|
*/
|
||||||
public static function set($variable, $value)
|
public static function set($variable, $value)
|
||||||
{
|
{
|
||||||
$browser = Browser::getInstance();
|
$browser = Browser::getInstance();
|
||||||
$browser->attributes[$variable] = $value;
|
$browser->attributes[$variable] = $value;
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get browser variable
|
* Get browser variable
|
||||||
*
|
*
|
||||||
* Gets a variable passed in from the browser. Currently only supports
|
* Gets a variable passed in from the browser. Currently only supports
|
||||||
* the custom attribute URI format /$variable:$value/.
|
* the custom attribute URI format /$variable:$value/.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $variable name of the variable to get
|
* @param string $variable name of the variable to get
|
||||||
* @return mixed the value of the variable or boolean false if not set
|
* @return mixed the value of the variable or boolean false if not set
|
||||||
*/
|
*/
|
||||||
public static function get($variable)
|
public static function get($variable)
|
||||||
{
|
{
|
||||||
$browser = Browser::getInstance();
|
$browser = Browser::getInstance();
|
||||||
|
|
||||||
if (isset($browser->attributes[$variable]))
|
if (isset($browser->attributes[$variable]))
|
||||||
{
|
{
|
||||||
return $browser->attributes[$variable];
|
return $browser->attributes[$variable];
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Go Home
|
* Go Home
|
||||||
*
|
*
|
||||||
* Alias for `Browser::redirect('/');`
|
* Alias for `Browser::redirect('/');`
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
public static function goHome()
|
public static function goHome()
|
||||||
{
|
{
|
||||||
return Browser::redirect('/');
|
return Browser::redirect('/');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Is Mobile
|
* Is Mobile
|
||||||
*
|
*
|
||||||
* Detects if we're working with a mobile browser.
|
* Detects if we're working with a mobile browser.
|
||||||
*
|
*
|
||||||
* @return boolean whether or not the browser is considered mobile
|
* @return boolean whether or not the browser is considered mobile
|
||||||
*/
|
*/
|
||||||
public static function isMobile()
|
public static function isMobile()
|
||||||
{
|
{
|
||||||
$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
|
$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
|
||||||
|
|
||||||
return preg_match('/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i', $user_agent) || preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i', substr($user_agent, 0, 4)) || strpos('iPhone', $user_agent);
|
return preg_match('/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i', $user_agent) || preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i', substr($user_agent, 0, 4)) || strpos('iPhone', $user_agent);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Redirect
|
* Redirect
|
||||||
*
|
*
|
||||||
* Redirects the browser to another URL. Stops execution as to not run
|
* Redirects the browser to another URL. Stops execution as to not run
|
||||||
* code erroneously due to output buffering. HTTP/1.1 request an
|
* code erroneously due to output buffering. HTTP/1.1 request an
|
||||||
* absolute URI, hence the inclusion of the scheme, hostname and
|
* absolute URI, hence the inclusion of the scheme, hostname and
|
||||||
* absolute path if :// is not found. Don't hate the player, hate the
|
* absolute path if :// is not found. Don't hate the player, hate the
|
||||||
* RFC.
|
* RFC.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $destination URL to redirect to
|
* @param string $destination URL to redirect to
|
||||||
* @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30
|
* @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30
|
||||||
*/
|
*/
|
||||||
public static function redirect($destination)
|
public static function redirect($destination)
|
||||||
{
|
{
|
||||||
if (strpos($destination, '://') === false)
|
if (strpos($destination, '://') === false)
|
||||||
{
|
{
|
||||||
$destination = 'http' . ((!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off' || $_SERVER['HTTPS'] == '') ? '' : 's') . '://' . $_SERVER['HTTP_HOST'] . $destination;
|
$destination = 'http' . ((!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off' || $_SERVER['HTTPS'] == '') ? '' : 's') . '://' . $_SERVER['HTTP_HOST'] . $destination;
|
||||||
}
|
}
|
||||||
|
|
||||||
header('Location: ' . $destination);
|
header('Location: ' . $destination);
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Refresh
|
* Refresh
|
||||||
*
|
*
|
||||||
* Forces a browser refresh of the currently requested page.
|
* Forces a browser refresh of the currently requested page.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
*/
|
*/
|
||||||
public static function refresh()
|
public static function refresh()
|
||||||
{
|
{
|
||||||
Browser::redirect($_SERVER['REQUEST_URI']);
|
Browser::redirect($_SERVER['REQUEST_URI']);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Remote IP
|
* Remote IP
|
||||||
*
|
*
|
||||||
* Returns the user's IP address.
|
* Returns the user's IP address.
|
||||||
*
|
*
|
||||||
* @return mixed IP address or false if unable to determine
|
* @return mixed IP address or false if unable to determine
|
||||||
*/
|
*/
|
||||||
public static function remoteIP()
|
public static function remoteIP()
|
||||||
{
|
{
|
||||||
if (!empty($_SERVER['HTTP_CLIENT_IP']))
|
if (!empty($_SERVER['HTTP_CLIENT_IP']))
|
||||||
{
|
{
|
||||||
$ip = $_SERVER['HTTP_CLIENT_IP'];
|
$ip = $_SERVER['HTTP_CLIENT_IP'];
|
||||||
}
|
}
|
||||||
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
|
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
|
||||||
{
|
{
|
||||||
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
|
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
|
||||||
}
|
}
|
||||||
elseif (isset($_SERVER['REMOTE_ADDR']))
|
elseif (isset($_SERVER['REMOTE_ADDR']))
|
||||||
{
|
{
|
||||||
$ip = $_SERVER['REMOTE_ADDR'];
|
$ip = $_SERVER['REMOTE_ADDR'];
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$ip = false;
|
$ip = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $ip;
|
return $ip;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Status
|
* Status
|
||||||
*
|
*
|
||||||
* Pushes a status code to the browser. Some of these codes are site
|
* Pushes a status code to the browser. Some of these codes are site
|
||||||
* (420) and server (444) specific, some just for LOLs (418) and some
|
* (420) and server (444) specific, some just for LOLs (418) and some
|
||||||
* that are still in draft (425) and subject to change. I wanted this
|
* that are still in draft (425) and subject to change. I wanted this
|
||||||
* to be a complete list and in the scenario that a code had multiple
|
* to be a complete list and in the scenario that a code had multiple
|
||||||
* meanings, I favored a more recent RFC (424) even if merely a draft
|
* meanings, I favored a more recent RFC (424) even if merely a draft
|
||||||
* (451).
|
* (451).
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param integer status response code
|
* @param integer status response code
|
||||||
*/
|
*/
|
||||||
public static function status($code = 200)
|
public static function status($code = 200)
|
||||||
{
|
{
|
||||||
switch ($code)
|
switch ($code)
|
||||||
{
|
{
|
||||||
// {{{ 1xx Informational
|
// {{{ 1xx Informational
|
||||||
case 100: $message = '100 Continue'; break;
|
case 100: $message = '100 Continue'; break;
|
||||||
case 101: $message = '101 Switching Protocols'; break;
|
case 101: $message = '101 Switching Protocols'; break;
|
||||||
case 102: $message = '102 Processing'; break;
|
case 102: $message = '102 Processing'; break;
|
||||||
// }}}
|
// }}}
|
||||||
// {{{ 2xx Success
|
// {{{ 2xx Success
|
||||||
case 201: $message = '201 Created'; break;
|
case 201: $message = '201 Created'; break;
|
||||||
case 202: $message = '202 Accepted'; break;
|
case 202: $message = '202 Accepted'; break;
|
||||||
case 203: $message = '203 Non-Authoritative Information'; break;
|
case 203: $message = '203 Non-Authoritative Information'; break;
|
||||||
case 204: $message = '204 No Content'; break;
|
case 204: $message = '204 No Content'; break;
|
||||||
case 205: $message = '205 Reset Content'; break;
|
case 205: $message = '205 Reset Content'; break;
|
||||||
case 206: $message = '206 Partial Content'; break;
|
case 206: $message = '206 Partial Content'; break;
|
||||||
case 207: $message = '207 Multi-Status'; break;
|
case 207: $message = '207 Multi-Status'; break;
|
||||||
case 208: $message = '208 Already Reported'; break;
|
case 208: $message = '208 Already Reported'; break;
|
||||||
case 226: $message = '226 IM Used'; break;
|
case 226: $message = '226 IM Used'; break;
|
||||||
// }}}
|
// }}}
|
||||||
// {{{ 3xx Redirection
|
// {{{ 3xx Redirection
|
||||||
case 300: $message = '300 Multiple Choices'; break;
|
case 300: $message = '300 Multiple Choices'; break;
|
||||||
case 301: $message = '301 Moved Permanently'; break;
|
case 301: $message = '301 Moved Permanently'; break;
|
||||||
case 302: $message = '302 Found'; break;
|
case 302: $message = '302 Found'; break;
|
||||||
case 303: $message = '303 See Other'; break;
|
case 303: $message = '303 See Other'; break;
|
||||||
case 304: $message = '304 Not Modified'; break;
|
case 304: $message = '304 Not Modified'; break;
|
||||||
case 305: $message = '305 Use Proxy'; break;
|
case 305: $message = '305 Use Proxy'; break;
|
||||||
case 306: $message = '306 Switch Proxy'; break;
|
case 306: $message = '306 Switch Proxy'; break;
|
||||||
case 307: $message = '307 Temporary Redirect'; break;
|
case 307: $message = '307 Temporary Redirect'; break;
|
||||||
case 308: $message = '308 Permanent Redirect'; break;
|
case 308: $message = '308 Permanent Redirect'; break;
|
||||||
// }}}
|
// }}}
|
||||||
// {{{ 4xx Client Error
|
// {{{ 4xx Client Error
|
||||||
case 400: $message = '400 Bad Request'; break;
|
case 400: $message = '400 Bad Request'; break;
|
||||||
case 401: $message = '401 Unauthorized'; break;
|
case 401: $message = '401 Unauthorized'; break;
|
||||||
case 402: $message = '402 Payment Required'; break;
|
case 402: $message = '402 Payment Required'; break;
|
||||||
case 403: $message = '403 Forbidden'; break;
|
case 403: $message = '403 Forbidden'; break;
|
||||||
case 404: $message = '404 Not Found'; break;
|
case 404: $message = '404 Not Found'; break;
|
||||||
case 405: $message = '405 Method Not Allowed'; break;
|
case 405: $message = '405 Method Not Allowed'; break;
|
||||||
case 406: $message = '406 Not Acceptable'; break;
|
case 406: $message = '406 Not Acceptable'; break;
|
||||||
case 407: $message = '407 Proxy Authentication Required'; break;
|
case 407: $message = '407 Proxy Authentication Required'; break;
|
||||||
case 408: $message = '408 Request Timeout'; break;
|
case 408: $message = '408 Request Timeout'; break;
|
||||||
case 409: $message = '409 Conflict'; break;
|
case 409: $message = '409 Conflict'; break;
|
||||||
case 410: $message = '410 Gone'; break;
|
case 410: $message = '410 Gone'; break;
|
||||||
case 411: $message = '411 Length Required'; break;
|
case 411: $message = '411 Length Required'; break;
|
||||||
case 412: $message = '412 Precondition Failed'; break;
|
case 412: $message = '412 Precondition Failed'; break;
|
||||||
case 413: $message = '413 Request Entity Too Large'; break;
|
case 413: $message = '413 Request Entity Too Large'; break;
|
||||||
case 414: $message = '414 Request-URI Too Long'; break;
|
case 414: $message = '414 Request-URI Too Long'; break;
|
||||||
case 415: $message = '415 Unsupported Media Type'; break;
|
case 415: $message = '415 Unsupported Media Type'; break;
|
||||||
case 416: $message = '416 Requested Range Not Satisfied'; break;
|
case 416: $message = '416 Requested Range Not Satisfied'; break;
|
||||||
case 417: $message = '417 Expectation Failed'; break;
|
case 417: $message = '417 Expectation Failed'; break;
|
||||||
case 418: $message = '418 I\'m a teapot'; break;
|
case 418: $message = '418 I\'m a teapot'; break;
|
||||||
case 420: $message = '420 Enhance Your Calm'; break;
|
case 420: $message = '420 Enhance Your Calm'; break;
|
||||||
case 422: $message = '422 Unprocessed Entity'; break;
|
case 422: $message = '422 Unprocessed Entity'; break;
|
||||||
case 423: $message = '423 Locked'; break;
|
case 423: $message = '423 Locked'; break;
|
||||||
case 424: $message = '424 Failed Dependency'; break;
|
case 424: $message = '424 Failed Dependency'; break;
|
||||||
case 425: $message = '425 Unordered Collection'; break;
|
case 425: $message = '425 Unordered Collection'; break;
|
||||||
case 426: $message = '426 Upgrade Required'; break;
|
case 426: $message = '426 Upgrade Required'; break;
|
||||||
case 428: $message = '428 Precondition Required'; break;
|
case 428: $message = '428 Precondition Required'; break;
|
||||||
case 429: $message = '429 Too Many Requests'; break;
|
case 429: $message = '429 Too Many Requests'; break;
|
||||||
case 431: $message = '431 Request Header Fields Too Large'; break;
|
case 431: $message = '431 Request Header Fields Too Large'; break;
|
||||||
case 444: $message = '444 No Response'; break;
|
case 444: $message = '444 No Response'; break;
|
||||||
case 449: $message = '449 Retry With'; break;
|
case 449: $message = '449 Retry With'; break;
|
||||||
case 450: $message = '450 Blocked by Windows Parental Controls'; break;
|
case 450: $message = '450 Blocked by Windows Parental Controls'; break;
|
||||||
case 451: $message = '451 Unavailable for Legal Reasons'; break;
|
case 451: $message = '451 Unavailable for Legal Reasons'; break;
|
||||||
case 494: $message = '494 Request Header Too Large'; break;
|
case 494: $message = '494 Request Header Too Large'; break;
|
||||||
case 495: $message = '495 Cert Error'; break;
|
case 495: $message = '495 Cert Error'; break;
|
||||||
case 496: $message = '496 No Cert'; break;
|
case 496: $message = '496 No Cert'; break;
|
||||||
case 497: $message = '497 HTTP to HTTPS'; break;
|
case 497: $message = '497 HTTP to HTTPS'; break;
|
||||||
case 499: $message = '499 Client Closed Request'; break;
|
case 499: $message = '499 Client Closed Request'; break;
|
||||||
// }}}
|
// }}}
|
||||||
// {{{ 5xx Server Error
|
// {{{ 5xx Server Error
|
||||||
case 500: $message = '500 Internal Server Error'; break;
|
case 500: $message = '500 Internal Server Error'; break;
|
||||||
case 501: $message = '501 Not Implemented'; break;
|
case 501: $message = '501 Not Implemented'; break;
|
||||||
case 502: $message = '502 Bad Gateway'; break;
|
case 502: $message = '502 Bad Gateway'; break;
|
||||||
case 503: $message = '503 Service Unavailable'; break;
|
case 503: $message = '503 Service Unavailable'; break;
|
||||||
case 504: $message = '504 Gateway Timeout'; break;
|
case 504: $message = '504 Gateway Timeout'; break;
|
||||||
case 505: $message = '505 HTTP Version Not Supported'; break;
|
case 505: $message = '505 HTTP Version Not Supported'; break;
|
||||||
case 506: $message = '506 Variant Also Negotiates'; break;
|
case 506: $message = '506 Variant Also Negotiates'; break;
|
||||||
case 507: $message = '507 Insufficient Storage'; break;
|
case 507: $message = '507 Insufficient Storage'; break;
|
||||||
case 508: $message = '508 Loop Detected'; break;
|
case 508: $message = '508 Loop Detected'; break;
|
||||||
case 509: $message = '509 Bandwidth Limit Exceeded'; break;
|
case 509: $message = '509 Bandwidth Limit Exceeded'; break;
|
||||||
case 510: $message = '510 Not Extended'; break;
|
case 510: $message = '510 Not Extended'; break;
|
||||||
case 511: $message = '511 Network Authentication Required'; break;
|
case 511: $message = '511 Network Authentication Required'; break;
|
||||||
case 598: $message = '598 Network read timeout error'; break;
|
case 598: $message = '598 Network read timeout error'; break;
|
||||||
case 599: $message = '599 Network connect timeout error'; break;
|
case 599: $message = '599 Network connect timeout error'; break;
|
||||||
// }}}
|
// }}}
|
||||||
default: $message = '200 OK'; break;
|
default: $message = '200 OK'; break;
|
||||||
}
|
}
|
||||||
|
|
||||||
header('HTTP/1.1 ' . $message, true, $code);
|
header('HTTP/1.1 ' . $message, true, $code);
|
||||||
header('Status: ' . $message, true, $code);
|
header('Status: ' . $message, true, $code);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -36,188 +36,187 @@
|
||||||
*/
|
*/
|
||||||
class Cache extends Object
|
class Cache extends Object
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Namespace (prefix)
|
* Namespace (prefix)
|
||||||
*
|
*
|
||||||
* @access private
|
* @access private
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
private $namespace = '';
|
private $namespace = '';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Servers
|
* Servers
|
||||||
*
|
*
|
||||||
* @access private
|
* @access private
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
private $servers = 0;
|
private $servers = 0;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connection resource to Memcached
|
* Connection resource to Memcached
|
||||||
*
|
*
|
||||||
* @access private
|
* @access private
|
||||||
* @var object
|
* @var object
|
||||||
*/
|
*/
|
||||||
private $connection = null;
|
private $connection = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
*
|
*
|
||||||
* Sets up our connection variables.
|
* Sets up our connection variables.
|
||||||
*
|
*
|
||||||
* @param string $hostname optional hostname to connect to
|
* @param string $hostname optional hostname to connect to
|
||||||
* @param string $database optional port to use
|
* @param string $database optional port to use
|
||||||
*/
|
*/
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
parent::__construct();
|
parent::__construct();
|
||||||
|
|
||||||
// @todo Shouldn't need the isset() but Travis is failing some tests
|
// @todo Shouldn't need the isset() but Travis is failing some tests
|
||||||
if (isset($this->config->pickles['cache']) && $this->config->pickles['cache'])
|
if (isset($this->config->pickles['cache']) && $this->config->pickles['cache'])
|
||||||
{
|
{
|
||||||
$datasources = $this->config->pickles['cache'];
|
$datasources = $this->config->pickles['cache'];
|
||||||
|
|
||||||
if (!is_array($datasources))
|
if (!is_array($datasources))
|
||||||
{
|
{
|
||||||
$datasources = [$datasources];
|
$datasources = [$datasources];
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->connection = new Memcache();
|
$this->connection = new Memcache();
|
||||||
|
|
||||||
foreach ($datasources as $name)
|
foreach ($datasources as $name)
|
||||||
{
|
{
|
||||||
if (isset($this->config->datasources[$name]))
|
if (isset($this->config->datasources[$name]))
|
||||||
{
|
{
|
||||||
$datasource = $this->config->datasources[$name];
|
$datasource = $this->config->datasources[$name];
|
||||||
|
|
||||||
$this->connection->addServer($datasource['hostname'], $datasource['port']);
|
$this->connection->addServer($datasource['hostname'], $datasource['port']);
|
||||||
$this->servers++;
|
$this->servers++;
|
||||||
|
|
||||||
if (isset($datasource['namespace']))
|
if (isset($datasource['namespace']))
|
||||||
{
|
{
|
||||||
$this->namespace = $datasource['namespace'];
|
$this->namespace = $datasource['namespace'];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($this->namespace != '')
|
if ($this->namespace != '')
|
||||||
{
|
{
|
||||||
$this->namespace .= '-';
|
$this->namespace .= '-';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Destructor
|
* Destructor
|
||||||
*
|
*
|
||||||
* Closes the connection when the object dies.
|
* Closes the connection when the object dies.
|
||||||
*/
|
*/
|
||||||
public function __destruct()
|
public function __destruct()
|
||||||
{
|
{
|
||||||
if ($this->servers)
|
if ($this->servers)
|
||||||
{
|
{
|
||||||
$this->connection->close();
|
$this->connection->close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get Instance
|
* Get Instance
|
||||||
*
|
*
|
||||||
* Let's the parent class do all the work.
|
* Let's the parent class do all the work.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $class name of the class to instantiate
|
* @param string $class name of the class to instantiate
|
||||||
* @return object self::$instance instance of the Cache class
|
* @return object self::$instance instance of the Cache class
|
||||||
*/
|
*/
|
||||||
public static function getInstance($class = 'Cache')
|
public static function getInstance($class = 'Cache')
|
||||||
{
|
{
|
||||||
return parent::getInstance($class);
|
return parent::getInstance($class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get Key
|
* Get Key
|
||||||
*
|
*
|
||||||
* Gets the value of the key(s) and returns it.
|
* Gets the value of the key(s) and returns it.
|
||||||
*
|
*
|
||||||
* @param mixed $keys key(s) to retrieve
|
* @param mixed $keys key(s) to retrieve
|
||||||
* @return mixed value(s) of the requested key(s), false if not set
|
* @return mixed value(s) of the requested key(s), false if not set
|
||||||
*/
|
*/
|
||||||
public function get($keys)
|
public function get($keys)
|
||||||
{
|
{
|
||||||
if (is_array($keys))
|
if (is_array($keys))
|
||||||
{
|
{
|
||||||
foreach ($keys as $index => $key)
|
foreach ($keys as $index => $key)
|
||||||
{
|
{
|
||||||
$keys[$index] = strtoupper($this->namespace . $key);
|
$keys[$index] = strtoupper($this->namespace . $key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$keys = strtoupper($this->namespace . $keys);
|
$keys = strtoupper($this->namespace . $keys);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->connection->get($keys);
|
return $this->connection->get($keys);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set Key
|
* Set Key
|
||||||
*
|
*
|
||||||
* Sets key to the specified value. I've found that compression can lead to
|
* Sets key to the specified value. I've found that compression can lead to
|
||||||
* issues with integers and can slow down the storage and retrieval of data
|
* issues with integers and can slow down the storage and retrieval of data
|
||||||
* (defeats the purpose of caching if you ask me) and isn't supported. I've
|
* (defeats the purpose of caching if you ask me) and isn't supported. I've
|
||||||
* also been burned by data inadvertantly being cached for infinity, but
|
* also been burned by data inadvertantly being cached for infinity, but
|
||||||
* have had great success caching data for a full day, hence defaulting the
|
* have had great success caching data for a full day, hence defaulting the
|
||||||
* expiration to a full day.
|
* expiration to a full day.
|
||||||
*
|
*
|
||||||
* @param string $key key to set
|
* @param string $key key to set
|
||||||
* @param mixed $value value to set
|
* @param mixed $value value to set
|
||||||
* @param integer $expiration optional expiration, defaults to 1 day
|
* @param integer $expiration optional expiration, defaults to 1 day
|
||||||
* @return boolean status of writing the data to the key
|
* @return boolean status of writing the data to the key
|
||||||
*/
|
*/
|
||||||
public function set($key, $value, $expire = Time::DAY)
|
public function set($key, $value, $expire = Time::DAY)
|
||||||
{
|
{
|
||||||
$key = strtoupper($key);
|
$key = strtoupper($key);
|
||||||
|
|
||||||
return $this->connection->set(strtoupper($this->namespace . $key), $value, 0, $expire);
|
return $this->connection->set(strtoupper($this->namespace . $key), $value, 0, $expire);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Delete Key
|
* Delete Key
|
||||||
*
|
*
|
||||||
* Deletes the specified key(s).
|
* Deletes the specified key(s).
|
||||||
*
|
*
|
||||||
* @param mixed $keys key(s) to delete
|
* @param mixed $keys key(s) to delete
|
||||||
* @return boolean status of deleting the key
|
* @return boolean status of deleting the key
|
||||||
*/
|
*/
|
||||||
public function delete($keys)
|
public function delete($keys)
|
||||||
{
|
{
|
||||||
if (!is_array($keys))
|
if (!is_array($keys))
|
||||||
{
|
{
|
||||||
$keys = [$keys];
|
$keys = [$keys];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Memcache() doesn't let you pass an array to delete all records the same way you can with get()
|
// Memcache() doesn't let you pass an array to delete all records the same way you can with get()
|
||||||
foreach ($keys as $key)
|
foreach ($keys as $key)
|
||||||
{
|
{
|
||||||
$this->connection->delete(strtoupper($this->namespace . $key));
|
$this->connection->delete(strtoupper($this->namespace . $key));
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Increment Key
|
* Increment Key
|
||||||
*
|
*
|
||||||
* Increments the value of an existing key.
|
* Increments the value of an existing key.
|
||||||
*
|
*
|
||||||
* @param string $key key to increment
|
* @param string $key key to increment
|
||||||
* @return boolean status of incrementing the key
|
* @return boolean status of incrementing the key
|
||||||
* @todo Check if it's set as Memcache() doesn't and won't inc if it doesn't exist
|
* @todo Check if it's set as Memcache() doesn't and won't inc if it doesn't exist
|
||||||
*/
|
*/
|
||||||
public function increment($key)
|
public function increment($key)
|
||||||
{
|
{
|
||||||
return $this->connection->increment(strtoupper($this->namespace . $key));
|
return $this->connection->increment(strtoupper($this->namespace . $key));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -29,228 +29,227 @@
|
||||||
*/
|
*/
|
||||||
class Config extends Object
|
class Config extends Object
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Config data
|
* Config data
|
||||||
*
|
*
|
||||||
* @var array
|
* @var array
|
||||||
*/
|
*/
|
||||||
public $data = [];
|
public $data = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
*
|
*
|
||||||
* Calls the parent constructor and loads the passed file.
|
* Calls the parent constructor and loads the passed file.
|
||||||
*/
|
*/
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
parent::__construct();
|
parent::__construct();
|
||||||
|
|
||||||
$filename = SITE_PATH . 'config.php';
|
$filename = SITE_PATH . 'config.php';
|
||||||
$environments = false;
|
$environments = false;
|
||||||
$environment = false;
|
$environment = false;
|
||||||
$is_cli = !isset($_SERVER['REQUEST_METHOD']);
|
$is_cli = !isset($_SERVER['REQUEST_METHOD']);
|
||||||
|
|
||||||
|
|
||||||
// Sanity checks the config file
|
// Sanity checks the config file
|
||||||
if (file_exists($filename) && is_file($filename) && is_readable($filename))
|
if (file_exists($filename) && is_file($filename) && is_readable($filename))
|
||||||
{
|
{
|
||||||
require $filename;
|
require $filename;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Checks that we have the config array
|
// Checks that we have the config array
|
||||||
if (isset($config))
|
if (isset($config))
|
||||||
{
|
{
|
||||||
// Determines the environment
|
// Determines the environment
|
||||||
if (isset($config['environment']))
|
if (isset($config['environment']))
|
||||||
{
|
{
|
||||||
$environment = $config['environment'];
|
$environment = $config['environment'];
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
if (isset($config['environments']) && is_array($config['environments']))
|
if (isset($config['environments']) && is_array($config['environments']))
|
||||||
{
|
{
|
||||||
$environments = $config['environments'];
|
$environments = $config['environments'];
|
||||||
|
|
||||||
// If we're on the CLI, check an environment was even passed in
|
// If we're on the CLI, check an environment was even passed in
|
||||||
// @todo is checking for argc enough?
|
// @todo is checking for argc enough?
|
||||||
if ($is_cli && $_SERVER['argc'] < 2)
|
if ($is_cli && $_SERVER['argc'] < 2)
|
||||||
{
|
{
|
||||||
throw new Exception('You must pass an environment (e.g. php script.php <environment>)');
|
throw new Exception('You must pass an environment (e.g. php script.php <environment>)');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Loops through the environments and tries to match on IP or name
|
// Loops through the environments and tries to match on IP or name
|
||||||
foreach ($config['environments'] as $name => $hosts)
|
foreach ($config['environments'] as $name => $hosts)
|
||||||
{
|
{
|
||||||
if (!is_array($hosts))
|
if (!is_array($hosts))
|
||||||
{
|
{
|
||||||
$hosts = [$hosts];
|
$hosts = [$hosts];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tries to determine the environment name
|
// Tries to determine the environment name
|
||||||
foreach ($hosts as $host)
|
foreach ($hosts as $host)
|
||||||
{
|
{
|
||||||
if ($is_cli)
|
if ($is_cli)
|
||||||
{
|
{
|
||||||
// Checks the first argument on the command line
|
// Checks the first argument on the command line
|
||||||
if ($_SERVER['argv'][1] == $name)
|
if ($_SERVER['argv'][1] == $name)
|
||||||
{
|
{
|
||||||
$environment = $name;
|
$environment = $name;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Exact match
|
// Exact match
|
||||||
if ((preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $host)
|
if ((preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $host)
|
||||||
&& $_SERVER['SERVER_ADDR'] == $host)
|
&& $_SERVER['SERVER_ADDR'] == $host)
|
||||||
|| (isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == $host))
|
|| (isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == $host))
|
||||||
{
|
{
|
||||||
$environment = $name;
|
$environment = $name;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
// Fuzzy match
|
// Fuzzy match
|
||||||
elseif (substr($host,0,1) == '/' && (preg_match($host, $_SERVER['SERVER_NAME'], $matches) > 0 || preg_match($host, $_SERVER['HTTP_HOST'], $matches) > 0))
|
elseif (substr($host,0,1) == '/' && (preg_match($host, $_SERVER['SERVER_NAME'], $matches) > 0 || preg_match($host, $_SERVER['HTTP_HOST'], $matches) > 0))
|
||||||
{
|
{
|
||||||
$environments[$name] = $matches[0];
|
$environments[$name] = $matches[0];
|
||||||
$environment = $name;
|
$environment = $name;
|
||||||
$config['environments'][$name] = $matches[0];
|
$config['environments'][$name] = $matches[0];
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Flattens the array based on the environment
|
// Flattens the array based on the environment
|
||||||
$this->data = $this->flatten($environment, $config);
|
$this->data = $this->flatten($environment, $config);
|
||||||
|
|
||||||
// Restore environments value
|
// Restore environments value
|
||||||
if ($environments != false)
|
if ($environments != false)
|
||||||
{
|
{
|
||||||
$this->data['environments'] = $environments;
|
$this->data['environments'] = $environments;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sets the environment if it's not set already
|
// Sets the environment if it's not set already
|
||||||
if (!isset($this->data['environment']))
|
if (!isset($this->data['environment']))
|
||||||
{
|
{
|
||||||
$this->data['environment'] = $environment;
|
$this->data['environment'] = $environment;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Defaults profiler to true if it doesn't match an option exactly
|
// Defaults profiler to true if it doesn't match an option exactly
|
||||||
if (isset($this->data['pickles']['profiler']))
|
if (isset($this->data['pickles']['profiler']))
|
||||||
{
|
{
|
||||||
// If we have an array convert to a string
|
// If we have an array convert to a string
|
||||||
if (is_array($this->data['pickles']['profiler']))
|
if (is_array($this->data['pickles']['profiler']))
|
||||||
{
|
{
|
||||||
$this->data['pickles']['profiler'] = implode(',', $this->data['pickles']['profiler']);
|
$this->data['pickles']['profiler'] = implode(',', $this->data['pickles']['profiler']);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$this->data['pickles']['profiler'] = false;
|
$this->data['pickles']['profiler'] = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Defaults expected PICKLES options to false
|
// Defaults expected PICKLES options to false
|
||||||
foreach (['cache', 'logging', 'minify'] as $variable)
|
foreach (['cache', 'logging', 'minify'] as $variable)
|
||||||
{
|
{
|
||||||
if (!isset($this->data['pickles'][$variable]))
|
if (!isset($this->data['pickles'][$variable]))
|
||||||
{
|
{
|
||||||
$this->data['pickles'][$variable] = false;
|
$this->data['pickles'][$variable] = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Creates constants for the security levels
|
// Creates constants for the security levels
|
||||||
if (isset($this->data['security']['levels']) && is_array($this->data['security']['levels']))
|
if (isset($this->data['security']['levels']) && is_array($this->data['security']['levels']))
|
||||||
{
|
{
|
||||||
foreach ($this->data['security']['levels'] as $value => $name)
|
foreach ($this->data['security']['levels'] as $value => $name)
|
||||||
{
|
{
|
||||||
$constant = 'SECURITY_LEVEL_' . strtoupper($name);
|
$constant = 'SECURITY_LEVEL_' . strtoupper($name);
|
||||||
|
|
||||||
// Checks if constant is already defined, and throws an error
|
// Checks if constant is already defined, and throws an error
|
||||||
if (defined($constant))
|
if (defined($constant))
|
||||||
{
|
{
|
||||||
throw new Exception('The constant ' . $constant . ' is already defined');
|
throw new Exception('The constant ' . $constant . ' is already defined');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
define($constant, $value);
|
define($constant, $value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flatten
|
* Flatten
|
||||||
*
|
*
|
||||||
* Flattens the configuration array around the specified environment.
|
* Flattens the configuration array around the specified environment.
|
||||||
*
|
*
|
||||||
* @param string $environment selected environment
|
* @param string $environment selected environment
|
||||||
* @param array $array configuration error to flatten
|
* @param array $array configuration error to flatten
|
||||||
* @return array flattened configuration array
|
* @return array flattened configuration array
|
||||||
*/
|
*/
|
||||||
public function flatten($environment, $array)
|
public function flatten($environment, $array)
|
||||||
{
|
{
|
||||||
if (is_array($array))
|
if (is_array($array))
|
||||||
{
|
{
|
||||||
foreach ($array as $key => $value)
|
foreach ($array as $key => $value)
|
||||||
{
|
{
|
||||||
if (is_array($value))
|
if (is_array($value))
|
||||||
{
|
{
|
||||||
if (isset($value[$environment]))
|
if (isset($value[$environment]))
|
||||||
{
|
{
|
||||||
$value = $value[$environment];
|
$value = $value[$environment];
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$value = $this->flatten($environment, $value);
|
$value = $this->flatten($environment, $value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$array[$key] = $value;
|
$array[$key] = $value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $array;
|
return $array;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get instance of the object
|
* Get instance of the object
|
||||||
*
|
*
|
||||||
* Let's the parent class do all the work
|
* Let's the parent class do all the work
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $class name of the class to instantiate
|
* @param string $class name of the class to instantiate
|
||||||
* @return object self::$instance instance of the Config class
|
* @return object self::$instance instance of the Config class
|
||||||
*/
|
*/
|
||||||
public static function getInstance($class = 'Config')
|
public static function getInstance($class = 'Config')
|
||||||
{
|
{
|
||||||
return parent::getInstance($class);
|
return parent::getInstance($class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Magic Getter Method
|
* Magic Getter Method
|
||||||
*
|
*
|
||||||
* Attempts to load the config variable. If it's not set, will override
|
* Attempts to load the config variable. If it's not set, will override
|
||||||
* the variable with boolean false.
|
* the variable with boolean false.
|
||||||
*
|
*
|
||||||
* @param string $name name of the variable requested
|
* @param string $name name of the variable requested
|
||||||
* @return mixed value of the variable or boolean false
|
* @return mixed value of the variable or boolean false
|
||||||
*/
|
*/
|
||||||
public function __get($name)
|
public function __get($name)
|
||||||
{
|
{
|
||||||
if (!isset($this->data[$name]))
|
if (!isset($this->data[$name]))
|
||||||
{
|
{
|
||||||
$this->data[$name] = false;
|
$this->data[$name] = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->data[$name];
|
return $this->data[$name];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -27,392 +27,394 @@
|
||||||
*/
|
*/
|
||||||
class Controller extends Object
|
class Controller extends Object
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
*
|
*
|
||||||
* To save a few keystrokes, the Controller is executed as part of the
|
* To save a few keystrokes, the Controller is executed as part of the
|
||||||
* constructor instead of via a method. You either want the Controller or
|
* constructor instead of via a method. You either want the Controller or
|
||||||
* you don't.
|
* you don't.
|
||||||
*/
|
*/
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
parent::__construct();
|
parent::__construct();
|
||||||
|
|
||||||
// Generate a generic "site down" message if the site is set to be disabled
|
// Generate a generic "site down" message if the site is set to be disabled
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// @todo Clean this up to be just a single sanity check
|
// @todo Clean this up to be just a single sanity check
|
||||||
if (isset($this->config->pickles['disabled']) && $this->config->pickles['disabled'])
|
if (isset($this->config->pickles['disabled']) && $this->config->pickles['disabled'])
|
||||||
{
|
{
|
||||||
$custom_template = SITE_TEMPLATE_PATH . '__shared/maintenance.phtml';
|
$custom_template = SITE_TEMPLATE_PATH . '__shared/maintenance.phtml';
|
||||||
|
|
||||||
if (file_exists($custom_template))
|
if (file_exists($custom_template))
|
||||||
{
|
{
|
||||||
require_once $custom_template;
|
require_once $custom_template;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
echo '
|
echo '
|
||||||
<h1>Down for Maintenance</h1>
|
<h1>Down for Maintenance</h1>
|
||||||
<p>' . $_SERVER['SERVER_NAME'] . ' is currently down for maintenance. Please check back in a few minutes.</p>
|
<p>
|
||||||
<p>Additionally, a custom maintenance template was not found.</p>
|
' . $_SERVER['SERVER_NAME'] . ' is currently down for maintenance.
|
||||||
<hr>
|
Please check back in a few minutes.
|
||||||
<em>Powered by <a href="https://github.com/joshtronic/pickles">PICKLES</a></em>
|
</p>
|
||||||
';
|
<p>Additionally, a custom maintenance template was not found.</p>
|
||||||
}
|
<hr>
|
||||||
|
<em>Powered by <a href="https://github.com/joshtronic/pickles">PICKLES</a></em>
|
||||||
|
';
|
||||||
|
}
|
||||||
|
|
||||||
throw new Exception();
|
throw new Exception();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Checks for attributes passed in the URI
|
// Checks for attributes passed in the URI
|
||||||
if (strstr($_REQUEST['request'], ':'))
|
if (strstr($_REQUEST['request'], ':'))
|
||||||
{
|
{
|
||||||
$parts = explode('/', $_REQUEST['request']);
|
$parts = explode('/', $_REQUEST['request']);
|
||||||
$_REQUEST['request'] = '';
|
$_REQUEST['request'] = '';
|
||||||
|
|
||||||
foreach ($parts as $part)
|
foreach ($parts as $part)
|
||||||
{
|
{
|
||||||
if (strstr($part, ':'))
|
if (strstr($part, ':'))
|
||||||
{
|
{
|
||||||
list($variable, $value) = explode(':', $part);
|
list($variable, $value) = explode(':', $part);
|
||||||
Browser::set($variable, $value);
|
Browser::set($variable, $value);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$_REQUEST['request'] .= ($_REQUEST['request'] ? '/' : '') . $part;
|
$_REQUEST['request'] .= ($_REQUEST['request'] ? '/' : '') . $part;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Catches requests that aren't lowercase
|
// Catches requests that aren't lowercase
|
||||||
$lowercase_request = strtolower($_REQUEST['request']);
|
$lowercase_request = strtolower($_REQUEST['request']);
|
||||||
|
|
||||||
if ($_REQUEST['request'] != $lowercase_request)
|
if ($_REQUEST['request'] != $lowercase_request)
|
||||||
{
|
{
|
||||||
// @todo Rework the Browser class to handle the 301 (perhaps redirect301()) to not break other code
|
// @todo Rework the Browser class to handle the 301 (perhaps redirect301()) to not break other code
|
||||||
header('Location: ' . substr_replace($_SERVER['REQUEST_URI'], $lowercase_request, 1, strlen($lowercase_request)), true, 301);
|
header('Location: ' . substr_replace($_SERVER['REQUEST_URI'], $lowercase_request, 1, strlen($lowercase_request)), true, 301);
|
||||||
throw new Exception();
|
throw new Exception();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Grabs the requested page
|
// Grabs the requested page
|
||||||
$request = $_REQUEST['request'];
|
$request = $_REQUEST['request'];
|
||||||
|
|
||||||
// Loads the module's information
|
// Loads the module's information
|
||||||
$module_class = strtr($request, '/', '_');
|
$module_class = strtr($request, '/', '_');
|
||||||
$module_filename = SITE_MODULE_PATH . $request . '.php';
|
$module_filename = SITE_MODULE_PATH . $request . '.php';
|
||||||
$module_exists = file_exists($module_filename);
|
$module_exists = file_exists($module_filename);
|
||||||
|
|
||||||
// Attempts to instantiate the requested module
|
// Attempts to instantiate the requested module
|
||||||
if ($module_exists)
|
if ($module_exists)
|
||||||
{
|
{
|
||||||
if (class_exists($module_class))
|
if (class_exists($module_class))
|
||||||
{
|
{
|
||||||
$module = new $module_class;
|
$module = new $module_class;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// No module instantiated, load up a generic Module
|
// No module instantiated, load up a generic Module
|
||||||
if (!isset($module))
|
if (!isset($module))
|
||||||
{
|
{
|
||||||
$module = new Module();
|
$module = new Module();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determines if we need to serve over HTTP or HTTPS
|
// Determines if we need to serve over HTTP or HTTPS
|
||||||
if ($module->secure == false && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'])
|
if ($module->secure == false && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'])
|
||||||
{
|
{
|
||||||
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], true, 301);
|
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], true, 301);
|
||||||
throw new Exception();
|
throw new Exception();
|
||||||
}
|
}
|
||||||
elseif ($module->secure == true && (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == false))
|
elseif ($module->secure == true && (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == false))
|
||||||
{
|
{
|
||||||
header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], true, 301);
|
header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], true, 301);
|
||||||
throw new Exception();
|
throw new Exception();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validates security level
|
// Validates security level
|
||||||
if ($module->security)
|
if ($module->security)
|
||||||
{
|
{
|
||||||
$is_authenticated = false;
|
$is_authenticated = false;
|
||||||
|
|
||||||
if (is_array($module->security))
|
if (is_array($module->security))
|
||||||
{
|
{
|
||||||
$module_security = $module->security;
|
$module_security = $module->security;
|
||||||
$security_check_class = 'isLevel';
|
$security_check_class = 'isLevel';
|
||||||
|
|
||||||
// Checks the type and validates it
|
// Checks the type and validates it
|
||||||
if (isset($module_security['type']))
|
if (isset($module_security['type']))
|
||||||
{
|
{
|
||||||
$security_check_type = strtoupper($module_security['type']);
|
$security_check_type = strtoupper($module_security['type']);
|
||||||
|
|
||||||
if (in_array($security_check_type, ['IS', 'HAS', 'BETWEEN']))
|
if (in_array($security_check_type, ['IS', 'HAS', 'BETWEEN']))
|
||||||
{
|
{
|
||||||
$security_check_class = $security_check_type;
|
$security_check_class = $security_check_type;
|
||||||
}
|
}
|
||||||
|
|
||||||
unset($module_security['type']);
|
unset($module_security['type']);
|
||||||
}
|
}
|
||||||
|
|
||||||
$module_security_levels = [];
|
$module_security_levels = [];
|
||||||
|
|
||||||
// If there's a level(s) key use it
|
// If there's a level(s) key use it
|
||||||
foreach (['level', 'levels'] as $security_level_key)
|
foreach (['level', 'levels'] as $security_level_key)
|
||||||
{
|
{
|
||||||
if (isset($module_security[$security_level_key]))
|
if (isset($module_security[$security_level_key]))
|
||||||
{
|
{
|
||||||
if (is_array($module_security[$security_level_key]))
|
if (is_array($module_security[$security_level_key]))
|
||||||
{
|
{
|
||||||
$module_security_levels = array_merge($module_security_levels, $module_security[$security_level_key]);
|
$module_security_levels = array_merge($module_security_levels, $module_security[$security_level_key]);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$module_security_levels[] = $module_security[$security_level_key];
|
$module_security_levels[] = $module_security[$security_level_key];
|
||||||
}
|
}
|
||||||
|
|
||||||
unset($module_security[$security_level_key]);
|
unset($module_security[$security_level_key]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Assume everything left in the array is a level and add it to the array
|
// Assume everything left in the array is a level and add it to the array
|
||||||
array_merge($module_security_levels, $module_security);
|
array_merge($module_security_levels, $module_security);
|
||||||
$security_level_count = count($module_security_levels);
|
$security_level_count = count($module_security_levels);
|
||||||
|
|
||||||
switch ($security_check_class)
|
switch ($security_check_class)
|
||||||
{
|
{
|
||||||
// @todo Thinking of removing this?
|
// @todo Thinking of removing this?
|
||||||
case 'BETWEEN':
|
case 'BETWEEN':
|
||||||
if ($security_level_count == 2)
|
if ($security_level_count == 2)
|
||||||
{
|
{
|
||||||
$is_authenticated = Security::betweenLevel($module_security_levels[0], array_pop($module_security_levels));
|
$is_authenticated = Security::betweenLevel($module_security_levels[0], array_pop($module_security_levels));
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'HAS':
|
case 'HAS':
|
||||||
if ($security_level_count)
|
if ($security_level_count)
|
||||||
{
|
{
|
||||||
$is_authenticated = Security::hasLevel($module_security_levels);
|
$is_authenticated = Security::hasLevel($module_security_levels);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'IS':
|
case 'IS':
|
||||||
if ($security_level_count)
|
if ($security_level_count)
|
||||||
{
|
{
|
||||||
$is_authenticated = Security::isLevel($module_security_levels);
|
$is_authenticated = Security::isLevel($module_security_levels);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$is_authenticated = Security::isLevel($module->security);
|
$is_authenticated = Security::isLevel($module->security);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!$is_authenticated)
|
if (!$is_authenticated)
|
||||||
{
|
{
|
||||||
if ($_SERVER['REQUEST_METHOD'] == 'POST')
|
if ($_SERVER['REQUEST_METHOD'] == 'POST')
|
||||||
{
|
{
|
||||||
// @todo Perhaps I could force a logout / redirect to the login page
|
// @todo Perhaps I could force a logout / redirect to the login page
|
||||||
throw new Exception('{"status": "error", "message": "You are not properly authenticated, try logging out and back in."}');
|
throw new Exception('{"status": "error", "message": "You are not properly authenticated, try logging out and back in."}');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Sets variable for the destination
|
// Sets variable for the destination
|
||||||
$_SESSION['__pickles']['login']['destination'] = $_REQUEST['request'] ? $_REQUEST['request'] : '/';
|
$_SESSION['__pickles']['login']['destination'] = $_REQUEST['request'] ? $_REQUEST['request'] : '/';
|
||||||
|
|
||||||
// Redirect to login page
|
// Redirect to login page
|
||||||
Browser::redirect('/login');
|
Browser::redirect('/login');
|
||||||
|
|
||||||
// Resolves testing error due to undefined $output
|
// Resolves testing error due to undefined $output
|
||||||
$output = '';
|
$output = '';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Gets the profiler status
|
// Gets the profiler status
|
||||||
$profiler = $this->config->pickles['profiler'];
|
$profiler = $this->config->pickles['profiler'];
|
||||||
$profiler = $profiler === true || stripos($profiler, 'timers') !== false;
|
$profiler = $profiler === true || stripos($profiler, 'timers') !== false;
|
||||||
|
|
||||||
$default_method = '__default';
|
$default_method = '__default';
|
||||||
$role_method = null;
|
$role_method = null;
|
||||||
|
|
||||||
if (isset($_SESSION['__pickles']['security']['role']) && !String::isEmpty($_SESSION['__pickles']['security']['role']))
|
if (isset($_SESSION['__pickles']['security']['role']) && !String::isEmpty($_SESSION['__pickles']['security']['role']))
|
||||||
{
|
{
|
||||||
$role_method = '__default_' . $_SESSION['__pickles']['security']['role'];
|
$role_method = '__default_' . $_SESSION['__pickles']['security']['role'];
|
||||||
|
|
||||||
if (method_exists($module, $role_method))
|
if (method_exists($module, $role_method))
|
||||||
{
|
{
|
||||||
$default_method = $role_method;
|
$default_method = $role_method;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attempts to execute the default method
|
// Attempts to execute the default method
|
||||||
// @todo Seems a bit redundant, refactor
|
// @todo Seems a bit redundant, refactor
|
||||||
if ($default_method == $role_method || method_exists($module, $default_method))
|
if ($default_method == $role_method || method_exists($module, $default_method))
|
||||||
{
|
{
|
||||||
// Starts a timer before the module is executed
|
// Starts a timer before the module is executed
|
||||||
if ($profiler)
|
if ($profiler)
|
||||||
{
|
{
|
||||||
Profiler::timer('module ' . $default_method);
|
Profiler::timer('module ' . $default_method);
|
||||||
}
|
}
|
||||||
|
|
||||||
$valid_request = false;
|
$valid_request = false;
|
||||||
$error_message = 'An unexpected error has occurred.';
|
$error_message = 'An unexpected error has occurred.';
|
||||||
|
|
||||||
// Determines if the request method is valid for this request
|
// Determines if the request method is valid for this request
|
||||||
if ($module->method)
|
if ($module->method)
|
||||||
{
|
{
|
||||||
if (!is_array($module->method))
|
if (!is_array($module->method))
|
||||||
{
|
{
|
||||||
$module->method = [$module->method];
|
$module->method = [$module->method];
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($module->method as $method)
|
foreach ($module->method as $method)
|
||||||
{
|
{
|
||||||
if ($_SERVER['REQUEST_METHOD'] == $method)
|
if ($_SERVER['REQUEST_METHOD'] == $method)
|
||||||
{
|
{
|
||||||
$valid_request = true;
|
$valid_request = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!$valid_request)
|
if (!$valid_request)
|
||||||
{
|
{
|
||||||
// @todo Should probably utilize that AJAX flag to determine the type of return
|
// @todo Should probably utilize that AJAX flag to determine the type of return
|
||||||
$error_message = 'There was a problem with your request method.';
|
$error_message = 'There was a problem with your request method.';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$valid_request = true;
|
$valid_request = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
$valid_form_input = true;
|
$valid_form_input = true;
|
||||||
|
|
||||||
if ($valid_request && $module->validate)
|
if ($valid_request && $module->validate)
|
||||||
{
|
{
|
||||||
$validation_errors = $module->__validate();
|
$validation_errors = $module->__validate();
|
||||||
|
|
||||||
if ($validation_errors)
|
if ($validation_errors)
|
||||||
{
|
{
|
||||||
$error_message = implode(' ', $validation_errors);
|
$error_message = implode(' ', $validation_errors);
|
||||||
$valid_form_input = false;
|
$valid_form_input = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Note to Self: When building in caching will need to let the
|
* Note to Self: When building in caching will need to let the
|
||||||
* module know to use the cache, either passing in a variable
|
* module know to use the cache, either passing in a variable
|
||||||
* or setting it on the object
|
* or setting it on the object
|
||||||
*/
|
*/
|
||||||
if ($valid_request && $valid_form_input)
|
if ($valid_request && $valid_form_input)
|
||||||
{
|
{
|
||||||
$module_return = $module->$default_method();
|
$module_return = $module->$default_method();
|
||||||
|
|
||||||
if (!is_array($module_return))
|
if (!is_array($module_return))
|
||||||
{
|
{
|
||||||
$module_return = $module->return;
|
$module_return = $module->return;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$module_return = array_merge($module_return, $module->return);
|
$module_return = array_merge($module_return, $module->return);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stops the module timer
|
// Stops the module timer
|
||||||
if ($profiler)
|
if ($profiler)
|
||||||
{
|
{
|
||||||
Profiler::timer('module ' . $default_method);
|
Profiler::timer('module ' . $default_method);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Checks if we have any templates
|
// Checks if we have any templates
|
||||||
$parent_template = $module->template;
|
$parent_template = $module->template;
|
||||||
$template_exists = $this->validateTemplates($module, $parent_template);
|
$template_exists = $this->validateTemplates($module, $parent_template);
|
||||||
|
|
||||||
// No templates? 404 that shit
|
// No templates? 404 that shit
|
||||||
if (!$module_exists && !$template_exists)
|
if (!$module_exists && !$template_exists)
|
||||||
{
|
{
|
||||||
Browser::status(404);
|
Browser::status(404);
|
||||||
$_REQUEST['request'] = '__shared/404';
|
$_REQUEST['request'] = '__shared/404';
|
||||||
|
|
||||||
if (!$this->validateTemplates($module, $parent_template))
|
if (!$this->validateTemplates($module, $parent_template))
|
||||||
{
|
{
|
||||||
throw new Exception('
|
throw new Exception('
|
||||||
<h1>Not Found</h1>
|
<h1>Not Found</h1>
|
||||||
<p>The requested URL /' . $request . ' was not found on this server.</p>
|
<p>The requested URL /' . $request . ' was not found on this server.</p>
|
||||||
<p>Additionally, a custom error template was not found.</p>
|
<p>Additionally, a custom error template was not found.</p>
|
||||||
<hr>
|
<hr>
|
||||||
<em>Powered by <a href="https://github.com/joshtronic/pickles">PICKLES</a></em>
|
<em>Powered by <a href="https://github.com/joshtronic/pickles">PICKLES</a></em>
|
||||||
');
|
');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// @todo Should simplify this, give Display direct acess to
|
// @todo Should simplify this, give Display direct acess to
|
||||||
// $module instead of all these variable assignment
|
// $module instead of all these variable assignment
|
||||||
$display = new Display();
|
$display = new Display();
|
||||||
$display->output = $module->output;
|
$display->output = $module->output;
|
||||||
$display->templates = $module->template;
|
$display->templates = $module->template;
|
||||||
$display->module = isset($module_return) ? $module_return : ['status' => 'error', 'message' => $error_message];
|
$display->module = isset($module_return) ? $module_return : ['status' => 'error', 'message' => $error_message];
|
||||||
|
|
||||||
// @todo Check for $module->meta variable first, then remove entirely when sites are updated
|
// @todo Check for $module->meta variable first, then remove entirely when sites are updated
|
||||||
$display->meta = [
|
$display->meta = [
|
||||||
'title' => $module->title,
|
'title' => $module->title,
|
||||||
'description' => $module->description,
|
'description' => $module->description,
|
||||||
'keywords' => $module->keywords
|
'keywords' => $module->keywords
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Starts a timer for the display rendering
|
// Starts a timer for the display rendering
|
||||||
if ($profiler)
|
if ($profiler)
|
||||||
{
|
{
|
||||||
Profiler::timer('display render');
|
Profiler::timer('display render');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Renders the content
|
// Renders the content
|
||||||
$output = $display->render();
|
$output = $display->render();
|
||||||
|
|
||||||
// Stops the display timer
|
// Stops the display timer
|
||||||
if ($profiler)
|
if ($profiler)
|
||||||
{
|
{
|
||||||
Profiler::timer('display render');
|
Profiler::timer('display render');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception $e)
|
catch (Exception $e)
|
||||||
{
|
{
|
||||||
$output = $e->getMessage();
|
$output = $e->getMessage();
|
||||||
}
|
}
|
||||||
|
|
||||||
echo $output;
|
echo $output;
|
||||||
|
|
||||||
// Display the Profiler's report if the stars are aligned
|
// Display the Profiler's report if the stars are aligned
|
||||||
if ($this->config->pickles['profiler'])
|
if ($this->config->pickles['profiler'])
|
||||||
{
|
{
|
||||||
Profiler::report();
|
Profiler::report();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// @todo Document me
|
// @todo Document me
|
||||||
private function validateTemplates(&$module, $parent_template)
|
private function validateTemplates(&$module, $parent_template)
|
||||||
{
|
{
|
||||||
$templates = [
|
$templates = [
|
||||||
SITE_TEMPLATE_PATH . '__shared/' . $parent_template . '.phtml',
|
SITE_TEMPLATE_PATH . '__shared/' . $parent_template . '.phtml',
|
||||||
SITE_TEMPLATE_PATH . $_REQUEST['request'] . '.phtml',
|
SITE_TEMPLATE_PATH . $_REQUEST['request'] . '.phtml',
|
||||||
];
|
];
|
||||||
|
|
||||||
$module->template = [];
|
$module->template = [];
|
||||||
$child_exists = file_exists($templates[1]);
|
$child_exists = file_exists($templates[1]);
|
||||||
|
|
||||||
if (file_exists($templates[0]) && $child_exists)
|
if (file_exists($templates[0]) && $child_exists)
|
||||||
{
|
{
|
||||||
$module->template = $templates;
|
$module->template = $templates;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
elseif ($child_exists)
|
elseif ($child_exists)
|
||||||
{
|
{
|
||||||
$module->template = [$templates[1]];
|
$module->template = [$templates[1]];
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -23,101 +23,100 @@
|
||||||
*/
|
*/
|
||||||
class Convert
|
class Convert
|
||||||
{
|
{
|
||||||
// {{{ Array to XML
|
// {{{ Array to XML
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Array to XML
|
* Array to XML
|
||||||
*
|
*
|
||||||
* Converts an array into XML tags (recursive). This method expects the
|
* Converts an array into XML tags (recursive). This method expects the
|
||||||
* passed array to be formatted very specifically to accomodate the fact
|
* passed array to be formatted very specifically to accomodate the fact
|
||||||
* that an array's format isn't quite the same as well-formed XML.
|
* that an array's format isn't quite the same as well-formed XML.
|
||||||
*
|
*
|
||||||
* Input Array =
|
* Input Array =
|
||||||
* ['children' => [
|
* ['children' => [
|
||||||
* 'child' => [
|
* 'child' => [
|
||||||
* ['name' => 'Wendy Darling'],
|
* ['name' => 'Wendy Darling'],
|
||||||
* ['name' => 'John Darling'],
|
* ['name' => 'John Darling'],
|
||||||
* ['name' => 'Michael Darling'],
|
* ['name' => 'Michael Darling'],
|
||||||
* ],
|
* ],
|
||||||
* ]]
|
* ]]
|
||||||
*
|
*
|
||||||
* Output XML =
|
* Output XML =
|
||||||
* <children>
|
* <children>
|
||||||
* <child><name>Wendy Darling</name></child>
|
* <child><name>Wendy Darling</name></child>
|
||||||
* <child><name>John Darling</name></child>
|
* <child><name>John Darling</name></child>
|
||||||
* <child><name>Michael Darling</name></child>
|
* <child><name>Michael Darling</name></child>
|
||||||
* </children>
|
* </children>
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param array $array array to convert into XML
|
* @param array $array array to convert into XML
|
||||||
* @return string generated XML
|
* @return string generated XML
|
||||||
*/
|
*/
|
||||||
public static function arrayToXML($array, $format = false, $level = 0)
|
public static function arrayToXML($array, $format = false, $level = 0)
|
||||||
{
|
{
|
||||||
$xml = '';
|
$xml = '';
|
||||||
|
|
||||||
if (is_array($array))
|
if (is_array($array))
|
||||||
{
|
{
|
||||||
foreach ($array as $node => $value)
|
foreach ($array as $node => $value)
|
||||||
{
|
{
|
||||||
// Checks if the value is an array
|
// Checks if the value is an array
|
||||||
if (is_array($value))
|
if (is_array($value))
|
||||||
{
|
{
|
||||||
foreach ($value as $node2 => $value2)
|
foreach ($value as $node2 => $value2)
|
||||||
{
|
{
|
||||||
if (is_array($value2))
|
if (is_array($value2))
|
||||||
{
|
{
|
||||||
// Nest the value if the node is an integer
|
// Nest the value if the node is an integer
|
||||||
$new_value = (is_int($node2) ? $value2 : [$node2 => $value2]);
|
$new_value = (is_int($node2) ? $value2 : [$node2 => $value2]);
|
||||||
|
|
||||||
$xml .= ($format ? str_repeat("\t", $level) : '');
|
$xml .= ($format ? str_repeat("\t", $level) : '');
|
||||||
$xml .= '<' . $node . '>' . ($format ? "\n" : '');
|
$xml .= '<' . $node . '>' . ($format ? "\n" : '');
|
||||||
$xml .= self::arrayToXML($new_value, $format, $level + 1);
|
$xml .= self::arrayToXML($new_value, $format, $level + 1);
|
||||||
$xml .= ($format ? str_repeat("\t", $level) : '');
|
$xml .= ($format ? str_repeat("\t", $level) : '');
|
||||||
$xml .= '</' . $node . '>' . ($format ? "\n" : '');
|
$xml .= '</' . $node . '>' . ($format ? "\n" : '');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
if (is_int($node2))
|
if (is_int($node2))
|
||||||
{
|
{
|
||||||
$node2 = $node;
|
$node2 = $node;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Checks for special characters
|
// Checks for special characters
|
||||||
if (htmlspecialchars($value2) != $value2)
|
if (htmlspecialchars($value2) != $value2)
|
||||||
{
|
{
|
||||||
$xml .= ($format ? str_repeat("\t", $level) : '');
|
$xml .= ($format ? str_repeat("\t", $level) : '');
|
||||||
$xml .= '<' . $node2 . '><![CDATA[' . $value2 . ']]></' . $node2 . '>' . ($format ? "\n" : '');
|
$xml .= '<' . $node2 . '><![CDATA[' . $value2 . ']]></' . $node2 . '>' . ($format ? "\n" : '');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$xml .= ($format ? str_repeat("\t", $level) : '');
|
$xml .= ($format ? str_repeat("\t", $level) : '');
|
||||||
$xml .= '<' . $node2 . '>' . $value2 . '</' . $node2 . '>' . ($format ? "\n" : '');
|
$xml .= '<' . $node2 . '>' . $value2 . '</' . $node2 . '>' . ($format ? "\n" : '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Checks for special characters
|
// Checks for special characters
|
||||||
if (htmlspecialchars($value) != $value)
|
if (htmlspecialchars($value) != $value)
|
||||||
{
|
{
|
||||||
$xml .= ($format ? str_repeat("\t", $level) : '');
|
$xml .= ($format ? str_repeat("\t", $level) : '');
|
||||||
$xml .= '<' . $node . '><![CDATA[' . $value . ']]></' . $node . '>' . ($format ? "\n" : '');
|
$xml .= '<' . $node . '><![CDATA[' . $value . ']]></' . $node . '>' . ($format ? "\n" : '');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$xml .= ($format ? str_repeat("\t", $level) : '');
|
$xml .= ($format ? str_repeat("\t", $level) : '');
|
||||||
$xml .= '<' . $node . '>' . $value . '</' . $node . '>' . ($format ? "\n" : '');
|
$xml .= '<' . $node . '>' . $value . '</' . $node . '>' . ($format ? "\n" : '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $xml;
|
return $xml;
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -26,396 +26,395 @@
|
||||||
*/
|
*/
|
||||||
class Database extends Object
|
class Database extends Object
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* DSN format
|
* DSN format
|
||||||
*
|
*
|
||||||
* @access protected
|
* @access protected
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
protected $dsn;
|
protected $dsn;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* PDO Attributes
|
* PDO Attributes
|
||||||
*
|
*
|
||||||
* @access protected
|
* @access protected
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
protected $attributes = [
|
protected $attributes = [
|
||||||
PDO::ATTR_PERSISTENT => true,
|
PDO::ATTR_PERSISTENT => true,
|
||||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||||
PDO::NULL_EMPTY_STRING => true,
|
PDO::NULL_EMPTY_STRING => true,
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Driver
|
* Driver
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
public $driver = null;
|
public $driver = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Hostname for the server
|
* Hostname for the server
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
public $hostname = 'localhost';
|
public $hostname = 'localhost';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Port number for the server
|
* Port number for the server
|
||||||
*
|
*
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
public $port = null;
|
public $port = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* UNIX socket for the server
|
* UNIX socket for the server
|
||||||
*
|
*
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
public $socket = null;
|
public $socket = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Username for the server
|
* Username for the server
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
public $username = null;
|
public $username = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Password for the server
|
* Password for the server
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
public $password = null;
|
public $password = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Database name for the server
|
* Database name for the server
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
public $database = null;
|
public $database = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Whether or not to use caching
|
* Whether or not to use caching
|
||||||
*
|
*
|
||||||
* @var boolean
|
* @var boolean
|
||||||
*/
|
*/
|
||||||
public $cache = false;
|
public $cache = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connection resource
|
* Connection resource
|
||||||
*
|
*
|
||||||
* @var object
|
* @var object
|
||||||
*/
|
*/
|
||||||
public $connection = null;
|
public $connection = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Results object for the executed statement
|
* Results object for the executed statement
|
||||||
*
|
*
|
||||||
* @var object
|
* @var object
|
||||||
*/
|
*/
|
||||||
public $results = null;
|
public $results = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get Instance
|
* Get Instance
|
||||||
*
|
*
|
||||||
* Instantiates a new instance of the Database class or returns the
|
* Instantiates a new instance of the Database class or returns the
|
||||||
* previously instantiated copy.
|
* previously instantiated copy.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $datasource_name name of the datasource
|
* @param string $datasource_name name of the datasource
|
||||||
* @return object instance of the class
|
* @return object instance of the class
|
||||||
*/
|
*/
|
||||||
public static function getInstance($datasource_name = false)
|
public static function getInstance($datasource_name = false)
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
|
|
||||||
// Tries to load a datasource if one wasn't specified
|
// Tries to load a datasource if one wasn't specified
|
||||||
if (!$datasource_name)
|
if (!$datasource_name)
|
||||||
{
|
{
|
||||||
if (isset($config->pickles['datasource']))
|
if (isset($config->pickles['datasource']))
|
||||||
{
|
{
|
||||||
$datasource_name = $config->pickles['datasource'];
|
$datasource_name = $config->pickles['datasource'];
|
||||||
}
|
}
|
||||||
elseif (is_array($config->datasources))
|
elseif (is_array($config->datasources))
|
||||||
{
|
{
|
||||||
$datasources = $config->datasources;
|
$datasources = $config->datasources;
|
||||||
|
|
||||||
foreach ($datasources as $name => $datasource)
|
foreach ($datasources as $name => $datasource)
|
||||||
{
|
{
|
||||||
if (isset($datasource['driver']))
|
if (isset($datasource['driver']))
|
||||||
{
|
{
|
||||||
$datasource_name = $name;
|
$datasource_name = $name;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attempts to validate the datasource
|
// Attempts to validate the datasource
|
||||||
if ($datasource_name)
|
if ($datasource_name)
|
||||||
{
|
{
|
||||||
if (!isset(self::$instances['Database'][$datasource_name]))
|
if (!isset(self::$instances['Database'][$datasource_name]))
|
||||||
{
|
{
|
||||||
if (!isset($config->datasources[$datasource_name]))
|
if (!isset($config->datasources[$datasource_name]))
|
||||||
{
|
{
|
||||||
throw new Exception('The specified datasource is not defined in the config.');
|
throw new Exception('The specified datasource is not defined in the config.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$datasource = $config->datasources[$datasource_name];
|
$datasource = $config->datasources[$datasource_name];
|
||||||
|
|
||||||
if (!isset($datasource['driver']))
|
if (!isset($datasource['driver']))
|
||||||
{
|
{
|
||||||
throw new Exception('The specified datasource lacks a driver.');
|
throw new Exception('The specified datasource lacks a driver.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$datasource['driver'] = strtolower($datasource['driver']);
|
$datasource['driver'] = strtolower($datasource['driver']);
|
||||||
|
|
||||||
// Checks the driver is legit and scrubs the name
|
// Checks the driver is legit and scrubs the name
|
||||||
switch ($datasource['driver'])
|
switch ($datasource['driver'])
|
||||||
{
|
{
|
||||||
case 'pdo_mysql':
|
case 'pdo_mysql':
|
||||||
$attributes = [
|
$attributes = [
|
||||||
'dsn' => 'mysql:host=[[hostname]];port=[[port]];unix_socket=[[socket]];dbname=[[database]]',
|
'dsn' => 'mysql:host=[[hostname]];port=[[port]];unix_socket=[[socket]];dbname=[[database]]',
|
||||||
'port' => 3306,
|
'port' => 3306,
|
||||||
];
|
];
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'pdo_pgsql':
|
case 'pdo_pgsql':
|
||||||
$attributes = [
|
$attributes = [
|
||||||
'dsn' => 'pgsql:host=[[hostname]];port=[[port]];dbname=[[database]];user=[[username]];password=[[password]]',
|
'dsn' => 'pgsql:host=[[hostname]];port=[[port]];dbname=[[database]];user=[[username]];password=[[password]]',
|
||||||
'port' => 5432,
|
'port' => 5432,
|
||||||
];
|
];
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'pdo_sqlite':
|
case 'pdo_sqlite':
|
||||||
$attributes = ['dsn' => 'sqlite:[[hostname]]'];
|
$attributes = ['dsn' => 'sqlite:[[hostname]]'];
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
throw new Exception('Datasource driver "' . $datasource['driver'] . '" is invalid');
|
throw new Exception('Datasource driver "' . $datasource['driver'] . '" is invalid');
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Instantiates our database class
|
// Instantiates our database class
|
||||||
$instance = new Database();
|
$instance = new Database();
|
||||||
|
|
||||||
// Sets our database parameters
|
// Sets our database parameters
|
||||||
if (is_array($datasource))
|
if (is_array($datasource))
|
||||||
{
|
{
|
||||||
$datasource = array_merge($attributes, $datasource);
|
$datasource = array_merge($attributes, $datasource);
|
||||||
|
|
||||||
foreach ($datasource as $variable => $value)
|
foreach ($datasource as $variable => $value)
|
||||||
{
|
{
|
||||||
$instance->$variable = $value;
|
$instance->$variable = $value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Caches the instance for possible reuse later
|
// Caches the instance for possible reuse later
|
||||||
self::$instances['Database'][$datasource_name] = $instance;
|
self::$instances['Database'][$datasource_name] = $instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Returns the instance
|
// Returns the instance
|
||||||
return self::$instances['Database'][$datasource_name];
|
return self::$instances['Database'][$datasource_name];
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Opens database connection
|
* Opens database connection
|
||||||
*
|
*
|
||||||
* Establishes a connection to the database based on the set configuration
|
* Establishes a connection to the database based on the set configuration
|
||||||
* options.
|
* options.
|
||||||
*
|
*
|
||||||
* @return boolean true on success, throws an exception overwise
|
* @return boolean true on success, throws an exception overwise
|
||||||
*/
|
*/
|
||||||
public function open()
|
public function open()
|
||||||
{
|
{
|
||||||
if ($this->connection === null)
|
if ($this->connection === null)
|
||||||
{
|
{
|
||||||
switch ($this->driver)
|
switch ($this->driver)
|
||||||
{
|
{
|
||||||
case 'pdo_mysql':
|
case 'pdo_mysql':
|
||||||
// Resolves "Invalid UTF-8 sequence" issues when encoding as JSON
|
// Resolves "Invalid UTF-8 sequence" issues when encoding as JSON
|
||||||
// @todo Didn't resolve that issue, borked some other characters though
|
// @todo Didn't resolve that issue, borked some other characters though
|
||||||
//$this->attributes[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8';
|
//$this->attributes[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'pdo_pgsql':
|
case 'pdo_pgsql':
|
||||||
// This combats a bug: https://bugs.php.net/bug.php?id=62571&edit=1
|
// This combats a bug: https://bugs.php.net/bug.php?id=62571&edit=1
|
||||||
$this->attributes[PDO::ATTR_PERSISTENT] = false;
|
$this->attributes[PDO::ATTR_PERSISTENT] = false;
|
||||||
|
|
||||||
// This allows for multiple prepared queries
|
// This allows for multiple prepared queries
|
||||||
$this->attributes[PDO::ATTR_EMULATE_PREPARES] = true;
|
$this->attributes[PDO::ATTR_EMULATE_PREPARES] = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isset($this->username, $this->password, $this->database))
|
if (isset($this->username, $this->password, $this->database))
|
||||||
{
|
{
|
||||||
// Swaps out any variables with values in the DSN
|
// Swaps out any variables with values in the DSN
|
||||||
$this->dsn = str_replace(
|
$this->dsn = str_replace(
|
||||||
['[[hostname]]', '[[port]]', '[[socket]]', '[[username]]', '[[password]]', '[[database]]'],
|
['[[hostname]]', '[[port]]', '[[socket]]', '[[username]]', '[[password]]', '[[database]]'],
|
||||||
[$this->hostname, $this->port, $this->socket, $this->username, $this->password, $this->database],
|
[$this->hostname, $this->port, $this->socket, $this->username, $this->password, $this->database],
|
||||||
$this->dsn
|
$this->dsn
|
||||||
);
|
);
|
||||||
|
|
||||||
// Strips any empty parameters in the DSN
|
// Strips any empty parameters in the DSN
|
||||||
$this->dsn = str_replace(['host=;', 'port=;', 'unix_socket=;'], '', $this->dsn);
|
$this->dsn = str_replace(['host=;', 'port=;', 'unix_socket=;'], '', $this->dsn);
|
||||||
|
|
||||||
// Attempts to establish a connection
|
// Attempts to establish a connection
|
||||||
$this->connection = new PDO($this->dsn, $this->username, $this->password, $this->attributes);
|
$this->connection = new PDO($this->dsn, $this->username, $this->password, $this->attributes);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
throw new Exception('There was an error loading the database configuration.');
|
throw new Exception('There was an error loading the database configuration.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Closes database connection
|
* Closes database connection
|
||||||
*
|
*
|
||||||
* Sets the connection to null regardless of state.
|
* Sets the connection to null regardless of state.
|
||||||
*
|
*
|
||||||
* @return boolean always true
|
* @return boolean always true
|
||||||
*/
|
*/
|
||||||
public function close()
|
public function close()
|
||||||
{
|
{
|
||||||
$this->connection = null;
|
$this->connection = null;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Executes an SQL Statement
|
* Executes an SQL Statement
|
||||||
*
|
*
|
||||||
* Executes a standard or prepared query based on passed parameters. All
|
* Executes a standard or prepared query based on passed parameters. All
|
||||||
* queries are logged to a file as well as timed and logged in the
|
* queries are logged to a file as well as timed and logged in the
|
||||||
* execution time is over 1 second.
|
* execution time is over 1 second.
|
||||||
*
|
*
|
||||||
* @param string $sql statement to execute
|
* @param string $sql statement to execute
|
||||||
* @param array $input_parameters optional key/values to be bound
|
* @param array $input_parameters optional key/values to be bound
|
||||||
* @param boolean $force_slow optional, force slow query logging
|
* @param boolean $force_slow optional, force slow query logging
|
||||||
* @return integer ID of the last inserted row or sequence number
|
* @return integer ID of the last inserted row or sequence number
|
||||||
*/
|
*/
|
||||||
public function execute($sql, $input_parameters = null, $force_slow = false)
|
public function execute($sql, $input_parameters = null, $force_slow = false)
|
||||||
{
|
{
|
||||||
$this->open();
|
$this->open();
|
||||||
|
|
||||||
if (isset($this->config->pickles['logging']) && $this->config->pickles['logging'])
|
if (isset($this->config->pickles['logging']) && $this->config->pickles['logging'])
|
||||||
{
|
{
|
||||||
$loggable_query = $sql;
|
$loggable_query = $sql;
|
||||||
|
|
||||||
if ($input_parameters != null)
|
if ($input_parameters != null)
|
||||||
{
|
{
|
||||||
$loggable_query .= ' -- ' . json_encode($input_parameters);
|
$loggable_query .= ' -- ' . json_encode($input_parameters);
|
||||||
}
|
}
|
||||||
|
|
||||||
Log::query($loggable_query);
|
Log::query($loggable_query);
|
||||||
}
|
}
|
||||||
|
|
||||||
$sql = trim($sql);
|
$sql = trim($sql);
|
||||||
|
|
||||||
// Checks if the query is blank
|
// Checks if the query is blank
|
||||||
if ($sql != '')
|
if ($sql != '')
|
||||||
{
|
{
|
||||||
// Builds out stack trace for queries
|
// Builds out stack trace for queries
|
||||||
$files = [];
|
$files = [];
|
||||||
|
|
||||||
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
|
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
|
||||||
krsort($backtrace);
|
krsort($backtrace);
|
||||||
|
|
||||||
foreach ($backtrace as $file)
|
foreach ($backtrace as $file)
|
||||||
{
|
{
|
||||||
if (isset($file['class'], $file['line']))
|
if (isset($file['class'], $file['line']))
|
||||||
{
|
{
|
||||||
$files[] = $file['class'] . ':' . $file['line'];
|
$files[] = $file['class'] . ':' . $file['line'];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$sql .= "\n" . '/* [' . implode('|', $files) . '] */';
|
$sql .= "\n" . '/* [' . implode('|', $files) . '] */';
|
||||||
|
|
||||||
// Establishes if we're working on an EXPLAIN
|
// Establishes if we're working on an EXPLAIN
|
||||||
if (Profiler::enabled('explains'))
|
if (Profiler::enabled('explains'))
|
||||||
{
|
{
|
||||||
$explain = preg_match('/^SELECT /i', $sql);
|
$explain = preg_match('/^SELECT /i', $sql);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$explain = null;
|
$explain = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Executes a standard query
|
// Executes a standard query
|
||||||
if ($input_parameters === null)
|
if ($input_parameters === null)
|
||||||
{
|
{
|
||||||
// Explains the query
|
// Explains the query
|
||||||
if ($explain)
|
if ($explain)
|
||||||
{
|
{
|
||||||
$explain = $this->fetch('EXPLAIN ' . $sql);
|
$explain = $this->fetch('EXPLAIN ' . $sql);
|
||||||
}
|
}
|
||||||
|
|
||||||
$start_time = microtime(true);
|
$start_time = microtime(true);
|
||||||
$this->results = $this->connection->query($sql);
|
$this->results = $this->connection->query($sql);
|
||||||
}
|
}
|
||||||
// Executes a prepared statement
|
// Executes a prepared statement
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Explains the query
|
// Explains the query
|
||||||
if ($explain)
|
if ($explain)
|
||||||
{
|
{
|
||||||
$explain = $this->fetch('EXPLAIN ' . $sql, $input_parameters);
|
$explain = $this->fetch('EXPLAIN ' . $sql, $input_parameters);
|
||||||
}
|
}
|
||||||
|
|
||||||
$start_time = microtime(true);
|
$start_time = microtime(true);
|
||||||
$this->results = $this->connection->prepare($sql);
|
$this->results = $this->connection->prepare($sql);
|
||||||
$this->results->execute($input_parameters);
|
$this->results->execute($input_parameters);
|
||||||
}
|
}
|
||||||
|
|
||||||
$end_time = microtime(true);
|
$end_time = microtime(true);
|
||||||
$duration = $end_time - $start_time;
|
$duration = $end_time - $start_time;
|
||||||
|
|
||||||
if ($duration >= 1 || $force_slow)
|
if ($duration >= 1 || $force_slow)
|
||||||
{
|
{
|
||||||
Log::slowQuery($duration . ' seconds: ' . $loggable_query);
|
Log::slowQuery($duration . ' seconds: ' . $loggable_query);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Logs the information to the profiler
|
// Logs the information to the profiler
|
||||||
if (Profiler::enabled('explains', 'queries'))
|
if (Profiler::enabled('explains', 'queries'))
|
||||||
{
|
{
|
||||||
Profiler::logQuery($sql, $input_parameters, (isset($explain) ? $explain : false), $duration);
|
Profiler::logQuery($sql, $input_parameters, (isset($explain) ? $explain : false), $duration);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
throw new Exception('No query to execute.');
|
throw new Exception('No query to execute.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->connection->lastInsertId();
|
return $this->connection->lastInsertId();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch records from the database
|
* Fetch records from the database
|
||||||
*
|
*
|
||||||
* @param string $sql statement to be executed
|
* @param string $sql statement to be executed
|
||||||
* @param array $input_parameters optional key/values to be bound
|
* @param array $input_parameters optional key/values to be bound
|
||||||
* @param string $return_type optional type of return set
|
* @param string $return_type optional type of return set
|
||||||
* @return mixed based on return type
|
* @return mixed based on return type
|
||||||
*/
|
*/
|
||||||
public function fetch($sql = null, $input_parameters = null)
|
public function fetch($sql = null, $input_parameters = null)
|
||||||
{
|
{
|
||||||
$this->open();
|
$this->open();
|
||||||
|
|
||||||
if ($sql !== null)
|
if ($sql !== null)
|
||||||
{
|
{
|
||||||
$this->execute($sql, $input_parameters);
|
$this->execute($sql, $input_parameters);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pulls the results based on the type
|
// Pulls the results based on the type
|
||||||
$results = $this->results->fetchAll(PDO::FETCH_ASSOC);
|
$results = $this->results->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
return $results;
|
return $results;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -23,19 +23,18 @@
|
||||||
*/
|
*/
|
||||||
class Date
|
class Date
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Age
|
* Age
|
||||||
*
|
*
|
||||||
* Calculates age based on the passed date.
|
* Calculates age based on the passed date.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $date birth / inception date
|
* @param string $date birth / inception date
|
||||||
* @return integer $age number of years old
|
* @return integer $age number of years old
|
||||||
*/
|
*/
|
||||||
public static function age($date)
|
public static function age($date)
|
||||||
{
|
{
|
||||||
return Time::age($date);
|
return Time::age($date);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -22,183 +22,183 @@
|
||||||
*/
|
*/
|
||||||
class Display extends Object
|
class Display extends Object
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Return Type
|
* Return Type
|
||||||
*
|
*
|
||||||
* This class supports loading a PHP template, displaying JSON, XML and an
|
* This class supports loading a PHP template, displaying JSON, XML and an
|
||||||
* RSS flavored XML. Inside your modules you can specify either a string or
|
* RSS flavored XML. Inside your modules you can specify either a string or
|
||||||
* array. Possible values include "template", "json", "xml" and "rss".
|
* array. Possible values include "template", "json", "xml" and "rss".
|
||||||
* Default behavior is to try to load a template and fallback to displaying
|
* Default behavior is to try to load a template and fallback to displaying
|
||||||
* JSON. The "template" option always takes precedence when used with the
|
* JSON. The "template" option always takes precedence when used with the
|
||||||
* other types.
|
* other types.
|
||||||
*
|
*
|
||||||
* @var mixed string or array to determine how to return
|
* @var mixed string or array to determine how to return
|
||||||
*/
|
*/
|
||||||
public $return = ['template', 'json'];
|
public $return = ['template', 'json'];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Templates
|
* Templates
|
||||||
*
|
*
|
||||||
* Templates are found in the ./templates directory of your site. The
|
* Templates are found in the ./templates directory of your site. The
|
||||||
* template workflow is to load ./templates/__shared/index.phtml and you
|
* template workflow is to load ./templates/__shared/index.phtml and you
|
||||||
* would set that template up to require $this->template, the path and
|
* would set that template up to require $this->template, the path and
|
||||||
* filename for the module template (named based on the structure of the
|
* filename for the module template (named based on the structure of the
|
||||||
* requested URI. Inside your module you can specify the basename of the
|
* requested URI. Inside your module you can specify the basename of the
|
||||||
* parent template you would like to use or false to not use a parent
|
* parent template you would like to use or false to not use a parent
|
||||||
* template.
|
* template.
|
||||||
*
|
*
|
||||||
* @var string or boolean false the basename of the parent template
|
* @var string or boolean false the basename of the parent template
|
||||||
*/
|
*/
|
||||||
public $templates = false;
|
public $templates = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Meta Data
|
* Meta Data
|
||||||
*
|
*
|
||||||
* An array of meta data that you want exposed to the template. Currently
|
* An array of meta data that you want exposed to the template. Currently
|
||||||
* you set the meta data from inside your module using the class variables
|
* you set the meta data from inside your module using the class variables
|
||||||
* title, description and keywords. The newer [preferred] method is to
|
* title, description and keywords. The newer [preferred] method is to
|
||||||
* set an array in your module using the meta variable using title,
|
* set an array in your module using the meta variable using title,
|
||||||
* description and keywords as the keys. You can also specify any other
|
* description and keywords as the keys. You can also specify any other
|
||||||
* meta keys in the array that you would like to be exposed to your
|
* meta keys in the array that you would like to be exposed to your
|
||||||
* templates. The meta data is only used by TEMPLATE and RSS return types.
|
* templates. The meta data is only used by TEMPLATE and RSS return types.
|
||||||
*/
|
*/
|
||||||
public $meta = [];
|
public $meta = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Module Data
|
* Module Data
|
||||||
*
|
*
|
||||||
* Any data the module returns or is assigned inside of the module will
|
* Any data the module returns or is assigned inside of the module will
|
||||||
* be available here and exposed to the template.
|
* be available here and exposed to the template.
|
||||||
*/
|
*/
|
||||||
public $module = null;
|
public $module = null;
|
||||||
|
|
||||||
public function render()
|
public function render()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// Starts up the buffer so we can capture it
|
// Starts up the buffer so we can capture it
|
||||||
ob_start();
|
ob_start();
|
||||||
|
|
||||||
if (!is_array($this->return))
|
if (!is_array($this->return))
|
||||||
{
|
{
|
||||||
$this->return = [$this->return];
|
$this->return = [$this->return];
|
||||||
}
|
}
|
||||||
|
|
||||||
$return_json = $return_rss = $return_template = $return_xml = false;
|
$return_json = $return_rss = $return_template = $return_xml = false;
|
||||||
|
|
||||||
foreach ($this->return as $return)
|
foreach ($this->return as $return)
|
||||||
{
|
{
|
||||||
$variable = 'return_' . $return;
|
$variable = 'return_' . $return;
|
||||||
$$variable = true;
|
$$variable = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Makes sure the return type is valid
|
// Makes sure the return type is valid
|
||||||
if (!$return_json && !$return_rss && !$return_template && !$return_xml)
|
if (!$return_json && !$return_rss && !$return_template && !$return_xml)
|
||||||
{
|
{
|
||||||
throw new Exception('Invalid return type.');
|
throw new Exception('Invalid return type.');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Checks for the PHPSESSID in the query string
|
// Checks for the PHPSESSID in the query string
|
||||||
if (stripos($_SERVER['REQUEST_URI'], '?PHPSESSID=') === false)
|
if (stripos($_SERVER['REQUEST_URI'], '?PHPSESSID=') === false)
|
||||||
{
|
{
|
||||||
// XHTML compliancy stuff
|
// XHTML compliancy stuff
|
||||||
// @todo Wonder if this could be yanked now that we're in HTML5 land
|
// @todo Wonder if this could be yanked now that we're in HTML5 land
|
||||||
ini_set('arg_separator.output', '&');
|
ini_set('arg_separator.output', '&');
|
||||||
ini_set('url_rewriter.tags', 'a=href,area=href,frame=src,input=src,fieldset=');
|
ini_set('url_rewriter.tags', 'a=href,area=href,frame=src,input=src,fieldset=');
|
||||||
|
|
||||||
header('Content-type: text/html; charset=UTF-8');
|
header('Content-type: text/html; charset=UTF-8');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Redirect so Google knows to index the page without the session ID
|
// Redirect so Google knows to index the page without the session ID
|
||||||
list($request_uri, $phpsessid) = explode('?PHPSESSID=', $_SERVER['REQUEST_URI'], 2);
|
list($request_uri, $phpsessid) = explode('?PHPSESSID=', $_SERVER['REQUEST_URI'], 2);
|
||||||
header('HTTP/1.1 301 Moved Permanently');
|
header('HTTP/1.1 301 Moved Permanently');
|
||||||
header('Location: ' . $request_uri);
|
header('Location: ' . $request_uri);
|
||||||
|
|
||||||
throw new Exception('Requested URI contains PHPSESSID, redirecting.');
|
throw new Exception('Requested URI contains PHPSESSID, redirecting.');
|
||||||
}
|
}
|
||||||
|
|
||||||
// @todo Derrive CSS and JS from _REQUEST['request'] no need to pass around
|
// @todo Derrive CSS and JS from _REQUEST['request'] no need to pass around
|
||||||
|
|
||||||
$loaded = false;
|
$loaded = false;
|
||||||
|
|
||||||
if ($return_template)
|
if ($return_template)
|
||||||
{
|
{
|
||||||
// Determines if we're using a custom class or not
|
// Determines if we're using a custom class or not
|
||||||
$dynamic_class = (class_exists('CustomDynamic') ? 'CustomDynamic' : 'Dynamic');
|
$dynamic_class = (class_exists('CustomDynamic') ? 'CustomDynamic' : 'Dynamic');
|
||||||
$form_class = (class_exists('CustomForm') ? 'CustomForm' : 'Form');
|
$form_class = (class_exists('CustomForm') ? 'CustomForm' : 'Form');
|
||||||
$html_class = (class_exists('CustomHTML') ? 'CustomHTML' : 'HTML');
|
$html_class = (class_exists('CustomHTML') ? 'CustomHTML' : 'HTML');
|
||||||
|
|
||||||
// Exposes some objects and variables to the local scope of the template
|
// Exposes some objects and variables to the local scope of the template
|
||||||
$this->request = $this->js_file = $_REQUEST['request'];
|
$this->request = $this->js_file = $_REQUEST['request'];
|
||||||
// @todo replace _ with - as it's more appropriate for CSS naming
|
// @todo replace _ with - as it's more appropriate for CSS naming
|
||||||
$this->css_class = strtr($this->request, '/', '_');
|
$this->css_class = strtr($this->request, '/', '_');
|
||||||
|
|
||||||
// @todo Remove the magic $__variable when all sites are ported
|
// @todo Remove the magic $__variable when all sites are ported
|
||||||
$__config = $this->config;
|
$__config = $this->config;
|
||||||
$__css_class = $this->css_class;
|
$__css_class = $this->css_class;
|
||||||
$__js_file = $this->js_file;
|
$__js_file = $this->js_file;
|
||||||
$__meta = $this->meta;
|
$__meta = $this->meta;
|
||||||
$__module = $this->module;
|
$__module = $this->module;
|
||||||
|
|
||||||
$__dynamic = $this->dynamic = new $dynamic_class();
|
$__dynamic = $this->dynamic = new $dynamic_class();
|
||||||
$__form = $this->form = new $form_class();
|
$__form = $this->form = new $form_class();
|
||||||
$__html = $this->html = new $html_class();
|
$__html = $this->html = new $html_class();
|
||||||
|
|
||||||
// Checks for the parent template and tries to load it
|
// Checks for the parent template and tries to load it
|
||||||
if ($this->templates)
|
if ($this->templates)
|
||||||
{
|
{
|
||||||
$profiler = $this->config->pickles['profiler'];
|
$profiler = $this->config->pickles['profiler'];
|
||||||
$profiler = $profiler === true || stripos($profiler, 'timers') !== false;
|
$profiler = $profiler === true || stripos($profiler, 'timers') !== false;
|
||||||
|
|
||||||
// Starts a timer for the loading of the template
|
// Starts a timer for the loading of the template
|
||||||
if ($profiler)
|
if ($profiler)
|
||||||
{
|
{
|
||||||
Profiler::timer('loading template');
|
Profiler::timer('loading template');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Assigns old variable
|
// Assigns old variable
|
||||||
$required_template = $this->templates[0];
|
$required_template = $this->templates[0];
|
||||||
$__template = $this->template = end($this->templates);
|
$__template = $this->template = end($this->templates);
|
||||||
$loaded = require_once $required_template;
|
$loaded = require_once $required_template;
|
||||||
|
|
||||||
// Stops the template loading timer
|
// Stops the template loading timer
|
||||||
if ($profiler)
|
if ($profiler)
|
||||||
{
|
{
|
||||||
Profiler::timer('loading template');
|
Profiler::timer('loading template');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!$loaded)
|
if (!$loaded)
|
||||||
{
|
{
|
||||||
if ($return_json)
|
if ($return_json)
|
||||||
{
|
{
|
||||||
echo json_encode($this->module, isset($_REQUEST['pretty']) ? JSON_PRETTY_PRINT : false);
|
$pretty = isset($_REQUEST['pretty']) ? JSON_PRETTY_PRINT : false;
|
||||||
}
|
echo json_encode($this->module, $pretty);
|
||||||
elseif ($return_xml)
|
}
|
||||||
{
|
elseif ($return_xml)
|
||||||
echo Convert::arrayToXML($this->module, isset($_REQUEST['pretty']));
|
{
|
||||||
}
|
echo Convert::arrayToXML($this->module, isset($_REQUEST['pretty']));
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Grabs the buffer so we can massage it a bit
|
// Grabs the buffer so we can massage it a bit
|
||||||
$buffer = ob_get_clean();
|
$buffer = ob_get_clean();
|
||||||
|
|
||||||
// Kills any whitespace and HTML comments in templates
|
// Kills any whitespace and HTML comments in templates
|
||||||
if ($loaded)
|
if ($loaded)
|
||||||
{
|
{
|
||||||
// The BSA exception is because their system sucks and demands there be comments present
|
// The BSA exception is because their system sucks and demands there be comments present
|
||||||
$buffer = preg_replace(['/^[\s]+/m', '/<!--(?:(?!BuySellAds).)+-->/U'], '', $buffer);
|
$buffer = preg_replace(['/^[\s]+/m', '/<!--(?:(?!BuySellAds).)+-->/U'], '', $buffer);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $buffer;
|
return $buffer;
|
||||||
}
|
}
|
||||||
catch (Exception $e)
|
catch (Exception $e)
|
||||||
{
|
{
|
||||||
return $e->getMessage();
|
return $e->getMessage();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -23,122 +23,121 @@
|
||||||
*/
|
*/
|
||||||
class Distance
|
class Distance
|
||||||
{
|
{
|
||||||
// {{{ Call Static
|
// {{{ Call Static
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Call Static
|
* Call Static
|
||||||
*
|
*
|
||||||
* Magic method to power the unit conversion without much code.
|
* Magic method to power the unit conversion without much code.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $method name of the static method being called
|
* @param string $method name of the static method being called
|
||||||
* @param array $arguments array of the passed arguments
|
* @param array $arguments array of the passed arguments
|
||||||
* @return mixed converted units or false
|
* @return mixed converted units or false
|
||||||
*/
|
*/
|
||||||
public static function __callStatic($method, $arguments)
|
public static function __callStatic($method, $arguments)
|
||||||
{
|
{
|
||||||
$pieces = explode('to', strtolower($method));
|
$pieces = explode('to', strtolower($method));
|
||||||
|
|
||||||
if (count($pieces) == 2 && $pieces[1])
|
if (count($pieces) == 2 && $pieces[1])
|
||||||
{
|
{
|
||||||
return Distance::convertUnit($arguments[0], $pieces[0], $pieces[1]);
|
return Distance::convertUnit($arguments[0], $pieces[0], $pieces[1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
// {{{ Convert Unit
|
// {{{ Convert Unit
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert Unit
|
* Convert Unit
|
||||||
*
|
*
|
||||||
* Converts a distance from one unit to another.
|
* Converts a distance from one unit to another.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param mixed $distance starting distance
|
* @param mixed $distance starting distance
|
||||||
* @param string $from starting unit
|
* @param string $from starting unit
|
||||||
* @param string $to ending unit
|
* @param string $to ending unit
|
||||||
* @return mixed
|
* @return mixed
|
||||||
*/
|
*/
|
||||||
private static function convertUnit($distance, $from, $to)
|
private static function convertUnit($distance, $from, $to)
|
||||||
{
|
{
|
||||||
$multiplier = 1;
|
$multiplier = 1;
|
||||||
|
|
||||||
switch ($from)
|
switch ($from)
|
||||||
{
|
{
|
||||||
case 'kilometers':
|
case 'kilometers':
|
||||||
switch ($to)
|
switch ($to)
|
||||||
{
|
{
|
||||||
case 'miles': $multiplier = 0.621371; break;
|
case 'miles': $multiplier = 0.621371; break;
|
||||||
case 'meters': $multiplier = 1000; break;
|
case 'meters': $multiplier = 1000; break;
|
||||||
case 'yards': $multiplier = 1093.61; break;
|
case 'yards': $multiplier = 1093.61; break;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'miles':
|
case 'miles':
|
||||||
switch ($to)
|
switch ($to)
|
||||||
{
|
{
|
||||||
case 'kilometers': $multiplier = 1.60934; break;
|
case 'kilometers': $multiplier = 1.60934; break;
|
||||||
case 'meters': $multiplier = 1609.34; break;
|
case 'meters': $multiplier = 1609.34; break;
|
||||||
case 'yards': $multiplier = 1760; break;
|
case 'yards': $multiplier = 1760; break;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'meters':
|
case 'meters':
|
||||||
switch ($to)
|
switch ($to)
|
||||||
{
|
{
|
||||||
case 'kilometers': $multiplier = 0.001; break;
|
case 'kilometers': $multiplier = 0.001; break;
|
||||||
case 'miles': $multiplier = 0.000621371; break;
|
case 'miles': $multiplier = 0.000621371; break;
|
||||||
case 'yards': $multiplier = 1.09361; break;
|
case 'yards': $multiplier = 1.09361; break;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $distance * $multiplier;
|
return $distance * $multiplier;
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
// {{{ Calculate Distance
|
// {{{ Calculate Distance
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Calculate Distance
|
* Calculate Distance
|
||||||
*
|
*
|
||||||
* Calculates the distance between two sets of coordinates and returns the
|
* Calculates the distance between two sets of coordinates and returns the
|
||||||
* requested units. I really wanted to call this distance() but it seems
|
* requested units. I really wanted to call this distance() but it seems
|
||||||
* you can't do that in PHP due to the backwards compatibility of the
|
* you can't do that in PHP due to the backwards compatibility of the
|
||||||
* PHP4 constructors that were named the same as the class.
|
* PHP4 constructors that were named the same as the class.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param mixed $latitude_from starting latitude
|
* @param mixed $latitude_from starting latitude
|
||||||
* @param mixed $longitude_from starting longitude
|
* @param mixed $longitude_from starting longitude
|
||||||
* @param mixed $latitude_to ending latitude
|
* @param mixed $latitude_to ending latitude
|
||||||
* @param mixed $longitude_to ending longitude
|
* @param mixed $longitude_to ending longitude
|
||||||
* @param string $unit optional units to return, miles by default
|
* @param string $unit optional units to return, miles by default
|
||||||
* @return mixed distance between the points in the desired unit
|
* @return mixed distance between the points in the desired unit
|
||||||
*/
|
*/
|
||||||
public static function calculateDistance($latitude_from, $longitude_from, $latitude_to, $longitude_to, $unit = 'miles')
|
public static function calculateDistance($latitude_from, $longitude_from, $latitude_to, $longitude_to, $unit = 'miles')
|
||||||
{
|
{
|
||||||
$unit = ucwords(strtolower($unit));
|
$unit = ucwords(strtolower($unit));
|
||||||
$theta = $longitude_from - $longitude_to;
|
$theta = $longitude_from - $longitude_to;
|
||||||
|
|
||||||
$distance =
|
$distance =
|
||||||
sin(deg2rad($latitude_from))
|
sin(deg2rad($latitude_from))
|
||||||
* sin(deg2rad($latitude_to))
|
* sin(deg2rad($latitude_to))
|
||||||
+ cos(deg2rad($latitude_from))
|
+ cos(deg2rad($latitude_from))
|
||||||
* cos(deg2rad($latitude_to))
|
* cos(deg2rad($latitude_to))
|
||||||
* cos(deg2rad($theta));
|
* cos(deg2rad($theta));
|
||||||
|
|
||||||
$distance = acos($distance);
|
$distance = acos($distance);
|
||||||
$distance = rad2deg($distance);
|
$distance = rad2deg($distance);
|
||||||
$miles = $distance * 60 * 1.1515;
|
$miles = $distance * 60 * 1.1515;
|
||||||
|
|
||||||
$method = 'milesTo' . $unit;
|
$method = 'milesTo' . $unit;
|
||||||
|
|
||||||
return Distance::$method($miles);
|
return Distance::$method($miles);
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -28,240 +28,239 @@
|
||||||
*/
|
*/
|
||||||
class Dynamic extends Object
|
class Dynamic extends Object
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Generate Reference
|
* Generate Reference
|
||||||
*
|
*
|
||||||
* Appends a dynamic piece of information to the passed reference in the
|
* Appends a dynamic piece of information to the passed reference in the
|
||||||
* form of a UNIX timestamp added to the query string.
|
* form of a UNIX timestamp added to the query string.
|
||||||
*
|
*
|
||||||
* @param string $reference URI reference of the file
|
* @param string $reference URI reference of the file
|
||||||
* @param string $failover URI reference to use if the reference can't be found
|
* @param string $failover URI reference to use if the reference can't be found
|
||||||
* @return string URI reference reference with dynamic content
|
* @return string URI reference reference with dynamic content
|
||||||
*/
|
*/
|
||||||
public function reference($reference, $failover = false)
|
public function reference($reference, $failover = false)
|
||||||
{
|
{
|
||||||
// Checks if the URI reference is absolute, and not relative
|
// Checks if the URI reference is absolute, and not relative
|
||||||
if (substr($reference, 0, 1) == '/')
|
if (substr($reference, 0, 1) == '/')
|
||||||
{
|
{
|
||||||
$query_string = '';
|
$query_string = '';
|
||||||
|
|
||||||
// Checks for ? and extracts query string
|
// Checks for ? and extracts query string
|
||||||
if (strstr($reference, '?'))
|
if (strstr($reference, '?'))
|
||||||
{
|
{
|
||||||
list($reference, $query_string) = explode('?', $reference);
|
list($reference, $query_string) = explode('?', $reference);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Adds the dot so the file functions can find the file
|
// Adds the dot so the file functions can find the file
|
||||||
$file = '.' . $reference;
|
$file = '.' . $reference;
|
||||||
|
|
||||||
if (file_exists($file))
|
if (file_exists($file))
|
||||||
{
|
{
|
||||||
// Replaces the extension with time().extension
|
// Replaces the extension with time().extension
|
||||||
$parts = explode('.', $reference);
|
$parts = explode('.', $reference);
|
||||||
|
|
||||||
if (count($parts) == 1)
|
if (count($parts) == 1)
|
||||||
{
|
{
|
||||||
throw new Exception('Filename must have an extension (e.g. /path/to/file.png)');
|
throw new Exception('Filename must have an extension (e.g. /path/to/file.png)');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
end($parts);
|
end($parts);
|
||||||
$parts[key($parts)] = filemtime($file) . '.' . current($parts);
|
$parts[key($parts)] = filemtime($file) . '.' . current($parts);
|
||||||
$reference = implode('.', $parts);
|
$reference = implode('.', $parts);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Adds the query string back
|
// Adds the query string back
|
||||||
if ($query_string != '')
|
if ($query_string != '')
|
||||||
{
|
{
|
||||||
$reference .= '?' . $query_string;
|
$reference .= '?' . $query_string;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
if ($failover != false)
|
if ($failover != false)
|
||||||
{
|
{
|
||||||
$reference = $failover;
|
$reference = $failover;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
throw new Exception('Supplied reference does not exist (' . $reference . ')');
|
throw new Exception('Supplied reference does not exist (' . $reference . ')');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
throw new Exception('Reference value must be absolute (e.g. /path/to/file.png)');
|
throw new Exception('Reference value must be absolute (e.g. /path/to/file.png)');
|
||||||
}
|
}
|
||||||
|
|
||||||
return $reference;
|
return $reference;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate Stylesheet Reference
|
* Generate Stylesheet Reference
|
||||||
*
|
*
|
||||||
* Attempts to minify the stylesheet and then returns the reference URI for
|
* Attempts to minify the stylesheet and then returns the reference URI for
|
||||||
* the file, minified or not. Supports LESS and SASS, pass it a .less file
|
* the file, minified or not. Supports LESS and SASS, pass it a .less file
|
||||||
* or a .scss file instead and it will be compiled before minification.
|
* or a .scss file instead and it will be compiled before minification.
|
||||||
*
|
*
|
||||||
* @param string $reference URI reference of the Stylesheet
|
* @param string $reference URI reference of the Stylesheet
|
||||||
* @return string URI reference reference with dynamic content
|
* @return string URI reference reference with dynamic content
|
||||||
* @url http://lesscss.org
|
* @url http://lesscss.org
|
||||||
* @url http://sass-lang.com
|
* @url http://sass-lang.com
|
||||||
*/
|
*/
|
||||||
public function css($original_reference)
|
public function css($original_reference)
|
||||||
{
|
{
|
||||||
$less = false;
|
$less = false;
|
||||||
$sass = false;
|
$sass = false;
|
||||||
|
|
||||||
// Injects .min into the filename
|
// Injects .min into the filename
|
||||||
$parts = explode('.', $original_reference);
|
$parts = explode('.', $original_reference);
|
||||||
|
|
||||||
if (count($parts) == 1)
|
if (count($parts) == 1)
|
||||||
{
|
{
|
||||||
throw new Exception('Filename must have an extension (e.g. /path/to/file.css)');
|
throw new Exception('Filename must have an extension (e.g. /path/to/file.css)');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
end($parts);
|
end($parts);
|
||||||
|
|
||||||
switch (current($parts))
|
switch (current($parts))
|
||||||
{
|
{
|
||||||
case 'less':
|
case 'less':
|
||||||
$less = true;
|
$less = true;
|
||||||
$parts[key($parts)] = 'css';
|
$parts[key($parts)] = 'css';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'scss':
|
case 'scss':
|
||||||
$sass = true;
|
$sass = true;
|
||||||
$parts[key($parts)] = 'css';
|
$parts[key($parts)] = 'css';
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
$parts[key($parts)] = 'min.' . current($parts);
|
$parts[key($parts)] = 'min.' . current($parts);
|
||||||
$minified_reference = implode('.', $parts);
|
$minified_reference = implode('.', $parts);
|
||||||
}
|
}
|
||||||
|
|
||||||
$original_filename = '.' . $original_reference;
|
$original_filename = '.' . $original_reference;
|
||||||
$minified_filename = '.' . $minified_reference;
|
$minified_filename = '.' . $minified_reference;
|
||||||
|
|
||||||
$path = dirname($original_filename);
|
$path = dirname($original_filename);
|
||||||
|
|
||||||
if (file_exists($original_filename))
|
if (file_exists($original_filename))
|
||||||
{
|
{
|
||||||
$reference = $original_reference;
|
$reference = $original_reference;
|
||||||
|
|
||||||
if ($this->config->pickles['minify'] === true)
|
if ($this->config->pickles['minify'] === true)
|
||||||
{
|
{
|
||||||
// Compiles LESS & SASS to CSS before minifying
|
// Compiles LESS & SASS to CSS before minifying
|
||||||
if ($less || $sass)
|
if ($less || $sass)
|
||||||
{
|
{
|
||||||
$compiled_filename = str_replace('.min', '', $minified_filename);
|
$compiled_filename = str_replace('.min', '', $minified_filename);
|
||||||
|
|
||||||
if ($less)
|
if ($less)
|
||||||
{
|
{
|
||||||
$less = new lessc();
|
$less = new lessc();
|
||||||
$less->compileFile($original_filename, $compiled_filename);
|
$less->compileFile($original_filename, $compiled_filename);
|
||||||
}
|
}
|
||||||
elseif ($sass)
|
elseif ($sass)
|
||||||
{
|
{
|
||||||
$scss = new Leafo\ScssPhp\Compiler();
|
$scss = new Leafo\ScssPhp\Compiler();
|
||||||
|
|
||||||
file_put_contents(
|
file_put_contents(
|
||||||
$compiled_filename,
|
$compiled_filename,
|
||||||
$scss->compile(file_get_contents($original_filename))
|
$scss->compile(file_get_contents($original_filename))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
$original_filename = $compiled_filename;
|
$original_filename = $compiled_filename;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Minifies CSS with a few basic character replacements.
|
// Minifies CSS with a few basic character replacements.
|
||||||
$stylesheet = file_get_contents($original_filename);
|
$stylesheet = file_get_contents($original_filename);
|
||||||
$stylesheet = str_replace(
|
$stylesheet = str_replace(
|
||||||
["\t", "\n", ', ', ' {', ': ', ';}', '{ ', '; '],
|
["\t", "\n", ', ', ' {', ': ', ';}', '{ ', '; '],
|
||||||
['', '', ',', '{', ':', '}', '{', ';'],
|
['', '', ',', '{', ':', '}', '{', ';'],
|
||||||
$stylesheet
|
$stylesheet
|
||||||
);
|
);
|
||||||
$stylesheet = preg_replace('/\/\*.+?\*\//', '', $stylesheet);
|
$stylesheet = preg_replace('/\/\*.+?\*\//', '', $stylesheet);
|
||||||
file_put_contents($minified_filename, $stylesheet);
|
file_put_contents($minified_filename, $stylesheet);
|
||||||
|
|
||||||
$reference = $minified_reference;
|
$reference = $minified_reference;
|
||||||
}
|
}
|
||||||
elseif (file_exists($minified_filename))
|
elseif (file_exists($minified_filename))
|
||||||
{
|
{
|
||||||
$reference = $minified_reference;
|
$reference = $minified_reference;
|
||||||
}
|
}
|
||||||
|
|
||||||
$reference = $this->reference($reference);
|
$reference = $this->reference($reference);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
throw new Exception('Supplied reference does not exist');
|
throw new Exception('Supplied reference does not exist');
|
||||||
}
|
}
|
||||||
|
|
||||||
return $reference;
|
return $reference;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate Javascript Reference
|
* Generate Javascript Reference
|
||||||
*
|
*
|
||||||
* Attempts to minify the source with Google's Closure compiler, and then
|
* Attempts to minify the source with Google's Closure compiler, and then
|
||||||
* returns the reference URI for the file, minified or not.
|
* returns the reference URI for the file, minified or not.
|
||||||
*
|
*
|
||||||
* @link http://code.google.com/closure/compiler/
|
* @link http://code.google.com/closure/compiler/
|
||||||
* @param string $reference URI reference of the Javascript file
|
* @param string $reference URI reference of the Javascript file
|
||||||
* @return string URI reference reference with dynamic content
|
* @return string URI reference reference with dynamic content
|
||||||
*/
|
*/
|
||||||
public function js($original_reference)
|
public function js($original_reference)
|
||||||
{
|
{
|
||||||
// Injects .min into the filename
|
// Injects .min into the filename
|
||||||
$parts = explode('.', $original_reference);
|
$parts = explode('.', $original_reference);
|
||||||
|
|
||||||
if (count($parts) == 1)
|
if (count($parts) == 1)
|
||||||
{
|
{
|
||||||
throw new Exception('Filename must have an extension (e.g. /path/to/file.js)');
|
throw new Exception('Filename must have an extension (e.g. /path/to/file.js)');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
end($parts);
|
end($parts);
|
||||||
$parts[key($parts)] = 'min.' . current($parts);
|
$parts[key($parts)] = 'min.' . current($parts);
|
||||||
$minified_reference = implode('.', $parts);
|
$minified_reference = implode('.', $parts);
|
||||||
}
|
}
|
||||||
|
|
||||||
$original_filename = '.' . $original_reference;
|
$original_filename = '.' . $original_reference;
|
||||||
$minified_filename = '.' . $minified_reference;
|
$minified_filename = '.' . $minified_reference;
|
||||||
|
|
||||||
$path = dirname($original_filename);
|
$path = dirname($original_filename);
|
||||||
|
|
||||||
if (file_exists($original_filename))
|
if (file_exists($original_filename))
|
||||||
{
|
{
|
||||||
$reference = $original_reference;
|
$reference = $original_reference;
|
||||||
|
|
||||||
if ($this->config->pickles['minify'] === true)
|
if ($this->config->pickles['minify'] === true)
|
||||||
{
|
{
|
||||||
$compiler = new Devize\ClosureCompiler\ClosureCompiler();
|
$compiler = new Devize\ClosureCompiler\ClosureCompiler();
|
||||||
$compiler->setSourceBaseDir(dirname($original_filename));
|
$compiler->setSourceBaseDir(dirname($original_filename));
|
||||||
$compiler->setTargetBaseDir(dirname($minified_filename));
|
$compiler->setTargetBaseDir(dirname($minified_filename));
|
||||||
$compiler->addSourceFile(basename($original_filename));
|
$compiler->addSourceFile(basename($original_filename));
|
||||||
$compiler->setTargetFile(basename($minified_filename));
|
$compiler->setTargetFile(basename($minified_filename));
|
||||||
$compiler->compile();
|
$compiler->compile();
|
||||||
|
|
||||||
$reference = $minified_reference;
|
$reference = $minified_reference;
|
||||||
}
|
}
|
||||||
elseif (file_exists($minified_filename))
|
elseif (file_exists($minified_filename))
|
||||||
{
|
{
|
||||||
$reference = $minified_reference;
|
$reference = $minified_reference;
|
||||||
}
|
}
|
||||||
|
|
||||||
$reference = $this->reference($reference);
|
$reference = $this->reference($reference);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
throw new Exception('Supplied reference does not exist');
|
throw new Exception('Supplied reference does not exist');
|
||||||
}
|
}
|
||||||
|
|
||||||
return $reference;
|
return $reference;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -23,52 +23,51 @@
|
||||||
*/
|
*/
|
||||||
class File
|
class File
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Remove a Directory, Recursively
|
* Remove a Directory, Recursively
|
||||||
*
|
*
|
||||||
* Removes a directory by emptying all of the contents recursively and then
|
* Removes a directory by emptying all of the contents recursively and then
|
||||||
* removing the directory, as PHP will not let you rmdir() on ain non-empty
|
* removing the directory, as PHP will not let you rmdir() on ain non-empty
|
||||||
* directory. Use with caution, seriously.
|
* directory. Use with caution, seriously.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $directory directory to remove
|
* @param string $directory directory to remove
|
||||||
* @return boolean status of the final rmdir();
|
* @return boolean status of the final rmdir();
|
||||||
*/
|
*/
|
||||||
public static function removeDirectory($directory)
|
public static function removeDirectory($directory)
|
||||||
{
|
{
|
||||||
if (substr($directory, -1) != '/')
|
if (substr($directory, -1) != '/')
|
||||||
{
|
{
|
||||||
$directory .= '/';
|
$directory .= '/';
|
||||||
}
|
}
|
||||||
|
|
||||||
// If directory is a directory, read in all the files
|
// If directory is a directory, read in all the files
|
||||||
if (is_dir($directory))
|
if (is_dir($directory))
|
||||||
{
|
{
|
||||||
$files = scandir($directory);
|
$files = scandir($directory);
|
||||||
|
|
||||||
// Loop through said files, check for directories, and unlink files
|
// Loop through said files, check for directories, and unlink files
|
||||||
foreach ($files as $file)
|
foreach ($files as $file)
|
||||||
{
|
{
|
||||||
if (!in_array($file, ['.', '..']))
|
if (!in_array($file, ['.', '..']))
|
||||||
{
|
{
|
||||||
if (is_dir($directory . $file))
|
if (is_dir($directory . $file))
|
||||||
{
|
{
|
||||||
File::removeDirectory($directory . $file);
|
File::removeDirectory($directory . $file);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
unlink($directory . $file);
|
unlink($directory . $file);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
rmdir($directory);
|
rmdir($directory);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
unlink($directory);
|
unlink($directory);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
1287
src/classes/Form.php
1287
src/classes/Form.php
File diff suppressed because it is too large
Load diff
|
@ -22,128 +22,127 @@
|
||||||
*/
|
*/
|
||||||
class HTML extends Object
|
class HTML extends Object
|
||||||
{
|
{
|
||||||
private $self_closing = ['br', 'hr', 'img', 'input', 'link', 'meta'];
|
private $self_closing = ['br', 'hr', 'img', 'input', 'link', 'meta'];
|
||||||
|
|
||||||
public function __call($method, $arguments)
|
public function __call($method, $arguments)
|
||||||
{
|
{
|
||||||
$attributes = null;
|
$attributes = null;
|
||||||
$contents = null;
|
$contents = null;
|
||||||
|
|
||||||
if (isset($arguments[0]))
|
if (isset($arguments[0]))
|
||||||
{
|
{
|
||||||
$attributes = $arguments[0];
|
$attributes = $arguments[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isset($arguments[1]))
|
if (isset($arguments[1]))
|
||||||
{
|
{
|
||||||
$contents = $arguments[1];
|
$contents = $arguments[1];
|
||||||
}
|
}
|
||||||
|
|
||||||
// ->inputType('name', $attributes);
|
// ->inputType('name', $attributes);
|
||||||
if (preg_match('/^input/', $method) && !isset($attributes['label']))
|
if (preg_match('/^input/', $method) && !isset($attributes['label']))
|
||||||
{
|
{
|
||||||
$type = strtolower(str_replace('input', '', $method));
|
$type = strtolower(str_replace('input', '', $method));
|
||||||
|
|
||||||
switch ($type)
|
switch ($type)
|
||||||
{
|
{
|
||||||
case 'datetimelocal': $type = 'datetime-local'; break;
|
case 'datetimelocal': $type = 'datetime-local'; break;
|
||||||
case '': $type = 'text'; break;
|
case '': $type = 'text'; break;
|
||||||
}
|
}
|
||||||
|
|
||||||
$method = 'input';
|
$method = 'input';
|
||||||
|
|
||||||
if (is_array($attributes))
|
if (is_array($attributes))
|
||||||
{
|
{
|
||||||
$attributes['type'] = $type;
|
$attributes['type'] = $type;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$attributes = ['type' => $type];
|
$attributes = ['type' => $type];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (is_array($attributes) && isset($attributes['label']))
|
if (is_array($attributes) && isset($attributes['label']))
|
||||||
{
|
{
|
||||||
if (isset($attributes['name']))
|
if (isset($attributes['name']))
|
||||||
{
|
{
|
||||||
$label = $this->label(['for' => $attributes['name']], $attributes['label']);
|
$label = $this->label(['for' => $attributes['name']], $attributes['label']);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$label = $this->label($attributes['label']);
|
$label = $this->label($attributes['label']);
|
||||||
}
|
}
|
||||||
|
|
||||||
unset($attributes['label']);
|
unset($attributes['label']);
|
||||||
|
|
||||||
return $label . $this->$method($attributes, $contents);
|
return $label . $this->$method($attributes, $contents);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
return $this->element($method, $attributes, $contents);
|
return $this->element($method, $attributes, $contents);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// {{{ Get Instance
|
// {{{ Get Instance
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get Instance
|
* Get Instance
|
||||||
*
|
*
|
||||||
* Gets an instance of the Form class
|
* Gets an instance of the Form class
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $class name of the class to get an instance of
|
* @param string $class name of the class to get an instance of
|
||||||
* @return object instance of the class
|
* @return object instance of the class
|
||||||
*/
|
*/
|
||||||
public static function getInstance($class = 'HTML')
|
public static function getInstance($class = 'HTML')
|
||||||
{
|
{
|
||||||
return parent::getInstance($class);
|
return parent::getInstance($class);
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
|
|
||||||
public function element($element)
|
public function element($element)
|
||||||
{
|
{
|
||||||
$attributes = null;
|
$attributes = null;
|
||||||
$contents = null;
|
$contents = null;
|
||||||
|
|
||||||
foreach (func_get_args() as $key => $value)
|
foreach (func_get_args() as $key => $value)
|
||||||
{
|
{
|
||||||
if ($key && $key < 3)
|
if ($key && $key < 3)
|
||||||
{
|
{
|
||||||
if (is_array($value))
|
if (is_array($value))
|
||||||
{
|
{
|
||||||
$attributes = $value;
|
$attributes = $value;
|
||||||
}
|
}
|
||||||
elseif ($value)
|
elseif ($value)
|
||||||
{
|
{
|
||||||
$contents = $value;
|
$contents = $value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$element = strtolower($element);
|
$element = strtolower($element);
|
||||||
$html = '<' . $element;
|
$html = '<' . $element;
|
||||||
|
|
||||||
if ($attributes)
|
if ($attributes)
|
||||||
{
|
{
|
||||||
if (is_array($attributes))
|
if (is_array($attributes))
|
||||||
{
|
{
|
||||||
foreach ($attributes as $attribute => $value)
|
foreach ($attributes as $attribute => $value)
|
||||||
{
|
{
|
||||||
$html .= ' ' . $attribute . '="' . str_replace('"', '\"', $value) . '"';
|
$html .= ' ' . $attribute . '="' . str_replace('"', '\"', $value) . '"';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$html .= '>';
|
$html .= '>';
|
||||||
|
|
||||||
if (!in_array($element, $this->self_closing))
|
if (!in_array($element, $this->self_closing))
|
||||||
{
|
{
|
||||||
$html .= $contents . '</' . $element . '>';
|
$html .= $contents . '</' . $element . '>';
|
||||||
}
|
}
|
||||||
|
|
||||||
return $html;
|
return $html;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -22,131 +22,130 @@
|
||||||
*/
|
*/
|
||||||
class Log
|
class Log
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Log Information
|
* Log Information
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $message message to log
|
* @param string $message message to log
|
||||||
* @return boolean whether or not the write was successful
|
* @return boolean whether or not the write was successful
|
||||||
*/
|
*/
|
||||||
public static function information($message)
|
public static function information($message)
|
||||||
{
|
{
|
||||||
return self::write('information', $message);
|
return self::write('information', $message);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Log Warning
|
* Log Warning
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $message message to log
|
* @param string $message message to log
|
||||||
* @return boolean whether or not the write was successful
|
* @return boolean whether or not the write was successful
|
||||||
*/
|
*/
|
||||||
public static function warning($message)
|
public static function warning($message)
|
||||||
{
|
{
|
||||||
return self::write('warning', $message);
|
return self::write('warning', $message);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Log Error
|
* Log Error
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $message message to log
|
* @param string $message message to log
|
||||||
* @return boolean whether or not the write was successful
|
* @return boolean whether or not the write was successful
|
||||||
*/
|
*/
|
||||||
public static function error($message)
|
public static function error($message)
|
||||||
{
|
{
|
||||||
return self::write('error', $message);
|
return self::write('error', $message);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Log Slow Query
|
* Log Slow Query
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $message message to log
|
* @param string $message message to log
|
||||||
* @return boolean whether or not the write was successful
|
* @return boolean whether or not the write was successful
|
||||||
*/
|
*/
|
||||||
public static function slowQuery($message)
|
public static function slowQuery($message)
|
||||||
{
|
{
|
||||||
return self::write('slow_query', $message);
|
return self::write('slow_query', $message);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Log Credit Card Transaction
|
* Log Credit Card Transaction
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $message message to log
|
* @param string $message message to log
|
||||||
* @return boolean whether or not the write was successful
|
* @return boolean whether or not the write was successful
|
||||||
*/
|
*/
|
||||||
public static function transaction($message)
|
public static function transaction($message)
|
||||||
{
|
{
|
||||||
return self::write('transaction', $message);
|
return self::write('transaction', $message);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Log PHP Error
|
* Log PHP Error
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $message message to log
|
* @param string $message message to log
|
||||||
* @return boolean whether or not the write was successful
|
* @return boolean whether or not the write was successful
|
||||||
*/
|
*/
|
||||||
public static function phpError($message, $time = false)
|
public static function phpError($message, $time = false)
|
||||||
{
|
{
|
||||||
return self::write('php_error', $message, false, $time);
|
return self::write('php_error', $message, false, $time);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Log SQL Query
|
* Log SQL Query
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $message message to log
|
* @param string $message message to log
|
||||||
* @return boolean whether or not the write was successful
|
* @return boolean whether or not the write was successful
|
||||||
*/
|
*/
|
||||||
public static function query($message)
|
public static function query($message)
|
||||||
{
|
{
|
||||||
return self::write('query', $message);
|
return self::write('query', $message);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Write Message to Log File
|
* Write Message to Log File
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @access private
|
* @access private
|
||||||
* @param string $message message to log
|
* @param string $message message to log
|
||||||
* @return boolean whether or not the write was successful
|
* @return boolean whether or not the write was successful
|
||||||
*/
|
*/
|
||||||
private static function write($log_type, $message, $format = true, $time = false)
|
private static function write($log_type, $message, $format = true, $time = false)
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
|
|
||||||
if (isset($config->pickles['logging']) && $config->pickles['logging'])
|
if (isset($config->pickles['logging']) && $config->pickles['logging'])
|
||||||
{
|
{
|
||||||
$log_path = LOG_PATH . date('Y/m/d/', ($time == false ? time() : $time));
|
$log_path = LOG_PATH . date('Y/m/d/', ($time == false ? time() : $time));
|
||||||
|
|
||||||
if (!file_exists($log_path))
|
if (!file_exists($log_path))
|
||||||
{
|
{
|
||||||
mkdir($log_path, 0755, true);
|
mkdir($log_path, 0755, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
$log_file = $log_path . $log_type . '.log';
|
$log_file = $log_path . $log_type . '.log';
|
||||||
|
|
||||||
$message .= "\n";
|
$message .= "\n";
|
||||||
|
|
||||||
if ($format == true)
|
if ($format == true)
|
||||||
{
|
{
|
||||||
$backtrace = debug_backtrace();
|
$backtrace = debug_backtrace();
|
||||||
rsort($backtrace);
|
rsort($backtrace);
|
||||||
$frame = $backtrace[strpos($backtrace[0]['file'], 'index.php') === false ? 0 : 1];
|
$frame = $backtrace[strpos($backtrace[0]['file'], 'index.php') === false ? 0 : 1];
|
||||||
|
|
||||||
return file_put_contents($log_file, date('H:i:s') . ' ' . str_replace(getcwd(), '', $frame['file']) . ':' . $frame['line'] . ' ' . $message, FILE_APPEND);
|
return file_put_contents($log_file, date('H:i:s') . ' ' . str_replace(getcwd(), '', $frame['file']) . ':' . $frame['line'] . ' ' . $message, FILE_APPEND);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
return file_put_contents($log_file, $message, FILE_APPEND);
|
return file_put_contents($log_file, $message, FILE_APPEND);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -27,268 +27,267 @@
|
||||||
*/
|
*/
|
||||||
class Module extends Object
|
class Module extends Object
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Page Title
|
* Page Title
|
||||||
*
|
*
|
||||||
* @var string, null by default
|
* @var string, null by default
|
||||||
* @todo Abandon for $this->meta
|
* @todo Abandon for $this->meta
|
||||||
*/
|
*/
|
||||||
public $title = null;
|
public $title = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Meta Description
|
* Meta Description
|
||||||
*
|
*
|
||||||
* @var string, null by default
|
* @var string, null by default
|
||||||
* @todo Abandon for $this->meta
|
* @todo Abandon for $this->meta
|
||||||
*/
|
*/
|
||||||
public $description = null;
|
public $description = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Meta Keywords (comma separated)
|
* Meta Keywords (comma separated)
|
||||||
*
|
*
|
||||||
* @var string, null by default
|
* @var string, null by default
|
||||||
* @todo Abandon for $this->meta
|
* @todo Abandon for $this->meta
|
||||||
*/
|
*/
|
||||||
public $keywords = null;
|
public $keywords = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Meta Data
|
* Meta Data
|
||||||
*
|
*
|
||||||
* @var array
|
* @var array
|
||||||
*/
|
*/
|
||||||
public $meta = [
|
public $meta = [
|
||||||
'title' => '',
|
'title' => '',
|
||||||
'description' => '',
|
'description' => '',
|
||||||
'keywords' => '',
|
'keywords' => '',
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Secure
|
* Secure
|
||||||
*
|
*
|
||||||
* Whether or not the page should be loaded via SSL.
|
* Whether or not the page should be loaded via SSL.
|
||||||
*
|
*
|
||||||
* @var boolean defaults to false
|
* @var boolean defaults to false
|
||||||
*/
|
*/
|
||||||
public $secure = false;
|
public $secure = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Security Settings
|
* Security Settings
|
||||||
*
|
*
|
||||||
* @var boolean, null by default
|
* @var boolean, null by default
|
||||||
*/
|
*/
|
||||||
public $security = null;
|
public $security = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* AJAX
|
* AJAX
|
||||||
*
|
*
|
||||||
* Whether or not the module is being called via AJAX. This determines if
|
* Whether or not the module is being called via AJAX. This determines if
|
||||||
* errors should be returned as JSON or if it should use the Error class
|
* errors should be returned as JSON or if it should use the Error class
|
||||||
* which can be interrogated from within a template.
|
* which can be interrogated from within a template.
|
||||||
*
|
*
|
||||||
* @var boolean, false (not AJAX) by default
|
* @var boolean, false (not AJAX) by default
|
||||||
* @todo Doesn't seem to be in use, but I have it defined on Clipinary
|
* @todo Doesn't seem to be in use, but I have it defined on Clipinary
|
||||||
* don't want to remove until I drop it else it would end up in the
|
* don't want to remove until I drop it else it would end up in the
|
||||||
* module return array.
|
* module return array.
|
||||||
*/
|
*/
|
||||||
public $ajax = false;
|
public $ajax = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Method
|
* Method
|
||||||
*
|
*
|
||||||
* Request methods that are allowed to access the module.
|
* Request methods that are allowed to access the module.
|
||||||
*
|
*
|
||||||
* @var string or array, null by default
|
* @var string or array, null by default
|
||||||
*/
|
*/
|
||||||
public $method = null;
|
public $method = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate
|
* Validate
|
||||||
*
|
*
|
||||||
* Variables to validate.
|
* Variables to validate.
|
||||||
*
|
*
|
||||||
* @var array
|
* @var array
|
||||||
*/
|
*/
|
||||||
public $validate = [];
|
public $validate = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Template
|
* Template
|
||||||
*
|
*
|
||||||
* This is the parent template that will be loaded if you are using the
|
* This is the parent template that will be loaded if you are using the
|
||||||
* 'template' return type in the Display class. Parent templates are found
|
* 'template' return type in the Display class. Parent templates are found
|
||||||
* in ./templates/__shared and use the phtml extension.
|
* in ./templates/__shared and use the phtml extension.
|
||||||
*
|
*
|
||||||
* @var string, 'index' by default
|
* @var string, 'index' by default
|
||||||
*/
|
*/
|
||||||
public $template = 'index';
|
public $template = 'index';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return
|
* Return
|
||||||
*
|
*
|
||||||
* Array that is returned to the template in the case of the module not
|
* Array that is returned to the template in the case of the module not
|
||||||
* returning anything itself. This is somewhat of a one way trip as you
|
* returning anything itself. This is somewhat of a one way trip as you
|
||||||
* cannot get the variable unless you reference the return array explicitly
|
* cannot get the variable unless you reference the return array explicitly
|
||||||
* $this->return['variable']
|
* $this->return['variable']
|
||||||
*
|
*
|
||||||
* @var array
|
* @var array
|
||||||
* @todo Rename __return so it's kinda obscured
|
* @todo Rename __return so it's kinda obscured
|
||||||
* @todo Will need to update leaderbin and sndcrd to use new variable
|
* @todo Will need to update leaderbin and sndcrd to use new variable
|
||||||
*/
|
*/
|
||||||
public $return = [];
|
public $return = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Output
|
* Output
|
||||||
*
|
*
|
||||||
* What should the class render as output? This can be a string or an array
|
* What should the class render as output? This can be a string or an array
|
||||||
* containing either 'json', 'rss', 'template' or 'xml'. Default is to use
|
* containing either 'json', 'rss', 'template' or 'xml'. Default is to use
|
||||||
* templates and if the template is not present, fall back to JSON.
|
* templates and if the template is not present, fall back to JSON.
|
||||||
*
|
*
|
||||||
* @var mixed string or array
|
* @var mixed string or array
|
||||||
*/
|
*/
|
||||||
public $output = ['template', 'json'];
|
public $output = ['template', 'json'];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
*
|
*
|
||||||
* The constructor does nothing by default but can be passed a boolean
|
* The constructor does nothing by default but can be passed a boolean
|
||||||
* variable to tell it to automatically run the __default() method. This is
|
* variable to tell it to automatically run the __default() method. This is
|
||||||
* typically used when a module is called outside of the scope of the
|
* typically used when a module is called outside of the scope of the
|
||||||
* controller (the registration page calls the login page in this manner.
|
* controller (the registration page calls the login page in this manner.
|
||||||
*
|
*
|
||||||
* @param boolean $autorun optional flag to autorun __default()
|
* @param boolean $autorun optional flag to autorun __default()
|
||||||
* @param boolean $valiate optional flag to disable autorun validation
|
* @param boolean $valiate optional flag to disable autorun validation
|
||||||
*/
|
*/
|
||||||
public function __construct($autorun = false, $validate = true)
|
public function __construct($autorun = false, $validate = true)
|
||||||
{
|
{
|
||||||
parent::__construct(['cache', 'db']);
|
parent::__construct(['cache', 'db']);
|
||||||
|
|
||||||
if ($autorun === true)
|
if ($autorun === true)
|
||||||
{
|
{
|
||||||
if ($validate === true)
|
if ($validate === true)
|
||||||
{
|
{
|
||||||
$errors = $this->__validate();
|
$errors = $this->__validate();
|
||||||
|
|
||||||
if ($errors !== false)
|
if ($errors !== false)
|
||||||
{
|
{
|
||||||
// @todo Fatal error perhaps?
|
// @todo Fatal error perhaps?
|
||||||
exit('Errors encountered, this is a @todo for form validation when calling modules from inside of modules');
|
exit('Errors encountered, this is a @todo for form validation when calling modules from inside of modules');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->__default();
|
$this->__default();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Default "Magic" Method
|
* Default "Magic" Method
|
||||||
*
|
*
|
||||||
* This function is overloaded by the module. The __default() method is
|
* This function is overloaded by the module. The __default() method is
|
||||||
* where you want to place any code that needs to be executed at runtime.
|
* where you want to place any code that needs to be executed at runtime.
|
||||||
*/
|
*/
|
||||||
public function __default()
|
public function __default()
|
||||||
{
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Magic Setter Method
|
* Magic Setter Method
|
||||||
*
|
*
|
||||||
* Places undefined properties into the return array as part of the
|
* Places undefined properties into the return array as part of the
|
||||||
* module's payload.
|
* module's payload.
|
||||||
*
|
*
|
||||||
* @param string $name name of the variable to be set
|
* @param string $name name of the variable to be set
|
||||||
* @param mixed $value value of the variable to be set
|
* @param mixed $value value of the variable to be set
|
||||||
*/
|
*/
|
||||||
public function __set($name, $value)
|
public function __set($name, $value)
|
||||||
{
|
{
|
||||||
$this->return[$name] = $value;
|
$this->return[$name] = $value;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Magic Getter Method
|
* Magic Getter Method
|
||||||
*
|
*
|
||||||
* Any variables not defined in this class are set in the return array and
|
* Any variables not defined in this class are set in the return array and
|
||||||
* default to false if not defined there.
|
* default to false if not defined there.
|
||||||
*
|
*
|
||||||
* @param string $name name of the variable requested
|
* @param string $name name of the variable requested
|
||||||
* @return mixed value of the variable or boolean false
|
* @return mixed value of the variable or boolean false
|
||||||
*/
|
*/
|
||||||
public function __get($name)
|
public function __get($name)
|
||||||
{
|
{
|
||||||
if (!isset($this->return[$name]))
|
if (!isset($this->return[$name]))
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
return $this->return[$name];
|
return $this->return[$name];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate
|
* Validate
|
||||||
*
|
*
|
||||||
* Internal validation for data passed to a Module. Grabs the super global
|
* Internal validation for data passed to a Module. Grabs the super global
|
||||||
* based on the Module's request method and loops through the data using the
|
* based on the Module's request method and loops through the data using the
|
||||||
* Module's validation array (if present) sanity checking each variable
|
* Module's validation array (if present) sanity checking each variable
|
||||||
* against the rules.
|
* against the rules.
|
||||||
*
|
*
|
||||||
* @return mixed boolean false if everything is fine or an array or errors
|
* @return mixed boolean false if everything is fine or an array or errors
|
||||||
*/
|
*/
|
||||||
public function __validate()
|
public function __validate()
|
||||||
{
|
{
|
||||||
$errors = [];
|
$errors = [];
|
||||||
|
|
||||||
if ($this->validate)
|
if ($this->validate)
|
||||||
{
|
{
|
||||||
if (is_array($this->method))
|
if (is_array($this->method))
|
||||||
{
|
{
|
||||||
$this->method = $this->method[0];
|
$this->method = $this->method[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (strtoupper($this->method))
|
switch (strtoupper($this->method))
|
||||||
{
|
{
|
||||||
case 'GET':
|
case 'GET':
|
||||||
$global = &$_GET;
|
$global = &$_GET;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'POST':
|
case 'POST':
|
||||||
$global = &$_POST;
|
$global = &$_POST;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
$global = &$_REQUEST;
|
$global = &$_REQUEST;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($this->validate as $variable => $rules)
|
foreach ($this->validate as $variable => $rules)
|
||||||
{
|
{
|
||||||
if (!is_array($rules) && $rules !== true)
|
if (!is_array($rules) && $rules !== true)
|
||||||
{
|
{
|
||||||
$variable = $rules;
|
$variable = $rules;
|
||||||
$rules = true;
|
$rules = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isset($global[$variable]) && !String::isEmpty($global[$variable]))
|
if (isset($global[$variable]) && !String::isEmpty($global[$variable]))
|
||||||
{
|
{
|
||||||
if (is_array($rules))
|
if (is_array($rules))
|
||||||
{
|
{
|
||||||
$rule_errors = Validate::isValid($global[$variable], $rules);
|
$rule_errors = Validate::isValid($global[$variable], $rules);
|
||||||
|
|
||||||
if (is_array($rule_errors))
|
if (is_array($rule_errors))
|
||||||
{
|
{
|
||||||
$errors = array_merge($errors, $rule_errors);
|
$errors = array_merge($errors, $rule_errors);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$errors[] = 'The ' . $variable . ' field is required.';
|
$errors[] = 'The ' . $variable . ' field is required.';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $errors == [] ? false : $errors;
|
return $errors == [] ? false : $errors;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -23,49 +23,48 @@
|
||||||
*/
|
*/
|
||||||
class Number
|
class Number
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Ordinal Indiciator
|
* Ordinal Indiciator
|
||||||
*
|
*
|
||||||
* Formats a number by appending an ordinal indicator.
|
* Formats a number by appending an ordinal indicator.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @link http://en.wikipedia.org/wiki/Ordinal_indicator
|
* @link http://en.wikipedia.org/wiki/Ordinal_indicator
|
||||||
* @link http://en.wikipedia.org/wiki/English_numerals#Ordinal_numbers
|
* @link http://en.wikipedia.org/wiki/English_numerals#Ordinal_numbers
|
||||||
* @param string $number number to format
|
* @param string $number number to format
|
||||||
* @param boolean $superscript include <sup> tags
|
* @param boolean $superscript include <sup> tags
|
||||||
* @return string formatted number
|
* @return string formatted number
|
||||||
*/
|
*/
|
||||||
public static function ordinalIndicator($number, $superscript = false)
|
public static function ordinalIndicator($number, $superscript = false)
|
||||||
{
|
{
|
||||||
if (!in_array(($number % 100), [11, 12, 13]))
|
if (!in_array(($number % 100), [11, 12, 13]))
|
||||||
{
|
{
|
||||||
switch ($number % 10)
|
switch ($number % 10)
|
||||||
{
|
{
|
||||||
case 1:
|
case 1:
|
||||||
$suffix = 'st';
|
$suffix = 'st';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 2:
|
case 2:
|
||||||
$suffix = 'nd';
|
$suffix = 'nd';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 3:
|
case 3:
|
||||||
$suffix = 'rd';
|
$suffix = 'rd';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
$suffix = 'th';
|
$suffix = 'th';
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($superscript)
|
if ($superscript)
|
||||||
{
|
{
|
||||||
$suffix = '<sup>' . $suffix . '</sup>';
|
$suffix = '<sup>' . $suffix . '</sup>';
|
||||||
}
|
}
|
||||||
|
|
||||||
return $number . $suffix;
|
return $number . $suffix;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -24,127 +24,126 @@
|
||||||
*/
|
*/
|
||||||
class Object
|
class Object
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Object Instances
|
* Object Instances
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @var array
|
* @var array
|
||||||
*/
|
*/
|
||||||
public static $instances = [];
|
public static $instances = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instance of the Config object
|
* Instance of the Config object
|
||||||
*
|
*
|
||||||
* @var object
|
* @var object
|
||||||
*/
|
*/
|
||||||
public $config = null;
|
public $config = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instance of the Cache object
|
* Instance of the Cache object
|
||||||
*
|
*
|
||||||
* @var object
|
* @var object
|
||||||
*/
|
*/
|
||||||
public $cache = null;
|
public $cache = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instance of the Database object
|
* Instance of the Database object
|
||||||
*
|
*
|
||||||
* @var object
|
* @var object
|
||||||
*/
|
*/
|
||||||
public $db = null;
|
public $db = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Profiler flag
|
* Profiler flag
|
||||||
*
|
*
|
||||||
* @var mixed
|
* @var mixed
|
||||||
*/
|
*/
|
||||||
public $profiler = false;
|
public $profiler = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
*
|
*
|
||||||
* Establishes a Config instance for all children to enjoy
|
* Establishes a Config instance for all children to enjoy
|
||||||
*/
|
*/
|
||||||
public function __construct($objects = null)
|
public function __construct($objects = null)
|
||||||
{
|
{
|
||||||
// Gets an instance of the config, unless we ARE the config
|
// Gets an instance of the config, unless we ARE the config
|
||||||
if (get_class($this) == 'Config')
|
if (get_class($this) == 'Config')
|
||||||
{
|
{
|
||||||
$this->config = true;
|
$this->config = true;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$this->config = Config::getInstance();
|
$this->config = Config::getInstance();
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($objects)
|
if ($objects)
|
||||||
{
|
{
|
||||||
if (!is_array($objects))
|
if (!is_array($objects))
|
||||||
{
|
{
|
||||||
$objects = [$objects];
|
$objects = [$objects];
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($objects as $object)
|
foreach ($objects as $object)
|
||||||
{
|
{
|
||||||
switch ($object)
|
switch ($object)
|
||||||
{
|
{
|
||||||
case 'cache': $this->cache = Cache::getInstance(); break;
|
case 'cache': $this->cache = Cache::getInstance(); break;
|
||||||
case 'db': $this->db = Database::getInstance(); break;
|
case 'db': $this->db = Database::getInstance(); break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Assigns the profiler flag
|
// Assigns the profiler flag
|
||||||
$this->profiler = (isset($this->config->pickles['profiler']) && $this->config->pickles['profiler'] != '' ? $this->config->pickles['profiler'] : false);
|
$this->profiler = (isset($this->config->pickles['profiler']) && $this->config->pickles['profiler'] != '' ? $this->config->pickles['profiler'] : false);
|
||||||
|
|
||||||
// Optionally logs the constructor to the profiler
|
// Optionally logs the constructor to the profiler
|
||||||
if ($this->profiler === true || ((is_array($this->profiler) && in_array('objects', $this->profiler)) || stripos($this->profiler, 'objects') !== false))
|
if ($this->profiler === true || ((is_array($this->profiler) && in_array('objects', $this->profiler)) || stripos($this->profiler, 'objects') !== false))
|
||||||
{
|
{
|
||||||
Profiler::log($this, '__construct');
|
Profiler::log($this, '__construct');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get Instance
|
* Get Instance
|
||||||
*
|
*
|
||||||
* Gets an instance of the passed class. Allows for easy sharing of certain
|
* Gets an instance of the passed class. Allows for easy sharing of certain
|
||||||
* classes within the system to avoid the extra overhead of creating new
|
* classes within the system to avoid the extra overhead of creating new
|
||||||
* objects each time. Also avoids the hassle of passing around variables.
|
* objects each time. Also avoids the hassle of passing around variables.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $class name of the class
|
* @param string $class name of the class
|
||||||
* @return object instance of the class
|
* @return object instance of the class
|
||||||
*/
|
*/
|
||||||
public static function getInstance($class = false)
|
public static function getInstance($class = false)
|
||||||
{
|
{
|
||||||
// In < 5.3 arguments must match in child, hence defaulting $class
|
// In < 5.3 arguments must match in child, hence defaulting $class
|
||||||
// @todo Remove this, as we're no longer supporting 5.3
|
// @todo Remove this, as we're no longer supporting 5.3
|
||||||
if ($class == false)
|
if ($class == false)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
if (!isset(self::$instances[$class]))
|
if (!isset(self::$instances[$class]))
|
||||||
{
|
{
|
||||||
self::$instances[$class] = new $class();
|
self::$instances[$class] = new $class();
|
||||||
}
|
}
|
||||||
|
|
||||||
return self::$instances[$class];
|
return self::$instances[$class];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Destructor
|
* Destructor
|
||||||
*/
|
*/
|
||||||
public function __destruct()
|
public function __destruct()
|
||||||
{
|
{
|
||||||
// Optionally logs the destructor to the profiler
|
// Optionally logs the destructor to the profiler
|
||||||
if ($this->profiler === true || ((is_array($this->profiler) && in_array('objects', $this->profiler)) || stripos($this->profiler, 'objects') !== false))
|
if ($this->profiler === true || ((is_array($this->profiler) && in_array('objects', $this->profiler)) || stripos($this->profiler, 'objects') !== false))
|
||||||
{
|
{
|
||||||
Profiler::log($this, '__destruct');
|
Profiler::log($this, '__destruct');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -33,358 +33,357 @@
|
||||||
*/
|
*/
|
||||||
class Profiler
|
class Profiler
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Profile
|
* Profile
|
||||||
*
|
*
|
||||||
* Array of logged events
|
* Array of logged events
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @access private
|
* @access private
|
||||||
* @var array
|
* @var array
|
||||||
*/
|
*/
|
||||||
private static $profile = [];
|
private static $profile = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Queries
|
* Queries
|
||||||
*
|
*
|
||||||
* Number of queries that have been logged
|
* Number of queries that have been logged
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @access private
|
* @access private
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
private static $queries = 0;
|
private static $queries = 0;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Timers
|
* Timers
|
||||||
*
|
*
|
||||||
* Array of active timers
|
* Array of active timers
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @access private
|
* @access private
|
||||||
* @var array
|
* @var array
|
||||||
*/
|
*/
|
||||||
private static $timers = [];
|
private static $timers = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enabled
|
* Enabled
|
||||||
*
|
*
|
||||||
* Checks if the profiler is set to boolean true or if the passed type is
|
* Checks if the profiler is set to boolean true or if the passed type is
|
||||||
* specified in the profiler configuration value.
|
* specified in the profiler configuration value.
|
||||||
*
|
*
|
||||||
* @param array $type type(s) to check
|
* @param array $type type(s) to check
|
||||||
* @return boolean whether or not the type is enabled
|
* @return boolean whether or not the type is enabled
|
||||||
*/
|
*/
|
||||||
public static function enabled(/* polymorphic */)
|
public static function enabled(/* polymorphic */)
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config = isset($config->pickles['profiler']) ? $config->pickles['profiler'] : false;
|
$config = isset($config->pickles['profiler']) ? $config->pickles['profiler'] : false;
|
||||||
|
|
||||||
// Checks if we're set to boolean true
|
// Checks if we're set to boolean true
|
||||||
if ($config === true)
|
if ($config === true)
|
||||||
{
|
{
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$types = func_get_args();
|
$types = func_get_args();
|
||||||
|
|
||||||
foreach ($types as $type)
|
foreach ($types as $type)
|
||||||
{
|
{
|
||||||
if (stripos($config, $type) !== false)
|
if (stripos($config, $type) !== false)
|
||||||
{
|
{
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Log
|
* Log
|
||||||
*
|
*
|
||||||
* Logs the event to be displayed later on. Due to the nature of how much
|
* Logs the event to be displayed later on. Due to the nature of how much
|
||||||
* of a pain it is to determine which class method called this method I
|
* of a pain it is to determine which class method called this method I
|
||||||
* opted to make the method a passable argument for ease of use. Perhaps
|
* opted to make the method a passable argument for ease of use. Perhaps
|
||||||
* I'll revisit in the future. Handles all elapsed time calculations and
|
* I'll revisit in the future. Handles all elapsed time calculations and
|
||||||
* memory usage.
|
* memory usage.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param mixed $data data to log
|
* @param mixed $data data to log
|
||||||
* @param string $method name of the class method being logged
|
* @param string $method name of the class method being logged
|
||||||
*/
|
*/
|
||||||
public static function log($data, $method = false, $type = false)
|
public static function log($data, $method = false, $type = false)
|
||||||
{
|
{
|
||||||
$time = microtime(true);
|
$time = microtime(true);
|
||||||
$data_type = ($data == 'timer' ? $data : gettype($data));
|
$data_type = ($data == 'timer' ? $data : gettype($data));
|
||||||
|
|
||||||
// Tidys the data by type
|
// Tidys the data by type
|
||||||
switch ($data_type)
|
switch ($data_type)
|
||||||
{
|
{
|
||||||
case 'array':
|
case 'array':
|
||||||
$log = '<pre>' . print_r($data, true) . '</pre>';
|
$log = '<pre>' . print_r($data, true) . '</pre>';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'object':
|
case 'object':
|
||||||
$log = '<span style="color:#666">[</span><span style="color:#777">' . get_parent_class($data) . '</span><span style="color:#666">]</span> '
|
$log = '<span style="color:#666">[</span><span style="color:#777">' . get_parent_class($data) . '</span><span style="color:#666">]</span> '
|
||||||
. '<span style="color:#69c">' . get_class($data) . '</span>'
|
. '<span style="color:#69c">' . get_class($data) . '</span>'
|
||||||
. ($method != '' ? '<span style="color:#666">-></span><span style="color:#4eed9e">' . $method . '</span><span style="color:#666">()</span>' : '');
|
. ($method != '' ? '<span style="color:#666">-></span><span style="color:#4eed9e">' . $method . '</span><span style="color:#666">()</span>' : '');
|
||||||
|
|
||||||
$data_type = '<span style="color:Peru">' . $data_type . '</span>';
|
$data_type = '<span style="color:Peru">' . $data_type . '</span>';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'timer':
|
case 'timer':
|
||||||
$log = $method;
|
$log = $method;
|
||||||
|
|
||||||
$data_type = '<span style="color:#6c0">' . $data_type . '</span>';
|
$data_type = '<span style="color:#6c0">' . $data_type . '</span>';
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'string':
|
case 'string':
|
||||||
default:
|
default:
|
||||||
if ($type != false)
|
if ($type != false)
|
||||||
{
|
{
|
||||||
$data_type = $type;
|
$data_type = $type;
|
||||||
}
|
}
|
||||||
|
|
||||||
$log = $data;
|
$log = $data;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
self::$profile[] = [
|
self::$profile[] = [
|
||||||
'log' => $log,
|
'log' => $log,
|
||||||
'type' => $data_type,
|
'type' => $data_type,
|
||||||
'time' => $time,
|
'time' => $time,
|
||||||
'elapsed' => $time - $_SERVER['REQUEST_TIME_FLOAT'],
|
'elapsed' => $time - $_SERVER['REQUEST_TIME_FLOAT'],
|
||||||
'memory' => memory_get_usage(),
|
'memory' => memory_get_usage(),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Log Query
|
* Log Query
|
||||||
*
|
*
|
||||||
* Serves as a wrapper to get query data to the log function
|
* Serves as a wrapper to get query data to the log function
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $query the query being executed
|
* @param string $query the query being executed
|
||||||
* @param array $input_parameters optional prepared statement data
|
* @param array $input_parameters optional prepared statement data
|
||||||
* @param array $explain EXPLAIN data for the query
|
* @param array $explain EXPLAIN data for the query
|
||||||
* @param float $duration the speed of the query
|
* @param float $duration the speed of the query
|
||||||
*/
|
*/
|
||||||
public static function logQuery($query, $input_parameters = false, $explain = false, $duration = false)
|
public static function logQuery($query, $input_parameters = false, $explain = false, $duration = false)
|
||||||
{
|
{
|
||||||
self::$queries++;
|
self::$queries++;
|
||||||
|
|
||||||
$log = '';
|
$log = '';
|
||||||
|
|
||||||
if ($input_parameters != 'false' && is_array($input_parameters))
|
if ($input_parameters != 'false' && is_array($input_parameters))
|
||||||
{
|
{
|
||||||
$log .= '<br>';
|
$log .= '<br>';
|
||||||
|
|
||||||
foreach ($input_parameters as $key => $value)
|
foreach ($input_parameters as $key => $value)
|
||||||
{
|
{
|
||||||
$log .= '<br><span style="color:#a82222">' . $key . '</span> <span style="color:#666">=></span> <span style="color:#ffff7f">' . $value . '</span>';
|
$log .= '<br><span style="color:#a82222">' . $key . '</span> <span style="color:#666">=></span> <span style="color:#ffff7f">' . $value . '</span>';
|
||||||
|
|
||||||
$query = str_replace($key, '<span style="color:#a82222">' . $key . '</span>', $query);
|
$query = str_replace($key, '<span style="color:#a82222">' . $key . '</span>', $query);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$log = '<span style="color:#009600">' . $query . '</span>' . $log;
|
$log = '<span style="color:#009600">' . $query . '</span>' . $log;
|
||||||
|
|
||||||
if (is_array($explain))
|
if (is_array($explain))
|
||||||
{
|
{
|
||||||
$log .= '<br>';
|
$log .= '<br>';
|
||||||
|
|
||||||
foreach ($explain as $table)
|
foreach ($explain as $table)
|
||||||
{
|
{
|
||||||
$log .= '<br><span style="color:RoyalBlue">Possible Keys</span> <span style="color:#666">=></span> <span style="color:DarkGoldenRod">' . ($table['possible_keys'] == '' ? '<em style="color:red">NONE</em>' : $table['possible_keys']) . '</span>'
|
$log .= '<br><span style="color:RoyalBlue">Possible Keys</span> <span style="color:#666">=></span> <span style="color:DarkGoldenRod">' . ($table['possible_keys'] == '' ? '<em style="color:red">NONE</em>' : $table['possible_keys']) . '</span>'
|
||||||
. '<br><span style="color:RoyalBlue">Key</span> <span style="color:#666">=></span> <span style="color:DarkGoldenRod">' . ($table['key'] == '' ? '<em style="color:red">NONE</em>' : $table['key']) . '</span>'
|
. '<br><span style="color:RoyalBlue">Key</span> <span style="color:#666">=></span> <span style="color:DarkGoldenRod">' . ($table['key'] == '' ? '<em style="color:red">NONE</em>' : $table['key']) . '</span>'
|
||||||
. '<br><span style="color:RoyalBlue">Type</span> <span style="color:#666">=></span> <span style="color:DarkGoldenRod">' . $table['type'] . '</span>'
|
. '<br><span style="color:RoyalBlue">Type</span> <span style="color:#666">=></span> <span style="color:DarkGoldenRod">' . $table['type'] . '</span>'
|
||||||
. '<br><span style="color:RoyalBlue">Rows</span> <span style="color:#666">=></span> <span style="color:DarkGoldenRod">' . $table['rows'] . '</span>'
|
. '<br><span style="color:RoyalBlue">Rows</span> <span style="color:#666">=></span> <span style="color:DarkGoldenRod">' . $table['rows'] . '</span>'
|
||||||
. ($table['Extra'] != '' ? '<br><span style="color:RoyalBlue">Extra</span> <span style="color:#666">=></span> <span style="color:DarkGoldenRod">' . $table['Extra'] . '</span>' : '');
|
. ($table['Extra'] != '' ? '<br><span style="color:RoyalBlue">Extra</span> <span style="color:#666">=></span> <span style="color:DarkGoldenRod">' . $table['Extra'] . '</span>' : '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$log .= '<br><br><span style="color:DarkKhaki">Speed:</span> ' . number_format($duration * 100, 3) . ' ms';
|
$log .= '<br><br><span style="color:DarkKhaki">Speed:</span> ' . number_format($duration * 100, 3) . ' ms';
|
||||||
|
|
||||||
self::log($log, false, '<span style="color:DarkCyan">database</span>');
|
self::log($log, false, '<span style="color:DarkCyan">database</span>');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Timer
|
* Timer
|
||||||
*
|
*
|
||||||
* Logs the start and end of a timer.
|
* Logs the start and end of a timer.
|
||||||
*
|
*
|
||||||
* @param string $timer name of the timer
|
* @param string $timer name of the timer
|
||||||
* @return boolean whether or not timer profiling is enabled
|
* @return boolean whether or not timer profiling is enabled
|
||||||
*/
|
*/
|
||||||
public static function timer($timer)
|
public static function timer($timer)
|
||||||
{
|
{
|
||||||
if (self::enabled('timers'))
|
if (self::enabled('timers'))
|
||||||
{
|
{
|
||||||
// Starts the timer
|
// Starts the timer
|
||||||
if (!isset(self::$timers[$timer]))
|
if (!isset(self::$timers[$timer]))
|
||||||
{
|
{
|
||||||
self::$timers[$timer] = microtime(true);
|
self::$timers[$timer] = microtime(true);
|
||||||
self::Log('timer', '<span style="color:Orchid">Started timer</span> <span style="color:Yellow">' . $timer . '</span>');
|
self::Log('timer', '<span style="color:Orchid">Started timer</span> <span style="color:Yellow">' . $timer . '</span>');
|
||||||
}
|
}
|
||||||
// Ends the timer
|
// Ends the timer
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
self::Log('timer', '<span style="color:Orchid">Stopped timer</span> <span style="color:Yellow">' . $timer . '</span> <span style="color:#666">=></span> <span style="color:DarkKhaki">Time Elapsed:</span> ' . number_format((microtime(true) - self::$timers[$timer]) * 100, 3) . ' ms');
|
self::Log('timer', '<span style="color:Orchid">Stopped timer</span> <span style="color:Yellow">' . $timer . '</span> <span style="color:#666">=></span> <span style="color:DarkKhaki">Time Elapsed:</span> ' . number_format((microtime(true) - self::$timers[$timer]) * 100, 3) . ' ms');
|
||||||
|
|
||||||
unset(self::$timers[$timer]);
|
unset(self::$timers[$timer]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Report
|
* Report
|
||||||
*
|
*
|
||||||
* Generates the Profiler report that is displayed by the Controller.
|
* Generates the Profiler report that is displayed by the Controller.
|
||||||
* Contains all the HTML needed to display the data properly inline on the
|
* Contains all the HTML needed to display the data properly inline on the
|
||||||
* page. Will generally be displayed after the closing HTML tag.
|
* page. Will generally be displayed after the closing HTML tag.
|
||||||
*
|
*
|
||||||
* @todo Thinking this should return the report and not necessarily echo it
|
* @todo Thinking this should return the report and not necessarily echo it
|
||||||
*/
|
*/
|
||||||
public static function report()
|
public static function report()
|
||||||
{
|
{
|
||||||
?>
|
?>
|
||||||
<style>
|
<style>
|
||||||
#pickles-profiler
|
#pickles-profiler
|
||||||
{
|
{
|
||||||
background: #212121;
|
background: #212121;
|
||||||
width: 800px;
|
width: 800px;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
margin-top: 20px;
|
margin-top: 20px;
|
||||||
margin-bottom: 20px;
|
margin-bottom: 20px;
|
||||||
-moz-border-radius: 20px;
|
-moz-border-radius: 20px;
|
||||||
-webkit-border-radius: 20px;
|
-webkit-border-radius: 20px;
|
||||||
border-radius: 20px;
|
border-radius: 20px;
|
||||||
-moz-box-shadow: 0 3px 4px rgba(0,0,0,0.5);
|
-moz-box-shadow: 0 3px 4px rgba(0,0,0,0.5);
|
||||||
-webkit-box-shadow: 0 3px 4px rgba(0,0,0,0.5);
|
-webkit-box-shadow: 0 3px 4px rgba(0,0,0,0.5);
|
||||||
box-shadow: 0 3px 4px rgba(0,0,0,0.5);
|
box-shadow: 0 3px 4px rgba(0,0,0,0.5);
|
||||||
border: 6px solid #666;
|
border: 6px solid #666;
|
||||||
padding: 10px 20px 20px;
|
padding: 10px 20px 20px;
|
||||||
font-family: monospace;
|
font-family: monospace;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
text-align: left;
|
text-align: left;
|
||||||
}
|
}
|
||||||
#pickles-profiler table
|
#pickles-profiler table
|
||||||
{
|
{
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
#pickles-profiler table tr th, #pickles-profiler table tr td
|
#pickles-profiler table tr th, #pickles-profiler table tr td
|
||||||
{
|
{
|
||||||
padding: 10px;
|
padding: 10px;
|
||||||
}
|
}
|
||||||
#pickles-profiler .even
|
#pickles-profiler .even
|
||||||
{
|
{
|
||||||
background-color: #323232;
|
background-color: #323232;
|
||||||
}
|
}
|
||||||
#pickles-profiler, #pickles-profiler table tr td, #pickles-profiler table tr th
|
#pickles-profiler, #pickles-profiler table tr td, #pickles-profiler table tr th
|
||||||
{
|
{
|
||||||
color: #efefe8;
|
color: #efefe8;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<div id="pickles-profiler">
|
<div id="pickles-profiler">
|
||||||
<strong style="font-size:1.5em">PICKLES Profiler</strong><br><br>
|
<strong style="font-size:1.5em">PICKLES Profiler</strong><br><br>
|
||||||
<?php
|
<?php
|
||||||
if (count(self::$profile) == 0)
|
if (count(self::$profile) == 0)
|
||||||
{
|
{
|
||||||
echo '<em style="line-height:18px">There is nothing to profile. This often happens when the profiler configuration is set to either "queries" or "explains" and there are no database queries on the page (common on pages that only have a template). You may want to set the profiler to boolean true to ensure you get a profile of the page.</em>';
|
echo '<em style="line-height:18px">There is nothing to profile. This often happens when the profiler configuration is set to either "queries" or "explains" and there are no database queries on the page (common on pages that only have a template). You may want to set the profiler to boolean true to ensure you get a profile of the page.</em>';
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$start_time = $_SERVER['REQUEST_TIME_FLOAT'];
|
$start_time = $_SERVER['REQUEST_TIME_FLOAT'];
|
||||||
$peak_usage = self::formatSize(memory_get_peak_usage());
|
$peak_usage = self::formatSize(memory_get_peak_usage());
|
||||||
$end_time = self::$profile[count(self::$profile) - 1]['time']; // @todo No idea what though?
|
$end_time = self::$profile[count(self::$profile) - 1]['time']; // @todo No idea what though?
|
||||||
$duration = ($end_time - $start_time);
|
$duration = ($end_time - $start_time);
|
||||||
|
|
||||||
$logs = count(self::$profile);
|
$logs = count(self::$profile);
|
||||||
$logs .= ' Log' . ($logs == 1 ? '' : 's');
|
$logs .= ' Log' . ($logs == 1 ? '' : 's');
|
||||||
|
|
||||||
$files = count(get_included_files());
|
$files = count(get_included_files());
|
||||||
$files .= ' File' . ($files == 1 ? '' : 's');
|
$files .= ' File' . ($files == 1 ? '' : 's');
|
||||||
|
|
||||||
$queries = self::$queries . ' Quer'. (self::$queries == 1 ? 'y' : 'ies');
|
$queries = self::$queries . ' Quer'. (self::$queries == 1 ? 'y' : 'ies');
|
||||||
?>
|
?>
|
||||||
<table style="border-collapse:separate;border-spacing:1px;border-radius:10px;text-shadow:1px 1px 1px #000">
|
<table style="border-collapse:separate;border-spacing:1px;border-radius:10px;text-shadow:1px 1px 1px #000">
|
||||||
<tr>
|
<tr>
|
||||||
<td style="text-align:center;background:#480000">
|
<td style="text-align:center;background:#480000">
|
||||||
<span style="font-weight:bold;">Console</span>
|
<span style="font-weight:bold;">Console</span>
|
||||||
<div style="color:#ff7f7f;font-size:1.2em;padding-top:10px"><?php echo $logs; ?></div>
|
<div style="color:#ff7f7f;font-size:1.2em;padding-top:10px"><?= $logs; ?></div>
|
||||||
</td>
|
</td>
|
||||||
<td style="text-align:center;background:#552200">
|
<td style="text-align:center;background:#552200">
|
||||||
<span style="font-weight:bold;">Load Time</span>
|
<span style="font-weight:bold;">Load Time</span>
|
||||||
<div style="color:#ffa366;font-size:1.2em;padding-top:10px"><?php echo number_format($duration * 100, 3) . ' ms / ' . ini_get('max_execution_time'); ?></div>
|
<div style="color:#ffa366;font-size:1.2em;padding-top:10px"><?= number_format($duration * 100, 3) . ' ms / ' . ini_get('max_execution_time'); ?></div>
|
||||||
</td>
|
</td>
|
||||||
<td style="text-align:center;background:#545500">
|
<td style="text-align:center;background:#545500">
|
||||||
<span style="font-weight:bold;">Memory Usage</span>
|
<span style="font-weight:bold;">Memory Usage</span>
|
||||||
<div style="color:#ffff6d;font-size:1.2em;padding-top:10px"><?php echo $peak_usage . ' / ' . ini_get('memory_limit'); ?></div>
|
<div style="color:#ffff6d;font-size:1.2em;padding-top:10px"><?= $peak_usage . ' / ' . ini_get('memory_limit'); ?></div>
|
||||||
</td>
|
</td>
|
||||||
<td style="text-align:center;background:#004200">
|
<td style="text-align:center;background:#004200">
|
||||||
<span style="font-weight:bold;">Database</span>
|
<span style="font-weight:bold;">Database</span>
|
||||||
<div style="color:#7dff7d;font-size:1.2em;padding-top:10px"><?php echo $queries; ?></div>
|
<div style="color:#7dff7d;font-size:1.2em;padding-top:10px"><?= $queries; ?></div>
|
||||||
</td>
|
</td>
|
||||||
<td style="text-align:center;background:#000048">
|
<td style="text-align:center;background:#000048">
|
||||||
<span style="font-weight:bold;">Includes</span>
|
<span style="font-weight:bold;">Includes</span>
|
||||||
<div style="color:#c4c4ff;font-size:1.2em;padding-top:10px"><?php echo $files; ?></div>
|
<div style="color:#c4c4ff;font-size:1.2em;padding-top:10px"><?= $files; ?></div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
</table>
|
</table>
|
||||||
<table>
|
<table>
|
||||||
<tr>
|
<tr>
|
||||||
<th style="text-align:left" colspan="2">Console</th>
|
<th style="text-align:left" colspan="2">Console</th>
|
||||||
<th style="text-align:right">Memory</th>
|
<th style="text-align:right">Memory</th>
|
||||||
<th style="text-align:right">Time</th>
|
<th style="text-align:right">Time</th>
|
||||||
</tr>
|
</tr>
|
||||||
<?php
|
<?php
|
||||||
foreach (self::$profile as $key => $entry)
|
foreach (self::$profile as $key => $entry)
|
||||||
{
|
{
|
||||||
?>
|
?>
|
||||||
<tr>
|
<tr>
|
||||||
<td style="font-weight:bold;color:#999"><?php echo $entry['type']; ?></td>
|
<td style="font-weight:bold;color:#999"><?= $entry['type']; ?></td>
|
||||||
<td><?php echo $entry['log']; ?></td>
|
<td><?= $entry['log']; ?></td>
|
||||||
<td style="text-align:right" nowrap="nowrap"><?php echo self::formatSize($entry['memory']); ?></td>
|
<td style="text-align:right" nowrap="nowrap"><?= self::formatSize($entry['memory']); ?></td>
|
||||||
<td style="text-align:right" nowrap="nowrap"><?php echo number_format($entry['elapsed'] * 100, 3); ?> ms</td>
|
<td style="text-align:right" nowrap="nowrap"><?= number_format($entry['elapsed'] * 100, 3); ?> ms</td>
|
||||||
</tr>
|
</tr>
|
||||||
<?php
|
<?php
|
||||||
}
|
}
|
||||||
?>
|
?>
|
||||||
</table>
|
</table>
|
||||||
<?php
|
<?php
|
||||||
}
|
}
|
||||||
?>
|
?>
|
||||||
</div>
|
</div>
|
||||||
<br><br>
|
<br><br>
|
||||||
<?php
|
<?php
|
||||||
self::$profile = [];
|
self::$profile = [];
|
||||||
self::$queries = 0;
|
self::$queries = 0;
|
||||||
self::$timers = [];
|
self::$timers = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Format Size
|
* Format Size
|
||||||
*
|
*
|
||||||
* Formats the passed size into a human readable string
|
* Formats the passed size into a human readable string
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @access private
|
* @access private
|
||||||
* @param float $filesize size of the file
|
* @param float $filesize size of the file
|
||||||
* @return string formatted number string
|
* @return string formatted number string
|
||||||
* @todo Probably can move this elsewhere and make it public
|
* @todo Probably can move this elsewhere and make it public
|
||||||
*/
|
*/
|
||||||
private static function formatSize($filesize)
|
private static function formatSize($filesize)
|
||||||
{
|
{
|
||||||
$units = ['bytes', 'kB', 'MB', 'GB'];
|
$units = ['bytes', 'kB', 'MB', 'GB'];
|
||||||
|
|
||||||
return number_format(round($filesize / pow(1024, ($i = floor(log($filesize, 1024)))), 2), 2) . ' ' . $units[$i];
|
return number_format(round($filesize / pow(1024, ($i = floor(log($filesize, 1024)))), 2), 2) . ' ' . $units[$i];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -26,318 +26,317 @@
|
||||||
*/
|
*/
|
||||||
class Security
|
class Security
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Lookup Cache
|
* Lookup Cache
|
||||||
*
|
*
|
||||||
* Used to minimize database lookups
|
* Used to minimize database lookups
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @access private
|
* @access private
|
||||||
* @var array
|
* @var array
|
||||||
*/
|
*/
|
||||||
private static $cache = [];
|
private static $cache = [];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate Hash
|
* Generate Hash
|
||||||
*
|
*
|
||||||
* Generates an SHA1 hash from the provided string. Salt optional.
|
* Generates an SHA1 hash from the provided string. Salt optional.
|
||||||
*
|
*
|
||||||
* @param string $source value to hash
|
* @param string $source value to hash
|
||||||
* @param mixed $salts optional salt or salts
|
* @param mixed $salts optional salt or salts
|
||||||
* @return string SHA1 hash
|
* @return string SHA1 hash
|
||||||
* @todo Transition away from this
|
* @todo Transition away from this
|
||||||
*/
|
*/
|
||||||
public static function generateHash($source, $salts = null)
|
public static function generateHash($source, $salts = null)
|
||||||
{
|
{
|
||||||
// Determines which salt(s) to use
|
// Determines which salt(s) to use
|
||||||
if ($salts == null)
|
if ($salts == null)
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
|
|
||||||
if (isset($config->security['salt']) && $config->security['salt'] != null)
|
if (isset($config->security['salt']) && $config->security['salt'] != null)
|
||||||
{
|
{
|
||||||
$salts = $config->security['salt'];
|
$salts = $config->security['salt'];
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$salts = ['P1ck73', 'Ju1C3'];
|
$salts = ['P1ck73', 'Ju1C3'];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Forces the variable to be an array
|
// Forces the variable to be an array
|
||||||
if (!is_array($salts))
|
if (!is_array($salts))
|
||||||
{
|
{
|
||||||
$salts = [$salts];
|
$salts = [$salts];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Loops through the salts, applies them and calculates the hash
|
// Loops through the salts, applies them and calculates the hash
|
||||||
$hash = $source;
|
$hash = $source;
|
||||||
|
|
||||||
foreach ($salts as $salt)
|
foreach ($salts as $salt)
|
||||||
{
|
{
|
||||||
$hash = sha1($salt . $hash);
|
$hash = sha1($salt . $hash);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $hash;
|
return $hash;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate SHA-256 Hash
|
* Generate SHA-256 Hash
|
||||||
*
|
*
|
||||||
* Generates an SHA-256 hash from the provided string and salt. Borrowed the
|
* Generates an SHA-256 hash from the provided string and salt. Borrowed the
|
||||||
* large iteration logic from fCryptography::hashWithSalt() as, and I quote,
|
* large iteration logic from fCryptography::hashWithSalt() as, and I quote,
|
||||||
* "makes rainbow table attacks infesible".
|
* "makes rainbow table attacks infesible".
|
||||||
*
|
*
|
||||||
* @param string $source value to hash
|
* @param string $source value to hash
|
||||||
* @param mixed $salt value to use as salt
|
* @param mixed $salt value to use as salt
|
||||||
* @return string SHA-256 hash
|
* @return string SHA-256 hash
|
||||||
* @link https://github.com/flourishlib/flourish-classes/blob/master/fCryptography.php
|
* @link https://github.com/flourishlib/flourish-classes/blob/master/fCryptography.php
|
||||||
*/
|
*/
|
||||||
public static function generateSHA256Hash($source, $salt)
|
public static function generateSHA256Hash($source, $salt)
|
||||||
{
|
{
|
||||||
$sha256 = sha1($salt . $source);
|
$sha256 = sha1($salt . $source);
|
||||||
|
|
||||||
for ($i = 0; $i < 1000; $i++)
|
for ($i = 0; $i < 1000; $i++)
|
||||||
{
|
{
|
||||||
$sha256 = hash('sha256', $sha256 . (($i % 2 == 0) ? $source : $salt));
|
$sha256 = hash('sha256', $sha256 . (($i % 2 == 0) ? $source : $salt));
|
||||||
}
|
}
|
||||||
|
|
||||||
return $sha256;
|
return $sha256;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check Session
|
* Check Session
|
||||||
*
|
*
|
||||||
* Checks if sessions are enabled.
|
* Checks if sessions are enabled.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @access private
|
* @access private
|
||||||
* @return boolean whether or not sessions are enabled
|
* @return boolean whether or not sessions are enabled
|
||||||
*/
|
*/
|
||||||
private static function checkSession()
|
private static function checkSession()
|
||||||
{
|
{
|
||||||
if (session_id() == '')
|
if (session_id() == '')
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check Level
|
* Check Level
|
||||||
*
|
*
|
||||||
* Checks if a passed level is an integer and/or properly defined in the
|
* Checks if a passed level is an integer and/or properly defined in the
|
||||||
* site's configuration file.
|
* site's configuration file.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @access private
|
* @access private
|
||||||
* @param mixed access level to validate
|
* @param mixed access level to validate
|
||||||
* @return whether ot not the access level is valid
|
* @return whether ot not the access level is valid
|
||||||
*/
|
*/
|
||||||
private static function checkLevel(&$access_level)
|
private static function checkLevel(&$access_level)
|
||||||
{
|
{
|
||||||
return is_int($access_level);
|
return is_int($access_level);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Login
|
* Login
|
||||||
*
|
*
|
||||||
* Creates a session variable containing the user ID and generated token.
|
* Creates a session variable containing the user ID and generated token.
|
||||||
* The token is also assigned to a cookie to be used when validating the
|
* The token is also assigned to a cookie to be used when validating the
|
||||||
* security level. When the level value is present, the class will by pass
|
* security level. When the level value is present, the class will by pass
|
||||||
* the database look up and simply use that value when validating (the less
|
* the database look up and simply use that value when validating (the less
|
||||||
* paranoid scenario).
|
* paranoid scenario).
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param integer $user_id ID of the user that's been logged in
|
* @param integer $user_id ID of the user that's been logged in
|
||||||
* @param integer $level optional level for the user being logged in
|
* @param integer $level optional level for the user being logged in
|
||||||
* @param string $role textual representation of the user's level
|
* @param string $role textual representation of the user's level
|
||||||
* @return boolean whether or not the login could be completed
|
* @return boolean whether or not the login could be completed
|
||||||
*/
|
*/
|
||||||
public static function login($user_id, $level = null, $role = null)
|
public static function login($user_id, $level = null, $role = null)
|
||||||
{
|
{
|
||||||
if (self::checkSession())
|
if (self::checkSession())
|
||||||
{
|
{
|
||||||
$token = sha1(microtime());
|
$token = sha1(microtime());
|
||||||
|
|
||||||
$_SESSION['__pickles']['security'] = [
|
$_SESSION['__pickles']['security'] = [
|
||||||
'token' => $token,
|
'token' => $token,
|
||||||
'user_id' => (int)$user_id,
|
'user_id' => (int)$user_id,
|
||||||
'level' => $level,
|
'level' => $level,
|
||||||
'role' => $role,
|
'role' => $role,
|
||||||
];
|
];
|
||||||
|
|
||||||
setcookie('pickles_security_token', $token);
|
setcookie('pickles_security_token', $token);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logout
|
* Logout
|
||||||
*
|
*
|
||||||
* Clears out the security information in the session and the cookie.
|
* Clears out the security information in the session and the cookie.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @return boolean true
|
* @return boolean true
|
||||||
*/
|
*/
|
||||||
public static function logout()
|
public static function logout()
|
||||||
{
|
{
|
||||||
if (isset($_SESSION['__pickles']['security']))
|
if (isset($_SESSION['__pickles']['security']))
|
||||||
{
|
{
|
||||||
$_SESSION['__pickles']['security'] = null;
|
$_SESSION['__pickles']['security'] = null;
|
||||||
unset($_SESSION['__pickles']['security']);
|
unset($_SESSION['__pickles']['security']);
|
||||||
|
|
||||||
setcookie('pickles_security_token', '', time() - 3600);
|
setcookie('pickles_security_token', '', time() - 3600);
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get User Level
|
* Get User Level
|
||||||
*
|
*
|
||||||
* Looks up the user level in the database and caches it. Cache is used
|
* Looks up the user level in the database and caches it. Cache is used
|
||||||
* for any subsequent look ups for the user. Also validates the session
|
* for any subsequent look ups for the user. Also validates the session
|
||||||
* variable against the cookie to ensure everything is legit. If the user
|
* variable against the cookie to ensure everything is legit. If the user
|
||||||
* level is set in the session, that value will take precedence.
|
* level is set in the session, that value will take precedence.
|
||||||
*
|
*
|
||||||
* return integer user level or false
|
* return integer user level or false
|
||||||
*/
|
*/
|
||||||
private static function getUserLevel()
|
private static function getUserLevel()
|
||||||
{
|
{
|
||||||
if (self::checkSession() == true && isset($_SESSION['__pickles']['security']['user_id']))
|
if (self::checkSession() == true && isset($_SESSION['__pickles']['security']['user_id']))
|
||||||
{
|
{
|
||||||
// Checks the session against the cookie
|
// Checks the session against the cookie
|
||||||
if (isset($_SESSION['__pickles']['security']['token'], $_COOKIE['pickles_security_token'])
|
if (isset($_SESSION['__pickles']['security']['token'], $_COOKIE['pickles_security_token'])
|
||||||
&& $_SESSION['__pickles']['security']['token'] != $_COOKIE['pickles_security_token'])
|
&& $_SESSION['__pickles']['security']['token'] != $_COOKIE['pickles_security_token'])
|
||||||
{
|
{
|
||||||
Security::logout();
|
Security::logout();
|
||||||
}
|
}
|
||||||
elseif (isset($_SESSION['__pickles']['security']['level']) && $_SESSION['__pickles']['security']['level'] != null)
|
elseif (isset($_SESSION['__pickles']['security']['level']) && $_SESSION['__pickles']['security']['level'] != null)
|
||||||
{
|
{
|
||||||
return $_SESSION['__pickles']['security']['level'];
|
return $_SESSION['__pickles']['security']['level'];
|
||||||
}
|
}
|
||||||
// Used to hit the database to determine the user's level, found it
|
// Used to hit the database to determine the user's level, found it
|
||||||
// to be overkill and just opted for a simple logout.
|
// to be overkill and just opted for a simple logout.
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Security::logout();
|
Security::logout();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Is Level
|
* Is Level
|
||||||
*
|
*
|
||||||
* Checks the user's access level is exactly the passed level
|
* Checks the user's access level is exactly the passed level
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param integer $access_level access level to be checked against
|
* @param integer $access_level access level to be checked against
|
||||||
* @return boolean whether or not the user is that level
|
* @return boolean whether or not the user is that level
|
||||||
*/
|
*/
|
||||||
public static function isLevel()
|
public static function isLevel()
|
||||||
{
|
{
|
||||||
$is_level = false;
|
$is_level = false;
|
||||||
|
|
||||||
if (self::checkSession())
|
if (self::checkSession())
|
||||||
{
|
{
|
||||||
$arguments = func_get_args();
|
$arguments = func_get_args();
|
||||||
if (is_array($arguments[0]))
|
if (is_array($arguments[0]))
|
||||||
{
|
{
|
||||||
$arguments = $arguments[0];
|
$arguments = $arguments[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($arguments as $access_level)
|
foreach ($arguments as $access_level)
|
||||||
{
|
{
|
||||||
if (self::checkLevel($access_level))
|
if (self::checkLevel($access_level))
|
||||||
{
|
{
|
||||||
if (self::getUserLevel() == $access_level)
|
if (self::getUserLevel() == $access_level)
|
||||||
{
|
{
|
||||||
$is_level = true;
|
$is_level = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $is_level;
|
return $is_level;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Has Level
|
* Has Level
|
||||||
*
|
*
|
||||||
* Checks the user's access level against the passed level.
|
* Checks the user's access level against the passed level.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param integer $access_level access level to be checked against
|
* @param integer $access_level access level to be checked against
|
||||||
* @return boolean whether or not the user has access
|
* @return boolean whether or not the user has access
|
||||||
*/
|
*/
|
||||||
public static function hasLevel()
|
public static function hasLevel()
|
||||||
{
|
{
|
||||||
$has_level = false;
|
$has_level = false;
|
||||||
|
|
||||||
if (self::checkSession())
|
if (self::checkSession())
|
||||||
{
|
{
|
||||||
$arguments = func_get_args();
|
$arguments = func_get_args();
|
||||||
|
|
||||||
if (is_array($arguments[0]))
|
if (is_array($arguments[0]))
|
||||||
{
|
{
|
||||||
$arguments = $arguments[0];
|
$arguments = $arguments[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($arguments as $access_level)
|
foreach ($arguments as $access_level)
|
||||||
{
|
{
|
||||||
if (self::checkLevel($access_level))
|
if (self::checkLevel($access_level))
|
||||||
{
|
{
|
||||||
if (self::getUserLevel() >= $access_level)
|
if (self::getUserLevel() >= $access_level)
|
||||||
{
|
{
|
||||||
$has_level = true;
|
$has_level = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $has_level;
|
return $has_level;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Between Level
|
* Between Level
|
||||||
*
|
*
|
||||||
* Checks the user's access level against the passed range.
|
* Checks the user's access level against the passed range.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param integer $low access level to be checked against
|
* @param integer $low access level to be checked against
|
||||||
* @param integer $high access level to be checked against
|
* @param integer $high access level to be checked against
|
||||||
* @return boolean whether or not the user has access
|
* @return boolean whether or not the user has access
|
||||||
*/
|
*/
|
||||||
public static function betweenLevel($low, $high)
|
public static function betweenLevel($low, $high)
|
||||||
{
|
{
|
||||||
$between_level = false;
|
$between_level = false;
|
||||||
|
|
||||||
if (self::checkSession())
|
if (self::checkSession())
|
||||||
{
|
{
|
||||||
if (self::checkLevel($low) && self::checkLevel($high))
|
if (self::checkLevel($low) && self::checkLevel($high))
|
||||||
{
|
{
|
||||||
$user_level = self::getUserLevel();
|
$user_level = self::getUserLevel();
|
||||||
|
|
||||||
if ($user_level >= $low && $user_level <= $high)
|
if ($user_level >= $low && $user_level <= $high)
|
||||||
{
|
{
|
||||||
$between_level = true;
|
$between_level = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $between_level;
|
return $between_level;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -26,101 +26,100 @@
|
||||||
*/
|
*/
|
||||||
class Session extends Object
|
class Session extends Object
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Constructor
|
* Constructor
|
||||||
*
|
*
|
||||||
* All of our set up logic for the session in contained here. This class is
|
* All of our set up logic for the session in contained here. This class is
|
||||||
* initially instantiated from pickles.php. Non-file handlers need to be
|
* initially instantiated from pickles.php. Non-file handlers need to be
|
||||||
* configured in the site's config. MySQL support was dropped in favor of
|
* configured in the site's config. MySQL support was dropped in favor of
|
||||||
* in memory stores or simply relying on file based sessions. Why? Because
|
* in memory stores or simply relying on file based sessions. Why? Because
|
||||||
* using MySQL for sessions is very write intensive and having done it in
|
* using MySQL for sessions is very write intensive and having done it in
|
||||||
* the past I don't recommend it. If you run a single server, files are
|
* the past I don't recommend it. If you run a single server, files are
|
||||||
* good enough if your volume is lower. Memcache[d] is fine if you don't
|
* good enough if your volume is lower. Memcache[d] is fine if you don't
|
||||||
* mind logging all of your users off your site when you restart the
|
* mind logging all of your users off your site when you restart the
|
||||||
* service and/or you run out of memory for the process. Redis is the best
|
* service and/or you run out of memory for the process. Redis is the best
|
||||||
* choice as it can be configured to be persistent and lives in memory.
|
* choice as it can be configured to be persistent and lives in memory.
|
||||||
* This is assuming you don't just want to roll your own sessions, which is
|
* This is assuming you don't just want to roll your own sessions, which is
|
||||||
* pretty damn easy as well.
|
* pretty damn easy as well.
|
||||||
*/
|
*/
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
if (isset($_SERVER['REQUEST_METHOD']))
|
if (isset($_SERVER['REQUEST_METHOD']))
|
||||||
{
|
{
|
||||||
parent::__construct();
|
parent::__construct();
|
||||||
|
|
||||||
// Sets up our configuration variables
|
// Sets up our configuration variables
|
||||||
if (isset($this->config->pickles['sessions']))
|
if (isset($this->config->pickles['sessions']))
|
||||||
{
|
{
|
||||||
$session = $this->config->pickles['sessions'];
|
$session = $this->config->pickles['sessions'];
|
||||||
}
|
}
|
||||||
|
|
||||||
$datasources = $this->config->datasources;
|
$datasources = $this->config->datasources;
|
||||||
$handler = 'files';
|
$handler = 'files';
|
||||||
$datasource = false;
|
$datasource = false;
|
||||||
|
|
||||||
if (isset($session, $datasources[$session]))
|
if (isset($session, $datasources[$session]))
|
||||||
{
|
{
|
||||||
$datasource = $datasources[$session];
|
$datasource = $datasources[$session];
|
||||||
$handler = $datasource['type'];
|
$handler = $datasource['type'];
|
||||||
|
|
||||||
if ($handler != 'files')
|
if ($handler != 'files')
|
||||||
{
|
{
|
||||||
if (isset($datasource['hostname'], $datasource['port']))
|
if (isset($datasource['hostname'], $datasource['port']))
|
||||||
{
|
{
|
||||||
$host = ($handler != 'memcached' ? 'tcp://' : '')
|
$host = ($handler != 'memcached' ? 'tcp://' : '')
|
||||||
. $datasource['hostname'] . ':' . $datasource['port'];
|
. $datasource['hostname'] . ':' . $datasource['port'];
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
throw new Exception('You must provide both the hostname and port for the datasource.');
|
throw new Exception('You must provide both the hostname and port for the datasource.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
switch ($handler)
|
switch ($handler)
|
||||||
{
|
{
|
||||||
case 'memcache':
|
case 'memcache':
|
||||||
ini_set('session.save_handler', 'memcache');
|
ini_set('session.save_handler', 'memcache');
|
||||||
ini_set('session.save_path', $host . '?persistent=1&weight=1&timeout=1&retry_interval=15');
|
ini_set('session.save_path', $host . '?persistent=1&weight=1&timeout=1&retry_interval=15');
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'memcached':
|
case 'memcached':
|
||||||
ini_set('session.save_handler', 'memcached');
|
ini_set('session.save_handler', 'memcached');
|
||||||
ini_set('session.save_path', $host);
|
ini_set('session.save_path', $host);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'redis':
|
case 'redis':
|
||||||
$save_path = $host . '?weight=1';
|
$save_path = $host . '?weight=1';
|
||||||
|
|
||||||
// Database ignored by phpredis when this was coded
|
// Database ignored by phpredis when this was coded
|
||||||
if (isset($datasource['database']))
|
if (isset($datasource['database']))
|
||||||
{
|
{
|
||||||
$save_path .= '&database=' . $datasource['database'];
|
$save_path .= '&database=' . $datasource['database'];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isset($datasource['prefix']))
|
if (isset($datasource['prefix']))
|
||||||
{
|
{
|
||||||
$save_path .= '&prefix=' . $datasource['prefix'];
|
$save_path .= '&prefix=' . $datasource['prefix'];
|
||||||
}
|
}
|
||||||
|
|
||||||
ini_set('session.save_handler', 'redis');
|
ini_set('session.save_handler', 'redis');
|
||||||
ini_set('session.save_path', $save_path);
|
ini_set('session.save_path', $save_path);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'files':
|
case 'files':
|
||||||
ini_set('session.save_handler', 'files');
|
ini_set('session.save_handler', 'files');
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Don't start sessions for people without a user agent and bots.
|
// Don't start sessions for people without a user agent and bots.
|
||||||
if (isset($_SERVER['HTTP_USER_AGENT'])
|
if (isset($_SERVER['HTTP_USER_AGENT'])
|
||||||
&& !String::isEmpty($_SERVER['HTTP_USER_AGENT'])
|
&& !String::isEmpty($_SERVER['HTTP_USER_AGENT'])
|
||||||
&& !preg_match('/(Baidu|Gigabot|Googlebot|libwww-perl|lwp-trivial|msnbot|SiteUptime|Slurp|WordPress|ZIBB|ZyBorg)/i', $_SERVER['HTTP_USER_AGENT']))
|
&& !preg_match('/(Baidu|Gigabot|Googlebot|libwww-perl|lwp-trivial|msnbot|SiteUptime|Slurp|WordPress|ZIBB|ZyBorg)/i', $_SERVER['HTTP_USER_AGENT']))
|
||||||
{
|
{
|
||||||
session_start();
|
session_start();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -23,50 +23,49 @@
|
||||||
*/
|
*/
|
||||||
class Sort
|
class Sort
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Ascending
|
* Ascending
|
||||||
*
|
*
|
||||||
* Variable to utilize ascending sort
|
* Variable to utilize ascending sort
|
||||||
*
|
*
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
const ASC = 'ASC';
|
const ASC = 'ASC';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Descending
|
* Descending
|
||||||
*
|
*
|
||||||
* Variable to utilize descending sort
|
* Variable to utilize descending sort
|
||||||
*
|
*
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
const DESC = 'DESC';
|
const DESC = 'DESC';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sort By
|
* Sort By
|
||||||
*
|
*
|
||||||
* Sorts an array by the specified column, optionally in either direction.
|
* Sorts an array by the specified column, optionally in either direction.
|
||||||
*
|
*
|
||||||
* @param string $field field to sort by
|
* @param string $field field to sort by
|
||||||
* @param array $array array to sort
|
* @param array $array array to sort
|
||||||
* @param string $direction optional direction to sort
|
* @param string $direction optional direction to sort
|
||||||
* @retun boolean true because sorting is done by reference
|
* @retun boolean true because sorting is done by reference
|
||||||
*/
|
*/
|
||||||
public static function by($field, &$array, $direction = Sort::ASC)
|
public static function by($field, &$array, $direction = Sort::ASC)
|
||||||
{
|
{
|
||||||
usort($array, create_function('$a, $b', '
|
usort($array, create_function('$a, $b', '
|
||||||
$a = $a["' . $field . '"];
|
$a = $a["' . $field . '"];
|
||||||
$b = $b["' . $field . '"];
|
$b = $b["' . $field . '"];
|
||||||
|
|
||||||
if ($a == $b)
|
if ($a == $b)
|
||||||
{
|
{
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
return ($a ' . ($direction == Sort::DESC ? '>' : '<') .' $b) ? -1 : 1;
|
return ($a ' . ($direction == Sort::DESC ? '>' : '<') .' $b) ? -1 : 1;
|
||||||
'));
|
'));
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -23,244 +23,243 @@
|
||||||
*/
|
*/
|
||||||
class String
|
class String
|
||||||
{
|
{
|
||||||
// {{{ Format Phone Number
|
// {{{ Format Phone Number
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Format Phone Number
|
* Format Phone Number
|
||||||
*
|
*
|
||||||
* Formats a 10 digit phone number with dashes as ###-###-####.
|
* Formats a 10 digit phone number with dashes as ###-###-####.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $number number to format
|
* @param string $number number to format
|
||||||
* @param string $replacement output of the string
|
* @param string $replacement output of the string
|
||||||
* @return string formatted phone number
|
* @return string formatted phone number
|
||||||
*/
|
*/
|
||||||
public static function formatPhoneNumber($number, $replacement = '$1-$2-$3')
|
public static function formatPhoneNumber($number, $replacement = '$1-$2-$3')
|
||||||
{
|
{
|
||||||
// Strips characters we don't need
|
// Strips characters we don't need
|
||||||
$number = str_replace(['(', ')', ' ', '-', '.', '_'], '', $number);
|
$number = str_replace(['(', ')', ' ', '-', '.', '_'], '', $number);
|
||||||
|
|
||||||
// Formats the number
|
// Formats the number
|
||||||
return preg_replace('/^(\d{3})(\d{3})(.+)$/', $replacement, $number);
|
return preg_replace('/^(\d{3})(\d{3})(.+)$/', $replacement, $number);
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
// {{{ Generate Gravatar Hash
|
// {{{ Generate Gravatar Hash
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate Gravatar Hash
|
* Generate Gravatar Hash
|
||||||
*
|
*
|
||||||
* Generates a hash from the passed string that can then be used for
|
* Generates a hash from the passed string that can then be used for
|
||||||
* fetching an avatar from Gravatar.com
|
* fetching an avatar from Gravatar.com
|
||||||
*
|
*
|
||||||
* @deprecated
|
* @deprecated
|
||||||
* @static
|
* @static
|
||||||
* @param string $string string to hash, should be an email address
|
* @param string $string string to hash, should be an email address
|
||||||
* @return string resulting hash
|
* @return string resulting hash
|
||||||
*/
|
*/
|
||||||
public static function generateGravatarHash($string)
|
public static function generateGravatarHash($string)
|
||||||
{
|
{
|
||||||
return API_Gravatar::hash($string);
|
return API_Gravatar::hash($string);
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
// {{{ Generate Slug
|
// {{{ Generate Slug
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate Slug
|
* Generate Slug
|
||||||
*
|
*
|
||||||
* Generates a slug from the pass string by lowercasing the string,
|
* Generates a slug from the pass string by lowercasing the string,
|
||||||
* trimming whitespace and converting non-alphanumeric values to
|
* trimming whitespace and converting non-alphanumeric values to
|
||||||
* dashes. Takes care of multiple dashes as well.
|
* dashes. Takes care of multiple dashes as well.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $string to be converted to the slug
|
* @param string $string to be converted to the slug
|
||||||
* @return string resulting slug
|
* @return string resulting slug
|
||||||
*/
|
*/
|
||||||
public static function generateSlug($string)
|
public static function generateSlug($string)
|
||||||
{
|
{
|
||||||
$string = strtolower(trim($string));
|
$string = strtolower(trim($string));
|
||||||
$string = preg_replace('/[^a-z0-9-]/', '-', $string);
|
$string = preg_replace('/[^a-z0-9-]/', '-', $string);
|
||||||
$string = preg_replace('/-+/', '-', $string);
|
$string = preg_replace('/-+/', '-', $string);
|
||||||
return trim($string, '-');;
|
return trim($string, '-');;
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
// {{{ Is Empty
|
// {{{ Is Empty
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Is Empty
|
* Is Empty
|
||||||
*
|
*
|
||||||
* Checks if a string is empty. You can use the PHP function empty()
|
* Checks if a string is empty. You can use the PHP function empty()
|
||||||
* but that returns true for a string of "0". Last I checked, that's
|
* but that returns true for a string of "0". Last I checked, that's
|
||||||
* not an empty string. PHP's function also doesn't apply trim() to the
|
* not an empty string. PHP's function also doesn't apply trim() to the
|
||||||
* value to ensure it's not just a bunch of spaces.
|
* value to ensure it's not just a bunch of spaces.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $value string(s) to be checked
|
* @param string $value string(s) to be checked
|
||||||
* @return boolean whether or not the string is empty
|
* @return boolean whether or not the string is empty
|
||||||
*/
|
*/
|
||||||
public static function isEmpty()
|
public static function isEmpty()
|
||||||
{
|
{
|
||||||
foreach (func_get_args() as $value)
|
foreach (func_get_args() as $value)
|
||||||
{
|
{
|
||||||
if (trim($value) == '')
|
if (trim($value) == '')
|
||||||
{
|
{
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
// {{{ Pluralize
|
// {{{ Pluralize
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pluralize
|
* Pluralize
|
||||||
*
|
*
|
||||||
* Based on a passed integer, the word will be pluralized. A value of
|
* Based on a passed integer, the word will be pluralized. A value of
|
||||||
* zero will also pluralize the word (e.g. 0 things not 0 thing).
|
* zero will also pluralize the word (e.g. 0 things not 0 thing).
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $string the word to plurailze
|
* @param string $string the word to plurailze
|
||||||
* @param integer $count the count to interrogate
|
* @param integer $count the count to interrogate
|
||||||
* @param boolean $both (optional) include count in return
|
* @param boolean $both (optional) include count in return
|
||||||
* @return string pluralized word
|
* @return string pluralized word
|
||||||
*/
|
*/
|
||||||
public static function pluralize($string, $count, $both = false)
|
public static function pluralize($string, $count, $both = false)
|
||||||
{
|
{
|
||||||
if ($count != 1)
|
if ($count != 1)
|
||||||
{
|
{
|
||||||
$string .= 's';
|
$string .= 's';
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($both)
|
if ($both)
|
||||||
{
|
{
|
||||||
$string = $count . ' ' . $string;
|
$string = $count . ' ' . $string;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $string;
|
return $string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
// {{{ Random
|
// {{{ Random
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Random
|
* Random
|
||||||
*
|
*
|
||||||
* Generates a pseudo-random string based on the passed parameters.
|
* Generates a pseudo-random string based on the passed parameters.
|
||||||
*
|
*
|
||||||
* Note: Similar characters = 0, O, 1, I (and may be expanded)
|
* Note: Similar characters = 0, O, 1, I (and may be expanded)
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param integer $length optional length of the generated string
|
* @param integer $length optional length of the generated string
|
||||||
* @param boolean $alpha optional include alpha characters
|
* @param boolean $alpha optional include alpha characters
|
||||||
* @param boolean $numeric optional include numeric characters
|
* @param boolean $numeric optional include numeric characters
|
||||||
* @param boolean $similar optional include similar characters
|
* @param boolean $similar optional include similar characters
|
||||||
* @return string generated string
|
* @return string generated string
|
||||||
*/
|
*/
|
||||||
public static function random($length = 8, $alpha = true, $numeric = true, $similar = true)
|
public static function random($length = 8, $alpha = true, $numeric = true, $similar = true)
|
||||||
{
|
{
|
||||||
$characters = [];
|
$characters = [];
|
||||||
$string = '';
|
$string = '';
|
||||||
|
|
||||||
// Adds alpha characters to the list
|
// Adds alpha characters to the list
|
||||||
if ($alpha == true)
|
if ($alpha == true)
|
||||||
{
|
{
|
||||||
if ($similar == true)
|
if ($similar == true)
|
||||||
{
|
{
|
||||||
$characters = array_merge($characters, range('a', 'z'));
|
$characters = array_merge($characters, range('a', 'z'));
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$characters = array_merge($characters, range('a', 'h'), range('j', 'n'), range('p', 'z'));
|
$characters = array_merge($characters, range('a', 'h'), range('j', 'n'), range('p', 'z'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Adds numeric characters to the list
|
// Adds numeric characters to the list
|
||||||
if ($numeric == true)
|
if ($numeric == true)
|
||||||
{
|
{
|
||||||
if ($similar == true)
|
if ($similar == true)
|
||||||
{
|
{
|
||||||
$characters = array_merge($characters, range('0', '9'));
|
$characters = array_merge($characters, range('0', '9'));
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$characters = array_merge($characters, range('2', '9'));
|
$characters = array_merge($characters, range('2', '9'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (count($characters) > 0)
|
if (count($characters) > 0)
|
||||||
{
|
{
|
||||||
shuffle($characters);
|
shuffle($characters);
|
||||||
|
|
||||||
for ($i = 0; $i < $length; $i++)
|
for ($i = 0; $i < $length; $i++)
|
||||||
{
|
{
|
||||||
$string .= $characters[array_rand($characters)];
|
$string .= $characters[array_rand($characters)];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $string;
|
return $string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
// {{{ Truncate
|
// {{{ Truncate
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Truncate
|
* Truncate
|
||||||
*
|
*
|
||||||
* Truncates a string to a specified length and (optionally) adds a
|
* Truncates a string to a specified length and (optionally) adds a
|
||||||
* span to provide a rollover to see the expanded text.
|
* span to provide a rollover to see the expanded text.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $string string to truncate
|
* @param string $string string to truncate
|
||||||
* @param integer $length length to truncate to
|
* @param integer $length length to truncate to
|
||||||
* @param boolean $hover (optional) whether or not to add the rollover
|
* @param boolean $hover (optional) whether or not to add the rollover
|
||||||
* @return string truncate string
|
* @return string truncate string
|
||||||
*/
|
*/
|
||||||
public static function truncate($string, $length, $hover = true)
|
public static function truncate($string, $length, $hover = true)
|
||||||
{
|
{
|
||||||
if (strlen($string) > $length)
|
if (strlen($string) > $length)
|
||||||
{
|
{
|
||||||
if ($hover == true)
|
if ($hover == true)
|
||||||
{
|
{
|
||||||
$string = '<span title="' . $string . '">' . mb_strcut($string, 0, $length, 'UTF-8') . '…</span>';
|
$string = '<span title="' . $string . '">' . mb_strcut($string, 0, $length, 'UTF-8') . '…</span>';
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$string = mb_strcut($string, 0, $length, 'UTF-8') . '…';
|
$string = mb_strcut($string, 0, $length, 'UTF-8') . '…';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $string;
|
return $string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
// {{{ Upper Words
|
// {{{ Upper Words
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Upper Words
|
* Upper Words
|
||||||
*
|
*
|
||||||
* Applies strtolower() and ucwords() to the passed string. The
|
* Applies strtolower() and ucwords() to the passed string. The
|
||||||
* exception being email addresses which are not formatted at all.
|
* exception being email addresses which are not formatted at all.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $string string to format
|
* @param string $string string to format
|
||||||
* @return string formatted string
|
* @return string formatted string
|
||||||
*/
|
*/
|
||||||
public static function upperWords($string)
|
public static function upperWords($string)
|
||||||
{
|
{
|
||||||
// Only formats non-email addresses
|
// Only formats non-email addresses
|
||||||
if (filter_var($string, FILTER_VALIDATE_EMAIL) == false)
|
if (filter_var($string, FILTER_VALIDATE_EMAIL) == false)
|
||||||
{
|
{
|
||||||
$string = ucwords(strtolower($string));
|
$string = ucwords(strtolower($string));
|
||||||
}
|
}
|
||||||
|
|
||||||
return $string;
|
return $string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -23,254 +23,253 @@
|
||||||
*/
|
*/
|
||||||
class Time
|
class Time
|
||||||
{
|
{
|
||||||
// {{{ Intervals (in seconds)
|
// {{{ Intervals (in seconds)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Minute
|
* Minute
|
||||||
*
|
*
|
||||||
* Seconds in a minute
|
* Seconds in a minute
|
||||||
*
|
*
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
const MINUTE = 60;
|
const MINUTE = 60;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Hour
|
* Hour
|
||||||
*
|
*
|
||||||
* Seconds in an hour (minute * 60)
|
* Seconds in an hour (minute * 60)
|
||||||
*
|
*
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
const HOUR = 3600;
|
const HOUR = 3600;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Day
|
* Day
|
||||||
*
|
*
|
||||||
* Seconds in a day (hour * 24)
|
* Seconds in a day (hour * 24)
|
||||||
*
|
*
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
const DAY = 86400;
|
const DAY = 86400;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Week
|
* Week
|
||||||
*
|
*
|
||||||
* Seconds in a week (day * 7)
|
* Seconds in a week (day * 7)
|
||||||
*
|
*
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
const WEEK = 604800;
|
const WEEK = 604800;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Month
|
* Month
|
||||||
*
|
*
|
||||||
* Seconds in a month (day * 30)
|
* Seconds in a month (day * 30)
|
||||||
*
|
*
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
const MONTH = 2592000;
|
const MONTH = 2592000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Quarter
|
* Quarter
|
||||||
*
|
*
|
||||||
* Seconds in a quarter (day * 90)
|
* Seconds in a quarter (day * 90)
|
||||||
*
|
*
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
const QUARTER = 7776000;
|
const QUARTER = 7776000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Year
|
* Year
|
||||||
*
|
*
|
||||||
* Seconds in a year (day * 365)
|
* Seconds in a year (day * 365)
|
||||||
*
|
*
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
const YEAR = 31536000;
|
const YEAR = 31536000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decade
|
* Decade
|
||||||
*
|
*
|
||||||
* Seconds in a decade (year * 10)
|
* Seconds in a decade (year * 10)
|
||||||
*
|
*
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
const DECADE = 315360000;
|
const DECADE = 315360000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Century
|
* Century
|
||||||
*
|
*
|
||||||
* Seconds in a decade (decade * 10)
|
* Seconds in a decade (decade * 10)
|
||||||
*
|
*
|
||||||
* @var integer
|
* @var integer
|
||||||
*/
|
*/
|
||||||
const CENTURY = 3153600000;
|
const CENTURY = 3153600000;
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Age
|
* Age
|
||||||
*
|
*
|
||||||
* Calculates age based on the passed date.
|
* Calculates age based on the passed date.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $date birth / inception date
|
* @param string $date birth / inception date
|
||||||
* @return integer $age number of years old
|
* @return integer $age number of years old
|
||||||
* @todo Wondering if this really should live in the Date class since
|
* @todo Wondering if this really should live in the Date class since
|
||||||
* it's a Date function. Could flip the aliasing to preserve any
|
* it's a Date function. Could flip the aliasing to preserve any
|
||||||
* older code.
|
* older code.
|
||||||
*/
|
*/
|
||||||
public static function age($date)
|
public static function age($date)
|
||||||
{
|
{
|
||||||
if (!preg_match('/\d{4}-\d{2}-\d{2}/', $date))
|
if (!preg_match('/\d{4}-\d{2}-\d{2}/', $date))
|
||||||
{
|
{
|
||||||
$date = date('Y-m-d', strtotime($date));
|
$date = date('Y-m-d', strtotime($date));
|
||||||
}
|
}
|
||||||
|
|
||||||
list($year, $month, $day) = explode('-', $date, 3);
|
list($year, $month, $day) = explode('-', $date, 3);
|
||||||
|
|
||||||
$age = date('Y') - $year;
|
$age = date('Y') - $year;
|
||||||
|
|
||||||
if (date('md') < $month . $day)
|
if (date('md') < $month . $day)
|
||||||
{
|
{
|
||||||
$age--;
|
$age--;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $age;
|
return $age;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ago
|
* Ago
|
||||||
*
|
*
|
||||||
* Generates a relative time (e.g. X minutes ago).
|
* Generates a relative time (e.g. X minutes ago).
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param mixed $time timestamp to calculate from
|
* @param mixed $time timestamp to calculate from
|
||||||
* @return string relative time
|
* @return string relative time
|
||||||
*/
|
*/
|
||||||
public static function ago($time)
|
public static function ago($time)
|
||||||
{
|
{
|
||||||
$current = strtotime(Time::timestamp());
|
$current = strtotime(Time::timestamp());
|
||||||
$time = preg_match('/^\d+$/', $time) ? $time : strtotime($time);
|
$time = preg_match('/^\d+$/', $time) ? $time : strtotime($time);
|
||||||
|
|
||||||
if ($current == $time)
|
if ($current == $time)
|
||||||
{
|
{
|
||||||
$time_ago = 'just now';
|
$time_ago = 'just now';
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
if ($current > $time)
|
if ($current > $time)
|
||||||
{
|
{
|
||||||
$difference = $current - $time;
|
$difference = $current - $time;
|
||||||
$suffix = ' ago';
|
$suffix = ' ago';
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$difference = $time - $current;
|
$difference = $time - $current;
|
||||||
$suffix = ' from now';
|
$suffix = ' from now';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Less than 1 minute ago (seconds ago)
|
// Less than 1 minute ago (seconds ago)
|
||||||
if ($difference < 60)
|
if ($difference < 60)
|
||||||
{
|
{
|
||||||
$time_ago = 'seconds';
|
$time_ago = 'seconds';
|
||||||
}
|
}
|
||||||
// Less than 1 hour ago (minutes ago)
|
// Less than 1 hour ago (minutes ago)
|
||||||
elseif ($difference < Time::HOUR)
|
elseif ($difference < Time::HOUR)
|
||||||
{
|
{
|
||||||
$minutes = round($difference / 60);
|
$minutes = round($difference / 60);
|
||||||
|
|
||||||
if ($minutes == 60)
|
if ($minutes == 60)
|
||||||
{
|
{
|
||||||
$time_ago = 'an hour';
|
$time_ago = 'an hour';
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$time_ago = ($minutes == 1 ? 'a' : $minutes) . ' minute' . ($minutes != 1 ? 's' : '');
|
$time_ago = ($minutes == 1 ? 'a' : $minutes) . ' minute' . ($minutes != 1 ? 's' : '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Less than 1 day ago (hours ago)
|
// Less than 1 day ago (hours ago)
|
||||||
elseif ($difference < Time::DAY)
|
elseif ($difference < Time::DAY)
|
||||||
{
|
{
|
||||||
$hours = round($difference / Time::HOUR);
|
$hours = round($difference / Time::HOUR);
|
||||||
|
|
||||||
if ($hours == 24)
|
if ($hours == 24)
|
||||||
{
|
{
|
||||||
$time_ago = 'a day';
|
$time_ago = 'a day';
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$time_ago = ($hours == 1 ? 'an' : $hours) . ' hour' . ($hours != 1 ? 's' : '');
|
$time_ago = ($hours == 1 ? 'an' : $hours) . ' hour' . ($hours != 1 ? 's' : '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Less than 1 week ago (days ago)
|
// Less than 1 week ago (days ago)
|
||||||
elseif ($difference < Time::WEEK)
|
elseif ($difference < Time::WEEK)
|
||||||
{
|
{
|
||||||
$days = round($difference / Time::DAY);
|
$days = round($difference / Time::DAY);
|
||||||
|
|
||||||
if ($days == 7)
|
if ($days == 7)
|
||||||
{
|
{
|
||||||
$time_ago = 'a week';
|
$time_ago = 'a week';
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$time_ago = ($days == 1 ? 'a' : $days) . ' day' . ($days != 1 ? 's' : '');
|
$time_ago = ($days == 1 ? 'a' : $days) . ' day' . ($days != 1 ? 's' : '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Less than 1 month ago (weeks ago)
|
// Less than 1 month ago (weeks ago)
|
||||||
elseif ($difference < Time::MONTH)
|
elseif ($difference < Time::MONTH)
|
||||||
{
|
{
|
||||||
$weeks = round($difference / Time::WEEK);
|
$weeks = round($difference / Time::WEEK);
|
||||||
|
|
||||||
if ($weeks == 4)
|
if ($weeks == 4)
|
||||||
{
|
{
|
||||||
$time_ago = 'a month';
|
$time_ago = 'a month';
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$time_ago = ($weeks == 1 ? 'a' : $weeks) . ' week' . ($weeks != 1 ? 's' : '');
|
$time_ago = ($weeks == 1 ? 'a' : $weeks) . ' week' . ($weeks != 1 ? 's' : '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Less than 1 year ago (months ago)
|
// Less than 1 year ago (months ago)
|
||||||
elseif ($difference < Time::YEAR)
|
elseif ($difference < Time::YEAR)
|
||||||
{
|
{
|
||||||
$months = round($difference / Time::MONTH);
|
$months = round($difference / Time::MONTH);
|
||||||
|
|
||||||
if ($months == 12)
|
if ($months == 12)
|
||||||
{
|
{
|
||||||
$time_ago = 'a year';
|
$time_ago = 'a year';
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$time_ago = ($months == 1 ? 'a' : $months) . ' month' . ($months != 1 ? 's' : '');
|
$time_ago = ($months == 1 ? 'a' : $months) . ' month' . ($months != 1 ? 's' : '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Over 1 year ago (years ago)
|
// Over 1 year ago (years ago)
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$years = round($difference / Time::YEAR);
|
$years = round($difference / Time::YEAR);
|
||||||
$time_ago = ($years == 1 ? 'a' : $years) . ' year' . ($years != 1 ? 's' : '');
|
$time_ago = ($years == 1 ? 'a' : $years) . ' year' . ($years != 1 ? 's' : '');
|
||||||
}
|
}
|
||||||
|
|
||||||
$time_ago .= $suffix;
|
$time_ago .= $suffix;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $time_ago;
|
return $time_ago;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Timestamp
|
* Timestamp
|
||||||
*
|
*
|
||||||
* Current Universal Time in the specified format.
|
* Current Universal Time in the specified format.
|
||||||
*
|
*
|
||||||
* @static
|
* @static
|
||||||
* @param string $format format of the timestamp
|
* @param string $format format of the timestamp
|
||||||
* @return string $timestamp formatted timestamp
|
* @return string $timestamp formatted timestamp
|
||||||
*/
|
*/
|
||||||
public static function timestamp($format = 'Y-m-d H:i:s')
|
public static function timestamp($format = 'Y-m-d H:i:s')
|
||||||
{
|
{
|
||||||
return gmdate($format);
|
return gmdate($format);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -24,153 +24,152 @@
|
||||||
*/
|
*/
|
||||||
class Validate
|
class Validate
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Is Valid?
|
* Is Valid?
|
||||||
*
|
*
|
||||||
* Checks if a variable is valid based on the passed rules.
|
* Checks if a variable is valid based on the passed rules.
|
||||||
*
|
*
|
||||||
* @param mixed $value the value to be validated
|
* @param mixed $value the value to be validated
|
||||||
* @param array $rules an array of rules (and messages) to validate with
|
* @param array $rules an array of rules (and messages) to validate with
|
||||||
* @return mixed boolean true if valid, array of errors if invalid
|
* @return mixed boolean true if valid, array of errors if invalid
|
||||||
*/
|
*/
|
||||||
public static function isValid($value, $rules)
|
public static function isValid($value, $rules)
|
||||||
{
|
{
|
||||||
$errors = [];
|
$errors = [];
|
||||||
|
|
||||||
if (is_array($rules))
|
if (is_array($rules))
|
||||||
{
|
{
|
||||||
foreach ($rules as $rule => $message)
|
foreach ($rules as $rule => $message)
|
||||||
{
|
{
|
||||||
$rule = explode(':', $rule);
|
$rule = explode(':', $rule);
|
||||||
|
|
||||||
switch (strtolower($rule[0]))
|
switch (strtolower($rule[0]))
|
||||||
{
|
{
|
||||||
// @todo case 'alpha':
|
// @todo case 'alpha':
|
||||||
// @todo case 'alphanumeric':
|
// @todo case 'alphanumeric':
|
||||||
// @todo case 'date':
|
// @todo case 'date':
|
||||||
|
|
||||||
// {{{ Checks using filter_var()
|
// {{{ Checks using filter_var()
|
||||||
|
|
||||||
case 'filter':
|
case 'filter':
|
||||||
if (count($rule) < 2)
|
if (count($rule) < 2)
|
||||||
{
|
{
|
||||||
throw new Exception('Invalid validation rule, expected: "validate:boolean|email|float|int|ip|url".');
|
throw new Exception('Invalid validation rule, expected: "validate:boolean|email|float|int|ip|url".');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
switch (strtolower($rule[1]))
|
switch (strtolower($rule[1]))
|
||||||
{
|
{
|
||||||
case 'boolean':
|
case 'boolean':
|
||||||
case 'email':
|
case 'email':
|
||||||
case 'float':
|
case 'float':
|
||||||
case 'int':
|
case 'int':
|
||||||
case 'ip':
|
case 'ip':
|
||||||
case 'url':
|
case 'url':
|
||||||
$filter = constant('FILTER_VALIDATE_' . strtoupper($rule[1]));
|
$filter = constant('FILTER_VALIDATE_' . strtoupper($rule[1]));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
throw new Exception('Invalid filter, expecting boolean, email, float, int, ip or url.');
|
throw new Exception('Invalid filter, expecting boolean, email, float, int, ip or url.');
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!filter_var($value, $filter))
|
if (!filter_var($value, $filter))
|
||||||
{
|
{
|
||||||
$errors[] = $message;
|
$errors[] = $message;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
// {{{ Checks using strlen()
|
// {{{ Checks using strlen()
|
||||||
|
|
||||||
case 'length':
|
case 'length':
|
||||||
if (count($rule) < 3)
|
if (count($rule) < 3)
|
||||||
{
|
{
|
||||||
throw new Exception('Invalid validation rule, expected: "length:<|<=|==|!=|>=|>:integer".');
|
throw new Exception('Invalid validation rule, expected: "length:<|<=|==|!=|>=|>:integer".');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
if (!filter_var($rule[2], FILTER_VALIDATE_INT))
|
if (!filter_var($rule[2], FILTER_VALIDATE_INT))
|
||||||
{
|
{
|
||||||
throw new Exception('Invalid length value, expecting an integer.');
|
throw new Exception('Invalid length value, expecting an integer.');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$length = strlen($value);
|
$length = strlen($value);
|
||||||
|
|
||||||
switch ($rule[1])
|
switch ($rule[1])
|
||||||
{
|
{
|
||||||
case '<':
|
case '<':
|
||||||
$valid = $length < $rule[2];
|
$valid = $length < $rule[2];
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case '<=':
|
case '<=':
|
||||||
$valid = $length <= $rule[2];
|
$valid = $length <= $rule[2];
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case '==':
|
case '==':
|
||||||
$valid = $length == $rule[2];
|
$valid = $length == $rule[2];
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case '!=':
|
case '!=':
|
||||||
$valid = $length != $rule[2];
|
$valid = $length != $rule[2];
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case '>=':
|
case '>=':
|
||||||
$valid = $length >= $rule[2];
|
$valid = $length >= $rule[2];
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case '>':
|
case '>':
|
||||||
$valid = $length > $rule[2];
|
$valid = $length > $rule[2];
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
throw new Exception('Invalid operator, expecting <, <=, ==, !=, >= or >.');
|
throw new Exception('Invalid operator, expecting <, <=, ==, !=, >= or >.');
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!$valid)
|
if (!$valid)
|
||||||
{
|
{
|
||||||
$errors[] = $message;
|
$errors[] = $message;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
|
|
||||||
// @todo case 'range':
|
// @todo case 'range':
|
||||||
|
|
||||||
// {{{ Checks using preg_match()
|
// {{{ Checks using preg_match()
|
||||||
|
|
||||||
case 'regex':
|
case 'regex':
|
||||||
if (count($rule) < 3)
|
if (count($rule) < 3)
|
||||||
{
|
{
|
||||||
throw new Exception('Invalid validation rule, expected: "regex:is|not:string".');
|
throw new Exception('Invalid validation rule, expected: "regex:is|not:string".');
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$rule[1] = strtolower($rule[1]);
|
$rule[1] = strtolower($rule[1]);
|
||||||
|
|
||||||
if (($rule[1] == 'is' && preg_match($rule[2], $value))
|
if (($rule[1] == 'is' && preg_match($rule[2], $value))
|
||||||
|| ($rule[1] == 'not' && !preg_match($rule[2], $value)))
|
|| ($rule[1] == 'not' && !preg_match($rule[2], $value)))
|
||||||
{
|
{
|
||||||
$errors[] = $message;
|
$errors[] = $message;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return count($errors) ? $errors : true;
|
return count($errors) ? $errors : true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
101
src/pickles.php
101
src/pickles.php
|
@ -26,20 +26,20 @@
|
||||||
// @todo Finish reworking constants to be part of the Config object
|
// @todo Finish reworking constants to be part of the Config object
|
||||||
if (!defined('SITE_PATH'))
|
if (!defined('SITE_PATH'))
|
||||||
{
|
{
|
||||||
// Establishes our site paths, sanity check is to allow vfsStream in our tests
|
// Establishes our site paths, sanity check is to allow vfsStream in our tests
|
||||||
define('SITE_PATH', getcwd() . '/../');
|
define('SITE_PATH', getcwd() . '/../');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!defined('SITE_CLASS_PATH'))
|
if (!defined('SITE_CLASS_PATH'))
|
||||||
{
|
{
|
||||||
define('SITE_CLASS_PATH', SITE_PATH . 'classes/');
|
define('SITE_CLASS_PATH', SITE_PATH . 'classes/');
|
||||||
define('SITE_MODEL_PATH', SITE_PATH . 'models/');
|
define('SITE_MODEL_PATH', SITE_PATH . 'models/');
|
||||||
// @todo The following 2 constants are being used in sites will need to update them before removing
|
// @todo The following 2 constants are being used in sites will need to update them before removing
|
||||||
define('SITE_MODULE_PATH', SITE_PATH . 'modules/');
|
define('SITE_MODULE_PATH', SITE_PATH . 'modules/');
|
||||||
define('SITE_TEMPLATE_PATH', SITE_PATH . 'templates/');
|
define('SITE_TEMPLATE_PATH', SITE_PATH . 'templates/');
|
||||||
|
|
||||||
define('PRIVATE_PATH', SITE_PATH . 'private/');
|
define('PRIVATE_PATH', SITE_PATH . 'private/');
|
||||||
define('LOG_PATH', PRIVATE_PATH . 'logs/');
|
define('LOG_PATH', PRIVATE_PATH . 'logs/');
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
|
@ -52,7 +52,7 @@ error_reporting(-1);
|
||||||
// Defaults timezone to UTC if not set
|
// Defaults timezone to UTC if not set
|
||||||
if (ini_get('date.timezone') == '')
|
if (ini_get('date.timezone') == '')
|
||||||
{
|
{
|
||||||
ini_set('date.timezone', 'Etc/UTC');
|
ini_set('date.timezone', 'Etc/UTC');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sets the session variables
|
// Sets the session variables
|
||||||
|
@ -78,38 +78,38 @@ ini_set('session.hash_function', 1);
|
||||||
*/
|
*/
|
||||||
function __autoload($class)
|
function __autoload($class)
|
||||||
{
|
{
|
||||||
$loaded = false;
|
$loaded = false;
|
||||||
$filename = preg_replace('/_/', '/', $class) . '.php';
|
$filename = preg_replace('/_/', '/', $class) . '.php';
|
||||||
|
|
||||||
$pickles_path = dirname(__FILE__) . '/';
|
$pickles_path = dirname(__FILE__) . '/';
|
||||||
$pickles_paths = [
|
$pickles_paths = [
|
||||||
'class' => $pickles_path . 'classes/',
|
'class' => $pickles_path . 'classes/',
|
||||||
];
|
];
|
||||||
|
|
||||||
// Path as the key, boolean value is whether ot not to convert back to hyphenated
|
// Path as the key, boolean value is whether ot not to convert back to hyphenated
|
||||||
$paths = [
|
$paths = [
|
||||||
$pickles_paths['class'] => false,
|
$pickles_paths['class'] => false,
|
||||||
SITE_CLASS_PATH => false,
|
SITE_CLASS_PATH => false,
|
||||||
SITE_MODEL_PATH => false,
|
SITE_MODEL_PATH => false,
|
||||||
SITE_MODULE_PATH => true,
|
SITE_MODULE_PATH => true,
|
||||||
];
|
];
|
||||||
|
|
||||||
foreach ($paths as $path => $hyphenated)
|
foreach ($paths as $path => $hyphenated)
|
||||||
{
|
{
|
||||||
// Converts the filename back to hypenated
|
// Converts the filename back to hypenated
|
||||||
if ($hyphenated == true)
|
if ($hyphenated == true)
|
||||||
{
|
{
|
||||||
$filename = strtolower(preg_replace('/([A-Z]{1})/', '-$1', $filename));;
|
$filename = strtolower(preg_replace('/([A-Z]{1})/', '-$1', $filename));;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (file_exists($path . $filename))
|
if (file_exists($path . $filename))
|
||||||
{
|
{
|
||||||
$loaded = require_once $path . $filename;
|
$loaded = require_once $path . $filename;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $loaded;
|
return $loaded;
|
||||||
}
|
}
|
||||||
|
|
||||||
spl_autoload_register('__autoload');
|
spl_autoload_register('__autoload');
|
||||||
|
@ -129,28 +129,28 @@ require_once $config->pickles['path'] . '../vendor/autoload.php';
|
||||||
// Configures any available PHP configuration options
|
// Configures any available PHP configuration options
|
||||||
if (is_array($config->php) && count($config->php))
|
if (is_array($config->php) && count($config->php))
|
||||||
{
|
{
|
||||||
foreach ($config->php as $variable => $value)
|
foreach ($config->php as $variable => $value)
|
||||||
{
|
{
|
||||||
ini_set($variable, $value);
|
ini_set($variable, $value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Starts session handling (old)
|
// Starts session handling (old)
|
||||||
if (isset($config->pickles['session']))
|
if (isset($config->pickles['session']))
|
||||||
{
|
{
|
||||||
if (session_id() == '' && $config->pickles['session'] !== false)
|
if (session_id() == '' && $config->pickles['session'] !== false)
|
||||||
{
|
{
|
||||||
new Session();
|
new Session();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Starts session handling (new)
|
// Starts session handling (new)
|
||||||
if (isset($config->pickles['sessions']))
|
if (isset($config->pickles['sessions']))
|
||||||
{
|
{
|
||||||
if (session_id() == '' && $config->pickles['sessions'] !== false)
|
if (session_id() == '' && $config->pickles['sessions'] !== false)
|
||||||
{
|
{
|
||||||
new Session();
|
new Session();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
|
@ -158,9 +158,8 @@ if (isset($config->pickles['sessions']))
|
||||||
|
|
||||||
if (!isset($_REQUEST['request']))
|
if (!isset($_REQUEST['request']))
|
||||||
{
|
{
|
||||||
$_REQUEST['request'] = 'home';
|
$_REQUEST['request'] = 'home';
|
||||||
}
|
}
|
||||||
|
|
||||||
// }}}
|
// }}}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -11,26 +11,26 @@ $root = org\bovigo\vfs\vfsStream::setup('site');
|
||||||
|
|
||||||
if (!defined('SITE_PATH'))
|
if (!defined('SITE_PATH'))
|
||||||
{
|
{
|
||||||
define('SECURITY_LEVEL_USER', 10);
|
define('SECURITY_LEVEL_USER', 10);
|
||||||
define('SECURITY_LEVEL_ADMIN', 20);
|
define('SECURITY_LEVEL_ADMIN', 20);
|
||||||
define('SITE_PATH', org\bovigo\vfs\vfsStream::url('site/'));
|
define('SITE_PATH', org\bovigo\vfs\vfsStream::url('site/'));
|
||||||
}
|
}
|
||||||
|
|
||||||
require_once 'src/pickles.php';
|
require_once 'src/pickles.php';
|
||||||
|
|
||||||
if (!file_exists(SITE_MODULE_PATH))
|
if (!file_exists(SITE_MODULE_PATH))
|
||||||
{
|
{
|
||||||
mkdir(SITE_MODULE_PATH, 0644);
|
mkdir(SITE_MODULE_PATH, 0644);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!file_exists(SITE_TEMPLATE_PATH))
|
if (!file_exists(SITE_TEMPLATE_PATH))
|
||||||
{
|
{
|
||||||
mkdir(SITE_TEMPLATE_PATH, 0644);
|
mkdir(SITE_TEMPLATE_PATH, 0644);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!file_exists(SITE_TEMPLATE_PATH . '__shared/'))
|
if (!file_exists(SITE_TEMPLATE_PATH . '__shared/'))
|
||||||
{
|
{
|
||||||
mkdir(SITE_TEMPLATE_PATH . '__shared/', 0644);
|
mkdir(SITE_TEMPLATE_PATH . '__shared/', 0644);
|
||||||
}
|
}
|
||||||
|
|
||||||
$_SERVER['HTTP_HOST'] = 'testsite.com';
|
$_SERVER['HTTP_HOST'] = 'testsite.com';
|
||||||
|
@ -39,17 +39,17 @@ $_SERVER['SERVER_ADDR'] = '127.0.0.1';
|
||||||
|
|
||||||
function setUpRequest($request, $method = 'GET')
|
function setUpRequest($request, $method = 'GET')
|
||||||
{
|
{
|
||||||
$_SERVER['REQUEST_URI'] = '/' . $request;
|
$_SERVER['REQUEST_URI'] = '/' . $request;
|
||||||
$_SERVER['REQUEST_METHOD'] = $method;
|
$_SERVER['REQUEST_METHOD'] = $method;
|
||||||
$_REQUEST['request'] = $request;
|
$_REQUEST['request'] = $request;
|
||||||
}
|
}
|
||||||
|
|
||||||
function setUpConfig($config)
|
function setUpConfig($config)
|
||||||
{
|
{
|
||||||
file_put_contents(
|
file_put_contents(
|
||||||
SITE_PATH . 'config.php',
|
SITE_PATH . 'config.php',
|
||||||
'<?php $config = ' . var_export($config, true) . '; ?>'
|
'<?php $config = ' . var_export($config, true) . '; ?>'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
`mysql -e 'TRUNCATE TABLE test.pickles;'`;
|
`mysql -e 'TRUNCATE TABLE test.pickles;'`;
|
||||||
|
@ -57,4 +57,3 @@ function setUpConfig($config)
|
||||||
`mysql -e 'TRUNCATE TABLE test.users;'`;
|
`mysql -e 'TRUNCATE TABLE test.users;'`;
|
||||||
`echo 'flush_all' | nc localhost 11211`;
|
`echo 'flush_all' | nc localhost 11211`;
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,40 +2,39 @@
|
||||||
|
|
||||||
class API_AYAHTest extends PHPUnit_Framework_TestCase
|
class API_AYAHTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Missing API configuration
|
* @expectedExceptionMessage Missing API configuration
|
||||||
*/
|
*/
|
||||||
public function testGetHTMLMissingConfig()
|
public function testGetHTMLMissingConfig()
|
||||||
{
|
{
|
||||||
API_AYAH::getHTML();
|
API_AYAH::getHTML();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Missing API configuration
|
* @expectedExceptionMessage Missing API configuration
|
||||||
*/
|
*/
|
||||||
public function testIsHumanMissingConfig()
|
public function testIsHumanMissingConfig()
|
||||||
{
|
{
|
||||||
API_AYAH::isHuman();
|
API_AYAH::isHuman();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testGetHTML()
|
public function testGetHTML()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['api']['ayah'] = [
|
$config->data['api']['ayah'] = [
|
||||||
'publisher_key' => '01f70454bada303692be5f36a8fd104eba8b00dd',
|
'publisher_key' => '01f70454bada303692be5f36a8fd104eba8b00dd',
|
||||||
'scoring_key' => '80cc3f9c6e1da29369c238d55bd8528a968473ad',
|
'scoring_key' => '80cc3f9c6e1da29369c238d55bd8528a968473ad',
|
||||||
];
|
];
|
||||||
|
|
||||||
$this->assertRegExp('/<div id=\'AYAH\'><\/div><script src=\'https:\/\/ws.areyouahuman.com\/ws\/script\/[a-z0-9]{40}(\/[a-zA-Z0-9]{45})?\' type=\'text\/javascript\' language=\'JavaScript\'><\/script>/', API_AYAH::getHTML());
|
$this->assertRegExp('/<div id=\'AYAH\'><\/div><script src=\'https:\/\/ws.areyouahuman.com\/ws\/script\/[a-z0-9]{40}(\/[a-zA-Z0-9]{45})?\' type=\'text\/javascript\' language=\'JavaScript\'><\/script>/', API_AYAH::getHTML());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testIsNotHuman()
|
public function testIsNotHuman()
|
||||||
{
|
{
|
||||||
// Unfortunately there's no way to test a true response (mock maybe?)
|
// Unfortunately there's no way to test a true response (mock maybe?)
|
||||||
$this->assertFalse(API_AYAH::isHuman());
|
$this->assertFalse(API_AYAH::isHuman());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,41 +2,40 @@
|
||||||
|
|
||||||
class API_Google_ProfanityTest extends PHPUnit_Framework_TestCase
|
class API_Google_ProfanityTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @dataProvider providerFormatPhoneNumber
|
* @dataProvider providerFormatPhoneNumber
|
||||||
*/
|
*/
|
||||||
public function testCheck($a, $b)
|
public function testCheck($a, $b)
|
||||||
{
|
{
|
||||||
$this->assertEquals($b, API_Google_Profanity::check($a));
|
$this->assertEquals($b, API_Google_Profanity::check($a));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function providerFormatPhoneNumber()
|
public function providerFormatPhoneNumber()
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
['alpha', false],
|
['alpha', false],
|
||||||
['beta', false],
|
['beta', false],
|
||||||
['joshtronic', false],
|
['joshtronic', false],
|
||||||
['god', false],
|
['god', false],
|
||||||
['fck', false],
|
['fck', false],
|
||||||
['fuck', true],
|
['fuck', true],
|
||||||
['shit', true],
|
['shit', true],
|
||||||
['cocksucker', true],
|
['cocksucker', true],
|
||||||
['cuntface', false], // Unsure why not...
|
['cuntface', false], // Unsure why not...
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Invalid response from API.
|
* @expectedExceptionMessage Invalid response from API.
|
||||||
*/
|
*/
|
||||||
public function testInvalidResponse()
|
public function testInvalidResponse()
|
||||||
{
|
{
|
||||||
$file = SITE_PATH . 'null-';
|
$file = SITE_PATH . 'null-';
|
||||||
|
|
||||||
file_put_contents($file . 'test', null);
|
file_put_contents($file . 'test', null);
|
||||||
|
|
||||||
API_Google_Profanity::check('test', $file);
|
API_Google_Profanity::check('test', $file);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,97 +2,96 @@
|
||||||
|
|
||||||
class API_Gravatar_Test extends PHPUnit_Framework_TestCase
|
class API_Gravatar_Test extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @dataProvider providerHash
|
* @dataProvider providerHash
|
||||||
*/
|
*/
|
||||||
public function testHash($a, $b)
|
public function testHash($a, $b)
|
||||||
{
|
{
|
||||||
$this->assertEquals($b, API_Gravatar::hash($a));
|
$this->assertEquals($b, API_Gravatar::hash($a));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function providerHash()
|
public function providerHash()
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
['foo@bar.com', 'f3ada405ce890b6f8204094deb12d8a8'],
|
['foo@bar.com', 'f3ada405ce890b6f8204094deb12d8a8'],
|
||||||
['FOO@BAR.COM', 'f3ada405ce890b6f8204094deb12d8a8'],
|
['FOO@BAR.COM', 'f3ada405ce890b6f8204094deb12d8a8'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Invalid email address.
|
* @expectedExceptionMessage Invalid email address.
|
||||||
*/
|
*/
|
||||||
public function testImgInvalidEmail()
|
public function testImgInvalidEmail()
|
||||||
{
|
{
|
||||||
API_Gravatar::img('invalidemail');
|
API_Gravatar::img('invalidemail');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Invalid size parameter, expecting an integer between 1 and 2048.
|
* @expectedExceptionMessage Invalid size parameter, expecting an integer between 1 and 2048.
|
||||||
*/
|
*/
|
||||||
public function testImgInvalidSize()
|
public function testImgInvalidSize()
|
||||||
{
|
{
|
||||||
API_Gravatar::img('foo@bar.com', 2050);
|
API_Gravatar::img('foo@bar.com', 2050);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Invalid default parameter, expecting gravatar, 404, mm, identicon, monsterid, wavatar, retro, blank or a valid URL.
|
* @expectedExceptionMessage Invalid default parameter, expecting gravatar, 404, mm, identicon, monsterid, wavatar, retro, blank or a valid URL.
|
||||||
*/
|
*/
|
||||||
public function testImgInvalidDefault()
|
public function testImgInvalidDefault()
|
||||||
{
|
{
|
||||||
API_Gravatar::img('foo@bar.com', 80, 'invalid');
|
API_Gravatar::img('foo@bar.com', 80, 'invalid');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Invalid rating parameter, expecting g, pg, r or x.
|
* @expectedExceptionMessage Invalid rating parameter, expecting g, pg, r or x.
|
||||||
*/
|
*/
|
||||||
public function testImgInvalidRating()
|
public function testImgInvalidRating()
|
||||||
{
|
{
|
||||||
API_Gravatar::img('foo@bar.com', 80, 'gravatar', 'sexytime');
|
API_Gravatar::img('foo@bar.com', 80, 'gravatar', 'sexytime');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testURLDefault()
|
public function testURLDefault()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'<img src="http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&d=http%253A%252F%252Fexample.org%252Ficon&r=g">',
|
'<img src="http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&d=http%253A%252F%252Fexample.org%252Ficon&r=g">',
|
||||||
API_Gravatar::img('foo@bar.com', 80, 'http://example.org/icon')
|
API_Gravatar::img('foo@bar.com', 80, 'http://example.org/icon')
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testForce()
|
public function testForce()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'<img src="http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&d=&r=g&f=y">',
|
'<img src="http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&d=&r=g&f=y">',
|
||||||
API_Gravatar::img('foo@bar.com', 80, 'gravatar', 'g', true)
|
API_Gravatar::img('foo@bar.com', 80, 'gravatar', 'g', true)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSecure()
|
public function testSecure()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'<img src="https://secure.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&d=&r=g">',
|
'<img src="https://secure.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&d=&r=g">',
|
||||||
API_Gravatar::img('foo@bar.com', 80, 'gravatar', 'g', false, true)
|
API_Gravatar::img('foo@bar.com', 80, 'gravatar', 'g', false, true)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testImg()
|
public function testImg()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'<img src="http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&d=&r=g">',
|
'<img src="http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&d=&r=g">',
|
||||||
API_Gravatar::img('foo@bar.com')
|
API_Gravatar::img('foo@bar.com')
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testImgWithParameters()
|
public function testImgWithParameters()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'<img src="http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&d=&r=g" class="gravatar">',
|
'<img src="http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&d=&r=g" class="gravatar">',
|
||||||
API_Gravatar::img('foo@bar.com', 80, 'gravatar', 'g', false, false, ['class' => 'gravatar'])
|
API_Gravatar::img('foo@bar.com', 80, 'gravatar', 'g', false, false, ['class' => 'gravatar'])
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,67 +2,66 @@
|
||||||
|
|
||||||
class API_PlaceholdIt_Test extends PHPUnit_Framework_TestCase
|
class API_PlaceholdIt_Test extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
private $placeholdit;
|
private $placeholdit;
|
||||||
|
|
||||||
public function setUp()
|
public function setUp()
|
||||||
{
|
{
|
||||||
$this->placeholdit = new API_PlaceholdIt();
|
$this->placeholdit = new API_PlaceholdIt();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testInstantiateObject()
|
public function testInstantiateObject()
|
||||||
{
|
{
|
||||||
$this->assertInstanceOf('API_PlaceholdIt', $this->placeholdit);
|
$this->assertInstanceOf('API_PlaceholdIt', $this->placeholdit);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testURL()
|
public function testURL()
|
||||||
{
|
{
|
||||||
$expected = 'http://placehold.it/350x150.png/ffffff/000000&text=PICKLES+Rules%21';
|
$expected = 'http://placehold.it/350x150.png/ffffff/000000&text=PICKLES+Rules%21';
|
||||||
$url = $this->placeholdit->url(350, 150, 'png', 'ffffff', '000000', 'PICKLES Rules!');
|
$url = $this->placeholdit->url(350, 150, 'png', 'ffffff', '000000', 'PICKLES Rules!');
|
||||||
$this->assertEquals($expected, $url);
|
$this->assertEquals($expected, $url);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Invalid format. Valid formats: gif, jpeg, jpg and png.
|
* @expectedExceptionMessage Invalid format. Valid formats: gif, jpeg, jpg and png.
|
||||||
*/
|
*/
|
||||||
public function testInvalidFormat()
|
public function testInvalidFormat()
|
||||||
{
|
{
|
||||||
$this->placeholdit->url(350, 150, 'invalid');
|
$this->placeholdit->url(350, 150, 'invalid');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage You must specify a background color if you wish to specify a foreground color.
|
* @expectedExceptionMessage You must specify a background color if you wish to specify a foreground color.
|
||||||
*/
|
*/
|
||||||
public function testForegroundNoBackground()
|
public function testForegroundNoBackground()
|
||||||
{
|
{
|
||||||
$this->placeholdit->url(350, 150, 'png', false, '000000');
|
$this->placeholdit->url(350, 150, 'png', false, '000000');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage The background color must be a 6 character hex code.
|
* @expectedExceptionMessage The background color must be a 6 character hex code.
|
||||||
*/
|
*/
|
||||||
public function testInvalidBackground()
|
public function testInvalidBackground()
|
||||||
{
|
{
|
||||||
$this->placeholdit->url(350, 150, 'png', 'fff');
|
$this->placeholdit->url(350, 150, 'png', 'fff');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage The foreground color must be a 6 character hex code.
|
* @expectedExceptionMessage The foreground color must be a 6 character hex code.
|
||||||
*/
|
*/
|
||||||
public function testInvalidForeground()
|
public function testInvalidForeground()
|
||||||
{
|
{
|
||||||
$this->placeholdit->url(350, 150, 'png', 'ffffff', '000');
|
$this->placeholdit->url(350, 150, 'png', 'ffffff', '000');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testIMG()
|
public function testIMG()
|
||||||
{
|
{
|
||||||
$expected = '<img src="http://placehold.it/350x150.png/ffffff/000000&text=PICKLES+Rules%21">';
|
$expected = '<img src="http://placehold.it/350x150.png/ffffff/000000&text=PICKLES+Rules%21">';
|
||||||
$url = $this->placeholdit->img(350, 150, 'png', 'ffffff', '000000', 'PICKLES Rules!');
|
$url = $this->placeholdit->img(350, 150, 'png', 'ffffff', '000000', 'PICKLES Rules!');
|
||||||
$this->assertEquals($expected, $url);
|
$this->assertEquals($expected, $url);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,105 +2,104 @@
|
||||||
|
|
||||||
class BrowserTest extends PHPUnit_Framework_TestCase
|
class BrowserTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
public function testGetInstance()
|
public function testGetInstance()
|
||||||
{
|
{
|
||||||
$this->assertInstanceOf('Browser', Browser::getInstance());
|
$this->assertInstanceOf('Browser', Browser::getInstance());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSetAndGet()
|
public function testSetAndGet()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Browser::set('foo', 'bar'));
|
$this->assertTrue(Browser::set('foo', 'bar'));
|
||||||
$this->assertEquals('bar', Browser::get('foo'));
|
$this->assertEquals('bar', Browser::get('foo'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testMissingVariable()
|
public function testMissingVariable()
|
||||||
{
|
{
|
||||||
$this->assertFalse(Browser::get('missing'));
|
$this->assertFalse(Browser::get('missing'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testGoHome()
|
public function testGoHome()
|
||||||
{
|
{
|
||||||
Browser::goHome();
|
Browser::goHome();
|
||||||
$this->assertTrue(in_array('Location: http://testsite.com/', xdebug_get_headers()));
|
$this->assertTrue(in_array('Location: http://testsite.com/', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testIsMobile()
|
public function testIsMobile()
|
||||||
{
|
{
|
||||||
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16';
|
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16';
|
||||||
|
|
||||||
$this->assertTrue(Browser::isMobile());
|
$this->assertTrue(Browser::isMobile());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testIsNotMobile()
|
public function testIsNotMobile()
|
||||||
{
|
{
|
||||||
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.73.11 (KHTML, like Gecko) Version/7.0.1 Safari/537.73.11';
|
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.73.11 (KHTML, like Gecko) Version/7.0.1 Safari/537.73.11';
|
||||||
|
|
||||||
$this->assertFalse(Browser::isMobile());
|
$this->assertFalse(Browser::isMobile());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRemoteIPNone()
|
public function testRemoteIPNone()
|
||||||
{
|
{
|
||||||
$this->assertFalse(Browser::remoteIP());
|
$this->assertFalse(Browser::remoteIP());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRemoteIPRemoteAddress()
|
public function testRemoteIPRemoteAddress()
|
||||||
{
|
{
|
||||||
$_SERVER['REMOTE_ADDR'] = '1.2.3.4';
|
$_SERVER['REMOTE_ADDR'] = '1.2.3.4';
|
||||||
|
|
||||||
$this->assertEquals('1.2.3.4', Browser::remoteIP());
|
$this->assertEquals('1.2.3.4', Browser::remoteIP());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRemoteIPHTTPXForwardedFor()
|
public function testRemoteIPHTTPXForwardedFor()
|
||||||
{
|
{
|
||||||
$_SERVER['HTTP_X_FORWARDED_FOR'] = '2.3.4.5';
|
$_SERVER['HTTP_X_FORWARDED_FOR'] = '2.3.4.5';
|
||||||
|
|
||||||
$this->assertEquals('2.3.4.5', Browser::remoteIP());
|
$this->assertEquals('2.3.4.5', Browser::remoteIP());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRemoteIPHTTPClientIP()
|
public function testRemoteIPHTTPClientIP()
|
||||||
{
|
{
|
||||||
$_SERVER['HTTP_CLIENT_IP'] = '3.4.5.6';
|
$_SERVER['HTTP_CLIENT_IP'] = '3.4.5.6';
|
||||||
|
|
||||||
$this->assertEquals('3.4.5.6', Browser::remoteIP());
|
$this->assertEquals('3.4.5.6', Browser::remoteIP());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testStatus1xx()
|
public function testStatus1xx()
|
||||||
{
|
{
|
||||||
Browser::status(100);
|
Browser::status(100);
|
||||||
$this->assertTrue(in_array('Status: 100 Continue', xdebug_get_headers()));
|
$this->assertTrue(in_array('Status: 100 Continue', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testStatus2xx()
|
public function testStatus2xx()
|
||||||
{
|
{
|
||||||
Browser::status(200);
|
Browser::status(200);
|
||||||
$this->assertTrue(in_array('Status: 200 OK', xdebug_get_headers()));
|
$this->assertTrue(in_array('Status: 200 OK', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testStatus3xx()
|
public function testStatus3xx()
|
||||||
{
|
{
|
||||||
Browser::status(300);
|
Browser::status(300);
|
||||||
$this->assertTrue(in_array('Status: 300 Multiple Choices', xdebug_get_headers()));
|
$this->assertTrue(in_array('Status: 300 Multiple Choices', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testStatus4xx()
|
public function testStatus4xx()
|
||||||
{
|
{
|
||||||
Browser::status(400);
|
Browser::status(400);
|
||||||
$this->assertTrue(in_array('Status: 400 Bad Request', xdebug_get_headers()));
|
$this->assertTrue(in_array('Status: 400 Bad Request', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testStatus5xx()
|
public function testStatus5xx()
|
||||||
{
|
{
|
||||||
Browser::status(500);
|
Browser::status(500);
|
||||||
$this->assertTrue(in_array('Status: 500 Internal Server Error', xdebug_get_headers()));
|
$this->assertTrue(in_array('Status: 500 Internal Server Error', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRefresh()
|
public function testRefresh()
|
||||||
{
|
{
|
||||||
$_SERVER['REQUEST_URI'] = '/some/uri';
|
$_SERVER['REQUEST_URI'] = '/some/uri';
|
||||||
Browser::goHome();
|
Browser::goHome();
|
||||||
Browser::refresh();
|
Browser::refresh();
|
||||||
$this->assertTrue(in_array('Location: http://testsite.com/some/uri', xdebug_get_headers()));
|
$this->assertTrue(in_array('Location: http://testsite.com/some/uri', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,87 +2,86 @@
|
||||||
|
|
||||||
class CacheTest extends PHPUnit_Framework_TestCase
|
class CacheTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
private $config;
|
private $config;
|
||||||
private $cache;
|
private $cache;
|
||||||
|
|
||||||
public function setUp()
|
public function setUp()
|
||||||
{
|
{
|
||||||
$this->config = Config::getInstance();
|
$this->config = Config::getInstance();
|
||||||
$this->config->data['pickles']['cache'] = 'mc';
|
$this->config->data['pickles']['cache'] = 'mc';
|
||||||
$this->config->data['datasources']['mc'] = [
|
$this->config->data['datasources']['mc'] = [
|
||||||
'type' => 'memcache',
|
'type' => 'memcache',
|
||||||
'hostname' => 'localhost',
|
'hostname' => 'localhost',
|
||||||
'port' => 11211,
|
'port' => 11211,
|
||||||
'namespace' => 'ns',
|
'namespace' => 'ns',
|
||||||
];
|
];
|
||||||
|
|
||||||
$this->cache = Cache::getInstance();
|
$this->cache = Cache::getInstance();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testGetInstance()
|
public function testGetInstance()
|
||||||
{
|
{
|
||||||
$this->assertInstanceOf('Cache', $this->cache);
|
$this->assertInstanceOf('Cache', $this->cache);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSetAndGet()
|
public function testSetAndGet()
|
||||||
{
|
{
|
||||||
$key = String::random();
|
$key = String::random();
|
||||||
$value = String::random();
|
$value = String::random();
|
||||||
|
|
||||||
$this->cache->set($key, $value);
|
$this->cache->set($key, $value);
|
||||||
|
|
||||||
$this->assertEquals($value, $this->cache->get($key));
|
$this->assertEquals($value, $this->cache->get($key));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSetAndGetMultiple()
|
public function testSetAndGetMultiple()
|
||||||
{
|
{
|
||||||
$keys = $values = $expected = [];
|
$keys = $values = $expected = [];
|
||||||
|
|
||||||
for ($i = 0; $i < 5; $i++)
|
for ($i = 0; $i < 5; $i++)
|
||||||
{
|
{
|
||||||
$keys[] = String::random();
|
$keys[] = String::random();
|
||||||
$values[] = String::random();
|
$values[] = String::random();
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($keys as $key => $key_name)
|
foreach ($keys as $key => $key_name)
|
||||||
{
|
{
|
||||||
$value = $values[$key];
|
$value = $values[$key];
|
||||||
$expected['NS-' . strtoupper($key_name)] = $value;
|
$expected['NS-' . strtoupper($key_name)] = $value;
|
||||||
$this->cache->set($key_name, $value);
|
$this->cache->set($key_name, $value);
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->assertEquals($expected, $this->cache->get($keys));
|
$this->assertEquals($expected, $this->cache->get($keys));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testDelete()
|
public function testDelete()
|
||||||
{
|
{
|
||||||
$key = String::random();
|
$key = String::random();
|
||||||
$value = String::random();
|
$value = String::random();
|
||||||
|
|
||||||
$this->cache->set($key, $value);
|
$this->cache->set($key, $value);
|
||||||
$this->cache->delete($key);
|
$this->cache->delete($key);
|
||||||
|
|
||||||
$this->assertFalse($this->cache->get($key));
|
$this->assertFalse($this->cache->get($key));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testIncrement()
|
public function testIncrement()
|
||||||
{
|
{
|
||||||
$key = String::random();
|
$key = String::random();
|
||||||
|
|
||||||
$this->assertFalse($this->cache->increment($key));
|
$this->assertFalse($this->cache->increment($key));
|
||||||
|
|
||||||
$this->cache->set($key, 1);
|
$this->cache->set($key, 1);
|
||||||
|
|
||||||
$this->assertEquals(2, $this->cache->increment($key));
|
$this->assertEquals(2, $this->cache->increment($key));
|
||||||
$this->assertEquals(3, $this->cache->increment($key));
|
$this->assertEquals(3, $this->cache->increment($key));
|
||||||
$this->assertEquals(4, $this->cache->increment($key));
|
$this->assertEquals(4, $this->cache->increment($key));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Doesn't do much but test that the destructor doesn't explode
|
// Doesn't do much but test that the destructor doesn't explode
|
||||||
public function testDestructor()
|
public function testDestructor()
|
||||||
{
|
{
|
||||||
$this->cache->__destruct();
|
$this->cache->__destruct();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,161 +2,160 @@
|
||||||
|
|
||||||
class ConfigTest extends PHPUnit_Framework_TestCase
|
class ConfigTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
private $config;
|
private $config;
|
||||||
|
|
||||||
public function setUp()
|
public function setUp()
|
||||||
{
|
{
|
||||||
$this->config = Config::getInstance();
|
$this->config = Config::getInstance();
|
||||||
setupConfig([]);
|
setupConfig([]);
|
||||||
|
|
||||||
$_SERVER['REQUEST_METHOD'] = 'GET';
|
$_SERVER['REQUEST_METHOD'] = 'GET';
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testConfigProperty()
|
public function testConfigProperty()
|
||||||
{
|
{
|
||||||
$config = new Config();
|
$config = new Config();
|
||||||
|
|
||||||
$this->assertTrue(PHPUnit_Framework_Assert::readAttribute($config, 'config'));
|
$this->assertTrue(PHPUnit_Framework_Assert::readAttribute($config, 'config'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testInstanceOf()
|
public function testInstanceOf()
|
||||||
{
|
{
|
||||||
$this->assertInstanceOf('Config', $this->config);
|
$this->assertInstanceOf('Config', $this->config);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testUndefined()
|
public function testUndefined()
|
||||||
{
|
{
|
||||||
$this->assertFalse($this->config->undefined);
|
$this->assertFalse($this->config->undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testDefinedEnvironment()
|
public function testDefinedEnvironment()
|
||||||
{
|
{
|
||||||
setUpConfig([
|
setUpConfig([
|
||||||
'environment' => 'local',
|
'environment' => 'local',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$config = new Config();
|
$config = new Config();
|
||||||
|
|
||||||
$this->assertEquals('local', $config->environment);
|
$this->assertEquals('local', $config->environment);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testMultipleEnvironmentsByIP()
|
public function testMultipleEnvironmentsByIP()
|
||||||
{
|
{
|
||||||
setUpConfig([
|
setUpConfig([
|
||||||
'environments' => [
|
'environments' => [
|
||||||
'local' => '127.0.0.1',
|
'local' => '127.0.0.1',
|
||||||
'prod' => '123.456.789.0',
|
'prod' => '123.456.789.0',
|
||||||
],
|
],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$config = new Config();
|
$config = new Config();
|
||||||
|
|
||||||
$this->assertEquals('local', $config->environment);
|
$this->assertEquals('local', $config->environment);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testMultipleEnvironmentsByRegex()
|
public function testMultipleEnvironmentsByRegex()
|
||||||
{
|
{
|
||||||
setUpConfig([
|
setUpConfig([
|
||||||
'environments' => [
|
'environments' => [
|
||||||
'local' => '/^local\.testsite\.com$/',
|
'local' => '/^local\.testsite\.com$/',
|
||||||
'prod' => '/^testsite\.com$/',
|
'prod' => '/^testsite\.com$/',
|
||||||
],
|
],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$config = new Config();
|
$config = new Config();
|
||||||
|
|
||||||
$this->assertEquals('prod', $config->environment);
|
$this->assertEquals('prod', $config->environment);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testCLIEnvironment()
|
public function testCLIEnvironment()
|
||||||
{
|
{
|
||||||
unset($_SERVER['REQUEST_METHOD']);
|
unset($_SERVER['REQUEST_METHOD']);
|
||||||
$_SERVER['argv'][1] = 'prod';
|
$_SERVER['argv'][1] = 'prod';
|
||||||
|
|
||||||
setUpConfig([
|
setUpConfig([
|
||||||
'environments' => [
|
'environments' => [
|
||||||
'local' => '127.0.0.1',
|
'local' => '127.0.0.1',
|
||||||
'prod' => '123.456.789.0',
|
'prod' => '123.456.789.0',
|
||||||
],
|
],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$config = new Config();
|
$config = new Config();
|
||||||
|
|
||||||
$this->assertEquals('prod', $config->environment);
|
$this->assertEquals('prod', $config->environment);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage You must pass an environment (e.g. php script.php <environment>)
|
* @expectedExceptionMessage You must pass an environment (e.g. php script.php <environment>)
|
||||||
*/
|
*/
|
||||||
public function testCLIMissingEnvironment()
|
public function testCLIMissingEnvironment()
|
||||||
{
|
{
|
||||||
unset($_SERVER['REQUEST_METHOD']);
|
unset($_SERVER['REQUEST_METHOD']);
|
||||||
$_SERVER['argc'] = 1;
|
$_SERVER['argc'] = 1;
|
||||||
|
|
||||||
setUpConfig(['environments' => []]);
|
setUpConfig(['environments' => []]);
|
||||||
|
|
||||||
$config = new Config();
|
$config = new Config();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testProfiler()
|
public function testProfiler()
|
||||||
{
|
{
|
||||||
setUpConfig([
|
setUpConfig([
|
||||||
'environment' => 'local',
|
'environment' => 'local',
|
||||||
'pickles' => ['profiler' => true],
|
'pickles' => ['profiler' => true],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$config = new Config();
|
$config = new Config();
|
||||||
|
|
||||||
$this->assertTrue($config->pickles['profiler']);
|
$this->assertTrue($config->pickles['profiler']);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testProfilerArray()
|
public function testProfilerArray()
|
||||||
{
|
{
|
||||||
setUpConfig([
|
setUpConfig([
|
||||||
'environment' => 'local',
|
'environment' => 'local',
|
||||||
'pickles' => ['profiler' => ['objects', 'timers']],
|
'pickles' => ['profiler' => ['objects', 'timers']],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$config = new Config();
|
$config = new Config();
|
||||||
|
|
||||||
$this->assertEquals('objects,timers', $config->pickles['profiler']);
|
$this->assertEquals('objects,timers', $config->pickles['profiler']);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSecurityConstant()
|
public function testSecurityConstant()
|
||||||
{
|
{
|
||||||
setUpConfig([
|
setUpConfig([
|
||||||
'environment' => 'local',
|
'environment' => 'local',
|
||||||
'security' => ['levels' => [10 => 'level']],
|
'security' => ['levels' => [10 => 'level']],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$config = new Config();
|
$config = new Config();
|
||||||
|
|
||||||
$this->assertEquals(10, SECURITY_LEVEL_USER);
|
$this->assertEquals(10, SECURITY_LEVEL_USER);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage The constant SECURITY_LEVEL_LEVEL is already defined
|
* @expectedExceptionMessage The constant SECURITY_LEVEL_LEVEL is already defined
|
||||||
*/
|
*/
|
||||||
public function testSecurityConstantAlreadyDefined()
|
public function testSecurityConstantAlreadyDefined()
|
||||||
{
|
{
|
||||||
setUpConfig([
|
setUpConfig([
|
||||||
'environment' => 'local',
|
'environment' => 'local',
|
||||||
'security' => ['levels' => [10 => 'level']],
|
'security' => ['levels' => [10 => 'level']],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$config = new Config();
|
$config = new Config();
|
||||||
|
|
||||||
$this->assertEquals(10, SECURITY_LEVEL_USER);
|
$this->assertEquals(10, SECURITY_LEVEL_USER);
|
||||||
}
|
}
|
||||||
|
|
||||||
// This test is just for coverage
|
// This test is just for coverage
|
||||||
public function testConfigArrayMissing()
|
public function testConfigArrayMissing()
|
||||||
{
|
{
|
||||||
file_put_contents(SITE_PATH . 'config.php', '');
|
file_put_contents(SITE_PATH . 'config.php', '');
|
||||||
new Config();
|
new Config();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,358 +2,357 @@
|
||||||
|
|
||||||
class ControllerTest extends PHPUnit_Framework_TestCase
|
class ControllerTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
private $config;
|
private $config;
|
||||||
|
|
||||||
public function setUp()
|
public function setUp()
|
||||||
{
|
{
|
||||||
$this->config = Config::getInstance();
|
$this->config = Config::getInstance();
|
||||||
$this->config->data['pickles']['disabled'] = false;
|
$this->config->data['pickles']['disabled'] = false;
|
||||||
$this->config->data['pickles']['profiler'] = false;
|
$this->config->data['pickles']['profiler'] = false;
|
||||||
$this->config->data['security']['levels'][10] = 'USER';
|
$this->config->data['security']['levels'][10] = 'USER';
|
||||||
$this->config->data['security']['levels'][20] = 'ADMIN';
|
$this->config->data['security']['levels'][20] = 'ADMIN';
|
||||||
|
|
||||||
setUpRequest('home');
|
setUpRequest('home');
|
||||||
|
|
||||||
$module = '<?php class home extends Module { } ?>';
|
$module = '<?php class home extends Module { }';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'home.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'home.php', $module);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSiteDown()
|
public function testSiteDown()
|
||||||
{
|
{
|
||||||
$this->config->data['pickles']['disabled'] = true;
|
$this->config->data['pickles']['disabled'] = true;
|
||||||
|
|
||||||
$this->expectOutputRegex('/Test Server is currently down for maintenance/');
|
$this->expectOutputRegex('/Test Server is currently down for maintenance/');
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testCustomSiteDown()
|
public function testCustomSiteDown()
|
||||||
{
|
{
|
||||||
$this->config->data['pickles']['disabled'] = true;
|
$this->config->data['pickles']['disabled'] = true;
|
||||||
|
|
||||||
file_put_contents(SITE_TEMPLATE_PATH . '__shared/maintenance.phtml', '<h1>Custom Down for Maintenance</h1>');
|
file_put_contents(SITE_TEMPLATE_PATH . '__shared/maintenance.phtml', '<h1>Custom Down for Maintenance</h1>');
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
$this->expectOutputRegex('/<h1>Custom Down for Maintenance<\/h1>/');
|
$this->expectOutputRegex('/<h1>Custom Down for Maintenance<\/h1>/');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAttributesInURI()
|
public function testAttributesInURI()
|
||||||
{
|
{
|
||||||
setUpRequest('home/id:123');
|
setUpRequest('home/id:123');
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
$this->assertEquals(123, Browser::get('id'));
|
$this->assertEquals(123, Browser::get('id'));
|
||||||
|
|
||||||
setUpRequest('home/id:456/foo:bar');
|
setUpRequest('home/id:456/foo:bar');
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
// Compensates for 2 empty template executions of the Controller
|
// Compensates for 2 empty template executions of the Controller
|
||||||
$this->expectOutputString('[][]');
|
$this->expectOutputString('[][]');
|
||||||
$this->assertEquals(456, Browser::get('id'));
|
$this->assertEquals(456, Browser::get('id'));
|
||||||
$this->assertEquals('bar', Browser::get('foo'));
|
$this->assertEquals('bar', Browser::get('foo'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testUpperCaseURI()
|
public function testUpperCaseURI()
|
||||||
{
|
{
|
||||||
setUpRequest('TESTING');
|
setUpRequest('TESTING');
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
$this->assertTrue(in_array('Location: /testing', xdebug_get_headers()));
|
$this->assertTrue(in_array('Location: /testing', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testForceSecure()
|
public function testForceSecure()
|
||||||
{
|
{
|
||||||
setUpRequest('secure');
|
setUpRequest('secure');
|
||||||
|
|
||||||
$module = '<?php class secure extends Module { public $secure = true; } ?>';
|
$module = '<?php class secure extends Module { public $secure = true; }';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'secure.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'secure.php', $module);
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
$this->assertTrue(in_array('Location: https://testsite.com/secure', xdebug_get_headers()));
|
$this->assertTrue(in_array('Location: https://testsite.com/secure', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testForceInsecure()
|
public function testForceInsecure()
|
||||||
{
|
{
|
||||||
setUpRequest('insecure');
|
setUpRequest('insecure');
|
||||||
$_SERVER['HTTPS'] = 'on';
|
$_SERVER['HTTPS'] = 'on';
|
||||||
|
|
||||||
$module = '<?php class insecure extends Module { public $secure = false; } ?>';
|
$module = '<?php class insecure extends Module { public $secure = false; }';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'insecure.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'insecure.php', $module);
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
$this->assertTrue(in_array('Location: http://testsite.com/insecure', xdebug_get_headers()));
|
$this->assertTrue(in_array('Location: http://testsite.com/insecure', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testNotAuthenticated()
|
public function testNotAuthenticated()
|
||||||
{
|
{
|
||||||
setUpRequest('notauth');
|
setUpRequest('notauth');
|
||||||
|
|
||||||
$module = '<?php class notauth extends Module { public $security = SECURITY_LEVEL_USER; } ?>';
|
$module = '<?php class notauth extends Module { public $security = SECURITY_LEVEL_USER; }';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'notauth.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'notauth.php', $module);
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
// Compensates for an empty template due to exit() being skipped
|
// Compensates for an empty template due to exit() being skipped
|
||||||
$this->expectOutputString('[]');
|
$this->expectOutputString('[]');
|
||||||
|
|
||||||
$this->assertTrue(in_array('Location: http://testsite.com/login', xdebug_get_headers()));
|
$this->assertTrue(in_array('Location: http://testsite.com/login', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSecurityArray()
|
public function testSecurityArray()
|
||||||
{
|
{
|
||||||
setUpRequest('securityarray');
|
setUpRequest('securityarray');
|
||||||
|
|
||||||
$module = '<?php class securityarray extends Module { public $security = [SECURITY_LEVEL_USER, SECURITY_LEVEL_ADMIN]; } ?>';
|
$module = '<?php class securityarray extends Module { public $security = [SECURITY_LEVEL_USER, SECURITY_LEVEL_ADMIN]; }';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'securityarray.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'securityarray.php', $module);
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
// Compensates for an empty template due to exit() being skipped
|
// Compensates for an empty template due to exit() being skipped
|
||||||
$this->expectOutputString('[]');
|
$this->expectOutputString('[]');
|
||||||
|
|
||||||
$this->assertTrue(in_array('Location: http://testsite.com/login', xdebug_get_headers()));
|
$this->assertTrue(in_array('Location: http://testsite.com/login', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSecurityArrayTypeString()
|
public function testSecurityArrayTypeString()
|
||||||
{
|
{
|
||||||
setUpRequest('securityarraytypestring');
|
setUpRequest('securityarraytypestring');
|
||||||
|
|
||||||
$module = '<?php class securityarraytypestring extends Module { public $security = ["type" => "IS", "level" => SECURITY_LEVEL_USER]; } ?>';
|
$module = '<?php class securityarraytypestring extends Module { public $security = ["type" => "IS", "level" => SECURITY_LEVEL_USER]; }';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'securityarraytypestring.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'securityarraytypestring.php', $module);
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
// Compensates for an empty template due to exit() being skipped
|
// Compensates for an empty template due to exit() being skipped
|
||||||
$this->expectOutputString('[]');
|
$this->expectOutputString('[]');
|
||||||
|
|
||||||
$this->assertTrue(in_array('Location: http://testsite.com/login', xdebug_get_headers()));
|
$this->assertTrue(in_array('Location: http://testsite.com/login', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSecurityArrayTypeArray()
|
public function testSecurityArrayTypeArray()
|
||||||
{
|
{
|
||||||
setUpRequest('securityarraytypearray');
|
setUpRequest('securityarraytypearray');
|
||||||
|
|
||||||
$module = '<?php class securityarraytypearray extends Module { public $security = ["type" => "IS", "level" => [SECURITY_LEVEL_USER, SECURITY_LEVEL_ADMIN]]; } ?>';
|
$module = '<?php class securityarraytypearray extends Module { public $security = ["type" => "IS", "level" => [SECURITY_LEVEL_USER, SECURITY_LEVEL_ADMIN]]; }';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'securityarraytypearray.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'securityarraytypearray.php', $module);
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
// Compensates for an empty template due to exit() being skipped
|
// Compensates for an empty template due to exit() being skipped
|
||||||
$this->expectOutputString('[]');
|
$this->expectOutputString('[]');
|
||||||
|
|
||||||
$this->assertTrue(in_array('Location: http://testsite.com/login', xdebug_get_headers()));
|
$this->assertTrue(in_array('Location: http://testsite.com/login', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSecurityArrayTypeBetween()
|
public function testSecurityArrayTypeBetween()
|
||||||
{
|
{
|
||||||
setUpRequest('securityarraytypebetween');
|
setUpRequest('securityarraytypebetween');
|
||||||
|
|
||||||
$module = '<?php class securityarraytypebetween extends Module { public $security = ["type" => "BETWEEN", "levels" => [SECURITY_LEVEL_USER, SECURITY_LEVEL_ADMIN]]; } ?>';
|
$module = '<?php class securityarraytypebetween extends Module { public $security = ["type" => "BETWEEN", "levels" => [SECURITY_LEVEL_USER, SECURITY_LEVEL_ADMIN]]; }';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'securityarraytypebetween.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'securityarraytypebetween.php', $module);
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
// Compensates for an empty template due to exit() being skipped
|
// Compensates for an empty template due to exit() being skipped
|
||||||
$this->expectOutputString('[]');
|
$this->expectOutputString('[]');
|
||||||
|
|
||||||
$this->assertTrue(in_array('Location: http://testsite.com/login', xdebug_get_headers()));
|
$this->assertTrue(in_array('Location: http://testsite.com/login', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSecurityArrayTypeHas()
|
public function testSecurityArrayTypeHas()
|
||||||
{
|
{
|
||||||
setUpRequest('securityarraytypehas');
|
setUpRequest('securityarraytypehas');
|
||||||
|
|
||||||
$module = '<?php class securityarraytypehas extends Module { public $security = ["type" => "HAS", "level" => SECURITY_LEVEL_USER]; } ?>';
|
$module = '<?php class securityarraytypehas extends Module { public $security = ["type" => "HAS", "level" => SECURITY_LEVEL_USER]; }';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'securityarraytypehas.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'securityarraytypehas.php', $module);
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
// Compensates for an empty template due to exit() being skipped
|
// Compensates for an empty template due to exit() being skipped
|
||||||
$this->expectOutputString('[]');
|
$this->expectOutputString('[]');
|
||||||
|
|
||||||
$this->assertTrue(in_array('Location: http://testsite.com/login', xdebug_get_headers()));
|
$this->assertTrue(in_array('Location: http://testsite.com/login', xdebug_get_headers()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testNotAuthenticatedPOST()
|
public function testNotAuthenticatedPOST()
|
||||||
{
|
{
|
||||||
setUpRequest('notauthpost', 'POST');
|
setUpRequest('notauthpost', 'POST');
|
||||||
|
|
||||||
$module = '<?php class notauthpost extends Module { public $security = SECURITY_LEVEL_USER; } ?>';
|
$module = '<?php class notauthpost extends Module { public $security = SECURITY_LEVEL_USER; }';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'notauthpost.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'notauthpost.php', $module);
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
$this->expectOutputRegex('/You are not properly authenticated/');
|
$this->expectOutputRegex('/You are not properly authenticated/');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAuthenticated()
|
public function testAuthenticated()
|
||||||
{
|
{
|
||||||
setUpRequest('auth');
|
setUpRequest('auth');
|
||||||
|
|
||||||
$module = '<?php class auth extends Module { '
|
$module = '<?php class auth extends Module { '
|
||||||
. 'public $security = SECURITY_LEVEL_USER;'
|
. 'public $security = SECURITY_LEVEL_USER;'
|
||||||
. 'public function __default() { return ["foo" => "bar"]; }'
|
. 'public function __default() { return ["foo" => "bar"]; }'
|
||||||
. '} ?>';
|
. '}';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'auth.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'auth.php', $module);
|
||||||
|
|
||||||
Security::login(1, 10, 'USER');
|
Security::login(1, 10, 'USER');
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
$this->expectOutputString('{"foo":"bar"}');
|
$this->expectOutputString('{"foo":"bar"}');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRoleDefaultMethod()
|
public function testRoleDefaultMethod()
|
||||||
{
|
{
|
||||||
setUpRequest('rolemethod');
|
setUpRequest('rolemethod');
|
||||||
|
|
||||||
$module = '<?php class rolemethod extends Module { '
|
$module = '<?php class rolemethod extends Module { '
|
||||||
. 'public $security = SECURITY_LEVEL_USER;'
|
. 'public $security = SECURITY_LEVEL_USER;'
|
||||||
. 'public function __default() { return ["foo" => "bar"]; }'
|
. 'public function __default() { return ["foo" => "bar"]; }'
|
||||||
. 'public function __default_USER() { return ["user" => "me"]; }'
|
. 'public function __default_USER() { return ["user" => "me"]; }'
|
||||||
. '} ?>';
|
. '}';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'rolemethod.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'rolemethod.php', $module);
|
||||||
|
|
||||||
Security::login(1, 10, 'USER');
|
Security::login(1, 10, 'USER');
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
$this->expectOutputString('{"user":"me"}');
|
$this->expectOutputString('{"user":"me"}');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testValidRequestMethod()
|
public function testValidRequestMethod()
|
||||||
{
|
{
|
||||||
setUpRequest('validrequestmethod');
|
setUpRequest('validrequestmethod');
|
||||||
|
|
||||||
$module = '<?php class validrequestmethod extends Module { '
|
$module = '<?php class validrequestmethod extends Module { '
|
||||||
. 'public $method = "GET";'
|
. 'public $method = "GET";'
|
||||||
. 'public function __default() { return ["foo" => "bar"]; }'
|
. 'public function __default() { return ["foo" => "bar"]; }'
|
||||||
. '} ?>';
|
. '}';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'validrequestmethod.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'validrequestmethod.php', $module);
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
$this->expectOutputString('{"foo":"bar"}');
|
$this->expectOutputString('{"foo":"bar"}');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testInvalidRequestMethod()
|
public function testInvalidRequestMethod()
|
||||||
{
|
{
|
||||||
setUpRequest('invalidrequestmethod');
|
setUpRequest('invalidrequestmethod');
|
||||||
|
|
||||||
$module = '<?php class invalidrequestmethod extends Module { '
|
$module = '<?php class invalidrequestmethod extends Module { '
|
||||||
. 'public $method = "POST";'
|
. 'public $method = "POST";'
|
||||||
. 'public function __default() { return ["foo" => "bar"]; }'
|
. 'public function __default() { return ["foo" => "bar"]; }'
|
||||||
. '} ?>';
|
. '}';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'invalidrequestmethod.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'invalidrequestmethod.php', $module);
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
$this->expectOutputString('{"status":"error","message":"There was a problem with your request method."}');
|
$this->expectOutputString('{"status":"error","message":"There was a problem with your request method."}');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testValidationErrors()
|
public function testValidationErrors()
|
||||||
{
|
{
|
||||||
setUpRequest('validationerrors');
|
setUpRequest('validationerrors');
|
||||||
|
|
||||||
$module = '<?php class validationerrors extends Module { '
|
$module = '<?php class validationerrors extends Module { '
|
||||||
. 'public $validate = ["test"];'
|
. 'public $validate = ["test"];'
|
||||||
. 'public function __default() { return ["foo" => "bar"]; }'
|
. 'public function __default() { return ["foo" => "bar"]; }'
|
||||||
. '} ?>';
|
. '}';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'validationerrors.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'validationerrors.php', $module);
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
$this->expectOutputString('{"status":"error","message":"The test field is required."}');
|
$this->expectOutputString('{"status":"error","message":"The test field is required."}');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testError404()
|
public function testError404()
|
||||||
{
|
{
|
||||||
setUpRequest('fourohfour');
|
setUpRequest('fourohfour');
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
$this->assertTrue(in_array('Status: 404 Not Found', xdebug_get_headers()));
|
$this->assertTrue(in_array('Status: 404 Not Found', xdebug_get_headers()));
|
||||||
$this->expectOutputRegex('/<h1>Not Found<\/h1>/');
|
$this->expectOutputRegex('/<h1>Not Found<\/h1>/');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testCustomError404()
|
public function testCustomError404()
|
||||||
{
|
{
|
||||||
setUpRequest('customfourohfour');
|
setUpRequest('customfourohfour');
|
||||||
|
|
||||||
file_put_contents(SITE_TEMPLATE_PATH . '__shared/404.phtml', '<h1>Custom Not Found</h1>');
|
file_put_contents(SITE_TEMPLATE_PATH . '__shared/404.phtml', '<h1>Custom Not Found</h1>');
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
$this->assertTrue(in_array('Status: 404 Not Found', xdebug_get_headers()));
|
$this->assertTrue(in_array('Status: 404 Not Found', xdebug_get_headers()));
|
||||||
$this->expectOutputRegex('/<h1>Custom Not Found<\/h1>/');
|
$this->expectOutputRegex('/<h1>Custom Not Found<\/h1>/');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testProfilerOutput()
|
public function testProfilerOutput()
|
||||||
{
|
{
|
||||||
$this->config->data['pickles']['profiler'] = true;
|
$this->config->data['pickles']['profiler'] = true;
|
||||||
|
|
||||||
$this->expectOutputRegex('/id="pickles-profiler"/');
|
$this->expectOutputRegex('/id="pickles-profiler"/');
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testTwoValidTemplates()
|
public function testTwoValidTemplates()
|
||||||
{
|
{
|
||||||
$this->config->data['pickles']['profiler'] = true;
|
$this->config->data['pickles']['profiler'] = true;
|
||||||
|
|
||||||
setUpRequest('validtemplates');
|
setUpRequest('validtemplates');
|
||||||
|
|
||||||
$module = '<?php class validtemplates extends Module { } ?>';
|
$module = '<?php class validtemplates extends Module { }';
|
||||||
|
|
||||||
file_put_contents(SITE_MODULE_PATH . 'validtemplates.php', $module);
|
file_put_contents(SITE_MODULE_PATH . 'validtemplates.php', $module);
|
||||||
|
|
||||||
$child_template = SITE_TEMPLATE_PATH . 'validtemplates.phtml';
|
$child_template = SITE_TEMPLATE_PATH . 'validtemplates.phtml';
|
||||||
file_put_contents($child_template, '<div>child template</div>');
|
file_put_contents($child_template, '<div>child template</div>');
|
||||||
|
|
||||||
// Vim syntax highlighting borks unless ----v
|
// Vim syntax highlighting borks unless ----v
|
||||||
$child = '<?php require $this->template; ?' . '>' . "\n";
|
$child = '<?php require $this->template; ?' . '>' . "\n";
|
||||||
|
|
||||||
$html = <<<HTML
|
$html = <<<HTML
|
||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html>
|
<html>
|
||||||
<body>
|
<body>
|
||||||
<h1>parent template</h1>
|
<h1>parent template</h1>
|
||||||
{$child}
|
{$child}
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
HTML;
|
HTML;
|
||||||
|
|
||||||
file_put_contents(SITE_TEMPLATE_PATH . '__shared/index.phtml', $html);
|
file_put_contents(SITE_TEMPLATE_PATH . '__shared/index.phtml', $html);
|
||||||
|
|
||||||
new Controller();
|
new Controller();
|
||||||
|
|
||||||
$this->expectOutputRegex('/^<!doctype html>
|
$this->expectOutputRegex('/^<!doctype html>
|
||||||
<html>
|
<html>
|
||||||
<body>
|
<body>
|
||||||
<h1>parent template<\/h1>
|
<h1>parent template<\/h1>
|
||||||
<div>child template<\/div>
|
<div>child template<\/div>
|
||||||
<\/body>
|
<\/body>
|
||||||
<\/html>.+<style>/');
|
<\/html>.+<style>/');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,27 +2,26 @@
|
||||||
|
|
||||||
class ConvertTest extends PHPUnit_Framework_TestCase
|
class ConvertTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @dataProvider providerArrayToXML
|
* @dataProvider providerArrayToXML
|
||||||
*/
|
*/
|
||||||
public function testArrayToXML($a, $b, $c)
|
public function testArrayToXML($a, $b, $c)
|
||||||
{
|
{
|
||||||
$this->assertEquals(Convert::arrayToXML($a, $b), $c);
|
$this->assertEquals(Convert::arrayToXML($a, $b), $c);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function providerArrayToXML()
|
public function providerArrayToXML()
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
['foo', false, ''],
|
['foo', false, ''],
|
||||||
[['foo', 'bar'], false, '<0>foo</0><1>bar</1>'],
|
[['foo', 'bar'], false, '<0>foo</0><1>bar</1>'],
|
||||||
[['foo', 'bar'], true, "<0>foo</0>\n<1>bar</1>\n"],
|
[['foo', 'bar'], true, "<0>foo</0>\n<1>bar</1>\n"],
|
||||||
[['foo' => 'bar'], false, '<foo>bar</foo>'],
|
[['foo' => 'bar'], false, '<foo>bar</foo>'],
|
||||||
[['foo' => 'b & r'], false, '<foo><![CDATA[b & r]]></foo>'],
|
[['foo' => 'b & r'], false, '<foo><![CDATA[b & r]]></foo>'],
|
||||||
[['children' => ['child' => ['foo', 'bar']]], false, '<children><child>foo</child><child>bar</child></children>'],
|
[['children' => ['child' => ['foo', 'bar']]], false, '<children><child>foo</child><child>bar</child></children>'],
|
||||||
[['children' => ['child' => ['foo & bar']]], false, '<children><child><![CDATA[foo & bar]]></child></children>'],
|
[['children' => ['child' => ['foo & bar']]], false, '<children><child><![CDATA[foo & bar]]></child></children>'],
|
||||||
[['children' => ['child' => ['foo', 'bar']]], true, "<children>\n\t<child>foo</child>\n\t<child>bar</child>\n</children>\n"],
|
[['children' => ['child' => ['foo', 'bar']]], true, "<children>\n\t<child>foo</child>\n\t<child>bar</child>\n</children>\n"],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,193 +2,192 @@
|
||||||
|
|
||||||
class DatabaseTest extends PHPUnit_Framework_TestCase
|
class DatabaseTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
public function testGetInstanceFalse()
|
public function testGetInstanceFalse()
|
||||||
{
|
{
|
||||||
$this->assertFalse(Database::getInstance());
|
$this->assertFalse(Database::getInstance());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage The specified datasource is not defined in the config.
|
* @expectedExceptionMessage The specified datasource is not defined in the config.
|
||||||
*/
|
*/
|
||||||
public function testGetInstanceDatasourceNotDefined()
|
public function testGetInstanceDatasourceNotDefined()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['datasource'] = 'bad';
|
$config->data['pickles']['datasource'] = 'bad';
|
||||||
Database::getInstance();
|
Database::getInstance();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage The specified datasource lacks a driver.
|
* @expectedExceptionMessage The specified datasource lacks a driver.
|
||||||
*/
|
*/
|
||||||
public function testGetInstanceDatasourceLacksDriver()
|
public function testGetInstanceDatasourceLacksDriver()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['datasources'] = [
|
$config->data['datasources'] = [
|
||||||
'bad' => [
|
'bad' => [
|
||||||
'type' => 'mysql',
|
'type' => 'mysql',
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
$this->assertInstanceOf('Database', Database::getInstance());
|
$this->assertInstanceOf('Database', Database::getInstance());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage There was an error loading the database configuration.
|
* @expectedExceptionMessage There was an error loading the database configuration.
|
||||||
*/
|
*/
|
||||||
public function testOpenConfigError()
|
public function testOpenConfigError()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['datasources'] = [
|
$config->data['datasources'] = [
|
||||||
'bad' => [
|
'bad' => [
|
||||||
'type' => 'mysql',
|
'type' => 'mysql',
|
||||||
'driver' => 'pdo_mysql',
|
'driver' => 'pdo_mysql',
|
||||||
'database' => 'test',
|
'database' => 'test',
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
$db = Database::getInstance();
|
$db = Database::getInstance();
|
||||||
$db->open();
|
$db->open();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testGetInstanceDatasourcesArray()
|
public function testGetInstanceDatasourcesArray()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['datasources'] = [
|
$config->data['datasources'] = [
|
||||||
'mysql' => [
|
'mysql' => [
|
||||||
'type' => 'mysql',
|
'type' => 'mysql',
|
||||||
'driver' => 'pdo_mysql',
|
'driver' => 'pdo_mysql',
|
||||||
'hostname' => 'localhost',
|
'hostname' => 'localhost',
|
||||||
'username' => 'root',
|
'username' => 'root',
|
||||||
'password' => '',
|
'password' => '',
|
||||||
'database' => 'test',
|
'database' => 'test',
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
$this->assertInstanceOf('Database', Database::getInstance());
|
$this->assertInstanceOf('Database', Database::getInstance());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Also tests the datasource being missing and selecting the first one
|
// Also tests the datasource being missing and selecting the first one
|
||||||
public function testGetInstanceMySQL()
|
public function testGetInstanceMySQL()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
unset($config->data['pickles']['datasource']);
|
unset($config->data['pickles']['datasource']);
|
||||||
$this->assertInstanceOf('Database', Database::getInstance());
|
$this->assertInstanceOf('Database', Database::getInstance());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testOpenMySQL()
|
public function testOpenMySQL()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['datasource'] = 'mysql';
|
$config->data['pickles']['datasource'] = 'mysql';
|
||||||
$db = Database::getInstance();
|
$db = Database::getInstance();
|
||||||
$db->open();
|
$db->open();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testExecute()
|
public function testExecute()
|
||||||
{
|
{
|
||||||
$db = Database::getInstance();
|
$db = Database::getInstance();
|
||||||
$this->assertEquals('0', $db->execute('SHOW TABLES'));
|
$this->assertEquals('0', $db->execute('SHOW TABLES'));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage No query to execute.
|
* @expectedExceptionMessage No query to execute.
|
||||||
*/
|
*/
|
||||||
public function testExecuteNoQuery()
|
public function testExecuteNoQuery()
|
||||||
{
|
{
|
||||||
$db = Database::getInstance();
|
$db = Database::getInstance();
|
||||||
$db->execute(' ');
|
$db->execute(' ');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFetch()
|
public function testFetch()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['logging'] = true;
|
$config->data['pickles']['logging'] = true;
|
||||||
$config->data['pickles']['profiler'] = true;
|
$config->data['pickles']['profiler'] = true;
|
||||||
$db = Database::getInstance();
|
$db = Database::getInstance();
|
||||||
$this->assertEquals([], $db->fetch('SELECT * FROM pickles WHERE id != ?', ['0']));
|
$this->assertEquals([], $db->fetch('SELECT * FROM pickles WHERE id != ?', ['0']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testExplainNoInput()
|
public function testExplainNoInput()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$db = Database::getInstance();
|
$db = Database::getInstance();
|
||||||
$this->assertEquals([], $db->fetch('SELECT * FROM pickles WHERE id != 0'));
|
$this->assertEquals([], $db->fetch('SELECT * FROM pickles WHERE id != 0'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSlowQuery()
|
public function testSlowQuery()
|
||||||
{
|
{
|
||||||
$db = Database::getInstance();
|
$db = Database::getInstance();
|
||||||
$this->assertEquals('0', $db->execute('SHOW DATABASES', null, true));
|
$this->assertEquals('0', $db->execute('SHOW DATABASES', null, true));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testCloseMySQL()
|
public function testCloseMySQL()
|
||||||
{
|
{
|
||||||
$db = Database::getInstance();
|
$db = Database::getInstance();
|
||||||
$db->open();
|
$db->open();
|
||||||
|
|
||||||
$this->assertTrue($db->close());
|
$this->assertTrue($db->close());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testGetInstancePostgreSQL()
|
public function testGetInstancePostgreSQL()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['datasource'] = 'pgsql';
|
$config->data['pickles']['datasource'] = 'pgsql';
|
||||||
$config->data['datasources']['pgsql'] = [
|
$config->data['datasources']['pgsql'] = [
|
||||||
'type' => 'pgsql',
|
'type' => 'pgsql',
|
||||||
'driver' => 'pdo_pgsql',
|
'driver' => 'pdo_pgsql',
|
||||||
'hostname' => 'localhost',
|
'hostname' => 'localhost',
|
||||||
'username' => '',
|
'username' => '',
|
||||||
'password' => '',
|
'password' => '',
|
||||||
'database' => 'test',
|
'database' => 'test',
|
||||||
];
|
];
|
||||||
$this->assertInstanceOf('Database', Database::getInstance());
|
$this->assertInstanceOf('Database', Database::getInstance());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException PDOException
|
* @expectedException PDOException
|
||||||
* @expectedExceptionCode 7
|
* @expectedExceptionCode 7
|
||||||
*/
|
*/
|
||||||
public function testOpenPostgreSQL()
|
public function testOpenPostgreSQL()
|
||||||
{
|
{
|
||||||
// Also throws an exception since I don't have PostgreSQL set up
|
// Also throws an exception since I don't have PostgreSQL set up
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$db = Database::getInstance();
|
$db = Database::getInstance();
|
||||||
$db->open();
|
$db->open();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testGetInstanceSQLite()
|
public function testGetInstanceSQLite()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['datasource'] = 'sqlite';
|
$config->data['pickles']['datasource'] = 'sqlite';
|
||||||
$config->data['datasources']['sqlite'] = [
|
$config->data['datasources']['sqlite'] = [
|
||||||
'type' => 'sqlite',
|
'type' => 'sqlite',
|
||||||
'driver' => 'pdo_sqlite',
|
'driver' => 'pdo_sqlite',
|
||||||
'hostname' => 'localhost',
|
'hostname' => 'localhost',
|
||||||
'username' => '',
|
'username' => '',
|
||||||
'password' => '',
|
'password' => '',
|
||||||
'database' => 'test',
|
'database' => 'test',
|
||||||
];
|
];
|
||||||
$this->assertInstanceOf('Database', Database::getInstance());
|
$this->assertInstanceOf('Database', Database::getInstance());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Datasource driver "pdo_invalid" is invalid
|
* @expectedExceptionMessage Datasource driver "pdo_invalid" is invalid
|
||||||
*/
|
*/
|
||||||
public function testGetInstanceInvalidDriver()
|
public function testGetInstanceInvalidDriver()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['datasource'] = 'invalid';
|
$config->data['pickles']['datasource'] = 'invalid';
|
||||||
$config->data['datasources']['invalid'] = [
|
$config->data['datasources']['invalid'] = [
|
||||||
'type' => 'invalid',
|
'type' => 'invalid',
|
||||||
'driver' => 'pdo_invalid',
|
'driver' => 'pdo_invalid',
|
||||||
'hostname' => 'localhost',
|
'hostname' => 'localhost',
|
||||||
'username' => '',
|
'username' => '',
|
||||||
'password' => '',
|
'password' => '',
|
||||||
'database' => 'test',
|
'database' => 'test',
|
||||||
];
|
];
|
||||||
Database::getInstance();
|
Database::getInstance();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,29 +2,28 @@
|
||||||
|
|
||||||
class DateTest extends PHPUnit_Framework_TestCase
|
class DateTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @dataProvider providerAge
|
* @dataProvider providerAge
|
||||||
*/
|
*/
|
||||||
public function testAge($a, $b)
|
public function testAge($a, $b)
|
||||||
{
|
{
|
||||||
$this->assertEquals(Date::age($a), $b);
|
$this->assertEquals(Date::age($a), $b);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function providerAge()
|
public function providerAge()
|
||||||
{
|
{
|
||||||
ini_set('date.timezone', 'America/New_York');
|
ini_set('date.timezone', 'America/New_York');
|
||||||
|
|
||||||
$time = strtotime('-25 years');
|
$time = strtotime('-25 years');
|
||||||
|
|
||||||
return [
|
return [
|
||||||
[date('Y-m-d', $time), '25'],
|
[date('Y-m-d', $time), '25'],
|
||||||
[date('m/d/Y', $time), '25'],
|
[date('m/d/Y', $time), '25'],
|
||||||
[date('r', $time), '25'],
|
[date('r', $time), '25'],
|
||||||
['today', '0'],
|
['today', '0'],
|
||||||
['400 days ago', '1'],
|
['400 days ago', '1'],
|
||||||
[true, Date::age('1969-12-31')],
|
[true, Date::age('1969-12-31')],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,85 +2,85 @@
|
||||||
|
|
||||||
class DisplayTest extends PHPUnit_Framework_TestCase
|
class DisplayTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
private $display, $shared_templates;
|
private $display, $shared_templates;
|
||||||
|
|
||||||
private $child_html = '<div>child template</div>';
|
private $child_html = '<div>child template</div>';
|
||||||
|
|
||||||
protected function setUp()
|
protected function setUp()
|
||||||
{
|
{
|
||||||
parent::setUp();
|
parent::setUp();
|
||||||
|
|
||||||
$this->shared_templates = SITE_TEMPLATE_PATH . '__shared/';
|
$this->shared_templates = SITE_TEMPLATE_PATH . '__shared/';
|
||||||
|
|
||||||
if (!file_exists($this->shared_templates))
|
if (!file_exists($this->shared_templates))
|
||||||
{
|
{
|
||||||
mkdir($this->shared_templates, 0644, true);
|
mkdir($this->shared_templates, 0644, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
$_SERVER['REQUEST_URI'] = '/test';
|
$_SERVER['REQUEST_URI'] = '/test';
|
||||||
$_REQUEST['request'] = 'test';
|
$_REQUEST['request'] = 'test';
|
||||||
|
|
||||||
$this->display = new Display();
|
$this->display = new Display();
|
||||||
$this->display->module = [
|
$this->display->module = [
|
||||||
'pickles' => [
|
'pickles' => [
|
||||||
'yummy' => 'gherkin',
|
'yummy' => 'gherkin',
|
||||||
'delish' => 'kosher dill',
|
'delish' => 'kosher dill',
|
||||||
'yucky' => 'bread & butter'
|
'yucky' => 'bread & butter'
|
||||||
]
|
]
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function tearDown()
|
protected function tearDown()
|
||||||
{
|
{
|
||||||
unlink(SITE_TEMPLATE_PATH . 'test.phtml');
|
unlink(SITE_TEMPLATE_PATH . 'test.phtml');
|
||||||
unlink($this->shared_templates . 'index.phtml');
|
unlink($this->shared_templates . 'index.phtml');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testInvalidReturnType()
|
public function testInvalidReturnType()
|
||||||
{
|
{
|
||||||
$this->display->return = 'invalid';
|
$this->display->return = 'invalid';
|
||||||
$this->assertEquals('Invalid return type.', $this->display->render());
|
$this->assertEquals('Invalid return type.', $this->display->render());
|
||||||
|
|
||||||
// Gotta do this or the test will be considered "risky"
|
// Gotta do this or the test will be considered "risky"
|
||||||
ob_end_clean();
|
ob_end_clean();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testPHPSESSID()
|
public function testPHPSESSID()
|
||||||
{
|
{
|
||||||
$request_uri = $_SERVER['REQUEST_URI'];
|
$request_uri = $_SERVER['REQUEST_URI'];
|
||||||
$_SERVER['REQUEST_URI'] .= '?PHPSESSID=session_id';
|
$_SERVER['REQUEST_URI'] .= '?PHPSESSID=session_id';
|
||||||
$return = $this->display->render();
|
$return = $this->display->render();
|
||||||
|
|
||||||
$this->assertTrue(in_array('Location: ' . $request_uri, xdebug_get_headers()));
|
$this->assertTrue(in_array('Location: ' . $request_uri, xdebug_get_headers()));
|
||||||
$this->assertEquals('Requested URI contains PHPSESSID, redirecting.', $return);
|
$this->assertEquals('Requested URI contains PHPSESSID, redirecting.', $return);
|
||||||
|
|
||||||
// Gotta do this or the test will be considered "risky"
|
// Gotta do this or the test will be considered "risky"
|
||||||
ob_end_clean();
|
ob_end_clean();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testNoParentTemplate()
|
public function testNoParentTemplate()
|
||||||
{
|
{
|
||||||
$child_template = SITE_TEMPLATE_PATH . 'test.phtml';
|
$child_template = SITE_TEMPLATE_PATH . 'test.phtml';
|
||||||
file_put_contents($child_template, $this->child_html);
|
file_put_contents($child_template, $this->child_html);
|
||||||
|
|
||||||
$this->display->templates = [$child_template];
|
$this->display->templates = [$child_template];
|
||||||
|
|
||||||
$this->assertEquals($this->child_html, $this->display->render());
|
$this->assertEquals($this->child_html, $this->display->render());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRenderJSON()
|
public function testRenderJSON()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'{"pickles":{"yummy":"gherkin","delish":"kosher dill","yucky":"bread & butter"}}',
|
'{"pickles":{"yummy":"gherkin","delish":"kosher dill","yucky":"bread & butter"}}',
|
||||||
$this->display->render()
|
$this->display->render()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRenderJSONPrettyPrint()
|
public function testRenderJSONPrettyPrint()
|
||||||
{
|
{
|
||||||
$_REQUEST['pretty'] = 'true';
|
$_REQUEST['pretty'] = 'true';
|
||||||
|
|
||||||
$pretty_json = <<<JSON
|
$pretty_json = <<<JSON
|
||||||
{
|
{
|
||||||
"pickles": {
|
"pickles": {
|
||||||
"yummy": "gherkin",
|
"yummy": "gherkin",
|
||||||
|
@ -90,44 +90,43 @@ class DisplayTest extends PHPUnit_Framework_TestCase
|
||||||
}
|
}
|
||||||
JSON;
|
JSON;
|
||||||
|
|
||||||
$this->assertEquals($pretty_json, $this->display->render());
|
$this->assertEquals($pretty_json, $this->display->render());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRenderXML()
|
public function testRenderXML()
|
||||||
{
|
{
|
||||||
$this->display->return = ['template', 'xml'];
|
$this->display->return = ['template', 'xml'];
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'<yummy>gherkin</yummy><delish>kosher dill</delish><yucky><![CDATA[bread & butter]]></yucky>',
|
'<yummy>gherkin</yummy><delish>kosher dill</delish><yucky><![CDATA[bread & butter]]></yucky>',
|
||||||
$this->display->render()
|
$this->display->render()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRenderXMLPrettyPrint()
|
public function testRenderXMLPrettyPrint()
|
||||||
{
|
{
|
||||||
$_REQUEST['pretty'] = 'true';
|
$_REQUEST['pretty'] = 'true';
|
||||||
|
|
||||||
$pretty_xml = <<<XML
|
$pretty_xml = <<<XML
|
||||||
<yummy>gherkin</yummy>
|
<yummy>gherkin</yummy>
|
||||||
<delish>kosher dill</delish>
|
<delish>kosher dill</delish>
|
||||||
<yucky><![CDATA[bread & butter]]></yucky>
|
<yucky><![CDATA[bread & butter]]></yucky>
|
||||||
|
|
||||||
XML;
|
XML;
|
||||||
|
|
||||||
$this->display->return = ['template', 'xml'];
|
$this->display->return = ['template', 'xml'];
|
||||||
$this->assertEquals($pretty_xml, $this->display->render());
|
$this->assertEquals($pretty_xml, $this->display->render());
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
public function testRenderRSS()
|
public function testRenderRSS()
|
||||||
{
|
{
|
||||||
$this->fail('Not yet implemented.');
|
$this->fail('Not yet implemented.');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRenderRSSPrettyPrint()
|
public function testRenderRSSPrettyPrint()
|
||||||
{
|
{
|
||||||
$this->fail('Not yet implemented.');
|
$this->fail('Not yet implemented.');
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,75 +2,74 @@
|
||||||
|
|
||||||
class DistanceTest extends PHPUnit_Framework_TestCase
|
class DistanceTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
public function testConvertKilometersToMiles()
|
public function testConvertKilometersToMiles()
|
||||||
{
|
{
|
||||||
$this->assertEquals(0.621371, Distance::kilometersToMiles(1));
|
$this->assertEquals(0.621371, Distance::kilometersToMiles(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testConvertKilometersToMeters()
|
public function testConvertKilometersToMeters()
|
||||||
{
|
{
|
||||||
$this->assertEquals(1000, Distance::kilometersToMeters(1));
|
$this->assertEquals(1000, Distance::kilometersToMeters(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testConvertKilometersToYards()
|
public function testConvertKilometersToYards()
|
||||||
{
|
{
|
||||||
$this->assertEquals(1093.61, Distance::kilometersToYards(1));
|
$this->assertEquals(1093.61, Distance::kilometersToYards(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testConvertMilesToKilometers()
|
public function testConvertMilesToKilometers()
|
||||||
{
|
{
|
||||||
$this->assertEquals(1.60934, Distance::milesToKilometers(1));
|
$this->assertEquals(1.60934, Distance::milesToKilometers(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testConvertMilesToMeters()
|
public function testConvertMilesToMeters()
|
||||||
{
|
{
|
||||||
$this->assertEquals(1609.34, Distance::milesToMeters(1));
|
$this->assertEquals(1609.34, Distance::milesToMeters(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testConvertMilesToYards()
|
public function testConvertMilesToYards()
|
||||||
{
|
{
|
||||||
$this->assertEquals(1760, Distance::milesToYards(1));
|
$this->assertEquals(1760, Distance::milesToYards(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testConvertMetersToKilometers()
|
public function testConvertMetersToKilometers()
|
||||||
{
|
{
|
||||||
$this->assertEquals(0.001, Distance::metersToKilometers(1));
|
$this->assertEquals(0.001, Distance::metersToKilometers(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testConvertMetersToMiles()
|
public function testConvertMetersToMiles()
|
||||||
{
|
{
|
||||||
$this->assertEquals(0.000621371, Distance::metersToMiles(1));
|
$this->assertEquals(0.000621371, Distance::metersToMiles(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testConvertMetersToYards()
|
public function testConvertMetersToYards()
|
||||||
{
|
{
|
||||||
$this->assertEquals(1.09361, Distance::metersToYards(1));
|
$this->assertEquals(1.09361, Distance::metersToYards(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testCalculateDistanceMiles()
|
public function testCalculateDistanceMiles()
|
||||||
{
|
{
|
||||||
$this->assertEquals(1003.2646776326, Distance::calculateDistance(27.947222, -82.458611, 40.67, -73.94));
|
$this->assertEquals(1003.2646776326, Distance::calculateDistance(27.947222, -82.458611, 40.67, -73.94));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testCalculateDistanceKilometers()
|
public function testCalculateDistanceKilometers()
|
||||||
{
|
{
|
||||||
$this->assertEquals(1614.5939763012, Distance::calculateDistance(27.947222, -82.458611, 40.67, -73.94, 'kilometers'));
|
$this->assertEquals(1614.5939763012, Distance::calculateDistance(27.947222, -82.458611, 40.67, -73.94, 'kilometers'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testCalculateDistanceMeters()
|
public function testCalculateDistanceMeters()
|
||||||
{
|
{
|
||||||
$this->assertEquals(1614593.9763012, Distance::calculateDistance(27.947222, -82.458611, 40.67, -73.94, 'meters'), '', 0.2);
|
$this->assertEquals(1614593.9763012, Distance::calculateDistance(27.947222, -82.458611, 40.67, -73.94, 'meters'), '', 0.2);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testCalculateDistanceYards()
|
public function testCalculateDistanceYards()
|
||||||
{
|
{
|
||||||
$this->assertEquals(1765745.8326334, Distance::calculateDistance(27.947222, -82.458611, 40.67, -73.94, 'yards'), '', 0.2);
|
$this->assertEquals(1765745.8326334, Distance::calculateDistance(27.947222, -82.458611, 40.67, -73.94, 'yards'), '', 0.2);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testNotEnoughUnits()
|
public function testNotEnoughUnits()
|
||||||
{
|
{
|
||||||
$this->assertFalse(Distance::milesTo(123));
|
$this->assertFalse(Distance::milesTo(123));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,236 +2,235 @@
|
||||||
|
|
||||||
class DynamicTest extends PHPUnit_Framework_TestCase
|
class DynamicTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
private $dynamic;
|
private $dynamic;
|
||||||
|
|
||||||
public static function setUpBeforeClass()
|
public static function setUpBeforeClass()
|
||||||
{
|
{
|
||||||
// Using actual filesystem because you can't chdir with vfs://
|
// Using actual filesystem because you can't chdir with vfs://
|
||||||
$public_path = '/tmp/pickles-fs/public/';
|
$public_path = '/tmp/pickles-fs/public/';
|
||||||
|
|
||||||
foreach (['css', 'images', 'js'] as $directory)
|
foreach (['css', 'images', 'js'] as $directory)
|
||||||
{
|
{
|
||||||
mkdir($public_path . $directory, 0777, true);
|
mkdir($public_path . $directory, 0777, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
touch($public_path . 'images/image.png');
|
touch($public_path . 'images/image.png');
|
||||||
touch($public_path . 'images/invalid');
|
touch($public_path . 'images/invalid');
|
||||||
|
|
||||||
$css = <<<CSS
|
$css = <<<CSS
|
||||||
body
|
body
|
||||||
{
|
{
|
||||||
color: #ffcc00;
|
color: #ffcc00;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
CSS;
|
CSS;
|
||||||
|
|
||||||
foreach (['css', 'less', 'scss'] as $extension)
|
foreach (['css', 'less', 'scss'] as $extension)
|
||||||
{
|
{
|
||||||
file_put_contents($public_path . 'css/stylesheet.' . $extension, $css);
|
file_put_contents($public_path . 'css/stylesheet.' . $extension, $css);
|
||||||
}
|
}
|
||||||
|
|
||||||
file_put_contents($public_path . 'css/alternate.css', $css);
|
file_put_contents($public_path . 'css/alternate.css', $css);
|
||||||
|
|
||||||
$js = <<<JS
|
$js = <<<JS
|
||||||
function foo()
|
function foo()
|
||||||
{
|
{
|
||||||
alert('bar');
|
alert('bar');
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('stuff');
|
console.log('stuff');
|
||||||
JS;
|
JS;
|
||||||
|
|
||||||
file_put_contents($public_path . 'js/script.js', $js);
|
file_put_contents($public_path . 'js/script.js', $js);
|
||||||
|
|
||||||
chdir($public_path);
|
chdir($public_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function setUp()
|
public function setUp()
|
||||||
{
|
{
|
||||||
$this->dynamic = new Dynamic();
|
$this->dynamic = new Dynamic();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function tearDown()
|
public function tearDown()
|
||||||
{
|
{
|
||||||
$minified_file = '/tmp/pickles-fs/public/css/stylesheet.min.css';
|
$minified_file = '/tmp/pickles-fs/public/css/stylesheet.min.css';
|
||||||
|
|
||||||
if (file_exists($minified_file))
|
if (file_exists($minified_file))
|
||||||
{
|
{
|
||||||
unlink($minified_file);
|
unlink($minified_file);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function tearDownAfterClass()
|
public static function tearDownAfterClass()
|
||||||
{
|
{
|
||||||
File::removeDirectory('/tmp/pickles-fs');
|
File::removeDirectory('/tmp/pickles-fs');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testReference()
|
public function testReference()
|
||||||
{
|
{
|
||||||
$this->assertRegExp(
|
$this->assertRegExp(
|
||||||
'/^\/images\/image\.\d{10}\.png$/',
|
'/^\/images\/image\.\d{10}\.png$/',
|
||||||
$this->dynamic->reference('/images/image.png'
|
$this->dynamic->reference('/images/image.png'
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Supplied reference does not exist (/images/missing.png)
|
* @expectedExceptionMessage Supplied reference does not exist (/images/missing.png)
|
||||||
*/
|
*/
|
||||||
public function testReferenceMissingFileWithoutFailover()
|
public function testReferenceMissingFileWithoutFailover()
|
||||||
{
|
{
|
||||||
$this->dynamic->reference('/images/missing.png');
|
$this->dynamic->reference('/images/missing.png');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testReferenceMissingFileWithFailover()
|
public function testReferenceMissingFileWithFailover()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'/images/failover.png',
|
'/images/failover.png',
|
||||||
$this->dynamic->reference('/images/missing.png', '/images/failover.png')
|
$this->dynamic->reference('/images/missing.png', '/images/failover.png')
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Filename must have an extension (e.g. /path/to/file.png)
|
* @expectedExceptionMessage Filename must have an extension (e.g. /path/to/file.png)
|
||||||
*/
|
*/
|
||||||
public function testReferenceInvalidFilename()
|
public function testReferenceInvalidFilename()
|
||||||
{
|
{
|
||||||
$this->dynamic->reference('/images/invalid');
|
$this->dynamic->reference('/images/invalid');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Reference value must be absolute (e.g. /path/to/file.png)
|
* @expectedExceptionMessage Reference value must be absolute (e.g. /path/to/file.png)
|
||||||
*/
|
*/
|
||||||
public function testReferenceNotAbsolute()
|
public function testReferenceNotAbsolute()
|
||||||
{
|
{
|
||||||
$this->dynamic->reference('../images/relative.png');
|
$this->dynamic->reference('../images/relative.png');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testReferenceWithQueryString()
|
public function testReferenceWithQueryString()
|
||||||
{
|
{
|
||||||
$this->assertRegExp(
|
$this->assertRegExp(
|
||||||
'/^\/images\/image\.\d{10}\.png\?foo=bar$/',
|
'/^\/images\/image\.\d{10}\.png\?foo=bar$/',
|
||||||
$this->dynamic->reference('/images/image.png?foo=bar'
|
$this->dynamic->reference('/images/image.png?foo=bar'
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Filename must have an extension (e.g. /path/to/file.css)
|
* @expectedExceptionMessage Filename must have an extension (e.g. /path/to/file.css)
|
||||||
*/
|
*/
|
||||||
public function testCSSMissingExtension()
|
public function testCSSMissingExtension()
|
||||||
{
|
{
|
||||||
$this->dynamic->css('/css/invalid');
|
$this->dynamic->css('/css/invalid');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testCSSWithoutMinify()
|
public function testCSSWithoutMinify()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['minify'] = false;
|
$config->data['pickles']['minify'] = false;
|
||||||
|
|
||||||
$this->assertRegExp('/^\/css\/stylesheet\.\d{10}\.css$/', $this->dynamic->css('/css/stylesheet.css'));
|
$this->assertRegExp('/^\/css\/stylesheet\.\d{10}\.css$/', $this->dynamic->css('/css/stylesheet.css'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testCSSWithoutMinifyFileMinifiedFileExists()
|
public function testCSSWithoutMinifyFileMinifiedFileExists()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['minify'] = false;
|
$config->data['pickles']['minify'] = false;
|
||||||
|
|
||||||
touch('/tmp/pickles-fs/public/css/stylesheet.min.css');
|
touch('/tmp/pickles-fs/public/css/stylesheet.min.css');
|
||||||
|
|
||||||
$this->assertRegExp('/^\/css\/stylesheet\.min\.\d{10}\.css$/', $this->dynamic->css('/css/stylesheet.css'));
|
$this->assertRegExp('/^\/css\/stylesheet\.min\.\d{10}\.css$/', $this->dynamic->css('/css/stylesheet.css'));
|
||||||
|
|
||||||
unlink('/tmp/pickles-fs/public/css/stylesheet.min.css');
|
unlink('/tmp/pickles-fs/public/css/stylesheet.min.css');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testCSSWithMinify()
|
public function testCSSWithMinify()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['minify'] = true;
|
$config->data['pickles']['minify'] = true;
|
||||||
|
|
||||||
$this->assertRegExp('/^\/css\/stylesheet\.min\.\d{10}\.css$/', $this->dynamic->css('/css/stylesheet.css'));
|
$this->assertRegExp('/^\/css\/stylesheet\.min\.\d{10}\.css$/', $this->dynamic->css('/css/stylesheet.css'));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Supplied reference does not exist
|
* @expectedExceptionMessage Supplied reference does not exist
|
||||||
*/
|
*/
|
||||||
public function testCSSReferenceDoesNotExist()
|
public function testCSSReferenceDoesNotExist()
|
||||||
{
|
{
|
||||||
$this->dynamic->css('/css/missing.css');
|
$this->dynamic->css('/css/missing.css');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLESSWithoutMinify()
|
public function testLESSWithoutMinify()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['minify'] = false;
|
$config->data['pickles']['minify'] = false;
|
||||||
|
|
||||||
$this->assertRegExp('/^\/css\/stylesheet\.\d{10}\.less$/', $this->dynamic->css('/css/stylesheet.less'));
|
$this->assertRegExp('/^\/css\/stylesheet\.\d{10}\.less$/', $this->dynamic->css('/css/stylesheet.less'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLESSWithMinify()
|
public function testLESSWithMinify()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['minify'] = true;
|
$config->data['pickles']['minify'] = true;
|
||||||
|
|
||||||
$this->assertRegExp('/^\/css\/stylesheet\.min\.\d{10}\.css$/', $this->dynamic->css('/css/stylesheet.less'));
|
$this->assertRegExp('/^\/css\/stylesheet\.min\.\d{10}\.css$/', $this->dynamic->css('/css/stylesheet.less'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSCSSWithoutMinify()
|
public function testSCSSWithoutMinify()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['minify'] = false;
|
$config->data['pickles']['minify'] = false;
|
||||||
|
|
||||||
$this->assertRegExp('/^\/css\/stylesheet\.\d{10}\.scss$/', $this->dynamic->css('/css/stylesheet.scss'));
|
$this->assertRegExp('/^\/css\/stylesheet\.\d{10}\.scss$/', $this->dynamic->css('/css/stylesheet.scss'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSCSSWithMinify()
|
public function testSCSSWithMinify()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['minify'] = true;
|
$config->data['pickles']['minify'] = true;
|
||||||
|
|
||||||
$this->assertRegExp('/^\/css\/stylesheet\.min\.\d{10}\.css$/', $this->dynamic->css('/css/stylesheet.scss'));
|
$this->assertRegExp('/^\/css\/stylesheet\.min\.\d{10}\.css$/', $this->dynamic->css('/css/stylesheet.scss'));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Filename must have an extension (e.g. /path/to/file.js)
|
* @expectedExceptionMessage Filename must have an extension (e.g. /path/to/file.js)
|
||||||
*/
|
*/
|
||||||
public function testJSMissingExtension()
|
public function testJSMissingExtension()
|
||||||
{
|
{
|
||||||
$this->dynamic->js('/js/invalid');
|
$this->dynamic->js('/js/invalid');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Supplied reference does not exist
|
* @expectedExceptionMessage Supplied reference does not exist
|
||||||
*/
|
*/
|
||||||
public function testJSReferenceDoesNotExist()
|
public function testJSReferenceDoesNotExist()
|
||||||
{
|
{
|
||||||
$this->dynamic->js('/js/missing.js');
|
$this->dynamic->js('/js/missing.js');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testJS()
|
public function testJS()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['minify'] = true;
|
$config->data['pickles']['minify'] = true;
|
||||||
|
|
||||||
$this->assertRegExp('/^\/js\/script\.min\.\d{10}\.js$/', $this->dynamic->js('/js/script.js'));
|
$this->assertRegExp('/^\/js\/script\.min\.\d{10}\.js$/', $this->dynamic->js('/js/script.js'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testJSWithoutMinifyFileMinifiedFileExists()
|
public function testJSWithoutMinifyFileMinifiedFileExists()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['minify'] = false;
|
$config->data['pickles']['minify'] = false;
|
||||||
|
|
||||||
touch('/tmp/pickles-fs/public/js/script.min.css');
|
touch('/tmp/pickles-fs/public/js/script.min.css');
|
||||||
|
|
||||||
$this->assertRegExp('/^\/js\/script\.min\.\d{10}\.js$/', $this->dynamic->js('/js/script.js'));
|
$this->assertRegExp('/^\/js\/script\.min\.\d{10}\.js$/', $this->dynamic->js('/js/script.js'));
|
||||||
|
|
||||||
unlink('/tmp/pickles-fs/public/js/script.min.css');
|
unlink('/tmp/pickles-fs/public/js/script.min.css');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,61 +2,60 @@
|
||||||
|
|
||||||
class FileTest extends PHPUnit_Framework_TestCase
|
class FileTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
public static function setUpBeforeClass()
|
public static function setUpBeforeClass()
|
||||||
{
|
{
|
||||||
// Using actual filesystem because you can't chdir with vfs://
|
// Using actual filesystem because you can't chdir with vfs://
|
||||||
$directory = '/tmp/pickles-fs/filetest/test/test';
|
$directory = '/tmp/pickles-fs/filetest/test/test';
|
||||||
|
|
||||||
if (!file_exists($directory))
|
if (!file_exists($directory))
|
||||||
{
|
{
|
||||||
mkdir($directory, 0777, true);
|
mkdir($directory, 0777, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function tearDownAfterClass()
|
public static function tearDownAfterClass()
|
||||||
{
|
{
|
||||||
File::removeDirectory('/tmp/pickles-fs');
|
File::removeDirectory('/tmp/pickles-fs');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRemoveDirectory()
|
public function testRemoveDirectory()
|
||||||
{
|
{
|
||||||
$directory = '/tmp/pickles-fs/filetest/';
|
$directory = '/tmp/pickles-fs/filetest/';
|
||||||
|
|
||||||
touch($directory . 'ing');
|
touch($directory . 'ing');
|
||||||
touch($directory . 'test/ing');
|
touch($directory . 'test/ing');
|
||||||
touch($directory . 'test/test/ing');
|
touch($directory . 'test/test/ing');
|
||||||
|
|
||||||
File::removeDirectory($directory);
|
File::removeDirectory($directory);
|
||||||
|
|
||||||
$this->assertFalse(file_exists($directory));
|
$this->assertFalse(file_exists($directory));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testMissingTrailingSlash()
|
public function testMissingTrailingSlash()
|
||||||
{
|
{
|
||||||
$directory = SITE_PATH . 'missing';
|
$directory = SITE_PATH . 'missing';
|
||||||
|
|
||||||
mkdir($directory, 0777, true);
|
mkdir($directory, 0777, true);
|
||||||
touch(SITE_PATH . 'missing/slash');
|
touch(SITE_PATH . 'missing/slash');
|
||||||
|
|
||||||
File::removeDirectory($directory);
|
File::removeDirectory($directory);
|
||||||
|
|
||||||
$this->assertFalse(file_exists($directory));
|
$this->assertFalse(file_exists($directory));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRemoveFileNotDirectory()
|
public function testRemoveFileNotDirectory()
|
||||||
{
|
{
|
||||||
$directory = SITE_PATH . 'dir';
|
$directory = SITE_PATH . 'dir';
|
||||||
$file = SITE_PATH . 'dir/file';
|
$file = SITE_PATH . 'dir/file';
|
||||||
|
|
||||||
mkdir($directory, 0777, true);
|
mkdir($directory, 0777, true);
|
||||||
touch($file);
|
touch($file);
|
||||||
|
|
||||||
File::removeDirectory($file);
|
File::removeDirectory($file);
|
||||||
|
|
||||||
$this->assertFalse(file_exists($file));
|
$this->assertFalse(file_exists($file));
|
||||||
|
|
||||||
File::removeDirectory($directory);
|
File::removeDirectory($directory);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
File diff suppressed because one or more lines are too long
|
@ -2,108 +2,107 @@
|
||||||
|
|
||||||
class HTMLTest extends PHPUnit_Framework_TestCase
|
class HTMLTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
private $html;
|
private $html;
|
||||||
|
|
||||||
public function setUp()
|
public function setUp()
|
||||||
{
|
{
|
||||||
$this->html = HTML::getInstance();
|
$this->html = HTML::getInstance();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testGetInstance()
|
public function testGetInstance()
|
||||||
{
|
{
|
||||||
$this->assertInstanceOf('HTML', $this->html);
|
$this->assertInstanceOf('HTML', $this->html);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testInput()
|
public function testInput()
|
||||||
{
|
{
|
||||||
$this->assertEquals('<input type="text">', $this->html->input());
|
$this->assertEquals('<input type="text">', $this->html->input());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testInputDateTimeLocal()
|
public function testInputDateTimeLocal()
|
||||||
{
|
{
|
||||||
$this->assertEquals('<input type="datetime-local">', $this->html->inputDateTimeLocal());
|
$this->assertEquals('<input type="datetime-local">', $this->html->inputDateTimeLocal());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testInputEmail()
|
public function testInputEmail()
|
||||||
{
|
{
|
||||||
$this->assertEquals('<input type="email">', $this->html->inputEmail());
|
$this->assertEquals('<input type="email">', $this->html->inputEmail());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testInputWithAttributes()
|
public function testInputWithAttributes()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'<input id="id" class="class" value="value" type="text">',
|
'<input id="id" class="class" value="value" type="text">',
|
||||||
$this->html->input([
|
$this->html->input([
|
||||||
'id' => 'id',
|
'id' => 'id',
|
||||||
'class' => 'class',
|
'class' => 'class',
|
||||||
'value' => 'value',
|
'value' => 'value',
|
||||||
])
|
])
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testInputPasswordWithLabel()
|
public function testInputPasswordWithLabel()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'<label for="password">Enter Password</label><input name="password" type="password">',
|
'<label for="password">Enter Password</label><input name="password" type="password">',
|
||||||
$this->html->inputPassword([
|
$this->html->inputPassword([
|
||||||
'name' => 'password',
|
'name' => 'password',
|
||||||
'label' => 'Enter Password',
|
'label' => 'Enter Password',
|
||||||
])
|
])
|
||||||
);
|
);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testNestedElements()
|
public function testNestedElements()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'<div><p>Nested!</p></div>',
|
'<div><p>Nested!</p></div>',
|
||||||
$this->html->div(
|
$this->html->div(
|
||||||
$this->html->p('Nested!')
|
$this->html->p('Nested!')
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testNestedElementsWithAttributes()
|
public function testNestedElementsWithAttributes()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'<div class="outer"><p class="inner">Nested!</p></div>',
|
'<div class="outer"><p class="inner">Nested!</p></div>',
|
||||||
$this->html->div(
|
$this->html->div(
|
||||||
['class' => 'outer'],
|
['class' => 'outer'],
|
||||||
$this->html->p(
|
$this->html->p(
|
||||||
['class' => 'inner'],
|
['class' => 'inner'],
|
||||||
'Nested!'
|
'Nested!'
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testClosingTag()
|
public function testClosingTag()
|
||||||
{
|
{
|
||||||
$this->assertEquals('<textarea></textarea>', $this->html->textarea());
|
$this->assertEquals('<textarea></textarea>', $this->html->textarea());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testElement()
|
public function testElement()
|
||||||
{
|
{
|
||||||
$this->assertEquals('<div></div>', $this->html->element('div'));
|
$this->assertEquals('<div></div>', $this->html->element('div'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testReversedParameters()
|
public function testReversedParameters()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'<div class="fancy">string</div>',
|
'<div class="fancy">string</div>',
|
||||||
$this->html->div('string', ['class' => 'fancy'])
|
$this->html->div('string', ['class' => 'fancy'])
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLabelWithInputWithoutName()
|
public function testLabelWithInputWithoutName()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'<label>Label</label><input type="text">',
|
'<label>Label</label><input type="text">',
|
||||||
$this->html->input([
|
$this->html->input([
|
||||||
'label' => 'Label',
|
'label' => 'Label',
|
||||||
])
|
])
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,102 +2,101 @@
|
||||||
|
|
||||||
class LogTest extends PHPUnit_Framework_TestCase
|
class LogTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
private $config;
|
private $config;
|
||||||
|
|
||||||
public function setUp()
|
public function setUp()
|
||||||
{
|
{
|
||||||
$this->config = Config::getInstance();
|
$this->config = Config::getInstance();
|
||||||
$this->config->data['pickles']['logging'] = true;
|
$this->config->data['pickles']['logging'] = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function tearDownAfterClass()
|
public static function tearDownAfterClass()
|
||||||
{
|
{
|
||||||
File::removeDirectory(LOG_PATH);
|
File::removeDirectory(LOG_PATH);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testInformation()
|
public function testInformation()
|
||||||
{
|
{
|
||||||
Log::information('information');
|
Log::information('information');
|
||||||
|
|
||||||
$file = LOG_PATH . date('Y/m/d/') . 'information.log';
|
$file = LOG_PATH . date('Y/m/d/') . 'information.log';
|
||||||
$data = file($file);
|
$data = file($file);
|
||||||
$line = $data[count($data) - 1];
|
$line = $data[count($data) - 1];
|
||||||
|
|
||||||
$this->assertRegExp('/^\d{2}:\d{2}:\d{2} .+ information$/', $line);
|
$this->assertRegExp('/^\d{2}:\d{2}:\d{2} .+ information$/', $line);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testWarning()
|
public function testWarning()
|
||||||
{
|
{
|
||||||
Log::warning('warning');
|
Log::warning('warning');
|
||||||
|
|
||||||
$file = LOG_PATH . date('Y/m/d/') . 'warning.log';
|
$file = LOG_PATH . date('Y/m/d/') . 'warning.log';
|
||||||
$data = file($file);
|
$data = file($file);
|
||||||
$line = $data[count($data) - 1];
|
$line = $data[count($data) - 1];
|
||||||
|
|
||||||
$this->assertRegExp('/^\d{2}:\d{2}:\d{2} .+ warning$/', $line);
|
$this->assertRegExp('/^\d{2}:\d{2}:\d{2} .+ warning$/', $line);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testError()
|
public function testError()
|
||||||
{
|
{
|
||||||
Log::error('error');
|
Log::error('error');
|
||||||
|
|
||||||
$file = LOG_PATH . date('Y/m/d/') . 'error.log';
|
$file = LOG_PATH . date('Y/m/d/') . 'error.log';
|
||||||
$data = file($file);
|
$data = file($file);
|
||||||
$line = $data[count($data) - 1];
|
$line = $data[count($data) - 1];
|
||||||
|
|
||||||
$this->assertRegExp('/^\d{2}:\d{2}:\d{2} .+ error$/', $line);
|
$this->assertRegExp('/^\d{2}:\d{2}:\d{2} .+ error$/', $line);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSlowQuery()
|
public function testSlowQuery()
|
||||||
{
|
{
|
||||||
Log::slowQuery('slow query');
|
Log::slowQuery('slow query');
|
||||||
|
|
||||||
$file = LOG_PATH . date('Y/m/d/') . 'slow_query.log';
|
$file = LOG_PATH . date('Y/m/d/') . 'slow_query.log';
|
||||||
$data = file($file);
|
$data = file($file);
|
||||||
$line = $data[count($data) - 1];
|
$line = $data[count($data) - 1];
|
||||||
|
|
||||||
$this->assertRegExp('/^\d{2}:\d{2}:\d{2} .+ slow query$/', $line);
|
$this->assertRegExp('/^\d{2}:\d{2}:\d{2} .+ slow query$/', $line);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testTransaction()
|
public function testTransaction()
|
||||||
{
|
{
|
||||||
Log::transaction('transaction');
|
Log::transaction('transaction');
|
||||||
|
|
||||||
$file = LOG_PATH . date('Y/m/d/') . 'transaction.log';
|
$file = LOG_PATH . date('Y/m/d/') . 'transaction.log';
|
||||||
$data = file($file);
|
$data = file($file);
|
||||||
$line = $data[count($data) - 1];
|
$line = $data[count($data) - 1];
|
||||||
|
|
||||||
$this->assertRegExp('/^\d{2}:\d{2}:\d{2} .+ transaction$/', $line);
|
$this->assertRegExp('/^\d{2}:\d{2}:\d{2} .+ transaction$/', $line);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testPHPError()
|
public function testPHPError()
|
||||||
{
|
{
|
||||||
Log::phperror('php error');
|
Log::phperror('php error');
|
||||||
|
|
||||||
$file = LOG_PATH . date('Y/m/d/') . 'php_error.log';
|
$file = LOG_PATH . date('Y/m/d/') . 'php_error.log';
|
||||||
$data = file($file);
|
$data = file($file);
|
||||||
$line = $data[count($data) - 1];
|
$line = $data[count($data) - 1];
|
||||||
|
|
||||||
$this->assertRegExp('/^php error$/', $line);
|
$this->assertRegExp('/^php error$/', $line);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testQuery()
|
public function testQuery()
|
||||||
{
|
{
|
||||||
Log::query('query');
|
Log::query('query');
|
||||||
|
|
||||||
$file = LOG_PATH . date('Y/m/d/') . 'query.log';
|
$file = LOG_PATH . date('Y/m/d/') . 'query.log';
|
||||||
$data = file($file);
|
$data = file($file);
|
||||||
$line = $data[count($data) - 1];
|
$line = $data[count($data) - 1];
|
||||||
|
|
||||||
$this->assertRegExp('/^\d{2}:\d{2}:\d{2} .+ query$/', $line);
|
$this->assertRegExp('/^\d{2}:\d{2}:\d{2} .+ query$/', $line);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLoggingDisabled()
|
public function testLoggingDisabled()
|
||||||
{
|
{
|
||||||
$this->config->data['pickles']['logging'] = false;
|
$this->config->data['pickles']['logging'] = false;
|
||||||
|
|
||||||
$this->assertFalse(Log::error('should return false'));
|
$this->assertFalse(Log::error('should return false'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -6,65 +6,64 @@ $_REQUEST['field2'] = 'short';
|
||||||
|
|
||||||
class MockParentModule extends Module
|
class MockParentModule extends Module
|
||||||
{
|
{
|
||||||
public $validate = [
|
public $validate = [
|
||||||
'field1',
|
'field1',
|
||||||
'field2' => [
|
'field2' => [
|
||||||
'length:<:10' => 'Too short',
|
'length:<:10' => 'Too short',
|
||||||
'length:>:50' => 'Too long',
|
'length:>:50' => 'Too long',
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
class MockChildModule extends MockParentModule
|
class MockChildModule extends MockParentModule
|
||||||
{
|
{
|
||||||
public $method = ['POST', 'GET'];
|
public $method = ['POST', 'GET'];
|
||||||
}
|
}
|
||||||
|
|
||||||
class ModuleTest extends PHPUnit_Framework_TestCase
|
class ModuleTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
public function testAutoRun()
|
public function testAutoRun()
|
||||||
{
|
{
|
||||||
$this->assertInstanceOf('Module', new Module(true));
|
$this->assertInstanceOf('Module', new Module(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAutoRunParentError()
|
public function testAutoRunParentError()
|
||||||
{
|
{
|
||||||
$this->expectOutputString('');
|
$this->expectOutputString('');
|
||||||
$model = new MockChildModule(true);
|
$model = new MockChildModule(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSetGetReturn()
|
public function testSetGetReturn()
|
||||||
{
|
{
|
||||||
$module = new Module();
|
$module = new Module();
|
||||||
$module->foo = 'bar';
|
$module->foo = 'bar';
|
||||||
$this->assertEquals('bar', $module->foo);
|
$this->assertEquals('bar', $module->foo);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testGetMissing()
|
public function testGetMissing()
|
||||||
{
|
{
|
||||||
$module = new Module();
|
$module = new Module();
|
||||||
$this->assertFalse($module->missing);
|
$this->assertFalse($module->missing);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testValidateGet()
|
public function testValidateGet()
|
||||||
{
|
{
|
||||||
$module = new MockParentModule();
|
$module = new MockParentModule();
|
||||||
$module->method = 'GET';
|
$module->method = 'GET';
|
||||||
$this->assertEquals(['The field1 field is required.', 'Too long'], $module->__validate());
|
$this->assertEquals(['The field1 field is required.', 'Too long'], $module->__validate());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testValidatePost()
|
public function testValidatePost()
|
||||||
{
|
{
|
||||||
$module = new MockParentModule();
|
$module = new MockParentModule();
|
||||||
$this->assertEquals(['The field1 field is required.', 'Too long'], $module->__validate());
|
$this->assertEquals(['The field1 field is required.', 'Too long'], $module->__validate());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testValidateRequest()
|
public function testValidateRequest()
|
||||||
{
|
{
|
||||||
$module = new MockParentModule();
|
$module = new MockParentModule();
|
||||||
$module->method = null;
|
$module->method = null;
|
||||||
$this->assertEquals(['The field1 field is required.', 'Too long'], $module->__validate());
|
$this->assertEquals(['The field1 field is required.', 'Too long'], $module->__validate());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,49 +2,48 @@
|
||||||
|
|
||||||
class NumberTest extends PHPUnit_Framework_TestCase
|
class NumberTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @dataProvider providerOrginalIndicatorNoSuper
|
* @dataProvider providerOrginalIndicatorNoSuper
|
||||||
*/
|
*/
|
||||||
public function testOrdinalIndicatorNoSuper($a, $b)
|
public function testOrdinalIndicatorNoSuper($a, $b)
|
||||||
{
|
{
|
||||||
$this->assertEquals($b, Number::ordinalIndicator($a));
|
$this->assertEquals($b, Number::ordinalIndicator($a));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function providerOrginalIndicatorNoSuper()
|
public function providerOrginalIndicatorNoSuper()
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
[1, '1st'],
|
[1, '1st'],
|
||||||
[2, '2nd'],
|
[2, '2nd'],
|
||||||
[3, '3rd'],
|
[3, '3rd'],
|
||||||
[4, '4th'],
|
[4, '4th'],
|
||||||
[51, '51st'],
|
[51, '51st'],
|
||||||
[52, '52nd'],
|
[52, '52nd'],
|
||||||
[53, '53rd'],
|
[53, '53rd'],
|
||||||
[54, '54th'],
|
[54, '54th'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @dataProvider providerOrginalIndicatorSuper
|
* @dataProvider providerOrginalIndicatorSuper
|
||||||
*/
|
*/
|
||||||
public function testOrdinalIndicatorSuper($a, $b)
|
public function testOrdinalIndicatorSuper($a, $b)
|
||||||
{
|
{
|
||||||
$this->assertEquals($b, Number::ordinalIndicator($a, true));
|
$this->assertEquals($b, Number::ordinalIndicator($a, true));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function providerOrginalIndicatorSuper()
|
public function providerOrginalIndicatorSuper()
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
[1, '1<sup>st</sup>'],
|
[1, '1<sup>st</sup>'],
|
||||||
[2, '2<sup>nd</sup>'],
|
[2, '2<sup>nd</sup>'],
|
||||||
[3, '3<sup>rd</sup>'],
|
[3, '3<sup>rd</sup>'],
|
||||||
[4, '4<sup>th</sup>'],
|
[4, '4<sup>th</sup>'],
|
||||||
[51, '51<sup>st</sup>'],
|
[51, '51<sup>st</sup>'],
|
||||||
[52, '52<sup>nd</sup>'],
|
[52, '52<sup>nd</sup>'],
|
||||||
[53, '53<sup>rd</sup>'],
|
[53, '53<sup>rd</sup>'],
|
||||||
[54, '54<sup>th</sup>'],
|
[54, '54<sup>th</sup>'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,24 +2,23 @@
|
||||||
|
|
||||||
class ObjectTest extends PHPUnit_Framework_TestCase
|
class ObjectTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
public function testConstructorWithoutObjects()
|
public function testConstructorWithoutObjects()
|
||||||
{
|
{
|
||||||
$object = new Object();
|
$object = new Object();
|
||||||
|
|
||||||
$this->assertInstanceOf('Config', PHPUnit_Framework_Assert::readAttribute($object, 'config'));
|
$this->assertInstanceOf('Config', PHPUnit_Framework_Assert::readAttribute($object, 'config'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testConstructorWithObjects()
|
public function testConstructorWithObjects()
|
||||||
{
|
{
|
||||||
$object = new Object('cache');
|
$object = new Object('cache');
|
||||||
|
|
||||||
$this->assertInstanceOf('Cache', PHPUnit_Framework_Assert::readAttribute($object, 'cache'));
|
$this->assertInstanceOf('Cache', PHPUnit_Framework_Assert::readAttribute($object, 'cache'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testGetInstanceWithoutClass()
|
public function testGetInstanceWithoutClass()
|
||||||
{
|
{
|
||||||
$this->assertFalse(Object::getInstance());
|
$this->assertFalse(Object::getInstance());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,81 +2,80 @@
|
||||||
|
|
||||||
class ProfilerTest extends PHPUnit_Framework_TestCase
|
class ProfilerTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
public function testReport()
|
public function testReport()
|
||||||
{
|
{
|
||||||
$this->expectOutputRegex('//');
|
$this->expectOutputRegex('//');
|
||||||
|
|
||||||
Profiler::report();
|
Profiler::report();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testDisabledType()
|
public function testDisabledType()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['profiler'] = false;
|
$config->data['pickles']['profiler'] = false;
|
||||||
|
|
||||||
$this->assertFalse(Profiler::enabled('timers'));
|
$this->assertFalse(Profiler::enabled('timers'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testTimerDisabled()
|
public function testTimerDisabled()
|
||||||
{
|
{
|
||||||
$this->assertFalse(Profiler::timer('disabled'));
|
$this->assertFalse(Profiler::timer('disabled'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testReportNothing()
|
public function testReportNothing()
|
||||||
{
|
{
|
||||||
$this->expectOutputRegex('/There is nothing to profile/');
|
$this->expectOutputRegex('/There is nothing to profile/');
|
||||||
|
|
||||||
Profiler::report();
|
Profiler::report();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testEnabled()
|
public function testEnabled()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['profiler'] = true;
|
$config->data['pickles']['profiler'] = true;
|
||||||
|
|
||||||
$this->assertTrue(Profiler::enabled());
|
$this->assertTrue(Profiler::enabled());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testEnabledType()
|
public function testEnabledType()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['profiler'] = 'timers';
|
$config->data['pickles']['profiler'] = 'timers';
|
||||||
|
|
||||||
$this->assertTrue(Profiler::enabled('timers'));
|
$this->assertTrue(Profiler::enabled('timers'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLogAndTimer()
|
public function testLogAndTimer()
|
||||||
{
|
{
|
||||||
Profiler::log('timer', 'timer-one');
|
Profiler::log('timer', 'timer-one');
|
||||||
Profiler::log(['foo' => 'bar']);
|
Profiler::log(['foo' => 'bar']);
|
||||||
Profiler::log(new Object);
|
Profiler::log(new Object);
|
||||||
Profiler::log('string');
|
Profiler::log('string');
|
||||||
Profiler::log(3.14, 'method', true);
|
Profiler::log(3.14, 'method', true);
|
||||||
Profiler::log('timer', 'timer-one');
|
Profiler::log('timer', 'timer-one');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLogQuery()
|
public function testLogQuery()
|
||||||
{
|
{
|
||||||
$explain = [
|
$explain = [
|
||||||
[
|
[
|
||||||
'key' => '',
|
'key' => '',
|
||||||
'possible_keys' => '',
|
'possible_keys' => '',
|
||||||
'type' => '',
|
'type' => '',
|
||||||
'rows' => '',
|
'rows' => '',
|
||||||
'Extra' => '',
|
'Extra' => '',
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
|
|
||||||
Profiler::logQuery('SELECT * FROM table;');
|
Profiler::logQuery('SELECT * FROM table;');
|
||||||
Profiler::logQuery('SELECT * FROM table WHERE column = ?;', ['foo']);
|
Profiler::logQuery('SELECT * FROM table WHERE column = ?;', ['foo']);
|
||||||
Profiler::logQuery('SELECT * FROM table;', false, $explain);
|
Profiler::logQuery('SELECT * FROM table;', false, $explain);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testTimer()
|
public function testTimer()
|
||||||
{
|
{
|
||||||
Profiler::timer('timer-two');
|
Profiler::timer('timer-two');
|
||||||
Profiler::timer('timer-two');
|
Profiler::timer('timer-two');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,153 +2,152 @@
|
||||||
|
|
||||||
class MockUserModel extends Model
|
class MockUserModel extends Model
|
||||||
{
|
{
|
||||||
public $table = 'users';
|
public $table = 'users';
|
||||||
}
|
}
|
||||||
|
|
||||||
class SecurityTest extends PHPUnit_Framework_TestCase
|
class SecurityTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
public function testGenerateHashWithDefaultSalts()
|
public function testGenerateHashWithDefaultSalts()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'4940e793006aa897db22751bba80dff4cb6a3e08',
|
'4940e793006aa897db22751bba80dff4cb6a3e08',
|
||||||
Security::generateHash('source')
|
Security::generateHash('source')
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testGenerateHashWithCustomSalts()
|
public function testGenerateHashWithCustomSalts()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['security']['salt'] = 'salt';
|
$config->data['security']['salt'] = 'salt';
|
||||||
|
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'4eac88c934c33cfa9a80c0b2eb322f23ac3b13c5',
|
'4eac88c934c33cfa9a80c0b2eb322f23ac3b13c5',
|
||||||
Security::generateHash('source')
|
Security::generateHash('source')
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testGenerateSHA256Hash()
|
public function testGenerateSHA256Hash()
|
||||||
{
|
{
|
||||||
$this->assertEquals(
|
$this->assertEquals(
|
||||||
'3d04f805aff4838ecaf98c7260a813fffd2b7a8a7f957add8018908a1bbdad04',
|
'3d04f805aff4838ecaf98c7260a813fffd2b7a8a7f957add8018908a1bbdad04',
|
||||||
Security::generateSHA256Hash('source', 'salt')
|
Security::generateSHA256Hash('source', 'salt')
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLogin()
|
public function testLogin()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Security::login(1, 10, 'USER'));
|
$this->assertTrue(Security::login(1, 10, 'USER'));
|
||||||
$this->assertTrue(isset($_SESSION['__pickles']['security']));
|
$this->assertTrue(isset($_SESSION['__pickles']['security']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLoginNoSession()
|
public function testLoginNoSession()
|
||||||
{
|
{
|
||||||
session_destroy();
|
session_destroy();
|
||||||
$this->assertFalse(Security::login(1, 10, 'USER'));
|
$this->assertFalse(Security::login(1, 10, 'USER'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLogout()
|
public function testLogout()
|
||||||
{
|
{
|
||||||
session_start();
|
session_start();
|
||||||
Security::login(1, 10, 'USER');
|
Security::login(1, 10, 'USER');
|
||||||
|
|
||||||
$this->assertTrue(Security::logout());
|
$this->assertTrue(Security::logout());
|
||||||
$this->assertFalse(isset($_SESSION['__pickles']['security']));
|
$this->assertFalse(isset($_SESSION['__pickles']['security']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testIsLevel()
|
public function testIsLevel()
|
||||||
{
|
{
|
||||||
Security::login(1, 10, 'USER');
|
Security::login(1, 10, 'USER');
|
||||||
|
|
||||||
$this->assertTrue(Security::isLevel(SECURITY_LEVEL_USER));
|
$this->assertTrue(Security::isLevel(SECURITY_LEVEL_USER));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testIsLevelArray()
|
public function testIsLevelArray()
|
||||||
{
|
{
|
||||||
Security::login(1, 10, 'USER');
|
Security::login(1, 10, 'USER');
|
||||||
|
|
||||||
$this->assertTrue(Security::isLevel([SECURITY_LEVEL_USER, SECURITY_LEVEL_ADMIN]));
|
$this->assertTrue(Security::isLevel([SECURITY_LEVEL_USER, SECURITY_LEVEL_ADMIN]));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testHasLevel()
|
public function testHasLevel()
|
||||||
{
|
{
|
||||||
Security::login(1, 10, 'USER');
|
Security::login(1, 10, 'USER');
|
||||||
|
|
||||||
$this->assertTrue(Security::hasLevel(SECURITY_LEVEL_USER));
|
$this->assertTrue(Security::hasLevel(SECURITY_LEVEL_USER));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testHasLevelArray()
|
public function testHasLevelArray()
|
||||||
{
|
{
|
||||||
Security::login(1, 10, 'USER');
|
Security::login(1, 10, 'USER');
|
||||||
|
|
||||||
$this->assertTrue(Security::hasLevel([SECURITY_LEVEL_USER, SECURITY_LEVEL_ADMIN]));
|
$this->assertTrue(Security::hasLevel([SECURITY_LEVEL_USER, SECURITY_LEVEL_ADMIN]));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testBetweenLevel()
|
public function testBetweenLevel()
|
||||||
{
|
{
|
||||||
Security::login(1, 10, 'USER');
|
Security::login(1, 10, 'USER');
|
||||||
|
|
||||||
$this->assertTrue(Security::betweenLevel(SECURITY_LEVEL_USER, SECURITY_LEVEL_ADMIN));
|
$this->assertTrue(Security::betweenLevel(SECURITY_LEVEL_USER, SECURITY_LEVEL_ADMIN));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testTokenMismatch()
|
public function testTokenMismatch()
|
||||||
{
|
{
|
||||||
Security::login(1, 10, 'USER');
|
Security::login(1, 10, 'USER');
|
||||||
|
|
||||||
$_SESSION['__pickles']['security']['token'] = 'foo';
|
$_SESSION['__pickles']['security']['token'] = 'foo';
|
||||||
$_COOKIE['pickles_security_token'] = 'bar';
|
$_COOKIE['pickles_security_token'] = 'bar';
|
||||||
|
|
||||||
$this->assertFalse(Security::isLevel(SECURITY_LEVEL_USER));
|
$this->assertFalse(Security::isLevel(SECURITY_LEVEL_USER));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testIsLevelDB()
|
public function testIsLevelDB()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
|
|
||||||
$config->data = [
|
$config->data = [
|
||||||
'pickles' => [
|
'pickles' => [
|
||||||
'datasource' => 'mysql',
|
'datasource' => 'mysql',
|
||||||
'cache' => 'memcache',
|
'cache' => 'memcache',
|
||||||
],
|
],
|
||||||
'datasources' => [
|
'datasources' => [
|
||||||
'mysql' => [
|
'mysql' => [
|
||||||
'type' => 'mysql',
|
'type' => 'mysql',
|
||||||
'driver' => 'pdo_mysql',
|
'driver' => 'pdo_mysql',
|
||||||
'hostname' => 'localhost',
|
'hostname' => 'localhost',
|
||||||
'username' => '',
|
'username' => '',
|
||||||
'password' => '',
|
'password' => '',
|
||||||
'database' => 'test',
|
'database' => 'test',
|
||||||
'cache' => true,
|
'cache' => true,
|
||||||
],
|
],
|
||||||
'memcache' => [
|
'memcache' => [
|
||||||
'type' => 'memcache',
|
'type' => 'memcache',
|
||||||
'hostname' => 'localhost',
|
'hostname' => 'localhost',
|
||||||
'port' => 11211,
|
'port' => 11211,
|
||||||
'namespace' => '',
|
'namespace' => '',
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
'security' => ['model' => 'MockUserModel'],
|
'security' => ['model' => 'MockUserModel'],
|
||||||
];
|
];
|
||||||
|
|
||||||
$model = new MockUserModel();
|
$model = new MockUserModel();
|
||||||
$model->record['username'] = 'pickles';
|
$model->record['username'] = 'pickles';
|
||||||
$model->commit();
|
$model->commit();
|
||||||
|
|
||||||
setUpConfig([
|
setUpConfig([
|
||||||
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
new Config();
|
new Config();
|
||||||
|
|
||||||
Security::login(1, 10, 'USER');
|
Security::login(1, 10, 'USER');
|
||||||
|
|
||||||
unset(
|
unset(
|
||||||
$_SESSION['__pickles']['security']['token'],
|
$_SESSION['__pickles']['security']['token'],
|
||||||
$_COOKIE['pickles_security_token'],
|
$_COOKIE['pickles_security_token'],
|
||||||
$_SESSION['__pickles']['security']['level']
|
$_SESSION['__pickles']['security']['level']
|
||||||
);
|
);
|
||||||
|
|
||||||
$this->assertFalse(Security::isLevel([SECURITY_LEVEL_USER, SECURITY_LEVEL_ADMIN]));
|
$this->assertFalse(Security::isLevel([SECURITY_LEVEL_USER, SECURITY_LEVEL_ADMIN]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,98 +2,97 @@
|
||||||
|
|
||||||
class SessionTest extends PHPUnit_Framework_TestCase
|
class SessionTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
public function setUp()
|
public function setUp()
|
||||||
{
|
{
|
||||||
if (session_id())
|
if (session_id())
|
||||||
{
|
{
|
||||||
session_destroy();
|
session_destroy();
|
||||||
}
|
}
|
||||||
|
|
||||||
$_SERVER['HTTP_USER_AGENT'] = 'yes';
|
$_SERVER['HTTP_USER_AGENT'] = 'yes';
|
||||||
$_SERVER['REQUEST_METHOD'] = 'GET';
|
$_SERVER['REQUEST_METHOD'] = 'GET';
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFiles()
|
public function testFiles()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['sessions'] = 'files';
|
$config->data['pickles']['sessions'] = 'files';
|
||||||
|
|
||||||
new Session();
|
new Session();
|
||||||
|
|
||||||
$_SESSION['test'] = 'files';
|
$_SESSION['test'] = 'files';
|
||||||
$this->assertEquals('files', $_SESSION['test']);
|
$this->assertEquals('files', $_SESSION['test']);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testMemcache()
|
public function testMemcache()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['sessions'] = 'memcache';
|
$config->data['pickles']['sessions'] = 'memcache';
|
||||||
$config->data['datasources']['memcache'] = [
|
$config->data['datasources']['memcache'] = [
|
||||||
'type' => 'memcache',
|
'type' => 'memcache',
|
||||||
'hostname' => 'localhost',
|
'hostname' => 'localhost',
|
||||||
'port' => '11211',
|
'port' => '11211',
|
||||||
];
|
];
|
||||||
|
|
||||||
new Session();
|
new Session();
|
||||||
|
|
||||||
$_SESSION['test'] = 'memcache';
|
$_SESSION['test'] = 'memcache';
|
||||||
$this->assertEquals('memcache', $_SESSION['test']);
|
$this->assertEquals('memcache', $_SESSION['test']);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testMemcached()
|
public function testMemcached()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['sessions'] = 'memcached';
|
$config->data['pickles']['sessions'] = 'memcached';
|
||||||
$config->data['datasources']['memcached'] = [
|
$config->data['datasources']['memcached'] = [
|
||||||
'type' => 'memcached',
|
'type' => 'memcached',
|
||||||
'hostname' => 'localhost',
|
'hostname' => 'localhost',
|
||||||
'port' => '11211',
|
'port' => '11211',
|
||||||
];
|
];
|
||||||
|
|
||||||
new Session();
|
new Session();
|
||||||
|
|
||||||
$_SESSION['test'] = 'memcached';
|
$_SESSION['test'] = 'memcached';
|
||||||
$this->assertEquals('memcached', $_SESSION['test']);
|
$this->assertEquals('memcached', $_SESSION['test']);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRedis()
|
public function testRedis()
|
||||||
{
|
{
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['sessions'] = 'redis';
|
$config->data['pickles']['sessions'] = 'redis';
|
||||||
$config->data['datasources']['redis'] = [
|
$config->data['datasources']['redis'] = [
|
||||||
'type' => 'redis',
|
'type' => 'redis',
|
||||||
'hostname' => 'localhost',
|
'hostname' => 'localhost',
|
||||||
'port' => '6379',
|
'port' => '6379',
|
||||||
'database' => '1',
|
'database' => '1',
|
||||||
'prefix' => 'p:',
|
'prefix' => 'p:',
|
||||||
];
|
];
|
||||||
|
|
||||||
new Session();
|
new Session();
|
||||||
|
|
||||||
$_SESSION['test'] = 'redis';
|
$_SESSION['test'] = 'redis';
|
||||||
$this->assertEquals('redis', $_SESSION['test']);
|
$this->assertEquals('redis', $_SESSION['test']);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage You must provide both the hostname and port for the datasource.
|
* @expectedExceptionMessage You must provide both the hostname and port for the datasource.
|
||||||
*/
|
*/
|
||||||
public function testMissingHostname()
|
public function testMissingHostname()
|
||||||
{
|
{
|
||||||
$_SERVER['REQUEST_METHOD'] = 'GET';
|
$_SERVER['REQUEST_METHOD'] = 'GET';
|
||||||
|
|
||||||
$config = Config::getInstance();
|
$config = Config::getInstance();
|
||||||
$config->data['pickles']['sessions'] = 'redis';
|
$config->data['pickles']['sessions'] = 'redis';
|
||||||
$config->data['datasources']['redis'] = [
|
$config->data['datasources']['redis'] = [
|
||||||
'type' => 'redis',
|
'type' => 'redis',
|
||||||
'port' => '6379',
|
'port' => '6379',
|
||||||
];
|
];
|
||||||
|
|
||||||
new Session();
|
new Session();
|
||||||
|
|
||||||
$_SESSION['test'] = 'redis';
|
$_SESSION['test'] = 'redis';
|
||||||
$this->assertEquals('redis', $_SESSION['test']);
|
$this->assertEquals('redis', $_SESSION['test']);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,61 +2,60 @@
|
||||||
|
|
||||||
class SortTest extends PHPUnit_Framework_TestCase
|
class SortTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
public function testByNameASC()
|
public function testByNameASC()
|
||||||
{
|
{
|
||||||
$shuffled = [
|
$shuffled = [
|
||||||
['name' => 'epsilon'],
|
['name' => 'epsilon'],
|
||||||
['name' => 'gamma'],
|
['name' => 'gamma'],
|
||||||
['name' => 'alpha'],
|
['name' => 'alpha'],
|
||||||
['name' => 'delta'],
|
['name' => 'delta'],
|
||||||
['name' => 'beta'],
|
['name' => 'beta'],
|
||||||
];
|
];
|
||||||
|
|
||||||
$sorted = [
|
$sorted = [
|
||||||
['name' => 'alpha'],
|
['name' => 'alpha'],
|
||||||
['name' => 'beta'],
|
['name' => 'beta'],
|
||||||
['name' => 'delta'],
|
['name' => 'delta'],
|
||||||
['name' => 'epsilon'],
|
['name' => 'epsilon'],
|
||||||
['name' => 'gamma'],
|
['name' => 'gamma'],
|
||||||
];
|
];
|
||||||
|
|
||||||
Sort::by('name', $shuffled);
|
Sort::by('name', $shuffled);
|
||||||
|
|
||||||
$this->assertEquals($sorted, $shuffled);
|
$this->assertEquals($sorted, $shuffled);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testByNameDESC()
|
public function testByNameDESC()
|
||||||
{
|
{
|
||||||
$shuffled = [
|
$shuffled = [
|
||||||
['name' => 'epsilon'],
|
['name' => 'epsilon'],
|
||||||
['name' => 'gamma'],
|
['name' => 'gamma'],
|
||||||
['name' => 'alpha'],
|
['name' => 'alpha'],
|
||||||
['name' => 'delta'],
|
['name' => 'delta'],
|
||||||
['name' => 'beta'],
|
['name' => 'beta'],
|
||||||
];
|
];
|
||||||
|
|
||||||
$sorted = [
|
$sorted = [
|
||||||
['name' => 'gamma'],
|
['name' => 'gamma'],
|
||||||
['name' => 'epsilon'],
|
['name' => 'epsilon'],
|
||||||
['name' => 'delta'],
|
['name' => 'delta'],
|
||||||
['name' => 'beta'],
|
['name' => 'beta'],
|
||||||
['name' => 'alpha'],
|
['name' => 'alpha'],
|
||||||
];
|
];
|
||||||
|
|
||||||
Sort::by('name', $shuffled, Sort::DESC);
|
Sort::by('name', $shuffled, Sort::DESC);
|
||||||
|
|
||||||
$this->assertEquals($sorted, $shuffled);
|
$this->assertEquals($sorted, $shuffled);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testMissingField()
|
public function testMissingField()
|
||||||
{
|
{
|
||||||
$shuffled = [['foo' => 'bar', 'bar' => 'foo']];
|
$shuffled = [['foo' => 'bar', 'bar' => 'foo']];
|
||||||
$sorted = [['foo' => 'bar', 'bar' => 'foo']];
|
$sorted = [['foo' => 'bar', 'bar' => 'foo']];
|
||||||
|
|
||||||
Sort::by('name', $shuffled);
|
Sort::by('name', $shuffled);
|
||||||
|
|
||||||
$this->assertEquals($sorted, $shuffled);
|
$this->assertEquals($sorted, $shuffled);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,141 +2,140 @@
|
||||||
|
|
||||||
class StringTest extends PHPUnit_Framework_TestCase
|
class StringTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @dataProvider providerFormatPhoneNumber
|
* @dataProvider providerFormatPhoneNumber
|
||||||
*/
|
*/
|
||||||
public function testFormatPhoneNumber($a, $b)
|
public function testFormatPhoneNumber($a, $b)
|
||||||
{
|
{
|
||||||
$this->assertEquals(String::formatPhoneNumber($a), $b);
|
$this->assertEquals(String::formatPhoneNumber($a), $b);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function providerFormatPhoneNumber()
|
public function providerFormatPhoneNumber()
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
['1234567890', '123-456-7890'],
|
['1234567890', '123-456-7890'],
|
||||||
['123 456 7890', '123-456-7890'],
|
['123 456 7890', '123-456-7890'],
|
||||||
['123.456.7890', '123-456-7890'],
|
['123.456.7890', '123-456-7890'],
|
||||||
['123_456_7890', '123-456-7890'],
|
['123_456_7890', '123-456-7890'],
|
||||||
['1234567890', '123-456-7890'],
|
['1234567890', '123-456-7890'],
|
||||||
['1234-56-7890', '123-456-7890'],
|
['1234-56-7890', '123-456-7890'],
|
||||||
['(123) 456-7890', '123-456-7890'],
|
['(123) 456-7890', '123-456-7890'],
|
||||||
['1234567890 x1000', '123-456-7890x1000'],
|
['1234567890 x1000', '123-456-7890x1000'],
|
||||||
['(123) 456-7890_x10.00', '123-456-7890x1000'],
|
['(123) 456-7890_x10.00', '123-456-7890x1000'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @dataProvider providerGenerateGravatarHash
|
* @dataProvider providerGenerateGravatarHash
|
||||||
*/
|
*/
|
||||||
public function testGenerateGravatarHash($a, $b)
|
public function testGenerateGravatarHash($a, $b)
|
||||||
{
|
{
|
||||||
$this->assertEquals(String::generateGravatarHash($a), $b);
|
$this->assertEquals(String::generateGravatarHash($a), $b);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function providerGenerateGravatarHash()
|
public function providerGenerateGravatarHash()
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
['foo@bar.com', 'f3ada405ce890b6f8204094deb12d8a8'],
|
['foo@bar.com', 'f3ada405ce890b6f8204094deb12d8a8'],
|
||||||
['FOO@BAR.COM', 'f3ada405ce890b6f8204094deb12d8a8'],
|
['FOO@BAR.COM', 'f3ada405ce890b6f8204094deb12d8a8'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testIsEmpty()
|
public function testIsEmpty()
|
||||||
{
|
{
|
||||||
$this->assertTrue(String::isEmpty(''));
|
$this->assertTrue(String::isEmpty(''));
|
||||||
$this->assertTrue(String::isEmpty(' '));
|
$this->assertTrue(String::isEmpty(' '));
|
||||||
$this->assertTrue(String::isEmpty(false));
|
$this->assertTrue(String::isEmpty(false));
|
||||||
$this->assertTrue(String::isEmpty(null));
|
$this->assertTrue(String::isEmpty(null));
|
||||||
$this->assertTrue(String::isEmpty(true, false));
|
$this->assertTrue(String::isEmpty(true, false));
|
||||||
|
|
||||||
$this->assertFalse(String::isEmpty(0));
|
$this->assertFalse(String::isEmpty(0));
|
||||||
$this->assertFalse(String::isEmpty('foo'));
|
$this->assertFalse(String::isEmpty('foo'));
|
||||||
$this->assertFalse(String::isEmpty(' bar '));
|
$this->assertFalse(String::isEmpty(' bar '));
|
||||||
$this->assertFalse(String::isEmpty(true));
|
$this->assertFalse(String::isEmpty(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRandom()
|
public function testRandom()
|
||||||
{
|
{
|
||||||
$this->assertEquals(strlen(String::random()), 8);
|
$this->assertEquals(strlen(String::random()), 8);
|
||||||
$this->assertEquals(strlen(String::random(16)), 16);
|
$this->assertEquals(strlen(String::random(16)), 16);
|
||||||
|
|
||||||
$this->assertEquals(preg_match('/[a-z0-9]/', String::random(32, true, true)), 1);
|
$this->assertEquals(preg_match('/[a-z0-9]/', String::random(32, true, true)), 1);
|
||||||
$this->assertEquals(preg_match('/[a-z]/', String::random(32, true, false)), 1);
|
$this->assertEquals(preg_match('/[a-z]/', String::random(32, true, false)), 1);
|
||||||
$this->assertEquals(preg_match('/[0-9]/', String::random(32, false, true)), 1);
|
$this->assertEquals(preg_match('/[0-9]/', String::random(32, false, true)), 1);
|
||||||
|
|
||||||
$this->assertEquals(preg_match('/[0-9]/', String::random(32, true, false)), 0);
|
$this->assertEquals(preg_match('/[0-9]/', String::random(32, true, false)), 0);
|
||||||
$this->assertEquals(preg_match('/[a-z]/', String::random(32, false, true)), 0);
|
$this->assertEquals(preg_match('/[a-z]/', String::random(32, false, true)), 0);
|
||||||
$this->assertEquals(preg_match('/[a-z0-9]/', String::random(32, false, false)), 0);
|
$this->assertEquals(preg_match('/[a-z0-9]/', String::random(32, false, false)), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRandomSimilarFalse()
|
public function testRandomSimilarFalse()
|
||||||
{
|
{
|
||||||
$this->assertRegExp('/[a-hj-np-z2-9]{8}/', String::random(8, true, true, false));
|
$this->assertRegExp('/[a-hj-np-z2-9]{8}/', String::random(8, true, true, false));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @dataProvider providerTruncate
|
* @dataProvider providerTruncate
|
||||||
*/
|
*/
|
||||||
public function testTruncate($a, $b, $c, $d)
|
public function testTruncate($a, $b, $c, $d)
|
||||||
{
|
{
|
||||||
$this->assertEquals(String::truncate($a, $b, $c), $d);
|
$this->assertEquals(String::truncate($a, $b, $c), $d);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function providerTruncate()
|
public function providerTruncate()
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
['foo bar', 3, true, '<span title="foo bar">foo…</span>'],
|
['foo bar', 3, true, '<span title="foo bar">foo…</span>'],
|
||||||
['foo bar', 3, false, 'foo…'],
|
['foo bar', 3, false, 'foo…'],
|
||||||
['foo bar', 7, true, 'foo bar'],
|
['foo bar', 7, true, 'foo bar'],
|
||||||
['foo bar', 8, true, 'foo bar'],
|
['foo bar', 8, true, 'foo bar'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @dataProvider providerUpperWords
|
* @dataProvider providerUpperWords
|
||||||
*/
|
*/
|
||||||
public function testUpperWords($a, $b)
|
public function testUpperWords($a, $b)
|
||||||
{
|
{
|
||||||
$this->assertEquals(String::upperWords($a), $b);
|
$this->assertEquals(String::upperWords($a), $b);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function providerUpperWords()
|
public function providerUpperWords()
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
['foo bar', 'Foo Bar'],
|
['foo bar', 'Foo Bar'],
|
||||||
['FOO BAR', 'Foo Bar'],
|
['FOO BAR', 'Foo Bar'],
|
||||||
['fOO bAR', 'Foo Bar'],
|
['fOO bAR', 'Foo Bar'],
|
||||||
['foo@bar.com', 'foo@bar.com'],
|
['foo@bar.com', 'foo@bar.com'],
|
||||||
['FOO@BAR.COM', 'FOO@BAR.COM'],
|
['FOO@BAR.COM', 'FOO@BAR.COM'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @dataProvider providerGenerateSlug
|
* @dataProvider providerGenerateSlug
|
||||||
*/
|
*/
|
||||||
public function testGenerateSlug($a, $b)
|
public function testGenerateSlug($a, $b)
|
||||||
{
|
{
|
||||||
$this->assertEquals($b, String::generateSlug($a));
|
$this->assertEquals($b, String::generateSlug($a));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function providerGenerateSlug()
|
public function providerGenerateSlug()
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
['TEST STRING', 'test-string'],
|
['TEST STRING', 'test-string'],
|
||||||
['Test String', 'test-string'],
|
['Test String', 'test-string'],
|
||||||
['TEST STRING', 'test-string'],
|
['TEST STRING', 'test-string'],
|
||||||
['#! Test String', 'test-string'],
|
['#! Test String', 'test-string'],
|
||||||
['-test--string-', 'test-string'],
|
['-test--string-', 'test-string'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testPluralize()
|
public function testPluralize()
|
||||||
{
|
{
|
||||||
$this->assertEquals('test', String::pluralize('test', 1, false));
|
$this->assertEquals('test', String::pluralize('test', 1, false));
|
||||||
$this->assertEquals('1 test', String::pluralize('test', 1, true));
|
$this->assertEquals('1 test', String::pluralize('test', 1, true));
|
||||||
$this->assertEquals('tests', String::pluralize('test', 2, false));
|
$this->assertEquals('tests', String::pluralize('test', 2, false));
|
||||||
$this->assertEquals('2 tests', String::pluralize('test', 2, true));
|
$this->assertEquals('2 tests', String::pluralize('test', 2, true));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,160 +2,159 @@
|
||||||
|
|
||||||
class TimeTest extends PHPUnit_Framework_TestCase
|
class TimeTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
public function setUp()
|
public function setUp()
|
||||||
{
|
{
|
||||||
date_default_timezone_set('GMT');
|
date_default_timezone_set('GMT');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgePastTime()
|
public function testAgePastTime()
|
||||||
{
|
{
|
||||||
$this->assertEquals(18, Time::age(date('Y-m-d', strtotime('-18 years'))));
|
$this->assertEquals(18, Time::age(date('Y-m-d', strtotime('-18 years'))));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgeFutureTime()
|
public function testAgeFutureTime()
|
||||||
{
|
{
|
||||||
$this->assertEquals(-18, Time::age(date('Y-m-d', strtotime('18 years'))));
|
$this->assertEquals(-18, Time::age(date('Y-m-d', strtotime('18 years'))));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgeWrongFormat()
|
public function testAgeWrongFormat()
|
||||||
{
|
{
|
||||||
$this->assertEquals(17, Time::age(date('Ymd', strtotime('December 31st -18 years'))));
|
$this->assertEquals(17, Time::age(date('Ymd', strtotime('December 31st -18 years'))));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoJustNow()
|
public function testAgoJustNow()
|
||||||
{
|
{
|
||||||
$this->assertEquals('just now', Time::ago(Time::timestamp()));
|
$this->assertEquals('just now', Time::ago(Time::timestamp()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoPastTimeSeconds()
|
public function testAgoPastTimeSeconds()
|
||||||
{
|
{
|
||||||
$this->assertEquals('seconds ago', Time::ago(strtotime('-30 seconds')));
|
$this->assertEquals('seconds ago', Time::ago(strtotime('-30 seconds')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoPastTimeMinute()
|
public function testAgoPastTimeMinute()
|
||||||
{
|
{
|
||||||
$this->assertEquals('a minute ago', Time::ago(strtotime('-1 minutes')));
|
$this->assertEquals('a minute ago', Time::ago(strtotime('-1 minutes')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoPastTimeMinutes()
|
public function testAgoPastTimeMinutes()
|
||||||
{
|
{
|
||||||
$this->assertEquals('5 minutes ago', Time::ago(strtotime('-5 minutes')));
|
$this->assertEquals('5 minutes ago', Time::ago(strtotime('-5 minutes')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoPastTimeHour()
|
public function testAgoPastTimeHour()
|
||||||
{
|
{
|
||||||
$this->assertEquals('an hour ago', Time::ago(strtotime('-1 hours')));
|
$this->assertEquals('an hour ago', Time::ago(strtotime('-1 hours')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoPastTimeHours()
|
public function testAgoPastTimeHours()
|
||||||
{
|
{
|
||||||
$this->assertEquals('2 hours ago', Time::ago(strtotime('-2 hours')));
|
$this->assertEquals('2 hours ago', Time::ago(strtotime('-2 hours')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoPastTimeDay()
|
public function testAgoPastTimeDay()
|
||||||
{
|
{
|
||||||
$this->assertEquals('a day ago', Time::ago(strtotime('-1 days')));
|
$this->assertEquals('a day ago', Time::ago(strtotime('-1 days')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoPastTimeDays()
|
public function testAgoPastTimeDays()
|
||||||
{
|
{
|
||||||
$this->assertEquals('2 days ago', Time::ago(strtotime('-2 days')));
|
$this->assertEquals('2 days ago', Time::ago(strtotime('-2 days')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoPastTimeWeek()
|
public function testAgoPastTimeWeek()
|
||||||
{
|
{
|
||||||
$this->assertEquals('a week ago', Time::ago(strtotime('-1 weeks')));
|
$this->assertEquals('a week ago', Time::ago(strtotime('-1 weeks')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoPastTimeWeeks()
|
public function testAgoPastTimeWeeks()
|
||||||
{
|
{
|
||||||
$this->assertEquals('2 weeks ago', Time::ago(strtotime('-2 weeks')));
|
$this->assertEquals('2 weeks ago', Time::ago(strtotime('-2 weeks')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoPastTimeMonth()
|
public function testAgoPastTimeMonth()
|
||||||
{
|
{
|
||||||
$this->assertEquals('a month ago', Time::ago(strtotime('-1 months')));
|
$this->assertEquals('a month ago', Time::ago(strtotime('-1 months')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoPastTimeMonths()
|
public function testAgoPastTimeMonths()
|
||||||
{
|
{
|
||||||
$this->assertEquals('2 months ago', Time::ago(strtotime('-2 months')));
|
$this->assertEquals('2 months ago', Time::ago(strtotime('-2 months')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoPastTimeYear()
|
public function testAgoPastTimeYear()
|
||||||
{
|
{
|
||||||
$this->assertEquals('a year ago', Time::ago(strtotime('-1 years')));
|
$this->assertEquals('a year ago', Time::ago(strtotime('-1 years')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoPastTimeYears()
|
public function testAgoPastTimeYears()
|
||||||
{
|
{
|
||||||
$this->assertEquals('2 years ago', Time::ago(strtotime('-2 years')));
|
$this->assertEquals('2 years ago', Time::ago(strtotime('-2 years')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoFutureTimeSeconds()
|
public function testAgoFutureTimeSeconds()
|
||||||
{
|
{
|
||||||
$this->assertEquals('seconds from now', Time::ago(strtotime('+30 seconds')));
|
$this->assertEquals('seconds from now', Time::ago(strtotime('+30 seconds')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoFutureTimeMinutes()
|
public function testAgoFutureTimeMinutes()
|
||||||
{
|
{
|
||||||
$this->assertEquals('5 minutes from now', Time::ago(strtotime('+5 minutes')));
|
$this->assertEquals('5 minutes from now', Time::ago(strtotime('+5 minutes')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoFutureTimeHours()
|
public function testAgoFutureTimeHours()
|
||||||
{
|
{
|
||||||
$this->assertEquals('an hour from now', Time::ago(strtotime('+1 hour')));
|
$this->assertEquals('an hour from now', Time::ago(strtotime('+1 hour')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoFutureTimeDays()
|
public function testAgoFutureTimeDays()
|
||||||
{
|
{
|
||||||
$this->assertEquals('a day from now', Time::ago(strtotime('+1 day')));
|
$this->assertEquals('a day from now', Time::ago(strtotime('+1 day')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoFutureTimeWeeks()
|
public function testAgoFutureTimeWeeks()
|
||||||
{
|
{
|
||||||
$this->assertEquals('a week from now', Time::ago(strtotime('+1 week')));
|
$this->assertEquals('a week from now', Time::ago(strtotime('+1 week')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoFutureTimeMonths()
|
public function testAgoFutureTimeMonths()
|
||||||
{
|
{
|
||||||
$this->assertEquals('a month from now', Time::ago(strtotime('+1 month')));
|
$this->assertEquals('a month from now', Time::ago(strtotime('+1 month')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAgoFutureTimeYears()
|
public function testAgoFutureTimeYears()
|
||||||
{
|
{
|
||||||
$this->assertEquals('a year from now', Time::ago(strtotime('+1 year')));
|
$this->assertEquals('a year from now', Time::ago(strtotime('+1 year')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testTimestamp()
|
public function testTimestamp()
|
||||||
{
|
{
|
||||||
$this->assertEquals(gmdate('Y-m-d H:i:s'), Time::timestamp());
|
$this->assertEquals(gmdate('Y-m-d H:i:s'), Time::timestamp());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRoundUpHour()
|
public function testRoundUpHour()
|
||||||
{
|
{
|
||||||
$this->assertEquals('an hour ago', Time::ago(strtotime('-59 minutes -55 seconds')));
|
$this->assertEquals('an hour ago', Time::ago(strtotime('-59 minutes -55 seconds')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRoundUpDay()
|
public function testRoundUpDay()
|
||||||
{
|
{
|
||||||
$this->assertEquals('a day ago', Time::ago(strtotime('-23 hours -55 minutes')));
|
$this->assertEquals('a day ago', Time::ago(strtotime('-23 hours -55 minutes')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRoundUpWeek()
|
public function testRoundUpWeek()
|
||||||
{
|
{
|
||||||
$this->assertEquals('a week ago', Time::ago(strtotime('-6 days -23 hours')));
|
$this->assertEquals('a week ago', Time::ago(strtotime('-6 days -23 hours')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRoundUpMonth()
|
public function testRoundUpMonth()
|
||||||
{
|
{
|
||||||
$this->assertEquals('a month ago', Time::ago(strtotime('-29 days')));
|
$this->assertEquals('a month ago', Time::ago(strtotime('-29 days')));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRoundUpYear()
|
public function testRoundUpYear()
|
||||||
{
|
{
|
||||||
$this->assertEquals('a year ago', Time::ago(strtotime('-364 days')));
|
$this->assertEquals('a year ago', Time::ago(strtotime('-364 days')));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
|
@ -2,200 +2,198 @@
|
||||||
|
|
||||||
class ValidateTest extends PHPUnit_Framework_TestCase
|
class ValidateTest extends PHPUnit_Framework_TestCase
|
||||||
{
|
{
|
||||||
public function testFilterBoolean()
|
public function testFilterBoolean()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Validate::isValid(true, ['filter:boolean' => 'error']));
|
$this->assertTrue(Validate::isValid(true, ['filter:boolean' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFilterBooleanError()
|
public function testFilterBooleanError()
|
||||||
{
|
{
|
||||||
$this->assertEquals(['error'], Validate::isValid(false, ['filter:boolean' => 'error']));
|
$this->assertEquals(['error'], Validate::isValid(false, ['filter:boolean' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFilterEmail()
|
public function testFilterEmail()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Validate::isValid('foo@bar.com', ['filter:email' => 'error']));
|
$this->assertTrue(Validate::isValid('foo@bar.com', ['filter:email' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFilterEmailError()
|
public function testFilterEmailError()
|
||||||
{
|
{
|
||||||
$this->assertEquals(['error'], Validate::isValid('invalid', ['filter:email' => 'error']));
|
$this->assertEquals(['error'], Validate::isValid('invalid', ['filter:email' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFilterFloat()
|
public function testFilterFloat()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Validate::isValid(2.231981, ['filter:float' => 'error']));
|
$this->assertTrue(Validate::isValid(2.231981, ['filter:float' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFilterFloatError()
|
public function testFilterFloatError()
|
||||||
{
|
{
|
||||||
$this->assertEquals(['error'], Validate::isValid('invalid', ['filter:float' => 'error']));
|
$this->assertEquals(['error'], Validate::isValid('invalid', ['filter:float' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFilterInt()
|
public function testFilterInt()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Validate::isValid(2231981, ['filter:int' => 'error']));
|
$this->assertTrue(Validate::isValid(2231981, ['filter:int' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFilterIntError()
|
public function testFilterIntError()
|
||||||
{
|
{
|
||||||
$this->assertEquals(['error'], Validate::isValid('invalid', ['filter:int' => 'error']));
|
$this->assertEquals(['error'], Validate::isValid('invalid', ['filter:int' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFilterIP()
|
public function testFilterIP()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Validate::isValid('2.23.19.81', ['filter:ip' => 'error']));
|
$this->assertTrue(Validate::isValid('2.23.19.81', ['filter:ip' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFilterIPError()
|
public function testFilterIPError()
|
||||||
{
|
{
|
||||||
$this->assertEquals(['error'], Validate::isValid('invalid', ['filter:ip' => 'error']));
|
$this->assertEquals(['error'], Validate::isValid('invalid', ['filter:ip' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFilterURL()
|
public function testFilterURL()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Validate::isValid('http://foo.com/bar?stuff', ['filter:url' => 'error']));
|
$this->assertTrue(Validate::isValid('http://foo.com/bar?stuff', ['filter:url' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testFilterURLError()
|
public function testFilterURLError()
|
||||||
{
|
{
|
||||||
$this->assertEquals(['error'], Validate::isValid('invalid', ['filter:url' => 'error']));
|
$this->assertEquals(['error'], Validate::isValid('invalid', ['filter:url' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Invalid validation rule, expected: "validate:boolean|email|float|int|ip|url".
|
* @expectedExceptionMessage Invalid validation rule, expected: "validate:boolean|email|float|int|ip|url".
|
||||||
*/
|
*/
|
||||||
public function testFilterVarInvalidRule()
|
public function testFilterVarInvalidRule()
|
||||||
{
|
{
|
||||||
Validate::isValid('value', ['filter' => 'foo']);
|
Validate::isValid('value', ['filter' => 'foo']);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Invalid filter, expecting boolean, email, float, int, ip or url.
|
* @expectedExceptionMessage Invalid filter, expecting boolean, email, float, int, ip or url.
|
||||||
*/
|
*/
|
||||||
public function testFilterVarInvalidFilter()
|
public function testFilterVarInvalidFilter()
|
||||||
{
|
{
|
||||||
Validate::isValid('value', ['filter:foo' => 'bar']);
|
Validate::isValid('value', ['filter:foo' => 'bar']);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLengthLessThan()
|
public function testLengthLessThan()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Validate::isValid('value', ['length:<:10' => 'error']));
|
$this->assertTrue(Validate::isValid('value', ['length:<:10' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLengthLessThanError()
|
public function testLengthLessThanError()
|
||||||
{
|
{
|
||||||
$this->assertEquals(['error'], Validate::isValid('value', ['length:<:1' => 'error']));
|
$this->assertEquals(['error'], Validate::isValid('value', ['length:<:1' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLengthLessThanOrEqual()
|
public function testLengthLessThanOrEqual()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Validate::isValid('value', ['length:<=:10' => 'error']));
|
$this->assertTrue(Validate::isValid('value', ['length:<=:10' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLengthLessThanOrEqualError()
|
public function testLengthLessThanOrEqualError()
|
||||||
{
|
{
|
||||||
$this->assertEquals(['error'], Validate::isValid('value', ['length:<=:1' => 'error']));
|
$this->assertEquals(['error'], Validate::isValid('value', ['length:<=:1' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLengthEqual()
|
public function testLengthEqual()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Validate::isValid('value', ['length:==:5' => 'error']));
|
$this->assertTrue(Validate::isValid('value', ['length:==:5' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLengthEqualError()
|
public function testLengthEqualError()
|
||||||
{
|
{
|
||||||
$this->assertEquals(['error'], Validate::isValid('value', ['length:==:1' => 'error']));
|
$this->assertEquals(['error'], Validate::isValid('value', ['length:==:1' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLengthNotEqual()
|
public function testLengthNotEqual()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Validate::isValid('value', ['length:!=:1' => 'error']));
|
$this->assertTrue(Validate::isValid('value', ['length:!=:1' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLengthNotEqualError()
|
public function testLengthNotEqualError()
|
||||||
{
|
{
|
||||||
$this->assertEquals(['error'], Validate::isValid('value', ['length:!=:5' => 'error']));
|
$this->assertEquals(['error'], Validate::isValid('value', ['length:!=:5' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLengthGreaterThanOrEqual()
|
public function testLengthGreaterThanOrEqual()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Validate::isValid('value', ['length:>=:1' => 'error']));
|
$this->assertTrue(Validate::isValid('value', ['length:>=:1' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLengthGreaterThanOrEqualError()
|
public function testLengthGreaterThanOrEqualError()
|
||||||
{
|
{
|
||||||
$this->assertEquals(['error'], Validate::isValid('value', ['length:>=:10' => 'error']));
|
$this->assertEquals(['error'], Validate::isValid('value', ['length:>=:10' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLengthGreaterThan()
|
public function testLengthGreaterThan()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Validate::isValid('value', ['length:>:1' => 'error']));
|
$this->assertTrue(Validate::isValid('value', ['length:>:1' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testLengthGreaterThanError()
|
public function testLengthGreaterThanError()
|
||||||
{
|
{
|
||||||
$this->assertEquals(['error'], Validate::isValid('value', ['length:>:10' => 'error']));
|
$this->assertEquals(['error'], Validate::isValid('value', ['length:>:10' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Invalid validation rule, expected: "length:<|<=|==|!=|>=|>:integer".
|
* @expectedExceptionMessage Invalid validation rule, expected: "length:<|<=|==|!=|>=|>:integer".
|
||||||
*/
|
*/
|
||||||
public function testLengthInvalidRule()
|
public function testLengthInvalidRule()
|
||||||
{
|
{
|
||||||
Validate::isValid('value', ['length:16' => 'bar']);
|
Validate::isValid('value', ['length:16' => 'bar']);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Invalid length value, expecting an integer.
|
* @expectedExceptionMessage Invalid length value, expecting an integer.
|
||||||
*/
|
*/
|
||||||
public function testLengthInvalidLength()
|
public function testLengthInvalidLength()
|
||||||
{
|
{
|
||||||
Validate::isValid('value', ['length:==:foo' => 'bar']);
|
Validate::isValid('value', ['length:==:foo' => 'bar']);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @expectedException Exception
|
* @expectedException Exception
|
||||||
* @expectedExceptionMessage Invalid operator, expecting <, <=, ==, !=, >= or >.
|
* @expectedExceptionMessage Invalid operator, expecting <, <=, ==, !=, >= or >.
|
||||||
*/
|
*/
|
||||||
public function testLengthInvalidOperator()
|
public function testLengthInvalidOperator()
|
||||||
{
|
{
|
||||||
Validate::isValid('value', ['length:&&:10' => 'foo']);
|
Validate::isValid('value', ['length:&&:10' => 'foo']);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRegexIs()
|
public function testRegexIs()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Validate::isValid('value', ['regex:is:/^va7ue$/' => 'error']));
|
$this->assertTrue(Validate::isValid('value', ['regex:is:/^va7ue$/' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRegexIsError()
|
public function testRegexIsError()
|
||||||
{
|
{
|
||||||
$this->assertEquals(['error'], Validate::isValid('value', ['regex:is:/^value$/' => 'error']));
|
$this->assertEquals(['error'], Validate::isValid('value', ['regex:is:/^value$/' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRegexNot()
|
public function testRegexNot()
|
||||||
{
|
{
|
||||||
$this->assertTrue(Validate::isValid('value', ['regex:not:/^value$/' => 'error']));
|
$this->assertTrue(Validate::isValid('value', ['regex:not:/^value$/' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRegexNotError()
|
public function testRegexNotError()
|
||||||
{
|
{
|
||||||
$this->assertEquals(['error'], Validate::isValid('value', ['regex:not:/^va7ue$/' => 'error']));
|
$this->assertEquals(['error'], Validate::isValid('value', ['regex:not:/^va7ue$/' => 'error']));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @expectedException Exception
|
|
||||||
* @expectedExceptionMessage Invalid validation rule, expected: "regex:is|not:string".
|
|
||||||
*/
|
|
||||||
public function testRegexInvalidRule()
|
|
||||||
{
|
|
||||||
Validate::isValid('value', ['regex:/foo/' => 'bar']);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @expectedException Exception
|
||||||
|
* @expectedExceptionMessage Invalid validation rule, expected: "regex:is|not:string".
|
||||||
|
*/
|
||||||
|
public function testRegexInvalidRule()
|
||||||
|
{
|
||||||
|
Validate::isValid('value', ['regex:/foo/' => 'bar']);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue