Completed
Push — master ( 197347...f6fd8e )
by mehdi
02:04
created

Datium::setConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 8
rs 9.4285
c 1
b 0
f 0
cc 1
eloc 5
nc 1
nop 1
1
<?php
2
/**
3
 * Main Datium class
4
 *
5
 * @category Core
6
 * @package  OpenCafe\Datium
7
 * @author   Mehdi Hosseini <[email protected]>
8
 * @license  License https://opensource.org/licenses/MIT
9
 * @link     https://github.com/opencafe/datium
10
 * @since    Aug 17, 2015
11
 */
12
13
namespace OpenCafe;
14
15
use DateTime;
16
use DateInterval;
17
use OpenCafe\Tools\Convert;
18
use OpenCafe\Tools\Leap;
19
use OpenCafe\Tools\DayOf;
20
use OpenCafe\Tools\Lang;
21
use OpenCafe\Tools\SimpleDiff;
22
23
/**
24
 * Main Datium class
25
 *
26
 * @category Core
27
 * @package  OpenCafe\Datium
28
 * @author   Mehdi Hosseini <[email protected]>
29
 * @license  icense https://opensource.org/licenses/MIT
30
 * @link     https://github.com/opencafe/datium
31
 * @since    Aug 17, 2015
32
 */
33
class Datium
34
{
35
36
    /**
37
     * Store DateTime object
38
     */
39
    protected $date_time;
40
41
    protected static $static_date_time;
42
43
    /**
44
     * Store config file statements
45
     *
46
     * @param array
47
     */
48
    protected $config;
49
50
    protected $date_interval_expression;
51
52
    protected static $date_start;
53
54
    protected static $date_end;
55
56
    protected $translate_from;
57
58
    protected $translate_to;
59
60
    protected $toConfig;
61
62
    protected $fromConfig;
63
64
    /**
65
     * Return store day number
66
     *
67
     * @param integer
68
     */
69
    protected $day_of;
70
71
    protected $leap;
72
73
    protected $events;
74
75
    protected $translate;
76
77
    protected $gregorian_DayofWeek;
78
79
    protected $convert_calendar;
80
81
    protected $calendar_type;
82
83
    protected static $array_date;
84
85
    protected static $call_type;
86
87
    protected $translate_from_file;
88
89
    protected $translate_to_file;
90
91
    protected $language;
92
93
    protected static $timestamp;
94
95
    /**
96
     * SimpleDiff
97
     *
98
     * @param integer
99
     */
100
    protected $simpleDiff;
101
102
    /**
103
     * Datium class constructure
104
     */
105
    public function __construct()
106
    {
107
108
        $this->language = 'en';
109
110
        $this->translate_from = 'gregorian';
111
112
        $this->translate_to = 'gregorian';
113
        $this->setConfig();
114
115
        $this->calendar_type = $this->config['default_calendar'];
116
117
        $this->calendar_type = 'gregorian';
118
119
        switch (Datium::$call_type) {
120
121
122
            case 'create-timestamp':
123
124
                $this->date_time = new DateTime();
125
126
                $this->date_time->setTimestamp(self::$timestamp);
127
128
                break;
129
130
            case 'now':
131
132
                $this->date_time = new DateTime('now');
133
134
                break;
135
136
            case 'make':
137
138
                $this->date_time = new DateTime('now');
139
140
                $this->date_time->setDate(
141
                    self::$array_date['year'],
142
                    self::$array_date['month'],
143
                    self::$array_date['day']
144
                );
145
146
                $this->date_time->setTime(
147
                    self::$array_date['hour'],
148
                    self::$array_date['minute'],
149
                    self::$array_date['second']
150
                );
151
152
                break;
153
154
            case 'set':
155
156
                $this->date_time = Datium::$static_date_time;
157
158
        }
159
160
        $this->gregorian_DayofWeek = $this->date_time->format('w');
161
162
        $this->convert_calendar = new Convert();
163
164
    }
165
166
    /**
167
     * Return all datetime parts as an object
168
     *
169
     * @return object
170
     */
171
    public function all()
172
    {
173
174
        return ( object )array(
175
176
            'second' => $this->date_time->format('s'),
177
178
            'minute' => $this->date_time->format('m'),
179
180
            'hour' => $this->date_time->format('H'),
181
182
            'day' => $this->date_time->format('d'),
183
184
            'month' => $this->date_time->format('m'),
185
186
            'year' => $this->date_time->format('Y')
187
188
        );
189
190
    }
191
192
    /**
193
     * Get current datetime
194
     *
195
     * @since  Aug 17 2015
196
     * @return object
197
     */
198
    public static function now()
199
    {
200
201
        self::$call_type = 'now';
202
203
        return new Datium();
204
205
    }
206
207
    /**
208
     * Set config
209
     *
210
     * @since June 28 2016
211
     *
212
     * @param array $config
213
     *
214
     * @return $this
215
     */
216
    public function setConfig($config = [])
217
    {
218
        $defaults     = include(__DIR__.'/Config.php');
219
        $this->config = array_merge($defaults, $config);
220
        date_default_timezone_set($this->config['timezone']);
221
222
        return $this;
223
    }
224
225
    /**
226
     * Create new date time
227
     *
228
     * @param integer $year   Year number
229
     * @param integer $month  month number
230
     * @param integer $day    day number
231
     * @param integer $hour   hour number
232
     * @param integer $minute minute number
233
     * @param integer $second second number
234
     *
235
     * @return object
236
     */
237
    public static function create(
238
        $year = 2000,
239
        $month = 1,
240
        $day = 1,
241
        $hour = 0,
242
        $minute = 0,
243
        $second = 0
244
    ) {
245
246
        /**
247
         * When we want to set a Datetime object to Datium
248
         */
249
        if (func_num_args() === 1) {
250
            self::$static_date_time = func_get_arg(0);
251
252
            self::$call_type = 'set';
253
        } else {
254
            self::$array_date = array(
255
                'year'   => $year,
256
                'month'  => $month,
257
                'day'    => $day,
258
                'hour'   => $hour,
259
                'minute' => $minute,
260
                'second' => $second
261
            );
262
263
            self::$call_type = 'make';
264
        }
265
266
        return new Datium();
267
268
    }
269
270
    /**
271
     * Accept Timestamp as Datium initializion
272
     *
273
     * @param  timestamp $timestamp Input timestamp value
274
     *
275
     * @return object
276
     */
277
    public static function createTimestamp($timestamp)
278
    {
279
280
        if ($timestamp != null && is_int($timestamp)) {
281
282
            self::$call_type = 'create-timestamp';
283
284
            self::$timestamp = $timestamp;
285
286
            return new Datium();
287
288
        } else {
289
290
            throw new \Exception("Error timestamp is not entered in true format", 1);
291
292
        }
293
294
295
    }
296
297
    /**
298
     * Select The range between two date object
299
     *
300
     * @param object $date_start Start of the DateTime
301
     * @param object $date_end   End of the DateTime
302
     *
303
     * @return object
304
     */
305
    public static function between($date_start, $date_end)
306
    {
307
308
        self::$date_start = $date_start;
309
310
        self::$date_end = $date_end;
311
312
        self::$call_type = 'between';
313
314
        return new Datium();
315
316
    }
317
318
    /**
319
     * Convert from current calendar, what type is current calendar?
320
     *
321
     * @param object $calendar Assigned calendar to start from
322
     *
323
     * @return $object
0 ignored issues
show
Documentation introduced by
The doc-type $object could not be parsed: Unknown type name "$object" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
324
     */
325 View Code Duplication
    public function from($calendar)
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...
326
    {
327
328
        $this->convert = new Convert($this->date_time);
0 ignored issues
show
Bug introduced by
The property convert does not seem to exist. Did you mean convert_calendar?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
329
330
        $this->date_time = $this->convert->from($calendar);
0 ignored issues
show
Bug introduced by
The property convert does not seem to exist. Did you mean convert_calendar?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
331
332
333
        /**
334
         * We need this part for DayOf class
335
         */
336
        $this->calendar_type = $calendar;
337
338
        $this->translate_to = $calendar;
339
340
        return $this;
341
342
    }
343
344
    /**
345
     * Convert date to current Date
346
     *
347
     * @param object $calendar Assigned calendar to when calendar should start.
348
     *
349
     * @return object
350
     */
351 View Code Duplication
    public function to($calendar)
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...
352
    {
353
354
        $this->convert = new Convert($this->date_time);
0 ignored issues
show
Bug introduced by
The property convert does not seem to exist. Did you mean convert_calendar?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
355
356
        $this->date_time = $this->convert->to($calendar);
0 ignored issues
show
Bug introduced by
The property convert does not seem to exist. Did you mean convert_calendar?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
357
358
        /**
359
         * We need this part for DayOf class
360
         */
361
        $this->calendar_type = $calendar;
362
363
        $this->translate_to = $calendar;
364
365
        return $this;
366
367
    }
368
369
    /**
370
     * Difference between two time
371
     *
372
     * @param DateTime $start Start of the date
373
     * @param DateTime $end   End of the date
374
     *
375
     * @return object
376
     */
377
    public static function diff($start, $end)
378
    {
379
380
        $difference = date_diff($start, $end);
381
382
        $difference->second = $difference->s;
383
384
        $difference->minute = $difference->i;
385
386
        $difference->hour = $difference->h;
387
388
        $difference->day = $difference->d;
389
390
        $difference->month = $difference->m;
391
392
        $difference->year = $difference->y;
393
394
        $difference->simple = ( new SimpleDiff( $start, $end, $difference ) );
395
396
        return $difference;
397
398
    }
399
400
    /**
401
     * Add new date value to current date
402
     *
403
     * @param string $value How much date should be added to current date
404
     *
405
     * @return object
406
     */
407 View Code Duplication
    public function add($value)
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...
408
    {
409
410
        $this->date_interval_expression = str_replace(
411
            $this->config['date_simple'],
412
            $this->config['date_interval'],
413
            $value
414
        );
415
416
        $unit = 'P';
417
418
        if (strpos($this->date_interval_expression, 'T')) {
419
            $this->date_interval_expression = str_replace(
420
                'T',
421
                '',
422
                $this->date_interval_expression
423
            );
424
425
            $unit = 'PT';
426
        }
427
428
        $this->date_interval_expression = str_replace(
429
            ' ',
430
            '',
431
            $unit.$this->date_interval_expression
432
        );
433
434
        $this->date_time->add(
435
            new DateInterval($this->date_interval_expression)
436
        );
437
438
        return $this;
439
440
    }
441
442
    /**
443
     * Sub date from current date
444
     *
445
     * @param string $value How much date should increase from current date
446
     *
447
     * @return obejct
448
     */
449 View Code Duplication
    public function sub($value)
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...
450
    {
451
452
        $this->date_interval_expression = str_replace(
453
            $this->config['date_simple'],
454
            $this->config['date_interval'],
455
            $value
456
        );
457
458
        $unit = 'P';
459
460
        if (strpos($this->date_interval_expression, 'T')) {
461
            $this->date_interval_expression = str_replace(
462
                'T',
463
                '',
464
                $this->date_interval_expression
465
            );
466
467
            $unit = 'PT';
468
        }
469
470
        $this->date_interval_expression = str_replace(
471
            ' ',
472
            '',
473
            $unit.$this->date_interval_expression
474
        );
475
476
        $this->date_time->sub(
477
            new DateInterval($this->date_interval_expression)
478
        );
479
480
        return $this;
481
482
    }
483
484
    /**
485
     * Check if current year is leap or not
486
     *
487
     * @param string $type Name of the calendar to caculate leap year
0 ignored issues
show
Bug introduced by
There is no parameter named $type. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
488
     *
489
     * @return boolean
490
     */
491
    public function leap()
492
    {
493
494
        $this->leap = new Leap($this->date_time->format('Y'), $this->calendar_type);
0 ignored issues
show
Bug introduced by
It seems like $this->calendar_type can also be of type object; however, OpenCafe\Tools\Leap::__construct() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
495
496
        return $this->leap;
497
498
    }
499
500
    /**
501
     * Caculate day of year or week
502
     *
503
     * @since Aug, 22 2015
504
     *
505
     * @return integer
506
     */
507
    public function dayOf()
508
    {
509
510
        $this->day_of = new DayOf($this->date_time, $this->calendar_type);
0 ignored issues
show
Bug introduced by
It seems like $this->calendar_type can also be of type object; however, OpenCafe\Tools\DayOf::__construct() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
511
512
        return $this->day_of;
513
514
    }
515
516
    // public function events()
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
517
    // {
518
    //
519
    //     if (Datium::$call_type == 'between' ) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
520
    //
521
    //         $this->events = new Events(Datium::$date_start, Datium::$date_end);
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
522
    //
523
    //     } else {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
524
    //
525
    //         $this->events = new Events($this->date_time);
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
526
    //
527
    //     }
528
    //
529
    //     return $this->events;
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
530
    //
531
    // }
532
533
    /**
534
     * Return Datetime as a original object
535
     *
536
     * @since Oct 22, 2015
537
     *
538
     * @return object
539
     */
540
    public function object()
541
    {
542
543
        return $this->date_time;
544
545
    }
546
547
    /**
548
     * Translate current date string to selected language
549
     *
550
     * @param string $language language short name fa, en, ar ...
551
     *
552
     * @return object
553
     */
554
    public function lang($language = 'fa')
555
    {
556
557
        $this->language = $language;
558
559
        $this->result = new Lang();
0 ignored issues
show
Bug introduced by
The property result does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
560
561
        $this->result->setConfig($this->language);
562
563
        $this->toConfig = $this->result->getConfig();
564
565
        return $this;
566
567
    }
568
569
    /**
570
     * Return object as timestamp
571
     *
572
     * @return timestamp
573
     */
574
    public function timestamp()
575
    {
576
577
        return strtotime($this->date_time->format('Y-m-d H:i:s'));
578
579
    }
580
581
    /**
582
     * Return fainal result
583
     *
584
     * @param string $format Date format
585
     *
586
     * @since Aug 17 2015
587
     *
588
     * @return string
589
     */
590
    public function get($format = 'Y-m-d H:i:s')
591
    {
592
593
        // $this->translate_from_file = include( 'Lang/en/general.php' );
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
594
        //
595
        // $this->translate_to_file = include( 'Lang/' . $this->language . '/general.php' );
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
596
597
        if (is_null($this->fromConfig)) {
598
            $this->fromConfig = include __DIR__.'/CalendarSettings/'.
599
                                        ucfirst($this->translate_from).'.php';
600
        }
601
602
603
        if (is_null($this->toConfig)) {
604
            $this->toConfig = include __DIR__.'/CalendarSettings/'.
605
                                      ucfirst($this->translate_to).'.php';
606
        }
607
608
        $string_date = $this->date_time->format($format);
609
610
        if ($this->translate_to != 'gregorian') {
611
            $string_date = str_replace(
612
                $this->fromConfig['month'],
613
                $this->toConfig['month'],
614
                $string_date
615
            );
616
617
            $string_date = str_replace(
618
                $this->fromConfig['days_of_week'],
619
                $this->toConfig['days_of_week'][$this->gregorian_DayofWeek],
620
                $string_date
621
            );
622
623
            $string_date = str_replace(
624
                $this->fromConfig['numbers'],
625
                $this->toConfig['numbers'],
626
                $string_date
627
            );
628
629
            $string_date = str_replace(
630
                $this->fromConfig['am_time'],
631
                $this->toConfig['am_time'],
632
                $string_date
633
            );
634
635
            $string_date = str_replace(
636
                $this->fromConfig['pm_time'],
637
                $this->toConfig['pm_time'],
638
                $string_date
639
            );
640
641
            $string_date = str_replace(
642
                $this->fromConfig['end_of_days'],
643
                $this->toConfig['end_of_days'],
644
                $string_date
645
            );
646
        }
647
648
        return $string_date;
649
650
    }
651
}
652