A PHP parser for TOML

Overview

TOML parser for PHP

A PHP parser for TOML compatible with TOML v0.4.0.

Build Status Latest Stable Version Total Downloads

Support:

Gitter

Installation

Requires PHP >= 7.1.

Use Composer to install this package:

composer require yosymfony/toml

Usage

You can parse an inline TOML string or from a file:

To parse an inline TOML string:

use Yosymfony\Toml\Toml;

$array = Toml::Parse('key = [1,2,3]');

print_r($array);

To parse a TOML file:

$array = Toml::ParseFile('example.toml');

print_r($array);

Additionally, methods parse and parseFile accept a second argument called resultAsObject to return the result as an object based on stdClass.

$object = Toml::Parse('key = [1,2,3]', true);

TomlBuilder

You can create a TOML string with TomlBuilder. TomlBuilder uses a fluent interface for more readable code:

    use Yosymfony\Toml\TomlBuilder;

    $tb = new TomlBuilder();

    $result = $tb->addComment('Toml file')
        ->addTable('data.string')
        ->addValue('name', "Toml", 'This is your name')
        ->addValue('newline', "This string has a \n new line character.")
        ->addValue('winPath', "C:\\Users\\nodejs\\templates")
        ->addValue('literal', '@<\i\c*\s*>') // literals starts with '@'.
        ->addValue('unicode', 'unicode character: ' . json_decode('"\u03B4"'))

        ->addTable('data.bool')
        ->addValue('t', true)
        ->addValue('f', false)

        ->addTable('data.integer')
        ->addValue('positive', 25, 'Comment inline.')
        ->addValue('negative', -25)

        ->addTable('data.float')
        ->addValue('positive', 25.25)
        ->addValue('negative', -25.25)

        ->addTable('data.datetime')
        ->addValue('datetime', new \Datetime())

        ->addComment('Related to arrays')

        ->addTable('data.array')
        ->addValue('simple', array(1,2,3))
        ->addValue('multiple', array(
            array(1,2),
            array('abc', 'def'),
            array(1.1, 1.2),
            array(true, false),
            array( new \Datetime()) ))

        ->addComment('Array of tables')

        ->addArrayOfTable('fruit')                            // Row
            ->addValue('name', 'apple')
            ->addArrayOfTable('fruit.variety')
                ->addValue('name', 'red delicious')
            ->addArrayOfTable('fruit.variety')
                ->addValue('name', 'granny smith')
        ->addArrayOfTable('fruit')                            // Row
            ->addValue('name', 'banana')
            ->addArrayOfTable('fruit.variety')
                ->addValue('name', 'plantain')
        ->getTomlString();    // Generate the TOML string

The result:

#Toml file

[data.string]
name = "Toml" #This is your name
newline = "This string has a \n new line character."
winPath = "C:\\Users\\nodejs\\templates"
literal = '<\i\c*\s*>'
unicode = "unicode character: δ"

[data.bool]
t = true
f = false

[data.integer]
positive = 25 #Comment inline.
negative = -25

[data.float]
positive = 25.25
negative = -25.25

[data.datetime]
datetime = 2013-06-10T21:12:48Z

#Related to arrays

[data.array]
simple = [1, 2, 3]
multiple = [[1, 2], ["abc", "def"], [1.1, 1.2], [true, false], [2013-06-10T21:12:48Z]]

# Array of tables

[[fruit]]
name = "apple"

[[fruit.variety]]
name = "red delicious"

[[fruit.variety]]
name = "granny smith"

[[fruit]]
name = "banana"

[[fruit.variety]]
name = "plantain"

Limitations

The TomlBuilder class is an utility to get Toml strings that has the following limitations:

  • Only admits basic strings and literal strings.

Deprecated method

The following method will be eliminated in version 2.0.0

  • [TomlBuilder] addArrayTables

Contributing

When Contributing code to this library, you must follow its coding standards. Toml follows PSR-2 coding style. To ensure the CS, you can use the CLI tool PHP-CS-Fixer.

Unit tests

You can run the unit tests with the following command:

$ cd toml
$ composer test

License

This library is open-sourced software licensed under the MIT license.

