Skip to content

Commit

Permalink
begin type helper
Browse files Browse the repository at this point in the history
  • Loading branch information
darkfriend committed Dec 21, 2019
0 parents commit 340a63d
Show file tree
Hide file tree
Showing 4 changed files with 97 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
vendor
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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) ""
);
```
51 changes: 51 additions & 0 deletions TypeHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace darkfriend\helpers;

/**
* PHP type helper package
* @package darkfriend\helpers
* @version 1.0.0
* @author darkfriend <hi@darkfriend.ru>
*/
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;
}
}
21 changes: 21 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -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"
]
}
}

0 comments on commit 340a63d

Please sign in to comment.