1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
use Illuminate\Support\Str; |
4
|
|
|
|
5
|
|
|
if (! function_exists('unique_random')) { |
6
|
|
|
/** |
7
|
|
|
* Generate a unique random string of characters |
8
|
|
|
* uses str_random() helper for generating the random string. |
9
|
|
|
* |
10
|
|
|
* @param $table - name of the table |
|
|
|
|
11
|
|
|
* @param $col - name of the column that needs to be tested |
12
|
|
|
* @param int $chars - length of the random string |
13
|
|
|
* |
14
|
|
|
* @return string |
15
|
|
|
*/ |
16
|
|
|
function unique_random($table, $col, $chars = 16) |
17
|
|
|
{ |
18
|
|
|
$unique = false; |
19
|
|
|
|
20
|
|
|
// Store tested results in array to not test them again |
21
|
|
|
$tested = []; |
22
|
|
|
|
23
|
|
|
do { |
24
|
|
|
|
25
|
|
|
// Generate random string of characters |
26
|
|
|
$random = Str::random($chars); |
27
|
|
|
|
28
|
|
|
// Check if it's already testing |
29
|
|
|
// If so, don't query the database again |
30
|
|
|
if (in_array($random, $tested)) { |
31
|
|
|
continue; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
// Check if it is unique in the database |
35
|
|
|
$count = DB::table($table)->where($col, '=', $random)->count(); |
36
|
|
|
|
37
|
|
|
// Store the random character in the tested array |
38
|
|
|
// To keep track which ones are already tested |
39
|
|
|
$tested[] = $random; |
40
|
|
|
|
41
|
|
|
// String appears to be unique |
42
|
|
|
if ($count == 0) { |
43
|
|
|
// Set unique to true to break the loop |
44
|
|
|
$unique = true; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
// If unique is still false at this point |
48
|
|
|
// it will just repeat all the steps until |
49
|
|
|
// it has generated a random string of characters |
50
|
|
|
} while (! $unique); |
51
|
|
|
|
52
|
|
|
return $random; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
if (! function_exists('readCSV')) { |
57
|
|
|
function readCSV($filename = '', $delimiter = ',') |
|
|
|
|
58
|
|
|
{ |
59
|
|
|
// Read the file |
60
|
|
|
$file = fopen($filename, 'r'); |
61
|
|
|
|
62
|
|
|
// Iterate over it to get every line |
63
|
|
|
while (($line = fgetcsv($file)) !== false) { |
64
|
|
|
// Store every line in an array |
65
|
|
|
$data[] = $line; |
66
|
|
|
} |
67
|
|
|
fclose($file); |
68
|
|
|
|
69
|
|
|
return $data; |
|
|
|
|
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
if (! function_exists('writeCSV')) { |
74
|
|
|
function writeCSV($filename = '', $data = []) |
75
|
|
|
{ |
76
|
|
|
$file = fopen($filename, 'w'); |
77
|
|
|
|
78
|
|
|
// Write remaining lines to file |
79
|
|
|
foreach ($data as $fields) { |
80
|
|
|
fputcsv($file, $fields); |
81
|
|
|
} |
82
|
|
|
fclose($file); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|