Skip to content

Commit d55d33a

Browse files
committed
add custom salted model
1 parent 53d0777 commit d55d33a

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

src/Eloquent/HashableId.php

+9-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ public static function hashToId(string $hash): ?int
7878
}
7979

8080
/**
81-
* Get Hash Key/.
81+
* Get Hash Key.
8282
*
8383
* @return string
8484
*/
@@ -146,13 +146,21 @@ public static function bootHashableId()
146146
* Get HashId Repository.
147147
*
148148
* @return \Veelasky\LaravelHashId\Repository
149+
*
150+
* @throws \Illuminate\Contracts\Container\BindingResolutionException
149151
*/
150152
protected function getHashIdRepository(): Repository
151153
{
152154
if ($this->getKeyType() !== 'int') {
153155
throw new LogicException('Invalid implementation of HashId, only works with `int` value of `keyType`');
154156
}
155157

158+
// get custom salt for the model (if exists)
159+
if (method_exists($this, 'getHashIdSalt')) {
160+
// force the repository to make a new instance of hashid.
161+
app('app.hashid')->make($this->getHashKey(), $this->getHashIdSalt());
162+
}
163+
156164
return app('app.hashid');
157165
}
158166
}

tests/Models/CustomSaltModel.php

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
namespace Tests\Models;
4+
5+
class CustomSaltModel extends HashModel
6+
{
7+
public function getHashIdSalt(): string
8+
{
9+
return 'custom-salt';
10+
}
11+
}

tests/Unit/HashableIdModelTest.php

+7
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use Illuminate\Support\Str;
77
use Tests\Models\HashModel;
88
use Tests\Models\CustomKeyModel;
9+
use Tests\Models\CustomSaltModel;
910
use Tests\Models\PersistingModel;
1011
use Tests\Models\IllegalHashModel;
1112
use Veelasky\LaravelHashId\Repository;
@@ -167,6 +168,12 @@ public function test_custom_key_model()
167168
$this->assertEquals(CustomKeyModel::idToHash($m->getKey()), $m->hash);
168169
}
169170

171+
public function test_custom_salt_model()
172+
{
173+
$this->getRepository()->make('custom', (new CustomSaltModel())->getHashIdSalt());
174+
$this->assertEquals(CustomSaltModel::idToHash(1), $this->getRepository()->idToHash(1, 'custom'));
175+
}
176+
170177
protected function getRepository(): Repository
171178
{
172179
return app('app.hashid');

0 commit comments

Comments
 (0)