ChunkHash.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /**
  3. * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License").
  6. * You may not use this file except in compliance with the License.
  7. * A copy of the License is located at
  8. *
  9. * http://aws.amazon.com/apache2.0
  10. *
  11. * or in the "license" file accompanying this file. This file is distributed
  12. * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  13. * express or implied. See the License for the specific language governing
  14. * permissions and limitations under the License.
  15. */
  16. namespace Aws\Common\Hash;
  17. use Aws\Common\Exception\LogicException;
  18. /**
  19. * Encapsulates the creation of a hash from streamed chunks of data
  20. */
  21. class ChunkHash implements ChunkHashInterface
  22. {
  23. /**
  24. * @var resource The hash context as created by `hash_init()`
  25. */
  26. protected $context;
  27. /**
  28. * @var string The resulting hash in hex form
  29. */
  30. protected $hash;
  31. /**
  32. * @var string The resulting hash in binary form
  33. */
  34. protected $hashRaw;
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function __construct($algorithm = self::DEFAULT_ALGORITHM)
  39. {
  40. HashUtils::validateAlgorithm($algorithm);
  41. $this->context = hash_init($algorithm);
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function addData($data)
  47. {
  48. if (!$this->context) {
  49. throw new LogicException('You may not add more data to a finalized chunk hash.');
  50. }
  51. hash_update($this->context, $data);
  52. return $this;
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function getHash($returnBinaryForm = false)
  58. {
  59. if (!$this->hash) {
  60. $this->hashRaw = hash_final($this->context, true);
  61. $this->hash = HashUtils::binToHex($this->hashRaw);
  62. $this->context = null;
  63. }
  64. return $returnBinaryForm ? $this->hashRaw : $this->hash;
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. public function __clone()
  70. {
  71. if ($this->context) {
  72. $this->context = hash_copy($this->context);
  73. }
  74. }
  75. }