Passed
Push — multiproject/local-access ( 5353e5 )
by Simon
04:56
created

DomainAccessManager::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
/******************************************************************************
3
 * Wikipedia Account Creation Assistance tool                                 *
4
 *                                                                            *
5
 * All code in this file is released into the public domain by the ACC        *
6
 * Development Team. Please see team.json for a list of contributors.         *
7
 ******************************************************************************/
8
9
namespace Waca\Security;
10
11
use Waca\DataObject;
12
use Waca\DataObjects\Domain;
13
use Waca\DataObjects\User;
14
use Waca\Exceptions\DomainSwitchNotAllowedException;
15
use Waca\Helpers\PreferenceManager;
16
use Waca\WebRequest;
17
18
class DomainAccessManager implements IDomainAccessManager
19
{
20
    /**
21
     * @param User $user
22
     *
23
     * @return Domain[]
24
     */
25
    public function getAllowedDomains(User $user): array
26
    {
27
        if ($user->isCommunityUser()) {
28
            return [];
29
        }
30
31
        return Domain::getDomainByUser($user->getDatabase(), $user, true);
32
    }
33
34
    public function switchDomain(User $user, Domain $newDomain): void
35
    {
36
        $mapToId = function(DataObject $object) {
37
            return $object->getId();
38
        };
39
40
        $allowed = in_array($newDomain->getId(), array_map($mapToId, $this->getAllowedDomains($user)));
41
42
        if ($allowed) {
43
            WebRequest::setActiveDomain($newDomain);
44
        }
45
        else {
46
            throw new DomainSwitchNotAllowedException();
47
        }
48
    }
49
50
    public function switchToDefaultDomain(User $user): void
51
    {
52
        $domains = $this->getAllowedDomains($user);
53
        $preferenceManager = new PreferenceManager($user->getDatabase(), $user->getId(), null);
54
        $defaultDomainPreference = $preferenceManager->getPreference(PreferenceManager::PREF_DEFAULT_DOMAIN);
55
56
        $chosenDomain = null;
57
        foreach ($domains as $d) {
58
            if ($d->getId() == $defaultDomainPreference) {
59
                $chosenDomain = $d;
60
                break;
61
            }
62
        }
63
64
        if ($chosenDomain !== null) {
65
            WebRequest::setActiveDomain($chosenDomain);
66
            return;
67
        }
68
69
        if (count($domains) > 0) {
70
            WebRequest::setActiveDomain($domains[0]);
71
        }
72
    }
73
}