Skip to content

API Reference

Jean-Marc Strauven edited this page Aug 1, 2025 · 1 revision

πŸ”Œ API Reference

Laravel Safeguard provides a comprehensive PHP API for programmatic access to security checking functionality.

πŸ—οΈ Core Classes

SafeguardManager

Main entry point for programmatic access.

use YourOrg\LaravelSafeguard\SafeguardManager;

$safeguard = app(SafeguardManager::class);

// Run all checks
$results = $safeguard->check();

// Run specific rules
$results = $safeguard->check(['app-debug-false', 'app-key-set']);

// Run with options
$results = $safeguard->check([], [
    'format' => 'json',
    'environment' => 'production',
    'fail_on_error' => false,
]);

RuleResult

Represents the result of a single rule check.

use YourOrg\LaravelSafeguard\Results\RuleResult;

// Create successful result
$result = RuleResult::passed('Check completed successfully');

// Create failed result
$result = RuleResult::failed('Security issue detected', [
    'recommendations' => ['Fix this issue', 'Update configuration'],
    'severity' => 'critical',
]);

// Create warning result
$result = RuleResult::warning('Potential issue detected');

// Access result data
$result->isSuccessful(); // bool
$result->getMessage(); // string
$result->getSeverity(); // string
$result->getRecommendations(); // array
$result->getMetadata(); // array

CheckResults

Collection of rule results with summary information.

use YourOrg\LaravelSafeguard\Results\CheckResults;

$results = $safeguard->check();

// Summary information
$results->getTotalChecks(); // int
$results->getPassedCount(); // int
$results->getFailedCount(); // int
$results->getWarningCount(); // int
$results->hasFailures(); // bool
$results->isSuccessful(); // bool

// Access individual results
foreach ($results->getResults() as $ruleName => $result) {
    echo "{$ruleName}: {$result->getMessage()}\n";
}

// Filter results
$failedResults = $results->getFailedResults();
$warningResults = $results->getWarningResults();
$passedResults = $results->getPassedResults();

// Export formats
$json = $results->toJson();
$array = $results->toArray();

🎯 Rule Development API

BaseRule

Abstract base class for all rules.

use YourOrg\LaravelSafeguard\Rules\BaseRule;
use YourOrg\LaravelSafeguard\Results\RuleResult;

class CustomSecurityRule extends BaseRule
{
    public function name(): string
    {
        return 'custom-security-check';
    }
    
    public function description(): string
    {
        return 'Checks custom security configuration';
    }
    
    public function severity(): string
    {
        return 'high'; // 'low', 'medium', 'high', 'critical'
    }
    
    public function environments(): array
    {
        return ['production', 'staging'];
    }
    
    public function check(): RuleResult
    {
        if ($this->isSecure()) {
            return RuleResult::passed('Security check passed');
        }
        
        return RuleResult::failed('Security issue detected', [
            'recommendations' => $this->getRecommendations(),
            'metadata' => $this->collectMetadata(),
        ]);
    }
    
    protected function isSecure(): bool
    {
        // Your security logic here
        return true;
    }
    
    protected function getRecommendations(): array
    {
        return [
            'Update your configuration',
            'Review security settings',
        ];
    }
    
    protected function collectMetadata(): array
    {
        return [
            'checked_at' => now()->toISOString(),
            'environment' => app()->environment(),
        ];
    }
}

RuleInterface

Interface that all rules must implement.

interface RuleInterface
{
    public function name(): string;
    public function description(): string;
    public function severity(): string;
    public function environments(): array;
    public function check(): RuleResult;
}

πŸ”§ Configuration API

Programmatic Configuration

use YourOrg\LaravelSafeguard\Configuration\SafeguardConfig;

// Create configuration instance
$config = new SafeguardConfig([
    'rules' => [
        'app-debug-false-in-production',
        'app-key-is-set',
    ],
    'environments' => ['production'],
    'output' => [
        'format' => 'json',
        'verbose' => true,
    ],
]);

// Use custom configuration
$results = $safeguard->checkWithConfig($config);

// Merge with existing configuration
$mergedConfig = $config->merge([
    'rules' => ['additional-rule'],
]);

Environment-Specific Configuration

$config = SafeguardConfig::forEnvironment('production', [
    'rules' => [
        'app-debug-false',
        'session-secure',
        'database-encrypted',
    ],
    'performance' => [
        'parallel_execution' => true,
    ],
]);

πŸ“Š Formatters API

Built-in Formatters

use YourOrg\LaravelSafeguard\Formatters\JsonFormatter;
use YourOrg\LaravelSafeguard\Formatters\HtmlFormatter;
use YourOrg\LaravelSafeguard\Formatters\JunitFormatter;

$results = $safeguard->check();

// JSON format
$jsonFormatter = new JsonFormatter();
$json = $jsonFormatter->format($results);

// HTML format
$htmlFormatter = new HtmlFormatter();
$html = $htmlFormatter->format($results);

// JUnit format
$junitFormatter = new JunitFormatter();
$xml = $junitFormatter->format($results);

Custom Formatter

use YourOrg\LaravelSafeguard\Formatters\FormatterInterface;
use YourOrg\LaravelSafeguard\Results\CheckResults;

