Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .envrc.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# If using asdf + Homebrew on macOS, you might need these before installing PHP
# export PKG_CONFIG_PATH="$(brew --prefix openssl@3)/lib/pkgconfig:$PKG_CONFIG_PATH"
# export PHP_CONFIGURE_OPTIONS="--with-openssl=$(brew --prefix openssl@3)"
42 changes: 42 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: CI

on:
pull_request:
push:
branches: main

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
php-version: ['7.4', '8.5']
name: PHP ${{ matrix.php-version }}
steps:
- uses: actions/checkout@v4

- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
extensions: curl, json, hash
coverage: none

- name: Cache Composer dependencies
uses: actions/cache@v4
with:
path: ${{ runner.temp }}/composer-cache
key: php-${{ matrix.php-version }}-composer-${{ hashFiles('composer.lock') }}
restore-keys: php-${{ matrix.php-version }}-composer-

- name: Install dependencies
run: composer install --no-interaction --prefer-dist
env:
COMPOSER_CACHE_DIR: ${{ runner.temp }}/composer-cache

- name: Run tests
run: composer test
23 changes: 23 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Composer
/vendor/
composer.lock

# PHPUnit
.phpunit.result.cache
.phpunit.cache/

# PHP CS Fixer
# .php-cs-fixer.cache

# OS files
.DS_Store
Thumbs.db

# IDE
.idea/
.vscode/
*.swp

# Environment
.env
.envrc
1 change: 1 addition & 0 deletions .tool-versions
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
php 8.5.3
20 changes: 20 additions & 0 deletions Brewfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
brew "autoconf"
brew "bison"
brew "curl"
brew "freetype"
brew "gd"
brew "gettext"
brew "gmp"
brew "icu4c@78"
brew "jpeg"
brew "libiconv"
brew "libpng"
brew "libsodium"
brew "libxml2"
brew "libzip"
brew "oniguruma"
brew "openssl@3"
brew "pkg-config"
brew "readline"
brew "re2c"
brew "webp"
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"ext-hash": "*"
},
"require-dev": {
"phpunit/phpunit": "^9.0|^10.0",
"phpunit/phpunit": "^9.0",
"php-cs-fixer/shim": "^3.0"
},
"autoload": {
Expand Down
60 changes: 25 additions & 35 deletions src/AccessGridClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use AccessGrid\Exceptions\AccessGridException;
use AccessGrid\Exceptions\AuthenticationException;
use AccessGrid\Http\HttpClientInterface;
use AccessGrid\Http\CurlHttpClient;
use AccessGrid\Services\AccessCards;
use AccessGrid\Services\Console;

Expand All @@ -12,23 +14,26 @@ class AccessGridClient
private string $accountId;
private string $secretKey;
private string $baseUrl;
/** @var HttpClientInterface */
private $httpClient;
public AccessCards $accessCards;
public Console $console;

public function __construct(string $accountId, string $secretKey, string $baseUrl = 'https://api.accessgrid.com')
public function __construct(string $accountId, string $secretKey, string $baseUrl = 'https://api.accessgrid.com', ?HttpClientInterface $httpClient = null)
{
if (empty($accountId)) {
throw new \InvalidArgumentException('Account ID is required');
}

if (empty($secretKey)) {
throw new \InvalidArgumentException('Secret Key is required');
}

$this->accountId = $accountId;
$this->secretKey = $secretKey;
$this->baseUrl = rtrim($baseUrl, '/');

$this->httpClient = $httpClient ?? new CurlHttpClient();

$this->accessCards = new AccessCards($this);
$this->console = new Console($this);
}
Expand Down Expand Up @@ -110,18 +115,6 @@ public function makeRequest(string $method, string $endpoint, ?array $data = nul
'User-Agent: accessgrid-php @ v1.0.0'
];

// Initialize cURL
$ch = curl_init();

// Set basic cURL options
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => 30,
CURLOPT_CUSTOMREQUEST => $method
]);

// For requests with empty bodies (GET or action endpoints like unlink/suspend/resume),
// we need to include the sig_payload parameter
if ($method === 'GET' || ($method === 'POST' && empty($data))) {
Expand All @@ -130,43 +123,40 @@ public function makeRequest(string $method, string $endpoint, ?array $data = nul
}
// Include the ID payload in the query params
if ($resourceId) {
// The server expects the raw JSON string, not URL-encoded
$params['sig_payload'] = json_encode(['id' => $resourceId]);
}
}

// Add query parameters for GET requests or when params are provided

// Build final URL with query parameters
$finalUrl = $url;
if (!empty($params)) {
$queryString = http_build_query($params);
$separator = strpos($url, '?') !== false ? '&' : '?';
curl_setopt($ch, CURLOPT_URL, $url . $separator . $queryString);
$finalUrl = $url . $separator . $queryString;
}

// For POST/PUT/PATCH with data, set the JSON body

// Build request body for POST/PUT/PATCH
$requestBody = null;
if (!empty($data) && $method !== 'GET') {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
throw new AccessGridException('Request failed: ' . $error);
$requestBody = json_encode($data);
}


// Delegate to HTTP client
$response = $this->httpClient->send($method, $finalUrl, $headers, $requestBody);
$httpCode = $response->getStatusCode();
$responseBody = $response->getBody();

if ($httpCode === 401) {
throw new AuthenticationException('Invalid credentials');
} elseif ($httpCode === 402) {
throw new AccessGridException('Insufficient account balance');
} elseif ($httpCode < 200 || $httpCode >= 300) {
$errorData = json_decode($response, true) ?: [];
$errorMessage = $errorData['message'] ?? $response;
$errorData = json_decode($responseBody, true) ?: [];
$errorMessage = $errorData['message'] ?? $responseBody;
throw new AccessGridException('API request failed: ' . $errorMessage);
}

$decoded = json_decode($response, true);
$decoded = json_decode($responseBody, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new AccessGridException('Invalid JSON response: ' . json_last_error_msg());
}
Expand Down
36 changes: 36 additions & 0 deletions src/Http/CurlHttpClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace AccessGrid\Http;

use AccessGrid\Exceptions\AccessGridException;

class CurlHttpClient implements HttpClientInterface
{
public function send(string $method, string $url, array $headers, ?string $body = null): HttpResponse
{
$ch = curl_init();

curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => 30,
CURLOPT_CUSTOMREQUEST => $method,
]);

if ($body !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}

$responseBody = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
throw new AccessGridException('Request failed: ' . $error);
}

return new HttpResponse($httpCode, $responseBody);
}
}
18 changes: 18 additions & 0 deletions src/Http/HttpClientInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace AccessGrid\Http;

interface HttpClientInterface
{
/**
* Send an HTTP request and return the response.
*
* @param string $method HTTP method (GET, POST, PUT, PATCH)
* @param string $url Fully-qualified URL including query string
* @param array $headers Headers in "Key: Value" format
* @param string|null $body Request body (JSON string), null for bodyless requests
* @return HttpResponse
* @throws \AccessGrid\Exceptions\AccessGridException on transport-level failure
*/
public function send(string $method, string $url, array $headers, ?string $body = null): HttpResponse;
}
28 changes: 28 additions & 0 deletions src/Http/HttpResponse.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace AccessGrid\Http;

class HttpResponse
{
/** @var int */
private $statusCode;

/** @var string */
private $body;

public function __construct(int $statusCode, string $body)
{
$this->statusCode = $statusCode;
$this->body = $body;
}

public function getStatusCode(): int
{
return $this->statusCode;
}

public function getBody(): string
{
return $this->body;
}
}
Loading