@inheritdoc

@SuppressWarnings(PHPMD.ElseExpression)
540297
public function createResponse(Throwable $throwable, ContainerInterface $container): ThrowableResponseInterface
    {
        $message = 'Internal Server Error';

        $this->logException($throwable, $container, $message);

        list($isDebug, $appName, $exceptionDumper) = $this->getSettings($container);

        if ($isDebug === true) {
            $run = new Run();

            // If these two options are not used it would work fine with PHP Unit and XDebug,
            // however it produces output to console under PhpDbg. So we need a couple of
            // tweaks to make it work predictably in both environments.
            //
            // this one forbids Whoops spilling output to console
            $run->writeToOutput(false);
            // by default after sending error to output Whoops stops execution
            // as we want just generated output `string` we instruct not to halt
            $run->allowQuit(false);

            $handler = new PrettyPageHandler();
            // without the line below Whoops is too smart and do not produce any output in tests
            $handler->handleUnconditionally(true);

            if ($exceptionDumper !== null) {
                $appSpecificDetails = call_user_func($exceptionDumper, $throwable, $container);
                $handler->addDataTable("$appName Details", $appSpecificDetails);
            }

            $handler->setPageTitle("Whoops! There was a problem with '$appName'.");
            $run->pushHandler($handler);

            $html     = $run->handleException($throwable);
            $response = $this->createThrowableHtmlResponse($throwable, $html, static::DEFAULT_HTTP_ERROR_CODE);
        } else {
            $response = $this->createThrowableTextResponse($throwable, $message, static::DEFAULT_HTTP_ERROR_CODE);
        }

        return $response;
    }
384010
function FilterFields($array, $operation = 'where') {
		if (!$array)
			return;
		$out = array();
		foreach ($array as $field => $value) {
			if ($operation == 'where' && $this->source == 'internal' && preg_match('/^(.*) (.*)$/', $field, $matches)) { // special CI syntax in key e.g. 'status !=' => 'something' (only for 'where' operations)
				$key = $matches[1];
				$cond = $matches[2];
				$val = $value;
			} elseif ($operation == 'where' && $this->source == 'controller' && is_string($value) && preg_match('/^([\<\>]=?)(.*)$/', $value, $matches)) { // CI syntax in value e.g. '>=value'
				$key = $field;
				$cond = $matches[1];
				$val = $matches[2];
			} elseif ($operation == 'where' && $this->source == 'controller' && is_array($value) && preg_match('/^([\<\>]=?)(.*)$/', $value[0], $matches)) { // CI syntax in value via array (e.g. ['>=value', '<=value'])
				// Accept an array of where conditions - this works around the fact that PHP will always accept the LAST where condition in an URL
				// e.g. ?foo=>1&foo=<10 (foo will == '<10')
				// Use ?foo[]=>1&foo[]=<10 to work around this
				$key = $field;
				$cond = $matches[1];
				$val = $matches[2];

				array_shift($value); // Remove first element - which we've already taken care of
				foreach ($value as $valIndex => $valArray) {
					if (preg_match('/^([\<\>]=?)(.*)$/', $value[$valIndex], $matches))
						$out[isset($matches[1]) && $matches[1] != '=' ? "$key {$matches[1]}" : $key] = $matches[2];
				}
			} else {
				$key = $field;
				$cond = '=';
				$val = $value;
			}

			if (!isset($this->schema[$key])) // Field definition does not exist at all
				continue;

			if ( // Is read-only during a 'set'
				$operation == 'set' &&
				isset($this->schema[$key]['allowset']) &&
				!$this->schema[$key]['allowset']
			)
				continue;

			if ( // Is not filterable by
				$operation == 'where' &&
				isset($this->schema[$key]['allowquery']) &&
				!$this->schema[$key]['allowquery']
			)
				continue;

			// If we got this far its a valid field
			$out[$cond && $cond != '=' ? "$key $cond" : $key] = $val;
		}
		return $out;
	}
