处理Guzzle代码

@return void
6205
protected function parseGuzzle()
    {
        $filePath = dirname(__DIR__) . '/load.php';
        $config = $this->composer->getConfig();

        $filesystem = new Filesystem();
        $filesystem->ensureDirectoryExists($config->get('vendor-dir'));
        $vendorPath = $filesystem->normalizePath(realpath(realpath($config->get('vendor-dir'))));
        $autoloadFilesFile = $vendorPath.'/composer/autoload_files.php';

        $files = include $autoloadFilesFile;
        
        foreach($files as $fileName)
        {
            if($this->stringEndwith($fileName, '/guzzlehttp/guzzle/src/functions_include.php'))
            {
                $path = dirname($fileName) . '/functions.php';
                include $path;
                $refFunction = new \ReflectionFunction('GuzzleHttp\choose_handler');
                $content = file_get_contents($path);
                $eol = $this->getEOL($content);
                $contents = explode($eol, $content);
                for($i = $refFunction->getStartLine() - 1; $i < $refFunction->getEndLine(); ++$i)
                {
                    unset($contents[$i]);
                }
                $content = implode($eol, $contents);
                file_put_contents($filePath, $content);
                break;
            }
        }
    }
1346033
protected function makeMainClient()
	{
		$this->mainClientData['uses'] = [
			'GuzzleHttp\Client as GuzzleClient'
		];
		$this->mainClientData['managers'] = [];
		$this->mainClientData['className'] = 'ApiClient';
		$this->mainClientData['classPhpDocTitle'] = $this->openApiFileContent['info']['title'] . ' client class';
		$this->mainClientData['classPhpDocTitle'] .= $this->openApiFileContent['info']['version'] ? (' (version ' . $this->openApiFileContent['info']['version'] . ')') : '';
		$this->mainClientData['namespace'] = $this->namespace;

		$this->mainClientData['info'] = $this->openApiFileContent['info'];

		$firstKey = array_keys($this->openApiFileContent['servers'])[0];
		$this->mainClientData['apiBaseUrl'] = $this->openApiFileContent['servers'][$firstKey]['url'];

		// Security
		// @todo Not only OAuth support
		// @todo Scopes support ?
		$this->mainClientData['useBearerToken'] = false;
		if (isset($this->openApiFileContent['security'])) {
			foreach ($this->openApiFileContent['security'] as $s) {
				foreach ($s as $securityRequirement => $scope) {
					// Ignoring scopes...
					if (!isset($this->mainClientData['security'])) {
						$this->mainClientData['security'] = [];
					}
					$this->mainClientData['security'][$securityRequirement] = $this->openApiFileContent['components']['securitySchemes'][$securityRequirement];

					if ($this->openApiFileContent['components']['securitySchemes'][$securityRequirement]['type'] == 'http') {
						if ($this->openApiFileContent['components']['securitySchemes'][$securityRequirement]['scheme'] == 'bearer') {
							$this->mainClientData['useBearerToken'] = true;
						}
					}

					if ($this->openApiFileContent['components']['securitySchemes'][$securityRequirement]['type'] == 'oauth2') {
						$this->mainClientData['useBearerToken'] = true;
					}
				}
			}
		}

		// Add extra Guzzle classes in uses
		if ($this->mainClientData['useBearerToken']) {
			$this->mainClientData['uses'][] = 'Psr\Http\Message\RequestInterface';
			$this->mainClientData['uses'][] = 'GuzzleHttp\HandlerStack';
			$this->mainClientData['uses'][] = 'GuzzleHttp\Handler\CurlHandler';
			$this->mainClientData['uses'][] = 'GuzzleHttp\Middleware';
		}

		foreach ($this->managersData as $managerName => $managerData) {
			$this->mainClientData['uses'][] = $this->namespace . '\\Managers\\' . $managerName . 'Manager';
			$this->mainClientData['managers'][$managerName] = [
				'name' => $managerName,
				'className' => $managerName . 'Manager',
				'lowerCamelCaseClassName' => lcfirst($managerName . 'Manager')
			];
		}
	}
554286
public function render()
    {
        parent::render();

        $oLang = \OxidEsales\Eshop\Core\Registry::getLang();

        // remove itm from list
        unset($this->_aViewData["sumtype"][2]);

        // Deliverytypes
        $aDelTypes = $this->getDeliveryTypes();

        $soxId = $this->_aViewData["oxid"] = $this->getEditObjectId();
        if (isset($soxId) && $soxId != "-1") {
            // load object
            $oDelivery = oxNew(\OxidEsales\Eshop\Application\Model\Delivery::class);
            $oDelivery->loadInLang($this->_iEditLang, $soxId);

            $oOtherLang = $oDelivery->getAvailableInLangs();
            if (!isset($oOtherLang[$this->_iEditLang])) {
                // echo "language entry doesn't exist! using: ".key($oOtherLang);
                $oDelivery->loadInLang(key($oOtherLang), $soxId);
            }

            $this->_aViewData["edit"] = $oDelivery;

            //Disable editing for derived articles
            if ($oDelivery->isDerived()) {
                $this->_aViewData['readonly'] = true;
            }

            // remove already created languages
            $aLang = array_diff($oLang->getLanguageNames(), $oOtherLang);
            if (count($aLang)) {
                $this->_aViewData["posslang"] = $aLang;
            }

            foreach ($oOtherLang as $id => $language) {
                $oLang = new stdClass();
                $oLang->sLangDesc = $language;
                $oLang->selected = ($id == $this->_iEditLang);
                $this->_aViewData["otherlang"][$id] = clone $oLang;
            }

            // set selected delivery type
            if (!$oDelivery->oxdelivery__oxdeltype->value) {
                $oDelivery->oxdelivery__oxdeltype = new \OxidEsales\Eshop\Core\Field("a"); // default
            }
            $aDelTypes[$oDelivery->oxdelivery__oxdeltype->value]->selected = true;
        }

        $this->_aViewData["deltypes"] = $aDelTypes;

        if (\OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("aoc")) {
            $oDeliveryMainAjax = oxNew(\OxidEsales\Eshop\Application\Controller\Admin\DeliveryMainAjax::class);
            $this->_aViewData['oxajax'] = $oDeliveryMainAjax->getColumns();

            return "popups/delivery_main.tpl";
        }

        return "delivery_main.tpl";
    }
200641
function cod() {
      global $order;

      $this->code = 'cod';
      $this->title = MODULE_PAYMENT_COD_TEXT_TITLE;
      $this->description = MODULE_PAYMENT_COD_TEXT_DESCRIPTION;
      $this->sort_order = MODULE_PAYMENT_COD_SORT_ORDER;
      $this->enabled = ((MODULE_PAYMENT_COD_STATUS == 'True') ? true : false);

      if ((int)MODULE_PAYMENT_COD_ORDER_STATUS_ID > 0) {
        $this->order_status = MODULE_PAYMENT_COD_ORDER_STATUS_ID;
      }

      if (is_object($order)) $this->update_status();
    }
630311
public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/config/config.php', 'requester');

        $this->app['requester'] = $this->app->share(function ($app) {
            return new Requester(new GuzzleClient(), config('requester'));
        });
    }
1072462
public function register(App $app)
    {
        if (isset($app["guzzle.service"]) === false) {
            $app["guzzleClient.service"] = function() {
                return new \GuzzleHttp\Client;
            };
        }

        /*
         * This is only a temporary service definition to satisfy the install component
         * command and to load the service provider into it through the new params
         * as services method.
         *
         * @todo: remove when the component commands are refactored
         */
        $app["serviceProvider.service"] = function(App $app) {
            return $app;
        };

        $app["slaxerCommands"] = array_merge(
            $app["slaxerCommands"] ?? [],
            [
                \SlaxWeb\Bootstrap\Commands\Component\InstallCommand::class => [
                    "serviceProvider.service",
                    "guzzleClient.service"
                ]
            ]
        );
    }
64955
final protected function _execute() {
		$s = df_customer_session(); /** @var Session|DfSession $s */
		if (!$this->mc()) {
			/**
			 * 2016-12-01
			 * Учётная запись покупателя отсутствует в Magento,
			 * и в то же время информации провайдера SSO недостаточно
			 * для автоматической регистрации покупателя в Magento
			 * (случай Blackbaud NetCommunity).
			 * Перенаправляем покупателя на стандартную страницу регистрации Magento,
			 * где часть полей будет уже заполнена данными от провайдера SSO,
			 * а пароль будет либо скрытым, либо необязательным полем.
			 * После регистрации свежесозданная учётная запись будет привязана
			 * к учётной записи покупателя в провайдере SSO.
			 */
			$this->_redirectToRegistration = true;
			$s->setDfSsoId($this->c()->id());
			$s->setDfSsoRegistrationData($this->registrationData());
			$s->setDfSsoProvider(df_module_name($this));
			$settings = dfs($this); /** @var Settings $settings */
			df_message_success($settings->regCompletionMessage());
		}
		else {
			/**
			 * 2015-10-08
			 * By analogy with @see \Magento\Customer\Controller\Account\LoginPost::execute()
			 * https://github.com/magento/magento2/blob/1.0.0-beta4/app/code/Magento/Customer/Controller/Account/LoginPost.php#L84-L85
			 */
			$s->setCustomerDataAsLoggedIn($this->mc()->getDataModel());
			$s->regenerateId();
			/**
			 * By analogy with @see \Magento\Customer\Model\Account\Redirect::updateLastCustomerId()
			 * Напрямую тот метод вызвать не можем, потому что он protected,
			 * а использовать весь класс @see \Magento\Customer\Model\Account\Redirect пробовал,
			 * но оказалось неудобно из-за слишком сложной процедуры перенаправлений.
			 */
			if ($s->getLastCustomerId() != $s->getId()) {
				$s->unsBeforeAuthUrl()->setLastCustomerId($s->getId());
			}
		}
	}
