QRString.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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\QRCode;
  14. /**
  15. *
  16. */
  17. class QRString extends QROutputBase implements QROutputInterface{
  18. /**
  19. * @var \chillerlan\QRCode\Output\QRStringOptions
  20. */
  21. protected $options;
  22. /**
  23. * @var \chillerlan\QRCode\Output\QRStringOptions $outputOptions
  24. */
  25. public function __construct(QRStringOptions $outputOptions = null){
  26. $this->options = $outputOptions;
  27. if(!$this->options instanceof QRStringOptions){
  28. $this->options = new QRStringOptions;
  29. }
  30. }
  31. /**
  32. * @return string
  33. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  34. */
  35. public function dump(){
  36. switch($this->options->type){
  37. case QRCode::OUTPUT_STRING_TEXT: return $this->toText();
  38. case QRCode::OUTPUT_STRING_JSON: return $this->toJSON();
  39. case QRCode::OUTPUT_STRING_HTML: return $this->toHTML();
  40. default:
  41. throw new QRCodeOutputException('Invalid string output type!');
  42. }
  43. }
  44. /**
  45. * @return string
  46. */
  47. public function toText(){
  48. $text = '';
  49. foreach($this->matrix as &$row){
  50. foreach($row as &$col){
  51. $text .= $col
  52. ? $this->options->textDark
  53. : $this->options->textLight;
  54. }
  55. $text .= $this->options->textNewline;
  56. }
  57. return $text;
  58. }
  59. /**
  60. * @return string
  61. */
  62. public function toJSON(){
  63. return json_encode($this->matrix);
  64. }
  65. /**
  66. * @return string
  67. */
  68. public function toHTML(){
  69. $html = '';
  70. foreach($this->matrix as &$row){
  71. // in order to not bloat the output too much, we use the shortest possible valid HTML tags
  72. $html .= '<p>';
  73. foreach($row as &$col){
  74. $tag = $col
  75. ? 'b' // dark
  76. : 'i'; // light
  77. $html .= '<'.$tag.'></'.$tag.'>';
  78. }
  79. // the closing <p> tag may be omitted
  80. # $html .= '</p>';
  81. $html .= PHP_EOL;
  82. }
  83. return $html;
  84. }
  85. }