1234546
private function serializeIfExpression(IfExpressionInterface $ifExpression): int
    {
        $index = $this->allocateIndex();

        $serialized = [
            static::TYPE                             => static::TYPE__IF_EXPRESSION,
            static::IF_EXPRESSION_CONDITION_CALLABLE => $ifExpression->getConditionCallable(),
        ];

        assert($ifExpression->getOnTrue() !== null || $ifExpression->getOnFalse() !== null);

        if ($ifExpression->getOnTrue() !== null) {
            $serialized[static::IF_EXPRESSION_ON_TRUE_BLOCK] = $this->addBlock($ifExpression->getOnTrue());
        }
        if ($ifExpression->getOnFalse() !== null) {
            $serialized[static::IF_EXPRESSION_ON_FALSE_BLOCK] = $this->addBlock($ifExpression->getOnFalse());
        }
        if (empty($ifExpression->getProperties()) === false) {
            $serialized[static::PROPERTIES] = $ifExpression->getProperties();
        }

        $this->serializedBlocks[$index] = $serialized;

        return $index;
    }
991117
function xmlDefaultHandler($parser,$data)
		{
			//strip '<!--' and '-->' off comments
			$data = repl(array("&lt;!--", "--&gt;"), "", htmlspecialchars($data));
			$count = $this->xmlCount - 1;
			if(!empty($this->xmlDData[$count])) $this->xmlDData[$count] .= $data;
			else $this->xmlDData[$count] = $data;
		}
617660
public function existsById($id) {
		$primaryKey = $this->getPrimaryKey();
		if (is_array($primaryKey)) {
			throw new RuntimeException('Not supported with multiple primary keys');
		}
		$conditions = [
			$primaryKey => $id
		];
		return parent::exists($conditions);
	}
747448
public function inheritFields(&$element, &$rootDoc, &$package)
    {
        $fields =& $element->fields();
        if ($fields) {
            ksort($fields);
            $num = count($fields); $foo = 0;
            echo '<table class="inherit">', "\n";
            echo '<tr><th colspan="2">Fields inherited from ', $element->qualifiedName(), "</th></tr>\n";
            echo '<tr><td>';
            foreach ($fields as $field) {
                echo '<a href="', str_repeat('../', $this->_depth), $field->asPath(), '">', $field->name(), '</a>';
                if (++$foo < $num) {
                    echo ', ';
                }
            }
            echo '</td></tr>';
            echo "</table>\n\n";
            if ($element->superclass()) {
                $superclass =& $rootDoc->classNamed($element->superclass());
                if ($superclass) {
                    $this->inheritFields($superclass, $rootDoc, $package);
                }
            }
        }
    }
566364
function exclude(array $exclusionFields = [], $exclusionBehave = self::EXCLUDE_DISALLOW)
    {
        $exclude = [];
        foreach ($this->value as $field => $term)
        {
            if (!empty($exclusionFields))
            {
                $flag = in_array($field, $exclusionFields);

                ($exclusionBehave != self::EXCLUDE_ALLOW) ?: $flag = !$flag;

                if ($flag)
                    // The Field not considered as Expression Term
                    continue;
            }

            $exclude[$field] = $term;

        }// end foreach


        return new StdArray($exclude);
    }
