Register a StreamWrapper for reading and writing to Google Storage

@param StorageClient $client The StorageClient configuration to use.
@param string $protocol The name of the protocol to use. **Defaults to**
`gs`.
@throws \RuntimeException
173287
public static function register(StorageClient $client, $protocol = null)
    {
        $protocol = $protocol ?: self::DEFAULT_PROTOCOL;
        if (!in_array($protocol, stream_get_wrappers())) {
            if (!stream_wrapper_register($protocol, StreamWrapper::class, STREAM_IS_URL)) {
                throw new \RuntimeException("Failed to register '$protocol://' protocol");
            }
            self::$clients[$protocol] = $client;
            return true;
        }
        return false;
    }
303264
public function createHttpClient($name = '', $client = null)
    {
        if (empty($name)) {
            return $this->createBestClient();
        }

        if (!isset($this->classes[$name])) {
            throw new \InvalidArgumentException(sprintf('The client "%s" is not registered.', $name));
        }

        $class = $this->classes[$name]['class'];
        $client = new $class($this->dispatcher, $this->options, $client);

        if ($client instanceof AbstractHttpClient) {
            return $client;
        }

        throw new \InvalidArgumentException('The client must be an implementation of ClientInterface.');
    }
1318288
public static function buildClient($client, array $configuration = [], array $constructorArguments = [])
    {
        // If client argument is a string, use autoloader to class from Buzz ns
        if (is_string($client)) {
            $possibleClass = '\\Buzz\\Client\\' . $client;
            if (!class_exists($possibleClass)) {
                throw new Exception("HTTP transporter class \"$possibleClass\" cannot be found!");
            }

            $reflClass = new \ReflectionClass($possibleClass);
            $client = $reflClass->newInstanceArgs($constructorArguments);
        }

        if (!$client instanceof ClientInterface) {
            throw new Exception('Client must be implement \\Buzz\\Client\\ClientInterface interface!');
        }

        // Well, we have valid client, just need to configure it at this point
        self::configureClient($client, $configuration);

        return $client;
    }
405729
private function addScopeAndRedirectUris(Client $client): void
    {
        $client->setScopeIdentifiers($this->readScopeIdentifiers($client->getIdentifier()));
        $client->setRedirectUriStrings($this->readRedirectUriStrings($client->getIdentifier()));
    }
249882
private function buildStreamContextOptions(ApiClient $apiClient, HttpRequest $request) {
		$options = array(
			'http' => array(),
			'ssl' => array()
		);
		if ($request->isSecureConnection()) {
			$options['ssl']['verify_host'] = true;
			$options['ssl']['allow_self_signed'] = false;
			$options['ssl']['verify_peer'] = false;

			if ($apiClient->isCertificateAuthorityCheckEnabled()) {
				$options['ssl']['verify_peer'] = true;
				$options['ssl']['cafile'] = $apiClient->getCertificateAuthority();
			}
		}
		$ipVersion = $this->readEnvironmentVariable(self::ENVIRONMENT_VARIABLE_IP_ADDRESS_VERSION);
		if ($ipVersion !== null) {
			if ($ipVersion == self::IP_ADDRESS_VERSION_V4) {
				$options['socket'] = array(
					'bindto' => '0.0.0.0:0'
				);
			} elseif ($ipVersion == self::IP_ADDRESS_VERSION_V6) {
				$options['socket'] = array(
					'bindto' => '[::]:0'
				);
			}
		}
		return $options;
	}
