diff --git a/src/DataType/FilePath.php b/src/DataType/FilePath.php new file mode 100644 index 0000000..3ec0b43 --- /dev/null +++ b/src/DataType/FilePath.php @@ -0,0 +1,55 @@ + 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']; + } + } +} diff --git a/tests/DataType/FilePathTest.php b/tests/DataType/FilePathTest.php new file mode 100644 index 0000000..4e2c8d2 --- /dev/null +++ b/tests/DataType/FilePathTest.php @@ -0,0 +1,46 @@ +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']] + ]; + } +}