Key.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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\Signer;
  8. use Exception;
  9. use InvalidArgumentException;
  10. use Lcobucci\JWT\Signer\Key\FileCouldNotBeRead;
  11. use SplFileObject;
  12. use function strpos;
  13. use function substr;
  14. /**
  15. * @author Luís Otávio Cobucci Oblonczyk <lcobucci@gmail.com>
  16. * @since 3.0.4
  17. */
  18. class Key
  19. {
  20. /**
  21. * @var string
  22. */
  23. protected $content;
  24. /**
  25. * @var string
  26. */
  27. private $passphrase;
  28. /**
  29. * @param string $content
  30. * @param string $passphrase
  31. */
  32. public function __construct($content, $passphrase = '')
  33. {
  34. $this->setContent($content);
  35. $this->passphrase = $passphrase;
  36. }
  37. /**
  38. * @param string $content
  39. *
  40. * @throws InvalidArgumentException
  41. */
  42. private function setContent($content)
  43. {
  44. if (strpos($content, 'file://') === 0) {
  45. $content = $this->readFile($content);
  46. }
  47. $this->content = $content;
  48. }
  49. /**
  50. * @param string $content
  51. *
  52. * @return string
  53. *
  54. * @throws InvalidArgumentException
  55. */
  56. private function readFile($content)
  57. {
  58. $path = substr($content, 7);
  59. try {
  60. $file = new SplFileObject($path);
  61. } catch (Exception $exception) {
  62. throw FileCouldNotBeRead::onPath($path, $exception);
  63. }
  64. $content = '';
  65. while (! $file->eof()) {
  66. $content .= $file->fgets();
  67. }
  68. return $content;
  69. }
  70. /** @return string */
  71. public function contents()
  72. {
  73. return $this->content;
  74. }
  75. /** @return string */
  76. public function passphrase()
  77. {
  78. return $this->passphrase;
  79. }
  80. /**
  81. * @deprecated This method is no longer part of the public interface
  82. * @see Key::contents()
  83. *
  84. * @return string
  85. */
  86. public function getContent()
  87. {
  88. return $this->content;
  89. }
  90. /**
  91. * @deprecated This method is no longer part of the public interface
  92. * @see Key::passphrase()
  93. *
  94. * @return string
  95. */
  96. public function getPassphrase()
  97. {
  98. return $this->passphrase;
  99. }
  100. }