Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Sanitycheck Bundle Laravel Package

chameleon-system/sanitycheck-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require chameleon-system/sanitycheck-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        ChameleonSystem\SanityCheckBundle\SanityCheckBundle::class => ['all' => true],
    ];
    
  2. Define a Basic Check Create a custom check class (e.g., src/Check/MyDiskSpaceCheck.php):

    namespace App\Check;
    
    use SanityCheck\Check\CheckInterface;
    
    class MyDiskSpaceCheck implements CheckInterface
    {
        public function check(): bool
        {
            $freeSpace = disk_free_space('/');
            return $freeSpace > 1024 * 1024 * 1024; // At least 1GB free
        }
    }
    
  3. Register the Check Add it to the container in config/services.yaml:

    services:
        App\Check\MyDiskSpaceCheck:
            tags: ['sanitycheck.check']
    
  4. Run Checks via CLI Execute checks programmatically or via a command:

    php bin/console sanitycheck:run
    

First Use Case

Use SanityCheck in a pre-deployment hook (e.g., deploy.php):

use Symfony\Component\HttpKernel\KernelInterface;
use SanityCheck\SanityCheck;

$kernel = new AppKernel('prod', false);
$kernel->boot();
$sanityCheck = new SanityCheck($kernel->getContainer());
$results = $sanityCheck->runChecks();

if (!$results->isValid()) {
    throw new \RuntimeException('Sanity checks failed: ' . $results->getErrors());
}

Implementation Patterns

Common Workflows

  1. Pre-Request Checks (Symfony Middleware) Use middleware to validate system state before processing requests:

    namespace App\Middleware;
    
    use SanityCheck\SanityCheck;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\HttpKernel\HttpKernelInterface;
    
    class SanityCheckMiddleware
    {
        public function __invoke(HttpKernelInterface $kernel, Response $response)
        {
            $sanityCheck = new SanityCheck($kernel->getContainer());
            $results = $sanityCheck->runChecks(['disk_space', 'database_connection']);
    
            if (!$results->isValid()) {
                return new Response('System checks failed: ' . $results->getErrors(), 503);
            }
    
            return $kernel->handle($request, $response->create($kernel->getRequest()));
        }
    }
    
  2. Scheduled Checks (Cron Jobs) Integrate with Laravel’s task scheduler (app/Console/Kernel.php):

    protected function schedule(Schedule $schedule)
    {
        $schedule->command('sanitycheck:run --format=json')
                 ->dailyAt('3:00')
                 ->emailOutputTo('admin@example.com');
    }
    
  3. Dynamic Check Registration Register checks conditionally (e.g., based on environment):

    # config/packages/sanitycheck.yaml
    sanitycheck:
        checks:
            - '%kernel.environment% == "prod" ? App\Check\ProdChecks : App\Check\DevChecks'
    
  4. Check Dependencies Chain checks to enforce logical dependencies:

    class DatabaseCheck implements CheckInterface
    {
        public function check(): bool
        {
            return DB::connection()->getPdo() !== null;
        }
    }
    
    class CacheCheck implements CheckInterface
    {
        public function check(): bool
        {
            return Cache::store('file')->get('test') === 'test';
        }
    }
    

Integration Tips

  • Laravel-Specific: Use Laravel’s Artisan commands to trigger checks:
    php artisan sanitycheck:run --checks="database,queue"
    
  • Logging: Pipe results to Laravel’s logger:
    $results = $sanityCheck->runChecks();
    \Log::info('SanityCheck Results', ['valid' => $results->isValid(), 'errors' => $results->getErrors()]);
    
  • API Responses: Return check results as JSON for monitoring:
    return response()->json([
        'status' => $results->isValid() ? 'healthy' : 'unhealthy',
        'errors' => $results->getErrors(),
    ]);
    

Gotchas and Tips

Pitfalls

  1. Check Order Matters

    • If Check A depends on Check B, ensure B runs first. Use tags or explicit ordering:
      # config/services.yaml
      services:
          App\Check\DatabaseCheck:
              tags: ['sanitycheck.check', { priority: 10 }] # Lower priority = runs first
      
  2. Performance Overhead

    • Avoid heavy checks (e.g., full database migrations) in middleware. Reserve them for CLI or cron.
  3. Symfony vs. Laravel Quirks

    • Dependency Injection: Laravel’s service container differs from Symfony’s. Use app() helper or bind services explicitly:
      $sanityCheck = new SanityCheck(app());
      
    • Configuration: Prefix Symfony configs with sanitycheck. (e.g., sanitycheck.checks).
  4. False Positives

    • Checks like file_permissions may fail intermittently (e.g., due to temporary locks). Add retries or grace periods:
      public function check(): bool
      {
          return file_exists('/tmp/required-file') && !is_writable('/tmp/required-file');
      }
      

Debugging

  • Verbose Output: Run checks with --verbose for detailed logs:
    php bin/console sanitycheck:run --verbose
    
  • Check Isolation: Test individual checks:
    php bin/console sanitycheck:run --checks="App\Check\MyDiskSpaceCheck"
    
  • Symfony Debug Toolbar: Use the sanitycheck:debug command to inspect registered checks.

Extension Points

  1. Custom Check Formats Extend SanityCheck\Result\ResultInterface to add custom metadata:

    class CustomResult implements ResultInterface
    {
        public function getSeverity(): string
        {
            return $this->severity ?? 'warning';
        }
    }
    
  2. Event Dispatching Trigger events when checks pass/fail (e.g., using Symfony’s EventDispatcher):

    use Symfony\Component\EventDispatcher\EventDispatcherInterface;
    
    $dispatcher = new EventDispatcher();
    $dispatcher->addListener('sanitycheck.failed', function ($event) {
        // Send alert (e.g., Slack, PagerDuty)
    });
    
  3. Check Templates Create reusable check templates for common scenarios (e.g., database, queue, storage):

    abstract class BaseCheck implements CheckInterface
    {
        abstract protected function getResource(): string;
    
        public function check(): bool
        {
            return file_exists($this->getResource());
        }
    }
    
  4. Laravel Notifications Integrate with Laravel’s notification system for failed checks:

    use Illuminate\Notifications\Notifiable;
    
    class SanityCheckFailed implements ShouldQueue
    {
        use Notifiable;
    
        public function via($notifiable)
        {
            return ['database'];
        }
    
        public function toMail($notifiable)
        {
            return (new MailMessage)
                ->line('Sanity check failed: ' . $this->error);
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope