Completed
Push — master ( d7dffa...54ccfb )
by Zhengchao
07:51
created

UserReferral   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 1
dl 0
loc 36
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getReferralLink() 0 4 1
A scopeReferralExists() 0 4 1
A boot() 0 12 2
A generateReferral() 0 10 2
1
<?php
2
3
/*
4
 * This file is part of questocat/laravel-referral package.
5
 *
6
 * (c) questocat <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Questocat\Referral\Traits;
13
14
use Illuminate\Database\Eloquent\Builder;
15
use Illuminate\Support\Facades\Cookie;
16
17
trait UserReferral
18
{
19
    public function getReferralLink()
20
    {
21
        return url('/').'/?ref='.$this->affiliate_id;
0 ignored issues
show
Bug introduced by
The property affiliate_id does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
22
    }
23
24
    public static function scopeReferralExists(Builder $query, $referral)
25
    {
26
        return $query->whereAffiliateId($referral)->exists();
27
    }
28
29
    protected static function boot()
30
    {
31
        parent::boot();
32
33
        static::creating(function ($model) {
34
            if ($referredBy = Cookie::get('referral')) {
35
                $model->referred_by = $referredBy;
36
            }
37
38
            $model->affiliate_id = self::generateReferral();
39
        });
40
    }
41
42
    protected static function generateReferral()
43
    {
44
        $length = config('referral.referral_length', 5);
45
46
        do {
47
            $referral = str_random($length);
48
        } while (static::referralExists($referral));
0 ignored issues
show
Bug introduced by
The method referralExists() does not exist on Questocat\Referral\Traits\UserReferral. Did you maybe mean scopeReferralExists()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
49
50
        return $referral;
51
    }
52
}
53