Issues (19)

src/Eloquent/Concerns/ChronosTimestamps.php (1 issue)

Labels
Severity
1
<?php
2
3
namespace Cino\LaravelChronos\Eloquent\Concerns;
4
5
use Cake\Chronos\Chronos;
6
use Cake\Chronos\ChronosInterface;
7
use DateTimeInterface;
8
9
trait ChronosTimestamps
10
{
11
    /**
12
     * Return a timestamp as DateTime object with time set to 00:00:00.
13
     *
14
     * @param mixed $value
15
     * @return \Cake\Chronos\Chronos
16
     */
17
    protected function asDate($value)
18
    {
19
        return $this->asDateTime($value)->startOfDay();
20
    }
21
22
    /**
23
     * Return a timestamp as DateTime object.
24
     *
25
     * @param mixed $value
26
     * @return \Cake\Chronos\Chronos
27
     */
28 16
    public function asDateTime($value)
29
    {
30
        // If this value is already a Chronos instance, we shall just return it as is.
31
        // This prevents us having to re-instantiate a Chronos instance when we know
32
        // it already is one, which wouldn't be fulfilled by the DateTime check.
33 16
        if ($value instanceof ChronosInterface) {
34 10
            return $value;
35
        }
36
37
        // If the value is already a DateTime instance, we will just skip the rest of
38
        // these checks since they will be a waste of time, and hinder performance
39
        // when checking the field. We will just return the DateTime right away.
40 15
        if ($value instanceof DateTimeInterface) {
41 2
            return Chronos::instance($value);
42
        }
43
44
        // If this value is an integer, we will assume it is a UNIX timestamp's value
45
        // and format a Carbon object from this timestamp. This allows flexibility
46
        // when defining your date fields as they might be UNIX timestamps here.
47 13
        if (is_numeric($value)) {
48 1
            return Chronos::createFromTimestamp($value);
49
        }
50
51
        // If the value is in simply year, month, day format, we will instantiate the
52
        // Chronos instances from that format. Again, this provides for simple date
53
        // fields on the database.
54 12
        if ($this->isStandardDateFormat($value)) {
0 ignored issues
show
It seems like isStandardDateFormat() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

54
        if ($this->/** @scrutinizer ignore-call */ isStandardDateFormat($value)) {
Loading history...
55 1
            return Chronos::createFromFormat('Y-m-d', $value)->startOfDay();
56
        }
57
58
        // If everything else try parsing.
59 11
        return Chronos::parse($value);
60
    }
61
62
    /**
63
     * @return \Cake\Chronos\Chronos
64
     */
65 10
    public function freshTimestamp()
66
    {
67 10
        return new Chronos;
68
    }
69
}
70