Completed
Push — master ( b2b692...c67b5d )
by Abdelrahman
02:40
created

UserRepository::create()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 25
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 3
nop 1
dl 0
loc 25
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * NOTICE OF LICENSE
5
 *
6
 * Part of the Rinvex Fort Package.
7
 *
8
 * This source file is subject to The MIT License (MIT)
9
 * that is bundled with this package in the LICENSE file.
10
 *
11
 * Package: Rinvex Fort Package
12
 * License: The MIT License (MIT)
13
 * Link:    https://rinvex.com
14
 */
15
16
namespace Rinvex\Fort\Repositories;
17
18
use Illuminate\Support\Str;
19
use Rinvex\Fort\Traits\HasRoles;
20
use Illuminate\Contracts\Hashing\Hasher;
21
use Illuminate\Contracts\Foundation\Application;
22
use Rinvex\Fort\Contracts\UserRepositoryContract;
23
use Rinvex\Fort\Contracts\AuthenticatableContract;
24
use Rinvex\Repository\Repositories\EloquentRepository;
25
26
class UserRepository extends EloquentRepository implements UserRepositoryContract
27
{
28
    use HasRoles;
29
30
    /**
31
     * The hasher implementation.
32
     *
33
     * @var \Illuminate\Contracts\Hashing\Hasher
34
     */
35
    protected $hasher;
36
37
    /**
38
     * create a new user repository instance.
39
     *
40
     * @param \Illuminate\Contracts\Foundation\Application $app
41
     *
42
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
43
     */
44
    public function __construct(Application $app, Hasher $hasher)
45
    {
46
        $this->setContainer($app)
47
             ->setHasher($hasher)
48
             ->setRepositoryId('rinvex.fort.user')
49
             ->setModel($app['config']['rinvex.fort.models.user']);
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function findByToken($identifier, $token)
56
    {
57
        return $this->where($this->getAuthIdentifierName(), $identifier)
0 ignored issues
show
Documentation Bug introduced by
The method getAuthIdentifierName does not exist on object<Rinvex\Fort\Repositories\UserRepository>? 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...
58
                    ->where($this->getRememberTokenName(), $token)
0 ignored issues
show
Documentation Bug introduced by
The method getRememberTokenName does not exist on object<Rinvex\Fort\Repositories\UserRepository>? 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...
59
                    ->findFirst();
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65
    public function findByCredentials(array $credentials)
66
    {
67
        if (empty($credentials)) {
68
            return;
69
        }
70
71
        // First we will add each credential element to the query as a where clause.
72
        // Then we can execute the query and, if we found a user, return it in a
73
        // Eloquent User "model" that will be utilized by the Guard instances.
74
        $model = $this;
75
76
        foreach ($credentials as $key => $value) {
77
            if (! Str::contains($key, 'password')) {
78
                $model = $model->where($key, $value);
79
            }
80
        }
81
82
        return $model->findFirst();
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88
    public function create(array $attributes = [])
89
    {
90
        $social = array_pull($attributes, 'social', false);
91
92
        // Fire the register start event
93
        $this->getContainer('events')->fire('rinvex.fort.register'.$social.'.start', [$attributes]);
94
95
        // Prepare registration data
96
        $attributes['password']  = bcrypt(! $social ? $attributes['password'] : str_random());
97
        $attributes['moderated'] = config('rinvex.fort.registration.moderated');
98
99
        // Create new user
100
        $user = parent::create($attributes);
101
102
        // Fire the register success event
103
        $this->getContainer('events')->fire('rinvex.fort.register'.$social.'.success', [$user]);
104
105
        // Send verification if required
106
        if (! $social && config('rinvex.fort.verification.required')) {
107
            return app('rinvex.fort.verifier')->broker()->sendVerificationLink(['email' => $attributes['email']]);
108
        }
109
110
        // Registration completed successfully
111
        return ! $social ? static::AUTH_REGISTERED : $user;
112
    }
113
114
    /**
115
     * {@inheritdoc}
116
     */
117
    public function updateRememberToken(AuthenticatableContract $user, $token)
118
    {
119
        $this->update($user, [$this->getRememberTokenName() => $token]);
0 ignored issues
show
Documentation Bug introduced by
The method getRememberTokenName does not exist on object<Rinvex\Fort\Repositories\UserRepository>? 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...
120
    }
121
122
    /**
123
     * {@inheritdoc}
124
     */
125
    public function validateCredentials(AuthenticatableContract $user, array $credentials)
126
    {
127
        $plain = $credentials['password'];
128
129
        return $this->getHasher()->check($plain, $user->getAuthPassword());
130
    }
131
132
    /**
133
     * Gets the hasher implementation.
134
     *
135
     * @return \Illuminate\Contracts\Hashing\Hasher
136
     */
137
    public function getHasher()
138
    {
139
        return $this->hasher;
140
    }
141
142
    /**
143
     * Sets the hasher implementation.
144
     *
145
     * @param \Illuminate\Contracts\Hashing\Hasher $hasher
146
     *
147
     * @return $this
148
     */
149
    public function setHasher(Hasher $hasher)
150
    {
151
        $this->hasher = $hasher;
152
153
        return $this;
154
    }
155
156
    /**
157
     * Get the menus for the given user.
158
     *
159
     * @param int  $modelId
160
     * @param bool $root
161
     *
162
     * @return mixed
163
     */
164
    public function menus($modelId, $root = true)
165
    {
166
        return $this->executeCallback(get_called_class(), __FUNCTION__, func_get_args(), function () use ($modelId, $root) {
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 124 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
167
            if (! is_int($modelId) || ! $model = $this->with(['abilities'])->find($modelId)) {
168
                return [];
169
            }
170
171
            $roleAbilities = null;
172
            $callback      = function ($item) {
173
                if (strpos($item, '.index') === false) {
174
                    return str_replace(strrchr($item, '.'), '.index', $item);
175
                } else {
176
                    return 'root';
177
                }
178
            };
179
180
            if (! $model instanceof Role) {
0 ignored issues
show
Bug introduced by
The class Rinvex\Fort\Repositories\Role does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
181
                $roleAbilities = $model->roles()->with(['abilities'])->get()->pluck('abilities')->flatten()->pluck('slug');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 123 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
182
            }
183
184
            $userAbilities = $model->abilities->pluck('slug')->merge($roleAbilities)->unique()->groupBy($callback)->toArray();
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
185
186
            return $root ? $userAbilities['root'] : $userAbilities;
187
        });
188
    }
189
}
190