cryptal  latest
Cryptography Abstraction Layer
AbstractContextBasedAlgorithm.php
1 <?php
2 
3 namespace fpoirotte\Cryptal;
4 
6 {
8  private $finalized = false;
9 
11  abstract protected function internalUpdate($data);
12 
20  abstract protected function internalFinalize();
21 
22  final public function update($data)
23  {
24  if ($this->finalized) {
25  throw new \RuntimeException('Cannot update an already-finalized context');
26  }
27 
28  if (!is_string($data)) {
29  throw new \InvalidArgumentException('Invalid data');
30  }
31 
32  $this->internalUpdate($data);
33  return $this;
34  }
35 
45  final public function finalize($raw = false)
46  {
47  if ($this->finalized) {
48  throw new \RuntimeException('Cannot update an already-finalized context');
49  }
50 
51  $this->finalized = true;
52  $res = $this->internalFinalize();
53  return $raw ? $res : bin2hex($res);
54  }
55 
63  final public function __toString()
64  {
65  // We clone the object first, to make sure
66  // it is still usable after this call.
67  $obj = clone $this;
68  return $obj->finalize(false);
69  }
70 }