Completed
Pull Request — master (#91)
by Bob Olde
04:16
created

AssetSources::import()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 31
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 6.288

Importance

Changes 0
Metric Value
dl 0
loc 31
ccs 16
cts 20
cp 0.8
rs 8.439
c 0
b 0
f 0
cc 6
eloc 17
nc 10
nop 2
crap 6.288
1
<?php
2
3
namespace NerdsAndCompany\Schematic\Services;
4
5
use Craft\Craft;
6
use Craft\AssetSourceRecord;
7
use Craft\AssetSourceModel;
8
9
/**
10
 * Schematic Assets Service.
11
 *
12
 * Sync Craft Setups.
13
 *
14
 * @author    Nerds & Company
15
 * @copyright Copyright (c) 2015-2017, Nerds & Company
16
 * @license   MIT
17
 *
18
 * @link      http://www.nerds.company
19
 */
20
class AssetSources extends Base
21
{
22
    /**
23
     * @return AssetSourcesService
24
     */
25 3
    private function getAssetSourcesService()
26
    {
27 3
        return Craft::app()->assetSources;
28
    }
29
30
    /**
31
     * @param $sourceTypeId
32
     *
33
     * @return array|mixed|null
34
     */
35
    public function getSourceTypeById($sourceTypeId)
36
    {
37
        return AssetSourceRecord::model()->findByAttributes(['id' => $sourceTypeId]);
38
    }
39
40
    /**
41
     * @param $sourceTypeHandle
42
     *
43
     * @return array|mixed|null
44
     */
45
    public function getSourceTypeByHandle($sourceTypeHandle)
46
    {
47
        return AssetSourceRecord::model()->findByAttributes(['handle' => $sourceTypeHandle]);
48
    }
49
50
    /**
51
     * Import asset source definitions.
52
     *
53
     * @param array $assetSourceDefinitions
54
     * @param bool  $force
55
     *
56
     * @return Result
57
     */
58 4
    public function import(array $assetSourceDefinitions, $force = false)
59
    {
60 4
        Craft::log(Craft::t('Importing Asset Sources'));
61
62 4
        $this->resetCraftAssetSourcesServiceCache();
63 4
        $assetSources = Craft::app()->assetSources->getAllSources('handle');
64
65 4
        foreach ($assetSourceDefinitions as $assetSourceHandle => $assetSourceDefinition) {
66 2
            $assetSource = array_key_exists($assetSourceHandle, $assetSources)
67 2
                ? $assetSources[$assetSourceHandle]
68 2
                : new AssetSourceModel();
69
70 2
            unset($assetSources[$assetSourceHandle]);
71
72 2
            $this->populateAssetSource($assetSource, $assetSourceDefinition, $assetSourceHandle);
73
74
            if (!Craft::app()->assetSources->saveSource($assetSource)) { // Save assetsource via craft
75
                $this->addErrors($assetSource->getAllErrors());
76
77
                continue;
78
            }
79 2
        }
80
81 2
        if ($force) {
82 1
            foreach ($assetSources as $assetSource) {
83
                Craft::app()->assetSources->deleteSourceById($assetSource->id);
84 1
            }
85 1
        }
86
87 2
        return $this->getResultModel();
88
    }
89
90
    /**
91
     * Populate asset source.
92
     *
93
     * @param AssetSourceModel $assetSource
94
     * @param string           $assetSourceHandle
95
     * @param array            $assetSourceDefinition
96
     *
97
     * @return AssetSourceModel
98
     */
99
    private function populateAssetSource(AssetSourceModel $assetSource, $assetSourceHandle, array $assetSourceDefinition)
100
    {
101
        $defaultAssetSourceSettings = array(
102
            'publicURLs' => true,
103
        );
104
105
        $assetSource->setAttributes([
106
            'handle' => $assetSourceHandle,
107
            'type' => $assetSourceDefinition['type'],
108
            'name' => $assetSourceDefinition['name'],
109
            'sortOrder' => $assetSourceDefinition['sortOrder'],
110
            'settings' => array_merge($defaultAssetSourceSettings, $assetSourceDefinition['settings']),
111
        ]);
112
113
        if (array_key_exists('fieldLayout', $assetSourceDefinition)) {
114
            $fieldLayout = Craft::app()->schematic_fields->getFieldLayout($assetSourceDefinition['fieldLayout']);
115
            $assetSource->setFieldLayout($fieldLayout);
116
        }
117
118
        return $assetSource;
119
    }
120
121
    /**
122
     * Export all asset sources.
123
     *
124
     * @param array $data
125
     *
126
     * @return array
127
     */
128 3
    public function export(array $data = [])
129
    {
130 3
        Craft::log(Craft::t('Exporting Asset Sources'));
131
132 3
        $assetSources = $this->getAssetSourcesService()->getAllSources();
133
134
        $assetSourceDefinitions = [];
135
        foreach ($assetSources as $assetSource) {
136
            $assetSourceDefinitions[$assetSource->handle] = $this->getAssetSourceDefinition($assetSource);
137
        }
138
139
        return $assetSourceDefinitions;
140
    }
141
142
    /**
143
     * @param AssetSourceModel $assetSource
144
     *
145
     * @return array
146
     */
147
    private function getAssetSourceDefinition(AssetSourceModel $assetSource)
148
    {
149
        return [
150
            'type' => $assetSource->type,
151
            'name' => $assetSource->name,
152
            'sortOrder' => $assetSource->sortOrder,
153
            'settings' => $assetSource->settings,
154
            'fieldLayout' => Craft::app()->schematic_fields->getFieldLayoutDefinition($assetSource->getFieldLayout()),
155
        ];
156
    }
157
158
    /**
159
     * Reset craft fields service cache using reflection.
160
     */
161 4
    private function resetCraftAssetSourcesServiceCache()
162
    {
163 4
        $obj = Craft::app()->categories;
164 4
        $refObject = new \ReflectionObject($obj);
165 4
        if ($refObject->hasProperty('_fetchedAllSources')) {
166
            $refProperty = $refObject->getProperty('_fetchedAllSources');
167
            $refProperty->setAccessible(true);
168
            $refProperty->setValue($obj, false);
169
        }
170 4
        if ($refObject->hasProperty('_sourcesById')) {
171
            $refProperty = $refObject->getProperty('_sourcesById');
172
            $refProperty->setAccessible(true);
173
            $refProperty->setValue($obj, array());
174
        }
175 4
    }
176
}
177