Completed
Branch develop (2a5993)
by Evan
02:52
created

Model::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
cc 1
eloc 7
nc 1
nop 1
rs 9.6666
1
<?php
2
3
namespace Silk\Term;
4
5
use stdClass;
6
use WP_Term;
7
use Silk\Taxonomy\Taxonomy;
8
use Silk\Type\Model as BaseModel;
9
use Illuminate\Support\Collection;
10
use Silk\Exception\WP_ErrorException;
11
use Silk\Term\Exception\TermNotFoundException;
12
use Silk\Term\Exception\TaxonomyMismatchException;
13
14
/**
15
 * @property-read WP_Term $term
16
 * @property int    $term_id
17
 * @property string $name
18
 * @property string $slug
19
 * @property string $term_group
20
 * @property int    $term_taxonomy_id
21
 * @property string $taxonomy
22
 * @property string $description
23
 * @property int    $parent
24
 * @property int    $count
25
 */
26
abstract class Model extends BaseModel
27
{
28
    /**
29
     * The term's taxonomy
30
     * @var string
31
     */
32
    const TAXONOMY = '';
33
34
    /**
35
     * The object type in WordPress
36
     * @var string
37
     */
38
    const OBJECT_TYPE = 'term';
39
40
    /**
41
     * The primary ID property on the object
42
     */
43
    const ID_PROPERTY = 'term_id';
44
45
    /**
46
     * Model Constructor.
47
     *
48
     * @param mixed $term  WP_Term to fill data from
49
     *
50
     * @throws TaxonomyMismatchException
51
     */
52
    public function __construct(WP_Term $term = null)
53
    {
54
        if (! $term) {
55
            $term = new WP_Term(new stdClass);
56
            $term->taxonomy = static::TAXONOMY;
57
        } elseif ($term->taxonomy != static::TAXONOMY) {
58
            throw new TaxonomyMismatchException();
59
        }
60
61
        $this->object = $term;
62
    }
63
64
    /**
65
     * Create a new instance from a WP_Term object.
66
     *
67
     * @param  WP_Term $term [description]
68
     *
69
     * @return static
70
     */
71
    public static function fromWpTerm(WP_Term $term)
72
    {
73
        return new static($term);
74
    }
75
76
    /**
77
     * Create a new instance from a term ID.
78
     *
79
     * @param  int|string $id  Term ID
80
     *
81
     * @throws TermNotFoundException
82
     *
83
     * @return static
84
     */
85
    public static function fromID($id)
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
86
    {
87
        if (! $term = get_term_by('id', (int) $id, static::TAXONOMY)) {
88
            throw new TermNotFoundException("No term found with ID $id.");
89
        }
90
91
        return static::fromWpTerm($term);
92
    }
93
94
    /**
95
     * Create a new instance from a slug.
96
     *
97
     * @param  string $slug  Term slug
98
     *
99
     * @throws TermNotFoundException
100
     *
101
     * @return static
102
     */
103
    public static function fromSlug($slug)
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
104
    {
105
        if (! $term = get_term_by('slug', $slug, static::TAXONOMY)) {
106
            throw new TermNotFoundException("No term found with slug '$slug'.");
107
        }
108
109
        return static::fromWpTerm($term);
110
    }
111
112
    /**
113
     * Create a new instance from an array of attributes.
114
     *
115
     * @param  array  $attributes [description]
116
     *
117
     * @return static
118
     */
119
    public static function fromArray(array $attributes)
120
    {
121
        return new static(
122
            new WP_Term((object) $attributes)
123
        );
124
    }
125
126
    /**
127
     * Create a new term, and get the instance for it.
128
     *
129
     * @param  array $attributes  Term attributes
130
     *
131
     * @return static
132
     */
133
    public static function create(array $attributes = [])
134
    {
135
        return static::fromArray(
136
            Collection::make($attributes)
137
                ->except([static::ID_PROPERTY, 'term_taxonomy_id'])
138
                ->put('taxonomy', static::TAXONOMY)
139
                ->toArray()
140
        )->save();
141
    }
142
143
    /**
144
     * Check if this term exists in the database.
145
     *
146
     * @return boolean
147
     */
148
    public function exists()
149
    {
150
        return $this->id && ((bool) term_exists((int) $this->id, static::TAXONOMY));
151
    }
152
153
    /**
154
     * Check if this term exists in the database as the child of the given parent.
155
     *
156
     * @param  int|string|object  $parent  integer Parent term ID
157
     *                                     string  Parent term slug or name
158
     *                                     object  The parent term object/model.
159
     *
160
     * @return boolean                     True if the this term and the parent
161
     *                                     exist in the database, and the instance
162
     *                                     is a child of the given parent;
163
     *                                     otherwise false
164
     */
165
    public function isChildOf($parent)
166
    {
167
        if (isset($parent->term_id)) {
168
            $parent = $parent->term_id;
169
        }
170
171
        return (bool) term_exists((int) $this->id, static::TAXONOMY, $parent);
172
    }
173
174
    /**
175
     * Get the parent term instance.
176
     *
177
     * @return static
178
     */
179
    public function parent()
180
    {
181
        return static::fromID($this->object->parent);
182
    }
183
184
    /**
185
     * Get all ancestors of this term as a collection.
186
     *
187
     * @return Collection
188
     */
189
    public function ancestors()
190
    {
191
        return Collection::make(get_ancestors($this->id, static::TAXONOMY, 'taxonomy'))
192
            ->map(function ($term_ID) {
193
                return static::fromID($term_ID);
194
            });
195
    }
196
197
    /**
198
     * Get the Taxonomy model.
199
     *
200
     * @return Taxonomy|\Silk\Taxonomy\Builder
201
     */
202
    public static function taxonomy()
203
    {
204
        return Taxonomy::make(static::TAXONOMY);
205
    }
206
207
    /**
208
     * Get the URL for this term.
209
     *
210
     * @return string|bool
211
     */
212
    public function url()
213
    {
214
        $url = get_term_link($this->id, $this->taxonomy);
215
216
        if (is_wp_error($url)) {
217
            throw new WP_ErrorException($url);
218
        }
219
220
        return $url;
221
    }
222
223
    /**
224
     * Start a new query for terms of this type.
225
     *
226
     * @return QueryBuilder
227
     */
228
    public function newQuery()
229
    {
230
        return QueryBuilder::make()->setModel($this);
231
    }
232
233
    /**
234
     * Save the term to the database.
235
     *
236
     * @throws WP_ErrorException
237
     *
238
     * @return $this
239
     */
240
    public function save()
241
    {
242
        if ($this->id) {
243
            $ids = wp_update_term($this->id, $this->taxonomy, $this->object->to_array());
244
        } else {
245
            $ids = wp_insert_term($this->name, $this->taxonomy, $this->object->to_array());
246
        }
247
248
        if (is_wp_error($ids)) {
249
            throw new WP_ErrorException($ids);
250
        }
251
252
        $this->setId($ids['term_id'])->refresh();
253
254
        return $this;
255
    }
256
257
    /**
258
     * Delete the term from the database.
259
     *
260
     * @return $this
261
     */
262
    public function delete()
263
    {
264
        if (wp_delete_term($this->id, $this->taxonomy)) {
265
            $this->object = new WP_Term(new stdClass);
266
        }
267
268
        return $this;
269
    }
270
271
    /**
272
     * Reload the term object from the database.
273
     *
274
     * @return $this
275
     */
276
    public function refresh()
277
    {
278
        $this->object = WP_Term::get_instance($this->id, $this->taxonomy);
279
280
        return $this;
281
    }
282
}
283