resolveTerritoryToCountries()   C
last analyzed

Complexity

Conditions 7
Paths 4

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 19
nc 4
nop 2
dl 0
loc 28
rs 6.7272
c 0
b 0
f 0
1
<?php
2
namespace Agavi\Config;
3
4
// +---------------------------------------------------------------------------+
5
// | This file is part of the Agavi package.                                   |
6
// | Copyright (c) 2005-2011 the Agavi Project.                                |
7
// |                                                                           |
8
// | For the full copyright and license information, please view the LICENSE   |
9
// | file that was distributed with this source code. You can also view the    |
10
// | LICENSE file online at http://www.agavi.org/LICENSE.txt                   |
11
// |   vi: set noexpandtab:                                                    |
12
// |   Local Variables:                                                        |
13
// |   indent-tabs-mode: t                                                     |
14
// |   End:                                                                    |
15
// +---------------------------------------------------------------------------+
16
17
18
use Agavi\Config\XmlConfigHandler;
19
use Agavi\Config\Util\Dom\XmlConfigDomDocument;
20
use Agavi\Date\DateDefinitions;
21
use Agavi\Exception\AgaviException;
22
23
/**
24
 * AgaviLdmlSupplementalConfigHandler allows you to parse ldml supplemental data
25
 * file into an array.
26
 *
27
 * @package    agavi
28
 * @subpackage config
29
 *
30
 * @author     Dominik del Bondio <[email protected]>
31
 * @author     David Zülke <[email protected]>
32
 * @copyright  Authors
33
 * @copyright  The Agavi Project
34
 *
35
 * @since      0.11.0
36
 *
37
 * @version    $Id$
38
 */
39
class LdmlSupplementalConfigHandler extends XmlConfigHandler
40
{
41
    /**
42
     * Execute this configuration handler.
43
     *
44
     * @param      XmlConfigDomDocument $document The document to parse.
45
     *
46
     * @return     string Data to be written to a cache file.
47
     *
48
     * @throws     <b>AgaviUnreadableException</b> If a requested configuration
49
     *                                             file does not exist or is not
50
     *                                             readable.
51
     * @throws     <b>AgaviParseException</b> If a requested configuration file is
52
     *                                        improperly formatted.
53
     *
54
     * @author     Dominik del Bondio <[email protected]>
55
     * @author     David Zülke <[email protected]>
56
     * @since      0.11.0
57
     */
58
    public function execute(XmlConfigDomDocument $document)
59
    {
60
        $dayMap = array(
61
            'sun' => DateDefinitions::SUNDAY,
62
            'mon' => DateDefinitions::MONDAY,
63
            'tue' => DateDefinitions::TUESDAY,
64
            'wed' => DateDefinitions::WEDNESDAY,
65
            'thu' => DateDefinitions::THURSDAY,
66
            'fri' => DateDefinitions::FRIDAY,
67
            'sat' => DateDefinitions::SATURDAY,
68
        );
69
70
        $dataTree = $document->documentElement;
71
72
        $parsedData = array();
73
        $data = array();
74
75
        foreach ($dataTree->getChild('currencyData') as $currencyNode) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DOMElement as the method getChild() does only exist in the following sub-classes of DOMElement: Agavi\Config\Util\Dom\XmlConfigDomElement. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
76
            if ($currencyNode->localName == 'fractions') {
77
                foreach ($currencyNode as $info) {
78
                    $data['fractions'][$info->getAttribute('iso4217')] = array(
79
                        'digits' => $info->getAttribute('digits', 2),
80
                        'rounding' => $info->getAttribute('rounding', 1),
81
                    );
82
                }
83
            } elseif ($currencyNode->localName == 'region') {
84
                foreach ($currencyNode as $currency) {
85
                    if ($currency->getName() == 'currency') {
86
                        $data['territories'][$currencyNode->getAttribute('iso3166')]['currencies'][$currency->getAttribute('iso4217')] = array(
87
                            'currency' => $currency->getAttribute('iso4217'),
88
                            'from' => $currency->getAttribute('from'),
89
                            'to' => $currency->getAttribute('to'),
90
                        );
91
                    } else {
92
                        throw new AgaviException('Invalid tag ' . $currency->localName . ' in region tag');
93
                    }
94
                }
95
            } else {
96
                throw new AgaviException('Invalid tag ' . $currencyNode->localName . ' in currencyData tag');
97
            }
98
        }
99
100
        foreach ($dataTree->getChild('territoryContainment') as $group) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DOMElement as the method getChild() does only exist in the following sub-classes of DOMElement: Agavi\Config\Util\Dom\XmlConfigDomElement. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
101
            if ($group->localName == 'group') {
102
                $data['territoryContainment'][$group->getAttribute('type')] = explode(' ', $group->getAttribute('contains'));
103
            } else {
104
                throw new AgaviException('Invalid tag ' . $group->localName . ' in territoryContainment tag');
105
            }
106
        }
107
108
        foreach ($dataTree->getChild('languageData') as $language) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DOMElement as the method getChild() does only exist in the following sub-classes of DOMElement: Agavi\Config\Util\Dom\XmlConfigDomElement. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
