Skip to content

Instantly share code, notes, and snippets.

@alexstandiford
Last active September 12, 2020 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexstandiford/5186d55bbf4998f0da0f97a5abf957e9 to your computer and use it in GitHub Desktop.
Save alexstandiford/5186d55bbf4998f0da0f97a5abf957e9 to your computer and use it in GitHub Desktop.
hash-generator
<?php
class Hash_Generator {
/**
* The generated hash.
*
* @var string
*/
private $hash = false;
/**
* Hash_Generator constructor.
*
* @param mixed $item data from which to generate the hash
* @param array|bool $whitelist Whitelist of allowed data in the hash. Optional.
*/
public function __construct( $item, $whitelist = false ) {
if ( is_array( $whitelist ) ) {
$this->item = array_intersect_key( $item, array_flip( $whitelist ) );
} else {
$this->item = $item;
}
}
/**
* Retrieves the hash.
*
* @since 1.2.4
*
* @return string
*/
public function get() {
if ( false === $this->hash ) {
$sorted = $this->sort( $this->item );
$this->hash = md5( maybe_serialize( $sorted ) );
}
return $this->hash;
}
/**
* Recursively sorts the data, if it needs to-be sorted.
*
* @param mixed $item The item to sort.
* @return mixed The sorted data. If the item is not an array or object, this will simply return the item, untouched.
*/
private function sort( $item ) {
if ( is_array( $item ) || is_object( $item ) ) {
$item = get_object_vars( (object) $item );
$result = [];
foreach ( $item as $key => $value ) {
$result[ $key ] = $this->sort( $value );
}
ksort( $item );
}
return $item;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment