PHP code example of phpmystic / kai

1. Go to this page and download the library: Download phpmystic/kai library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phpmystic / kai example snippets


use Phpmystic\Kai\Client;

$client = new Client('https://api.github.com');

$client->get('/users/octocat')
    ->onSuccess(function ($response) {
        echo "User: " . $response->body->login;
    })
    ->notFound(function ($response) {
        echo "User not found";
    })
    ->onError(function ($response) {
        echo "Connection error: " . $response->error;
    });

use Phpmystic\Kai\Client;

// Simple client
$client = new Client('https://api.example.com');

// Client with default headers
$client = new Client('https://api.example.com', [
    'Authorization' => 'Bearer your-token-here',
    'Accept' => 'application/json'
]);

$client->get('/users')
    ->onSuccess(function ($response) {
        print_r($response->body);
    });

$client->post('/users', [
    'name' => 'John Doe',
    'email' => '[email protected]'
])->created(function ($response) {
    echo "User created with ID: " . $response->body->id;
});

$client->put('/users/123', [
    'name' => 'Jane Doe'
])->onSuccess(function ($response) {
    echo "User updated successfully";
});

$client->patch('/users/123', [
    'email' => '[email protected]'
])->onSuccess(function ($response) {
    echo "Email updated";
});

$client->delete('/users/123')
    ->noContent(function ($response) {
        echo "User deleted";
    });

$client->query(['page' => 1, 'limit' => 10])
    ->get('/users')
    ->onSuccess(function ($response) {
        // Handles: GET /users?page=1&limit=10
    });

