Execute requests
@param MultiCurlRequest[] $requests
428572
public function run($requests)
    {
        $this->_queue   = $requests;
        $this->_status  = array_fill(0, $this->threads, false);
        $this->_retries = array_fill(0, $this->threads, 0);
        $this->processNext();
        parent::run();
    }
55784
public function fetch(array $urls){

		if(empty($urls)){
			throw new RequestException('$urls is empty');
		}

		$this->stack      = $urls;
		$this->curl_multi = curl_multi_init();

		curl_multi_setopt($this->curl_multi, CURLMOPT_PIPELINING, 2);
		curl_multi_setopt($this->curl_multi, CURLMOPT_MAXCONNECTS, $this->options->window_size);

		// shoot out the first batch of requests
		array_map(function(){
			$this->createHandle();
		}, range(1, $this->options->window_size));

		/// ...and start processing the stack
		$this->processStack();
	}
945405
public function execute(Request $request)
    {

        $phases = ['prepare', 'respond', 'close'];
        $response = null;

        foreach ($phases as $phase) {

            $key = 0;

            if ($phase === 'respond' && is_null($response)) {
                throw new StackException;
            } else if ($phase === 'close' && $key === 0) {
                $response->send();
            }

            if ($phase === 'prepare' && count($this->{$phase . 'ableMiddlewares'}) === 0) {
                throw new StackException('You must at least add one prepareableMiddleware that generates a Response.');
            } else if (count($this->{$phase . 'ableMiddlewares'}) === 0) {
                continue;
            }

            $next_middleware_spec = $this->{$phase . 'ableMiddlewares'}[$key];

            //Use a while so that middlewares can add other middlewares to execute
            while ($next_middleware_spec) {
                //Get the middleware
                $middleware = array_shift($next_middleware_spec);

                if (!is_null($response)) {
                    array_unshift($next_middleware_spec, $response);
                }

                //Put request as first parameter for the middleware
                array_unshift($next_middleware_spec, $request);

                $return = call_user_func_array([$middleware, $phase], $next_middleware_spec);

                if ($phase === 'prepare' && $return instanceof Response) {
                    $response = $return;
                    break;
                } else if ($phase === 'respond') {
                    //Reassign response in case it was recreated during that phase
                    $response = $return;
                }
                $key++;
                $next_middleware_spec = isset($this->{$phase . 'ableMiddlewares'}[$key]) ? $this->{$phase . 'ableMiddlewares'}[$key] : false;
            }
        }
    }
389590
public function batchRequest(array $requests) {
        $data = [];

        foreach ($requests as $request) {
            if (!array_key_exists('method', $request)) {
                throw new BadMethodCallException(
                    'Missing method in one of the sub-requests of this batch request'
                );
            }

            $params = [];

            if (array_key_exists('params', $request)) {
                $params = $request['params'];
            }

            $params['apikey'] = $this->config[self::KEY];

            if (array_key_exists(self::LANGUAGE, $this->config)) {
                $params[self::LANGUAGE] = $this->config[self::LANGUAGE];
            }

            $data[] = [
                'version' => '2.0',
                'method' => $request['method'],
                'params' => $params,
                'id' => $this->genID()
            ];
        }

        $responses = $this->execute($data);

        $results = [];

        foreach ($responses as $response) {
            if (!is_array($response)) {
                throw new RuntimeException(sprintf(
                    'Found invalid result for request in batch: %s',
                    $response
                ));
            }

            $this->evaluateResponse($response);

            $results[] = $response['result'];
        }

        return $results;
    }
88832
protected function makeExecuteRequest(Collection $requests)
    {
        $clientRequests = $requests->map(function (VkRequest $request) {
            return new Request($request->method, $request->parameters);
        });

        return ExecuteRequest::make($clientRequests->all());
    }
