00001 <?php 00002 /**************************************************************************** 00003 * Copyright (C) 2004-2007 by Konstantin V. Arkhipov, Anton E. Lebedevich * 00004 * * 00005 * This program is free software; you can redistribute it and/or modify * 00006 * it under the terms of the GNU Lesser General Public License as * 00007 * published by the Free Software Foundation; either version 3 of the * 00008 * License, or (at your option) any later version. * 00009 * * 00010 ****************************************************************************/ 00011 /* $Id: LogicalChain.class.php 4687 2007-12-09 18:57:18Z voxus $ */ 00012 00018 final class LogicalChain extends SQLChain 00019 { 00023 public static function block($args, $logic) 00024 { 00025 Assert::isTrue( 00026 ($logic == BinaryExpression::EXPRESSION_AND) 00027 || ($logic == BinaryExpression::EXPRESSION_OR), 00028 00029 "unknown logic '{$logic}'" 00030 ); 00031 00032 $logicalChain = new self; 00033 00034 foreach ($args as &$arg) { 00035 if ( 00036 !$arg instanceof LogicalObject 00037 && !$arg instanceof SelectQuery 00038 ) 00039 throw new WrongArgumentException( 00040 'unsupported object type: '.get_class($arg) 00041 ); 00042 00043 $logicalChain->exp($arg, $logic); 00044 } 00045 00046 return $logicalChain; 00047 } 00048 00052 public function expAnd(LogicalObject $exp) 00053 { 00054 return $this->exp($exp, BinaryExpression::EXPRESSION_AND); 00055 } 00056 00060 public function expOr(LogicalObject $exp) 00061 { 00062 return $this->exp($exp, BinaryExpression::EXPRESSION_OR); 00063 } 00064 00065 public function toBoolean(Form $form) 00066 { 00067 $chain = &$this->chain; 00068 00069 $size = count($chain); 00070 00071 if (!$size) 00072 throw new WrongArgumentException( 00073 'empty chain can not be calculated' 00074 ); 00075 elseif ($size == 1) 00076 return $chain[0]->toBoolean($form); 00077 else { // size > 1 00078 $out = $chain[0]->toBoolean($form); 00079 00080 for ($i = 1; $i < $size; ++$i) { 00081 $out = 00082 self::calculateBoolean( 00083 $this->logic[$i], 00084 $out, 00085 $chain[$i]->toBoolean($form) 00086 ); 00087 } 00088 00089 return $out; 00090 } 00091 00092 Assert::isUnreachable(); 00093 } 00094 00095 private static function calculateBoolean($logic, $left, $right) 00096 { 00097 switch ($logic) { 00098 case BinaryExpression::EXPRESSION_AND: 00099 return $left && $right; 00100 00101 case BinaryExpression::EXPRESSION_OR: 00102 return $left || $right; 00103 00104 default: 00105 throw new WrongArgumentException( 00106 "unknown logic - '{$logic}'" 00107 ); 00108 } 00109 00110 Assert::isUnreachable(); 00111 } 00112 } 00113 ?>