511066
private function createSocketStream(ApiClient $apiClient, HttpRequest $request) {
		if ($request->isSecureConnection()) {
			if (!extension_loaded('openssl')) {
				throw new \Exception("You have to enable OpenSSL.");
			}
		}

		$proxyUrl = $this->readEnvironmentVariable(self::ENVIRONMENT_VARIABLE_PROXY_URL);
		if ($proxyUrl !== null) {
			$host = parse_url($proxyUrl, PHP_URL_HOST);
			$port = parse_url($proxyUrl, PHP_URL_PORT);
			if(empty($port)) {
				throw new ConnectionException($request->getUrl(), $request->getLogToken(), "The Proxy URL must contain a port number.");
			}
			
		} else {
			$host = ($request->isSecureConnection() ? $this->getSslProtocol() . '://' : '') . $request->getHost();
			$port = $request->getPort();
			if(empty($port)) {
				$port = $request->isSecureConnection() ? 443 : 80;
			}	
		}			
		$socket = $host . ':' . $port;

		$filePointer = @stream_socket_client($socket, $errno, $errstr, $apiClient->getConnectionTimeout(), STREAM_CLIENT_CONNECT,
				$this->createStreamContext($apiClient, $request));

		if ($filePointer === false) {
			throw new ConnectionException($request->getUrl(), $request->getLogToken(), $errstr);
		}

		if (!(get_resource_type($filePointer) == 'stream')) {
			$errorMessage = 'Could not connect to the server. The returned socket was not a stream.';
			throw new ConnectionException($request->getUrl(), $request->getLogToken(), $errorMessage);
		}

		return $filePointer;
	}
689602
protected function generateClient(FileGenerator $file, ClientGenerator $generator, Client $client, $path)
    {
        $code = $generator->generate($file, $client);
        $this->filesystem->putFileContents($path, $code);
    }
1182475
function giveClient(\Predis\Client $client)
    {
        if ($this->client)
            throw new exImmutable;

        $this->client = $client;
        return $this;
    }
503790
public function create(DynamoDbClient $client, string $tableName): void
    {
        try {
            $client->describeTable(['TableName' => $tableName]);
            return;
        } catch (DynamoDbException $e) {
            // table doesn't exist, create it below
        }

        try {
            $client->createTable([
                'TableName'              => $tableName,
                'AttributeDefinitions'   => [
                    ['AttributeName' => self::HASH_KEY_NAME, 'AttributeType' => 'S'],
                    ['AttributeName' => self::RANGE_KEY_NAME, 'AttributeType' => 'N'],
                    ['AttributeName' => self::GSI_EVENT_ID_HASH_KEY_NAME, 'AttributeType' => 'S'],
                ],
                'KeySchema'              => [
                    ['AttributeName' => self::HASH_KEY_NAME, 'KeyType' => 'HASH'],
                    ['AttributeName' => self::RANGE_KEY_NAME, 'KeyType' => 'RANGE'],
                ],
                'GlobalSecondaryIndexes' => [
                    [
                        'IndexName'             => self::GSI_EVENT_ID_NAME,
                        'KeySchema'             => [
                            ['AttributeName' => self::GSI_EVENT_ID_HASH_KEY_NAME, 'KeyType' => 'HASH'],
                        ],
                        'Projection'            => [
                            'ProjectionType' => 'KEYS_ONLY',
                        ],
                        'ProvisionedThroughput' => [
                            'ReadCapacityUnits'  => 2,
                            'WriteCapacityUnits' => 2,
                        ],
                    ],
                ],
                'StreamSpecification'    => [
                    'StreamEnabled'  => true,
                    'StreamViewType' => 'NEW_IMAGE',
                ],
                'ProvisionedThroughput'  => [
                    'ReadCapacityUnits'  => 2,
                    'WriteCapacityUnits' => 2,
                ],
            ]);

            $client->waitUntil('TableExists', ['TableName' => $tableName]);
        } catch (\Throwable $e) {
            throw new EventStoreOperationFailed(
                sprintf(
                    '%s::Unable to create table [%s] in region [%s].',
                    ClassUtils::getShortName($this),
                    $tableName,
                    $client->getRegion()
                ),
                Code::INTERNAL,
                $e
            );
        }
    }
