Issues (364)

app/Traits/UniqueStringTrait.php (1 issue)

Severity
1
<?php
2
3
namespace App\Traits;
4
5
use Illuminate\Support\Str;
6
use LaravelEnso\Companies\Models\Company;
7
8
trait UniqueStringTrait
9
{
10
    public function unique_random($table, $col, $chars = 16)
0 ignored issues
show
The parameter $table is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

10
    public function unique_random(/** @scrutinizer ignore-unused */ $table, $col, $chars = 16)

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

Loading history...
11
    {
12
        $unique = false;
13
14
        // Store tested results in array to not test them again
15
        $tested = [];
16
17
        do {
18
            // Generate random string of characters
19
            $random = Str::random($chars);
20
21
            // Check if it's already testing
22
            // If so, don't query the database again
23
            if (in_array($random, $tested)) {
24
                continue;
25
            }
26
27
            // Check if it is unique in the database
28
            $count = Company::where($col, '=', $random)->count();
29
30
            // Store the random character in the tested array
31
            // To keep track which ones are already tested
32
            $tested[] = $random;
33
34
            // String appears to be unique
35
            if ($count === 0) {
36
                // Set unique to true to break the loop
37
                $unique = true;
38
            }
39
40
            // If unique is still false at this point
41
            // it will just repeat all the steps until
42
            // it has generated a random string of characters
43
        } while (! $unique);
44
45
        return $random;
46
    }
47
}
48