Encoder.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /**
  3. * This file is part of Lcobucci\JWT, a simple library to handle JWT and JWS
  4. *
  5. * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
  6. */
  7. namespace Lcobucci\JWT\Parsing;
  8. use JsonException;
  9. use Lcobucci\JWT\Encoding\CannotEncodeContent;
  10. use RuntimeException;
  11. use function json_encode;
  12. use function json_last_error;
  13. use function json_last_error_msg;
  14. /**
  15. * Class that encodes data according with the specs of RFC-4648
  16. *
  17. * @author Luís Otávio Cobucci Oblonczyk <lcobucci@gmail.com>
  18. * @since 0.1.0
  19. *
  20. * @link http://tools.ietf.org/html/rfc4648#section-5
  21. */
  22. class Encoder
  23. {
  24. /**
  25. * Encodes to JSON, validating the errors
  26. *
  27. * @param mixed $data
  28. * @return string
  29. *
  30. * @throws RuntimeException When something goes wrong while encoding
  31. */
  32. public function jsonEncode($data)
  33. {
  34. if (PHP_VERSION_ID < 70300) {
  35. $json = json_encode($data);
  36. if (json_last_error() != JSON_ERROR_NONE) {
  37. throw CannotEncodeContent::jsonIssues(new JsonException(json_last_error_msg()));
  38. }
  39. return $json;
  40. }
  41. try {
  42. return json_encode($data, JSON_THROW_ON_ERROR);
  43. } catch (JsonException $exception) {
  44. throw CannotEncodeContent::jsonIssues($exception);
  45. }
  46. }
  47. /**
  48. * Encodes to base64url
  49. *
  50. * @param string $data
  51. * @return string
  52. */
  53. public function base64UrlEncode($data)
  54. {
  55. return str_replace('=', '', strtr(base64_encode($data), '+/', '-_'));
  56. }
  57. }