Passed
Branch main (2e4b54)
by Andreas
10:30
created

createIteratorFromXmlFile()   B

Complexity

Conditions 10
Paths 11

Size

Total Lines 36
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 36
rs 7.6666
cc 10
nc 11
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Copyright (c) Andreas Heigl<[email protected]>
7
 *
8
 * Permission is hereby granted, free of charge, to any person obtaining a copy
9
 * of this software and associated documentation files (the "Software"), to deal
10
 * in the Software without restriction, including without limitation the rights
11
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
 * copies of the Software, and to permit persons to whom the Software is
13
 * furnished to do so, subject to the following conditions:
14
 *
15
 * The above copyright notice and this permission notice shall be included in
16
 * all copies or substantial portions of the Software.
17
 *
18
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
 * THE SOFTWARE.
25
 *
26
 * @author    Andreas Heigl<[email protected]>
27
 * @copyright Andreas Heigl
28
 * @license   http://www.opensource.org/licenses/mit-license.php MIT-License
29
 * @since     09.03.2017
30
 * @link      http://github.com/heiglandreas/org.heigl.Holidaychecker
31
 */
32
33
namespace Org_Heigl\Holidaychecker;
34
35
use DOMDocument;
36
use DOMElement;
37
use Exception;
38
use Org_Heigl\Holidaychecker\IteratorItem\Date;
39
use Org_Heigl\Holidaychecker\IteratorItem\DateFollowUp;
40
use Org_Heigl\Holidaychecker\IteratorItem\Easter;
41
use Org_Heigl\Holidaychecker\IteratorItem\EasterOrthodox;
42
use Org_Heigl\Holidaychecker\IteratorItem\Relative;
43
use RuntimeException;
44
use Throwable;
45
use UnexpectedValueException;
46
use function explode;
47
use function is_readable;
48
use function sprintf;
49
50
class HolidayIteratorFactory
51
{
52
    /**
53
     * Create a HolidayIterator from an XML-File
54
     *
55
     * The provided XML-File has to validate against the holiday.xsd-file you
56
     * can find in this projects "share" folder.
57
     *
58
     * @param string $file
59
     *
60
     * @return HolidayIterator
61
     */
62
    public function createIteratorFromXmlFile(string $file): HolidayIterator
63
    {
64
        $iterator = new HolidayIterator();
65
66
        $dom = new DOMDocument('1.0', 'UTF-8');
67
        $dom->load($file);
68
        $dom->xinclude();
69
70
        if (! @$dom->schemaValidate(__DIR__ . '/../share/holidays.xsd')) {
71
            throw new Exception('XML-File does not validate agains schema');
72
        }
73
        foreach ($dom->documentElement->childNodes as $child) {
74
            if (! $child instanceof DOMElement) {
75
                continue;
76
            }
77
            if ($child->nodeName === 'resources') {
78
                continue;
79
            }
80
81
			try {
82
				$element = $this->getElement($child);
83
				if ($child->hasAttribute('firstobservance') || $child->hasAttribute('lastobservance')) {
84
					$element = new ObservanceDecorator(
85
						$element,
86
						$child->hasAttribute('firstobservance') ? (int) $child->getAttribute('firstobservance') : null,
87
						$child->hasAttribute('lastobservance') ? (int) $child->getAttribute('lastobservance') : null,
88
					);
89
				}
90
91
				$iterator->append($element);
92
			} catch (Throwable $e) {
93
				// Do nothing on purpose
94
			}
95
        }
96
97
        return $iterator;
98
    }
99
100
    /**
101
     * Create a HolidayIterator from an ISO 3166-code.
102
     *
103
     * @param string $isoCode
104
     *
105
     * @return HolidayIterator
106
     */
107
    public function createIteratorFromISO3166(string $isoCode): HolidayIterator
108
    {
109
        $file = __DIR__ . '/../share/%s.xml';
110
        $file1 = sprintf($file, $isoCode);
111
112
        if (! is_readable($file1)) {
113
            throw new UnexpectedValueException(sprintf(
114
                'There is no holiday-file for %s',
115
                $isoCode
116
            ));
117
        }
118
119
        return self::createIteratorFromXmlFile($file1);
0 ignored issues
show
Bug Best Practice introduced by
The method Org_Heigl\Holidaychecker...teIteratorFromXmlFile() is not static, but was called statically. ( Ignorable by Annotation )

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

119
        return self::/** @scrutinizer ignore-call */ createIteratorFromXmlFile($file1);
Loading history...
120
    }
121
122
    private function getElement(DOMElement $child): HolidayIteratorItemInterface
123
    {
124
        switch ($child->nodeName) {
125
            case 'easter':
126
                return new Easter(
127
                    $child->textContent,
128
                    $this->getFree($child),
129
                    (int) $child->getAttribute('offset')
130
                );
131
            case 'easterorthodox':
132
                return new EasterOrthodox(
133
                    $child->textContent,
134
                    $this->getFree($child),
135
                    (int) $child->getAttribute('offset')
136
                );
137
            case 'date':
138
                $day = CalendarDayFactory::createCalendarDay(
139
                    (int) $child->getAttribute('day'),
140
                    (int) $child->getAttribute('month'),
141
                    ($child->hasAttribute('calendar')?$child->getAttribute('calendar'): 'gregorian')
142
                );
143
                if ($child->hasAttribute('year')) {
144
                    $day->setYear((int) $child->getAttribute('year'));
145
                }
146
                return new Date(
147
                    $child->textContent,
148
                    $this->getFree($child),
149
                    $day,
150
                    $child->hasAttribute('forwardto')?$child->getAttribute('forwardto'):'',
151
                    $child->hasAttribute('forwardwhen')?explode(' ', $child->getAttribute('forwardwhen')):[],
152
                    $child->hasAttribute('rewindto')?$child->getAttribute('rewindto'):'',
153
                    $child->hasAttribute('rewindwhen')?explode(' ', $child->getAttribute('rewindwhen')):[],
154
                );
155
            case 'dateFollowUp':
156
                $day = CalendarDayFactory::createCalendarDay(
157
                    (int) $child->getAttribute('day'),
158
                    (int) $child->getAttribute('month'),
159
                    ($child->hasAttribute('calendar')?$child->getAttribute('calendar'): 'gregorian')
160
                );
161
162
                return new DateFollowUp(
163
                    $child->textContent,
164
                    $this->getFree($child),
165
                    $day,
166
                    $child->getAttribute('followup'),
167
                    ($child->hasAttribute('replaced')?explode(' ', $child->getAttribute('replaced')):[])
168
                );
169
            case 'relative':
170
                return new Relative(
171
                    $child->textContent,
172
                    $this->getFree($child),
173
                    (int) $child->getAttribute('day'),
174
                    (int) $child->getAttribute('month'),
175
                    $child->getAttribute('relation')
176
                );
177
            default:
178
                throw new RuntimeException('Unknown element encountered');
179
        }
180
	}
181
182
    private function getFree(DOMElement $element): bool
183
    {
184
        return ($element->getAttribute('free') === "true");
185
    }
186
}
187