Skip to content

Instantly share code, notes, and snippets.

@MarkRedeman
Created January 22, 2015 23:09
Show Gist options
  • Save MarkRedeman/00b46d7d873d21f173d7 to your computer and use it in GitHub Desktop.
Save MarkRedeman/00b46d7d873d21f173d7 to your computer and use it in GitHub Desktop.
This gist uses a decorator to create a `HashedValue` object from the result of the `$hasherContext->make()` function such that it is possible to determine if a string has been hashed.
<?php
// Use a value object to represent Hashed Values (for example passwords)
// this way we can deterine if a string has been hashed before or if it needs hashing
class HashedValue {
private $hash;
public function __construct($hash = '')
{
$this->hash = $hash;
}
public function __toString()
{
return $this->hash;
}
}
trait HashPassword {
// TODO make it customizable
// protected $propertiesToHash = ['password'];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = $this->hashedVersionOf($password);
}
public function getPasswordAttribute($password)
{
return $this->hashedVersionOf($password);
}
public function hashedVersionOf($value)
{
return ($this->isHashed($value)) ? $value : $this->hash($value);
}
public function isHash($value)
{
return is_a($value, HashedValue::class);
}
public function hash($value)
{
return Hash::make($value);
}
}
use Illuminate\Contracts\Hashing\Hasher;
class HashedValueHasher implements HasherContract {
private $hasher;
public function __construct(HasherContract $hasher)
{
$this->hasher = $hasher;
}
public function make($value, array $options = array())
{
$hash = $this->hasher->make($value, $options);
return new HashedValue($hash);
}
public function check($value, $hashedValue, array $options = array())
{
return $this->hasher->check($value, $hashedValue, $options);
}
public function needsRehash($hashedValue, array $options = array())
{
return $this->hasher->needsRehash($hashedValue, $options):
}
}
use Illuminate\Support\ServiceProvider;
use Illuminate\Hashing\BcryptHasher;
class HashVOServiceProvider extends ServiceProvider {
protected $defer = true;
public function register()
{
$this->app->singleton('hash', function() {
$bcryptHasher = new BcryptHasher;;
return new HashedValueHasher($bcryptHasher);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment