1: <?php
2:
3: class AtomicOperation {
4:
5: private $operations = array();
6:
7: public function add(UndoableOperation $operation) {
8: $this->operations[] = $operation;
9: }
10:
11: public function run() {
12: $executed = array();
13: $error = null;
14:
15: foreach ($this->operations as $operation) {
16: try {
17: if ($operation->run()) {
18: array_unshift($executed, $operation);
19: } else {
20: $error = $operation;
21: break;
22: }
23: } catch (Exception $ex) {
24: $error = $operation;
25: break;
26: }
27: }
28:
29: if ($error != null) {
30: foreach ($executed as $operation) {
31: try {
32: $operation->undo();
33: } catch (Exception $ex) {
34:
35: }
36: }
37: throw new Exception("Error on execute operation \"$error\"");
38: }
39:
40: foreach ($this->operations as $operation) {
41: if ($operation instanceof CommitableOperation) {
42: try {
43: $operation->commit();
44: } catch (Exception $ex) {
45:
46: }
47: }
48: }
49: }
50:
51: public function __toString() {
52: $b = '';
53: foreach ($this->operations as $operation) {
54: $b .= "$operation\n";
55: }
56: return $b;
57: }
58:
59: }