526940
function execute($m, $params=null, $paramtypes=null, $msgID=null)
		{
			if (is_object($m))
			{
				// watch out: if $m is an xmlrpcmsg obj, this will raise a warning: no id memeber...
				$methName = $m->method();
				$msgID = $m->id;
			}
			else
			{
				$methName = $m;
			}
			$sysCall = $this->allow_system_funcs && strpos($methName, "system.") === 0;
			$dmap = $sysCall ? $GLOBALS['_xmlrpcs_dmap'] : $this->dmap;

			if(!isset($dmap[$methName]['function']))
			{
				// No such method
				return new jsonrpcresp(0,
					$GLOBALS['xmlrpcerr']['unknown_method'],
					$GLOBALS['xmlrpcstr']['unknown_method']);
			}

			// Check signature
			if(isset($dmap[$methName]['signature']))
			{
				$sig = $dmap[$methName]['signature'];
				if (is_object($m))
				{
					list($ok, $errstr) = $this->verifySignature($m, $sig);
				}
				else
				{
					list($ok, $errstr) = $this->verifySignature($paramtypes, $sig);
				}
				if(!$ok)
				{
					// Didn't match.
					return new jsonrpcresp(
						0,
						$GLOBALS['xmlrpcerr']['incorrect_params'],
						$GLOBALS['xmlrpcstr']['incorrect_params'] . ": ${errstr}"
					);
				}
			}

			$func = $dmap[$methName]['function'];
			// let the 'class::function' syntax be accepted in dispatch maps
			if(is_string($func) && strpos($func, '::'))
			{
				$func = explode('::', $func);
			}
			// verify that function to be invoked is in fact callable
			if(!is_callable($func))
			{
				error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler is not callable");
				return new jsonrpcresp(
					0,
					$GLOBALS['xmlrpcerr']['server_error'],
					$GLOBALS['xmlrpcstr']['server_error'] . ": no function matches method"
				);
			}

			// If debug level is 3, we should catch all errors generated during
			// processing of user function, and log them as part of response
			if($this->debug > 2)
			{
				$GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler('_xmlrpcs_errorHandler');
			}
			try
			{
				if (is_object($m))
				{
					if($sysCall)
					{
						$r = call_user_func($func, $this, $m);
					}
					else
					{
						$r = call_user_func($func, $m);
					}
					if (!is_a($r, 'xmlrpcresp'))
					{
						error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler does not return an xmlrpcresp object");
						if (is_a($r, 'xmlrpcval'))
						{
							$r = new jsonrpcresp($r);
						}
						else
						{
							$r = new jsonrpcresp(
								0,
								$GLOBALS['xmlrpcerr']['server_error'],
								$GLOBALS['xmlrpcstr']['server_error'] . ": function does not return jsonrpcresp or xmlrpcresp object"
							);
						}
					}
				}
				else
				{
					// call a 'plain php' function
					if($sysCall)
					{
						array_unshift($params, $this);
						$r = call_user_func_array($func,$params);
					}
					else
					{
						// 3rd API convention for method-handling functions: EPI-style
						if ($this->functions_parameters_type == 'epivals')
						{
							$r = call_user_func_array($func, array($methName, $params, $this->user_data));
							// mimic EPI behaviour: if we get an array that looks like an error, make it
							// an eror response
							if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r))
							{
								$r = new jsonrpcresp(0, (integer)$r['faultCode'], (string)$r['faultString']);
							}
							else
							{
								// functions using EPI api should NOT return resp objects,
								// so make sure we encode the return type correctly
								$r = new jsonrpcresp(php_xmlrpc_encode($r, array('extension_api')));
							}
						}
						else
						{
							$r = call_user_func_array($func, $params);
						}
					}
					// the return type can be either an xmlrpcresp object or a plain php value...
					if (!is_a($r, 'xmlrpcresp'))
					{
						// what should we assume here about automatic encoding of datetimes
						// and php classes instances???
						$r = new jsonrpcresp(php_jsonrpc_encode($r, $this->phpvals_encoding_options));
					}
				}
				// here $r is either an xmlrpcresp or jsonrpcresp
				if (!is_a($r, 'jsonrpcresp'))
				{

					// dirty trick: user has given us back an xmlrpc response,
					// since he had an existing xmlrpc server with boatloads of code.
					// Be nice to him, and serialize the xmlrpc stuff into JSON.
					// We also override the content_type of the xmlrpc response,
					// but lack knoweledge of intented response charset...
					$r->content_type = 'application/json';
					$r->payload = serialize_jsonrpcresp($r, $msgID);
				}
				else
				{
					$r->id = $msgID;
				}
			}
			catch(Exception $e)
			{
			// (barring errors in the lib) an uncatched exception happened
				// in the called function, we wrap it in a proper error-response
				switch($this->exception_handling)
				{
					case 2:
						throw $e;
						break;
					case 1:
						$r = new jsonrpcresp(0, $e->getCode(), $e->getMessage());
						break;
					default:
						$r = new jsonrpcresp(0, $GLOBALS['xmlrpcerr']['server_error'], $GLOBALS['xmlrpcstr']['server_error']);
				}
			}
			if($this->debug > 2)
			{
				// note: restore the error handler we found before calling the
				// user func, even if it has been changed inside the func itself
				if($GLOBALS['_xmlrpcs_prev_ehandler'])
				{
					set_error_handler($GLOBALS['_xmlrpcs_prev_ehandler']);
				}
				else
				{
					restore_error_handler();
				}
			}
			return $r;
		}
