generated from spawnia/php-package-template
-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add class SafeCast #61
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
spawnia
wants to merge
4
commits into
master
Choose a base branch
from
safe-cast
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,170 @@ | ||
| <?php declare(strict_types=1); | ||
|
|
||
| namespace MLL\Utils; | ||
|
|
||
| use function Safe\preg_match; | ||
|
|
||
| /** | ||
| * Safe type casting utilities to prevent unexpected or meaningless cast results. | ||
| * | ||
| * PHP's native type casts like (int) and (float) can produce unexpected results, | ||
| * especially when casting from strings. This class provides safe alternatives that | ||
| * validate the input before casting. | ||
| * | ||
| * Example of problematic native casts: | ||
| * - (int)"hello" returns 0 (misleading, not an error) | ||
| * - (int)"123abc" returns 123 (partial conversion, data loss) | ||
| * - (float)"1.23.45" returns 1.23 (invalid format accepted) | ||
| * | ||
| * The methods in this class throw exceptions for invalid inputs instead of | ||
| * silently producing incorrect values. | ||
| */ | ||
| class SafeCast | ||
| { | ||
| /** | ||
| * Safely cast a value to an integer. | ||
| * | ||
| * Only accepts: | ||
| * - Integers (returned as-is) | ||
| * - Numeric strings that represent valid integers | ||
| * - Floats that are exact integer values (e.g., 5.0) | ||
| * | ||
| * @param mixed $value The value to cast | ||
| * | ||
| * @throws \InvalidArgumentException If the value cannot be safely cast to an integer | ||
| */ | ||
| public static function toInt($value): int | ||
| { | ||
| if (is_int($value)) { | ||
| return $value; | ||
| } | ||
|
|
||
| // Allow floats that represent exact integers (e.g., 5.0 -> 5) | ||
| if (is_float($value)) { | ||
| if ($value === floor($value) && is_finite($value)) { | ||
| return (int) $value; | ||
| } | ||
|
|
||
| throw new \InvalidArgumentException('Float value "' . $value . '" cannot be safely cast to int (not a whole number or not finite)'); | ||
| } | ||
|
|
||
| if (is_string($value)) { | ||
| $trimmed = trim($value); | ||
|
|
||
| // Empty string is not a valid integer | ||
| if ($trimmed === '') { | ||
| throw new \InvalidArgumentException('Empty string cannot be cast to int'); | ||
| } | ||
|
|
||
| // Check if the string represents a valid integer | ||
| if (! self::isIntegerString($trimmed)) { | ||
| throw new \InvalidArgumentException('String value "' . $value . '" is not a valid integer format'); | ||
| } | ||
|
|
||
| return (int) $trimmed; | ||
| } | ||
|
|
||
| throw new \InvalidArgumentException('Cannot cast value of type "' . gettype($value) . '" to int'); | ||
| } | ||
|
|
||
| /** | ||
| * Safely cast a value to a float. | ||
| * | ||
| * Only accepts: | ||
| * - Floats (returned as-is) | ||
| * - Integers (cast to float) | ||
| * - Numeric strings that represent valid floats | ||
| * | ||
| * @param mixed $value The value to cast | ||
| * | ||
| * @throws \InvalidArgumentException If the value cannot be safely cast to a float | ||
| */ | ||
| public static function toFloat($value): float | ||
| { | ||
| if (is_float($value)) { | ||
| return $value; | ||
| } | ||
|
|
||
| if (is_int($value)) { | ||
| return (float) $value; | ||
| } | ||
|
|
||
| if (is_string($value)) { | ||
| $trimmed = trim($value); | ||
|
|
||
| // Empty string is not a valid float | ||
| if ($trimmed === '') { | ||
| throw new \InvalidArgumentException('Empty string cannot be cast to float'); | ||
| } | ||
|
|
||
| // Check if the string represents a valid numeric value | ||
| if (! self::isNumericString($trimmed)) { | ||
| throw new \InvalidArgumentException('String value "' . $value . '" is not a valid numeric format'); | ||
| } | ||
|
|
||
| return (float) $trimmed; | ||
| } | ||
|
|
||
| throw new \InvalidArgumentException('Cannot cast value of type "' . gettype($value) . '" to float'); | ||
| } | ||
|
|
||
| /** | ||
| * Safely cast a value to a string. | ||
| * | ||
| * Only accepts: | ||
| * - Strings (returned as-is) | ||
| * - Integers and floats (converted to string) | ||
| * - Objects with __toString() method | ||
| * - null (converted to empty string) | ||
| * | ||
| * @param mixed $value The value to cast | ||
| * | ||
| * @throws \InvalidArgumentException If the value cannot be safely cast to a string | ||
| */ | ||
| public static function toString($value): string | ||
| { | ||
| if (is_string($value)) { | ||
| return $value; | ||
| } | ||
|
|
||
| if (is_int($value) || is_float($value)) { | ||
| return (string) $value; | ||
| } | ||
|
|
||
| if ($value === null) { | ||
| return ''; | ||
| } | ||
|
|
||
| if (is_object($value) && method_exists($value, '__toString')) { | ||
| return (string) $value; | ||
| } | ||
|
|
||
| throw new \InvalidArgumentException('Cannot cast value of type "' . gettype($value) . '" to string'); | ||
| } | ||
|
|
||
| /** | ||
| * Check if a string represents a valid integer. | ||
| * | ||
| * Accepts optional leading/trailing whitespace, optional sign, and digits only. | ||
| */ | ||
| private static function isIntegerString(string $value): bool | ||
| { | ||
| return preg_match('/^[+-]?\d+$/', $value) === 1; | ||
| } | ||
|
|
||
| /** | ||
| * Check if a string represents a valid numeric value (integer or float). | ||
| * | ||
| * Accepts scientific notation, decimals with optional sign. | ||
| */ | ||
| private static function isNumericString(string $value): bool | ||
| { | ||
| if (! is_numeric($value)) { | ||
| return false; | ||
| } | ||
|
|
||
| // is_numeric accepts some formats we want to reject, like hexadecimal (0x1F) or binary (0b1010). | ||
| // Check for these and reject them for stricter validation | ||
| return preg_match('/^0[xXbB]/', $value) !== 1; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.