QROutputAbstract.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. /**
  3. * Class QROutputAbstract
  4. *
  5. * @filesource QROutputAbstract.php
  6. * @created 09.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. /**
  14. *
  15. */
  16. abstract class QROutputAbstract implements QROutputInterface{
  17. /**
  18. * @var string
  19. */
  20. protected $optionsInterface;
  21. /**
  22. * @var array
  23. */
  24. protected $types;
  25. /**
  26. * @var array
  27. */
  28. protected $matrix;
  29. /**
  30. * @var int
  31. */
  32. protected $pixelCount;
  33. /**
  34. * @var object
  35. */
  36. protected $options;
  37. /**
  38. * @var \chillerlan\QRCode\Output\QROutputOptionsAbstract $outputOptions
  39. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  40. */
  41. public function __construct(QROutputOptionsAbstract $outputOptions = null){
  42. $this->options = $outputOptions;
  43. if($this->optionsInterface && !$this->options instanceof $this->optionsInterface){
  44. $this->options = new $this->optionsInterface;
  45. }
  46. if(is_array($this->types) && !in_array($this->options->type, $this->types , true)){
  47. throw new QRCodeOutputException('Invalid output type!');
  48. }
  49. }
  50. /**
  51. * @param array $matrix
  52. *
  53. * @return \chillerlan\QRCode\Output\QROutputInterface
  54. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  55. */
  56. public function setMatrix(array $matrix):QROutputInterface {
  57. $this->pixelCount = count($matrix);
  58. // specify valid range?
  59. if($this->pixelCount < 2
  60. || !isset($matrix[$this->pixelCount - 1])
  61. || $this->pixelCount !== count($matrix[$this->pixelCount - 1])
  62. ){
  63. throw new QRCodeOutputException('Invalid matrix!');
  64. }
  65. $this->matrix = $matrix;
  66. return $this;
  67. }
  68. /**
  69. * @param string $data
  70. *
  71. * @return bool
  72. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  73. */
  74. protected function saveToFile(string $data):bool {
  75. try{
  76. return (bool)file_put_contents($this->options->cachefile, $data);
  77. }
  78. catch(\Exception $e){
  79. throw new QRCodeOutputException('Could not write to cache file: '.$e->getMessage());
  80. }
  81. }
  82. }