Issues
  • fixed a bug when used the function

    fixed a bug when used the function "in_array"

    I used your code to convert a PHP array to a .toml file, but when I used TomlBuilder class to build my .toml file, the program always threw the DumpException. When my array included the zero element, your expression return true, made program stop.

    if (in_array($key, $this->keyListArryOfTables)) {
        throw new DumpException(
            sprintf('The table %s has already been defined as previous array of tables', $key)
        );
    }
    

    I debugged it and found this bug.document of in_array

    I added the third param true in your code, I guessed it would always suit for your scene. In that case, I could build my program easily.

    Additionally, there were some mistakes in the code. For example, the variable $this->keyListArryOfTables was a key=>value array, so I thought array_key_exists would be more correct than in_array.

    if (in_array($key, $this->keyListArryOfTables, true)) {
            throw new DumpException(
            sprintf('The table %s has already been defined as previous array of tables', $key)
        );
    }
    
    if (false == isset($this->keyListArryOfTables[$key])) {
            $this->keyListArryOfTables[$key] = 0;
            $this->addKeyToKeyList($key);
        } else {
            $counter = $this->keyListArryOfTables[$key] + 1;
            $this->keyListArryOfTables[$key] = $counter + 1;
    }
    
    opened by jkhhjkhiukhjhukjhkh 4
  • How can I save a array config to a toml file?

    How can I save a array config to a toml file?

    I want to save some additional variables to my config file for program next running, but I don't know how to do it, I haven't found in your documentation. Does it hava this function?

    opened by jkhhjkhiukhjhukjhkh 3
  • AOT and Table nesting complexity

    AOT and Table nesting complexity

    Testing on some of the TOML github examples, and reading the documentation, and testing on some of my website toml configuration files, suggests that the current branch doesn't do Array of Table and nested tables quite right, and looks to me to be worth getting it right. It is a little bit hard to tell, almost inscrutable, from the official TOML scarce documentation. Does anyone have really detailed specification?
    The AOT stack keeps track of nested AOT while they are still in context. Usage of finds the current-in-use item of AOT, or adds a new table for repeats. I also enlarged the parse key specification to include encounters with single quoted strings, and bare integers which are converted to string. I am not sure that storing the key paths is all that much independently useful when not debugging the parser, so I've made it optional. I like checking for the BOM when loading raw file contents, so I added a parseFile in the Parser class.

    opened by betrixed 3
  • Unable to parse ArrayTables that contain Tables

    Unable to parse ArrayTables that contain Tables

    It seems that the current implementation does not support tables contained within array tables :

    <?php
    use Yosymfony\Toml\Toml;
    
    require dirname(__DIR__) . '/vendor/autoload.php';
    
    $toml = <<<TOML
    [[tls]]
    entrypoints = ["https"]
    [tls.certificate]
        certFile = "certs/foo.crt"
        keyFile  = "keys/foo.key"
    
    [[tls]]
    entrypoints = ["https"]
    [tls.certificate]
        certFile = "certs/bar.crt"
        keyFile  = "keys/bar.key"
    TOML;
    
    Toml::parse($toml);
    

    It throw the following exception :

    Fatal error: Uncaught Yosymfony\ParserUtils\SyntaxErrorException: The key "tls.certificate" has already been defined previously.
    

    https://www.tomllint.com/ indicate that to TOML content provided above is perfectly valid.

    bug 
    opened by guillemcanal 3
  • fixed empty string value not parsed.

    fixed empty string value not parsed.

    hope this is correct and works

    opened by chaosue 3
  • Exception: Syntax error: the key %s has already been defined

    Exception: Syntax error: the key %s has already been defined

    TomlBuilder:

    Exception raises when 0 exists in the keyList and any string keys that are to be added to the keyList, since strings starts without non-zero numbers will be converted to 0. Using "in_array($key, $this->keyList, true)" instead of in_array($key, $this->keyList,) solves this problem.

    opened by chaosue 2
  • Toml::parse() throws exception on Windows when a string is used.

    Toml::parse() throws exception on Windows when a string is used.

    When i try to parse a string i get an exception that the path limit has been reached. \Exception\ErrorException (E_WARNING) is_file(): File name is longer than the maximum allowed path length on this platform (260):

    Which makes sense, because i'm not trying to open a file.

    image

    opened by Zerzera 2
  • Better support for dates as specified in the latest TOML spec

    Better support for dates as specified in the latest TOML spec

    This adds support for less specific datetimes, which was added after v0.4.0 of the spec. The feature is still not tagged in a new spec version, but it is incredibly useful.

    opened by sagebind 2
  • Does not parse a table with an array of tables

    Does not parse a table with an array of tables

    This should be valid syntax, if I'm reading the specs correctly:

    [fruit]
    name = "apple"
    
    [[fruit.variety]]
    name = "red delicious"
    
    [[fruit.variety]]
    name = "granny smith"
    

    and should produce the following (in JSON):

    {
        "fruit": {
            "name": "apple",
            "variety": [
                {"name": "red delicious"},
                {"name": "granny smith"}
            ]
        }
    }
    

    But right now this parser returns an error:

    Yosymfony\Toml\Exception\ParseException with message 'Syntax error: the table fruit.variety has already been defined in "test.toml" at line 6 (near "]")'

    By the way, it should also work without the initial section:

    [[fruit.variety]]
    name = "red delicious"
    
    [[fruit.variety]]
    name = "granny smith"
    

    in which case it should give the same JSON as above, without the "name": "apple" line.

    bug 
    opened by tobia 2
  • Added a fromArray() method to convert a parsed TOML file (an array) back to a TOML file.

    Added a fromArray() method to convert a parsed TOML file (an array) back to a TOML file.

    The biggest thing I'm missing in this library is to 'edit' TOML files:

    1. Load in a TOML file
    2. Make changes
    3. Write back to TOML file.

    For this purpose I've added an additional method fromArray() on the TomlBuilder class to allow just this. I must say I'm not very pleased with it, but it does the job. A better way would be to parse a file to an object oriented representation to allow easy manipulation (with some helper methods) and write that OO version back to a file. I've tried to do this, but I cannot really grasp how this library does it's magic so I failed miserably...

    Example use:

    // Parse file to array:
    $array = \Yosymfony\Toml\Toml::parse('/my/config.toml');
    
    // Modify $array where needed...
    
    // Build new file from the above array:
    $tb = new \Yosymfony\Toml\TomlBuilder();
    $tb->fromArray($array);
    // View the toml string.
    echo $tb->getTomlString();
    

    Edit: Forgot to mention that at some point I bumped into this one #12. Edit2: I'm not sure how to write a proper test for this though: grab a file, parse it, use the fromArray() method followed by getTomlString() and parse that 'new' string to an array and compare it with the original array?

    opened by malc0mn 2
  • Dump to TOML?

    Dump to TOML?

    Thank you for and congratulations with this great library! I am using both YAML and TOML. For YAML I use the Yaml::parse and Yaml::dump to read and write files. With TOML I am missing the 'dump' command. Is there a way around this? Kind regards, Maurits

    opened by mevdschee 0
  • Multiline triple single-quote issue

    Multiline triple single-quote issue

    It appears that a toml file with a multi-line string (three 's) causes the parser to crash.

    key=''' This is a line '''

    key2=""" This is also a line """

    It's possible that the contents of the line also has something to do with it, but in my experience one or both of the above will cause a crash.

    opened by cowpod 0
  • TOML v0.5.0 support

    TOML v0.5.0 support

    Has anyone started working on it already?

    opened by themightychris 5
  • Test enhancement

    Test enhancement

    Changed log

    • Add more tests.
    • Set the phpunit version in require-dev.
    • Use composer update because it can let the different PHP versions to install proper packages when executing Travis CI build.
    opened by peter279k 3
  • line count (error message)

    line count (error message)

    # Global tags can be specified here in key="value" format.
    [global_tags] #fghfgh
      # dc 
    [[agent1.edfgdfg]] #dfgdfgd
    [[agent1.edfgdfg]] #dfgdfg
    [[agent1.edfgdfg]] #dfgdfgdf
    [[agent1.edfgdfg]] #dfgdfgdf
    

    got expected error, but line number is invalid: Syntax error: the table agent1.edfgdfg has already been defined at line 0 (near "]")

    $this->processComment(); finds comment after line and move to EOF or \n and do not increase $this->currentLine because after that it takes token again (after switch-case)

    (Parser.php lines: 53 => 107 => 114 => 99)

    opened by MikhailMarchenko 2
Releases(v1.0.4)
  • v1.0.4(Aug 8, 2018)

    What's new in this release?

    • Several corrections and refactorings in TomBuilder class. The problem described in the PR #25 "fixed a bug when used the function 'in_array'" has been solved.
    • The test file TomlBuilderTest has been refactored for readability. Added some tests.
    • The README.md file has been updated with the TomlBuilder class limitations.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.3(Jul 30, 2018)

    What's new in this release?

    • TomlBuilder does not throw a DumpException anymore when the character "#" appears in a quoted key.
    • The method addArrayTables from the class TomlBuilder has been declared as deprecated. Use the method addArrayOfTable instead.
    • Fixed the bug #24: "Wrong array of tables implementation".
    • A new class TomlArray has been added to handle the Toml array generation.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.2(Jun 29, 2018)

    What's new in this release?

    • Fixed the bug #23: "Unable to parse ArrayTables that contain Tables".
    • A new class KeyStore has been added to deal with the logic of the keys (keys, tables and array of tables).
    • Package yosymfony/parser-utils has been updated to 2.0.0.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.1(Feb 5, 2018)

    What's new in this release?

    • Fixed a bug related to integer keys: now, it's possible to create keys using an integer. Reported by @betrixed.
    • Merged the pull request #17: "removing is_string check".
    • Minor fixes in README file.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Nov 18, 2017)

    What's new in this release?

    • The code has been rewritten from scratch for PHP 7.1.
    • The method parse from Toml class must only be applied to TOML strings. In case of parsing a TOML filename use the new method parseFile.
    • Methods parse and parseFile from Toml class accept a new argument resultAsObject (optional) to return the parsed input as an object (an instance of stdClass).
    • The method addGroup of TomlBuilder class has been deleted.
    • The exceptions have been refactored, so the classes ExceptionInterface, LexerException and RuntimeException have been removed.
    • Added the inner exception when a ParseException is thrown in method parse of class Toml.
    • Fixed bug #13: "Inline sub-tables don't work".
    • Fixed bug #12: "Does not parse a table with an array of tables".
    • Better support for dates as specified in the latest TOML spec. See PR #11.
    Source code(tar.gz)
    Source code(zip)
  • v0.3.3(Aug 24, 2015)

  • v0.3.2(Mar 9, 2015)

  • v0.3.1(Mar 7, 2015)

  • v0.3.0(Mar 6, 2015)

  • v0.2.0(May 3, 2014)

  • v0.1.1(Dec 14, 2013)

    What's new in this release?

    • Fixed bug with empty string value parse error.
    • Fixed exception default timezone unset in unit tests.
    • Added travis configuration file.
    • Fixed some issues in README.md.
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Dec 14, 2013)

