donatj/printf-parser

PHP printf compatible printf string parser breaking printf strings into lexemes

v0.1.0 2019-03-18 17:21 UTC

This package is auto-updated.

Last update: 2020-01-29 20:25:23 UTC


README

Latest Stable Version Total Downloads License Build Status Scrutinizer Code Quality Code Coverage

Parses printf style strings, e.g. cats: %d into inspectable lexemes.

Requirements

  • php: >=7.1

Installing

Install the latest version with:

composer require 'donatj/printf-parser'

Example

Here is a simple example:

<?php

require __DIR__ . '/../vendor/autoload.php';

$emitter = new \donatj\Printf\LexemeEmitter();
$parser  = new \donatj\Printf\Parser($emitter);

$parser->parseStr('percent of %s: %d%%');

$lexemes = $emitter->getLexemes();

foreach( $lexemes as $lexeme ) {
	echo $lexeme->getLexItemType() . ' -> ';
	echo var_export($lexeme->getVal(), true);

	if( $lexeme instanceof \donatj\Printf\ArgumentLexeme ) {
		echo ' arg type: ' . $lexeme->argType();
	}

	echo PHP_EOL;
}

Output:

! -> 'percent of '
s -> 's' arg type: string
! -> ': '
d -> 'd' arg type: int
! -> '%'

Documentation

Class: \donatj\Printf\Parser

Parser implements a PHP Printf compatible Printf string parser.

Method: Parser->__construct

function __construct(\donatj\Printf\Emitter $emitter)

Parser constructor.

Parameters:
  • \donatj\Printf\Emitter $emitter - The given Emitter to emit Lexemes as parsed

Method: Parser->parseStr

function parseStr(string $string) : void

Parses a printf string and emit parsed lexemes to the configured Emitter

Class: \donatj\Printf\LexemeEmitter

Method: LexemeEmitter->getLexemes

function getLexemes() : \donatj\Printf\donatj\Printf\LexemeCollection

Return the Lexemes received by the emitter as an immutable LexemeCollection

Class: \donatj\Printf\LexemeCollection

LexemeCollection is an immutable iterable collection of Lexemes with ArrayAccess

Method: LexemeCollection->getInvalid

function getInvalid() : ?\donatj\Printf\donatj\Printf\Lexeme

Retrieve the first invalid Lexeme or null if all are valid.

This is useful for checking if a printf string parsed without error.

Method: LexemeCollection->toArray

function toArray() : array

Get the LexemeCollection as an Array

Returns:
  • \donatj\Printf\Lexeme[]

Method: LexemeCollection->argTypes

function argTypes() : array
Returns the list of expected arguments a 1-indexed map of the following
PrintfLexeme::ARG_TYPE_MISSING  
PrintfLexeme::ARG_TYPE_INT  
PrintfLexeme::ARG_TYPE_DOUBLE  
PrintfLexeme::ARG_TYPE_STRING  
Returns:
  • string[]