PageRenderTime 31ms CodeModel.GetById 20ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/core/CDFDataHelper.php

#
PHP | 228 lines | 131 code | 19 blank | 78 comment | 43 complexity | 5397ac0e7feaacef4df24fef9a7b0df4 MD5 | raw file
  1<?php
  2
  3require_once 'CDFFormat.php';
  4require_once 'CDFExceptions.php';
  5
  6/**
  7 *  Provides wrappers for guaranteeing a variable is the specified type.
  8 */
  9final class CDFDataHelper
 10{
 11	/**
 12	 * Formats any value passed in to be guaranteed as a string output.
 13	 * @param mixed $value
 14	 * @throws CDFInvalidArgumentException
 15	 * @return string
 16	 */
 17	public static function AsString($value)
 18	{
 19		if(is_null($value))
 20			return ''; // null returns an empty string
 21		if(is_string($value))
 22			return $value; // if already a string, don't do anything
 23		if(is_float($value))
 24			return CDFFormat::DoubleToString($value); // format it correctly
 25		if(is_int($value))
 26			return CDFFormat::IntegerToString($value);
 27		if(is_bool($value))
 28			return $value === true ? "True" : "False";
 29		if(is_object($value))
 30		{
 31			if(method_exists($value, '__toString'))
 32				$value = $value->__toString();
 33			else
 34				throw new CDFInvalidArgumentException('Cannot convert object to string');
 35		}
 36
 37		// anything else, convert it to a string
 38		return trim((string)$value);
 39	}
 40
 41	/**
 42	 * Returns the specified value as a string, but if it is already a string, applies 'safe' formatting to the string.
 43	 * @param mixed $value
 44	 * @param bool $stripHtml
 45	 * @return string
 46	 */
 47	public static function AsStringSafe($value, $stripHtml = true)
 48	{
 49		if(is_null($value))
 50			return '';
 51		if(!is_string($value))
 52			return self::AsString($value);
 53
 54		// if stripping html, add anything inside a <> pair to remove from the string.
 55		return trim($stripHtml ? strip_tags($value) : $value);
 56	}
 57
 58	/**
 59	 * Returns the specified value as a float.
 60	 * @param mixed $value
 61	 * @throws CDFInvalidArgumentException
 62	 * @return float
 63	 */
 64	public static function AsFloat($value)
 65	{
 66		if(is_float($value))
 67			return $value;
 68		if(is_null($value))
 69			return 0.0;
 70		if(is_string($value))
 71			return floatval(trim($value));
 72		if(is_object($value))
 73			throw new CDFInvalidArgumentException('Cannot convert object to float');
 74
 75		// lazy conversion from anything else
 76		return 0.0 + $value;
 77	}
 78
 79	/**
 80	 * Returns the specified value as a 32-bit integer.
 81	 * @param mixed $value
 82	 * @throws CDFInvalidObjectException
 83	 * @return int
 84	 */
 85	public static function AsInt($value)
 86	{
 87		if(is_int($value))
 88			return $value;
 89		if(is_null($value))
 90			return 0;
 91		if(is_string($value))
 92			return intval(trim($value)); // force conversion to integer
 93		if(is_object($value))
 94			throw new CDFInvalidObjectException('Cannot convert object to integer');
 95
 96		return 0 + $value;
 97	}
 98
 99	/**
100	 * Returns the specified value as a boolean.
101	 * @param mixed $value
102	 * @return bool
103	 */
104	public static function AsBool($value)
105	{
106		if(is_bool($value))
107			return $value;
108		if(is_null($value))
109			return false;
110		if(is_string($value))
111		{
112			// special case to handle BIT fields in a database
113			if(strlen($value) > 0 && $value[0] == chr(1))
114				return true;
115
116			$s = trim(strtolower($value));
117			return ($s === '1' || $s === 'true' || $s === 'on' || $s === 'yes') ? true : false;
118		}
119
120		return $value ? true : false;
121	}
122
123	/**
124	 * Returns the specified value as a DateTime object.  Will equal the Epoch if fails to parse.
125	 * @param mixed $value
126	 * @param string $timezone Defaults to GMT. Pass null to use system default
127	 * @return DateTime
128	 */
129	public static function AsDateTime($value, $timezone = 'GMT')
130	{
131		if($value instanceof DateTime) // if already a DateTime object, just return it
132		{
133			// check its timezone first
134			$tz = $timezone == null ? ini_get('date.timezone') : $timezone;
135			/** @var $value DateTime */
136			if($value->getTimezone()->getName() != $tz)
137				// convert to GMT then to the timezone
138			return CDFDataHelper::AsDateTime($value->getTimestamp(), $tz);
139			// timezone is the same
140			return $value;
141		}
142		if(is_null($value) || (is_string($value) && strlen($value) < 1))
143			return new DateTime('@0');
144		try
145		{
146			$tz = $timezone == null ? null : new DateTimeZone($timezone);
147			if(is_numeric($value))
148				return new DateTime(sprintf('@%d', $value), $tz);
149			return new DateTime($value, $tz);
150		}
151		catch(Exception $ex)
152		{
153			return new DateTime('@0');
154		}
155	}
156
157	/**
158	 * Returns true if the specified valid is a valid DateTime object AND the time is not equal to the Epoch
159	 * (i.e. it is actually a specified time).
160	 * @param mixed $value
161	 * @return bool
162	 */
163	public static function hasDateTime($value)
164	{
165		if($value instanceof DateTime)
166		{
167			/** @var $value DateTime */
168			$ts = $value->getTimestamp(); // if negative, returns false
169			return $ts !== false && $ts > 0;
170		}
171		return false;
172	}
173
174	/**
175	 * Returns true if the specified array contains all of the defined keys.
176	 * <code>
177	 * echo CDFDataHelper::hasArrayKeys(array('foo'=>1,'bar'=>2), array('foo','bar'));
178	 * // prints true
179	 * echo CDFDataHelper::hasArrayKeys(array('foo'=>1,'bar'=>2), 'foo', 'bar');
180	 * // also prints true
181	 * echo CDFDataHelper::hasArrayKeys(array('foo'=>1,'bar'=>2), array('moo'));
182	 * // prints false
183	 * </code>
184	 * @static
185	 * @throws CDFInvalidArgumentException
186	 * @param array $array The array to test against.
187	 * @param array|mixed $keys Either an array of key names or a variable arg list of names.
188	 * @return bool
189	 */
190	public static function hasArrayKeys($array, $keys)
191	{
192		// must be an array and must have at least one key to test
193		if(!is_array($array) || func_num_args() < 2)
194			throw new CDFInvalidArgumentException();
195
196		if(!is_array($keys))
197		{
198			// argument is not an array, use variable args
199			$keyNames = array();
200			for($arg = 1; $arg < func_num_args(); $arg++)
201				$keyNames[] = func_get_arg($arg);
202		}
203		else
204			$keyNames = $keys;
205
206		// test the array for the keys
207		foreach($keyNames as $key)
208		{
209			if(!isset($array[$key]))
210				return false;
211		}
212
213		return true;
214	}
215
216	/**
217	 * Returns true if the specified value is 'empty', i.e. an empty string, zero, false or null.
218	 * @remarks This wraps the PHP empty function where before PHP 5.5, empty() only accepts a variable and not an expression.
219	 * @param mixed $value
220	 * @return bool
221	 */
222	public static function isEmpty($value)
223	{
224		if($value instanceof DateTime)
225			return self::hasDateTime($value);
226		return empty($value);
227	}
228}