PHP code example of szczyglis / ultimate-chain-parser

1. Go to this page and download the library: Download szczyglis/ultimate-chain-parser 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/ */

    

szczyglis / ultimate-chain-parser example snippets


  

  // app.php

  rser\ChainParser;
  use Szczyglis\ChainParser\Input\TextInput;
  use Szczyglis\ChainParser\Options\ArrayOptions;

  $parser = new ChainParser();
  $parser->setInput(new TextInput('some text data that needs to be parsed'));
  $parser->add('parser', new ArrayOptions([
    // options here
  ]); 
  $parser->run();

  $result = $parser->renderOutput();
  $log = $parser->renderLog();

  echo $result;

  $parser = new ChainParser();  
  $parser
    ->add('cleaner', new ArrayOptions([
        //options
    ])
    ->add('parser', new ArrayOptions([
        //options
    ])
    ->add('limiter', new ArrayOptions([
        //options
    ]); 
  
  $parser->run();

    $options['regex_match'] = [
      'id' => [
         0 => '/^[\d]+$/',
      ],
      'name' => [
        0 => '/^[^\d]+/',
        1 => '/[^\d]+$/',
      ],
    ];

    $options['regex_ignore_before'] = [
      0 => '/^XYZ+$/',
      1 => '/^some unwanted data/',
    ];
  

    $options['regex_ignore_after'] = [
      0 => '/^XYZ+$/',
      1 => '/^some unwanted data/',
    ];
  

    $options['replace_field_before'] = [
      'id' => [
        0 => [
          'pattern' => '/^[\d]+$/',
          'replacement' => '12345',
        ],        
      ],
      'name' => [
        0 => [
          'pattern' => '/^([^\d]+)/',
          'replacement' => '$1',
        ], 
        1 => [
          'pattern' => '/^([A-Z]+)/',
          'replacement' => 'abc$1',
        ],        
      ],
    ];
  

    $options['replace_field_after'] = [
      'id' => [
        0 => [
          'pattern' => '/^[\d]+$/',
          'replacement' => '12345',
        ],        
      ],
      'name' => [
        0 => [
          'pattern' => '/^([^\d]+)/',
          'replacement' => '$1',
        ],        
      ],
    ];

    $options['replace_block_before'] = [
      0 => [
        'pattern' => '/^[\d]+$/',
        'replacement' => '12345',
      ]
      1 => [
        'pattern' => '/^([^\d]+)/',
        'replacement' => '$1',
      ],
    ];

    $options['replace_block_after'] = [
      0 => [
        'pattern' => '/^[\d]+$/',
        'replacement' => '12345',
      ]
      1 => [
        'pattern' => '/^([^\d]+)/',
        'replacement' => '$1',
      ],
    ];

    $options['fields'] = [
      'id',
      'title',
      'actor',
      'description',
    ];

    $options['output_fields'] = [
      'id',
      'title',
      'actor',
      'description',
    ];


    $options['range'] = [
      0 => 0,
      1 => 3,
      2 => [
        'from' => 5
        'to' => 7,
      ],
      3 => [
        'from' => 15,
        'to' => null,
      ],
      4 => [
        'from' => null,
        'to' => 20,
      ],
    ];
  

    $options['regex_allow'] = [
      0 => '/^XYZ+$/',
      1 => '/^ZYX+$/',
    ];

  

    $options['range'] = [
      0 => 0,
      1 => 3,
      2 => [
        'from' => 5
        'to' => 7,
      ],
      3 => [
        'from' => 15,
        'to' => null,
      ],
      4 => [
        'from' => null,
        'to' => 20,
      ],
    ];
  

    $options['regex_deny'] = [
      0 => '/^XYZ+$/',
      1 => '/^ZYX+$/',
    ];

  

    $options['regex'] = [
      0 => [
        'pattern' => '/^[\d]+$/',
        'replacement' => '12345',
      ]
      1 => [
        'pattern' => '/^([^\d]+)/',
        'replacement' => '$1',
      ],
    ];
  

    $options['range'] = [
      0 => 0,
      1 => 3,
      2 => [
        'from' => 5
        'to' => 7,
      ],
      3 => [
        'from' => 15,
        'to' => null,
      ],
      4 => [
        'from' => null,
        'to' => 20,
      ],
    ];
  
  


namespace App;

use Szczyglis\ChainParser\Config\YamlConfig;


//...

$parser->setConfig(new YamlConfig('/path/to/config.yaml'));



namespace App;

use Szczyglis\ChainParser\Config\ArrayConfig;

//...

$parser->setConfig(new ArrayConfig([
  'key' => 'value',
]));



namespace App;

use Szczyglis\ChainParser\Logger\ArrayLogger;
use Szczyglis\ChainParser\Logger\PsrLogger;
use Szczyglis\ChainParser\Logger\ConsoleLogger;


//...

$parser->addLogger(new ArrayLogger());
$parser->addLogger(new PsrLogger('/path/to/logfile'));
$parser->addLogger(new ConsoleLogger());

  
  ...
$parser->run();

$log = $parser->renderLog();

dump($log);

$parser->run();

$output = $parser->getOutput();
$log = $output->get('logs');
dump($log);
  


// MyConfig.php

namespace App;

use Szczyglis\ChainParser\Contract\ConfigInterface;
use Szczyglis\ChainParser\Helper\AbstractInput;

class MyConfig implements ConfigInterface
{
  private $config;

  public function __construct(array $config)
  {
    $this->config = $config;
  }

  public function get(string $key)
  {
    if (array_key_exists($key, $this->config)) {
      return $this->config[$key];
    }   
  }

  public function set(string $key, $value)
  {
    $this-config[$key] = $value;    
  }

  public function has(string $key)
  {
    if (array_key_exists($key, $this->config)) {
      return true;
    }   
  }

  public function all()
  {
    return $this->config;
  }
}





// app.php

use Szczyglis\ChainParser\ChainParser;
use App\MyConfig;

$parser = new ChainParser();
$parser->setConfig(new MyConfig([
  'foo' => 'bar',
]));

// rest of initialization, config, etc...

$parser->run();
$parser->renderOutput();
  


// MyInput.php

namespace App;

use Szczyglis\ChainParser\Contract\InputInterface;
use Szczyglis\ChainParser\Helper\AbstractInput;

class MyInput extends AbstractInput implements InputInterface
{
  private $input;
  private $dataset = [];

  public function __construct(string $input)
  {
    $this->input = $input;
  }

  public function getInput()
  {
    return $this->input;
  }

  public function getDataset()
  {
    return $this->dataset;
  }
}





// app.php

use Szczyglis\ChainParser\ChainParser;
use App\MyInput;

$parser = new ChainParser();
$parser->setInput(new MyInput('some input data here...'));

// rest of initialization, config, etc...

$parser->run();
$parser->renderOutput();
  


// MyLogger.php

namespace App;

use Szczyglis\ChainParser\Contract\LoggerInterface;
use Szczyglis\ChainParser\Helper\AbstractLogger;

class MyLogger extends AbstractLogger implements LoggerInterface
{
  private $logs;

  public function addMessage(string $message, array $data)
  {
    $this->logs[] = $message;
  }

  // ...rest of code
}





// app.php

use Szczyglis\ChainParser\ChainParser;
use App\MyLogger;

$parser = new ChainParser();
$parser->addLogger(new MyLogger());

// rest of initialization, config, etc...

$parser->run();
$parser->renderOutput();
  


// MyOptions.php

namespace App;

use Szczyglis\ChainParser\Contract\OptionsInterface;
use Szczyglis\ChainParser\Helper\AbstractOptions;

class MyOptions extends AbstractOptions implements OptionsInterface
{
  private $options;

  public function __construct(string $options)
  {
    $this->options = $options;
  }

  public function get(string $key)
  {
    if (array_key_exists($key, $this->options)) {
      return $this->options[$key];
    }   
  }

  public function has(string $key)
  {
    if (array_key_exists($key, $this->options)) {
      return true;
    }   
  }

  public function all()
  {
    return $this->options;
  }
}




// app.php

use Szczyglis\ChainParser\ChainParser;
use App\MyOptions;

$parser = new ChainParser();
$parser->add('parser', new MyOptions([
    'foo' => 'bar',
]));

// rest of initialization, config, etc...

$parser->run();
$parser->renderOutput();



// MyPlugin.php


class MyPlugin ...

public function run(): bool
{
  // ...
}

public function registerOptions(): array
{
    return [
        'my_resolver' => [  // resolver name
            'foo', // option name
        ],
    ];
}



// app.php

use Szczyglis\ChainParser\ChainParser;
use Szczyglis\ChainParser\Options\FormOptions;
use App\MyResolver;

$parser = new ChainParser();
$parser->addResolver(new MyResolver());
$parser->add('parser', new FormOptions([
    'foo' => 'bar1;bar2;bar3', // option "foo" will be parsed with your resolver
]));

// rest of initialization, config, etc...

$parser->run();
$parser->renderOutput();



// MyPlugin.php

namespace App;

use Szczyglis\ChainParser\Contract\PluginInterface;
use Szczyglis\ChainParser\Contract\LoggableInterface;
use Szczyglis\ChainParser\Helper\AbstractPlugin;

class MyPlugin extends AbstractPlugin implements PluginInterface, LoggableInterface
{
  const NAME = 'my_plugin';

  public function run(): bool
  {
    $dataset = $this->getDataset(); // get previous data or from input

    // do something with data
    
    $this->setDataset($dataset); // return data to next element or to output

    return true;
  }

  public function getName(): string
  {
    return self::NAME;
  }
}



// app.php

use Szczyglis\ChainParser\ChainParser;
use Szczyglis\ChainParser\Input\TextInput;
use Szczyglis\ChainParser\Options\ArrayOptions;
use App\MyPlugin;

$parser = new ChainParser();
$parser->addPlugin(new MyPlugin());
$parser->setInput(new TextInput('foo'));
$parser->add('my_plugin', new ArrayOptions([
    'option' => 'value',
]));

// rest of initialization, config, etc...

$parser->run();
echo $parser->renderOutput(); // returns "Hello foo"




// MyWorker.php

namespace App;

use Szczyglis\ChainParser\Contract\WorkerInterface;
use Szczyglis\ChainParser\Contract\LoggableWorkerInterface;
use Szczyglis\ChainParser\Helper\AbstractWorker;

class MyWorker extends AbstractWorker implements WorkerInterface, LoggableWorkerInterface
{
  public function doSomeJob()
  {
    $var = $this->getVar('foo');
    $var++;
    $this->setVar('foo', $var);
  }
}




// MyPlugin.php

namespace App;

use Szczyglis\ChainParser\Contract\PluginInterface;
use Szczyglis\ChainParser\Contract\LoggableInterface;
use Szczyglis\ChainParser\Helper\AbstractPlugin;

class MyPlugin extends AbstractPlugin implements PluginInterface, LoggableInterface
{
  const NAME = 'my_plugin';

  public function run(): bool
  {
    $worker = $this->getWorker('my_worker');

    $foo = 10;
    $this->setVar('foo', $foo);

    $worker->doSomeJob();

    $bar = $this->getVar('foo');

    echo $bar; // will display 11

    return true;
  }

  public function registerWorkers(): array
  {
    return [
      'my_worker' => new MyWorker(),
    ];
  }
}

$this->setVar('foo', $bar); // sets var foo 
$foo = $this->getVar('foo'); // gets var foo



// MyPlugin.php

class MyPlugin ...

public function run(): bool
{
  $input = $this->getPrev('output'); // output from previous element in chain (or raw input if Plugin is first in chain)
  $prevDataset = $this->getPrev('dataset'); // output data (as `array`, not parsed) from previous element in chan
  $dataset = $this->get('dataset'); // get current dataset or output from previous element

  $rawInput = $this->get('input'); // raw, initial input

  $i = $this->getIteration(); // current iteration index in chain
  $config = $this->getConfig(); // returns config object

  $optionValue = $this->getOption('key'); // returns option value by key
  $allOptions = $this->getOptions(); // returns all options (as key => value array)

  $dataset = $this->getDataset(); // alias for $this->get('dataset');

  return true;
}




// MyPlugin.php


class MyPlugin ...

public function run(): bool
{
  $input = $this->getPrev('output');  // get parsed previous output or current input
  $dataset = $this->getDataset(); // get data form previous output or current input

  // do manipulation on data

  $this->setDataset($dataset);  // data will be sent to the next element in the chain as its input

  return true;
}


  $dataset = $this->iterateDataset($dataset, function($value) {
      return str_replace('A', 'B', $value);
  });



// MyPlugin.php


class MyPlugin ...

public function run(): bool
{
  // ...
}

public function registerOptions(): array
{
    return [
        'multiline' => [  // resolver name
            'my_pattern', // option name
        ],
        'range' => [ // resolver name
            'my_range', // option name
        ],
    ];
}



// MyPlugin.php

namespace App;

use Szczyglis\ChainParser\Contract\PluginInterface;
use Szczyglis\ChainParser\Contract\LoggableInterface;
use Szczyglis\ChainParser\Helper\AbstractPlugin;

class MyPlugin extends AbstractPlugin implements PluginInterface, LoggableInterface
{
  const NAME = 'my_plugin';

  public function run(): bool
  {
    $this->log('some message');

    return true;
  }
}




// MyWorker.php

namespace App;

use Szczyglis\ChainParser\Contract\WorkerInterface;
use Szczyglis\ChainParser\Contract\LoggableWorkerInterface;
use Szczyglis\ChainParser\Helper\AbstractWorker;

class MyWorker extends AbstractWorker implements WorkerInterface, LoggableWorkerInterface
{
  public function doSomeJob()
  {
    $this->log('some message');
  }
}

  


// MyRenderer.php

namespace App;

use Szczyglis\ChainParser\Contract\RendererInterface;
use Szczyglis\ChainParser\Helper\AbstractRenderer;

class MyRenderer extends AbstractRenderer implements RendererInterface
{
  public function renderOutput(?array $options = [])
  {
    foreach ($this->output as $item) {
      dump($item->get('output'));
    }
  }

  public function renderData(?array $options = [])
  {
    foreach ($this->output as $item) {
      dump($item->get('data'));
    }
  }

  public function renderLog(?array $options = [])
  {
    foreach ($this->output as $item) {
      $loggers = $item->getLog();
      foreach ($loggers as $lines) {
        foreach ($lines as $line) {
          dump($line);
        }       
      }
    }
  }
} 



// app.php

use Szczyglis\ChainParser\ChainParser;
use App\MyRenderer;

$parser = new ChainParser();
$parser->preventDefault(); // unregister default renderer
$parser->setRenderer(new MyRenderer()); // set your own

// rest of initialization, config, etc...

$parser->run();
$parser->renderOutput(); // will display dumped output from your renderer
$parser->renderData(); // will display dumped output from your renderer
$parser->renderLog(); // will display dumped output from your renderer




// app.php

inParser\ChainParser;
use Szczyglis\ChainParser\Core\ConfigGenerator;

$parser = new ChainParser;

// initialization, configuration, etc...

$parser->run();

$myConfig = (new ConfigGenerator())->build($parser, 'yaml'); // yaml | json

dump($myConfig); // displays configuration in Yaml format


  ./cmd.php chainparser ./example.txt ./example.yaml
  

  ./cmd.php chainparser ./example.txt ./example.yaml --log=0 --data=0
  

  ./cmd.php chainparser ./example.txt ./example.yaml --log=0 --data=0 > output.txt
  
 php


// MyResolver.php

namespace App;

use Szczyglis\ChainParser\Contract\OptionResolverInterface;
use Szczyglis\ChainParser\Helper\AbstractInput;

class MyResolver implements OptionResolverInterface
{
  public function resolve(string $key, $value)
  {
    return explode(';', $value);    
  }

  public function getName(): string
  {
    return 'my_resolver';
  }
}