Owner
Yo! Symfony
Yo! Symfony
The VarDumper component provides mechanisms for walking through any arbitrary PHP variable. It provides a better dump() function that you can use instead of var_dump().

VarDumper Component The VarDumper component provides mechanisms for walking through any arbitrary PHP variable. It provides a better dump() function t

Symfony 6.8k Jan 15, 2022
A beautiful, fully open-source, tunneling service - written in pure PHP

Expose A completely open-source ngrok alternative - written in pure PHP. Documentation For installation instructions, in-depth usage and deployment de

Beyond Code 3.6k Jan 14, 2022
All PHP functions, rewritten to throw exceptions instead of returning false

Safe PHP This project is deprecated Because of how this project needs to be in sync with the official PHP documentation, maintaining a set of function

TheCodingMachine 1.9k Jan 19, 2022
PHP client library for the Square Connect APIs

Square Connect PHP SDK - RETIRED replaced by square/square-php-sdk NOTICE: Square Connect PHP SDK retired The Square Connect PHP SDK is retired (EOL)

Square 114 Jan 10, 2022
Simple yet expressive schema-based configuration library for PHP apps

league/config helps you define nested configuration arrays with strict schemas and access configuration values with dot notation.

The League of Extraordinary Packages 152 Jan 11, 2022
This library can parse a TypeSchema specification either from a JSON file, or from PHP classes using reflection and annotations.

