TemporaryStorage.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation\File;
  11. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  12. use Symfony\Component\HttpFoundation\File\Exception\UnexpectedTypeException;
  13. /**
  14. * @author Bernhard Schussek <bernhard.schussek@symfony-project.com>
  15. */
  16. class TemporaryStorage
  17. {
  18. private $directory;
  19. private $secret;
  20. private $nestingLevels;
  21. public function __construct($secret, $nestingLevels = 3, $directory = null)
  22. {
  23. if (empty($directory)) {
  24. $directory = sys_get_temp_dir();
  25. }
  26. $this->directory = realpath($directory);
  27. $this->secret = $secret;
  28. $this->nestingLevels = $nestingLevels;
  29. }
  30. protected function generateHashInfo($token)
  31. {
  32. return $this->secret . $token;
  33. }
  34. protected function generateHash($token)
  35. {
  36. return md5($this->generateHashInfo($token));
  37. }
  38. public function getTempDir($token)
  39. {
  40. if (!is_string($token)) {
  41. throw new UnexpectedTypeException($token, 'string');
  42. }
  43. $hash = $this->generateHash($token);
  44. if (strlen($hash) < $this->nestingLevels) {
  45. throw new FileException(sprintf(
  46. 'For %s nesting levels the hash must have at least %s characters', $this->nestingLevels, $this->nestingLevels));
  47. }
  48. $directory = $this->directory;
  49. for ($i = 0; $i < ($this->nestingLevels - 1); ++$i) {
  50. $directory .= DIRECTORY_SEPARATOR . $hash{$i};
  51. }
  52. return $directory . DIRECTORY_SEPARATOR . substr($hash, $i);
  53. }
  54. }