diff --git a/.gitignore b/.gitignore index 800c48f..27a8720 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,5 @@ vendor/ composer.lock .idea .DS_Store +/.phpunit.result.cache +/.phpunit.cache diff --git a/composer.json b/composer.json index abe53a3..6c6fe89 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "nmiles/phpqrcode", - "description": "PHP 7 QR Code library - update of original version by Dominik Dzienia", + "description": "PHP 8 QR Code library - update of original version by Dominik Dzienia", "type": "library", "license": "LGPL-3.0-or-later", "keywords": [ @@ -8,13 +8,15 @@ "qr" ], "require": { - "php": ">=7.3", + "php": "^8.1", "ext-gd": "*", "ext-zlib": "*" }, "require-dev": { - "phpunit/phpunit": "^7.1.4", - "squizlabs/php_codesniffer": "^3.5" + "phpunit/phpunit": "^12.3.6", + "squizlabs/php_codesniffer": "^3.5.4", + "symplify/easy-coding-standard": "^12.5", + "rector/rector": "^2.1" }, "autoload": { "psr-4": { diff --git a/ecs.php b/ecs.php new file mode 100644 index 0000000..98346e0 --- /dev/null +++ b/ecs.php @@ -0,0 +1,21 @@ +withSpacing( + Option::INDENTATION_SPACES, + PHP_EOL + ) + ->withPaths([ + __DIR__ . '/src', + __DIR__ . '/test', + ]) + ->withPreparedSets( + psr12: true, common: true, symplify: true + ) + ->withRules([ + ]); diff --git a/phpunit.xml b/phpunit.xml index 638ccb6..e070f8f 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,17 +1,13 @@ - - - - ./test - - - - - - ./src - - - \ No newline at end of file + + + + ./test + + + + + ./src + + + diff --git a/rector.php b/rector.php new file mode 100644 index 0000000..c1e5f05 --- /dev/null +++ b/rector.php @@ -0,0 +1,17 @@ +withPaths([ + __DIR__ . '/src', + __DIR__ . '/test', + ]) + ->withPreparedSets( + deadCode: true, + codeQuality: true, + codingStyle: true, + ) + ->withPhpSets(php81: true); \ No newline at end of file diff --git a/src/Bitstream.php b/src/Bitstream.php index bbabf61..fefa802 100755 --- a/src/Bitstream.php +++ b/src/Bitstream.php @@ -1,78 +1,61 @@ data); } - public function allocate(int $setLength): int { $this->data = array_fill(0, $setLength, 0); return 0; } - - public static function newFromNum(int $bits, int $num): Bitstream + public static function newFromNum(int $bits, int $num): self { - $bstream = new Bitstream(); + $bstream = new self(); $bstream->allocate($bits); $mask = 1 << ($bits - 1); for ($i = 0; $i < $bits; $i++) { - if ($num & $mask) { - $bstream->data[$i] = 1; - } else { - $bstream->data[$i] = 0; - } - $mask = $mask >> 1; + $bstream->data[$i] = ($num & $mask) !== 0 ? 1 : 0; + + $mask >>= 1; } return $bstream; } - - public static function newFromBytes(int $size, array $data): Bitstream + public static function newFromBytes(int $size, array $data): self { - $bstream = new Bitstream(); + $bstream = new self(); $bstream->allocate($size * 8); + $p = 0; for ($i = 0; $i < $size; $i++) { $mask = 0x80; for ($j = 0; $j < 8; $j++) { - if ($data[$i] & $mask) { - $bstream->data[$p] = 1; - } else { - $bstream->data[$p] = 0; - } + $bstream->data[$p] = ($data[$i] & $mask) !== 0 ? 1 : 0; + $p++; - $mask = $mask >> 1; + $mask >>= 1; } } return $bstream; } - public function append(Bitstream $arg): int + public function append(self $arg): int { - if (is_null($arg)) { - return -1; - } - if ($arg->size() == 0) { return 0; } @@ -93,11 +76,7 @@ public function appendNum(int $bits, int $num): int return 0; } - $b = Bitstream::newFromNum($bits, $num); - - if (is_null($b)) { - return -1; - } + $b = self::newFromNum($bits, $num); $ret = $this->append($b); unset($b); @@ -105,17 +84,13 @@ public function appendNum(int $bits, int $num): int return $ret; } - public function appendBytes(int $size, array $data) :int + public function appendBytes(int $size, array $data): int { if ($size == 0) { return 0; } - $b = Bitstream::newFromBytes($size, $data); - - if (is_null($b)) { - return -1; - } + $b = self::newFromBytes($size, $data); $ret = $this->append($b); unset($b); @@ -131,28 +106,30 @@ public function toByte(): array return []; } - $data = array_fill(0, (int)(($size + 7) / 8), 0); - $bytes = (int)($size / 8); + $data = array_fill(0, (int) (($size + 7) / 8), 0); + $bytes = (int) ($size / 8); $p = 0; for ($i = 0; $i < $bytes; $i++) { $v = 0; for ($j = 0; $j < 8; $j++) { - $v = $v << 1; + $v <<= 1; $v |= $this->data[$p]; $p++; } + $data[$i] = $v; } - if ($size & 7) { + if (($size & 7) !== 0) { $v = 0; for ($j = 0; $j < ($size & 7); $j++) { - $v = $v << 1; + $v <<= 1; $v |= $this->data[$p]; $p++; } + $data[$bytes] = $v; } diff --git a/src/Code.php b/src/Code.php index ec0216d..225414b 100644 --- a/src/Code.php +++ b/src/Code.php @@ -1,27 +1,28 @@ getVersion() < 0 || $input->getVersion() > Spec::QRSPEC_VERSION_MAX) { throw new Exception('wrong version'); } + if ($input->getErrorCorrectionLevel() > Str::QR_ECLEVEL_H) { throw new Exception('wrong level'); } @@ -35,9 +36,6 @@ public function encodeMask(Input $input, $mask) $frame = Spec::newFrame($version); $filler = new FrameFiller($width, $frame); - if (is_null($filler)) { - return null; - } // interleaved data and ecc codes for ($i = 0; $i < $raw->dataLength + $raw->eccLength; $i++) { @@ -46,7 +44,7 @@ public function encodeMask(Input $input, $mask) for ($j = 0; $j < 8; $j++) { $addr = $filler->next(); $filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0)); - $bit = $bit >> 1; + $bit >>= 1; } } @@ -70,13 +68,18 @@ public function encodeMask(Input $input, $mask) if (Config::$findBestMask) { $masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel()); } else { - $masked = $maskObj->makeMask($width, $frame, (intval(Config::$defaultMask) % 8), $input->getErrorCorrectionLevel()); + $masked = $maskObj->makeMask( + $width, + $frame, + (intval(Config::$defaultMask) % 8), + $input->getErrorCorrectionLevel() + ); } } else { $masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel()); } - if (is_null($masked)) { + if ($masked === null) { return null; } @@ -96,7 +99,7 @@ public function encodeInput(Input $input) public function encodeString8bit(string $string, $version, $level) { - if (is_null($string)) { + if ($string === null) { throw new Exception('empty string!'); } @@ -110,6 +113,7 @@ public function encodeString8bit(string $string, $version, $level) unset($input); return null; } + return $this->encodeInput($input); } @@ -120,9 +124,6 @@ public function encodeString(string $string, $version, $level, $hint, $casesensi } $input = new Input($version, $level); - if (is_null($input)) { - return null; - } $ret = Split::splitStringToQRInput($string, $input, $hint, $casesensitive); if ($ret < 0) { @@ -132,20 +133,36 @@ public function encodeString(string $string, $version, $level, $hint, $casesensi return $this->encodeInput($input); } - public static function png(string $text, string $outfile = null, $level = Str::QR_ECLEVEL_L, int $size = 3, int $margin = 4, bool $saveAndPrint = false) - { + public static function png( + string $text, + string $outfile = null, + $level = Str::QR_ECLEVEL_L, + int $size = 3, + int $margin = 4, + bool $saveAndPrint = false + ) { $enc = Encode::factory($level, $size, $margin); return $enc->encodePNG($text, $outfile, $saveAndPrint); } - public static function text(string $text, string $outfile = null, $level = Str::QR_ECLEVEL_L, int $size = 3, int $margin = 4) - { + public static function text( + string $text, + string $outfile = null, + $level = Str::QR_ECLEVEL_L, + int $size = 3, + int $margin = 4 + ) { $enc = Encode::factory($level, $size, $margin); return $enc->encode($text, $outfile); } - public static function raw(string $text, string $outfile = null, $level = Str::QR_ECLEVEL_L, int $size = 3, int $margin = 4) - { + public static function raw( + string $text, + string $outfile = null, + $level = Str::QR_ECLEVEL_L, + int $size = 3, + int $margin = 4 + ) { $enc = Encode::factory($level, $size, $margin); return $enc->encodeRAW($text); } diff --git a/src/Config.php b/src/Config.php index f9ac3b3..623f043 100755 --- a/src/Config.php +++ b/src/Config.php @@ -1,34 +1,41 @@ $value) { - static::$$key = $value; + static::${$key} = $value; } } } diff --git a/src/Encode.php b/src/Encode.php index aec8d79..50a0af1 100755 --- a/src/Encode.php +++ b/src/Encode.php @@ -1,33 +1,35 @@ size = $size; $enc->margin = $margin; @@ -84,11 +86,13 @@ public function encode(string $inText, string $outfile = null) Tools::markTime('after_encode'); - if (!empty($outfile)) { - file_put_contents($outfile, join("\n", Tools::binarize($code->data))); + if (! empty($outfile)) { + file_put_contents($outfile, implode("\n", Tools::binarize($code->data))); } else { return Tools::binarize($code->data); } + + return null; } public function encodePNG(string $inText, string $outfile, $saveAndPrint = false) @@ -103,13 +107,14 @@ public function encodePNG(string $inText, string $outfile, $saveAndPrint = false Tools::log($outfile, $err); } - $maxSize = (int)(Config::$pngMaximumSize / (count($tab) + 2 * $this->margin)); + $maxSize = (int) (Config::$pngMaximumSize / (count($tab) + 2 * $this->margin)); Image::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin, $saveAndPrint); - } catch (Exception $e) { - Tools::log($outfile, $e->getMessage()); + } catch (Exception $exception) { + Tools::log($outfile, $exception->getMessage()); } + return $outfile; } } diff --git a/src/FrameFiller.php b/src/FrameFiller.php index 40d4e76..dd5933a 100644 --- a/src/FrameFiller.php +++ b/src/FrameFiller.php @@ -1,53 +1,42 @@ width = $width; - $this->frame = $frame; - $this->x = $width - 1; - $this->y = $width - 1; - $this->dir = -1; - $this->bit = -1; - } + public int $dir = -1; + public int $bit = -1; - public function setFrameAt($at, $val) - { - $this->frame[$at['y']][$at['x']] = chr($val); + public function __construct( + public $width, + public $frame + ) { + $this->x = $this->width - 1; + $this->y = $this->width - 1; } - - public function getFrameAt($at) + public function setFrameAt($at, $val) { - return ord($this->frame[$at['y']][$at['x']]); + $this->frame[$at['y']][$at['x']] = chr($val); } - public function next() { do { if ($this->bit == -1) { $this->bit = 0; - return array('x' => $this->x, 'y' => $this->y); + return [ + 'x' => $this->x, + 'y' => $this->y, + ]; } $x = $this->x; @@ -73,25 +62,28 @@ public function next() $y = 9; } } - } else { - if ($y == $w) { - $y = $w - 1; - $x -= 2; - $this->dir = -1; - if ($x == 6) { - $x--; - $y -= 8; - } + } elseif ($y == $w) { + $y = $w - 1; + $x -= 2; + $this->dir = -1; + if ($x == 6) { + $x--; + $y -= 8; } } - if ($x < 0 || $y < 0) return null; + + if ($x < 0 || $y < 0) { + return null; + } $this->x = $x; $this->y = $y; } while (ord($this->frame[$y][$x]) & 0x80); - return array('x' => $x, 'y' => $y); + return [ + 'x' => $x, + 'y' => $y, + ]; } - } diff --git a/src/Image.php b/src/Image.php index 1252e6b..903d5a3 100755 --- a/src/Image.php +++ b/src/Image.php @@ -1,41 +1,45 @@ level = $level; } - public function getVersion() { return $this->version; } - public function setVersion($version) { if ($version < 0 || $version > Spec::QRSPEC_VERSION_MAX) { @@ -47,13 +53,11 @@ public function setVersion($version) return 0; } - public function getErrorCorrectionLevel() { return $this->level; } - public function setErrorCorrectionLevel($level) { if ($level > Str::QR_ECLEVEL_H) { @@ -65,25 +69,22 @@ public function setErrorCorrectionLevel($level) return 0; } - public function appendEntry(InputItem $entry) { $this->items[] = $entry; } - public function append($mode, $size, $data) { try { $entry = new InputItem($mode, $size, $data); $this->items[] = $entry; return 0; - } catch (Exception $e) { + } catch (Exception) { return -1; } } - public function insertStructuredAppendHeader($size, $index, $parity) { if ($size > static::MAX_STRUCTURED_SYMBOLS) { @@ -94,18 +95,17 @@ public function insertStructuredAppendHeader($size, $index, $parity) throw new Exception('insertStructuredAppendHeader wrong index'); } - $buf = array($size, $index, $parity); + $buf = [$size, $index, $parity]; try { $entry = new InputItem(Str::QR_MODE_STRUCTURE, 3, $buf); array_unshift($this->items, $entry); return 0; - } catch (Exception $e) { + } catch (Exception) { return -1; } } - public function calcParity() { $parity = 0; @@ -121,7 +121,6 @@ public function calcParity() return $parity; } - public static function checkModeNum($size, $data) { for ($i = 0; $i < $size; $i++) { @@ -133,10 +132,9 @@ public static function checkModeNum($size, $data) return true; } - public static function estimateBitsModeNum($size) { - $w = (int)$size / 3; + $w = (int) $size / 3; $bits = $w * 10; switch ($size - $w * 3) { @@ -153,25 +151,11 @@ public static function estimateBitsModeNum($size) return $bits; } - - public static $anTable = array( - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, - -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - ); - - public static function lookAnTable($c) { - return (($c > 127) ? -1 : self::$anTable[$c]); + return ($c > 127) ? -1 : self::$anTable[$c]; } - public static function checkModeAn($size, $data) { for ($i = 0; $i < $size; $i++) { @@ -183,36 +167,33 @@ public static function checkModeAn($size, $data) return true; } - public static function estimateBitsModeAn($size) { - $w = (int)($size / 2); + $w = (int) ($size / 2); $bits = $w * 11; - if ($size & 1) { + if (($size & 1) !== 0) { $bits += 6; } return $bits; } - public static function estimateBitsMode8($size) { return $size * 8; } - public static function estimateBitsModeKanji($size) { - return (int)(($size / 2) * 13); + return (int) (($size / 2) * 13); } - public static function checkModeKanji($size, $data) { - if ($size & 1) + if (($size & 1) !== 0) { return false; + } for ($i = 0; $i < $size; $i += 2) { $val = (ord($data[$i]) << 8) | ord($data[$i + 1]); @@ -232,23 +213,20 @@ public static function checkModeKanji($size, $data) public static function check($mode, $size, $data) { - if ($size <= 0) + if ($size <= 0) { return false; + } switch ($mode) { case Str::QR_MODE_NUM: return self::checkModeNum($size, $data); - break; case Str::QR_MODE_AN: return self::checkModeAn($size, $data); - break; case Str::QR_MODE_KANJI: return self::checkModeKanji($size, $data); - break; case Str::QR_MODE_8: case Str::QR_MODE_STRUCTURE: return true; - break; default: break; } @@ -256,7 +234,6 @@ public static function check($mode, $size, $data) return false; } - public function estimateBitStreamSize($version) { $bits = 0; @@ -268,14 +245,13 @@ public function estimateBitStreamSize($version) return $bits; } - public function estimateVersion() { $version = 0; do { $prev = $version; $bits = $this->estimateBitStreamSize($prev); - $version = Spec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); + $version = Spec::getMinimumVersion((int) (($bits + 7) / 8), $this->level); if ($version < 0) { return -1; } @@ -284,34 +260,36 @@ public function estimateVersion() return $version; } - public static function lengthOfCode($mode, $version, $bits) { $payload = $bits - 4 - Spec::lengthIndicator($mode, $version); switch ($mode) { case Str::QR_MODE_NUM: - $chunks = (int)($payload / 10); + $chunks = (int) ($payload / 10); $remain = $payload - $chunks * 10; $size = $chunks * 3; if ($remain >= 7) { $size += 2; - } else if ($remain >= 4) { - $size += 1; + } elseif ($remain >= 4) { + ++$size; } + break; case Str::QR_MODE_AN: - $chunks = (int)($payload / 11); + $chunks = (int) ($payload / 11); $remain = $payload - $chunks * 11; $size = $chunks * 2; - if ($remain >= 6) + if ($remain >= 6) { $size++; + } + break; case Str::QR_MODE_KANJI: - $size = (int)(($payload / 13) * 2); + $size = (int) (($payload / 13) * 2); break; case Str::QR_MODE_8: case Str::QR_MODE_STRUCTURE: - $size = (int)($payload / 8); + $size = (int) ($payload / 8); break; default: $size = 0; @@ -319,13 +297,17 @@ public static function lengthOfCode($mode, $version, $bits) } $maxsize = Spec::maximumWords($mode, $version); - if ($size < 0) $size = 0; - if ($size > $maxsize) $size = $maxsize; + if ($size < 0) { + $size = 0; + } + + if ($size > $maxsize) { + $size = $maxsize; + } return $size; } - public function createBitStream() { $total = 0; @@ -333,8 +315,9 @@ public function createBitStream() foreach ($this->items as $item) { $bits = $item->encodeBitStream($this->version); - if ($bits < 0) + if ($bits < 0) { return -1; + } $total += $bits; } @@ -342,7 +325,6 @@ public function createBitStream() return $total; } - public function convertData() { $ver = $this->estimateVersion(); @@ -353,13 +335,14 @@ public function convertData() for (; ;) { $bits = $this->createBitStream(); - if ($bits < 0) + if ($bits < 0) { return -1; + } - $ver = Spec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); + $ver = Spec::getMinimumVersion((int) (($bits + 7) / 8), $this->level); if ($ver < 0) { throw new Exception('WRONG VERSION'); - } else if ($ver > $this->getVersion()) { + } elseif ($ver > $this->getVersion()) { $this->setVersion($ver); } else { break; @@ -369,7 +352,6 @@ public function convertData() return 0; } - public function appendPaddingBit(Bitstream &$bstream): ?int { $bits = $bstream->size(); @@ -385,13 +367,14 @@ public function appendPaddingBit(Bitstream &$bstream): ?int } $bits += 4; - $words = (int)(($bits + 7) / 8); + $words = (int) (($bits + 7) / 8); $padding = new Bitstream(); $ret = $padding->appendNum($words * 8 - $bits + 4, 0); - if ($ret < 0) + if ($ret < 0) { return $ret; + } $padlen = $maxwords - $words; @@ -399,22 +382,20 @@ public function appendPaddingBit(Bitstream &$bstream): ?int $padbuf = []; for ($i = 0; $i < $padlen; $i++) { - $padbuf[$i] = ($i & 1) ? 0x11 : 0xec; + $padbuf[$i] = (($i & 1) !== 0) ? 0x11 : 0xec; } $ret = $padding->appendBytes($padlen, $padbuf); - if ($ret < 0) + if ($ret < 0) { return $ret; + } } - $ret = $bstream->append($padding); - - return $ret; + return $bstream->append($padding); } - public function mergeBitStream(): ?Bitstream { if ($this->convertData() < 0) { @@ -433,13 +414,12 @@ public function mergeBitStream(): ?Bitstream return $bstream; } - public function getBitStream(): ?Bitstream { $bstream = $this->mergeBitStream(); - if (empty($bstream)) { + if (! $bstream instanceof Bitstream) { return null; } @@ -451,11 +431,10 @@ public function getBitStream(): ?Bitstream return $bstream; } - public function getByteStream() { $bstream = $this->getBitStream(); - if (empty($bstream)) { + if (! $bstream instanceof Bitstream) { return null; } diff --git a/src/InputItem.php b/src/InputItem.php index c93866a..2d3e931 100755 --- a/src/InputItem.php +++ b/src/InputItem.php @@ -1,48 +1,39 @@ mode = $mode; - $this->size = $size; $this->data = $setData; - $this->bstream = $bstream; } - public function encodeModeNum($version) { try { - $words = (int)($this->size / 3); + $words = (int) ($this->size / 3); $bs = new Bitstream(); $val = 0x1; @@ -59,7 +50,7 @@ public function encodeModeNum($version) if ($this->size - $words * 3 == 1) { $val = ord($this->data[$words * 3]) - ord('0'); $bs->appendNum(4, $val); - } else if ($this->size - $words * 3 == 2) { + } elseif ($this->size - $words * 3 == 2) { $val = (ord($this->data[$words * 3]) - ord('0')) * 10; $val += (ord($this->data[$words * 3 + 1]) - ord('0')); $bs->appendNum(7, $val); @@ -68,29 +59,28 @@ public function encodeModeNum($version) $this->bstream = $bs; return 0; - } catch (Exception $e) { + } catch (Exception) { return -1; } } - public function encodeModeAn($version) { try { - $words = (int)($this->size / 2); + $words = (int) ($this->size / 2); $bs = new Bitstream(); $bs->appendNum(4, 0x02); $bs->appendNum(Spec::lengthIndicator(Str::QR_MODE_AN, $version), $this->size); for ($i = 0; $i < $words; $i++) { - $val = (int)Input::lookAnTable(ord($this->data[$i * 2])) * 45; - $val += (int)Input::lookAnTable(ord($this->data[$i * 2 + 1])); + $val = (int) Input::lookAnTable(ord($this->data[$i * 2])) * 45; + $val += (int) Input::lookAnTable(ord($this->data[$i * 2 + 1])); $bs->appendNum(11, $val); } - if ($this->size & 1) { + if (($this->size & 1) !== 0) { $val = Input::lookAnTable(ord($this->data[$words * 2])); $bs->appendNum(6, $val); } @@ -98,12 +88,11 @@ public function encodeModeAn($version) $this->bstream = $bs; return 0; - } catch (Exception $e) { + } catch (Exception) { return -1; } } - public function encodeMode8($version) { try { @@ -119,12 +108,11 @@ public function encodeMode8($version) $this->bstream = $bs; return 0; - } catch (Exception $e) { + } catch (Exception) { return -1; } } - public function encodeModeKanji($version) { try { @@ -132,7 +120,7 @@ public function encodeModeKanji($version) $bs = new Bitstream(); $bs->appendNum(4, 0x8); - $bs->appendNum(Spec::lengthIndicator(Str::QR_MODE_KANJI, $version), (int)($this->size / 2)); + $bs->appendNum(Spec::lengthIndicator(Str::QR_MODE_KANJI, $version), (int) ($this->size / 2)); for ($i = 0; $i < $this->size; $i += 2) { $val = (ord($this->data[$i]) << 8) | ord($this->data[$i + 1]); @@ -151,12 +139,11 @@ public function encodeModeKanji($version) $this->bstream = $bs; return 0; - } catch (Exception $e) { + } catch (Exception) { return -1; } } - public function encodeModeStructure() { try { @@ -170,12 +157,11 @@ public function encodeModeStructure() $this->bstream = $bs; return 0; - } catch (Exception $e) { + } catch (Exception) { return -1; } } - public function estimateBitStreamSizeOfEntry($version) { if ($version == 0) { @@ -203,14 +189,11 @@ public function estimateBitStreamSizeOfEntry($version) $l = Spec::lengthIndicator($this->mode, $version); $m = 1 << $l; - $num = (int)(($this->size + $m - 1) / $m); + $num = (int) (($this->size + $m - 1) / $m); - $bits += $num * (4 + $l); - - return $bits; + return $bits + $num * (4 + $l); } - public function encodeBitStream($version) { try { @@ -220,8 +203,8 @@ public function encodeBitStream($version) if ($this->size > $words) { - $st1 = new InputItem($this->mode, $words, $this->data); - $st2 = new InputItem($this->mode, $this->size - $words, array_slice($this->data, $words)); + $st1 = new self($this->mode, $words, $this->data); + $st2 = new self($this->mode, $this->size - $words, array_slice($this->data, $words)); $st1->encodeBitStream($version); $st2->encodeBitStream($version); @@ -258,13 +241,14 @@ public function encodeBitStream($version) break; } - if ($ret < 0) + if ($ret < 0) { return -1; + } } return $this->bstream->size(); - } catch (Exception $e) { + } catch (Exception) { return -1; } } diff --git a/src/Mask.php b/src/Mask.php index 70ca4ad..0ee1959 100755 --- a/src/Mask.php +++ b/src/Mask.php @@ -1,36 +1,33 @@ runLength = array_fill(0, Spec::QRSPEC_WIDTH_MAX + 1, 0); } - public function writeFormatInformation($width, &$frame, $mask, $level) { $blacks = 0; $format = Spec::getFormatInfo($mask, $level); for ($i = 0; $i < 8; $i++) { - if ($format & 1) { + if (($format & 1) !== 0) { $blacks += 2; $v = 0x85; } else { @@ -43,11 +40,12 @@ public function writeFormatInformation($width, &$frame, $mask, $level) } else { $frame[$i + 1][8] = chr($v); } - $format = $format >> 1; + + $format >>= 1; } for ($i = 0; $i < 7; $i++) { - if ($format & 1) { + if (($format & 1) !== 0) { $blacks += 2; $v = 0x85; } else { @@ -61,13 +59,12 @@ public function writeFormatInformation($width, &$frame, $mask, $level) $frame[8][6 - $i] = chr($v); } - $format = $format >> 1; + $format >>= 1; } return $blacks; } - public function mask0($x, $y) { return ($x + $y) & 1; @@ -75,12 +72,12 @@ public function mask0($x, $y) public function mask1($x, $y) { - return ($y & 1); + return $y & 1; } public function mask2($x, $y) { - return ($x % 3); + return $x % 3; } public function mask3($x, $y) @@ -90,7 +87,7 @@ public function mask3($x, $y) public function mask4($x, $y) { - return (((int)($y / 2)) + ((int)($x / 3))) & 1; + return (((int) ($y / 2)) + ((int) ($x / 3))) & 1; } public function mask5($x, $y) @@ -108,34 +105,15 @@ public function mask7($x, $y) return ((($x * $y) % 3) + (($x + $y) & 1)) & 1; } - - private function generateMaskNo($maskNo, $width, $frame) - { - $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); - - for ($y = 0; $y < $width; $y++) { - for ($x = 0; $x < $width; $x++) { - if (ord($frame[$y][$x]) & 0x80) { - $bitMask[$y][$x] = 0; - } else { - $maskFunc = call_user_func(array($this, 'mask' . $maskNo), $x, $y); - $bitMask[$y][$x] = ($maskFunc == 0) ? 1 : 0; - } - - } - } - - return $bitMask; - } - public static function serial($bitFrame) { $codeArr = []; - foreach ($bitFrame as $line) - $codeArr[] = join('', $line); + foreach ($bitFrame as $line) { + $codeArr[] = implode('', $line); + } - return gzcompress(join("\n", $codeArr), 9); + return gzcompress(implode("\n", $codeArr), 9); } public static function unserial($code) @@ -143,8 +121,9 @@ public static function unserial($code) $codeArr = []; $codeLines = explode("\n", gzuncompress($code)); - foreach ($codeLines as $line) + foreach ($codeLines as $line) { $codeArr[] = str_split($line); + } return $codeArr; } @@ -159,18 +138,19 @@ public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false) if (file_exists($fileName)) { $bitMask = self::unserial(file_get_contents($fileName)); } else { - $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); - if (!file_exists(Config::$cacheDir . 'mask_' . $maskNo)) { + $bitMask = $this->generateMaskNo($maskNo, $width, $s); + if (! file_exists(Config::$cacheDir . 'mask_' . $maskNo)) { mkdir(Config::$cacheDir . 'mask_' . $maskNo); } + file_put_contents($fileName, self::serial($bitMask)); } } else { - $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); + $bitMask = $this->generateMaskNo($maskNo, $width, $s); } if ($maskGenOnly) { - return; + return null; } $d = $s; @@ -178,16 +158,16 @@ public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false) for ($y = 0; $y < $width; $y++) { for ($x = 0; $x < $width; $x++) { if ($bitMask[$y][$x] == 1) { - $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]); + $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int) $bitMask[$y][$x]); } - $b += (int)(ord($d[$y][$x]) & 1); + + $b += ord($d[$y][$x]) & 1; } } return $b; } - public function makeMask($width, $frame, $maskNo, $level) { $masked = array_fill(0, $width, str_repeat("\0", $width)); @@ -197,7 +177,6 @@ public function makeMask($width, $frame, $maskNo, $level) return $masked; } - public function calcN1N3($length) { $demerit = 0; @@ -207,26 +186,25 @@ public function calcN1N3($length) if ($this->runLength[$i] >= 5) { $demerit += (static::N1 + ($this->runLength[$i] - 5)); } - if ($i & 1) { - if (($i >= 3) && ($i < ($length - 2)) && ($this->runLength[$i] % 3 == 0)) { - $fact = (int)($this->runLength[$i] / 3); - if (($this->runLength[$i - 2] == $fact) && - ($this->runLength[$i - 1] == $fact) && - ($this->runLength[$i + 1] == $fact) && - ($this->runLength[$i + 2] == $fact)) { - if (($this->runLength[$i - 3] < 0) || ($this->runLength[$i - 3] >= (4 * $fact))) { - $demerit += static::N3; - } else if ((($i + 3) >= $length) || ($this->runLength[$i + 3] >= (4 * $fact))) { - $demerit += static::N3; - } + + if (($i & 1) !== 0 && ($i >= 3 && $i < $length - 2 && $this->runLength[$i] % 3 == 0)) { + $fact = (int) ($this->runLength[$i] / 3); + if (($this->runLength[$i - 2] == $fact) && + ($this->runLength[$i - 1] == $fact) && + ($this->runLength[$i + 1] == $fact) && + ($this->runLength[$i + 2] == $fact)) { + if (($this->runLength[$i - 3] < 0) || ($this->runLength[$i - 3] >= (4 * $fact))) { + $demerit += static::N3; + } elseif ((($i + 3) >= $length) || ($this->runLength[$i + 3] >= (4 * $fact))) { + $demerit += static::N3; } } } } + return $demerit; } - public function evaluateSymbol($width, $frame) { $demerit = 0; @@ -237,24 +215,26 @@ public function evaluateSymbol($width, $frame) $frameY = $frame[$y]; - if ($y > 0) + if ($y > 0) { $frameYM = $frame[$y - 1]; + } for ($x = 0; $x < $width; $x++) { if (($x > 0) && ($y > 0)) { $b22 = ord($frameY[$x]) & ord($frameY[$x - 1]) & ord($frameYM[$x]) & ord($frameYM[$x - 1]); $w22 = ord($frameY[$x]) | ord($frameY[$x - 1]) | ord($frameYM[$x]) | ord($frameYM[$x - 1]); - if (($b22 | ($w22 ^ 1)) & 1) { + if ((($b22 | $w22 ^ 1) & 1) !== 0) { $demerit += static::N2; } } + if (($x == 0) && (ord($frameY[$x]) & 1)) { $this->runLength[0] = -1; $head = 1; $this->runLength[$head] = 1; - } else if ($x > 0) { - if ((ord($frameY[$x]) ^ ord($frameY[$x - 1])) & 1) { + } elseif ($x > 0) { + if (((ord($frameY[$x]) ^ ord($frameY[$x - 1])) & 1) !== 0) { $head++; $this->runLength[$head] = 1; } else { @@ -275,8 +255,8 @@ public function evaluateSymbol($width, $frame) $this->runLength[0] = -1; $head = 1; $this->runLength[$head] = 1; - } else if ($y > 0) { - if ((ord($frame[$y][$x]) ^ ord($frame[$y - 1][$x])) & 1) { + } elseif ($y > 0) { + if (((ord($frame[$y][$x]) ^ ord($frame[$y - 1][$x])) & 1) !== 0) { $head++; $this->runLength[$head] = 1; } else { @@ -295,12 +275,12 @@ public function mask(int $width, $frame, $level) { $minDemerit = PHP_INT_MAX; - $checked_masks = array(0, 1, 2, 3, 4, 5, 6, 7); + $checked_masks = [0, 1, 2, 3, 4, 5, 6, 7]; if (Config::$findFromRandom !== false) { $howManuOut = 8 - (Config::$findFromRandom % 9); for ($i = 0; $i < $howManuOut; $i++) { - $remPos = rand(0, count($checked_masks) - 1); + $remPos = random_int(0, count($checked_masks) - 1); unset($checked_masks[$remPos]); $checked_masks = array_values($checked_masks); } @@ -313,8 +293,8 @@ public function mask(int $width, $frame, $level) $blacks = $this->makeMaskNo($i, $width, $frame, $mask); $blacks += $this->writeFormatInformation($width, $mask, $i, $level); - $blacks = (int)(100 * $blacks / ($width * $width)); - $demerit = (int)((int)(abs($blacks - 50) / 5) * static::N4); + $blacks = (int) (100 * $blacks / ($width * $width)); + $demerit = (int) ((int) (abs($blacks - 50) / 5) * static::N4); $demerit += $this->evaluateSymbol($width, $mask); if ($demerit < $minDemerit) { @@ -325,4 +305,23 @@ public function mask(int $width, $frame, $level) return $bestMask; } + + private function generateMaskNo($maskNo, $width, $frame) + { + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + + for ($y = 0; $y < $width; $y++) { + for ($x = 0; $x < $width; $x++) { + if ((ord($frame[$y][$x]) & 0x80) !== 0) { + $bitMask[$y][$x] = 0; + } else { + $maskFunc = call_user_func([$this, 'mask' . $maskNo], $x, $y); + $bitMask[$y][$x] = ($maskFunc == 0) ? 1 : 0; + } + + } + } + + return $bitMask; + } } diff --git a/src/RawCode.php b/src/RawCode.php index 7027781..05ce3c9 100644 --- a/src/RawCode.php +++ b/src/RawCode.php @@ -1,25 +1,30 @@ datacode = $input->getByteStream(); - if (is_null($this->datacode)) { + if ($this->datacode === null) { throw new Exception('null input string'); } @@ -94,22 +99,22 @@ public function init(array $spec): int public function getCode(): ?int { - $ret = null; - if ($this->count < $this->dataLength) { $row = $this->count % $this->blocks; - $col = $this->count / $this->blocks; + $col = (int) ($this->count / $this->blocks); if ($col >= $this->rsblocks[0]->dataLength) { $row += $this->b1; } + $ret = $this->rsblocks[$row]->data[$col]; - } else if ($this->count < $this->dataLength + $this->eccLength) { + } elseif ($this->count < $this->dataLength + $this->eccLength) { $row = ($this->count - $this->dataLength) % $this->blocks; - $col = ($this->count - $this->dataLength) / $this->blocks; + $col = (int) (($this->count - $this->dataLength) / $this->blocks); $ret = $this->rsblocks[$row]->ecc[$col]; } else { return 0; } + $this->count++; return $ret; diff --git a/src/Rs.php b/src/Rs.php index 262944c..b3e1b53 100644 --- a/src/Rs.php +++ b/src/Rs.php @@ -1,32 +1,47 @@ pad != $pad) continue; - if ($rs->nroots != $nroots) continue; - if ($rs->mm != $symsize) continue; - if ($rs->gfpoly != $gfpoly) continue; - if ($rs->fcr != $fcr) continue; - if ($rs->prim != $prim) continue; + if ($rs->pad != $pad) { + continue; + } + + if ($rs->nroots != $nroots) { + continue; + } + + if ($rs->mm != $symsize) { + continue; + } + + if ($rs->gfpoly != $gfpoly) { + continue; + } + + if ($rs->fcr != $fcr) { + continue; + } + + if ($rs->prim != $prim) { + continue; + } return $rs; } - $rs = RsItem::init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad); + $rs = RsItem::init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad, 1); array_unshift(self::$items, $rs); return $rs; diff --git a/src/RsBlock.php b/src/RsBlock.php index 152e85b..1d92b34 100644 --- a/src/RsBlock.php +++ b/src/RsBlock.php @@ -1,28 +1,19 @@ encode_rs_char($data, $ecc); - - $this->dataLength = $dl; - $this->data = $data; - $this->eccLength = $el; $this->ecc = $ecc; } } - diff --git a/src/RsItem.php b/src/RsItem.php index 4006505..16a2f05 100755 --- a/src/RsItem.php +++ b/src/RsItem.php @@ -1,26 +1,52 @@ 8) return $rs; - if ($fcr < 0 || $fcr >= (1 << $symsize)) return $rs; - if ($prim <= 0 || $prim >= (1 << $symsize)) return $rs; - if ($nroots < 0 || $nroots >= (1 << $symsize)) return $rs; // Can't have more roots than symbol values! - if ($pad < 0 || $pad >= ((1 << $symsize) - 1 - $nroots)) return $rs; // Too much padding + if ($symsize < 0 || $symsize > 8) { + return $rs; + } + + if ($fcr < 0 || $fcr >= (1 << $symsize)) { + return $rs; + } - $rs = new RsItem(); + if ($prim <= 0 || $prim >= (1 << $symsize)) { + return $rs; + } + + if ($nroots < 0 || $nroots >= (1 << $symsize)) { + return $rs; + } + + // Can't have more roots than symbol values! + if ($pad < 0 || $pad >= ((1 << $symsize) - 1 - $nroots)) { + return $rs; + } // Too much padding + + $rs = new self(); $rs->mm = $symsize; $rs->nn = (1 << $symsize) - 1; $rs->pad = $pad; @@ -56,8 +96,8 @@ public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pa $rs->index_of = array_fill(0, $rs->nn + 1, 0); // PHP style macro replacement ;) - $NN =& $rs->nn; - $A0 =& $NN; + $NN = &$rs->nn; + $A0 = &$NN; // Generate Galois field lookup tables $rs->index_of[0] = $A0; // log(zero) = -inf @@ -68,16 +108,17 @@ public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pa $rs->index_of[$sr] = $i; $rs->alpha_to[$i] = $sr; $sr <<= 1; - if ($sr & (1 << $symsize)) { + if (($sr & 1 << $symsize) !== 0) { $sr ^= $gfpoly; } + $sr &= $rs->nn; } if ($sr != 1) { // field generator polynomial is not primitive! $rs = null; - return $rs; + return null; } /* Form RS code generator polynomial from its roots */ @@ -90,9 +131,9 @@ public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pa /* Find prim-th root of 1, used in decoding */ for ($iprim = 1; ($iprim % $prim) != 0; $iprim += $rs->nn) - ; // intentional empty-body loop! + ; // intentional empty-body loop! - $rs->iprim = (int)($iprim / $prim); + $rs->iprim = (int) ($iprim / $prim); $rs->genpoly[0] = 1; for ($i = 0, $root = $fcr * $prim; $i < $nroots; $i++, $root += $prim) { @@ -101,11 +142,14 @@ public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pa // Multiply rs->genpoly[] by @**(root + x) for ($j = $i; $j > 0; $j--) { if ($rs->genpoly[$j] != 0) { - $rs->genpoly[$j] = $rs->genpoly[$j - 1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)]; + $rs->genpoly[$j] = $rs->genpoly[$j - 1] ^ $rs->alpha_to[$rs->modnn( + $rs->index_of[$rs->genpoly[$j]] + $root + )]; } else { $rs->genpoly[$j] = $rs->genpoly[$j - 1]; } } + // rs->genpoly[0] can never be zero $rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)]; } @@ -120,13 +164,13 @@ public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pa public function encode_rs_char(array $data, array &$parity): void { - $NN =& $this->nn; - $ALPHA_TO =& $this->alpha_to; - $INDEX_OF =& $this->index_of; - $GENPOLY =& $this->genpoly; - $NROOTS =& $this->nroots; - $PAD =& $this->pad; - $A0 =& $NN; + $NN = &$this->nn; + $ALPHA_TO = &$this->alpha_to; + $INDEX_OF = &$this->index_of; + $GENPOLY = &$this->genpoly; + $NROOTS = &$this->nroots; + $PAD = &$this->pad; + $A0 = &$NN; $parity = array_fill(0, $NROOTS, 0); @@ -147,11 +191,7 @@ public function encode_rs_char(array $data, array &$parity): void // Shift array_shift($parity); - if ($feedback != $A0) { - array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]); - } else { - array_push($parity, 0); - } + $parity[] = $feedback != $A0 ? $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])] : 0; } } } diff --git a/src/Spec.php b/src/Spec.php index 2d49236..661ed16 100755 --- a/src/Spec.php +++ b/src/Spec.php @@ -1,119 +1,213 @@ = $size) + if ($words >= $size) { return $i; + } } return -1; } - public static $lengthTableBits = array( - array(10, 12, 14), - array(9, 11, 13), - array(8, 16, 16), - array(8, 10, 12) - ); - public static function lengthIndicator($mode, $version) { - if ($mode == Str::QR_MODE_STRUCTURE) + if ($mode == Str::QR_MODE_STRUCTURE) { return 0; + } if ($version <= 9) { $l = 0; - } else if ($version <= 26) { + } elseif ($version <= 26) { $l = 1; } else { $l = 2; @@ -124,12 +218,13 @@ public static function lengthIndicator($mode, $version) public static function maximumWords($mode, $version) { - if ($mode == Str::QR_MODE_STRUCTURE) + if ($mode == Str::QR_MODE_STRUCTURE) { return 3; + } if ($version <= 9) { $l = 0; - } else if ($version <= 26) { + } elseif ($version <= 26) { $l = 1; } else { $l = 2; @@ -145,61 +240,12 @@ public static function maximumWords($mode, $version) return $words; } - // Error correction code - // Table of the error correction code (Reed-Solomon block) - // See Table 12-16 (pp.30-36), JIS X0510:2004. - - public static $eccTable = array( - array(array(0, 0), array(0, 0), array(0, 0), array(0, 0)), - array(array(1, 0), array(1, 0), array(1, 0), array(1, 0)), // 1 - array(array(1, 0), array(1, 0), array(1, 0), array(1, 0)), - array(array(1, 0), array(1, 0), array(2, 0), array(2, 0)), - array(array(1, 0), array(2, 0), array(2, 0), array(4, 0)), - array(array(1, 0), array(2, 0), array(2, 2), array(2, 2)), // 5 - array(array(2, 0), array(4, 0), array(4, 0), array(4, 0)), - array(array(2, 0), array(4, 0), array(2, 4), array(4, 1)), - array(array(2, 0), array(2, 2), array(4, 2), array(4, 2)), - array(array(2, 0), array(3, 2), array(4, 4), array(4, 4)), - array(array(2, 2), array(4, 1), array(6, 2), array(6, 2)), //10 - array(array(4, 0), array(1, 4), array(4, 4), array(3, 8)), - array(array(2, 2), array(6, 2), array(4, 6), array(7, 4)), - array(array(4, 0), array(8, 1), array(8, 4), array(12, 4)), - array(array(3, 1), array(4, 5), array(11, 5), array(11, 5)), - array(array(5, 1), array(5, 5), array(5, 7), array(11, 7)), //15 - array(array(5, 1), array(7, 3), array(15, 2), array(3, 13)), - array(array(1, 5), array(10, 1), array(1, 15), array(2, 17)), - array(array(5, 1), array(9, 4), array(17, 1), array(2, 19)), - array(array(3, 4), array(3, 11), array(17, 4), array(9, 16)), - array(array(3, 5), array(3, 13), array(15, 5), array(15, 10)), //20 - array(array(4, 4), array(17, 0), array(17, 6), array(19, 6)), - array(array(2, 7), array(17, 0), array(7, 16), array(34, 0)), - array(array(4, 5), array(4, 14), array(11, 14), array(16, 14)), - array(array(6, 4), array(6, 14), array(11, 16), array(30, 2)), - array(array(8, 4), array(8, 13), array(7, 22), array(22, 13)), //25 - array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)), - array(array(8, 4), array(22, 3), array(8, 26), array(12, 28)), - array(array(3, 10), array(3, 23), array(4, 31), array(11, 31)), - array(array(7, 7), array(21, 7), array(1, 37), array(19, 26)), - array(array(5, 10), array(19, 10), array(15, 25), array(23, 25)), //30 - array(array(13, 3), array(2, 29), array(42, 1), array(23, 28)), - array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)), - array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)), - array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)), - array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35 - array(array(6, 14), array(6, 34), array(46, 10), array(2, 64)), - array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)), - array(array(4, 18), array(13, 32), array(48, 14), array(42, 32)), - array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)), - array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)),//40 - ); - - // CACHEABLE!!! public static function getEccSpec($version, $level, array &$spec) { if (count($spec) < 5) { - $spec = array(0, 0, 0, 0, 0); + $spec = [0, 0, 0, 0, 0]; } $b1 = self::$eccTable[$version][$level][0]; @@ -209,56 +255,32 @@ public static function getEccSpec($version, $level, array &$spec) if ($b2 == 0) { $spec[0] = $b1; - $spec[1] = (int)($data / $b1); - $spec[2] = (int)($ecc / $b1); + $spec[1] = (int) ($data / $b1); + $spec[2] = (int) ($ecc / $b1); $spec[3] = 0; $spec[4] = 0; } else { $spec[0] = $b1; - $spec[1] = (int)($data / ($b1 + $b2)); - $spec[2] = (int)($ecc / ($b1 + $b2)); + $spec[1] = (int) ($data / ($b1 + $b2)); + $spec[2] = (int) ($ecc / ($b1 + $b2)); $spec[3] = $b2; $spec[4] = $spec[1] + 1; } } - // Alignment pattern --------------------------------------------------- - - // Positions of alignment patterns. - // This array includes only the second and the third position of the - // alignment patterns. Rest of them can be calculated from the distance - // between them. - - // See Table 1 in Appendix E (pp.71) of JIS X0510:2004. - - public static $alignmentPattern = array( - array(0, 0), - array(0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5 - array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10 - array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15 - array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20 - array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25 - array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30 - array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35 - array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40 - ); - - /** * Put an alignment marker. - * @param array $frame - * @param int $ox * @param int $oy center coordinate of the pattern */ public static function putAlignmentMarker(array &$frame, int $ox, int $oy) { - $finder = array( + $finder = [ "\xa1\xa1\xa1\xa1\xa1", "\xa1\xa0\xa0\xa0\xa1", "\xa1\xa0\xa1\xa0\xa1", "\xa1\xa0\xa0\xa0\xa1", - "\xa1\xa1\xa1\xa1\xa1" - ); + "\xa1\xa1\xa1\xa1\xa1", + ]; $yStart = $oy - 2; $xStart = $ox - 2; @@ -275,11 +297,7 @@ public static function putAlignmentPattern($version, &$frame, $width) } $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0]; - if ($d < 0) { - $w = 2; - } else { - $w = (int)(($width - self::$alignmentPattern[$version][0]) / $d + 2); - } + $w = $d < 0 ? 2 : (int) (($width - self::$alignmentPattern[$version][0]) / $d + 2); if ($w * $w - 3 == 1) { $x = self::$alignmentPattern[$version][0]; @@ -306,55 +324,28 @@ public static function putAlignmentPattern($version, &$frame, $width) } } - // Version information pattern ----------------------------------------- - - // Version information pattern (BCH coded). - // See Table 1 in Appendix D (pp.68) of JIS X0510:2004. - - // size: [QRSPEC_VERSION_MAX - 6] - - public static $versionPattern = array( - 0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d, - 0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9, - 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75, - 0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64, - 0x27541, 0x28c69 - ); - public static function getVersionPattern($version) { - if ($version < 7 || $version > static::QRSPEC_VERSION_MAX) + if ($version < 7 || $version > static::QRSPEC_VERSION_MAX) { return 0; + } return self::$versionPattern[$version - 7]; } - // Format information -------------------------------------------------- - // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib) - - public static $formatInfo = array( - array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976), - array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0), - array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed), - array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b) - ); - public static function getFormatInfo($mask, $level) { - if ($mask < 0 || $mask > 7) + if ($mask < 0 || $mask > 7) { return 0; + } - if ($level < 0 || $level > 3) + if ($level < 0 || $level > 3) { return 0; + } return self::$formatInfo[$level][$mask]; } - // Frame --------------------------------------------------------------- - // Cache of initial frames. - - public static $frames = []; - /** -------------------------------------------------------------------- * Put a finder pattern. * @param mixed $frame @@ -363,22 +354,21 @@ public static function getFormatInfo($mask, $level) */ public static function putFinderPattern(&$frame, $ox, $oy) { - $finder = array( + $finder = [ "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", - "\xc1\xc1\xc1\xc1\xc1\xc1\xc1" - ); + "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", + ]; for ($y = 0; $y < 7; $y++) { Str::set($frame, $ox, $oy + $y, $finder[$y]); } } - public static function createFrame($version) { $width = self::$capacity[$version][static::QRCAP_WIDTH]; @@ -437,7 +427,7 @@ public static function createFrame($version) for ($x = 0; $x < 6; $x++) { for ($y = 0; $y < 3; $y++) { $frame[($width - 11) + $y][$x] = chr(0x88 | ($v & 1)); - $v = $v >> 1; + $v >>= 1; } } @@ -445,7 +435,7 @@ public static function createFrame($version) for ($y = 0; $y < 6; $y++) { for ($x = 0; $x < 3; $x++) { $frame[$y][$x + ($width - 11)] = chr(0x88 | ($v & 1)); - $v = $v >> 1; + $v >>= 1; } } } @@ -456,14 +446,13 @@ public static function createFrame($version) return $frame; } - public static function debug($frame, $binary_mode = false) { if ($binary_mode) { foreach ($frame as &$frameLine) { - $frameLine = join('  ', explode('0', $frameLine)); - $frameLine = join('██', explode('1', $frameLine)); + $frameLine = implode('  ', explode('0', (string) $frameLine)); + $frameLine = implode('██', explode('1', $frameLine)); } ?> @@ -474,25 +463,25 @@ public static function debug($frame, $binary_mode = false)


        '; - echo join("
        ", $frame); + echo implode('
        ', $frame); echo '