1140628
public function clientRequest(Client $client, ExecuteRequest $msg)
    {
        $requestId = $msg->getRequestId();
        if (!$requestId) {
            // No requestId given, generate a unique one.
            do {
                $requestId = sha1(uniqid());
            } while (isset($this->request[$requestId]));
        }

        if ($this->storage->has($requestId)) {
            $this->getLogger()->info(
                sprintf(
                    'Client %s wants to execute request %s. '.
                    'Since there already is a result for that request, '.
                    'it will be sent back immediately.',
                    bin2hex($client->getId()),
                    $requestId
                )
            );

            $this->reply(
                $client,
                new ExecuteResponse(
                    $requestId,
                    $this->storage->get($requestId)
                )
            );

            return;
        }

        // The Client always needs to receive this
        // response, so just send it right away.
        $this->reply($client, new ExecuteResponse($requestId));

        // Now actually handle the message.
        $request = $this->getRequest($requestId);

        if ($request) {
            $this->getLogger()->info(
                sprintf(
                    'Client %s wants to execute already known request %s.',
                    bin2hex($client->getId()),
                    $requestId
                )
            );

            return;
        }

        $action = $msg->getAction();
        $params = $msg->getParams();

        $this->getLogger()->info(
            sprintf(
                'New request %s from client %s for action %s',
                $requestId,
                bin2hex($client->getId()),
                $action
            )
        );

        $this->addRequest(new Request($requestId, $action, $params));

        if (!$this->storage->has($requestId)) {
            $this->addWorkerQueue($requestId);
        }
    }
1129876
protected function broadcastToClients(\SplObjectStorage $clients)
    {
        foreach ($clients as $client) {
            $client->sendString($this->processOutput());
        }
    }
1262632
protected function registerClientSubscribers(ClientInterface $client)
    {
        $client->on('irc.received', function ($message, $write, $connection) {
            $this->processClientEvent('irc.received', $message, $connection, $write);
        });

        $client->on('irc.sent', function ($message, $write, $connection) {
            $parsed = $this->getParser()->parse($message);
            if (!$parsed) {
                return;
            }
            $this->processClientEvent('irc.sent', $parsed, $connection, $write);
        });

        $client->on('irc.tick', function ($write, $connection) {
            $this->processOutgoingEvents($connection, $write);
        });
    }
596007
protected function createClient($client)
    {
        try {
            new \ReflectionClass($client);
        } catch (\ReflectionException $e) {
            throw new FoundationException(sprintf("Could not load class '%s'.", $client), null, $e);
        }

        $client_instance = new $client();

        return $client_instance;
    }
480987
static function register(iWrapperStream $wrapper, $label = null)
    {
        if ($label == null)
            $label = $wrapper->getLabel();

        if ($pos = strpos($label, ':') !== false)
            throw new \Exception(sprintf(
                '(%s) Is Invalid Label Provided For Stream Wrapper.'
                . ' It must include just a name like "http".'
                , $label
            ));

        stream_wrapper_register($label, get_class($wrapper));

        // Set the default stream context which will be used whenever
        // file operations (fopen(), file_get_contents(), etc...) are
        // called without a context parameter.
        $options = array(
            $label => \Poirot\Std\cast($wrapper->optsData())->toArray()
        );

        stream_context_set_default($options);
    }
1222250
public function addClient($client, RequestMatcher $requestMatcher): void
    {
        $this->clients[] = [
            'matcher' => $requestMatcher,
            'client' => new FlexibleHttpClient($client),
        ];
    }
784885
private static function &getStorage(ServerRequestInterface $request, $key = null)
    {
        if (!self::hasAttribute($request, Middleware::STORAGE_KEY)) {
            throw new RuntimeException('No session storage initialized');
        }

        $storage = self::getAttribute($request, Middleware::STORAGE_KEY);

        if (!isset($storage->$key)) {
            $storage->$key = [];
        }

        return $storage->$key;
    }
67667
public static function init(Client $client, &$request)
    {
        // Verification for required parameters
        $config = $client->getConfig();
        if (empty($config['public_key']) || empty($config['private_key'])) {
            throw new InvalidKeysHmacException('Both, public and private key are required for hmac authentication');
        }

        // Data to process
        switch ($request->getMethod()) {
            case 'POST':
                $data = count($request->getBody()->getFields()) ? json_encode($request->getBody()->getFields()) : null;
                break;
            case 'GET' :
                $data = count($request->getQuery()) ? json_encode((string)$request->getQuery()) : null;
                break;
            case 'PUT' :
                $data = $request->getBody()->getContents();
                break;
            case 'DELETE':
                $data = $request->getQuery();
                break;
        }

        // Setting the credentials
        $request->setHeaders([
            'X-PUBLIC-KEY' => $config['public_key'],
            'X-SIGNATURE' => base64_encode(hash_hmac('sha256', $data, $config['private_key'])),
            'X-NONCE' => time(),
        ]);
    }