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