Completed
Pull Request — master (#114)
by Bart
07:39
created

Volumes::import()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 31
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.439
c 0
b 0
f 0
cc 6
eloc 17
nc 10
nop 2
1
<?php
2
3
namespace NerdsAndCompany\Schematic\Services;
4
5
use \Craft;
6
use craft\base\VolumeInterface;
7
8
/**
9
 * Schematic Asset Sources Service.
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 Volumes extends Base
20
{
21
    //==============================================================================================================
22
    //================================================  EXPORT  ====================================================
23
    //==============================================================================================================
24
25
    /**
26
     * Get all asset transforms
27
     *
28
     * @return VolumeInterface[]
29
     */
30
    protected function getRecords()
31
    {
32
        return Craft::$app->volumes->getAllVolumes();
33
    }
34
35
    //==============================================================================================================
36
    //================================================  IMPORT  ====================================================
37
    //==============================================================================================================
38
39
    /**
40
     * Import asset source definitions.
41
     *
42
     * @param array $assetSourceDefinitions
43
     * @param bool  $force
44
     *
45
     * @return Result
46
     */
47
    public function import($force = false, array $assetSourceDefinitions = null)
48
    {
49
        Craft::info('Importing Asset Sources', 'schematic');
50
51
        $this->resetCraftAssetSourcesServiceCache();
52
        $assetSources = $this->getAssetSourcesService()->getAllSources('handle');
0 ignored issues
show
Documentation Bug introduced by
The method getAssetSourcesService does not exist on object<NerdsAndCompany\S...matic\Services\Volumes>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
53
54
        foreach ($assetSourceDefinitions as $assetSourceHandle => $assetSourceDefinition) {
0 ignored issues
show
Bug introduced by
The expression $assetSourceDefinitions of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
55
            $assetSource = array_key_exists($assetSourceHandle, $assetSources)
56
                ? $assetSources[$assetSourceHandle]
57
                : new AssetSourceModel();
58
59
            unset($assetSources[$assetSourceHandle]);
60
61
            $this->populateAssetSource($assetSource, $assetSourceDefinition, $assetSourceHandle);
62
63
            if (!$this->getAssetSourcesService()->saveSource($assetSource)) { // Save assetsource via craft
0 ignored issues
show
Documentation Bug introduced by
The method getAssetSourcesService does not exist on object<NerdsAndCompany\S...matic\Services\Volumes>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
64
                $this->addErrors($assetSource->getAllErrors());
0 ignored issues
show
Documentation Bug introduced by
The method addErrors does not exist on object<NerdsAndCompany\S...matic\Services\Volumes>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
65
66
                continue;
67
            }
68
        }
69
70
        if ($force) {
71
            foreach ($assetSources as $assetSource) {
72
                $this->getAssetSourcesService()->deleteSourceById($assetSource->id);
0 ignored issues
show
Documentation Bug introduced by
The method getAssetSourcesService does not exist on object<NerdsAndCompany\S...matic\Services\Volumes>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
73
            }
74
        }
75
76
        return $this->getResultModel();
0 ignored issues
show
Documentation Bug introduced by
The method getResultModel does not exist on object<NerdsAndCompany\S...matic\Services\Volumes>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
77
    }
78
79
    /**
80
     * Populate asset source.
81
     *
82
     * @param AssetSourceModel $assetSource
83
     * @param array            $assetSourceDefinition
84
     * @param string           $assetSourceHandle
85
     *
86
     * @return AssetSourceModel
87
     */
88
    private function populateAssetSource(AssetSourceModel $assetSource, array $assetSourceDefinition, $assetSourceHandle)
89
    {
90
        $defaultAssetSourceSettings = array(
91
            'publicURLs' => true,
92
        );
93
94
        $assetSource->setAttributes([
95
            'handle' => $assetSourceHandle,
96
            'type' => $assetSourceDefinition['type'],
97
            'name' => $assetSourceDefinition['name'],
98
            'sortOrder' => $assetSourceDefinition['sortOrder'],
99
            'settings' => array_merge($defaultAssetSourceSettings, $assetSourceDefinition['settings']),
100
        ]);
101
102
        if (array_key_exists('fieldLayout', $assetSourceDefinition)) {
103
            $fieldLayout = Craft::$app->schematic_fields->getFieldLayout($assetSourceDefinition['fieldLayout']);
104
            $assetSource->setFieldLayout($fieldLayout);
105
        }
106
107
        return $assetSource;
108
    }
109
110
    /**
111
     * Reset craft fields service cache using reflection.
112
     */
113
    private function resetCraftAssetSourcesServiceCache()
114
    {
115
        $obj = $this->getAssetSourcesService();
0 ignored issues
show
Documentation Bug introduced by
The method getAssetSourcesService does not exist on object<NerdsAndCompany\S...matic\Services\Volumes>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
116
        $refObject = new \ReflectionObject($obj);
117
        if ($refObject->hasProperty('_fetchedAllSources')) {
118
            $refProperty = $refObject->getProperty('_fetchedAllSources');
119
            $refProperty->setAccessible(true);
120
            $refProperty->setValue($obj, false);
121
        }
122
        if ($refObject->hasProperty('_sourcesById')) {
123
            $refProperty = $refObject->getProperty('_sourcesById');
124
            $refProperty->setAccessible(true);
125
            $refProperty->setValue($obj, array());
126
        }
127
    }
128
}
129