Completed
Pull Request — master (#114)
by Bart
06:18
created

Base::deleteRecord()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
ccs 0
cts 0
cp 0
nc 1
1
<?php
2
3
namespace NerdsAndCompany\Schematic\Services;
4
5
use craft\base\Model;
6
use yii\base\Component as BaseComponent;
7
use NerdsAndCompany\Schematic\Behaviors\FieldLayoutBehavior;
8
use NerdsAndCompany\Schematic\Behaviors\SourcesBehavior;
9
use NerdsAndCompany\Schematic\Interfaces\MappingInterface;
10
use NerdsAndCompany\Schematic\Schematic;
11
use LogicException;
12
13
/**
14
 * Schematic Base Service.
15
 *
16
 * Sync Craft Setups.
17
 *
18
 * @author    Nerds & Company
19
 * @copyright Copyright (c) 2015-2018, Nerds & Company
20
 * @license   MIT
21
 *
22
 * @see      http://www.nerds.company
23
 */
24
abstract class Base extends BaseComponent implements MappingInterface
25
{
26
    /**
27
     * Check required properties
28
     */
29
    public function __construct()
30
    {
31
        if (!isset($this->recordClass)) {
32
            throw new LogicException(get_class($this) . ' must have a $recordClass');
33
        }
34
    }
35
36
    /**
37
     * Load fieldlayout and sources behaviors
38
     *
39
     * @return array
40
     */
41
    public function behaviors()
42
    {
43
        return [
44
          FieldLayoutBehavior::className(),
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
45
          SourcesBehavior::className(),
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
46
        ];
47 57
    }
48
49 57
    /**
50 57
     * Get all records
51
     *
52
     * @return Model[]
53
     */
54
    abstract protected function getRecords();
55
56
    //==============================================================================================================
57
    //================================================  EXPORT  ====================================================
58
    //==============================================================================================================
59
60
    /**
61
     * Get all record definitions
62
     *
63
     * @return array
64
     */
65
    public function export(array $records = null)
66
    {
67
        $records = $records ?: $this->getRecords();
68
        $result = [];
69
        foreach ($records as $record) {
70
            $result[$record->handle] = $this->getRecordDefinition($record);
71
        }
72
        return $result;
73
    }
74
75
    /**
76
     * Get single record definition
77
     *
78
     * @param  Model $record
79
     * @return array
80
     */
81
    protected function getRecordDefinition(Model $record)
82
    {
83
        $attributes = $record->attributes;
84
        unset($attributes['id']);
85
        unset($attributes['dateCreated']);
86
        unset($attributes['dateUpdated']);
87
88
        if (isset($attributes['sources'])) {
89
            $attributes['sources'] = $this->getSources(get_class($record), $attributes['sources'], 'id', 'handle');
0 ignored issues
show
Documentation Bug introduced by
The method getSources does not exist on object<NerdsAndCompany\Schematic\Services\Base>? 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...
90
        }
91
92
        if (isset($attributes['source'])) {
93
            $attributes['source'] = $this->getSource(get_class($record), $attributes['sources'], 'id', 'handle');
0 ignored issues
show
Documentation Bug introduced by
The method getSource does not exist on object<NerdsAndCompany\Schematic\Services\Base>? 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...
94
        }
95
96
        if (isset($attributes['fieldLayoutId'])) {
97
            $attributes['fieldLayout'] = $this->getFieldLayoutDefinition($record->getFieldLayout());
0 ignored issues
show
Documentation Bug introduced by
The method getFieldLayoutDefinition does not exist on object<NerdsAndCompany\Schematic\Services\Base>? 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...
98
            unset($attributes['fieldLayoutId']);
99
        }
100
101
        return $attributes;
102
    }
103
104
    //==============================================================================================================
105
    //================================================  IMPORT  ====================================================
106
    //==============================================================================================================
107
108
    /**
109
     * Import asset volumes.
110
     *
111
     * @param array $definitions
112
     * @param bool  $force
113 4
     */
114
    public function import(array $definitions, $force = false)
115 4
    {
116 4
        $recordsByHandle = [];
117
        foreach ($this->getRecords() as $record) {
118
            $recordsByHandle[$record->handle] = $record;
119
        }
120
121
        foreach ($definitions as $handle => $definition) {
122
            $record = new $this->recordClass();
0 ignored issues
show
Documentation introduced by
The property recordClass does not exist on object<NerdsAndCompany\Schematic\Services\Base>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
123
            if (array_key_exists($handle, $recordsByHandle)) {
124 11
                $record = $recordsByHandle[$handle];
125
            }
126 11
            $record->setAttributes($definition);
127 11
            Schematic::info('Importing record '.$handle);
128
            if (!$this->saveRecord($record)) {
129
                Schematic::warning('Error importing record '.$handle);
130
                foreach ($record->getErrors() as $errors) {
131
                    foreach ($errors as $error) {
132
                        Schematic::error($error);
133
                    }
134
                }
135
            }
136
            unset($recordsByHandle[$handle]);
137
        }
138
139
        if ($force) {
140
            // Delete volumes not in definitions
141
            foreach ($recordsByHandle as $handle => $record) {
142
                Schematic::info('Deleting record '.$handle);
143
                $this->deleteRecord($record);
144
            }
145
        }
146
    }
147
148
    /**
149
     * Save a record
150
     *
151
     * @param Model $record
152
     * @return boolean
153
     */
154
    abstract protected function saveRecord(Model $record);
155
156
    /**
157
     * Delete a record
158
     *
159
     * @param Model $record
160
     * @return boolean
161
     */
162
    abstract protected function deleteRecord(Model $record);
163
}
164