Changeset View
Changeset View
Standalone View
Standalone View
src/utils/utils.php
Show First 20 Lines • Show All 2,181 Lines • ▼ Show 20 Lines | |||||
* | * | ||||
* The value "null", the empty string, and objects which have a "__toString()" | * The value "null", the empty string, and objects which have a "__toString()" | ||||
* method which returns the empty string are empty. | * method which returns the empty string are empty. | ||||
* | * | ||||
* Other strings, objects with a "__toString()" method which returns a | * Other strings, objects with a "__toString()" method which returns a | ||||
* string other than the empty string, integers, and floats are considered | * string other than the empty string, integers, and floats are considered | ||||
* scalar. | * scalar. | ||||
* | * | ||||
* Note that booleans are also valid scalars, where false is considered empty, | |||||
* and true is non-empty since if you cast true to string, it's non-empty. | |||||
* | |||||
* This method raises an exception if passed any other value. | * This method raises an exception if passed any other value. | ||||
* | * | ||||
* @param Value to test. | * @param Value to test. | ||||
* @return bool True if the parameter is a nonempty, scalar value. | * @return bool True if the parameter is a nonempty, scalar value. | ||||
*/ | */ | ||||
function phutil_nonempty_scalar($value) { | function phutil_nonempty_scalar($value) { | ||||
if ($value === null) { | if ($value === null) { | ||||
return false; | return false; | ||||
} | } | ||||
if ($value === '') { | if ($value === '') { | ||||
return false; | return false; | ||||
} | } | ||||
if (is_string($value) || is_int($value) || is_float($value)) { | if (is_string($value) || is_int($value) || is_float($value)) { | ||||
return true; | return true; | ||||
} | } | ||||
// Booleans are also valid scalars by PHP. Inventing the opposite can be | |||||
// too much esoteric and problematic. | |||||
// false: empty, because casted to string becomes '' (empty) | |||||
// true: non-empty, because casted to string becomes '1' (non-empty) | |||||
if ($value === false || $value === true) { | |||||
return $value; | |||||
} | |||||
if (is_object($value)) { | if (is_object($value)) { | ||||
try { | try { | ||||
$string = phutil_string_cast($value); | $string = phutil_string_cast($value); | ||||
return phutil_nonempty_string($string); | return phutil_nonempty_string($string); | ||||
} catch (Exception $ex) { | } catch (Exception $ex) { | ||||
// Continue below. | // Continue below. | ||||
} catch (Throwable $ex) { | } catch (Throwable $ex) { | ||||
// Continue below. | // Continue below. | ||||
Show All 9 Lines |
Content licensed under Creative Commons Attribution-ShareAlike 4.0 (CC-BY-SA) unless otherwise noted; code licensed under Apache 2.0 or other open source licenses. · CC BY-SA 4.0 · Apache 2.0