|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PetrKnap\Binary\Coder; |
| 6 | + |
| 7 | +use PetrKnap\Binary\HasRequirementsTrait; |
| 8 | +use PetrKnap\Shorts\HasRequirements; |
| 9 | + |
| 10 | +/** |
| 11 | + * @see hash() |
| 12 | + * |
| 13 | + * @link https://en.wikipedia.org/wiki/Checksum |
| 14 | + */ |
| 15 | +final class Checksum extends Coder implements HasRequirements |
| 16 | +{ |
| 17 | + use HasRequirementsTrait; |
| 18 | + |
| 19 | + public const ALGORITHM = 'crc32'; |
| 20 | + private const REQUIRED_FUNCTIONS = [ |
| 21 | + 'mb_strlen', |
| 22 | + 'mb_strcut', |
| 23 | + ]; |
| 24 | + |
| 25 | + private string $algorithm; |
| 26 | + |
| 27 | + public function __construct() |
| 28 | + { |
| 29 | + self::checkRequirements(); |
| 30 | + } |
| 31 | + |
| 32 | + public function encode(string $decoded, ?string $algorithm = null): string |
| 33 | + { |
| 34 | + $this->algorithm = $algorithm ?? self::ALGORITHM; |
| 35 | + return parent::encode($decoded); |
| 36 | + } |
| 37 | + |
| 38 | + public function decode(string $encoded, ?string $algorithm = null): string |
| 39 | + { |
| 40 | + $this->algorithm = $algorithm ?? self::ALGORITHM; |
| 41 | + return parent::decode($encoded); |
| 42 | + } |
| 43 | + |
| 44 | + protected function doEncode(string $decoded): string |
| 45 | + { |
| 46 | + $checksum = hash($this->algorithm, $decoded, binary: true); |
| 47 | + return $decoded . $checksum; |
| 48 | + } |
| 49 | + |
| 50 | + protected function doDecode(string $encoded): string |
| 51 | + { |
| 52 | + $checksumLength = mb_strlen(hash($this->algorithm, '', binary: true), encoding: '8bit'); |
| 53 | + $dataLength = mb_strlen($encoded, encoding: '8bit') - $checksumLength; |
| 54 | + $decoded = mb_strcut($encoded, 0, $dataLength, encoding: '8bit'); |
| 55 | + if ($this->doEncode($decoded) !== $encoded) { |
| 56 | + throw new Exception\CouldNotDecodeData(__METHOD__, $encoded); |
| 57 | + } |
| 58 | + return $decoded; |
| 59 | + } |
| 60 | +} |
0 commit comments