Returns a new AMQPWriter or mutates the provided $pkt

@param string $channel
@param array $method_sig
@param AMQPWriter|string $args
@param AMQPWriter $pkt
@return AMQPWriter
486645
protected function prepare_channel_method_frame($channel, $method_sig, $args = '', $pkt = null)
    {
        if ($args instanceof AMQPWriter) {
            $args = $args->getvalue();
        }

        $pkt = $pkt ?: new AMQPWriter();

        $pkt->write_octet(1);
        $pkt->write_short($channel);
        $pkt->write_long(mb_strlen($args, 'ASCII') + 4); // 4 = length of class_id and method_id
        // in payload

        $pkt->write_short($method_sig[0]); // class_id
        $pkt->write_short($method_sig[1]); // method_id
        $pkt->write($args);

        $pkt->write_octet(0xCE);

        $this->debug->debug_method_signature1($method_sig);

        return $pkt;
    }
281832
public static void generateSQL(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
		JQLChecker jqlChecker = JQLChecker.getInstance();

		methodBuilder.addCode("\n// generate sql\n");
		String sql = jqlChecker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {
			@Override
			public String onColumnNameToUpdate(String columnName) {
				// only entity's columns
				return currentEntity.findPropertyByName(columnName).columnName;
			}

			@Override
			public String onColumnName(String columnName) {
				return currentSchema.findColumnNameByPropertyName(method, columnName);
			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				return "?";
			}

		});

		if (method.jql.dynamicReplace.containsKey(JQLDynamicStatementType.DYNAMIC_WHERE)) {
			methodBuilder.addStatement("String _sql=String.format($S, $L)",
					sql.replace(method.jql.dynamicReplace.get(JQLDynamicStatementType.DYNAMIC_WHERE), "%s"),
					"StringUtils.ifNotEmptyAppend(_sqlDynamicWhere,\" AND \")");
		} else {
			methodBuilder.addStatement("String _sql=$S", sql);
		}
	}
465208
public static function paginate($method, array $params = [])
    {
        // Set request params
        $params = array_filter(array_merge([
            'page' => 1
        ], $params));

        $instance = new static([], static::getParentID());;

        // Make request
        $result = $instance->makeRequest($instance->getEndpoint(), $method, [$params]);

        // Hydrate object
        $result = $instance->paginateHydrate($result);

        // Append search params
        $result->appends($params);

        return $result;
    }
509974
private Formatter createFormatter(Method method, Class<?>[] sig, int prio)
    {
        if (method.getReturnType() != Component.class)
        {
            throw new InvalidFormatMethodException(getClass(), method, "Format methods must return Component!");
        }

        final Invoker invoker;
        if (sig.length == 1)
        {
            invoker = new InputOnly();
        }
        else if (sig.length == 2)
        {
            if (sig[1] == Context.class)
            {
                invoker = new ContextOnly();
            }
            else if (sig[1] == Arguments.class)
            {
                invoker = new ArgsOnly();
            }
            else
            {
                throw new InvalidFormatMethodException(getClass(), method,
                                                       "Format methods may only take Context and Arguments parameters!");
            }
        }
        else if (sig.length == 3)
        {
            if (sig[1] == Context.class && sig[2] == Arguments.class)
            {
                invoker = new CompleteContextFirst();
            }
            else if (sig[1] == Arguments.class && sig[2] == Context.class)
            {
                invoker = new CompleteArgsFirst();
            }
            else
            {
                throw new InvalidFormatMethodException(getClass(), method,
                                                       "Format methods may only take Context and Arguments parameters!");
            }
        }
        else
        {
            throw new InvalidFormatMethodException(getClass(), method,
                                                   "Format methods must take at most 3 parameters!");
        }
        return new Formatter(this, method, prio, invoker);
    }
1147213
public function set($method_or_arg, $method = null)
    {
        $method = is_callable($method_or_arg) ? $method_or_arg : $method;
        $arg = is_callable($method_or_arg) ? null : $method_or_arg;

        $self = $this;

        if ($this->isActive($arg)) {
            $this->app->addHook('post-init', function () use ($method, $self) {
                $page = $self->getPage();
                $page->id = $_GET[$self->name.'_id'];
                $self->app->stickyGET($self->name.'_id');

                try {
                    call_user_func($method, $page, $self);
                } catch (Exception $e) {
                    // post-init cannot catch StopInit
                    if ($e instanceof Exception_StopInit) {
                        return;
                    }
                    throw $e;
                    // exception occured possibly due to a nested page. We
                    // are already executing from post-init, so
                    // it's fine to ignore it.
                }

                //Imants: most likely forgetting is not needed, because we stop execution anyway
                //$self->app->stickyForget($self->name.'_id');
                //$self->app->stickyForget($self->name);
            });
            throw $this->exception('', 'StopInit');
        }

        return $this;
    }
1117686
public function invoke($method, $_ = null)
	{
		$params = func_get_args();
		array_shift($params);

		return $this->invokeArgs($method, $params);
	}
349222
private static function createMethodParam(
        ParseTree &$current_leaf,
        ParseTree $current_parent,
        array $type_tokens,
        $current_token,
        &$i
    ) {
        $byref = false;
        $variadic = false;
        $has_default = false;
        $default = '';

        $c = count($type_tokens);

        if ($current_token === '&') {
            throw new TypeParseTreeException('Magic args cannot be passed by reference');
        }

        if ($current_token === '...') {
            $variadic = true;

            ++$i;
            $current_token = $i < $c ? $type_tokens[$i] : null;
        }

        if (!$current_token || $current_token[0] !== '$') {
            throw new TypeParseTreeException('Unexpected token after space ' . $current_token);
        }

        $new_parent_leaf = new ParseTree\MethodParamTree(
            $current_token,
            $byref,
            $variadic,
            $current_parent
        );

        for ($j = $i + 1; $j < $c; ++$j) {
            $ahead_type_token = $type_tokens[$j];

            if ($ahead_type_token === ','
                || ($ahead_type_token === ')' && $type_tokens[$j - 1] !== '(')
            ) {
                $i = $j - 1;
                break;
            }

            if ($has_default) {
                $default .= $ahead_type_token;
            }

            if ($ahead_type_token === '=') {
                $has_default = true;
                continue;
            }

            if ($j === $c - 1) {
                throw new TypeParseTreeException('Unterminated method');
            }
        }

        $new_parent_leaf->default = $default;

        if ($current_leaf !== $current_parent) {
            $new_parent_leaf->children = [$current_leaf];
            $current_leaf->parent = $new_parent_leaf;
            array_pop($current_parent->children);
        }

        $current_parent->children[] = $new_parent_leaf;

        $current_leaf = $new_parent_leaf;
    }
1207624
AmqpClient startOkConnection(AmqpArguments clientProperties, String mechanism, String response, String locale, Continuation callback, ErrorHandler error) {
        Object[] args = {clientProperties, mechanism, response, locale};
        AmqpBuffer bodyArg = null;

        String methodName = "startOkConnection";
        String methodId = "10" + "11";
        AmqpMethod amqpMethod = MethodLookup.LookupMethod(methodId);
        Object[] arguments = {this, amqpMethod, 0, args, bodyArg};
        asyncClient.enqueueAction(methodName, "write", arguments, callback, error);
        return this;
    }
1239523
public function callMethod (&$api, $module, $method, $args = array ())
	{
		
		// Set module class name
		
		$class		= $this->getModuleClass ($module);
		
		// Create module object
		
		$obj		= new $class;
		
		// Set the API reference
		
		$obj->api	= $api;
		
		// Call the method init function for any custom code before the action
		
		if ($obj->callInit ($this, $method, $args))
		{
			
			// Call module method and pass the arguments list as 
			
			$return	= call_user_func_array (array ($obj, $method), array ($args));
			
		}
		
		// Return result
		
		return $obj->getResult ();
		
	}
1047144
public function createQueue(AMQPChannel $channel, RabbitMqOptionTransfer $queueOptionTransfer)
    {
        $queueParams = $this->convertTransferToArray($queueOptionTransfer);

        $channel
            ->queue_declare(
                $queueParams['queue_name'],
                $queueParams['passive'],
                $queueParams['durable'],
                $queueParams['exclusive'],
                $queueParams['auto_delete'],
                $queueParams['no_wait'],
                new AMQPTable($queueParams['arguments'])
            );

        return $queueParams;
    }
