PHP code example of besnovatyj / yii2-cms-info

1. Go to this page and download the library: Download besnovatyj/yii2-cms-info 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/ */

    

besnovatyj / yii2-cms-info example snippets


abstract public function getName(): string;
abstract public function getCategory(): string;
abstract protected function checkAvailability(): bool;
abstract protected function collectMetrics(): array;

public function isAvailable(): bool;
public function getMetrics(): array;
protected function formatBytes(int $bytes, int $precision = 2): string;
protected function safeShellExec(string $command, int $timeout = 5): ?string;
protected function safeFileReadLines(string $path): ?array;

[
    'server' => [
        'hostname' => 'server-name',
        'serverAddr' => '192.168.1.100',
        'remoteAddr' => '192.168.1.50',
        'os' => 'Ubuntu 22.04 LTS',
        'kernel' => '5.15.0-91-generic',
        'architecture' => 'x86_64'
    ],
    'cpu' => [
        'model' => 'Intel(R) Xeon(R) CPU E5-2680 v4',
        'cores' => 8,
        'frequency' => '2.40 GHz',
        'cache' => '35840 KB',
        'bogomips' => '4800.00'
    ],
    'cpuUsage' => [
        'user' => 1234567,
        'nice' => 123,
        'system' => 234567,
        'idle' => 9876543,
        'iowait' => 1234,
        'irq' => 123,
        'softirq' => 234
    ],
    'memory' => [
        'total' => 16777216000,
        'totalFormatted' => '15.63 GB',
        'used' => 8388608000,
        'usedFormatted' => '7.81 GB',
        'usedPercent' => 50.0,
        'free' => 8388608000,
        'freeFormatted' => '7.81 GB',
        'buffers' => 524288000,
        'buffersFormatted' => '500 MB',
        'cached' => 2097152000,
        'cachedFormatted' => '2.00 GB'
    ],
    'disk' => [
        'total' => 107374182400,
        'totalFormatted' => '100 GB',
        'used' => 53687091200,
        'usedFormatted' => '50 GB',
        'free' => 53687091200,
        'freeFormatted' => '50 GB',
        'percent' => 50,
        'mount' => '/'
    ],
    'loadavg' => [
        '1min' => 0.52,
        '5min' => 0.48,
        '15min' => 0.45,
        'formatted' => '0.52 0.48 0.45'
    ],
    'network' => [
        'eth0' => [
            'rx' => 1234567890,
            'tx' => 987654321,
            'rxFormatted' => '1.15 GB',
            'txFormatted' => '942.23 MB'
        ],
        'lo' => [...]
    ],
    'uptime' => [
        'seconds' => 864000,
        'formatted' => '10 days, 0 hours'
    ],
    'temperature' => [
        'cpu' => 45.5 // в градусах Цельсия
    ]
]

[
    'version' => '8.4.0',
    'sapi' => 'fpm-fcgi',
    'os' => 'Linux',
    'architecture' => '64-bit',
    'memory' => [
        'current' => 2097152,
        'currentFormatted' => '2.00 MB',
        'peak' => 4194304,
        'peakFormatted' => '4.00 MB',
        'limit' => 134217728,
        'limitFormatted' => '128 MB',
        'usagePercent' => 1.56
    ],
    'limits' => [
        'maxExecutionTime' => 30,
        'maxInputTime' => 60,
        'postMaxSize' => '8M',
        'uploadMaxFilesize' => '2M',
        'maxFileUploads' => 20,
        'defaultSocketTimeout' => 60
    ],
    'opcache' => [
        'enabled' => true,
        'memoryUsage' => [
            'used' => 16777216,
            'usedFormatted' => '16.00 MB',
            'free' => 117440512,
            'freeFormatted' => '112.00 MB',
            'wasted' => 0,
            'wastedFormatted' => '0 B',
            'usagePercent' => 12.5
        ],
        'statistics' => [
            'hits' => 12345,
            'misses' => 123,
            'hitRate' => 99.01
        ]
    ],
    'extensions' => [
        'Core', 'date', 'libxml', 'openssl', 'pcre', ...
    ]
]

[
    'version' => '24.0.7',
    'containers' => [
        [
            'id' => 'abc123def456',
            'name' => 'yii2-cms-php-fpm-1',
            'state' => 'running',
            'status' => 'Up 2 hours',
            'image' => 'php:8.4-fpm-alpine3.23'
        ],
        // ... остальные контейнеры
    ],
    'images' => 15,
    'volumes' => 4,
    'networks' => 3
]

