ObjectUtils.php 623 B

1234567891011121314151617181920212223
  1. <?php
  2. namespace App\Service\Utils;
  3. class ObjectUtils
  4. {
  5. /**
  6. * Créé un hash à partir d'un objet
  7. * (après l'avoir trié selon ses clés, et convertit en json sans espace).
  8. *
  9. * @param object|array<mixed> $instance
  10. */
  11. public static function hash(object|array $instance, string $algorithm = 'sha256'): string
  12. {
  13. // Convertit l'objet en tableau associatif
  14. $array = (array) $instance;
  15. // Puis trie l'objet selon ses clés, encode en json, et hash
  16. ksort($array);
  17. $json = json_encode((object) $array);
  18. return hash($algorithm, $json);
  19. }
  20. }