Completed
Push — master ( 63e741...02cbf4 )
by
unknown
04:16
created

BuiltInFunctionsExtension::startOfYear()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 15
rs 9.4286
cc 2
eloc 8
nc 2
nop 1
1
<?php
2
3
namespace Netdudes\DataSourceryBundle\Extension;
4
5
use Netdudes\DataSourceryBundle\Extension\Type\TableBundleFunctionExtension;
6
use Netdudes\DataSourceryBundle\Util\CurrentDateTimeProvider;
7
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
8
9
class BuiltInFunctionsExtension extends AbstractTableBundleExtension
10
{
11
    /**
12
     * @var TokenStorageInterface
13
     */
14
    private $tokenStorage;
15
16
    /**
17
     * @var CurrentDateTimeProvider
18
     */
19
    private $dateTimeProvider;
20
21
    /**
22
     * @param TokenStorageInterface   $tokenStorage
23
     * @param CurrentDateTimeProvider $dateTimeProvider
24
     */
25
    public function __construct(TokenStorageInterface $tokenStorage, CurrentDateTimeProvider $dateTimeProvider)
26
    {
27
        $this->tokenStorage = $tokenStorage;
28
        $this->dateTimeProvider = $dateTimeProvider;
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function getName()
35
    {
36
        return 'table_bundle_extension_built_in';
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function getFunctions()
43
    {
44
        return [
45
            new TableBundleFunctionExtension('now', $this, 'now'),
46
            new TableBundleFunctionExtension('startOfDay', $this, 'startOfDay'),
47
            new TableBundleFunctionExtension('startOfWeek', $this, 'startOfWeek'),
48
            new TableBundleFunctionExtension('startOfMonth', $this, 'startOfMonth'),
49
            new TableBundleFunctionExtension('startOfYear', $this, 'startOfYear'),
50
            new TableBundleFunctionExtension('currentUser', $this, 'currentUser'),
51
            new TableBundleFunctionExtension('random', $this, 'random')
52
        ];
53
    }
54
55
    /**
56
     * Gets the current timestamp, with an offset string
57
     *
58
     * @param string $offset
59
     *
60
     * @return string
61
     * @throws \Exception
62
     */
63
    public function now($offset = null)
64
    {
65
        $now = clone $this->dateTimeProvider->get();
66
67
        if ($offset) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $offset of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
68
            $interval = \DateInterval::createFromDateString($offset);
69
            $now->add($interval);
70
71
            if ($now == $this->dateTimeProvider->get()) {
72
                // The date didn't change therefore we assume the given offset is not valid
73
                throw new \Exception($offset . ' is not a valid date/time interval.');
74
            }
75
        }
76
77
        return $now->format(\DateTime::ISO8601);
78
    }
79
80
    /**
81
     * Gets a date with the hour 00:00:00
82
     *
83
     * @param string $date
84
     *
85
     * @return string
86
     * @throws \Exception
87
     */
88
    public function startOfDay($date = null)
89
    {
90
        $now = clone $this->dateTimeProvider->get();
91
92
        if ($date) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $date of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
93
            $now = $this->modifyDate($now, $date);
94
        }
95
96
        $now->setTime(0, 0, 0);
97
98
        return $now->format(\DateTime::ISO8601);
99
    }
100
101
    /**
102
     * Gets the Monday of the week for the specified date with the hour 00:00:00
103
     *
104
     * @param string $date
105
     *
106
     * @return string
107
     * @throws \Exception
108
     */
109 View Code Duplication
    public function startOfWeek($date = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
    {
111
        $now = clone $this->dateTimeProvider->get();
112
113
        if ($date) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $date of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
114
            $now = $this->modifyDate($now, $date);
115
        }
116
117
        $year = $now->format('o'); // o = ISO-8601 year number
118
        $week = $now->format('W'); // W = ISO-8601 week number of year, weeks starting on Monday
119
120
        $startOfWeek = $now->setISODate($year, $week);
121
        $startOfWeek->setTime(0, 0, 0);
122
123
        return $startOfWeek->format(\DateTime::ISO8601);
124
    }
125
126
    /**
127
     * Gets the first day of the month for the specified date with the hour 00:00:00
128
     *
129
     * @param string $date
130
     *
131
     * @return string
132
     * @throws \Exception
133
     */
134 View Code Duplication
    public function startOfMonth($date = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
135
    {
136
        $now = clone $this->dateTimeProvider->get();
137
138
        if ($date) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $date of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
139
            $now = $this->modifyDate($now, $date);
140
        }
141
142
        $year = $now->format('Y');
143
        $month = $now->format('m');
144
145
        $startOfMonth = $now->setDate($year, $month, 1);
146
        $startOfMonth->setTime(0, 0, 0);
147
148
        return $startOfMonth->format(\DateTime::ISO8601);
149
    }
150
151
    /**
152
     * Gets the first day of the year for the specified date with the hour 00:00:00
153
     *
154
     * @param string $date
155
     *
156
     * @return string
157
     * @throws \Exception
158
     */
159
    public function startOfYear($date = null)
160
    {
161
        $now = clone $this->dateTimeProvider->get();
162
163
        if ($date) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $date of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
164
            $now = $this->modifyDate($now, $date);
165
        }
166
167
        $year = $now->format('Y');
168
169
        $startOfYear = $now->setDate($year, 1, 1);
170
        $startOfYear->setTime(0, 0, 0);
171
172
        return $startOfYear->format(\DateTime::ISO8601);
173
    }
174
175
    /**
176
     * Gets the current users' username
177
     *
178
     * @return string
179
     */
180
    public function currentUser()
181
    {
182
        return $this->tokenStorage->getToken()->getUsername();
183
    }
184
185
    /**
186
     * Gets a random value between $min and $max
187
     *
188
     * @param int $min
189
     * @param int $max
190
     *
191
     * @return int
192
     */
193
    public function random($min = 0, $max = 10)
194
    {
195
        return rand($min, $max);
196
    }
197
198
    /**
199
     * @param \DateTime $date
200
     * @param string    $change
201
     *
202
     * @return \DateTime
203
     * @throws \Exception
204
     */
205
    private function modifyDate(\DateTime $date, $change)
206
    {
207
        try {
208
            $date->modify($change);
209
        } catch (\Exception $e) {
210
            throw new \Exception($change . ' is not a valid date or date offset.');
211
        }
212
213
        return ($date);
214
    }
215
}
216