Created
June 5, 2021 16:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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