class CustomFormatter implements FormatterInterface
{
    public function format(CheckResults $results): string
    {
        $output = "Custom Security Report\n";
        $output .= "======================\n\n";
        
        foreach ($results->getResults() as $ruleName => $result) {
            $status = $result->isSuccessful() ? 'PASS' : 'FAIL';
            $output .= "[{$status}] {$ruleName}: {$result->getMessage()}\n";
        }
        
        return $output;
    }
    
    public function getContentType(): string
    {
        return 'text/plain';
    }
}

// Register and use custom formatter
$formatter = new CustomFormatter();
$output = $formatter->format($results);

🎣 Events API

Available Events

use YourOrg\LaravelSafeguard\Events\CheckStarted;
use YourOrg\LaravelSafeguard\Events\CheckCompleted;
use YourOrg\LaravelSafeguard\Events\RuleExecuted;

// Listen to events
Event::listen(CheckStarted::class, function (CheckStarted $event) {
    Log::info('Security check started', [
        'rules' => $event->rules,
        'environment' => $event->environment,
    ]);
});

Event::listen(RuleExecuted::class, function (RuleExecuted $event) {
    Log::info('Rule executed', [
        'rule' => $event->ruleName,
        'result' => $event->result->isSuccessful(),
        'duration' => $event->duration,
    ]);
});

Event::listen(CheckCompleted::class, function (CheckCompleted $event) {
    Log::info('Security check completed', [
        'total' => $event->results->getTotalChecks(),
        'failed' => $event->results->getFailedCount(),
        'duration' => $event->duration,
    ]);
});

Custom Event Handling

class SecurityNotificationHandler
{
    public function handle(CheckCompleted $event): void
    {
        if ($event->results->hasFailures()) {
            // Send notification
            Notification::route('slack', config('slack.security-channel'))
                ->notify(new SecurityFailureNotification($event->results));
        }
    }
}

// Register handler
Event::listen(CheckCompleted::class, [SecurityNotificationHandler::class, 'handle']);

πŸ”Œ Extensions API

Rule Collections

use YourOrg\LaravelSafeguard\Collections\RuleCollection;

class SecurityRuleCollection extends RuleCollection
{
    public function rules(): array
    {
        return [
            new AppDebugRule(),
            new AppKeyRule(),
            new DatabaseSecurityRule(),
            new SessionSecurityRule(),
        ];
    }
    
    public function name(): string
    {
        return 'security-essentials';
    }
    
    public function description(): string
    {
        return 'Essential security rules for Laravel applications';
    }
}

// Register collection
$safeguard->registerCollection(new SecurityRuleCollection());

// Use collection
$results = $safeguard->checkCollection('security-essentials');

Rule Providers

use YourOrg\LaravelSafeguard\Providers\RuleProvider;

class CustomRuleProvider extends RuleProvider
{
    public function rules(): array
    {
        return [
            'database-security' => DatabaseSecurityRule::class,
            'file-permissions' => FilePermissionsRule::class,
            'api-security' => ApiSecurityRule::class,
        ];
    }
    
    public function collections(): array
    {
        return [
            'web-security' => WebSecurityCollection::class,
            'api-security' => ApiSecurityCollection::class,
        ];
    }
}

// Register provider
$safeguard->registerProvider(new CustomRuleProvider());

πŸ§ͺ Testing API

Rule Testing

use YourOrg\LaravelSafeguard\Testing\RuleTester;

class CustomRuleTest extends TestCase
{
    public function testCustomRule()
    {
        $tester = new RuleTester(new CustomSecurityRule());
        
        // Test passing scenario
        $this->mockSecureEnvironment();
        $result = $tester->run();
        $this->assertTrue($result->isSuccessful());
        
        // Test failing scenario
        $this->mockInsecureEnvironment();
        $result = $tester->run();
        $this->assertFalse($result->isSuccessful());
        $this->assertEquals('high', $result->getSeverity());
    }
    
    private function mockSecureEnvironment()
    {
        config(['app.debug' => false]);
        config(['app.key' => 'base64:' . base64_encode(random_bytes(32))]);
    }
    
    private function mockInsecureEnvironment()
    {
        config(['app.debug' => true]);
    }
}

Safeguard Testing

use YourOrg\LaravelSafeguard\Testing\SafeguardTester;

class SafeguardIntegrationTest extends TestCase
{
    public function testSecurityChecks()
    {
        $tester = new SafeguardTester();
        
        // Test specific rules
        $results = $tester->check(['app-debug-false', 'app-key-set']);
        
        $this->assertTrue($results->isSuccessful());
        $this->assertEquals(2, $results->getTotalChecks());
        $this->assertEquals(0, $results->getFailedCount());
        
        // Test with custom configuration
        $results = $tester->checkWithConfig([
            'rules' => ['custom-rule'],
            'environment' => 'testing',
        ]);
        
        $this->assertInstanceOf(CheckResults::class, $results);
    }
}

πŸ“š Related Documentation


🏠 Home | 🎨 Custom Rules | βš™οΈ Configuration | πŸ’‘ Examples

Clone this wiki locally