376427
public function sendRequests(array $requests) {
		if (!extension_loaded('curl')) {
			throw new \TYPO3\Flow\Http\Exception('CurlEngine requires the PHP CURL extension to be installed and loaded.', 1346319808);
		}

		$multiCurl = curl_multi_init();

		$curlHandles = array();
		foreach ($requests as $index => $request) {
			$requestUri = $request->getUri();
			$curlHandle = curl_init((string)$requestUri);

			$options = array(
				CURLOPT_RETURNTRANSFER => TRUE,
				CURLOPT_HEADER => TRUE,
				CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				CURLOPT_FRESH_CONNECT => TRUE,
				CURLOPT_FORBID_REUSE => TRUE,
				CURLOPT_TIMEOUT => $this->timeout,
			);
			curl_setopt_array($curlHandle, $options);

				// Send an empty Expect header in order to avoid chunked data transfer (which we can't handle yet).
				// If we don't set this, cURL will set "Expect: 100-continue" for requests larger than 1024 bytes.
			curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array('Expect:'));

			switch ($request->getMethod()) {
				case 'GET' :
					if ($request->getContent()) {
							// workaround because else the request would implicitly fall into POST:
						curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, 'GET');
						curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $request->getContent());
					}
				break;
				case 'POST' :
					curl_setopt($curlHandle, CURLOPT_POST, TRUE);

					$body = $request->getContent() !== '' ? $request->getContent() : http_build_query($request->getArguments());
					curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $body);
				break;
				case 'PUT' :
					curl_setopt($curlHandle, CURLOPT_PUT, TRUE);
					if ($request->getContent() !== '') {
						$inFileHandler = fopen('php://temp', 'r+');
						fwrite($inFileHandler, $request->getContent());
						rewind($inFileHandler);
						curl_setopt_array($curlHandle, array(
							CURLOPT_INFILE => $inFileHandler,
							CURLOPT_INFILESIZE => strlen($request->getContent()),
						));
					}
				break;
				default:
					curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, $request->getMethod());
			}

			$preparedHeaders = array();
			foreach ($request->getHeaders()->getAll() as $fieldName => $values) {
				foreach ($values as $value) {
					$preparedHeaders[] = $fieldName . ': ' . $value;
				}
			}
			curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $preparedHeaders);

			if ($requestUri->getPort() !== NULL) {
				curl_setopt($curlHandle, CURLOPT_PORT, $requestUri->getPort());
			}

			$curlHandles[$index] = $curlHandle;

			curl_multi_add_handle($multiCurl, $curlHandle);
		}

		$active = 0;
		// execute handles
		do {
			$mrc = curl_multi_exec($multiCurl, $active);
		} while ($mrc === CURLM_CALL_MULTI_PERFORM);

		while ($active && $mrc === CURLM_OK) {
			if (curl_multi_select($multiCurl) !== -1) {
				do {
					$mrc = curl_multi_exec($multiCurl, $active);
				} while ($mrc === CURLM_CALL_MULTI_PERFORM);
			}
		}

		$responses = array();
		foreach ($curlHandles as $index => $curlHandle) {
			$error = curl_error($curlHandle);
			if ($error !== '') {
				$responses[$index] = new CurlEngineException('cURL reported error code ' . curl_errno($curlHandle) . ' with message "' . curl_error($curlHandle) . '". Last requested URL was "' . curl_getinfo($curlHandle, CURLINFO_EFFECTIVE_URL) . '".', 1355496033);
			} else {
				$curlResult = curl_multi_getcontent($curlHandle);
				$response = Response::createFromRaw($curlResult);
				if ($response->getStatusCode() === 100) {
					$response = Response::createFromRaw($response->getContent(), $response);
				}
				$responses[$index] = $response;
			}
			curl_multi_remove_handle($multiCurl, $curlHandle);
		}

		curl_multi_close($multiCurl);

		return $responses;
	}
1261126
protected function getBatchRequestOptions(array $requests)
    {
        return array_map(function (RequestInterface $request) {
            return JsonRpc\json_decode((string) $request->getBody());
        }, $requests);
    }
1069697
public function execute($requestParams = array()){

        $this->getQueryBuilder()->setValues($requestParams);
        
        $query = $this->getQueryBuilder()->getQuery($this->entity, QueryBuilder::SAVE_QUERY, QueryBuilder::PARENT_ONLY);

        $this->beginTransaction();
        try{
            //first save into the parent table 
            $result = $this->query("$query", FALSE);
           
            if(intval($result) > 0) {
                 
                $requestParams['id'] = $result;               
                $this->saveI18nValues($result,  $requestParams, $requestParams['locale']);
                $this->saveChildTableParams($result, $requestParams);
                $this->saveOneToManyJoins($result, $requestParams);
            }elseif(array_key_exists('id', $requestParams) && intval($requestParams['id']) > 0){      
          
                if(array_key_exists('locale', $requestParams)) {
                    $this->saveI18nValues($requestParams['id'], $requestParams, $requestParams['locale']); 
                }
       
                $this->saveChildTableParams($requestParams['id'],  $requestParams);
                $this->saveOneToManyJoins($requestParams['id'],  $requestParams);
                
            }   
            $this->saveMultiRowValues($requestParams);
      
            $this->commitTransaction();
        }catch(Exception $e){
          
            error_log($e->getMessage());
            $this->rollbackTransaction();
        }
        if(array_key_exists('locale', $requestParams)) {
            $requestParams['locale'] = $this->parseJson($requestParams['locale']);
        }
      
        return array(get_class($this->entity) => $requestParams);
    }
