Skip to content

Commit 74715a4

Browse files
committed
Added comments
1 parent 062d52a commit 74715a4

File tree

1 file changed

+43
-7
lines changed

1 file changed

+43
-7
lines changed

src/Keyable.php

Lines changed: 43 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,19 @@
88

99
trait Keyable
1010
{
11-
public static function bootKeyable()
11+
/**
12+
* Boots the Keyable trait.
13+
*/
14+
public static function bootKeyable() : void
1215
{
1316
static::creating(function ($model) {
1417
$model->assignUniqueKeys();
1518
});
1619
}
1720

21+
/**
22+
* Assign keys to the current model instance.
23+
*/
1824
public function assignUniqueKeys() : void
1925
{
2026
if ( ! property_exists($this, 'keys')) {
@@ -30,30 +36,60 @@ public function assignUniqueKeys() : void
3036
}
3137
}
3238

39+
/**
40+
* Generates a random string.
41+
*
42+
* @param string $attribute
43+
* @param integer $length
44+
* @return string
45+
*/
3346
public function keyableStrategy(string $attribute, int $length = 32) : string
3447
{
3548
return Str::random($length);
3649
}
3750

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
3959
{
4060
$table = $this->getTable();
4161

4262
do {
4363
$key = $this->keyableStrategy($attribute, $length);
44-
} while (DB::table($table)->where($attribute, $key)->first());
64+
} while (DB::table($table)->where($attribute, $key)->exists());
4565

4666
return $key;
4767
}
4868

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
5077
{
51-
return static::where('key', $key)->first();
78+
return static::where($attribute, $value)->first();
5279
}
5380

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)
5591
{
56-
$model = static::findByKey($key);
92+
$model = static::findByKey($attribute, $value);
5793

5894
if ( ! $model) {
5995
return abort($code);

0 commit comments

Comments
 (0)