This library can parse a TypeSchema specification either from a JSON file, or from PHP classes using reflection and annotations. Based on this schema it can generate source code and transform raw JSON data into DTO objects. Through this you can work with fully typed objects in your API for incoming and outgoing data.

Apioo 51 Jan 10, 2022
LOAD is a PHP library for configuration loading to APCu

LOAD LOAD is a PHP library for configuration loading to APCu Sources Available sources for configuration loading are: PHP file Consul Environment vari

Beat Labs 4 Dec 21, 2021
A PHP parser for TOML

TOML parser for PHP A PHP parser for TOML compatible with TOML v0.4.0. Support: Installation Requires PHP >= 7.1. Use Composer to install this package

Yo! Symfony 161 Dec 25, 2021
DBML parser for PHP8. It's a PHP parser for DBML syntax.

DBML parser written on PHP8 DBML (database markup language) is a simple, readable DSL language designed to define database structures. This page outli

Pavel Buchnev 22 Jan 10, 2022
php html parser,类似与PHP Simple HTML DOM Parser,但是比它快好几倍

HtmlParser php html解析工具,类似与PHP Simple HTML DOM Parser。 由于基于php模块dom,所以在解析html时的效率比 PHP Simple HTML DOM Parser 快好几倍。 注意:html代码必须是utf-8编码字符,如果不是请转成utf-8

俊杰jerry 519 Jan 12, 2022
A PHP parser written in PHP

PHP Parser This is a PHP 5.2 to PHP 8.0 parser written in PHP. Its purpose is to simplify static code analysis and manipulation. Documentation for ver

Nikita Popov 15.2k Jan 19, 2022
An object-oriented option parser library for PHP, which supports type constraints, flag, multiple flag, multiple values, required value checking