745037
public function run()
    {
        // todo: think of a better way of doing this.
        $script = "jQuery('{$this->selector}').attr('data-spy', 'scroll');";
        if (isset($this->target)) {
            $script .= "jQuery('{$this->selector}').attr('data-target', '{$this->target}');";
        }
        if (isset($this->offset)) {
            $script .= "jQuery('{$this->selector}').attr('data-offset', '{$this->offset}');";
        }
        Yii::app()->clientScript->registerScript($this->getId(), $script, CClientScript::POS_BEGIN);
        $this->registerEvents($this->selector, $this->events);
    }
1298248
public function getGuzzleClient()
    {
        $guzzle = $this->guzzleClient;

        if ($this->retry) {
            $guzzle = $this->addRetrySubscriber($guzzle);
        }

        return $guzzle;
    }
379750
public function register()
    {
        $this->container['cache.manager'] = function ($container) {
            $config = $container['config']->get('cache');

            $manager = new Manager($config->drivers->toArray());

            // 设置默认缓存驱动
            $manager->setDefault($config->default);

            // 设置日志处理器
            $logger = value($config->logger);
            if ($logger instanceof LoggerInterface) {
                $manager->setLogger($logger);
            }

            return $manager;
        };

        $this->container['cache'] = function ($container) {
            return $container['cache.manager']->getDefaultCache();
        };

        $this->container['cache.simple'] = function ($container) {
            return $container['cache.manager']->getDefaultSimpleCache();
        };
    }
87957
public function pour(): void
    {
        $provider = $this->source->getCask();
        foreach ($provider as $dataBag) {
            try {
                $this->pipeLine->rewind();
                while ($this->pipeLine->valid()) {
                    $handler = $this->pipeLine->current();
                    $dataBag = $handler->pass($dataBag);
                    $this->pipeLine->next();
                }
            } catch (FlowTerminationException $exception) {
                $this->emitter->emit('valve_closed', $exception->getIdentifier(), $dataBag);
            }
        }
        $this->emitter->emit('empty_cask');
    }
1028901
public function run()
	{
		$context = $this->getContext();
		$config = $context->getConfig();

		/** controller/jobs/order/email/voucher/standard/limit-days
		 * Only send voucher e-mails of orders that were created in the past within the configured number of days
		 *
		 * The voucher e-mails are normally send immediately after the voucher
		 * has been ordered. This option prevents e-mails for old orders from
		 * being send in case anything went wrong or an update failed to avoid
		 * confusion of customers.
		 *
		 * @param integer Number of days
		 * @since 2018.07
		 * @category User
		 * @category Developer
		 * @see controller/jobs/order/email/voucher/standard/status
		 */
		$limit = $config->get( 'controller/jobs/order/email/voucher/standard/limit-days', 30 );
		$limitDate = date( 'Y-m-d H:i:s', time() - $limit * 86400 );

		$default = array(
			\Aimeos\MShop\Order\Item\Base::PAY_AUTHORIZED,
			\Aimeos\MShop\Order\Item\Base::PAY_RECEIVED,
		);

		/** controller/jobs/order/email/voucher/standard/status
		 * Only send e-mails containing voucher for these payment status values
		 *
		 * E-mail containing vouchers can be sent for these payment status values:
		 * * 0: deleted
		 * * 1: canceled
		 * * 2: refused
		 * * 3: refund
		 * * 4: pending
		 * * 5: authorized
		 * * 6: received
		 *
		 * @param integer Payment status constant
		 * @since 2018.07
		 * @category User
		 * @category Developer
		 * @see controller/jobs/order/email/voucher/standard/limit-days
		 */
		$status = (array) $config->get( 'controller/jobs/order/email/voucher/standard/status', $default );


		$client = \Aimeos\Client\Html\Email\Voucher\Factory::create( $context );
		$orderManager = \Aimeos\MShop::create( $context, 'order' );

		$orderSearch = $orderManager->createSearch();

		$param = array( \Aimeos\MShop\Order\Item\Status\Base::EMAIL_VOUCHER, 1 );
		$orderFunc = $orderSearch->createFunction( 'order.containsStatus', $param );

		$expr = array(
			$orderSearch->compare( '>=', 'order.mtime', $limitDate ),
			$orderSearch->compare( '==', 'order.statuspayment', $status ),
			$orderSearch->compare( '==', 'order.base.product.type', 'voucher' ),
			$orderSearch->compare( '==', $orderFunc, 0 ),
		);
		$orderSearch->setConditions( $orderSearch->combine( '&&', $expr ) );

		$start = 0;

		do
		{
			$items = $orderManager->searchItems( $orderSearch );

			$this->process( $client, $items, 1 );

			$count = count( $items );
			$start += $count;
			$orderSearch->setSlice( $start );
		}
		while( $count >= $orderSearch->getSliceSize() );
	}