[
    'driver' => 'mysql',
    'version' => '8.0.35',
    'database' => 'yii2_cms',
    'charset' => 'utf8mb4',
    'size' => [
        'bytes' => 52428800,
        'formatted' => '50.00 MB'
    ],
    'tables' => [
        'count' => 45,
        'totalRows' => 123456,
        'dataSize' => [
            'bytes' => 41943040,
            'formatted' => '40.00 MB'
        ],
        'indexSize' => [
            'bytes' => 10485760,
            'formatted' => '10.00 MB'
        ]
    ],
    'connections' => [
        'current' => 5,
        'running' => 2,
        'cached' => 3,
        'created' => 150,
        'maxUsed' => 8
    ]
]

[
    'version' => '7.2.3',
    'uptime' => [
        'seconds' => 864000,
        'formatted' => '10 days'
    ],
    'clients' => [
        'connected' => 5,
        'blocked' => 0
    ],
    'memory' => [
        'used' => 2097152,
        'usedFormatted' => '2.00 MB',
        'peak' => 4194304,
        'peakFormatted' => '4.00 MB',
        'max' => 0,
        'maxFormatted' => 'Unlimited',
        'fragmentation' => 1.05
    ],
    'stats' => [
        'totalConnections' => 1234,
        'totalCommands' => 567890,
        'keyspaceHits' => 123456,
        'keyspaceMisses' => 1234,
        'hitRate' => 99.01
    ],
    'keyspace' => [
        'totalKeys' => 5678,
        'databases' => [
            'db0' => ['keys' => 5678, 'expires' => 234]
        ]
    ]
]

[
    'version' => '1.29.0',
    'serverSoftware' => 'nginx/1.29.0',
    'protocol' => 'HTTP/2.0',
    'http2' => true,
    'http3' => false,
    'https' => true,
    'scheme' => 'https',
    'gateway' => 'CGI/1.1',
    'tls' => [
        // state: 'ok' | 'plain' | 'absent' — самодиагностика проброса SSL_*
        'state' => 'ok',
        'protocol' => 'TLSv1.3',
        'cipher' => 'TLS_AES_256_GCM_SHA384'
    ],
    'build' => [
        'tlsLibrary' => 'OpenSSL 3.0.13',
        'modulesCount' => 27
    ]
]

[
    'yii' => [
        'version' => '2.0.49',
        'name' => 'Yii2 CMS',
        'id' => 'yii2-app'
    ],
    'environment' => [
        'environment' => 'dev',
        'debug' => true,
        'timezone' => 'Asia/Yekaterinburg',
        'language' => 'ru-RU'
    ],
    'cache' => [
        'enabled' => true,
        'class' => 'yii\\redis\\Cache',
        'keyPrefix' => 'yii2cms_'
    ],
    'session' => [
        'available' => true,
        'class' => 'yii\\redis\\Session',
        'timeout' => 3600
    ],
    'queue' => [
        'enabled' => true,
        'class' => 'yii\\queue\\redis\\Queue',
        'driver' => 'redis'
    ]
]

public function __construct(
    SystemMetricProvider $systemProvider,
    PhpMetricProvider $phpProvider,
    DockerMetricProvider $dockerProvider,
    DatabaseMetricProvider $databaseProvider,
    RedisMetricProvider $redisProvider,
    NginxMetricProvider $nginxProvider,
    ApplicationMetricProvider $applicationProvider
)

[
    'timestamp' => 1737249600,
    'timestampFormatted' => '2026-01-19 01:00:00',
    'system' => [...],      // SystemMetricProvider
    'php' => [...],         // PhpMetricProvider
    'docker' => [...],      // DockerMetricProvider
    'database' => [...],    // DatabaseMetricProvider
    'redis' => [...],       // RedisMetricProvider
    'nginx' => [...],       // NginxMetricProvider
    'application' => [...]  // ApplicationMetricProvider
]

[
    'timestamp' => 1737249603,
    'timestampFormatted' => '2026-01-19 01:00:03',
    'system' => [
        'available' => true,
        'cpuUsage' => [...],    // Текущее использование CPU
        'memory' => [...],      // Текущая память
        'disk' => [...],        // Текущий диск
        'loadavg' => [...],     // Load average
        'temperature' => [...]  // Температура
    ],
    'docker' => [
        'available' => true,
        'containers' => [...]   // Только статусы контейнеров
    ],
    'database' => [
        'available' => true,
        'connections' => [...]  // Только соединения
    ]
]