GetOptionKit Code Quality Versions & Stats A powerful option parser toolkit for PHP, supporting type constraints, flag, multiple flag, multiple values

Yo-An Lin 138 Dec 6, 2021
Better Markdown Parser in PHP

Parsedown Better Markdown Parser in PHP - Demo. Features One File No Dependencies Super Fast Extensible GitHub flavored Tested in 5.3 to 7.3 Markdown

Emanuil Rusev 14k Jan 11, 2022
Highly-extensible PHP Markdown parser which fully supports the CommonMark and GFM specs.

league/commonmark league/commonmark is a highly-extensible PHP Markdown parser created by Colin O'Dell which supports the full CommonMark spec and Git

The League of Extraordinary Packages 2.1k Jan 14, 2022
A super fast, highly extensible markdown parser for PHP

A super fast, highly extensible markdown parser for PHP What is this? A set of PHP classes, each representing a Markdown flavor, and a command line to

Carsten Brandt 961 Jan 13, 2022
An HTML5 parser and serializer for PHP.

HTML5-PHP HTML5 is a standards-compliant HTML5 parser and writer written entirely in PHP. It is stable and used in many production websites, and has w

null 972 Jan 6, 2022
📜 Modern Simple HTML DOM Parser for PHP

?? Simple Html Dom Parser for PHP A HTML DOM parser written in PHP - let you manipulate HTML in a very easy way! This is a fork of PHP Simple HTML DOM

Lars Moelleken 512 Jan 20, 2022
Advanced shortcode (BBCode) parser and engine for PHP

Shortcode Shortcode is a framework agnostic PHP library allowing to find, extract and process text fragments called "shortcodes" or "BBCodes". Example

Tomasz Kowalczyk 347 Dec 25, 2021
👮 A PHP desktop/mobile user agent parser with support for Laravel, based on Mobiledetect

Agent A PHP desktop/mobile user agent parser with support for Laravel, based on Mobile Detect with desktop support and additional functionality. Insta

Jens Segers 3.9k Jan 20, 2022
A Parser for CSS Files written in PHP. Allows extraction of CSS files into a data structure, manipulation of said structure and output as (optimized) CSS

PHP CSS Parser A Parser for CSS Files written in PHP. Allows extraction of CSS files into a data structure, manipulation of said structure and output

Raphael Schweikert 1.5k Jan 11, 2022
Better Markdown Parser in PHP

Parsedown Better Markdown Parser in PHP - Demo. Features One File No Dependencies Super Fast Extensible GitHub flavored Tested in 5.3 to 7.3 Markdown

Emanuil Rusev 14k Jan 11, 2022
Highly-extensible PHP Markdown parser which fully supports the CommonMark and GFM specs.

league/commonmark league/commonmark is a highly-extensible PHP Markdown parser created by Colin O'Dell which supports the full CommonMark spec and Git

The League of Extraordinary Packages 2.1k Jan 18, 2022
Parsica - PHP Parser Combinators - The easiest way to build robust parsers.

Parsica The easiest way to build robust parsers in PHP.

null 325 Jan 12, 2022
A web tool to explore the ASTs generated by PHP-Parser.

phpast.com A web tool to explore the ASTs generated by PHP-Parser. About This web tool provides a GUI for exploring the AST of your PHP code. You can

Ryan Chandler 24 Nov 15, 2021
php-crossplane - Reliable and fast NGINX configuration file parser and builder

php-crossplane Reliable and fast NGINX configuration file parser and builder ℹ️ This is a PHP port of the Nginx Python crossplane package which can be

null 16 Aug 17, 2021
Parsica - PHP Parser Combinators - The easiest way to build robust parsers.

Parsica The easiest way to build robust parsers in PHP. composer require parsica-php/parsica Documentation & API: parsica-php.github.io <?php $parser

null 324 Jan 7, 2022
This is a php parser for plantuml source file.

PlantUML parser for PHP Overview This package builds AST of class definitions from plantuml files. This package works only with php. Installation Via

Tasuku Yamashita 4 Jan 4, 2022
Efficient, easy-to-use, and fast PHP JSON stream parser

JSON Machine Very easy to use and memory efficient drop-in replacement for inefficient iteration of big JSON files or streams for PHP 5.6+. See TL;DR.

Filip Halaxa 625 Jan 14, 2022
PHP Simple M3U Parser, it clean the playlist and remove duplicate

SimpleM3UParser PHP Simple M3U Playlist Parser, it clean, remove duplicate, and group the playlist. Usage see example.php <?php require_once "M3UPars

erwin solihin 1 Jan 3, 2022