345550
public function execute($params = array()){
    
        if($this->entity instanceof OneToOneJoinInterface) { 
           if(array_key_exists('locale', $params)) {
               $this->getQueryBuilder()->where($params['locale']);
           }
            
            $this->getQueryBuilder()->join($this->entity->getJoinRelationships());
        }
     
        $this->getQueryBuilder()->where($params);
        
        $query = $this->getQueryBuilder()->getQuery($this->entity, QueryBuilder::GET_ALL_ITEMS_QUERY, QueryBuilder::PARENT_AND_CHILD);

        $result = $this->query($query);
        $param = get_class($this->entity) . 's';
             
        return array($param => $result, $param . 'Count' => $this->getTotalRowCount());
    }
433423
public function bind(array $param) {
		foreach ($param as $key => $value) {
			if (is_null($value)) {
				$type = \PDO::PARAM_NULL;
			} else if (is_bool($value)) {
				$type = \PDO::PARAM_BOOL;
			} else if (is_int($value)) {
				$type = \PDO::PARAM_INT;
			} else {
				$type = \PDO::PARAM_STR;
			}
			$this->result->bindValue(is_int($key) ? ++$key : $key, $value, $type);
		}
	}
685996
public function select(
        $table,
        $conditions = null,
        $fields = null,
        $order = null,
        $limit = null,
        $offset = null
    )
    {
        if (is_null($fields)) {
            $fields = "*";
        }

        $queryString = "SELECT {$fields} FROM {$table} ";

        if (!is_null($conditions)) {
            $queryString .= "WHERE {$conditions} ";
        }

        if (!is_null($order)) {
            $queryString .= "ORDER BY {$order} ";
        }

        if (!is_null($limit)) {
            $queryString .= "LIMIT {$limit} ";
        }

        if (!is_null($offset) && !is_null($limit)) {
            $queryString .= "OFFSET {$offset} ";
        }


        $queryString .= ";";

        $this->query($queryString);

        return $this->countRows();
    }
1167932
public function buildExpression()
    {
        /** @var EditableFormField $formFieldWatch */
        $formFieldWatch = $this->ConditionField();
        //Encapsulated the action to the object
        $action = $formFieldWatch->getJsEventHandler();

        // is this field a special option field
        $checkboxField = $formFieldWatch->isCheckBoxField();
        $radioField = $formFieldWatch->isRadioField();
        $target = sprintf('$("%s")', $formFieldWatch->getSelectorFieldOnly());
        $fieldValue = Convert::raw2js($this->FieldValue);

        $conditionOptions = [
            'ValueLessThan'         => '<',
            'ValueLessThanEqual'    => '<=',
            'ValueGreaterThan'      => '>',
            'ValueGreaterThanEqual' => '>='
        ];

        // and what should we evaluate
        switch ($this->ConditionOption) {
            case 'IsNotBlank':
            case 'IsBlank':
                $expression = ($checkboxField || $radioField) ? "!{$target}.is(\":checked\")" : "{$target}.val() == ''";
                if ((string) $this->ConditionOption === 'IsNotBlank') {
                    //Negate
                    $expression = "!({$expression})";
                }
                break;
            case 'HasValue':
            case 'ValueNot':
                if ($checkboxField) {
                    if ($formFieldWatch->isCheckBoxGroupField()) {
                        $expression = sprintf(
                            "$.inArray('%s', %s.filter(':checked').map(function(){ return $(this).val();}).get()) > -1",
                            $fieldValue,
                            $target
                        );
                    } else {
                        $expression = "{$target}.prop('checked')";
                    }
                } elseif ($radioField) {
                    // We cannot simply get the value of the radio group, we need to find the checked option first.
                    $expression = sprintf(
                        '%s.closest(".field, .control-group").find("input:checked").val() == "%s"',
                        $target,
                        $fieldValue
                    );
                } else {
                    $expression = sprintf('%s.val() == "%s"', $target, $fieldValue);
                }

                if ((string) $this->ConditionOption === 'ValueNot') {
                    //Negate
                    $expression = "!({$expression})";
                }
                break;
            case 'ValueLessThan':
            case 'ValueLessThanEqual':
            case 'ValueGreaterThan':
            case 'ValueGreaterThanEqual':
                $expression = sprintf(
                    '%s.val() %s parseFloat("%s")',
                    $target,
                    $conditionOptions[$this->ConditionOption],
                    $fieldValue
                );
                break;
            default:
                throw new LogicException("Unhandled rule {$this->ConditionOption}");
                break;
        }

        $result = [
            'operation' => $expression,
            'event'     => $action,
        ];

        return $result;
    }