public function actionIndex(): string

public function actionApiMetrics(): Response

public function actionApiRealtime(): Response

public function actionApiDockerLogs(string $container, int $lines = 100): Response

public function actionExportJson(): Response

public function actionExportCsv(): Response


use Besnovatyj\Info\providers\*;
use Besnovatyj\Info\services\SysInfoService;

return [
    'singletons' => [
        SystemMetricProvider::class => SystemMetricProvider::class,
        PhpMetricProvider::class => PhpMetricProvider::class,
        DockerMetricProvider::class => DockerMetricProvider::class,
        DatabaseMetricProvider::class => DatabaseMetricProvider::class,
        RedisMetricProvider::class => RedisMetricProvider::class,
        NginxMetricProvider::class => NginxMetricProvider::class,
        ApplicationMetricProvider::class => ApplicationMetricProvider::class,
        SysInfoService::class => [
            'class' => SysInfoService::class,
            '__construct()' => [
                'systemProvider' => Instance::of(SystemMetricProvider::class),
                'phpProvider' => Instance::of(PhpMetricProvider::class),
                'dockerProvider' => Instance::of(DockerMetricProvider::class),
                'databaseProvider' => Instance::of(DatabaseMetricProvider::class),
                'redisProvider' => Instance::of(RedisMetricProvider::class),
                'nginxProvider' => Instance::of(NginxMetricProvider::class),
                'applicationProvider' => Instance::of(ApplicationMetricProvider::class),
            ],
        ],
    ],
];

public function getContainerConfig(): array
{
    return 

// В view: /app/Besnovatyj/Info/widgets/sysinfo/views/index.php
<div id="<?= Html::encode($widgetId) 

$config = [
    'updateInterval' => 3000,  // Интервал обновления (мс)
    'autoRefresh' => true,     // Включить auto-refresh
    'csrfToken' => Yii::$app->request->csrfToken,
    'endpoints' => [
        'metrics' => Url::to(['/info/backend/sys-info/api-metrics']),
        'realtime' => Url::to(['/info/backend/sys-info/api-realtime']),
        'dockerLogs' => Url::to(['/info/backend/sys-info/api-docker-logs']),
        'exportJson' => Url::to(['/info/backend/sys-info/export-json']),
        'exportCsv' => Url::to(['/info/backend/sys-info/export-csv']),
    ],
];

class SysInfoAsset extends AssetBundle
{
    public $sourcePath = __DIR__ . '/media';

    public $css = [
        'css/sysinfo.css',
    ];

    public $js = [
        'https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js',
        'js/dist/index.js',
    ];

    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap5\BootstrapAsset',
        'yii\bootstrap5\BootstrapPluginAsset',
    ];

    public $jsOptions = [
        'type' => 'module', // ES6 модули
    ];
}

// В контроллере
Yii::$app->request->csrfToken;

// В JS
headers: {
    'X-CSRF-Token': this.csrfToken
}

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::class,
            'rules' => [
                [
                    'allow' => true,
                    'roles' => ['@'], // Только авторизованные
                ],
            ],
        ],
    ];
}

protected function safeShellExec(string $command, int $timeout = 5): ?string
{
    if (!function_exists('shell_exec')) {
        return null;
    }

    $fullCommand = sprintf(
        'timeout %d %s 2>&1',
        $timeout,
        $command  // БЕЗ пользовательского ввода!
    );

    $output = @shell_exec($fullCommand);
    return $output !== null ? trim($output) : null;
}

$sql = "SELECT SUM(data_length + index_length)
        FROM information_schema.TABLES
        WHERE table_schema = :dbName";

$size = Yii::$app->db->createCommand($sql, [
    ':dbName' => $dbName  // Параметр, НЕ конкатенация!
])->queryScalar();

// Читаем файл один раз
$lines = file('/proc/stat');

// Парсим все метрики из одного массива
$cpuInfo = $this->parseCpuInfo($lines);
$cpuUsage = $this->parseCpuUsage($lines);

// НЕПРАВИЛЬНО
<div data-config='<?= $config 

