Skip to content

Commit

Permalink
add custom salted model
Browse files Browse the repository at this point in the history
  • Loading branch information
veelasky committed Jun 22, 2021
1 parent 53d0777 commit d55d33a
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/Eloquent/HashableId.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public static function hashToId(string $hash): ?int
}

/**
* Get Hash Key/.
* Get Hash Key.
*
* @return string
*/
Expand Down Expand Up @@ -146,13 +146,21 @@ public static function bootHashableId()
* Get HashId Repository.
*
* @return \Veelasky\LaravelHashId\Repository
*
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
protected function getHashIdRepository(): Repository
{
if ($this->getKeyType() !== 'int') {
throw new LogicException('Invalid implementation of HashId, only works with `int` value of `keyType`');
}

// get custom salt for the model (if exists)
if (method_exists($this, 'getHashIdSalt')) {
// force the repository to make a new instance of hashid.
app('app.hashid')->make($this->getHashKey(), $this->getHashIdSalt());
}

return app('app.hashid');
}
}
11 changes: 11 additions & 0 deletions tests/Models/CustomSaltModel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Tests\Models;

class CustomSaltModel extends HashModel
{
public function getHashIdSalt(): string
{
return 'custom-salt';
}
}
7 changes: 7 additions & 0 deletions tests/Unit/HashableIdModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Support\Str;
use Tests\Models\HashModel;
use Tests\Models\CustomKeyModel;
use Tests\Models\CustomSaltModel;
use Tests\Models\PersistingModel;
use Tests\Models\IllegalHashModel;
use Veelasky\LaravelHashId\Repository;
Expand Down Expand Up @@ -167,6 +168,12 @@ public function test_custom_key_model()
$this->assertEquals(CustomKeyModel::idToHash($m->getKey()), $m->hash);
}

public function test_custom_salt_model()
{
$this->getRepository()->make('custom', (new CustomSaltModel())->getHashIdSalt());
$this->assertEquals(CustomSaltModel::idToHash(1), $this->getRepository()->idToHash(1, 'custom'));
}

protected function getRepository(): Repository
{
return app('app.hashid');
Expand Down

0 comments on commit d55d33a

Please sign in to comment.