Skip to content

Commit

Permalink
Push inicial
Browse files Browse the repository at this point in the history
  • Loading branch information
elzobrito committed May 31, 2023
0 parents commit c344242
Show file tree
Hide file tree
Showing 22 changed files with 1,390 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# OliviaHttpService

OliviaHttpService é um serviço de cliente HTTP simples para realizar solicitações HTTP a uma API específica.

## Requisitos

- PHP 7.2 ou superior

# Contribuição

Contribuições são bem-vindas! Se você encontrou um bug, tem alguma sugestão ou deseja implementar uma nova funcionalidade, abra uma issue.

# Licença
Este projeto está licenciado sob a Licença MIT.
18 changes: 18 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "elzobrito/olivia-app",
"description": "HttpService Olivia",
"authors": [
{
"name": "elzobrito",
"email": "elzo.filho@etec.sp.gov.br"
}
],
"autoload": {
"psr-4": {
"HttpServiceSrc\\": "src/"
}
},
"require": {
"php": "^7.2.5|^8.0"
}
}
20 changes: 20 additions & 0 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace HttpService;

use HttpServiceSrc\HttpClient\ServicoHttpClient;
use HttpServiceSrc\service\ServicoService;

require_once __DIR__ . '/vendor/autoload.php';
class Index
{
public function __construct()
{
// Cria uma instância do ServicoHttpClient passando a base URL
$httpClient = new ServicoHttpClient('https://dummyjson.com', 'Content-Type: application/json\r\n', '1.1');

// Cria uma instância do ServicoService passando o HttpClient
$servicoService = new ServicoService($httpClient);
$result = $servicoService->getSearchWithSlash('products/1'); // Corrigido: passando uma string como argumento
print_r(json_decode($result));
}
}
new Index();
156 changes: 156 additions & 0 deletions llmteste.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
<?php


namespace HttpService;

use HttpServiceSrc\HttpClient\ServicoHttpClient;
use HttpServiceSrc\service\ServicoService;

require_once __DIR__ . '/vendor/autoload.php';
class Index
{
public function __construct()
{
// Cria uma instância do ServicoHttpClient passando a base URL
$httpClient = new ServicoHttpClient('https://dummyjson.com', 'Content-Type: application/json\r\n');

// Cria uma instância do ServicoService passando o HttpClient
$servicoService = new ServicoService($httpClient);
$result = $servicoService->getSearchWithSlash('products',1); // Corrigido: passando uma string como argumento
print_r(json_decode($result));
}
}
new Index();


namespace HttpServiceSrc\service;

use HttpServiceSrc\HttpClient\HttpClientInterface;

class ServicoService
{
private $httpClient;

public function __construct(HttpClientInterface $httpClient)
{
$this->httpClient = $httpClient;
}

public function getSearchWithSlash($query, $params = null)
{
$uri = '/' .$query . '/' . $params;

return $this->httpClient->get($uri);
}

public function getSearch($query, $params = null)
{
$endpoint = '/' . $query;

$queryParams = [];

if ($params) {
$queryParams = array_merge($queryParams, $params);
}

return $this->httpClient->get($endpoint, $queryParams);
}
}


namespace HttpServiceSrc\HttpClient;

use HttpServiceSrc\Exception\HttpClientException;

abstract class AbstractHttpClient implements HttpClientInterface
{
protected $defaultHeaders;

public function __construct($handler = null)
{
$this->defaultHeaders = $handler ?? array('Content-Type: application/x-www-form-urlencoded');
}

abstract public function get($endpoint, $params = null);

protected function getDefaultContextOptions($method, $parametros = null)
{
return array(
'http' =>
array(
'method' => $method,
'header' => $this->defaultHeaders,
'content' => $parametros ?? ''
)
);
}

protected function handleResponse($response, $context)
{
if ($response === false) {
$error = error_get_last();
throw new HttpClientException('Failed to retrieve data from the server. Error: ' . $error['message']);
}

return $response;
}
protected function isResponseSuccessful($responseHeaders)
{
if (!empty($responseHeaders)) {
$statusCode = $this->getStatusCodeFromHeaders($responseHeaders);
return $statusCode >= 200 && $statusCode < 300;
}

return false;
}

protected function getStatusCodeFromHeaders($headers)
{
preg_match('/^HTTP\/\d\.\d\s+(\d+)/', $headers[0], $matches);
return (int) $matches[1];
}
}
namespace HttpServiceSrc\HttpClient;
interface HttpClientInterface
{
public function get($endpoint, $params = null);
}

