User::generateApiKey()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of Gitamin.
5
 *
6
 * Copyright (C) 2015-2016 The Gitamin Team
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
# == Schema Information
13
#
14
# Table name: users
15
#
16
#  id             :integer          not null, primary key
17
#  username       :string(255)
18
#  password       :string(255)
19
#  remember_token :string(100)
20
#  email          :integer
21
#  api_key        :string(255)
22
#  active         :boolean          default(FALSE)
23
#  level          :integer          default(2)
24
#  created_at     :timestamp
25
#  updated_at     :timestamp
26
#
27
28
namespace Gitamin\Models;
29
30
use AltThree\Validator\ValidatingTrait;
31
use Gitamin\Exceptions\UserAlreadyBeenTakenException;
32
use Illuminate\Auth\Authenticatable;
33
use Illuminate\Auth\Passwords\CanResetPassword;
34
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
35
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
36
use Illuminate\Database\Eloquent\Model;
37
use Illuminate\Database\Eloquent\ModelNotFoundException;
38
use Illuminate\Support\Facades\Hash;
39
use Zizaco\Entrust\Traits\EntrustUserTrait;
40
41
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
42
{
43
    use Authenticatable, CanResetPassword, ValidatingTrait, EntrustUserTrait;
44
45
    /**
46
     * The attributes that should be casted to native types.
47
     *
48
     * @var string[]
49
     */
50
    protected $casts = [
51
        'id' => 'int',
52
        'username' => 'string',
53
        'email' => 'string',
54
        'api_key' => 'string',
55
        'active' => 'bool',
56
        'level' => 'int',
57
    ];
58
59
    /**
60
     * The properties that cannot be mass assigned.
61
     *
62
     * @var string[]
63
     */
64
    protected $guarded = [];
65
66
    /**
67
     * The hidden properties.
68
     *
69
     * These are excluded when we are serializing the model.
70
     *
71
     * @var string[]
72
     */
73
    protected $hidden = ['password', 'remember_token'];
74
75
    /**
76
     * The validation rules.
77
     *
78
     * @var string[]
79
     */
80
    public $rules = [
81
        'username' => ['required', 'regex:/\A(?!.*[:;]-\))[ -~]+\z/'],
82
        'email' => 'required|email',
83
        'password' => 'required',
84
    ];
85
86
    /**
87
     * Overrides the models boot method.
88
     */
89
    public static function boot()
90
    {
91
        parent::boot();
92
93
        self::creating(function ($user) {
94
            $ownerExists = Owner::where('path', '=', $user->username)->exists();
95
            if ($ownerExists) {
96
                throw new UserAlreadyBeenTakenException(trans('gitamin.signup.taken'));
97
            }
98
            if (! $user->api_key) {
99
                $user->api_key = self::generateApiKey();
100
            }
101
        });
102
    }
103
104
    /**
105
     * Hash any password being inserted by default.
106
     *
107
     * @param string $password
108
     *
109
     * @return \Gitamin\Models\User
110
     */
111
    public function setPasswordAttribute($password)
112
    {
113
        $this->attributes['password'] = Hash::make($password);
114
115
        return $this;
116
    }
117
118
    /**
119
     * Returns a Gravatar URL for the users email address.
120
     *
121
     * @param int $size
122
     *
123
     * @return string
124
     */
125
    public function getGravatarAttribute($size = 200)
0 ignored issues
show
Unused Code introduced by
The parameter $size is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
126
    {
127
        return 'https://avatars2.githubusercontent.com/u/15867969?v=3&s=40';
128
        //return sprintf('https://www.gravatar.com/avatar/%s?size=%d', md5($this->email), $size);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
129
    }
130
131
    /**
132
     * Find by api_key, or throw an exception.
133
     *
134
     * @param string   $token
135
     * @param string[] $columns
136
     *
137
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
138
     *
139
     * @return \Gitamin\Models\User
140
     */
141
    public static function findByApiToken($token, $columns = ['*'])
142
    {
143
        $user = static::where('api_key', $token)->first($columns);
144
145
        if (! $user) {
146
            throw new ModelNotFoundException();
147
        }
148
149
        return $user;
150
    }
151
152
    /**
153
     * Returns an API key.
154
     *
155
     * @return string
156
     */
157
    public static function generateApiKey()
158
    {
159
        return str_random(20);
160
    }
161
162
    /**
163
     * Returns whether a user is approved.
164
     *
165
     * @return bool
166
     */
167
    public function isApproved()
168
    {
169
        return $this->active == 1;
0 ignored issues
show
Documentation introduced by
The property active does not exist on object<Gitamin\Models\User>. 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...
170
    }
171
172
    /**
173
     * Returns whether a user is at admin level.
174
     *
175
     * @return bool
176
     */
177
    public function getIsAdminAttribute()
178
    {
179
        return $this->level === 1;
0 ignored issues
show
Documentation introduced by
The property level does not exist on object<Gitamin\Models\User>. 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...
180
    }
181
182
    /**
183
     * A user can have many issues.
184
     *
185
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
186
     */
187
    public function issues()
188
    {
189
        return $this->hasMany(Issue::class, 'user_id', 'id');
190
    }
191
}
192