1098718
private function setRequestHeaders($headers = array()) {
        foreach ($this->headers as $key => $value) {
            $headers[] = $key . ': ' . $value;
        }
        curl_setopt($this->request, CURLOPT_HTTPHEADER, $headers);
    }
1039277
public function execute(array $clients) {
        if ($clients) {
            $mh      = curl_multi_init();
            $handles = [];
            /**@var \wulaphp\restful\RESTFulClient $client */
            foreach ($clients as $i => $client) {
                $ch             = $client->curl;
                $handles [ $i ] = ['h' => $ch, 'c' => $client];
                curl_multi_add_handle($mh, $ch);
            }
            $active = null;
            do {
                curl_multi_exec($mh, $active);
                if ($active > 0) {
                    usleep(50);
                }
            } while ($active > 0);
            $rsts = [];
            foreach ($handles as $i => $h) {
                /**@var \wulaphp\restful\RESTFulClient $client */
                $client      = $h ['c'];
                $rsts [ $i ] = $client->getReturn(curl_multi_getcontent($client->curl));
                curl_multi_remove_handle($mh, $h ['h']);
            }
            curl_multi_close($mh);

            return $rsts;
        }

        return [];
    }
1263782
protected function perform()
    {
        if (!$this->requests) {
            return;
        }

        // Initialize the handles with a very quick select timeout
        $active = $mrc = null;
        $this->executeHandles($active, $mrc, 0.001);
        $event = new Event(array('curl_multi' => $this));
        $this->processMessages();

        while ($this->requests) {

            // Notify each request as polling
            $blocking = $total = 0;
            foreach ($this->requests as $request) {
                ++$total;
                $event['request'] = $request;
                $request->getEventDispatcher()->dispatch(self::POLLING_REQUEST, $event);
                // The blocking variable just has to be non-falsey to block the loop
                if ($request->getParams()->hasKey(self::BLOCKING)) {
                    ++$blocking;
                }
            }

            if ($blocking == $total) {
                // Sleep to prevent eating CPU because no requests are actually pending a select call
                usleep(500);
            } else {
                do {
                    $this->executeHandles($active, $mrc, 1);
                } while ($active);
            }
            $this->processMessages();
        }
    }
618021
public function waitForSingleRequest(Request $request)
    {
        $this->executeRequest($request);
        while ($this->multiCurl->getStillRunningRequests() > 0
            && $this->multiCurl->getCurrentExecutionCode() === CURLM_OK
            && in_array($request, $this->runningRequests)
        ) {
            $this->multiCurl->select();
            $this->executeMultiCurl();
        }
        return $this;
    }
335172
def execute(self, requests, resp_generator, *args, **kwargs):
        '''
            
        '''
        return [resp_generator(request) for request in requests]
18593
public function execute($request): void
    {
        RequestNotSupportedException::assertSupports($this, $request);

        /** @var SyliusPaymentInterface $payment */
        $payment = $request->getModel();

        /** @var OrderInterface $order */
        $order = $payment->getOrder();

        $this->gateway->execute($status = new GetStatus($payment));
        if ($status->isNew()) {
            try {
                $this->gateway->execute($convert = new Convert($payment, 'array', $request->getToken()));
                $payment->setDetails($convert->getResult());
            } catch (RequestNotSupportedException $e) {
                $totalAmount = $order->getTotal();
                $payumPayment = new PayumPayment();
                $payumPayment->setNumber($order->getNumber());
                $payumPayment->setTotalAmount($totalAmount);
                $payumPayment->setCurrencyCode($order->getCurrencyCode());
                $payumPayment->setClientEmail($order->getCustomer()->getEmail());
                $payumPayment->setClientId($order->getCustomer()->getId());
                $payumPayment->setDescription($this->paymentDescriptionProvider->getPaymentDescription($payment));
                $payumPayment->setDetails($payment->getDetails());

                $this->gateway->execute($convert = new Convert($payumPayment, 'array', $request->getToken()));
                $payment->setDetails($convert->getResult());
            }
        }

        $details = ArrayObject::ensureArrayObject($payment->getDetails());

        try {
            $request->setModel($details);
            $this->gateway->execute($request);
        } finally {
            $payment->setDetails((array) $details);
        }
    }
