Passed
Push — main ( e8f487...78ef96 )
by Michiel
06:38
created

TstampTask   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 100
Duplicated Lines 0 %

Test Coverage

Coverage 82.93%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 17
eloc 40
c 2
b 0
f 0
dl 0
loc 100
ccs 34
cts 41
cp 0.8293
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A createProperty() 0 13 3
B getUnixTime() 0 25 7
A init() 0 5 2
A addFormat() 0 3 1
A setPrefix() 0 6 2
A main() 0 12 2
1
<?php
2
3
/**
4
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
13
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
14
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15
 *
16
 * This software consists of voluntary contributions made by many individuals
17
 * and is licensed under the LGPL. For more information please see
18
 * <http://phing.info>.
19
 */
20
21
namespace Phing\Task\System;
22
23
use DateTime;
24
use Error;
25
use ValueError;
26
use Exception;
27
use IntlDateFormatter;
28
use Phing\Exception\BuildException;
29
use Phing\Project;
30
use Phing\Task;
31
32
/**
33
 * Sets properties to the current time, or offsets from the current time.
34
 * The default properties are TSTAMP, DSTAMP and TODAY;.
35
 *
36
 * Based on Ant's Tstamp task.
37
 *
38
 * @author  Michiel Rook <[email protected]>
39
 *
40
 * @since   2.2.0
41
 */
42
class TstampTask extends Task
43
{
44
    /** @var \Phing\Task\System\TstampCustomFormat[] */
45
    private $customFormats = [];
46
47
    /** @var string */
48
    private $prefix = '';
49
50
    /**
51
     * Set a prefix for the properties.
52
     */
53 1
    public function setPrefix(string $prefix): void
54
    {
55 1
        $this->prefix = $prefix;
56
57 1
        if (!empty($this->prefix)) {
58 1
            $this->prefix .= '.';
59
        }
60
    }
61
62
    /**
63
     * @param TstampCustomFormat $format object representing `<format/>` tag
64
     */
65 24
    public function addFormat(TstampCustomFormat $format): void
66
    {
67 24
        $this->customFormats[] = $format;
68
    }
69
70 28
    public function init(): void
71
    {
72
        // Testing class instead of extension to allow polyfills
73 28
        if (!class_exists(IntlDateFormatter::class)) {
74
            throw new BuildException('TstampTask requires Intl extension');
75
        }
76
    }
77
78
    /**
79
     * Create the timestamps. Custom ones are done before the standard ones.
80
     */
81 29
    public function main(): void
82
    {
83 29
        $unixTime = $this->getUnixTime();
84
85 29
        foreach ($this->customFormats as $format) {
86 24
            $format->validate($this);
87 24
            $this->createProperty($format->propertyName, $unixTime, $format->pattern, $format->locale, $format->timezone);
88
        }
89
90 29
        $this->createProperty('DSTAMP', $unixTime, 'yyyyMMdd');
91 29
        $this->createProperty('TSTAMP', $unixTime, 'HHmm');
92 29
        $this->createProperty('TODAY', $unixTime);
93
    }
94
95
    /**
96
     * @param string      $propertyName  name of the property to be created
97
     * @param int         $unixTimestamp unix timestamp to be converted
98
     * @param null|string $pattern       ICU pattern, when null locale-dependent date pattern is used
99
     * @param null|string $locale        locale to use with timestamp, when null PHP default locale is used
100
     * @param null|string $timezone      timezone to use with timestamp, when null PHP default timezone is used
101
     */
102 29
    protected function createProperty(string $propertyName, int $unixTimestamp, ?string $pattern = null, ?string $locale = null, ?string $timezone = null): void
103
    {
104
        try {
105 29
            $formatter = new IntlDateFormatter($locale, IntlDateFormatter::LONG, IntlDateFormatter::NONE, $timezone, IntlDateFormatter::GREGORIAN, $pattern);
106 29
            $value = $formatter->format($unixTimestamp);
107 1
        } catch (Error $e) {
108 1
            $value = "";
109 1
            $this->log("Unable to format date (locale $locale) [{$e->getMessage()}]", Project::MSG_WARN);
110
        } catch (ValueError $e) {
111
            $value = "";
112
            $this->log("Unable to create a date formatter (locale $locale) [{$e->getMessage()}]", Project::MSG_WARN);
113
        }
114 29
        $this->getProject()->setNewProperty($this->prefix . $propertyName, $value);
115
    }
116
117 29
    protected function getUnixTime(): int
118
    {
119
        // phing.tstamp.now.iso
120 29
        $property = $this->getProject()->getProperty('phing.tstamp.now.iso');
121 29
        if (null !== $property && '' !== $property) {
122
            try {
123 3
                $dateTime = new DateTime($property);
124
125 3
                return $dateTime->getTimestamp();
126
            } catch (Exception $e) {
127
                $this->log('magic property phing.tstamp.now.iso ignored as ' . $property . ' is not a valid number');
128
            }
129
        }
130
131
        // phing.tstamp.now
132 26
        $property = $this->getProject()->getProperty('phing.tstamp.now');
133 26
        if (null !== $property && '' !== $property) {
134 4
            $dateTime = DateTime::createFromFormat('U', $property);
135 4
            if ($dateTime instanceof DateTime) {
0 ignored issues
show
introduced by
$dateTime is always a sub-type of DateTime.
Loading history...
136 4
                return $dateTime->getTimestamp();
137
            }
138
            $this->log('magic property phing.tstamp.now ignored as ' . $property . ' is not a valid number');
139
        }
140
141 22
        return time();
142
    }
143
}
144