00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00016 final class CommandChain implements EditorCommand
00017 {
00018 private $chain = array();
00019
00023 public static function create()
00024 {
00025 return new self;
00026 }
00027
00031 public function add(EditorCommand $command)
00032 {
00033 $this->chain[] = $command;
00034
00035 return $this;
00036 }
00037
00042 public function run(Prototyped $subject, Form $form, HttpRequest $request)
00043 {
00044 Assert::isTrue(
00045 ($size = count($this->chain)) > 0,
00046
00047 'command chain is empty'
00048 );
00049
00050 for ($i = 0; $i < $size; ++$i) {
00051 $command = &$this->chain[$i];
00052
00053 try {
00054 $mav = $command->run($subject, $form, $request);
00055
00056 if ($mav->getView() == EditorController::COMMAND_FAILED) {
00057 $this->rollback($i);
00058 return $mav;
00059 }
00060 } catch (BaseException $e) {
00061 $this->rollback($i);
00062 throw $e;
00063 }
00064 }
00065
00066 return $mav;
00067 }
00068
00072 private function rollback($position)
00073 {
00074 for ($i = $position; $i > -1; --$i) {
00075 if ($this->chain[$i] instanceof CarefulCommand) {
00076 try {
00077 $this->chain[$i]->rollback();
00078 } catch (BaseException $e) {
00079
00080
00081 }
00082 }
00083 }
00084
00085 return $this;
00086 }
00087
00091 private function commit()
00092 {
00093 for ($size = count($this->chain), $i = 0; $i < $size; --$i) {
00094 if ($this->chain[$i] instanceof CarefulCommand)
00095 $this->chain[$i]->commit();
00096 }
00097
00098 return $this;
00099 }
00100 }
00101 ?>