1324680
function doSelect(PDO $conn = null) {
		$q = clone $this;

		if (!$q->getTable()) {
			throw new RuntimeException('No table specified.');
		}

		$q->setAction(self::ACTION_SELECT);
		return $q->getQuery($conn)->bindAndExecute();
	}
463807
private function _sqlFromMethod($method)
    {
        if(!preg_match('/^(findBy|oneBy)(.*?)$/', $method, $m))
            throw new \BadMethodCallException("Unable to parse $method");

        // split on AND or OR and case boundries
        $sql = strtolower(preg_replace('/(?<=[a-z0-9\b])(Or|And)(?=[A-Z])/',' $1 ',$m[2]));

        // add parameter binds
        return preg_replace_callback('/\b([\w-]+)\b/', function($m) {
            return ($m[0] != 'or' && $m[0] != 'and') ? "`{$m[0]}`=?" : $m[0];
        }, $sql);
    }
923653
function bind($orig,$b,$wanted){
    $result = array($b);
    foreach($wanted as $k => $field){
      if(isset($orig[$field])&&strlen("".$orig[$field])){
        $result[$field] = $orig[$field];
      }else{
        $result[$field] = null;
      }
    }
    return $result;
  }
1046695
function insertSiblingData($FieldValueArray=array(),$ConditionString=null,$Rest=null)
    {
		$this->lock();
    	//Find the Sibling
        $Arguments=func_get_args();
        array_shift($Arguments); //first argument, the array
        array_shift($Arguments);
        if ($ConditionString) $ConditionString="WHERE $ConditionString";
        $Query="SELECT {$this->right()} AS `Right`".
        	" FROM {$this->table()} $ConditionString";

        array_unshift($Arguments,$Query);
        $Sibl=call_user_func_array("Jf::sql",$Arguments);

        $Sibl=$Sibl[0];
        if ($Sibl==null)
        {
            $Sibl["Left"]=$Sibl["Right"]=0;
        }
        Jf::sql("UPDATE {$this->table()} SET {$this->right()} = {$this->right()} + 2 WHERE {$this->right()} > ?",$Sibl["Right"]);
        Jf::sql("UPDATE {$this->table()} SET {$this->left()} = {$this->left()} + 2 WHERE {$this->left()} > ?",$Sibl["Right"]);

        $FieldsString=$ValuesString="";
        $Values=array();
        if ($FieldValueArray)
        foreach($FieldValueArray as $k=>$v)
        {
            $FieldsString.=",";
            $FieldsString.="`".$k."`";
            $ValuesString.=",?";
            $Values[]=$v;
        }

        $Query= "INSERT INTO {$this->table()} ({$this->left()},{$this->right()} $FieldsString) ".
        	"VALUES(?,? $ValuesString)";
        array_unshift($Values,$Sibl["Right"]+2);
        array_unshift($Values,$Sibl["Right"]+1);
        array_unshift($Values,$Query);

        $Res=call_user_func_array("Jf::sql",$Values);
		$this->unlock();
        return $Res;
    }
452791
public function execute($objectContext)
    {
        if (method_exists($objectContext, $this->method))
        {
            if (!empty($this->parameters))
            {
                $objectContext->{$this->method}($this->parameters);
            }
            else
            {
                $objectContext->{$this->method}($this->parameters);
            }
        }
    }