QRString.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Class QRString
  4. *
  5. * @filesource QRString.php
  6. * @created 05.12.2015
  7. * @package chillerlan\QRCode\Output
  8. * @author Smiley <smiley@chillerlan.net>
  9. * @copyright 2015 Smiley
  10. * @license MIT
  11. */
  12. namespace chillerlan\QRCode\Output;
  13. use chillerlan\QRCode\Data\QRCodeDataException;
  14. use chillerlan\QRCode\QRCode;
  15. /**
  16. *
  17. */
  18. class QRString extends QROutputBase implements QROutputInterface{
  19. /**
  20. * @var \chillerlan\QRCode\Output\QRStringOptions
  21. */
  22. protected $options;
  23. /**
  24. * @var \chillerlan\QRCode\Output\QRStringOptions $outputOptions
  25. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  26. */
  27. public function __construct(QRStringOptions $outputOptions = null){
  28. $this->options = $outputOptions;
  29. if(!$this->options instanceof QRStringOptions){
  30. $this->options = new QRStringOptions;
  31. }
  32. if(!in_array($this->options->type, [QRCode::OUTPUT_STRING_TEXT, QRCode::OUTPUT_STRING_JSON, QRCode::OUTPUT_STRING_HTML], true)){
  33. throw new QRCodeOutputException('Invalid string output type!');
  34. }
  35. }
  36. /**
  37. * @return string
  38. */
  39. public function dump(){
  40. if($this->options->type === QRCode::OUTPUT_STRING_JSON){
  41. return json_encode($this->matrix);
  42. }
  43. else if($this->options->type === QRCode::OUTPUT_STRING_TEXT){
  44. $text = '';
  45. foreach($this->matrix as $row){
  46. foreach($row as $col){
  47. $text .= $col
  48. ? $this->options->textDark
  49. : $this->options->textLight;
  50. }
  51. $text .= $this->options->textNewline;
  52. }
  53. return $text;
  54. }
  55. else if($this->options->type === QRCode::OUTPUT_STRING_HTML){
  56. $html = '';
  57. foreach($this->matrix as $row){
  58. // in order to not bloat the output too much, we use the shortest possible valid HTML tags
  59. $html .= '<'.$this->options->htmlRowTag.'>';
  60. foreach($row as $col){
  61. $tag = $col
  62. ? 'b' // dark
  63. : 'i'; // light
  64. $html .= '<'.$tag.'></'.$tag.'>';
  65. }
  66. if(!(bool)$this->options->htmlOmitEndTag){
  67. $html .= '</'.$this->options->htmlRowTag.'>';
  68. }
  69. $html .= PHP_EOL;
  70. }
  71. return $html;
  72. }
  73. }
  74. }