Skip to content
This repository has been archived by the owner on Dec 29, 2024. It is now read-only.

Commit

Permalink
First init
Browse files Browse the repository at this point in the history
  • Loading branch information
erashdan committed Jan 17, 2019
0 parents commit 388c4b2
Show file tree
Hide file tree
Showing 12 changed files with 511 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
vendor/*
/vendor
composer.lock
/vendor
/.idea
.env
.DS_Store
/.vscode
/.phpunit.result.cache
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Emad Rashdan

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
46 changes: 46 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"name": "erashdan/hashid",
"type": "library",
"keywords": [
"Laravel", "Php", "Hashed ID"
],
"description": "Simple package to hash eloquent primary key",
"require": {
"php": ">=7.1.3",
"hashids/hashids": "^3.0",
"illuminate/container": "~5.5.0|~5.6.0|~5.7.0",
"illuminate/contracts": "~5.5.0|~5.6.0|~5.7.0",
"illuminate/database": "~5.5.0|~5.6.0|~5.7.0"
},
"require-dev": {
"phpunit/phpunit": "^5.7|6.2|^7.0",
"orchestra/testbench": "~3.0"
},
"authors": [
{
"name": "Emad Rashdan",
"email": "[email protected]"
}
],
"minimum-stability": "dev",
"extra": {
"laravel": {
"providers": [
"Erashdan\\Hashid\\HashidServiceProvider"
]
}
},
"autoload": {
"psr-4": {
"Erashdan\\Hashid\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Erashdan\\Hashid\\Test\\": "tests"
}
},
"scripts": {
"test": "phpunit"
}
}
18 changes: 18 additions & 0 deletions config/hashid.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

return [

'hash_data' => [

/*
* Set hashing key to be encrypt and decrypt by
*/
'key' => env('HASHID_KEY'),

/*
* Length for encrypted data.
*/

'length' => env('HASHID_LENGTH', 6),
]
];
25 changes: 25 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="League Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
<php>

</php>
</phpunit>
84 changes: 84 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Eloquent Hashid

* [Installation](#installation)
* [Usage](#usage)
* [Credits](#credits)

This package make the primary key in eloquent is hashed.

```php
// Get Hash ID
$user = \App\User::first();
$user->hashed_id; //x7LR5oQJleJX60yPpNWV
```

## Installation
This package can be used in Laravel 5.5 or higher.

You can install the package via composer:

``` bash
composer require erashdan/hashid
```

The service provider will automatically get registered package.

You should set configuration by publish it to your project:

```bash
php artisan vendor:publish --provider="Erashdan\Hashid\HashidServiceProvider" --tag="config"
```

Then add in .env file
```dotenv
HASHID_KEY=SET_YOUR_KEY
```
**OR**

Change in `config/hashid.php` key parameter to laravel application key
```php
'key' => env('APP_KEY'),
```

You can change hashing length from `.env` file .

```dotenv
HASHID_LENGTH=6
```

## Usage

The eloquent by default will not implement hashid, so you should use it as trait.

```php
use Illuminate\Database\Eloquent\Model;
use Erashdan\Hashid\Traits\Hashid;

class Post extends Model
{
use Hashid;
```

After use trait in eloquent you can call hashed_id attribute.

```php
$post = \App\Post::first();
$post->hashed_id; //x7LR5oQJleJX60yPpNWV
```

To search for hashed element
```php
$post = \App\Post::FindOrFailHashed('x7LR5oQJleJX60yPpNWV');
$post->id; //1
```

## Credits
- [Emad Rashdan](https://github.com/erashdan)


```.todo
- [x] Build dev version.
- [] Create command for key generater.
- [] Can store hash id on database.
- [] Can be cached.
```
60 changes: 60 additions & 0 deletions src/HashData.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

namespace Erashdan\Hashid;

use Hashids\Hashids;

class HashData
{
/**
* Encode ID
*
* @param $key
* @param null $baseKey
* @return mixed
* @throws \Exception
*/
public static function Encode($key, $baseKey)
{
$hashids = new Hashids($baseKey, self::getLength());

return $hashids->encode($key);
}


/**
* Decode ID
*
* @param $key
* @param null $baseKey
* @return mixed
* @throws \Exception
*/
public static function Decode($key, $baseKey = null)
{
if (!$baseKey)
$baseKey = self::getKey();

$hashids = new Hashids($baseKey, self::getLength());
return $hashids->decode($key);
}

/**
* Get length
*
* @throws \Exception
* @return integer
*/
private static function getLength(): int
{
if (
(config('hashid.hash_data.length') == null) ||
(config('hashid.hash_data.length') == '') ||
!is_int(config('hashid.hash_data.length'))
) {
throw new \Exception('Unable to define hashing length');
}

return config('hashid.hash_data.length');
}
}
30 changes: 30 additions & 0 deletions src/HashidServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace Erashdan\Hashid;

use Illuminate\Support\ServiceProvider;

class HashidServiceProvider extends ServiceProvider
{
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/../config/hashid.php' => config_path('hashid.php'),
], 'config');
}

/**
* Register services.
*
* @return void
*/
public function register()
{

}
}
78 changes: 78 additions & 0 deletions src/Traits/Hashid.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

namespace Erashdan\Hashid\Traits;

use Erashdan\Hashid\HashData;
use Illuminate\Database\Eloquent\ModelNotFoundException;

trait Hashid
{
/**
* Encode hashed id
*
* @return mixed
* @throws \Exception
*/
public function getHashedIdAttribute()
{
$primary = $this->primaryKey;
return HashData::Encode($this->$primary, self::setHashKey(self::class), 20);
}

/**
* Decode hash id
*
* @param $id
* @return |null
* @throws \Exception
*/
public static function DecodeId($id)
{
$decode = HashData::Decode($id, self::setHashKey(self::class), 20);

if (count($decode) > 0) {
return $decode[0];
}

return null;
}

public function scopeFindOrFailHashed($query, $id)
{
if (empty($decoded = self::DecodeId($id))) {
throw new ModelNotFoundException('Unable to find element', 404);
}

return $query->findOrFail(self::DecodeId($id));
}

public function scopeFindHashed($query, $id)
{
if (empty($decoded = self::DecodeId($id))) {
return null;
}

return $query->find(self::DecodeId($id));
}

public function scopeWhereInHashed($query, $values)
{
$hash = [];
foreach ($values as $value) {
$hash[] = self::DecodeId($value);
}
return $query->whereIn($this->primaryKey, $hash);
}

private static function setHashKey($class)
{
if (
(config('hashid.hash_data.key') == null) ||
(config('hashid.hash_data.key') == '')
) {
throw new \Exception('Unable to define hashing key');
}

return config('hashid.hash_data.key') . $class;
}
}
Loading

0 comments on commit 388c4b2

Please sign in to comment.