25/09
2016
Wallogit.com
2017 © Pedro Peláez
A class for parsing nginx config files in PHP
Read and create Nginx config files in php, (*2)
Use composer to to add the classes to your project, (*3)
composer require jorisros/nginxparser
Run in the main directory the following command, (*4)
./vendor/bin/phpunit tests
Examples to use the class, (*5)
Simple config file, (*6)
<?php
require __DIR__ . '/vendor/autoload.php';
use JorisRos\NginxParser\NginxParser;
use JorisRos\NginxParser\NginxElement;
$config = new NginxParser('server');
$location = new NginxParser('location','/');
$location->setRoot('/usr/share/nginx/html')
->setIndex(array('index.html', 'index.htm'));
$config ->setPort(80)
->setServerName(array('localhost','local','serveralias'))
->setAccessLog('/var/log/nginx/log/host.access.log')
->setLocation($location);
if($config->validate())
{
$strFile = $config->build();
file_put_contents('server.conf', $strFile);
}else{
foreach ($config->getValidatorErrors() as $error) {
# code...
}
}
It will result in, (*7)
server {
port 80;
server_name localhost;
server_alias local serveralias;
access_log /var/log/nginx/log/host.access.log;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
Read existing config file, (*8)
<?php
require __DIR__ . '/vendor/autoload.php';
use JorisRos\NginxParser\NginxParser;
use JorisRos\NginxParser\NginxElement;
$d = new NginxParser();
$objects = $d->readFromFile('Resources/nginx-config/nginx.conf');
//var_dump($objects);
foreach($objects as $object)
{
print($object->build());
}