Write data into firebase

@param mixed $data
@param string $method
@return array
15735
private function write($data, $method = 'PUT')
    {
        $jsonData = json_encode($data);
        $header = array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($jsonData)
        );
        try
        {
            $ch = $this->curl($method);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            $return = curl_exec($ch);
            curl_close($ch);
            return json_decode($return, true);
        } catch (Exception $e)
        {
            //...
        }
        return null;
    }
976815
public function makeRequest($method, $endpoint, array $data = [])
    {
        $response = $this->client->request($method, $endpoint, $data);

        return json_decode((string) $response->getBody());
    }
659617
private function createRequest($method, $resource, array $data = [])
    {
        if (!empty($data)) {
            $data['signature'] = $this->apiSignature;
        }

        return $this->requestFactory->createRequest($method, $resource, [], $this->encode($data));
    }
1256091
private function _buildRequestContent(&$parse, $method, $data) {
    $strLength = '';
    $content = '';

    if ($method == self::METHOD_GET) {
      $data = ltrim($data, '&');
      $query = isset($parse['query']) ? $parse['query'] : '';
      $parse['path'] .= ($query ? '&' : '?') . $data;
    } else {
      $method = self::METHOD_POST;
      $strLength = "Content-length: " . strlen($data) . "\r\n";
      $content = $data;
    }

    $write = $method . " " . $parse['path'] . " HTTP/1.0\r\n";
    $write .= "Host: " . $parse['host'] . "\r\n";
    $write .= "Content-type: application/x-www-form-urlencoded\r\n";
    $write .= "User-Agent: opensearch/php sdk ".$this->sdkVersion."\r\n";
    if ($this->gzip) {
      $write .= "Accept-Encoding: gzip\r\n";
    }
    $write .= $strLength;
    $write .= "Connection: close\r\n\r\n";
    $write .= $content;

    return $write;
  }
787910
protected function dumpMethod(Method $method)
    {
        $builder = new MethodBuilder();

        $documentation = $method->getDescription()."\n\n";
        $signature = array();

        foreach ($method->getParameters() as $parameter) {
            $builder->addParameter($parameter->getName());
            $documentation .= "@param string $".$parameter->getName()." ".$parameter->getDescription()."\n\n";
            $signature[] = '$'.$parameter->getName();
        }

        $signature = implode(', ', $signature);

        if ($method->isAction()) {
            $documentation .= '@return \Selenium\Browser Fluid interface';

            $body  = '$this->driver->action("'.$method->getName().'"'. ($signature ? ', '.$signature : '') . ');'."\n";
            $body .= "\n";
            $body .= "return \$this;";

        } else {
            $returnType = $method->getReturnType();

            if ($returnType === 'boolean') {
                $getMethod = 'getBoolean';
            } elseif ($returnType === 'string') {
                $getMethod = 'getString';
            } elseif ($returnType === 'string[]') {
                $getMethod = 'getStringArray';
            } elseif ($returnType === 'number') {
                $getMethod = 'getNumber';
                $returnType = 'integer';

                if (0 === strpos($method->getReturnDescription(), 'of ')) {
                    $returnType .= ' number';
                }
            }

            $documentation .= '@return '.$returnType.' '.$method->getReturnDescription();

            $body = 'return $this->driver->'.$getMethod.'("'.$method->getName().'"'.($signature ? ', '.$signature : '').');';
        }

        $builder->setName($method->getName());
        $builder->setBody($body);
        $builder->setDocumentation($documentation);

        return $builder->buildCode();
    }
388830
protected function processRequest($data, $method = self::POST)
    {
        $this->_headers['Content-Type'] = 'application/json';
        try {
            $client = new Client();

            // create a log channel
            $log = new Logger(get_class($this));
            $log->pushHandler(new StreamHandler('service_call.log', Logger::DEBUG));

            $subscriber = new LogSubscriber($log);
            $client->getEmitter()->attach($subscriber);

            $response = $client->$method($this->uri, [
                'auth' => [$this->username, $this->password],
                'headers' => $this->_headers,
                'body' => $data
            ]);

            return json_decode($response->getBody());
        } catch (BadResponseException $e) {
            $this->output->error($e->getRequest());
            if ($e->hasResponse()) {
                $this->output->error($e->getResponse());
            }
        }
    }
1087492
protected function call($eventName, $method, $data = null)
    {
        if (method_exists($this, $method)) {
            $result = call_user_func_array([$this, $method], $data);
            return $result;
        }

        return null;
    }
70382
protected function getValueDiffData($method)
    {
        $data = array();
        foreach ($this->getSafeAttributes() as $attribute) {
            $buffer = call_user_func(array($attribute, $method));
            if (count($buffer) > 0) {
                $data[$attribute->getName()] = $buffer;
            }
        }
        return $data;
    }
171574
private function getContext(string $method, $data, array $headers)
    {
        $options = [
            'http' => [
                'header' => $this->join(': ', $headers),
                'method' => $method,
                'content' => $this->getRawData($data),
            ],
        ];

        if (is_array($this->options)) {
            $options = array_merge_recursive($options, $this->options);
        }

        if (!empty($this->cookies)) {
            $options['http']['header'] .= 'Cookie: '.$this->join('=', $this->cookies, '; ');
        }

        $context = stream_context_create($options);

        return $context;
    }