namespace HttpServiceSrc\HttpClient;

use InvalidArgumentException;

class ServicoHttpClient extends AbstractHttpClient
{
private $baseUrl;

public function __construct($baseUrl,$handler = null)
{
parent::__construct($handler);
$this->baseUrl = $baseUrl;
}

public function get($endpoint, $params = null)
{
$url = $this->baseUrl . $endpoint;

// Validação da URL
if (!filter_var($url, FILTER_VALIDATE_URL)) {
throw new InvalidArgumentException("Invalid URL: $url");
}

$options = $this->getDefaultContextOptions('GET');
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

return $this->handleResponse($response, $context);
}

}
namespace HttpServiceSrc\Exception;

use Exception;

class HttpClientException extends Exception
{
}
8 changes: 8 additions & 0 deletions src/Exception/HttpClientException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php
namespace HttpServiceSrc\Exception;

use Exception;

class HttpClientException extends Exception
{
}
57 changes: 57 additions & 0 deletions src/HttpClient/AbstractHttpClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace HttpServiceSrc\HttpClient;

use HttpServiceSrc\Exception\HttpClientException;

abstract class AbstractHttpClient implements HttpClientInterface
{
protected $defaultHeaders;
protected $protocol_version;

public function __construct($handler = null,$protocol_version)
{
$this->defaultHeaders = $handler ?? array('Content-Type: application/x-www-form-urlencoded');
$this->protocol_version = $protocol_version;
}

abstract public function get($endpoint, $params = null);

protected function getDefaultContextOptions($method, $parametros = null)
{
return array(
'http' =>
array(
'method' => $method,
'header' => $this->defaultHeaders,
'content' => $parametros ?? '',
'protocol_version' => $this->protocol_version,
)
);
}

protected function handleResponse($response, $context)
{
if ($response === false) {
$error = error_get_last();
throw new HttpClientException('Failed to retrieve data from the server. Error: ' . $error['message']);
}

return $response;
}
protected function isResponseSuccessful($responseHeaders)
{
if (!empty($responseHeaders)) {
$statusCode = $this->getStatusCodeFromHeaders($responseHeaders);
return $statusCode >= 200 && $statusCode < 300;
}

return false;
}

protected function getStatusCodeFromHeaders($headers)
{
preg_match('/^HTTP\/\d\.\d\s+(\d+)/', $headers[0], $matches);
return (int) $matches[1];
}
}
6 changes: 6 additions & 0 deletions src/HttpClient/HttpClientInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php
namespace HttpServiceSrc\HttpClient;
interface HttpClientInterface
{
public function get($endpoint, $params = null);
}
32 changes: 32 additions & 0 deletions src/HttpClient/ServicoHttpClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace HttpServiceSrc\HttpClient;

use InvalidArgumentException;

class ServicoHttpClient extends AbstractHttpClient
{
private $baseUrl;

public function __construct($baseUrl, $handler = null, $protocol_version = null)
{
parent::__construct($handler, $protocol_version);
$this->baseUrl = $baseUrl;
}

public function get($endpoint, $params = null)
{
$url = $this->baseUrl . $endpoint;

// Validação da URL
if (!filter_var($url, FILTER_VALIDATE_URL)) {
throw new InvalidArgumentException("Invalid URL: $url");
}

$options = $this->getDefaultContextOptions('GET');
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

return $this->handleResponse($response, $context);
}
}
35 changes: 35 additions & 0 deletions src/Service/ServicoService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace HttpServiceSrc\service;

use HttpServiceSrc\HttpClient\HttpClientInterface;

class ServicoService
{
private $httpClient;

public function __construct(HttpClientInterface $httpClient)
{
$this->httpClient = $httpClient;
}

public function getSearchWithSlash($query, $params = null)
{
$uri = '/' .$query . '/' . $params;

return $this->httpClient->get($uri);
}

public function getSearch($query, $params = null)
{
$endpoint = '/' . $query;

$queryParams = [];

if ($params) {
$queryParams = array_merge($queryParams, $params);
}

return $this->httpClient->get($endpoint, $queryParams);
}
}
7 changes: 7 additions & 0 deletions vendor/autoload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInitd8fdea5f824ff0ce43134e67dfcd9377::getLoader();

0 comments on commit c344242

Please sign in to comment.