diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..22d0d82 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +vendor diff --git a/README.md b/README.md new file mode 100644 index 0000000..b5c306c --- /dev/null +++ b/README.md @@ -0,0 +1,24 @@ +# TypeHelper + +* ```TypeHelper::toStrictType($value)``` - return $value to strict type + +## Example + +```php +use \darkfriend\helpers\TypeHelper; + +var_dump( + TypeHelper::toStrict('false'), // bool(false) + TypeHelper::toStrict(null), // NULL + TypeHelper::toStrict(0), // int(0) + TypeHelper::toStrict('0'), // int(0) + TypeHelper::toStrict('1'), // int(1) + TypeHelper::toStrict(1), // int(1) + TypeHelper::toStrict('1.1'), // float(1.1) + TypeHelper::toStrict(1.1), // float(1.1) + TypeHelper::toStrict(true), // bool(true) + TypeHelper::toStrict(false), // bool(false) + TypeHelper::toStrict('my string'), // string(9) "my string" + TypeHelper::toStrict('') // string(0) "" +); +``` \ No newline at end of file diff --git a/TypeHelper.php b/TypeHelper.php new file mode 100644 index 0000000..14f6b07 --- /dev/null +++ b/TypeHelper.php @@ -0,0 +1,51 @@ + + */ +class TypeHelper +{ + /** + * Return value to strict type + * @param mixed $value + * @return bool|int|string|null + */ + public static function toStrict($value) + { + if ($value === null) { + return null; + } + + if (\is_numeric($value)) { + $num = \filter_var($value, \FILTER_VALIDATE_INT | \FILTER_VALIDATE_FLOAT); + if ($num === false) { + return (string)$value; + } + + if ((int)$num == (float)$num) { + return (int)$num; + } + + return $num; + } + + if ((bool)$value == $value) { + switch ($value) { + case 'true': + $value = true; + break; + case 'false': + $value = false; + break; + } + return $value; + } + + return (string)$value; + } +} \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..8c6a417 --- /dev/null +++ b/composer.json @@ -0,0 +1,21 @@ +{ + "name": "darkfriend/php7-type", + "type": "library", + "description": "PHP7-helper for type data", + "keywords": ["dev","types","darkfriend","development","php7","php"], + "homepage": "https://github.com/darkfriend/php7-helpers", + "authors": [ + { + "name": "darkfriend", + "email": "hi@darkfriend.ru" + } + ], + "require": { + "php":">=7.0" + }, + "autoload":{ + "classmap":[ + "./TypeHelper.php" + ] + } +} \ No newline at end of file