1010379
protected function request($url, $method, $data = null)
    {
        $this->testLogin();
        try {
            $response = $this->transport->send(
                $url, $method, $data, array(
                'Content-Type: ' . $this->mapper->getContentType(),
                )
            );
        } catch (HttpStatusException $e) {
            $message = $e->getMessage();
            if ($e->getCode() == 403 || $e->getCode() == 422) {
                $this->errors = $this->mapper->mapFromStorage($this->transport->getLastResponse());
                if ($this->errors instanceof ErrorArray && count($this->errors) > 0) {
                    $message .= PHP_EOL . 'Errors:' . PHP_EOL . $this->errors;
                }
            }

            if (self::$debug) {
                printf(
                    'Url: %s' . PHP_EOL . 'Method: %s' . PHP_EOL . 'Data: %s', $url, $method, $data
                );
            }

            switch ($e->getCode()) {
                case 401:
                    throw new NotLoggedInException($message, 0, $e);
                    break;
                case 403:
                    throw new ForbiddenException($message, 0, $e);
                    break;
                case 404:
                    throw new NotFoundException($message, 0, $e);
                    break;
                case 406:
                case 422:
                    throw new NotValidException($message, 0, $e);
                    break;
                default:
                    $message = 'Unknown error; check https://github.com/bluetools/moneybird_php_api/wiki/Common-errors';
                // no break
                case 500:
                case 501:
                    throw new ServerErrorException($message, 0, $e);
                    break;
            }
        }

        return $response;
    }
129973
private function transformPaymentInstrumentValue(array $data, $method)
    {
        if ($method == 'card') {
            $instrument = new PaymentInstrumentCard();
        } elseif ($method == 'recurring') {
            $instrument = new PaymentInstrumentRecurring();
        } else {
            throw new Exception\Runtime(sprintf('Method "%s" is not supported', $method));
        }

        $this->map($data, $instrument);

        return $instrument;
    }
79352
private function prepareRequestArguments(array $data = null, string $method = null): array
    {
        $data   = $data ?? [];
        $method = $method ?? 'GET';

        // Removes null entries.
        $data = array_filter($data, function ($val) {
            return (null !== $val);
        });

        $headers = [
            'Content-Type' => 'application/json',
            'X-Auth-Email' => $this->email,
            'X-Auth-Key'   => $this->auth_key,
        ];

        $args = [
            'body'    => wp_json_encode($data),
            'headers' => $headers,
            'method'  => strtoupper($method),
            'timeout' => 15,
        ];

        return $args;
    }
655251
private function doSend($method, array $data, $token = null)
    {
        try {
            $data['token'] = $token ?: $this->token;

            $this->eventDispatcher->dispatch(self::EVENT_REQUEST, new RequestEvent($data));

            $request = $this->createRequest($method, $data);

            /** @var ResponseInterface $response */
            $response = $this->client->send($request);
        } catch (\Exception $e) {
            throw new SlackException('Failed to send data to the Slack API', null, $e);
        }

        try {
            $responseData = json_decode($response->getBody()->getContents(), true);
            if (!is_array($responseData)) {
                throw new \Exception(sprintf(
                    'Expected JSON-decoded response data to be of type "array", got "%s"',
                    gettype($responseData)
                ));
            }

            $this->eventDispatcher->dispatch(self::EVENT_RESPONSE, new ResponseEvent($responseData));

            return $responseData;
        } catch (\Exception $e) {
            throw new SlackException('Failed to process response from the Slack API', null, $e);
        }
    }
188697
private function processSerializeTypeMethod(Type\Method $method, $object, array $data, string $attribute): array
    {
        $value = $object->{$method->getter()}();

        if ($this->checkNullForAttribute($value, $attribute) === false) {
            $data[$attribute] = $value;
        }

        return $data;
    }
527278
protected function fireCustomModelEvent($event, $method)
    {
        if (! isset($this->dispatchesEvents[$event])) {
            return;
        }

        $result = static::$dispatcher->$method(new $this->dispatchesEvents[$event]($this));

        if (! is_null($result)) {
            return $result;
        }
    }
382774
public function json($method, $uri, array $data = [], array $headers = [])
    {
        $files = $this->extractFilesFromDataArray($data);

        $content = json_encode($data);

        $headers = array_merge([
            'CONTENT_LENGTH' => mb_strlen($content, '8bit'),
            'CONTENT_TYPE' => 'application/json',
            'Accept' => 'application/json',
        ], $headers);

        $this->call(
            $method, $uri, [], [], $files, $this->transformHeadersToServerVars($headers), $content
        );

        return $this;
    }
810133
public function write(string $id, array $data) : bool
    {
        static $create, $update, $delete;
        $values = $data + compact('id'); // Default.
        unset($values['dateactive']);
        if (!isset($create, $update)) {
            $fields = [];
            $placeholders = [];
            $updates = [];
            foreach ($values as $key => &$value) {
                if ($key == 'data') {
                    $value = base64_encode($value);
                }
                $fields[] = $key;
                $placeholders[] = ":$key";
                if ($key != 'id') {
                    $updates[] = "$key = :$key";
                }
            }
            $create = $this->pdo->prepare(sprintf(
                "INSERT INTO cesession_session (%s) VALUES (%s)",
                implode(', ', $fields),
                implode(', ', $placeholders)
            ));
            $update = $this->pdo->prepare(sprintf(
                "UPDATE cesession_session SET %s WHERE id = :id",
                implode(', ', $updates)
            ));
            $delete = $this->pdo->prepare("DELETE FROM cesession_session WHERE id = :id");
        }
        if ($this->exists) {
            $update->execute($values);
            return (bool)$update->rowCount();
        } else {
            $delete->execute(compact('id'));
            try {
                $create->execute($values);
                return ($affectedRows = $create->rowCount()) && $affectedRows;
            } catch (PDOException $e) {
                $update->execute($values);
                return (bool)$update->rowCount();
            }
        }
    }