Completed
Push — master ( fa30b9...467c9d )
by Bart
15s queued 10s
created

SiteDataType::clearEmptyGroups()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 0
crap 12
1
<?php
2
3
namespace NerdsAndCompany\Schematic\DataTypes;
4
5
use Craft;
6
use NerdsAndCompany\Schematic\Schematic;
7
8
/**
9
 * Schematic Sites DataType.
10
 *
11
 * Sync Craft Setups.
12
 *
13
 * @author    Nerds & Company
14
 * @copyright Copyright (c) 2015-2018, Nerds & Company
15
 * @license   MIT
16
 *
17
 * @see      http://www.nerds.company
18
 */
19
class SiteDataType extends Base
20
{
21
    /**
22
     * {@inheritdoc}
23
     */
24 1
    public function getMapperHandle(): string
25
    {
26 1
        return 'modelMapper';
27
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32 1
    public function getRecords(): array
33
    {
34 1
        return Craft::$app->sites->getAllSites();
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function afterImport()
41
    {
42
        $this->clearSiteCaches();
43
        if (Schematic::$force) {
44
            $this->clearEmptyGroups();
45
        }
46
    }
47
48
    /**
49
     * Reset craft site service sites cache using reflection.
50
     */
51
    private function clearSiteCaches()
52
    {
53
        $obj = Craft::$app->sites;
54
        $refObject = new \ReflectionObject($obj);
55
        if ($refObject->hasProperty('_sitesById')) {
56
            $refProperty1 = $refObject->getProperty('_sitesById');
57
            $refProperty1->setAccessible(true);
58
            $refProperty1->setValue($obj, null);
59
        }
60
        if ($refObject->hasProperty('_sitesByHandle')) {
61
            $refProperty2 = $refObject->getProperty('_sitesByHandle');
62
            $refProperty2->setAccessible(true);
63
            $refProperty2->setValue($obj, null);
64
        }
65
        $obj->init(); // reload sites
66
    }
67
68
    /**
69
     * Clear empty sute groups
70
     */
71
    private function clearEmptyGroups()
72
    {
73
        foreach (Craft::$app->sites->getAllGroups() as $group) {
74
            if (count($group->getSites()) == 0) {
75
                Craft::$app->sites->deleteGroup($group);
76
            }
77
        }
78
    }
79
}
80