rconfig/laravel-zabbix

Laravel-first Zabbix JSON-RPC API client with fluent, testable DX.

0.1.1 2025-08-09 08:28 UTC

This package is auto-updated.

Last update: 2025-08-09 08:33:28 UTC


README

Tests License PHP Version Laravel Version

A Laravel-first, developer-friendly client for the Zabbix JSON-RPC API that makes monitoring integrations a breeze, developed by rConfig.

✨ Features

  • 🎯 Fluent, Eloquent-style queries for hosts and host groups
  • πŸš€ First-class developer experience with expressive, chainable methods
  • πŸ§ͺ Local testing without a live Zabbix server via HTTP fakes
  • πŸ”§ Optional real server integration for end-to-end testing
  • πŸ“¦ Laravel package best practices with auto-discovery
  • πŸ”Œ Extensible design for additional Zabbix endpoints

πŸ“¦ Installation

Install via Composer:

composer require rconfig/laravel-zabbix

The service provider will be auto-discovered. Optionally publish the config:

php artisan vendor:publish --tag=zabbix-config

βš™οΈ Configuration

Environment Variables

# Server connection
ZABBIX_BASE_URL=https://zabbix.example.com
ZABBIX_ENDPOINT=/api_jsonrpc.php

# Authentication (use token when possible)
ZABBIX_API_TOKEN=your_api_token_here

# Legacy fallback
ZABBIX_USERNAME=Admin
ZABBIX_PASSWORD=zabbix

# HTTP client settings
ZABBIX_TIMEOUT=15
ZABBIX_RETRIES=2

# Testing mode
ZABBIX_FAKE_BY_DEFAULT=true

Config File

The config file at config/zabbix.php provides sensible defaults:

return [
    'base_url' => env('ZABBIX_BASE_URL', 'http://localhost'),
    'endpoint' => env('ZABBIX_ENDPOINT', '/api_jsonrpc.php'),
    
    // Prefer API token (Zabbix 5.4+)
    'token' => env('ZABBIX_API_TOKEN'),
    
    // Legacy authentication
    'username' => env('ZABBIX_USERNAME'),
    'password' => env('ZABBIX_PASSWORD'),
    
    // HTTP settings
    'timeout' => (int) env('ZABBIX_TIMEOUT', 15),
    'retries' => (int) env('ZABBIX_RETRIES', 2),
    'retry_sleep_ms' => (int) env('ZABBIX_RETRY_SLEEP_MS', 250),
    
    // Testing
    'fake_by_default' => env('ZABBIX_FAKE_BY_DEFAULT', true),
];

πŸš€ Quick Start

use Rconfig\Zabbix\Facades\Zabbix;

// Get API version
$version = Zabbix::apiVersion(); // "7.0.0"

// List all hosts
$hosts = Zabbix::hosts()->all();

// Find hosts with filters
$activeLinux = Zabbix::hosts()->where([
    'status' => 0, 
    'name' => 'linux-server'
]);

// Create a new host
$newHost = Zabbix::hosts()->create([
    'host' => 'app-01',
    'interfaces' => [[
        'type' => 1, 'main' => 1, 'useip' => 1,
        'ip' => '10.0.0.50', 'port' => '10050'
    ]],
    'groups' => [['groupid' => '2']],
]);

πŸ” Fluent Queries

Build complex queries with an Eloquent-style fluent interface:

Hosts

$hosts = Zabbix::hosts()->get(
    Zabbix::hosts()->query()
        ->select(['hostid', 'host', 'status'])
        ->withInterfaces()
        ->withGroups()
        ->where(['status' => 0])
        ->limit(50)
        ->sort('host')
);

Host Groups

$groups = Zabbix::hostGroups()->get(
    Zabbix::hostGroups()->query()
        ->select(['groupid', 'name'])
        ->limit(20)
);

πŸ“Š Version Matrix & Compatibility

Zabbix Version Tested Minor Notes
6.0 LTS 6.0.29 Fully supported. apiinfo.version requires auth in some setups.
7.x 7.0.2 Fully supported. Some methods differ slightly in param requirements.

We recommend running your integration tests against both LTS and current major to catch method or parameter changes early.

🚫 Unsupported Operations

Some Zabbix API resources do not implement all CRUD operations.
For example, certain system resources cannot be created or deleted.

In these cases:

  • Methods like create(), update(), or delete() will throw an UnsupportedOperationException
  • This makes it clear the operation isn’t available for that resource, rather than failing silently.

Example:

use Rconfig\Zabbix\Exceptions\UnsupportedOperationException;

try {
    Zabbix::apiinfo()->delete(['id' => 1]);
} catch (UnsupportedOperationException $e) {
    echo $e->getMessage(); // "Delete is not supported for Apiinfo resource"
}
 

---

## πŸ›‘οΈ Lightweight Parameter Validation

An **optional** guard can warn or throw if obviously invalid parameters are passed.
This is not a full schema validator β€” just common-sense checks to help catch mistakes early.

* Wrong data types for known fields
* Mutually exclusive params used together
* Missing required params for certain calls

Enable warnings in `.env`:

```env
ZABBIX_PARAM_VALIDATION=true

Example:

// Will trigger a warning about 'limit' being a string instead of an integer
Zabbix::hosts()->get(['limit' => 'fifty']);

πŸ” Authentication

API Token (Recommended)

For Zabbix 5.4+ with API tokens:

ZABBIX_API_TOKEN=your_api_token_here

Username/Password

Legacy authentication fallback:

ZABBIX_USERNAME=Admin
ZABBIX_PASSWORD=zabbix

The package automatically chooses the best authentication method available.

πŸ§ͺ Testing

Fake Mode (Default)

Perfect for local development and unit testing:

ZABBIX_FAKE_BY_DEFAULT=true

All API calls return realistic mock data without needing a real Zabbix server.

Integration Testing

Test against a real Zabbix server:

RUN_ZABBIX_INTEGRATION=1
ZABBIX_BASE_URL=https://zabbix.example.com
ZABBIX_API_TOKEN=your_token

Example Test

it('fetches hosts via fluent query', function () {
    $hosts = Zabbix::hosts()->all();
    expect($hosts)->toBeArray()->not->toBeEmpty();
});

⚠️ Error Handling

The package provides specific exceptions for different error types:

use Rconfig\Zabbix\Exceptions\ZabbixException;
use Rconfig\Zabbix\Exceptions\ZabbixHttpException;

try {
    $hosts = Zabbix::hosts()->all();
} catch (ZabbixException $e) {
    // API-level errors (invalid params, auth issues, etc.)
    logger()->error('Zabbix API error: ' . $e->getMessage());
} catch (ZabbixHttpException $e) {
    // HTTP transport errors (timeouts, connectivity, etc.)
    logger()->error('Zabbix HTTP error: ' . $e->getMessage());
}

πŸ› οΈ Local Development

Package Development Setup

For developing this package alongside a Laravel application:

/code
  β”œβ”€ myapp/                   # Your Laravel app
  └─ rconfig-laravel-zabbix/  # This package

1. Link the Package

In your Laravel app's composer.json:

{
  "repositories": [
    {
      "type": "path",
      "url": "../rconfig-laravel-zabbix",
      "options": { "symlink": true }
    }
  ]
}

2. Install the Package

cd myapp
composer require rconfig/laravel-zabbix:"dev-main"
php artisan vendor:publish --tag=zabbix-config

3. Test in Tinker

php artisan tinker
>>> use Rconfig\Zabbix\Facades\Zabbix;
>>> Zabbix::apiVersion()      // "7.0.0" (fake)
>>> Zabbix::hosts()->all()    // Mock data

4. Quick Test Route

// routes/web.php
Route::get('/zabbix-test', function () {
    return [
        'version' => Zabbix::apiVersion(),
        'hosts' => Zabbix::hosts()->all(5),
    ];
});

Here’s a clean way to add it to your main README so contributors (or future you) know exactly how to cut a release. I’d suggest adding a "Releases" or "Publishing" section at the bottom:

πŸ“¦ Publishing a New Release

We use Semantic Versioning for all releases.

1. Update the Changelog

  • Edit CHANGELOG.md
  • Add a new section at the top for the version you’re releasing:
## [0.1.0] - 2025-08-09
### Added
- Initial public release of the Laravel Zabbix client.
  • Commit the changes:
git add CHANGELOG.md
git commit -m "docs: update changelog for v0.1.0"
git push origin main

2. Tag the Release

Create an annotated Git tag and push it:

git tag -a v0.1.0 -m "v0.1.0 initial public release"
git push origin v0.1.0

3. Create the GitHub Release

  1. Go to the GitHub Releases page.
  2. Click Draft a new release.
  3. Select the tag you just pushed (v0.1.0).
  4. Set the title to match the tag (e.g. v0.1.0).
  5. Paste the changelog notes for that version.
  6. Publish the release.

πŸ’‘ Tip: If the Packagist webhook is active, the new version will appear there automatically within minutes.

πŸ—ΊοΈ Roadmap

Planned features for future releases:

  • Pagination Support
  • More fluent convenience methods

🀝 Contributing

We welcome contributions! Here's how to get started:

Development Setup

  1. Fork and clone the repository
  2. Install dependencies:
    composer install
  3. Run the test suite:
    vendor/bin/pest
  4. Make your changes in a feature branch
  5. Submit a pull request with a clear description

Coding Standards

  • Follow PSR-12 for PHP code style
  • Use Pint for automatic formatting. Push to main will fail if there are formatting issues.
    vendor/bin/pint
  • Keep methods small and expressive
  • Add tests for new features and bug fixes
  • Update documentation when applicable
  • Use meaningful commit messages

Running Tests

# Run all tests with fakes
vendor/bin/pest

# Run integration tests (requires real Zabbix server)
RUN_ZABBIX_INTEGRATION=1 \
ZABBIX_BASE_URL=https://your-zabbix.com \
ZABBIX_API_TOKEN=your_token \
vendor/bin/pest

πŸ“„ License

This package is open-sourced software licensed under the MIT license.

Code of Conduct

While we aren't directly affiliated with Zabbix or Laravel, but we follow their respective Codes of Conduct. We expect you to abide by these guidelines as well.

Authors

This library is created by rConfig Developers.

License

The MIT License (MIT). Please see License File for more information.

Built with ❀️ by rConfig for the Zabbix and Laravel communities