Skip to content

Commit 440c7dc

Browse files
committed
add VariableUtils
1 parent f7e9912 commit 440c7dc

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

src/VariableUtils.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
namespace Hatamiarash7\Utils;
4+
5+
/**
6+
* Class VariableUtils
7+
*
8+
* @package Hatamiarash7\Utils
9+
*/
10+
class VariableUtils
11+
{
12+
/**
13+
* Smart convert string to int
14+
*
15+
* @param string $value
16+
* @return int
17+
*/
18+
public static function int($value): int
19+
{
20+
$cleaned = preg_replace('#[^0-9-+.,]#', '', $value);
21+
preg_match('#[-+]?[\d]+#', $cleaned, $matches);
22+
$result = $matches[0] ?? 0;
23+
return (int)$result;
24+
}
25+
26+
/**
27+
* Return only digits chars
28+
*
29+
* @param $value
30+
* @return mixed
31+
*/
32+
public static function digits($value)
33+
{
34+
$cleaned = str_replace(['-', '+'], '', $value);
35+
$cleaned = filter_var($cleaned, FILTER_SANITIZE_NUMBER_INT);
36+
return $cleaned;
37+
}
38+
}

tests/VariableUtilsTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
namespace Hatamiarash7\Utils\Test;
4+
5+
use Hatamiarash7\Utils\LaravelUtilsServiceProvider;
6+
use Hatamiarash7\Utils\VariableUtils;
7+
use Orchestra\Testbench\TestCase as Orchestra;
8+
9+
class VariableUtilsTest extends Orchestra
10+
{
11+
/**
12+
* add the package provider
13+
*
14+
* @param $app
15+
* @return array
16+
*/
17+
protected function getPackageProviders($app)
18+
{
19+
return [LaravelUtilsServiceProvider::class];
20+
}
21+
22+
/** @test */
23+
public function test_functions()
24+
{
25+
$this->assertEquals(123, VariableUtils::int("123"));
26+
$this->assertEquals(123, VariableUtils::int("a123"));
27+
$this->assertEquals(123, VariableUtils::int("at12e3h"));
28+
29+
$this->assertEquals(123, VariableUtils::digits("at12e3h"));
30+
}
31+
}

0 commit comments

Comments
 (0)