Completed
Push — develop ( 07d619...391d38 )
by Evan
05:11 queued 02:23
created

Model::setObject()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
cc 1
eloc 3
nc 1
nop 1
rs 9.4285
1
<?php
2
3
namespace Silk\User;
4
5
use WP_User;
6
use Silk\Type\Model as BaseModel;
7
use Silk\Exception\WP_ErrorException;
8
use Silk\User\Exception\UserNotFoundException;
9
10
class Model extends BaseModel
11
{
12
    /**
13
     * The object type in WordPress
14
     */
15
    const OBJECT_TYPE = 'user';
16
17
    /**
18
     * The primary ID property on the object
19
     */
20
    const ID_PROPERTY = 'ID';
21
22
    /**
23
     * User Constructor.
24
     *
25
     * @param array|WP_User $user  User object or array of attributes
26
     */
27
    public function __construct($user = null)
28
    {
29
        $attributes = is_array($user) ? $user : [];
30
31
        if (! $user instanceof WP_User) {
0 ignored issues
show
Bug introduced by
The class WP_User does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
32
            $user = new WP_User();
33
        }
34
35
        $this->object = $this->normalizeData($user);
36
37
        $this->fill($attributes);
38
    }
39
40
    /**
41
     * Create a new instance from the user ID.
42
     *
43
     * @param  string|int $id  User ID
44
     *
45
     * @throws UserNotFoundException
46
     *
47
     * @return static
48
     */
49 View Code Duplication
    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...
50
    {
51
        if (! $user = get_user_by('id', $id)) {
52
            throw new UserNotFoundException("No user found with ID $id");
53
        }
54
55
        return new static($user);
56
    }
57
58
    /**
59
     * Create a new instance from the username.
60
     *
61
     * @param  string $username  Username (login)
62
     *
63
     * @throws UserNotFoundException
64
     *
65
     * @return static
66
     */
67
    public static function fromUsername($username)
68
    {
69
        if (! $user = get_user_by('login', $username)) {
70
            throw new UserNotFoundException("No user found with username: $username");
71
        }
72
73
        return new static($user);
74
    }
75
76
    /**
77
     * Create a new instance from the user's email address.
78
     *
79
     * @param  string $email  User email address
80
     *
81
     * @throws UserNotFoundException
82
     *
83
     * @return static
84
     */
85 View Code Duplication
    public static function fromEmail($email)
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 (! $user = get_user_by('email', $email)) {
88
            throw new UserNotFoundException("No user found with email address: $email");
89
        }
90
91
        return new static($user);
92
    }
93
94
    /**
95
     * Create a new instance from the user's slug.
96
     *
97
     * @param  string $slug  User slug (nicename)
98
     *
99
     * @throws UserNotFoundException
100
     *
101
     * @return static
102
     */
103
    public static function fromSlug($slug)
104
    {
105
        if (! $user = get_user_by('slug', $slug)) {
106
            throw new UserNotFoundException("No user found with slug: $slug");
107
        }
108
109
        return new static($user);
110
    }
111
112
    /**
113
     * Create a new instance using the currently authenticated user.
114
     *
115
     * @return static
116
     */
117
    public static function auth()
118
    {
119
        return new static(wp_get_current_user());
120
    }
121
122
    /**
123
     * Get the URL for the user's posts archive.
124
     *
125
     * @return string
126
     */
127
    public function postsUrl()
128
    {
129
        return get_author_posts_url($this->id, $this->slug);
0 ignored issues
show
Documentation introduced by
The property slug does not exist on object<Silk\User\Model>. 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...
130
    }
131
132
    /**
133
    * Get a new query builder for the model.
134
    *
135
    * @return \Silk\Contracts\BuildsQueries
136
    */
137
    public function newQuery()
138
    {
139
        return QueryBuilder::make()->setModel($this);
140
    }
141
142
    /**
143
     * Save the changes to the database.
144
     *
145
     * @throws WP_ErrorException
146
     *
147
     * @return $this
148
     */
149 View Code Duplication
    public function save()
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...
150
    {
151
        if (! $this->id) {
152
            $result = wp_insert_user($this->object);
153
        } else {
154
            $result = wp_update_user($this->object);
155
        }
156
157
        if (is_wp_error($result)) {
158
            throw new WP_ErrorException($result);
159
        }
160
161
        $this->setId($result)->refresh();
162
163
        return $this;
164
    }
165
166
    /**
167
     * Delete the modeled record from the database.
168
     *
169
     * @return $this
170
     */
171
    public function delete()
172
    {
173
        if (wp_delete_user($this->id)) {
174
            $this->setObject(new WP_User);
175
        }
176
177
        return $this;
178
    }
179
180
    /**
181
     * Reload the object from the database.
182
     *
183
     * @return $this
184
     */
185
    public function refresh()
186
    {
187
        $this->setObject(new WP_User($this->id));
188
189
        return $this;
190
    }
191
192
    /**
193
     * Set the WP_User object on the model.
194
     *
195
     * @param WP_User $user
196
     *
197
     * @return $this
198
     */
199
    protected function setObject($user)
200
    {
201
        $this->object = $this->normalizeData($user);
202
203
        return $this;
204
    }
205
206
    /**
207
     * Normalize the user data object on the given User.
208
     *
209
     * This is necessary for object aliases and shorthand properties to work properly
210
     * due to the fact that the WP_User's data object is a plain object which
211
     * does not always contain all properties as is the case with other WP objects.
212
     *
213
     * @param WP_User $user
214
     *
215
     * @return WP_User
216
     */
217
    protected function normalizeData(WP_User $user)
218
    {
219
        $properties = [
220
            'ID',
221
            'user_login',
222
            'user_pass',
223
            'user_nicename',
224
            'user_email',
225
            'user_registered',
226
            'user_activation_key',
227
            'user_status',
228
            'display_name',
229
            'spam',
230
            'deleted',
231
        ];
232
233
        foreach ($properties as $property) {
234
            if (! property_exists($user->data, $property)) {
235
                $user->data->$property = null; // exists but ! isset
236
            }
237
        }
238
239
        return $user;
240
    }
241
242
    /**
243
     * Get the aliased object.
244
     *
245
     * Most user data from the database is stored as an object on the user's `data` property.
246
     *
247
     * @return object|\stdClass
248
     */
249
    protected function getAliasedObject()
250
    {
251
        return $this->object->data;
252
    }
253
}
254