// SysInfoAsset.php
public $js = [
    'https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js',
    'js/dist/index.js',
];
nginx
fastcgi_param SSL_PROTOCOL $ssl_protocol;
fastcgi_param SSL_CIPHER   $ssl_cipher;
json
{
    "timestamp": 1737249600,
    "timestampFormatted": "2026-01-19 01:00:00",
    "system": {...},
    "php": {...},
    "docker": {...},
    "database": {...},
    "redis": {...},
    "application": {...}
}
json
{
    "timestamp": 1737249603,
    "timestampFormatted": "2026-01-19 01:00:03",
    "system": {
        "available": true,
        "cpuUsage": {...},
        "memory": {...},
        "disk": {...},
        "loadavg": {...},
        "temperature": {...}
    },
    "docker": {
        "available": true,
        "containers": [...]
    }
}
typescript
// Статические данные (только при полной загрузке)
if (metrics.system?.available && metrics.system.server) {
    // Рендерить server info
}

// Динамические данные (обновляются всегда)
if (metrics.system?.available && metrics.system.memory) {
    // Рендерить memory с прогресс-баром
}
typescript
// PHP - проверяем вложенные объекты
if (metrics.php?.available && metrics.php.version) {
    const php = metrics.php;
    // memory.limitFormatted (НЕ memoryLimit!)
    // limits.maxExecutionTime (НЕ maxExecutionTime!)
}

// Database
if (metrics.database?.available && metrics.database.driver) {
    // tables.count (НЕ tableCount!)
    // connections.current (НЕ connections напрямую!)
}

// Redis
if (metrics.redis?.available && metrics.redis.version) {
    // uptime.formatted (НЕ uptimeFormatted!)
    // clients.connected (НЕ clients напрямую!)
    // memory.usedFormatted
    // keyspace.totalKeys (НЕ keys!)
}

// Application
if (metrics.application?.available && metrics.application.yii) {
    // yii.version (НЕ yiiVersion!)
    // environment.environment (НЕ environment напрямую!)
    // environment.debug
    // cache.class (НЕ cacheClass!)
}
json
{
    "timestamp": 1737249600,
    "timestampFormatted": "2026-01-19 01:00:00",
    "system": {
        "available": true,
        "server": {...},
        "cpu": {...},
        "cpuUsage": {...},
        "memory": {...},
        "disk": {...},
        "loadavg": {...},
        "network": {...},
        "uptime": {...},
        "temperature": {...}
    },
    "php": {
        "available": true,
        "version": "8.4.0",
        "memory": {...},
        "limits": {...},
        "opcache": {...},
        "extensions": [...]
    },
    "docker": {
        "available": true,
        "version": "24.0.7",
        "containers": [...],
        "images": 15,
        "volumes": 4,
        "networks": 3
    },
    "database": {
        "available": true,
        "driver": "mysql",
        "version": "8.0.35",
        "size": {...},
        "tables": {...},
        "connections": {...}
    },
    "redis": {
        "available": true,
        "version": "7.2.3",
        "uptime": {...},
        "clients": {...},
        "memory": {...},
        "stats": {...},
        "keyspace": {...}
    },
    "nginx": {
        "available": true,
        "version": "1.29.0",
        "protocol": "HTTP/2.0",
        "http2": true,
        "https": true,
        "tls": {...}
    },
    "application": {
        "available": true,
        "yii": {...},
        "environment": {...},
        "cache": {...},
        "session": {...},
        "queue": {...}
    }
}
json
{
    "timestamp": 1737249603,
    "timestampFormatted": "2026-01-19 01:00:03",
    "system": {
        "available": true,
        "cpuUsage": {...},
        "memory": {...},
        "disk": {...},
        "loadavg": {...},
        "temperature": {...}
    },
    "docker": {
        "available": true,
        "containers": [...]
    },
    "database": {
        "available": true,
        "connections": {...}
    }
}
json
{
    "success": true,
    "logs": "[2026-01-19 01:00:00] app.INFO: Message...\n[2026-01-19 01:00:01] ...",
    "lines": 100
}
typescript
// НЕПРАВИЛЬНО
php.memoryLimit         // Это объект!
database.connections    // Это объект!

// ПРАВИЛЬНО
php.memory.limitFormatted
database.connections.current
typescript
if (metrics.php?.available && metrics.php.version) {
    // Рендерить
}
// Если данных нет - НЕ очищать DOM (пропустить рендеринг)