195354
public function getMethodParams(
        $method_id,
        StatementsSource $source = null,
        array $args = null,
        Context $context = null
    ) : array {
        list($fq_class_name, $method_name) = explode('::', $method_id);

        if ($this->params_provider->has($fq_class_name)) {
            $method_params = $this->params_provider->getMethodParams(
                $fq_class_name,
                $method_name,
                $args,
                $source,
                $context
            );

            if ($method_params !== null) {
                return $method_params;
            }
        }

        $declaring_method_id = $this->getDeclaringMethodId($method_id);

        // functions
        if (CallMap::inCallMap($declaring_method_id ?: $method_id)) {
            $declaring_fq_class_name = explode('::', $declaring_method_id ?: $method_id)[0];

            $class_storage = $this->classlike_storage_provider->get($declaring_fq_class_name);

            if (!$class_storage->stubbed) {
                $function_param_options = CallMap::getParamsFromCallMap($declaring_method_id ?: $method_id);

                if ($function_param_options === null) {
                    throw new \UnexpectedValueException(
                        'Not expecting $function_param_options to be null for ' . $declaring_method_id
                    );
                }

                if (!$source || $args === null || count($function_param_options) === 1) {
                    return $function_param_options[0];
                }

                if ($context && $source instanceof \Psalm\Internal\Analyzer\StatementsAnalyzer) {
                    foreach ($args as $arg) {
                        \Psalm\Internal\Analyzer\Statements\ExpressionAnalyzer::analyze(
                            $source,
                            $arg->value,
                            $context
                        );
                    }
                }

                return FunctionLikeAnalyzer::getMatchingParamsFromCallMapOptions(
                    $source->getCodebase(),
                    $function_param_options,
                    $args
                );
            }
        }

        if ($declaring_method_id) {
            $storage = $this->getStorage($declaring_method_id);

            $params = $storage->params;

            if ($storage->has_docblock_param_types) {
                return $params;
            }

            $appearing_method_id = $this->getAppearingMethodId($declaring_method_id);

            if (!$appearing_method_id) {
                return $params;
            }

            list($appearing_fq_class_name, $appearing_method_name) = explode('::', $appearing_method_id);

            $class_storage = $this->classlike_storage_provider->get($appearing_fq_class_name);

            if (!isset($class_storage->overridden_method_ids[$appearing_method_name])) {
                return $params;
            }

            if (!isset($class_storage->documenting_method_ids[$appearing_method_name])) {
                return $params;
            }

            $overridden_method_id = $class_storage->documenting_method_ids[$appearing_method_name];
            $overridden_storage = $this->getStorage($overridden_method_id);

            list($overriding_fq_class_name) = explode('::', $overridden_method_id);

            foreach ($params as $i => $param) {
                if (isset($overridden_storage->params[$i]->type)
                    && $overridden_storage->params[$i]->has_docblock_type
                    && $overridden_storage->params[$i]->name === $param->name
                ) {
                    $params[$i] = clone $param;
                    /** @var Type\Union $params[$i]->type */
                    $params[$i]->type = clone $overridden_storage->params[$i]->type;

                    if ($source) {
                        $params[$i]->type = self::localizeParamType(
                            $source->getCodebase(),
                            $params[$i]->type,
                            $appearing_fq_class_name,
                            $overriding_fq_class_name
                        );
                    }

                    if ($params[$i]->signature_type
                        && $params[$i]->signature_type->isNullable()
                    ) {
                        $params[$i]->type->addType(new Type\Atomic\TNull);
                    }

                    $params[$i]->type_location = $overridden_storage->params[$i]->type_location;
                }
            }

            return $params;
        }

        throw new \UnexpectedValueException('Cannot get method params for ' . $method_id);
    }
124563
public function close($reply_code = 0, $reply_text = '', $method_sig = array(0, 0))
    {
        $this->callbacks = array();
        if ($this->is_open === false || $this->connection === null) {
            $this->do_close();

            return null; // already closed
        }
        list($class_id, $method_id, $args) = $this->protocolWriter->channelClose(
            $reply_code,
            $reply_text,
            $method_sig[0],
            $method_sig[1]
        );

        try {
            $this->send_method_frame(array($class_id, $method_id), $args);
        } catch (\Exception $e) {
            $this->do_close();

            throw $e;
        }

        return $this->wait(array(
            $this->waitHelper->get_wait('channel.close_ok')
        ), false, $this->channel_rpc_timeout );
    }
