FormatDateFilter::filter()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 2
nop 2
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
ccs 6
cts 6
cp 1
crap 3
1
<?php namespace Arcanedev\Sanitizer\Filters;
2
3
use Arcanedev\Sanitizer\Contracts\Filterable;
4
use DateTime;
5
use InvalidArgumentException;
6
7
/**
8
 * Class     FormatDateFilter
9
 *
10
 * @package  Arcanedev\Sanitizer\Filters
11
 * @author   ARCANEDEV <[email protected]>
12
 */
13
class FormatDateFilter implements Filterable
14
{
15
    /* ------------------------------------------------------------------------------------------------
16
     |  Main Functions
17
     | ------------------------------------------------------------------------------------------------
18
     */
19
    /**
20
     * Format date of the given string.
21
     *
22
     * @param  mixed  $value
23
     * @param  array  $options
24
     *
25
     * @return string|mixed
26
     */
27 36
    public function filter($value, array $options = [])
28
    {
29 36
        if ( ! is_string($value) || empty(trim($value)))
30 18
            return $value;
31
32 36
        $this->checkOptions($options);
33
34 27
        list($currentFormat, $targetFormat) = array_map('trim', $options);
35
36 27
        return DateTime::createFromFormat($currentFormat, $value)->format($targetFormat);
37
    }
38
39
    /* ------------------------------------------------------------------------------------------------
40
     |  Other Functions
41
     | ------------------------------------------------------------------------------------------------
42
     */
43
    /**
44
     * Check Options.
45
     *
46
     * @param  array  $options
47
     *
48
     * @throws \InvalidArgumentException
49
     */
50 36
    private function checkOptions(array $options)
51
    {
52 36
        if (count($options) != 2) {
53 9
            throw new InvalidArgumentException(
54 6
                'The Sanitizer Format Date filter requires both the current date format as well as the target format.'
55 3
            );
56
        }
57 27
    }
58
}
59