Skip to content

Instantly share code, notes, and snippets.

@duncanmcclean
Created June 5, 2021 16:01
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 duncanmcclean/a9b465225f887fd4787f8408174ab3be to your computer and use it in GitHub Desktop.
Save duncanmcclean/a9b465225f887fd4787f8408174ab3be to your computer and use it in GitHub Desktop.
Generates & checks parameters are the same between creating & submitting a form. Inspiration from Livewire's checksum component: https://github.com/livewire/livewire/blob/master/src/ComponentChecksumManager.php
<?php
namespace DoubleThreeDigital\SimpleCommerce\Tags\Concerns;
class FormParameters
{
// TODO: this isn't really a 'concern', so maybe we should move this elsewhere?
// Kept in sync with $knownParams on `FormBuilder`
private static $knownParams = [
'redirect', 'error_redirect', 'action_needed_redirect', 'request',
];
public static function generate(array $parameters): string
{
$parameters = collect($parameters)
->filter(function ($value, $key) {
return in_array(ltrim($key, '_'), static::$knownParams);
})
->mapWithKeys(function ($value, $key) {
$key = ltrim($key, '_');
return ["_$key" => $value];
})
->toArray();
return hash_hmac('sha256', json_encode($parameters), app('encrypter')->getKey());
}
public static function check(string $hash, array $parameters)
{
return hash_equals(static::generate($parameters), $hash);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment