Skip to content

Commit

Permalink
Regex Class for DataType and its tests are added
Browse files Browse the repository at this point in the history
  • Loading branch information
mkorkmaz committed Jan 21, 2017
1 parent 9b9471a commit c5a3572
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/DataType/Regex.php
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);

namespace Selami\Entity\DataType;

use Selami\Entity\Interfaces\DataTypeInterface;
use InvalidArgumentException;

class Regex implements DataTypeInterface
{
use DataTypeRegexTrait;

const DATA_FORMAT_ERROR = 'Assertion failed for value "%s" for "%s" : INVALID_FORMAT';

protected $regex;
protected $sanitizeFlags;
protected static $defaults = [
'default' => null,
'regex' => null,
'sanitize_flag' => null
];

/**
* Regex constructor.
* @param string $key
* @param mixed $datum
* @param array $options
* @throws InvalidArgumentException
*/
public function __construct(string $key, $datum, array $options = [])
{
if (!isset($options['regex']) || empty($options['regex'])) {
throw new InvalidArgumentException('$options[regex] can\'t be empty and must be a valid regex');
}
$this->key = $key;
$this->datum = $datum;
$this->regex = $options['regex'];
$this->sanitizeFlags = $options['sanitize_flag'] ?? null;
$this->checkValidOptions($options);
$this->options = array_merge(self::$defaults, $options);
}
}
54 changes: 54 additions & 0 deletions tests/DataType/RegexTest.php
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);

namespace tests;

use Selami\Test\Abstracts\DataType;
use InvalidArgumentException;

class MyRegexClass extends DataType
{

public function setUp()
{
$this->className = '\\Selami\\Entity\\DataType\\Regex';
$this->validValue = 'valid_regex_text';
$this->key = 'field';
$this->options = ['regex' => '#^v#'];
}

/**
* @test
* @expectedException InvalidArgumentException
*/
public function shouldThrowExceptionForEmptyRegexOption()
{
new $this->className($this->key, $this->validValue, []);
}

public function trueProvider()
{
return [
[
'https://www.youtube.com/watch?v=1VVj1zqbWpU',
['regex' => '#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#']
]
];
}

public function exceptionProvider()
{
return [
['not_found_text', ['regex' => '#^t#']],
['not_found_text', ['regex' => '#^#t#']]
];
}

public function defaultsProvider()
{
return [
['-slug', '-slug', ['regex' => '#^\-#']],
['slug/slug:', 'NaN', ['default' => 'NaN', 'regex' => '#^t#']]
];
}
}

0 comments on commit c5a3572

Please sign in to comment.