609271
public static function createConnectionUsingPHPAMQPLib(AMQPServerConfigurationInterface $config, $sslCAPath = null, $sslHost = null)
    {
        if($config->getSSL() === true) {
            $sslOptions = [
                'verify_peer' => true,
            ];

            if ($sslCAPath !== null) {
                $sslOptions['capath'] = $sslCAPath;
            }

            if ($sslHost !== null) {
                $sslOptions['CN_match'] = $sslHost;
            } elseif(!filter_var($config->getHost(), FILTER_VALIDATE_IP)) {
                $sslOptions['CN_match'] = $config->getHost();
            }

            $amqp = new AMQPSSLConnection(
                $config->getHost(),
                $config->getPort(),
                $config->getUsername(),
                $config->getPassword(),
                $config->getVHost(),
                $sslOptions,
                [
                    'connection_timeout' => $config->getConnectionTimeout(),
                ]
            );
        } else {
            $amqp = new AMQPSocketConnection(
                $config->getHost(),
                $config->getPort(),
                $config->getUsername(),
                $config->getPassword(),
                $config->getVHost(),
                false,
                'AMQPLAIN',
                null,
                'en_US',
                $config->getConnectionTimeout(),
                true
            );
        }

        register_shutdown_function(function() use ($amqp){
            if ($amqp->isConnected()) {
                try {
                    $amqp->close();
                } catch (Exception $ex) {
                }
            }
        });

        return $amqp;
    }
845355
public function make_request($api_method, $args = array(),
                               $http_method = 'GET') {
    $args['format'] = 'json';
    $args['auth_token'] = $this->auth_token;
    $url = "$this->api_target/$this->api_version/$api_method";
    $post_data = null;

    // add args to url for GET
    if ($http_method == 'GET') {
      $url .= '?' . http_build_query($args);
    } else {
      $post_data = $args;
    }

    $response = $this->curl_request($url, $post_data);

    // make sure response is valid json
    $response = json_decode($response);
    if (!$response) {
      throw new HipChat_Exception(self::STATUS_BAD_RESPONSE,
        "Invalid JSON received: $response", $url);
    }

    return $response;
  }
997785
private function send(callable $method, ...$args): \Generator
    {
        while ($this->busy) {
            try {
                yield $this->busy->promise();
            } catch (\Throwable $exception) {
                // Ignore failure from another operation.
            }
        }

        if (!$this->handle) {
            throw new ConnectionException("The connection to the database has been closed");
        }

        try {
            $this->deferred = $this->busy = new Deferred;

            $handle = $method(...$args);

            Loop::enable($this->poll);
            if (!$this->handle->flush()) {
                Loop::enable($this->await);
            }

            $result = yield $this->deferred->promise();
        } catch (pq\Exception $exception) {
            throw new FailureException($this->handle->errorMessage, 0, $exception);
        } finally {
            $this->deferred = $this->busy = null;
        }

        if (!$result instanceof pq\Result) {
            throw new FailureException("Unknown query result");
        }

        switch ($result->status) {
            case pq\Result::EMPTY_QUERY:
                throw new QueryError("Empty query string");

            case pq\Result::COMMAND_OK:
                if ($handle instanceof pq\Statement) {
                    return $handle; // Will be wrapped into a PqStatement object.
                }

                return new PqCommandResult($result);

            case pq\Result::TUPLES_OK:
                return new PqBufferedResultSet($result);

            case pq\Result::SINGLE_TUPLE:
                $this->busy = new Deferred;
                $result = new PqUnbufferedResultSet($this->fetch, $result, $this->release);
                return $result;

            case pq\Result::NONFATAL_ERROR:
            case pq\Result::FATAL_ERROR:
                throw new QueryExecutionError($result->errorMessage, $result->diag);

            case pq\Result::BAD_RESPONSE:
                throw new FailureException($result->errorMessage);

            default:
                throw new FailureException("Unknown result status");
        }
    }
871455
public function createExchange(AMQPChannel $channel, RabbitMqOptionTransfer $queueOptionTransfer)
    {
        $exchangeParams = $this->convertTransferToArray($queueOptionTransfer);

        $channel
            ->exchange_declare(
                $exchangeParams['queue_name'],
                $exchangeParams['type'],
                $exchangeParams['passive'],
                $exchangeParams['durable'],
                $exchangeParams['auto_delete']
            );
    }
855040
protected function buildPKConditions($pk, $_data){
        if(is_string($pk)){
            $pks = array($pk);
            if(!is_array($_data)){
                $_data = array($pk => $_data);
            }
        }
        else{
            $pks = $pk;
        }
        $params = array();
        foreach($pks as $k => $pk){
            $pks[$k] = $pk.'=:pk'.$k;
            $params[':pk'.$k] = $_data[$pk];
        }
        array_unshift($pks, 'AND');
        
        return array($pks, $params);
    }