| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Endroid\QrCode\Writer\Result; |
| 6 |
|
| 7 |
use Endroid\QrCode\Color\ColorInterface; |
| 8 |
use Endroid\QrCode\Matrix\MatrixInterface; |
| 9 |
|
| 10 |
final class ConsoleResult extends AbstractResult |
| 11 |
{ |
| 12 |
private const TWO_BLOCKS = [ |
| 13 |
0 => ' ', |
| 14 |
1 => "\xe2\x96\x80", |
| 15 |
2 => "\xe2\x96\x84", |
| 16 |
3 => "\xe2\x96\x88", |
| 17 |
]; |
| 18 |
|
| 19 |
private string $colorEscapeCode; |
| 20 |
|
| 21 |
public function __construct( |
| 22 |
MatrixInterface $matrix, |
| 23 |
ColorInterface $foreground, |
| 24 |
ColorInterface $background |
| 25 |
) { |
| 26 |
parent::__construct($matrix); |
| 27 |
|
| 28 |
$this->colorEscapeCode = sprintf( |
| 29 |
"\e[38;2;%d;%d;%dm\e[48;2;%d;%d;%dm", |
| 30 |
$foreground->getRed(), |
| 31 |
$foreground->getGreen(), |
| 32 |
$foreground->getBlue(), |
| 33 |
$background->getRed(), |
| 34 |
$background->getGreen(), |
| 35 |
$background->getBlue() |
| 36 |
); |
| 37 |
} |
| 38 |
|
| 39 |
public function getMimeType(): string |
| 40 |
{ |
| 41 |
return 'text/plain'; |
| 42 |
} |
| 43 |
|
| 44 |
public function getString(): string |
| 45 |
{ |
| 46 |
$matrix = $this->getMatrix(); |
| 47 |
|
| 48 |
$side = $matrix->getBlockCount(); |
| 49 |
$marginLeft = $this->colorEscapeCode.self::TWO_BLOCKS[0].self::TWO_BLOCKS[0]; |
| 50 |
$marginRight = self::TWO_BLOCKS[0].self::TWO_BLOCKS[0]."\e[0m".PHP_EOL; |
| 51 |
$marginVertical = $marginLeft.str_repeat(self::TWO_BLOCKS[0], $side).$marginRight; |
| 52 |
|
| 53 |
$qrCodeString = $marginVertical; |
| 54 |
for ($rowIndex = 0; $rowIndex < $side; $rowIndex += 2) { |
| 55 |
$qrCodeString .= $marginLeft; |
| 56 |
for ($columnIndex = 0; $columnIndex < $side; ++$columnIndex) { |
| 57 |
$combined = $matrix->getBlockValue($rowIndex, $columnIndex); |
| 58 |
if ($rowIndex + 1 < $side) { |
| 59 |
$combined |= $matrix->getBlockValue($rowIndex + 1, $columnIndex) << 1; |
| 60 |
} |
| 61 |
$qrCodeString .= self::TWO_BLOCKS[$combined]; |
| 62 |
} |
| 63 |
$qrCodeString .= $marginRight; |
| 64 |
} |
| 65 |
$qrCodeString .= $marginVertical; |
| 66 |
|
| 67 |
return $qrCodeString; |
| 68 |
} |
| 69 |
} |