Skip to content

Commit

Permalink
FilePath Class for DataType and its tests added
Browse files Browse the repository at this point in the history
  • Loading branch information
mkorkmaz committed Jan 19, 2017
1 parent 5351e80 commit 8c20cf4
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 0 deletions.
55 changes: 55 additions & 0 deletions src/DataType/FilePath.php
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);

namespace Selami\Entity\DataType;

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

class FilePath extends DataTypeAbstract implements DataTypeInterface
{
const DATA_TYPE_ERROR = 'Assertion failed for value "%s" for "%s" : INVALID_TYPE';

protected static $defaults = [
'default' => null
];

/**
* Slug constructor.
* @param string $key
* @param mixed $datum
* @param array $options
*/
public function __construct(string $key, $datum, array $options = [])
{
$this->key = $key;
$this->datum = $datum;
$this->checkValidOptions($options);
$this->options = array_merge(self::$defaults, $options);
}

/**
* {@inheritdoc}
*/
public function assert()
{
if (!preg_match('#^[a-zA-Z0-9/._-]+$#', $this->datum)) {
$this->errorMessageTemplate = self::DATA_TYPE_ERROR;
$this->throwException();
}
return true;
}

/**
* {@inheritdoc}
*/
public function normalize()
{
try {
$this->assert();
return filter_var($this->datum, FILTER_SANITIZE_URL);
} catch (InvalidArgumentException $e) {
return $this->options['default'];
}
}
}
46 changes: 46 additions & 0 deletions tests/DataType/FilePathTest.php
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);

namespace tests;

use Selami\Test\Abstracts\DataType;

class MyFilePathClass extends DataType
{

public function setUp()
{
$this->className = '\\Selami\\Entity\\DataType\\FilePath';
$this->validValue = 'path/file.jpg';
$this->key = 'path';
$this->options = [];
}

public function trueProvider()
{
return [
['path/to/file.jpg'],
['path-2'],
['/etc'],
['path-2/file.jpg'],
['path-2/path-3'],
['path-2/path-3/pa_th']
];
}

public function exceptionProvider()
{
return [
['file/to/path:'],
['file/t o/path']
];
}

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

0 comments on commit 8c20cf4

Please sign in to comment.