8
8
9
9
trait Keyable
10
10
{
11
- public static function bootKeyable ()
11
+ /**
12
+ * Boots the Keyable trait.
13
+ */
14
+ public static function bootKeyable () : void
12
15
{
13
16
static ::creating (function ($ model ) {
14
17
$ model ->assignUniqueKeys ();
15
18
});
16
19
}
17
20
21
+ /**
22
+ * Assign keys to the current model instance.
23
+ */
18
24
public function assignUniqueKeys () : void
19
25
{
20
26
if ( ! property_exists ($ this , 'keys ' )) {
@@ -30,30 +36,60 @@ public function assignUniqueKeys() : void
30
36
}
31
37
}
32
38
39
+ /**
40
+ * Generates a random string.
41
+ *
42
+ * @param string $attribute
43
+ * @param integer $length
44
+ * @return string
45
+ */
33
46
public function keyableStrategy (string $ attribute , int $ length = 32 ) : string
34
47
{
35
48
return Str::random ($ length );
36
49
}
37
50
38
- public function generateUniqueKey (string $ attribute , int $ length )
51
+ /**
52
+ * Generates a unique key against the current table.
53
+ *
54
+ * @param string $attribute
55
+ * @param int $length
56
+ * @return string
57
+ */
58
+ public function generateUniqueKey (string $ attribute , int $ length ) : string
39
59
{
40
60
$ table = $ this ->getTable ();
41
61
42
62
do {
43
63
$ key = $ this ->keyableStrategy ($ attribute , $ length );
44
- } while (DB ::table ($ table )->where ($ attribute , $ key )->first ());
64
+ } while (DB ::table ($ table )->where ($ attribute , $ key )->exists ());
45
65
46
66
return $ key ;
47
67
}
48
68
49
- static function findByKey (string $ key ) : ?Model
69
+ /**
70
+ * Find a model by its key.
71
+ *
72
+ * @param string $attribute
73
+ * @param string $value
74
+ * @return Model|null
75
+ */
76
+ static function findByKey (string $ attribute , string $ value ) : ?Model
50
77
{
51
- return static ::where (' key ' , $ key )->first ();
78
+ return static ::where ($ attribute , $ value )->first ();
52
79
}
53
80
54
- static function findByKeyOrFail (string $ key , $ code = 404 ) : ?Model
81
+ /**
82
+ * Find a model by its key or throw an exception.
83
+ *
84
+ * @param string $key
85
+ * @param integer $code
86
+ * @return Model|void
87
+ *
88
+ * @throws \Symfony\Component\HttpKernel\Exception\HttpException
89
+ */
90
+ static function findByKeyOrFail (string $ attribute , string $ value , int $ code = 404 )
55
91
{
56
- $ model = static ::findByKey ($ key );
92
+ $ model = static ::findByKey ($ attribute , $ value );
57
93
58
94
if ( ! $ model ) {
59
95
return abort ($ code );
0 commit comments