1 <?php
2 3 4
5 namespace Team3\PayU\SignatureCalculator\Encoder;
6
7 use Psr\Log\LoggerInterface;
8 use Team3\PayU\SignatureCalculator\Encoder\Algorithms\AlgorithmInterface;
9 use Team3\PayU\SignatureCalculator\Encoder\Strategy\EncoderStrategyInterface;
10
11 12 13 14 15 16
17 class Encoder implements EncoderInterface
18 {
19 20 21
22 private $strategies;
23
24 25 26
27 private $logger;
28
29 30 31
32 public function __construct(LoggerInterface $logger)
33 {
34 $this->strategies = [];
35 $this->logger = $logger;
36 }
37
38 39 40 41 42 43 44 45 46 47
48 public function encode($data, AlgorithmInterface $algorithm)
49 {
50 foreach ($this->strategies as $strategy) {
51 if ($strategy->supports($algorithm)) {
52 $result = $strategy->encode($data);
53 $this->logEncoderResult($strategy, $algorithm, $data, $result);
54
55 return $result;
56 }
57 }
58
59 $exception = $this->buildException($algorithm);
60 $this->logException($exception);
61
62 throw $exception;
63 }
64
65 66 67 68 69
70 public function addStrategy(EncoderStrategyInterface $strategy)
71 {
72 $this->strategies[] = $strategy;
73
74 return $this;
75 }
76
77 78 79 80 81 82
83 private function logEncoderResult(
84 EncoderStrategyInterface $encoderStrategy,
85 AlgorithmInterface $algorithm,
86 $inputData,
87 $encoderResult
88 ) {
89 $this
90 ->logger
91 ->debug(sprintf(
92 'Encoder\'s strategy %s (algorithm: %s) successfully encode data "%s" into "%s"',
93 get_class($encoderStrategy),
94 get_class($algorithm),
95 $inputData,
96 $encoderResult
97 ));
98 }
99
100 101 102 103 104
105 private function buildException(AlgorithmInterface $algorithm)
106 {
107 return new EncoderException(sprintf(
108 'None of encoder strategies supports algorithm "%s"',
109 get_class($algorithm)
110 ));
111 }
112
113 114 115
116 private function logException(\Exception $exception)
117 {
118 $this
119 ->logger
120 ->error(sprintf(
121 '%s thrown %s with message "%s"',
122 get_class($this),
123 get_class($exception),
124 $exception->getMessage()
125 ));
126 }
127 }
128