$client->withHeaders([
    'X-Custom-Header' => 'value',
    'Authorization' => 'Bearer token123'
])->get('/protected')
    ->onSuccess(function ($response) {
        // Request 

$client->query(['filter' => 'active'])
    ->withHeaders(['X-Request-ID' => uniqid()])
    ->get('/users')
    ->onSuccess(function ($response) {
        echo "Found " . count($response->body) . " users";
    })
    ->always(function ($response) {
        echo "Request completed with status: " . $response->status;
    });

$client->get('/users/123')
    ->ok(function ($response) {
        // Handles 200 OK
    })
    ->created(function ($response) {
        // Handles 201 Created
    })
    ->accepted(function ($response) {
        // Handles 202 Accepted
    })
    ->noContent(function ($response) {
        // Handles 204 No Content
    })
    ->badRequest(function ($response) {
        // Handles 400 Bad Request
    })
    ->unauthorized(function ($response) {
        // Handles 401 Unauthorized
    })
    ->forbidden(function ($response) {
        // Handles 403 Forbidden
    })
    ->notFound(function ($response) {
        // Handles 404 Not Found
    })
    ->unprocessable(function ($response) {
        // Handles 422 Unprocessable Entity
    })
    ->serverError(function ($response) {
        // Handles 500 Internal Server Error
    });

$client->get('/endpoint')
    ->on(418, function ($response) {
        echo "I'm a teapot!";
    });

$client->get('/users')
    ->onSuccess(function ($response) {
        // Handles any 2xx status code
        echo "Success!";
    })
    ->onClientError(function ($response) {
        // Handles any 4xx status code
        echo "Client error: " . $response->status;
    })
    ->onServerError(function ($response) {
        // Handles any 5xx status code
        echo "Server error: " . $response->status;
    });

$client->get('/endpoint')
    ->onError(function ($response) {
        echo "Connection error: " . $response->error;
        echo "Error code: " . $response->status; // Will be 0 for cURL errors
    });

$client->get('/endpoint')
    ->onSuccess(function ($response) {
        // Handle success
    })
    ->onClientError(function ($response) {
        // Handle client error
    })
    ->always(function ($response) {
        // This runs regardless of success or failure
        echo "Request completed at " . date('Y-m-d H:i:s');
    });

$response->status;      // HTTP status code (int)
$response->body;        // Parsed JSON response (object|array|null)
$response->raw_body;    // Raw response body (string)
$response->headers;     // Response headers (array)
$response->error;       // cURL error message (string|null)

// Check response status
$response->isSuccessful();    // Returns true for 2xx status codes
$response->isClientError();   // Returns true for 4xx status codes
$response->isServerError();   // Returns true for 5xx status codes
$response->hasError();        // Returns true for cURL errors

// Access response data
$response->json();            // Get parsed JSON body (same as $response->body)
$response->text();            // Get raw response body as string
$response->toArray();         // Convert body to array

// Get specific header (case-insensitive)
$response->header('Content-Type');     // Returns header value or null
$response->header('content-type');     // Same as above

$client->get('/users/123')
    ->onSuccess(function ($response) {
        // Access status code
        echo "Status: " . $response->status; // 200

        // Access parsed JSON body
        echo "Name: " . $response->body->name;
        echo "Email: " . $response->body->email;

        // Or use helper methods
        $data = $response->toArray();
        echo "Name: " . $data['name'];

        // Access raw body
        echo "Raw: " . $response->text();

        // Access headers (case-insensitive)
        echo "Content-Type: " . $response->header('content-type');

        // Check status
        if ($response->isSuccessful()) {
            echo "Success!";
        }
    })
    ->onError(function ($response) {
        // Access error information
        echo "Error: " . $response->error;
        echo "Status: " . $response->status; // 0 for cURL errors

        if ($response->hasError()) {
            echo "This is a cURL error";
        }
    });

// JSON response
$client->get('/api/user')
    ->onSuccess(function ($response) {
        // Access as object
        $name = $response->body->name;

        // Or convert to array
        $user = $response->toArray();
        $name = $user['name'];

        // Or use json() helper
        $data = $response->json();
    });

// Text/HTML response
$client->get('/page.html')
    ->onSuccess(function ($response) {
        $html = $response->text();
        echo $html;
    });

// Check headers
$client->get('/file')
    ->onSuccess(function ($response) {
        $contentType = $response->header('Content-Type');

        if ($contentType === 'application/pdf') {
            // Handle PDF
        }
    });

// Conditional logic based on status
$client->get('/endpoint')
    ->always(function ($response) {
        if ($response->isSuccessful()) {
            echo "Request succeeded";
        } elseif ($response->isClientError()) {
            echo "Client error: " . $response->status;
        } elseif ($response->isServerError()) {
            echo "Server error: " . $response->status;
        } elseif ($response->hasError()) {
            echo "Connection error: " . $response->error;
        }
    });

class UserService
{
    private Client $client;

    public function __construct()
    {
        $this->client = new Client('https://api.example.com', [
            'Authorization' => 'Bearer ' . getenv('API_TOKEN'),
            'Accept' => 'application/json'
        ]);
    }

    public function getUser(int $id): ?array
    {
        $user = null;

        $this->client->get("/users/{$id}")
            ->onSuccess(function ($response) use (&$user) {
                $user = (array) $response->body;
            })
            ->notFound(function ($response) {
                // User doesn't exist, return null
            })
            ->onError(function ($response) {
                error_log("API Error: " . $response->error);
            });

        return $user;
    }

    public function createUser(array $data): ?int
    {
        $userId = null;

        $this->client->post('/users', $data)
            ->created(function ($response) use (&$userId) {
                $userId = $response->body->id;
            })
            ->unprocessable(function ($response) {
                error_log("Validation errors: " . json_encode($response->body->errors));
            })
            ->onError(function ($response) {
                error_log("Connection error: " . $response->error);
            });

        return $userId;
    }

    public function listUsers(int $page = 1, int $limit = 20): array
    {
        $users = [];

        $this->client->query(['page' => $page, 'limit' => $limit])
            ->get('/users')
            ->onSuccess(function ($response) use (&$users) {
                $users = $response->body;
            });

        return $users;
    }
}

$github = new Client('https://api.github.com', [
    'Accept' => 'application/vnd.github.v3+json',
    'User-Agent' => 'MyApp/1.0'
]);

// Get repository information
$github->get('/repos/laravel/framework')
    ->onSuccess(function ($response) {
        echo "Repository: " . $response->body->full_name . "\n";
        echo "Stars: " . $response->body->stargazers_count . "\n";
        echo "Forks: " . $response->body->forks_count . "\n";
    })
    ->notFound(function ($response) {
        echo "Repository not found\n";
    })
    ->forbidden(function ($response) {
        echo "Access forbidden - check your token\n";
    });

// Search repositories
$github->query(['q' => 'language:php stars:>1000', 'sort' => 'stars'])
    ->get('/search/repositories')
    ->onSuccess(function ($response) {
        echo "Found " . $response->body->total_count . " repositories\n";
        foreach ($response->body->items as $repo) {
            echo "- {$repo->full_name} ({$repo->stargazers_count} stars)\n";
        }
    });

$weather = new Client('https://api.openweathermap.org/data/2.5');

$apiKey = getenv('OPENWEATHER_API_KEY');

$weather->query(['q' => 'London', 'appid' => $apiKey, 'units' => 'metric'])
    ->get('/weather')
    ->onSuccess(function ($response) {
        $temp = $response->body->main->temp;
        $description = $response->body->weather[0]->description;
        echo "London: {$temp}°C, {$description}\n";
    })
    ->unauthorized(function ($response) {
        echo "Invalid API key\n";
    })
    ->notFound(function ($response) {
        echo "City not found\n";
    })
    ->onError(function ($response) {
        echo "Failed to fetch weather: " . $response->error . "\n";
    });

$api = new Client('https://api.example.com', [
    'Authorization' => 'Bearer token123'
]);

// Step 1: Create a post
$postId = null;
$api->post('/posts', ['title' => 'Hello World', 'content' => 'First post'])
    ->created(function ($response) use (&$postId) {
        $postId = $response->body->id;
        echo "Post created with ID: {$postId}\n";
    });

// Step 2: Add a comment to the post
if ($postId) {
    $api->post("/posts/{$postId}/comments", [
        'text' => 'Great post!'
    ])->created(function ($response) {
        echo "Comment added\n";
    });
}

// Step 3: Fetch the post with comments
if ($postId) {
    $api->get("/posts/{$postId}?

$client = new Client('https://api.example.com');

$client->get('/data')
    ->onSuccess(function ($response) {
        // Everything went well
        processData($response->body);
    })
    ->unauthorized(function ($response) {
        // Need to re-authenticate
        refreshAuthToken();
    })
    ->forbidden(function ($response) {
        // Don't have permission
        logSecurityEvent('Forbidden access attempt');
    })
    ->notFound(function ($response) {
        // Resource doesn't exist
        showNotFoundPage();
    })
    ->unprocessable(function ($response) {
        // Validation errors
        displayValidationErrors($response->body->errors);
    })
    ->onServerError(function ($response) {
        // Server is having issues
        queueRetryJob();
        notifyAdmins('API server error: ' . $response->status);
    })
    ->onError(function ($response) {
        // Network/connection issues
        logError('Connection failed: ' . $response->error);
        showOfflineMessage();
    })
    ->always(function ($response) {
        // Cleanup, logging, metrics
        logRequest($response->status);
        updateMetrics();
    });

use PHPUnit\Framework\TestCase;
use Phpmystic\Kai\Client;
use Phpmystic\Kai\Tests\Mocks\MockCurlWrapper;

class MyServiceTest extends TestCase
{
    public function testApiCall(): void
    {
        // Create a mock
        $mockCurl = new MockCurlWrapper();
        $mockCurl->setMockResponse(
            json_encode(['id' => 123, 'name' => 'Test User']),
            200
        );

        // Inject mock into client
        $client = new Client('https://api.example.com', [], $mockCurl);

        // Test your code
        $result = null;
        $client->get('/users/123')
            ->onSuccess(function ($response) use (&$result) {
                $result = $response->body;
            });

        $this->assertEquals(123, $result->id);
        $this->assertEquals('Test User', $result->name);
    }
}

// Traditional approach
try {
    $response = $client->get('/users/123');
    $user = $response->json();
} catch (NotFoundException $e) {
    // Handle 404
} catch (UnauthorizedException $e) {
    // Handle 401
} catch (ServerException $e) {
    // Handle 5xx
} catch (RequestException $e) {
    // Handle other errors
}

// Kai approach
$client->get('/users/123')
    ->onSuccess(function ($response) {
        $user = $response->body;
    })
    ->notFound(function ($response) {
        // Handle 404
    })
    ->unauthorized(function ($response) {
        // Handle 401
    })
    ->onServerError(function ($response) {
        // Handle 5xx
    })
    ->onError(function ($response) {
        // Handle connection errors
    });

__construct(string $baseUrl = '', array $defaultHeaders = [], ?CurlWrapperInterface $curl = null)