Completed
Push — develop ( 391d38...d77dc3 )
by Evan
02:52
created

Model::normalizeData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

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