'; } else { foreach ($frame as &$frameLine) { - $frameLine = join(' ', explode("\xc0", $frameLine)); - $frameLine = join('', explode("\xc1", $frameLine)); - $frameLine = join(' ', explode("\xa0", $frameLine)); - $frameLine = join('', explode("\xa1", $frameLine)); - $frameLine = join('', explode("\x84", $frameLine)); //format 0 - $frameLine = join('', explode("\x85", $frameLine)); //format 1 - $frameLine = join('', explode("\x81", $frameLine)); //special bit - $frameLine = join(' ', explode("\x90", $frameLine)); //clock 0 - $frameLine = join('', explode("\x91", $frameLine)); //clock 1 - $frameLine = join(' ', explode("\x88", $frameLine)); //version - $frameLine = join('', explode("\x89", $frameLine)); //version - $frameLine = join('♦', explode("\x01", $frameLine)); - $frameLine = join('⋅', explode("\0", $frameLine)); + $frameLine = implode(' ', explode("\xc0", (string) $frameLine)); + $frameLine = implode('', explode("\xc1", $frameLine)); + $frameLine = implode(' ', explode("\xa0", $frameLine)); + $frameLine = implode('', explode("\xa1", $frameLine)); + $frameLine = implode('', explode("\x84", $frameLine)); //format 0 + $frameLine = implode('', explode("\x85", $frameLine)); //format 1 + $frameLine = implode('', explode("\x81", $frameLine)); //special bit + $frameLine = implode(' ', explode("\x90", $frameLine)); //clock 0 + $frameLine = implode('', explode("\x91", $frameLine)); //clock 1 + $frameLine = implode(' ', explode("\x88", $frameLine)); //version + $frameLine = implode('', explode("\x89", $frameLine)); //version + $frameLine = implode('♦', explode("\x01", $frameLine)); + $frameLine = implode('⋅', explode("\0", $frameLine)); } ?> @@ -522,32 +511,30 @@ public static function debug($frame, $binary_mode = false) } "; - echo join("
", $frame); - echo "
"; + echo '
';
+            echo implode('
', $frame); + echo '
'; } } - public static function serial($frame) { - return gzcompress(join("\n", $frame), 9); + return gzcompress(implode("\n", $frame), 9); } - public static function unserial($code) { return explode("\n", gzuncompress($code)); } - public static function newFrame($version) { - if ($version < 1 || $version > static::QRSPEC_VERSION_MAX) + if ($version < 1 || $version > static::QRSPEC_VERSION_MAX) { return null; + } - if (!isset(self::$frames[$version])) { + if (! isset(self::$frames[$version])) { $fileName = Config::$cacheDir . 'frame_' . $version . '.dat'; @@ -563,13 +550,13 @@ public static function newFrame($version) } } - if (is_null(self::$frames[$version])) + if (self::$frames[$version] === null) { return null; + } return self::$frames[$version]; } - public static function rsBlockNum($spec) { return $spec[0] + $spec[3]; diff --git a/src/Split.php b/src/Split.php index ff2b0e3..0f659be 100755 --- a/src/Split.php +++ b/src/Split.php @@ -1,46 +1,39 @@ dataStr = $dataStr; - $this->input = $input; - $this->modeHint = $modeHint; + public function __construct( + public string $dataStr, + public Input $input, + public int $modeHint + ) { } public static function isDigitAt(string $str, int $pos): bool { - if ($pos >= strlen($str)) + if ($pos >= strlen($str)) { return false; + } - return ((ord($str[$pos]) >= ord('0')) && (ord($str[$pos]) <= ord('9'))); + return (ord($str[$pos]) >= ord('0')) && (ord($str[$pos]) <= ord('9')); } public static function isAlNumAt(string $str, int $pos): bool { - if ($pos >= strlen($str)) + if ($pos >= strlen($str)) { return false; + } - return (Input::lookAnTable(ord($str[$pos])) >= 0); + return Input::lookAnTable(ord($str[$pos])) >= 0; } public function identifyMode(int $pos): int @@ -53,9 +46,9 @@ public function identifyMode(int $pos): int if (self::isDigitAt($this->dataStr, $pos)) { return Str::QR_MODE_NUM; - } else if (self::isAlNumAt($this->dataStr, $pos)) { + } elseif (self::isAlNumAt($this->dataStr, $pos)) { return Str::QR_MODE_AN; - } else if ($this->modeHint == Str::QR_MODE_KANJI) { + } elseif ($this->modeHint == Str::QR_MODE_KANJI) { if ($pos + 1 < strlen($this->dataStr)) { $d = $this->dataStr[$pos + 1]; $word = (ord($c) << 8) | ord($d); @@ -88,10 +81,11 @@ public function eatNum(): int return $this->eat8(); } } + if ($mode == Str::QR_MODE_AN) { $dif = Input::estimateBitsModeNum($run) + 4 + $ln + Input::estimateBitsModeAn(1) // + 4 + la - - Input::estimateBitsModeAn($run + 1);// - 4 - la + - Input::estimateBitsModeAn($run + 1); // - 4 - la if ($dif > 0) { return $this->eatAn(); } @@ -125,9 +119,10 @@ public function eatAn(): int if ($dif < 0) { break; - } else { - $p = $q; } + + $p = $q; + } else { $p++; } @@ -135,7 +130,7 @@ public function eatAn(): int $run = $p; - if (!self::isAlNumAt($this->dataStr, $p)) { + if (! self::isAlNumAt($this->dataStr, $p)) { $dif = Input::estimateBitsModeAn($run) + 4 + $la + Input::estimateBitsMode8(1) // + 4 + l8 - Input::estimateBitsMode8($run + 1); // - 4 - l8 @@ -152,7 +147,6 @@ public function eatAn(): int return $run; } - public function eatKanji(): int { $p = 0; @@ -160,6 +154,7 @@ public function eatKanji(): int while ($this->identifyMode($p) == Str::QR_MODE_KANJI) { $p += 2; } + $run = $p; $ret = $this->input->append(Str::QR_MODE_KANJI, $p, str_split($this->dataStr)); @@ -170,7 +165,6 @@ public function eatKanji(): int return $run; } - public function eat8(): int { $la = Spec::lengthIndicator(Str::QR_MODE_AN, $this->input->getVersion()); @@ -184,32 +178,39 @@ public function eat8(): int if ($mode == Str::QR_MODE_KANJI) { break; } + if ($mode == Str::QR_MODE_NUM) { $q = $p; while (self::isDigitAt($this->dataStr, $q)) { $q++; } + $dif = Input::estimateBitsMode8($p) // + 4 + l8 + Input::estimateBitsModeNum($q - $p) + 4 + $ln - - Input::estimateBitsMode8($q); // - 4 - l8 + - Input::estimateBitsMode8($q); + // - 4 - l8 if ($dif < 0) { break; - } else { - $p = $q; } - } else if ($mode == Str::QR_MODE_AN) { + + $p = $q; + + } elseif ($mode == Str::QR_MODE_AN) { $q = $p; while (self::isAlNumAt($this->dataStr, $q)) { $q++; } + $dif = Input::estimateBitsMode8($p) // + 4 + l8 + Input::estimateBitsModeAn($q - $p) + 4 + $la - - Input::estimateBitsMode8($q); // - 4 - l8 + - Input::estimateBitsMode8($q); + // - 4 - l8 if ($dif < 0) { break; - } else { - $p = $q; } + + $p = $q; + } else { $p++; } @@ -228,37 +229,30 @@ public function eat8(): int public function splitString(): ?int { while (strlen($this->dataStr) > 0) { - if ($this->dataStr == '') { + if ($this->dataStr === '') { return 0; } $mode = $this->identifyMode(0); - switch ($mode) { - case Str::QR_MODE_NUM: - $length = $this->eatNum(); - break; - case Str::QR_MODE_AN: - $length = $this->eatAn(); - break; - case Str::QR_MODE_KANJI: - $length = $this->eatKanji(); - break; - default: - $length = $this->eat8(); - break; - - } + $length = match ($mode) { + Str::QR_MODE_NUM => $this->eatNum(), + Str::QR_MODE_AN => $this->eatAn(), + Str::QR_MODE_KANJI => $this->eatKanji(), + default => $this->eat8(), + }; if ($length == 0) { return 0; } + if ($length < 0) { return -1; } $this->dataStr = substr($this->dataStr, $length); } + return null; } @@ -276,6 +270,7 @@ public function toUpper(): string if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) { $this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32); } + $p++; } } @@ -283,15 +278,19 @@ public function toUpper(): string return $this->dataStr; } - public static function splitStringToQRInput(string $string, Input $input, int $modeHint, bool $caseSensitive = true): ?string - { - if (is_null($string) || $string == '\0' || $string == '') { + public static function splitStringToQRInput( + string $string, + Input $input, + int $modeHint, + bool $caseSensitive = true + ): ?string { + if ($string === '\0' || $string === '') { throw new Exception('empty string!!!'); } - $split = new Split($string, $input, $modeHint); + $split = new self($string, $input, $modeHint); - if (!$caseSensitive) { + if (! $caseSensitive) { $split->toUpper(); } diff --git a/src/Str.php b/src/Str.php index 69fee55..e455b1a 100755 --- a/src/Str.php +++ b/src/Str.php @@ -1,32 +1,43 @@ makeMaskNo($maskNo, $width, $frame, $bitMask, true); + } } - Tools::markTime('after_build_cache'); + self::markTime('after_build_cache'); } public static function log($outfile, $err) { - if (Config::$logDir !== false) { - if ($err != '') { - if ($outfile !== false) { - file_put_contents(Config::$logDir . basename($outfile) . '-errors.txt', date('Y-m-d H:i:s') . ': ' . $err, FILE_APPEND); - } else { - file_put_contents(Config::$logDir . 'errors.txt', date('Y-m-d H:i:s') . ': ' . $err, FILE_APPEND); - } + if (Config::$logDir !== false && $err != '') { + if ($outfile !== false) { + file_put_contents( + Config::$logDir . basename((string) $outfile) . '-errors.txt', + date('Y-m-d H:i:s') . ': ' . $err, + FILE_APPEND + ); + } else { + file_put_contents(Config::$logDir . 'errors.txt', date('Y-m-d H:i:s') . ': ' . $err, FILE_APPEND); } } } @@ -107,10 +111,10 @@ public static function dumpMask(array $frame) public static function markTime($markerId) { - list($usec, $sec) = explode(" ", microtime()); - $time = ((float)$usec + (float)$sec); + [$usec, $sec] = explode(' ', microtime()); + $time = ((float) $usec + (float) $sec); - if (!isset($GLOBALS['qr_time_bench'])) { + if (! isset($GLOBALS['qr_time_bench'])) { $GLOBALS['qr_time_bench'] = []; } @@ -131,7 +135,10 @@ public static function timeBenchmark() foreach ($GLOBALS['qr_time_bench'] as $markerId => $thisTime) { if ($p > 0) { - echo 'till ' . $markerId . ': ' . number_format($thisTime - $lastTime, 6) . 's'; + echo 'till ' . $markerId . ': ' . number_format( + $thisTime - $lastTime, + 6 + ) . 's'; } else { $startTime = $thisTime; } @@ -141,7 +148,10 @@ public static function timeBenchmark() } echo ' - TOTAL: ' . number_format($lastTime - $startTime, 6) . 's + TOTAL: ' . number_format( + $lastTime - $startTime, + 6 + ) . 's '; } diff --git a/test/SmokeTest.php b/test/SmokeTest.php index 59ba64a..09e6480 100644 --- a/test/SmokeTest.php +++ b/test/SmokeTest.php @@ -2,8 +2,9 @@ namespace PhpQrCodeTest; -use PHPUnit\Framework\TestCase; use PhpQrCode; +use PhpQrCode\Str; +use PHPUnit\Framework\TestCase; class SmokeTest extends TestCase { @@ -15,13 +16,17 @@ public function test() $data = 'https://github.com/nmiles/PhpQrCode'; // Override default config if required - PhpQrCode\Config::configure(['defaultMask' => 3]); + PhpQrCode\Config::configure([ + 'defaultMask' => 3, + ]); $this->assertEquals(3, PhpQrCode\Config::$defaultMask); $levels = ['L', 'M', 'Q', 'H']; foreach ($levels as $errorCorrectionLevel) { for ($matrixPointSize = 1; $matrixPointSize <= 10; $matrixPointSize++) { - $filename = $pngTmpDir . 'test' . md5($data . '|' . $errorCorrectionLevel . '|' . $matrixPointSize) . '.png'; + $filename = $pngTmpDir . 'test' . md5( + $data . '|' . $errorCorrectionLevel . '|' . $matrixPointSize + ) . '.png'; PhpQrCode\Code::png($data, $filename, $errorCorrectionLevel, $matrixPointSize, 2); $this->assertFileExists($filename); unlink($filename); @@ -30,12 +35,15 @@ public function test() } // Kanji - $data = '分分分分国国国'; - $output = PhpQrCode\Code::text($data, false, 'L', 5, 5); - $this->assertIsArray($output); + $data = '投級ルケチ尾精シワキテ球意サヱレ転接未エタワア口94技ぞひり歩別へゆ平朝ぜかし実装めむず励供やだふり同完なろづ判引目をルめ'; + $code = new PhpQrCode\Code; + $output = $code->encodeString($data, 0, Str::QR_ECLEVEL_Q, Str::QR_MODE_KANJI, false); + $this->assertIsObject($output); // Change config - PhpQrCode\Config::configure(['findFromRandom' => true]); + PhpQrCode\Config::configure([ + 'findFromRandom' => true, + ]); $this->assertEquals(true, PhpQrCode\Config::$findFromRandom); $output = PhpQrCode\Code::text($data, false, 'L', 5, 5); $this->assertIsArray($output);