354042
protected function executeMultiCurl()
    {
        do {
            $this->multiCurl->execute();
            $this->checkStatusMessages();
        } while ($this->multiCurl->getCurrentExecutionCode() === CURLM_CALL_MULTI_PERFORM);
        return $this;
    }
372018
private function exec(array $curlOptions, array $requestHeaders)
    {
        // make sure we always start with a clean slate, we do this here
        // and not after curl_exec because when calling CurlHttpClient::exec
        // again after a caught exception may result in unexpected weirdness
        $this->curlReset();

        $defaultCurlOptions = [
            CURLOPT_HEADER => false,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_PROTOCOLS => $this->allowHttp ? CURLPROTO_HTTPS | CURLPROTO_HTTP : CURLPROTO_HTTPS,
            CURLOPT_SSL_VERIFYHOST => 2,    // default, but just to make sure
            CURLOPT_SSL_VERIFYPEER => true, // default, but just to make sure
            CURLOPT_HEADERFUNCTION => [$this, 'responseHeaderFunction'],
        ];

        if (0 !== \count($requestHeaders)) {
            $curlRequestHeaders = [];
            foreach ($requestHeaders as $k => $v) {
                $curlRequestHeaders[] = \sprintf('%s: %s', $k, $v);
            }
            $defaultCurlOptions[CURLOPT_HTTPHEADER] = $curlRequestHeaders;
        }

        if (false === \curl_setopt_array($this->curlChannel, $curlOptions + $defaultCurlOptions)) {
            throw new CurlException('unable to set cURL options');
        }

        $responseData = \curl_exec($this->curlChannel);
        if (false === \is_string($responseData)) {
            // curl_exec returns true/false when CURLOPT_RETURNTRANSFER is not
            // set, but false|string when CURLOPT_RETURNTRANSFER _IS_ set, but
            // Psalm is not clever enough to distinguish this, so if the
            // response is NOT a string it MUST be false
            throw new CurlException(
                \sprintf(
                    '[%d] %s',
                    \curl_errno($this->curlChannel),
                    \curl_error($this->curlChannel)
                )
            );
        }

        return new Response(
            \curl_getinfo($this->curlChannel, CURLINFO_HTTP_CODE),
            $responseData,
            $this->responseHeaderList
        );
    }
1121781
protected function performFullRequest( $urls ) {
		// Create multiple curl handle
		$multicurl_resource = curl_multi_init();
		if ( $multicurl_resource === false ) {
			return false;
		}
		$curl_instances = [];
		$deadlinks = [];
		foreach ( $urls as $id => $url ) {
			$curl_instances[$id] = curl_init();
			if ( $curl_instances[$id] === false ) {
				return false;
			}
			// Get appropriate curl options
			curl_setopt_array(
				$curl_instances[$id],
				$this->getCurlOptions( $this->sanitizeURL( $url, false, true ), true )
			);
			// Add the instance handle
			curl_multi_add_handle( $multicurl_resource, $curl_instances[$id] );
		}
		// Let's do the CURL operations
		$active = null;
		do {
			$mrc = curl_multi_exec( $multicurl_resource, $active );
		} while ( $mrc == CURLM_CALL_MULTI_PERFORM );
		while ( $active && $mrc == CURLM_OK ) {
			if ( curl_multi_select( $multicurl_resource ) == -1 ) {
				// To prevent CPU spike
				usleep( 100 );
			}
			do {
				$mrc = curl_multi_exec( $multicurl_resource, $active );
			} while ( $mrc == CURLM_CALL_MULTI_PERFORM );
		}
		// Let's process our curl results and extract the useful information
		foreach ( $urls as $id => $url ) {
			$headers = curl_getinfo( $curl_instances[$id] );
			$error = curl_errno( $curl_instances[$id] );
			$errormsg = curl_error( $curl_instances[$id] );
			$curlInfo = [
				'http_code' => $headers['http_code'],
				'effective_url' => $headers['url'],
				'curl_error' => $error,
				'curl_error_msg' => $errormsg,
				'url' => $this->sanitizeURL( $url, false, true ),
				'rawurl' => $url
			];
			// Remove each of the individual handles
			curl_multi_remove_handle( $multicurl_resource, $curl_instances[$id] );
			$deadlinks[$url] = $this->processCurlResults( $curlInfo, true );
		}
		// Close resource
		curl_multi_close( $multicurl_resource );

		return $deadlinks;
	}