109
            if ($language->localName == 'language') {
110
                $lang = $language->getAttribute('type');
111
                $scripts = explode(' ', $language->getAttribute('scripts'));
112
                $territories = explode(' ', $language->getAttribute('territories'));
113
                $alt = $language->getAttribute('alt', 'primary');
114
115
                foreach ($scripts as $script) {
116
                    $parsedData['languages'][$lang][$alt][$script] = $territories;
117
                }
118
119
                foreach ($territories as $territory) {
120
                    $data['territories'][$territory]['languages'][$alt][$lang] = $scripts;
121
                }
122
            } else {
123
                throw new AgaviException('Invalid tag ' . $language->getName() . ' in languageData tag');
124
            }
125
        }
126
127
        // set the default calendar to gregorian for all territories first
128
        foreach ($data['territories'] as &$territoryData) {
129
            $territoryData['calendar'] = 'gregorian';
130
        }
131
132
        foreach ($dataTree->getChild('calendarData') as $calendar) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DOMElement as the method getChild() does only exist in the following sub-classes of DOMElement: Agavi\Config\Util\Dom\XmlConfigDomElement. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
133
            $type = $calendar->getAttribute('type');
134
            foreach (explode(' ', $calendar->getAttribute('territories')) as $territory) {
135
                $data['territories'][$territory]['calendar'] = $type;
136
            }
137
        }
138
139
        foreach ($dataTree->getChild('weekData') as $entry) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DOMElement as the method getChild() does only exist in the following sub-classes of DOMElement: Agavi\Config\Util\Dom\XmlConfigDomElement. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
140
            $entryName = $entry->localName;
141
            if ($entryName == 'minDays') {
142 View Code Duplication
                foreach (explode(' ', $entry->getAttribute('territories')) as $territory) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
143
                    $countries = $this->resolveTerritoryToCountries($data['territoryContainment'], $territory);
144
                    foreach ($countries as $country) {
145
                        $data['territories'][$country]['week'][$entryName] = $entry->getAttribute('count');
146
                    }
147
                }
148
            } elseif ($entryName == 'firstDay' || $entryName == 'weekendStart' || $entryName == 'weekendEnd') {
149
                if (!$entry->hasAttribute('alt')) {
150 View Code Duplication
                    foreach (explode(' ', $entry->getAttribute('territories')) as $territory) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
151
                        $countries = $this->resolveTerritoryToCountries($data['territoryContainment'], $territory);
152
                        foreach ($countries as $country) {
153
                            $data['territories'][$country]['week'][$entryName] = $dayMap[$entry->getAttribute('day')];
154
                        }
155
                    }
156
                }
157
            } else {
158
                throw new AgaviException('Invalid tag ' . $entry->localName . ' in weekData tag');
159
            }
160
        }
161
162
        $data['timezones'] = array('territories' => array(), 'multiZones' => array());
163
        foreach (explode(' ', $dataTree->getChild('timezoneData')->getChild('zoneFormatting')->getAttribute('multizone')) as $zone) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DOMElement as the method getChild() does only exist in the following sub-classes of DOMElement: Agavi\Config\Util\Dom\XmlConfigDomElement. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
164
            $data['timezones']['multiZones'][$zone] = true;
165
        }
166
167
        foreach ($dataTree->getChild('timezoneData')->getChild('zoneFormatting') as $zoneItem) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DOMElement as the method getChild() does only exist in the following sub-classes of DOMElement: Agavi\Config\Util\Dom\XmlConfigDomElement. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
168
            if ($zoneItem->localName == 'zoneItem') {
169
                $zone = $zoneItem->getAttribute('type');
170
                $territory = $zoneItem->getAttribute('territory');
171
                $data['timezones']['territories'][$zone] = $territory;
172
            } else {
173
                throw new AgaviException('Invalid tag ' . $language->localName . ' in zoneFormatting tag');
174
            }
175
        }
176
177
        $code = array();
178
        $code[] = 'return ' . var_export($data, true) . ';';
179
180
        return $this->generate($code, $document->documentURI);
181
    }
182
183
    protected function resolveTerritoryToCountries($territoryContainments, $territory)
184
    {
185
        if (!isset($territoryContainments[$territory])) {
186
            return (array) $territory;
187
        }
188
        $resultCountries = array();
189
        
190
        $territories = $territoryContainments[$territory];
191
        do {
192
            $newTerrs = array();
193
            foreach ($territories as $terr) {
194
                if (isset($territoryContainments[$terr])) {
195
                    foreach ($territoryContainments[$terr] as $resolvedTerr) {
196
                        if (is_numeric($resolvedTerr)) {
197
                            $newTerrs[] = $resolvedTerr;
198
                        } else {
199
                            $resultCountries[] = $resolvedTerr;
200
                        }
201
                    }
202
                } else {
203
                    $resultCountries[] = $terr;
204
                }
205
            }
206
            $territories = $newTerrs;
207
        } while (count($territories));
208
209
        return $resultCountries;
210
    }
211
}
212