1286323
public function getHttpClient()
    {
        if (!isset($this->_httpClient)) {
            $this->_httpClient = Yii::createObject($this->guzzleClass, [$this->guzzleConfig]);
        }
        return $this->_httpClient;
    }
669657
public function run()
    {
        if ($this->is_route == true) {
            if ($this->segments instanceof \Closure) {
                echo call_user_func($this->segments);
                die();
            } else {
                $class = $this->getBundleUrl();
            }
        } else {
            $class = $this->getUnBundleUrl();

            if (!class_exists($class)) {

                $this->initDefaultRoute();

                $class = $this->getBundleUrl();
            }
        }

        if (!class_exists($class)) {
            $message = sprintf('No route found for "%s %s"', Zilf::$container['request']->getMethod(), Zilf::$container['request']->getPathInfo());

            if ($referer = Zilf::$container['request']->headers->get('referer')) {
                $message .= sprintf(' (from "%s")', $referer);
            }
            throw new NotFoundHttpException($message);
        }

        unset($this->segments);

        //将参数追加到GET里面
        if (!empty($this->params)) {
            foreach ($this->params as $key => $row) {
                if (is_string($key)) {
                    $_GET[$key] = $row;
                } else {
                    $_GET['zget' . $key] = $row;
                }
            }
            Zilf::$container->getShare('request')->query->add($_GET);
        }

        $object = Zilf::$container->build($class, []);
        if (method_exists($object, $this->action)) {

            $response = call_user_func_array(array($object, $this->action), $this->params);
            if (!$response instanceof Response) {
                $msg = sprintf('The controller must return a response (%s given).', $this->varToString($response));

                // the user may have forgotten to return something
                if (null === $response) {
                    $msg .= ' Did you forget to add a return statement somewhere in your controller?';
                }
                throw new \LogicException($msg);
            }
            $response->send();

        } else {
            throw new \Exception('类: ' . $class . ' 调用的方法：' . $this->action . ' 不存在！');
        }
    }
28128
protected function preprocessInsert()
    {
        /**
         * 合并设置项 data 和 values, 并解析为 field,values
         * $this->query['data'] = array(array('id'=>3, 'name'=>'ccccc'), array('id'=>3, 'name'=>'ccccc'))
         */
        if ( isset($this->query['data']) ) {
            if (!isset($this->query['values'])) {
                $this->query->setRaw('values', $this->query['data']);
            } else {
                $this->query->setRaw('values', array_merge($this->query['data'], $this->query['values']));
            }
        }
        if ($this->query['values']) {
            $set = $this->_parseDataItemToExtractValues($this->query['values']);
            if (count($set) > 0) {
                
                if (isset($set['fields'])) {
                    $this->query->remove('fields')->set('fields', $set['fields']);
                }
                
                $this->query->remove('values')->set('values', $set['values']);
            }
        }
    }
171926
public function make()
    {
        $guzzle = Client::makeGuzzle($this->endpoint);

        $client = new Client(new Config($this->key ?: ''), $this->resolver, $guzzle);

        if ($this->callbacks) {
            $client->registerDefaultCallbacks();
        }

        if ($this->tokens && $this->checker && $this->user) {
            $this->setupUserDetection($client, $this->tokens, $this->checker);
        }

        $this->setupPaths($client, $this->strip, $this->project, $this->root);

        $client->setReleaseStage($this->stage ?: ($this->env === 'prod' ? 'production' : $this->env));

        $client->setAppVersion($this->version);
        $client->setFallbackType('Console');
        $client->setAppType($this->type);

        $client->setBatchSending($this->batch);
        $client->setHostname($this->hostname);
        $client->setSendCode($this->code);

        $client->setNotifier(array_filter([
            'name' => 'Bugsnag Symfony',
            'version' => BugsnagBundle::VERSION,
            'url' => 'https://github.com/bugsnag/bugsnag-symfony',
        ]));

        if ($this->stages) {
            $client->setNotifyReleaseStages($this->stages);
        }

        if ($this->filters) {
            $client->setFilters($this->filters);
        }

        return $client;
    }
886530
protected function buildQueue()
    {
        // 清空队列
        $this->initQueue();
        // 重新建立队列
        foreach($this->pool as $item)
        {
            $this->queue->push($item->getResource());
        }
    }