itul / bugherdapi
Laravel package for using the bugherd API
Requires
- php: ^7.4|^8.0
- illuminate/support: >=8.0
Requires (Dev)
- orchestra/testbench: ^6.0
- phpunit/phpunit: ^9.0
README
Overview
The BugHerd API Laravel Package provides an elegant, Laravel-style interface for interacting with the BugHerd API. This comprehensive package offers Eloquent-style models, advanced caching, intelligent rate limiting, webhook support, and bulk operations - all designed to seamlessly integrate with your Laravel application.
Purpose: Simplify BugHerd API integration by providing familiar Laravel patterns and robust functionality for managing projects, tasks, comments, users, and webhooks in your bug tracking workflow.
Features
- 🎯 Eloquent-Style Models - Work with BugHerd resources using familiar Laravel patterns
- ⚡ Intelligent Caching - Built-in caching with automatic cache invalidation
- 🔄 Persistent Rate Limiting - Multi-backend rate limiting with database persistence
- 🪝 Webhook Support - Complete webhook handling with event processing and job queues
- 📂 File Attachments - Upload and manage task attachments seamlessly
- 🔍 Advanced Search - Powerful search capabilities across projects and tasks
- ⚙️ Bulk Operations - Efficiently manage multiple resources at once
- 🛡️ Exception Handling - Comprehensive error handling and custom exceptions
- 📊 Debug Mode - Detailed logging for development and troubleshooting
- 🎨 Laravel Integration - Service provider, facades, and Artisan commands
- 🔐 Input Validation - Built-in sanitization and security features
Table of Contents
Quickstart
Installation
Install the package via Composer:
composer require itul/bugherdapi
Publish the configuration file:
php artisan vendor:publish --tag=bugherd-config
Requirements
- PHP: 7.4+ or 8.0+
- Laravel: 8.0+ (11.x+ recommended)
- BugHerd API Key: Available from your BugHerd account settings
- cURL Extension: Required for HTTP requests
Configuration
Add the following to your .env
file:
# Required
BUGHERD_API_KEY=your_api_key_here
# Optional - Advanced Configuration
BUGHERD_BASE_URL=https://www.bugherd.com/api_v2
BUGHERD_CACHE_TTL=28800
BUGHERD_TIMEOUT=30
BUGHERD_DEBUG=false
Examples
Reading Tasks:
use Itul\BugherdAPI\BugherdProject;
use Itul\BugherdAPI\BugherdProjectTask;
// Get all projects
$projects = BugherdProject::list();
// Find a specific project by ID (123 = project ID)
$project = BugherdProject::find(123);
// Get tasks for a project with status filter
$tasks = $project->tasks(['status' => 'open']);
// Find a specific task by local ID (123 = project ID, 45 = local task ID)
$task = BugherdProjectTask::findByLocalId(123, 45);
// Get task comments
$comments = $task->comments();
Writing Tasks:
use Itul\BugherdAPI\BugherdProject;
use Itul\BugherdAPI\BugherdProjectTask;
// Create a new project
$project = BugherdProject::create([
'name' => 'My New Project',
'is_active' => true
]);
// Create a task in the project (using project ID from created project)
$task = $project->createTask([
'description' => 'Fix the login bug',
'priority' => 'high',
'status' => 'todo'
]);
// Update task status with optional updater email
$task->moveToStatus('doing');
// Archive a task
$task->archive();
Models
BugherdProject
Overview
Represents a BugHerd project with associated tasks and members. Provides methods for project management, task creation, and member administration.
Available Methods and Arguments
Method | Arguments | Description |
---|---|---|
create() | array $projectData | Create a new project |
update() | array $projectData | Update project details |
delete() | None | Delete the project (permanent) |
addMember() | int $userId | Add a member to the project |
addGuest() | $userIdOrEmail | Add a guest to the project |
tasks() | ...$args (optional filters) | Get project tasks |
createTask() | array $taskData | Create a new task |
getStatistics() | None | Get project statistics |
isActive() | None | Check if project is active |
Examples
Create:
use Itul\BugherdAPI\BugherdProject;
$project = BugherdProject::create([
'name' => 'Website Redesign',
'is_active' => true,
'is_public' => false,
'guests_see_guests' => false
]);
Update:
// Find project by ID (123 = project ID)
$project = BugherdProject::find(123);
$project->update([
'name' => 'Updated Project Name',
'is_active' => false
]);
Delete:
// Find project by ID (123 = project ID)
$project = BugherdProject::find(123);
$project->delete(); // WARNING: This is permanent!
List:
Normal Listing:
$projects = BugherdProject::list();
Filtered Listing:
$activeProjects = BugherdProject::list(['status' => 'active']);
Get Tasks:
// Find project by ID (123 = project ID)
$project = BugherdProject::find(123);
// All tasks
$allTasks = $project->tasks();
// Filtered tasks
$openTasks = $project->tasks(['status' => 'open']);
$highPriorityTasks = $project->tasks(['priority' => 'high']);
BugherdProjectTask
Overview
Represents a task within a project, with support for comments, attachments, and status management. Provides comprehensive task manipulation capabilities.
Available Methods and Arguments
Method | Arguments | Description |
---|---|---|
find() | $id | Find task by ID |
findByLocalId() | int $projectId, int $localTaskId | Find task by local ID within project |
create() | int $projectId, array $taskData | Create a new task |
update() | array $taskData | Update task details |
archive() | ?string $updaterEmail | Archive the task |
moveToStatus() | string $status, ?string $updaterEmail | Move task to new status |
assignTo() | $assignee, ?string $updaterEmail | Assign task to user |
setPriority() | string $priority, ?string $updaterEmail | Set task priority |
project() | None | Get associated project |
comments() | None | Get task comments |
addComment() | string $text, $user | Add comment to task |
delete() | None | Delete the task |
isClosed() | None | Check if task is closed |
getSecretLink() | None | Get secret sharing link |
getAdminLink() | None | Get admin link |
hasExternalId() | None | Check if task has external ID |
getAgeInDays() | None | Get task age in days |
Examples
Create:
use Itul\BugherdAPI\BugherdProjectTask;
// Create task in project 123 with task data
$task = BugherdProjectTask::create(
123, // project ID
[
'description' => 'Fix the header navigation bug',
'priority' => 'high',
'status' => 'todo',
'external_id' => 'JIRA-123'
]
);
Update:
// Find task by local ID (123 = project ID, 45 = local task ID)
$task = BugherdProjectTask::findByLocalId(123, 45);
$task->update([
'description' => 'Updated task description',
'priority' => 'medium'
]);
Delete:
// Find task by local ID (123 = project ID, 45 = local task ID)
$task = BugherdProjectTask::findByLocalId(123, 45);
$task->delete();
List:
Normal Listing:
// Find project by ID (123 = project ID)
$project = BugherdProject::find(123);
$tasks = $project->tasks();
Filtered Listing:
$openTasks = $project->tasks(['status' => 'open']);
$assignedTasks = $project->tasks(['assigned_to_id' => 456]); // 456 = user ID
$highPriorityTasks = $project->tasks(['priority' => 'high']);
Get Comments:
// Find task by local ID (123 = project ID, 45 = local task ID)
$task = BugherdProjectTask::findByLocalId(123, 45);
$comments = $task->comments();
BugherdProjectTaskComment
Overview
Represents a comment on a task. Provides methods for comment creation, updating, deletion, and managing comment attachments.
Available Methods and Arguments
Method | Arguments | Description |
---|---|---|
find() | $id | Find comment by ID |
create() | int $projectId, int $taskId, string $text, $user | Create a new comment |
update() | array $commentData | Update comment details |
delete() | None | Delete the comment |
updateText() | string $newText | Update comment text |
task() | None | Get associated task |
isFromGuest() | None | Check if comment is from guest |
Examples
Create:
use Itul\BugherdAPI\BugherdProjectTaskComment;
// Create comment on task 45 in project 123
$comment = BugherdProjectTaskComment::create(
123, // project ID
45, // task local ID
'This looks good to me!', // comment text
'user@example.com' // user email
);
Update:
// Find comment by ID (789 = comment ID)
$comment = BugherdProjectTaskComment::find(789);
$comment->update(['text' => 'Updated comment text']);
Delete:
// Find comment by ID (789 = comment ID)
$comment = BugherdProjectTaskComment::find(789);
$comment->delete();
List:
// Find task by local ID (123 = project ID, 45 = local task ID)
$task = BugherdProjectTask::findByLocalId(123, 45);
$comments = $task->comments();
Get Attachments:
// Comments can contain attachments - access via comment data
// Find comment by ID (789 = comment ID)
$comment = BugherdProjectTaskComment::find(789);
$attachments = $comment->attachments ?? [];
BugherdUser
Overview
Represents a BugHerd user with access to their projects and assigned tasks. Provides methods for user management and retrieving user-specific data.
Available Methods and Arguments
Method | Arguments | Description |
---|---|---|
projects() | None | Get projects accessible to user |
tasks() | ...$args (optional filters) | Get tasks assigned to user |
guests() | None | Get all guest users (static) |
members() | None | Get all member users (static) |
assignedTasks() | None | Get tasks assigned to this user |
isGuest() | None | Check if user is a guest |
isMember() | None | Check if user is a member |
getCurrentWorkload() | None | Get current workload statistics |
getTaskStatistics() | None | Get task statistics for user |
Examples
Create:
// Users are typically created through BugHerd's web interface
// or via project member/guest addition
$project = BugherdProject::find(123); // 123 = project ID
$project->addMember($userId); // $userId = user ID to add
$project->addGuest('guest@example.com'); // Add guest by email
Update:
// User updates are typically handled through BugHerd's web interface
// This package focuses on reading user data and managing assignments
Delete:
// User deletion is typically handled through BugHerd's web interface
// This package focuses on reading user data
Get Projects:
Normal Listing:
// Find user by ID (456 = user ID)
$user = BugherdUser::find(456);
$projects = $user->projects();
Filtered Listing:
// Projects are filtered at the API level based on user permissions
$user = BugherdUser::find(456); // 456 = user ID
$projects = $user->projects(); // Returns only accessible projects
Get Tasks:
Normal Listing:
// Find user by ID (456 = user ID)
$user = BugherdUser::find(456);
$tasks = $user->tasks();
Filtered Listing:
$user = BugherdUser::find(456); // 456 = user ID
$openTasks = $user->tasks(['status' => 'open']);
$projectTasks = $user->tasks(['project_id' => 123]); // 123 = project ID
$highPriorityTasks = $user->tasks(['priority' => 'high']);
BugherdWebhook
Overview
Represents a webhook configuration for receiving real-time notifications from BugHerd. Supports both project-specific and global webhooks.
Available Methods and Arguments
Method | Arguments | Description |
---|---|---|
create() | string $targetUrl, ?string $event, ?int $projectId | Create a new webhook |
delete() | None | Delete the webhook |
isGlobal() | None | Check if webhook is global (all projects) |
Examples
Create:
Single Project:
use Itul\BugherdAPI\BugherdWebhook;
// Create webhook for specific project
$webhook = BugherdWebhook::create(
'https://yourapp.com/api/bugherd/webhook', // target URL
'task_create', // event type
123 // project ID
);
All Projects:
// Create global webhook (applies to all projects)
$globalWebhook = BugherdWebhook::create(
'https://yourapp.com/api/bugherd/webhook', // target URL
'task_update' // event type
// No project ID = global webhook
);
List:
$webhooks = BugherdWebhook::list();
foreach ($webhooks as $webhook) {
if ($webhook->isGlobal()) {
echo "Global webhook for all projects\n";
} else {
echo "Project-specific webhook for project {$webhook->project_id}\n";
}
}
Delete:
// Find webhook by ID (789 = webhook ID)
$webhook = BugherdWebhook::find(789);
$webhook->delete();
How to Receive Webhooks
Once you've created webhooks, you need to set up your Laravel application to receive and process them. The package provides built-in webhook handling capabilities.
Route Registration
The package automatically registers webhook routes when auto_register_routes
is enabled in the configuration:
// config/bugherdapi.php
'webhooks' => [
'auto_register_routes' => true, // Automatically register webhook routes
'middleware' => ['api'], // Middleware to apply to webhook routes
'prefix' => 'bugherd', // Route prefix
],
This creates the following route:
POST /api/bugherd/webhook
- Receives all BugHerd webhooks
Manual Route Registration
If you prefer to register routes manually, set auto_register_routes
to false
and add this to your routes/api.php
:
use Itul\BugherdAPI\Http\Controllers\WebhookController;
Route::post('/bugherd/webhook', [WebhookController::class, 'handle'])
->middleware(['api']);
Webhook Security
BugHerd webhooks don't include built-in authentication, so you should secure your webhook endpoint:
Option 1: Secret URL Path
// Use a secret path that's hard to guess
Route::post('/bugherd/webhook/your-secret-key-here', [WebhookController::class, 'handle']);
Option 2: IP Whitelisting
Route::post('/bugherd/webhook', [WebhookController::class, 'handle'])
->middleware(['api', 'whitelist.bugherd.ips']);
Option 3: Custom Middleware
// Create custom authentication middleware
Route::post('/bugherd/webhook', [WebhookController::class, 'handle'])
->middleware(['api', 'webhook.auth']);
Processing Webhook Events
The package provides several ways to handle incoming webhook data:
1. Event Listeners
The package fires a WebhookReceived
event for every incoming webhook:
// app/Providers/EventServiceProvider.php
use Itul\BugherdAPI\Events\WebhookReceived;
use App\Listeners\ProcessBugherdWebhook;
protected $listen = [
WebhookReceived::class => [
ProcessBugherdWebhook::class,
],
];
Create your listener:
// app/Listeners/ProcessBugherdWebhook.php
namespace App\Listeners;
use Itul\BugherdAPI\Events\WebhookReceived;
use Illuminate\Support\Facades\Log;
class ProcessBugherdWebhook
{
public function handle(WebhookReceived $event)
{
$payload = $event->payload;
$eventType = $event->event_type;
// Log the webhook for debugging
Log::info('BugHerd webhook received', [
'event_type' => $eventType,
'payload' => $payload
]);
// Process based on event type
switch ($eventType) {
case 'task_create':
$this->handleTaskCreated($payload);
break;
case 'task_update':
$this->handleTaskUpdated($payload);
break;
case 'comment_create':
$this->handleCommentCreated($payload);
break;
}
}
private function handleTaskCreated($payload)
{
// Handle new task creation
$taskId = $payload['task']['local_task_id'];
$projectId = $payload['task']['project_id'];
// Your custom logic here
// e.g., send notifications, update local database, etc.
}
private function handleTaskUpdated($payload)
{
// Handle task updates
// Your custom logic here
}
private function handleCommentCreated($payload)
{
// Handle new comments
// Your custom logic here
}
}
2. Queue Jobs
For better performance, process webhooks asynchronously using queue jobs:
// app/Listeners/ProcessBugherdWebhook.php
use Itul\BugherdAPI\Jobs\ProcessWebhookJob;
public function handle(WebhookReceived $event)
{
// Dispatch job to queue for processing
ProcessWebhookJob::dispatch($event->payload, $event->event_type)
->onQueue('webhooks'); // Use dedicated queue
}
Create a custom job:
// app/Jobs/ProcessBugherdWebhookJob.php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ProcessBugherdWebhookJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $payload;
public $eventType;
public function __construct($payload, $eventType)
{
$this->payload = $payload;
$this->eventType = $eventType;
}
public function handle()
{
// Process webhook payload
switch ($this->eventType) {
case 'task_create':
$this->syncTaskToLocalDatabase($this->payload);
$this->sendTaskCreatedNotification($this->payload);
break;
// Handle other event types...
}
}
private function syncTaskToLocalDatabase($payload)
{
// Sync BugHerd task with your local database
}
private function sendTaskCreatedNotification($payload)
{
// Send notifications to team members
}
}
3. Custom Webhook Handlers
Publish and customize the webhook handlers:
php artisan vendor:publish --tag=bugherd-webhook-handlers
This creates handler classes in app/Http/Controllers/Bugherd/
:
// app/Http/Controllers/Bugherd/TaskCreateHandler.php
namespace App\Http\Controllers\Bugherd;
use Itul\BugherdAPI\Events\WebhookReceived;
use Itul\BugherdAPI\Http\Controllers\WebhookHandlers\TaskCreateHandler as BaseHandler;
class TaskCreateHandler extends BaseHandler
{
public function handle(WebhookReceived $event)
{
$payload = $event->payload;
$task = $payload['task'];
// Your custom task creation logic
\Log::info('New BugHerd task created', [
'task_id' => $task['local_task_id'],
'project_id' => $task['project_id'],
'description' => $task['description']
]);
// Example: Create notification
$this->notifyTeam($task);
// Example: Update external system
$this->updateJiraTicket($task);
}
private function notifyTeam($task)
{
// Send team notification
}
private function updateJiraTicket($task)
{
// Update external ticket system
}
}
Webhook Payload Examples
Here are examples of what BugHerd sends for different events:
Task Created
{
"event": "task_create",
"task": {
"id": 12345,
"local_task_id": 42,
"project_id": 123,
"description": "Fix header navigation bug",
"priority": "high",
"status": "todo",
"created_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-15T10:30:00Z",
"assigned_to": {
"id": 456,
"email": "developer@example.com",
"name": "John Developer"
}
}
}
Task Updated
{
"event": "task_update",
"task": {
"id": 12345,
"local_task_id": 42,
"project_id": 123,
"description": "Fix header navigation bug",
"priority": "high",
"status": "doing",
"updated_at": "2024-01-15T14:20:00Z"
},
"changes": {
"status": {
"from": "todo",
"to": "doing"
}
}
}
Comment Created
{
"event": "comment_create",
"comment": {
"id": 789,
"text": "This has been fixed and is ready for testing",
"task_id": 12345,
"project_id": 123,
"created_at": "2024-01-15T16:45:00Z",
"user": {
"id": 456,
"email": "developer@example.com",
"name": "John Developer"
}
}
}
Testing Webhooks
1. Local Development with ngrok
For local testing, use ngrok to expose your local server:
# Install ngrok and expose your local server
ngrok http 8000
# Use the ngrok URL for your webhook
https://abc123.ngrok.io/api/bugherd/webhook
2. Webhook Testing Command
Create a test command to simulate webhook calls:
// app/Console/Commands/TestBugherdWebhook.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Itul\BugherdAPI\Events\WebhookReceived;
class TestBugherdWebhook extends Command
{
protected $signature = 'bugherd:test-webhook {event=task_create}';
protected $description = 'Test BugHerd webhook processing';
public function handle()
{
$eventType = $this->argument('event');
$samplePayload = [
'task' => [
'id' => 12345,
'local_task_id' => 42,
'project_id' => 123,
'description' => 'Test webhook task',
'priority' => 'high',
'status' => 'todo'
]
];
// Fire the webhook event
event(new WebhookReceived($samplePayload, $eventType));
$this->info("Test webhook '{$eventType}' fired successfully!");
}
}
Run the test:
php artisan bugherd:test-webhook task_create
Webhook Debugging
Enable debug mode to log all webhook activity:
BUGHERD_DEBUG=true
This will log:
- Incoming webhook payloads
- Processing time
- Any errors during processing
- Event handler execution
Check the logs:
tail -f storage/logs/laravel.log | grep "BugHerd"
Core Classes
BugherdAPI
Overview
The main API client that handles all HTTP requests, caching, rate limiting, and input validation. Provides both instance and static methods for backwards compatibility.
Available Methods and Arguments
Method | Arguments | Description |
---|---|---|
sendRequest() | string $type, string $endpoint, array $data = [] | Send API request with validation |
getRateLimitStatus() | None | Get current rate limit status |
canMakeRequest() | None | Check if request can be made |
waitForRateLimit() | int $maxSeconds | Wait for rate limit reset |
Static Methods (Backwards Compatible):
| Method | Arguments | Description |
|--------|-----------|-------------|
| getUserProjects()
| None | Get user projects |
| getProjects()
| None | Get cached projects |
| getUsers()
| None | Get cached users |
| sendGet()
| string $endpoint, array $data
| Send GET request |
| sendPost()
| string $endpoint, array $data
| Send POST request |
| sendPut()
| string $endpoint, array $data
| Send PUT request |
| sendDelete()
| string $endpoint
| Send DELETE request |
BugherdModel
Overview
Base model class that provides Eloquent-style functionality for all BugHerd resources. All model classes extend this base class.
Available Methods and Arguments
Method | Arguments | Description |
---|---|---|
find() | $id | Find resource by ID |
list() | array $params = [] | List resources with optional filtering |
details() | None | Get detailed resource information |
hasMany() | string $model, ...$args | Define has-many relationships |
belongsTo() | string $model, $id | Define belongs-to relationships |
Advanced Features
Bulk Operations
Overview
Efficiently manage multiple resources at once with bulk operations. Designed for handling large-scale task management scenarios.
Available Methods and Arguments
Method | Arguments | Description |
---|---|---|
moveTasks() | int $sourceProjectId, int $destinationProjectId, array $taskIds | Move multiple tasks between projects |
bulkUpdateTasks() | int $projectId, array $taskIds, array $updates | Update multiple tasks at once |
getSummary() | array $results | Get summary of bulk operations |
Examples
Move Tasks:
use Itul\BugherdAPI\BugherdBulkOperations;
// Move multiple tasks from one project to another
$success = BugherdBulkOperations::moveTasks(
123, // source project ID
456, // destination project ID
[1, 2, 3, 4, 5] // array of task local IDs to move
);
if ($success) {
echo "Tasks moved successfully!";
}
Update Tasks:
// Bulk update multiple tasks in project 123
$results = BugherdBulkOperations::bulkUpdateTasks(
123, // project ID
[1, 2, 3], // array of task local IDs
[ // updates to apply
'status' => 'closed',
'resolution' => 'fixed'
]
);
// Get summary of operations
$summary = BugherdBulkOperations::getSummary($results);
echo "Updated: {$summary['successful']}, Failed: {$summary['failed']}";
Archive Tasks:
// Archive multiple tasks at once
$taskIds = [4, 5, 6, 7, 8]; // local task IDs
$projectId = 123; // project ID
$results = [];
foreach ($taskIds as $taskId) {
$task = BugherdProjectTask::findByLocalId($projectId, $taskId);
$results[] = $task->archive();
}
API Utilities
Overview
Utility functions for API management, health checking, and diagnostics. Useful for monitoring and troubleshooting your BugHerd integration.
Available Methods and Arguments
Method | Arguments | Description |
---|---|---|
validateApiKey() | None | Validate current API key |
getRateLimitStatus() | None | Get detailed rate limit status |
getApiHealth() | None | Get API health status |
clearBugherdCache() | None | Clear BugHerd-specific caches |
getPackageInfo() | None | Get package information |
testConnection() | None | Test connection with diagnostics |
Examples
Validate API Key:
use Itul\BugherdAPI\BugherdApiUtils;
if (BugherdApiUtils::validateApiKey()) {
echo "API key is valid!";
} else {
echo "API key is invalid or expired.";
}
API Health:
$health = BugherdApiUtils::getApiHealth();
if ($health['status'] === 'healthy') {
echo "BugHerd API is operational";
echo "Response time: {$health['response_time']}ms";
} else {
echo "BugHerd API has issues: " . $health['message'];
}
Test Connection:
$results = BugherdApiUtils::testConnection();
echo "Connection Status: " . ($results['success'] ? 'OK' : 'Failed') . "\n";
echo "API Endpoint: {$results['endpoint']}\n";
echo "Response Time: {$results['response_time']}ms\n";
if (!$results['success']) {
echo "Error: {$results['error']}\n";
}
Exceptions
Overview
Comprehensive exception handling with custom exception classes for different error scenarios. Helps with debugging and error management.
Available Classes
Exception Class | Description |
---|---|
BugherdException | Base exception class for all BugHerd-related errors |
BugherdAuthenticationException | Authentication and API key related errors |
BugherdRateLimitException | Rate limit exceeded errors |
BugherdNotFoundException | Resource not found errors |
BugherdValidationException | Input validation errors |
BugherdConfigurationException | Configuration-related errors |
Examples
use Itul\BugherdAPI\BugherdProject;
use Itul\BugherdAPI\Exceptions\BugherdException;
use Itul\BugherdAPI\Exceptions\BugherdAuthenticationException;
use Itul\BugherdAPI\Exceptions\BugherdRateLimitException;
use Itul\BugherdAPI\Exceptions\BugherdNotFoundException;
use Itul\BugherdAPI\Exceptions\BugherdValidationException;
try {
// Try to find project with ID 999
$project = BugherdProject::find(999);
} catch (BugherdNotFoundException $e) {
// Handle project not found (project ID 999 doesn't exist)
echo "Project not found: " . $e->getMessage();
} catch (BugherdAuthenticationException $e) {
// Handle authentication error (invalid API key)
echo "Authentication failed: " . $e->getMessage();
// Check API key configuration
} catch (BugherdRateLimitException $e) {
// Handle rate limit exceeded (too many API requests)
echo "Rate limit exceeded: " . $e->getMessage();
// Rate limit details available in exception message
sleep(60); // Wait before retrying
} catch (BugherdValidationException $e) {
// Handle validation error (invalid input data)
echo "Validation error: " . $e->getMessage();
// Check input data
} catch (BugherdException $e) {
// Handle general API errors
echo "BugHerd API error: " . $e->getMessage();
}
Credits
- Brandon Moore - Initial development - iTul
- BugHerd - API and platform - BugHerd.com