Skip to content

Commit

Permalink
Added non-empty flag to toStringOrNull()
Browse files Browse the repository at this point in the history
Signed-off-by: Tom Wright <tom@inflatablecookie.com>
  • Loading branch information
betterthanclay committed Nov 27, 2023
1 parent 7503807 commit ef34eb0
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
* Added non-empty flag to toStringOrNull()
* Made PHP8.1 minimum version
* Check for DateInterval parse failure

Expand Down
14 changes: 12 additions & 2 deletions src/Coercion.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,24 @@ public static function toString(
* Coerce value to string or null
*/
public static function toStringOrNull(
mixed $value
mixed $value,
bool $nonEmpty = false
): ?string {
if (
is_string($value) ||
$value instanceof Stringable ||
is_numeric($value)
) {
return (string)$value;
$output = (string)$value;

if (
$nonEmpty &&
$output === ''
) {
return null;
}

return $output;
}

return null;
Expand Down

0 comments on commit ef34eb0

Please sign in to comment.