First commit

This commit is contained in:
Cody Cook 2024-04-29 19:04:51 -07:00
commit d5bb2f19fa
117 changed files with 68604 additions and 0 deletions

3
vendor/yosymfony/toml/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
vendor/
phpunit.xml
.php_cs.cache

15
vendor/yosymfony/toml/.travis.yml vendored Normal file
View file

@ -0,0 +1,15 @@
language: php
php:
- 7.1
- 7.2
- nightly
before_script:
- composer self-update
- composer install --no-interaction --no-dev
matrix:
allow_failures:
- php: nightly
fast_finish: true

81
vendor/yosymfony/toml/CHANGELOG.md vendored Normal file
View file

@ -0,0 +1,81 @@
CHANGELOG
=========
1.0.4 (2018-08-08)
------------------
* 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.
1.0.3 (2018-07-31)
------------------
* `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.
1.0.2 (2018-06-29)
------------------
* 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.
1.0.1 (2018-02-05)
------------------
* 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.
1.0.0 (2017-11-18)
------------------
* 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.
0.3.3 (2015-08-24)
------------------
* Fixed bug #10: Cannot parse quote (") in table name.
0.3.2 (2015-03-07)
------------------
* Fixed issue #9: Only double-quoted strings work in arrays, contrary to spec.
0.3.1 (2015-03-07)
------------------
* Added support to literal strings in `TomlBuilder`.
0.3.0 (2015-03-06)
------------------
* Support for TOML 0.4.0.
* CS fixes.
0.2.0 (2014-05-03)
--------------------
* Support for TOML 0.2.0.
* New tests for arrays of tables.
* TomlBuilder: new methods `addTabl`e
* TomlBuilder: Deprecated methods `addGroup`.
* Fixtures folder in tests renamed to fixtures.
* Fixtures reorganized.
0.1.1 (2013-12-14)
------------------
* 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.
0.1.0 (2013-05-12)
------------------
* Initial release.
* Support for TOML 0.1.0.
* BurntSushi test suite included.
* Included TomlBuilder to create inline TOML strings.

19
vendor/yosymfony/toml/LICENSE vendored Normal file
View file

@ -0,0 +1,19 @@
Copyright (c) 2013-2017 Víctor Puertas
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

185
vendor/yosymfony/toml/README.md vendored Normal file
View file

@ -0,0 +1,185 @@
TOML parser for PHP
===================
A PHP parser for [TOML](https://github.com/toml-lang/toml) compatible with [TOML v0.4.0](https://github.com/toml-lang/toml/releases/tag/v0.4.0).
[![Build Status](https://travis-ci.org/yosymfony/toml.png?branch=master)](https://travis-ci.org/yosymfony/toml)
[![Latest Stable Version](https://poser.pugx.org/yosymfony/toml/v/stable.png)](https://packagist.org/packages/yosymfony/toml)
[![Total Downloads](https://poser.pugx.org/yosymfony/toml/downloads.png)](https://packagist.org/packages/yosymfony/toml)
Support:
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/yosymfony/Toml?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
Installation
------------
**Requires PHP >= 7.1.**
Use [Composer](http://getcomposer.org/) to install this package:
```bash
composer require yosymfony/toml
```
Usage
-----
You can parse an inline TOML string or from a file:
To parse an inline TOML string:
```php
use Yosymfony\Toml\Toml;
$array = Toml::Parse('key = [1,2,3]');
print_r($array);
```
To parse a TOML file:
```php
$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`.
```php
$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:
```php
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](https://www.php-fig.org/psr/psr-2/). To ensure
the CS, you can use the CLI tool [PHP-CS-Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer).
Unit tests
----------
You can run the unit tests with the following command:
```bash
$ cd toml
$ composer test
```
## License
This library is open-sourced software licensed under the
[MIT license](http://opensource.org/licenses/MIT).

33
vendor/yosymfony/toml/composer.json vendored Normal file
View file

@ -0,0 +1,33 @@
{
"name": "yosymfony/toml",
"description": "A PHP parser for TOML compatible with specification 0.4.0",
"type": "library",
"keywords": ["toml", "parser", "mojombo"],
"homepage": "http://github.com/yosymfony/toml",
"license": "MIT",
"authors": [
{
"name": "Victor Puertas",
"email": "vpgugr@gmail.com",
"homepage": "http://yosymfony.com"
}
],
"require": {
"php": ">=7.1",
"yosymfony/parser-utils": "^2.0"
},
"require-dev": {
"phpunit/phpunit": "^7.1"
},
"autoload": {
"psr-4": { "Yosymfony\\Toml\\": "src/" }
},
"scripts": {
"test": "vendor/bin/phpunit"
},
"extra": {
"branch-alias": {
"dev-master": "1.0-dev"
}
}
}

1476
vendor/yosymfony/toml/composer.lock generated vendored Normal file

File diff suppressed because it is too large Load diff

26
vendor/yosymfony/toml/phpunit.xml.dist vendored Normal file
View file

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.1/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php"
failOnRisky="true"
failOnWarning="true"
>
<testsuites>
<testsuite name="Yosymfony Toml Parser test suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>./</directory>
<exclude>
<directory>./vendor</directory>
<directory>./tests</directory>
</exclude>
</whitelist>
</filter>
</phpunit>

View file

@ -0,0 +1,22 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml\Exception;
/**
* Exception class thrown when an error occurs during dumping.
*
* @author Victor Puertas <vpgugr@gmail.com>
*
*/
class DumpException extends \RuntimeException
{
}

View file

@ -0,0 +1,142 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml\Exception;
/**
* Exception class thrown when an error occurs during parsing.
* Based on ParseException of YAML component from Symfony.
*
* @author Victor Puertas <vpgugr@gmail.com>
*/
class ParseException extends \RuntimeException
{
private $parsedFile;
private $parsedLine;
private $snippet;
private $rawMessage;
/**
* Constructor.
*
* @param string $message The error message
* @param int $parsedLine The line where the error occurred
* @param string|null $snippet The snippet of code near the problem
* @param string|null $parsedFile The file name where the error occurred
* @param Exception $previous The previous exception
*/
public function __construct(string $message, int $parsedLine = -1, string $snippet = null, string $parsedFile = null, \Exception $previous = null)
{
$this->parsedFile = $parsedFile;
$this->parsedLine = $parsedLine;
$this->snippet = $snippet;
$this->rawMessage = $message;
$this->updateRepr();
parent::__construct($this->message, 0, $previous);
}
/**
* Gets the snippet of code near the error.
*
* @return string The snippet of code
*/
public function getSnippet() : string
{
return $this->snippet;
}
/**
* Sets the snippet of code near the error.
*
* @param string $snippet The code snippet
*/
public function setSnippet(string $snippet) : void
{
$this->snippet = $snippet;
$this->updateRepr();
}
/**
* Gets the filename where the error occurred.
*
* This method returns null if a string is parsed.
*
* @return string The filename
*/
public function getParsedFile() : string
{
return $this->parsedFile;
}
/**
* Sets the filename where the error occurred.
*
* @param string $parsedFile The filename
*/
public function setParsedFile(string $parsedFile) : void
{
$this->parsedFile = $parsedFile;
$this->updateRepr();
}
/**
* Gets the line where the error occurred.
*
* @return int The file line
*/
public function getParsedLine() : int
{
return $this->parsedLine;
}
/**
* Sets the line where the error occurred.
*
* @param int $parsedLine The file line
*/
public function setParsedLine(int $parsedLine) : void
{
$this->parsedLine = $parsedLine;
$this->updateRepr();
}
private function updateRepr() : void
{
$this->message = $this->rawMessage;
$dot = false;
if ('.' === substr($this->message, -1)) {
$this->message = substr($this->message, 0, -1);
$dot = true;
}
if (null !== $this->parsedFile) {
$this->message .= sprintf(' in %s', json_encode($this->parsedFile));
}
if ($this->parsedLine >= 0) {
$this->message .= sprintf(' at line %d', $this->parsedLine);
}
if ($this->snippet) {
$this->message .= sprintf(' (near "%s")', $this->snippet);
}
if ($dot) {
$this->message .= '.';
}
}
}

197
vendor/yosymfony/toml/src/KeyStore.php vendored Normal file
View file

@ -0,0 +1,197 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml;
/**
* Internal class for managing keys (key-values, tables and array of tables)
*
* @author Victor Puertas <vpgugr@vpgugr.com>
*/
class KeyStore
{
private $keys = [];
private $tables = [];
private $arrayOfTables = [];
private $implicitArrayOfTables = [];
private $currentTable = '';
private $currentArrayOfTable = '';
public function addKey(string $name) : void
{
if (!$this->isValidKey($name)) {
throw new \LogicException("The key \"{$name}\" is not valid.");
}
$this->keys[] = $this->composeKeyWithCurrentPrefix($name);
}
public function isValidKey(string $name) : bool
{
$composedKey = $this->composeKeyWithCurrentPrefix($name);
if (in_array($composedKey, $this->keys, true) === true) {
return false;
}
return true;
}
public function addTableKey(string $name) : void
{
if (!$this->isValidTableKey($name)) {
throw new \LogicException("The table key \"{$name}\" is not valid.");
}
$this->currentTable = '';
$this->currentArrayOfTable = $this->getArrayOfTableKeyFromTableKey($name);
$this->addkey($name);
$this->currentTable = $name;
$this->tables[] = $name;
}
public function isValidTableKey($name) : bool
{
$currentTable = $this->currentTable;
$currentArrayOfTable = $this->currentArrayOfTable;
$this->currentTable = '';
$this->currentArrayOfTable = $this->getArrayOfTableKeyFromTableKey($name);
if ($this->currentArrayOfTable == $name) {
return false;
}
$isValid = $this->isValidKey($name);
$this->currentTable = $currentTable;
$this->currentArrayOfTable = $currentArrayOfTable;
return $isValid;
}
public function isValidInlineTable(string $name): bool
{
return $this->isValidTableKey($name);
}
public function addInlineTableKey(string $name) : void
{
$this->addTableKey($name);
}
public function addArrayTableKey(string $name) : void
{
if (!$this->isValidArrayTableKey($name)) {
throw new \LogicException("The array table key \"{$name}\" is not valid.");
}
$this->currentTable = '';
$this->currentArrayOfTable = '';
if (isset($this->arrayOfTables[$name]) === false) {
$this->addkey($name);
$this->arrayOfTables[$name] = 0;
} else {
$this->arrayOfTables[$name]++;
}
$this->currentArrayOfTable = $name;
$this->processImplicitArrayTableNameIfNeeded($name);
}
public function isValidArrayTableKey(string $name) : bool
{
$isInArrayOfTables = isset($this->arrayOfTables[$name]);
$isInKeys = in_array($name, $this->keys, true);
if ((!$isInArrayOfTables && !$isInKeys) || ($isInArrayOfTables && $isInKeys)) {
return true;
}
return false;
}
public function isRegisteredAsTableKey(string $name) : bool
{
return in_array($name, $this->tables);
}
public function isRegisteredAsArrayTableKey(string $name) : bool
{
return isset($this->arrayOfTables[$name]);
}
public function isTableImplicitFromArryTable(string $name) : bool
{
$isInImplicitArrayOfTables = in_array($name, $this->implicitArrayOfTables);
$isInArrayOfTables = isset($this->arrayOfTables[$name]);
if ($isInImplicitArrayOfTables && !$isInArrayOfTables) {
return true;
}
return false;
}
private function composeKeyWithCurrentPrefix(string $name) : string
{
$currentArrayOfTableIndex = '';
if ($this->currentArrayOfTable != '') {
$currentArrayOfTableIndex = (string) $this->arrayOfTables[$this->currentArrayOfTable];
}
return \trim("{$this->currentArrayOfTable}{$currentArrayOfTableIndex}.{$this->currentTable}.{$name}", '.');
}
private function getArrayOfTableKeyFromTableKey(string $name) : string
{
if (isset($this->arrayOfTables[$name])) {
return $name;
}
$keyParts = explode('.', $name);
if (count($keyParts) === 1) {
return '';
}
array_pop($keyParts);
while (count($keyParts) > 0) {
$candidateKey = implode('.', $keyParts);
if (isset($this->arrayOfTables[$candidateKey])) {
return $candidateKey;
}
array_pop($keyParts);
}
return '';
}
private function processImplicitArrayTableNameIfNeeded(string $name) : void
{
$nameParts = explode('.', $name);
if (count($nameParts) < 2) {
return;
}
array_pop($nameParts);
while (count($nameParts) != 0) {
$this->implicitArrayOfTables[] = implode('.', $nameParts);
array_pop($nameParts);
}
}
}

69
vendor/yosymfony/toml/src/Lexer.php vendored Normal file
View file

@ -0,0 +1,69 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml;
use Yosymfony\ParserUtils\BasicLexer;
use Yosymfony\ParserUtils\LexerInterface;
use Yosymfony\ParserUtils\TokenStream;
/**
* Lexer for Toml strings.
*
* @author Victor Puertas <vpgugr@vpgugr.com>
*/
class Lexer implements LexerInterface
{
private $basicLexer;
/**
* Constructor
*/
public function __construct()
{
$this->basicLexer = new BasicLexer([
'/^(=)/' => 'T_EQUAL',
'/^(true|false)/' => 'T_BOOLEAN',
'/^(\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{6})?(Z|-\d{2}:\d{2})?)?)/' => 'T_DATE_TIME',
'/^([+-]?((((\d_?)+[\.]?(\d_?)*)[eE][+-]?(\d_?)+)|((\d_?)+[\.](\d_?)+)))/' => 'T_FLOAT',
'/^([+-]?(\d_?)+)/' => 'T_INTEGER',
'/^(""")/' => 'T_3_QUOTATION_MARK',
'/^(")/' => 'T_QUOTATION_MARK',
"/^(''')/" => 'T_3_APOSTROPHE',
"/^(')/" => 'T_APOSTROPHE',
'/^(#)/' => 'T_HASH',
'/^(\s+)/' => 'T_SPACE',
'/^(\[)/' => 'T_LEFT_SQUARE_BRAKET',
'/^(\])/' => 'T_RIGHT_SQUARE_BRAKET',
'/^(\{)/' => 'T_LEFT_CURLY_BRACE',
'/^(\})/' => 'T_RIGHT_CURLY_BRACE',
'/^(,)/' => 'T_COMMA',
'/^(\.)/' => 'T_DOT',
'/^([-A-Z_a-z0-9]+)/' => 'T_UNQUOTED_KEY',
'/^(\\\(b|t|n|f|r|"|\\\\|u[0-9AaBbCcDdEeFf]{4,4}|U[0-9AaBbCcDdEeFf]{8,8}))/' => 'T_ESCAPED_CHARACTER',
'/^(\\\)/' => 'T_ESCAPE',
'/^([\x{20}-\x{21}\x{23}-\x{26}\x{28}-\x{5A}\x{5E}-\x{10FFFF}]+)/u' => 'T_BASIC_UNESCAPED',
]);
$this->basicLexer
->generateNewlineTokens()
->generateEosToken();
}
/**
* {@inheritdoc}
*/
public function tokenize(string $input) : TokenStream
{
return $this->basicLexer->tokenize($input);
}
}

593
vendor/yosymfony/toml/src/Parser.php vendored Normal file
View file

@ -0,0 +1,593 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml;
use Yosymfony\ParserUtils\AbstractParser;
use Yosymfony\ParserUtils\Token;
use Yosymfony\ParserUtils\TokenStream;
use Yosymfony\ParserUtils\SyntaxErrorException;
/**
* Parser for TOML strings (specification version 0.4.0).
*
* @author Victor Puertas <vpgugr@vpgugr.com>
*/
class Parser extends AbstractParser
{
/** @var KeyStore */
private $keyStore;
/** @var TomlArray */
private $tomlArray;
private static $tokensNotAllowedInBasicStrings = [
'T_ESCAPE',
'T_NEWLINE',
'T_EOS',
];
private static $tokensNotAllowedInLiteralStrings = [
'T_NEWLINE',
'T_EOS',
];
/**
* {@inheritdoc}
*/
public function parse(string $input)
{
if (preg_match('//u', $input) === false) {
throw new SyntaxErrorException('The TOML input does not appear to be valid UTF-8.');
}
$input = str_replace(["\r\n", "\r"], "\n", $input);
$input = str_replace("\t", ' ', $input);
return parent::parse($input);
}
/**
* {@inheritdoc}
*/
protected function parseImplementation(TokenStream $ts) : array
{
$this->keyStore = new KeyStore();
$this->tomlArray = new TomlArray();
while ($ts->hasPendingTokens()) {
$this->processExpression($ts);
}
return $this->tomlArray->getArray();
}
private function processExpression(TokenStream $ts) : void
{
if ($ts->isNext('T_HASH')) {
$this->parseComment($ts);
} elseif ($ts->isNextAny(['T_QUOTATION_MARK', 'T_UNQUOTED_KEY', 'T_INTEGER'])) {
$this->parseKeyValue($ts);
} elseif ($ts->isNextSequence(['T_LEFT_SQUARE_BRAKET','T_LEFT_SQUARE_BRAKET'])) {
$this->parseArrayOfTables($ts);
} elseif ($ts->isNext('T_LEFT_SQUARE_BRAKET')) {
$this->parseTable($ts);
} elseif ($ts->isNextAny(['T_SPACE','T_NEWLINE', 'T_EOS'])) {
$ts->moveNext();
} else {
$msg = 'Expected T_HASH or T_UNQUOTED_KEY.';
$this->unexpectedTokenError($ts->moveNext(), $msg);
}
}
private function parseComment(TokenStream $ts) : void
{
$this->matchNext('T_HASH', $ts);
while (!$ts->isNextAny(['T_NEWLINE', 'T_EOS'])) {
$ts->moveNext();
}
}
private function parseKeyValue(TokenStream $ts, bool $isFromInlineTable = false) : void
{
$keyName = $this->parseKeyName($ts);
$this->parseSpaceIfExists($ts);
$this->matchNext('T_EQUAL', $ts);
$this->parseSpaceIfExists($ts);
$isInlineTable = $ts->isNext('T_LEFT_CURLY_BRACE');
if ($isInlineTable) {
if (!$this->keyStore->isValidInlineTable($keyName)) {
$this->syntaxError("The inline table key \"{$keyName}\" has already been defined previously.");
}
$this->keyStore->addInlineTableKey($keyName);
} else {
if (!$this->keyStore->isValidKey($keyName)) {
$this->syntaxError("The key \"{$keyName}\" has already been defined previously.");
}
$this->keyStore->addKey($keyName);
}
if ($ts->isNext('T_LEFT_SQUARE_BRAKET')) {
$this->tomlArray->addKeyValue($keyName, $this->parseArray($ts));
} elseif ($isInlineTable) {
$this->parseInlineTable($ts, $keyName);
} else {
$this->tomlArray->addKeyValue($keyName, $this->parseSimpleValue($ts)->value);
}
if (!$isFromInlineTable) {
$this->parseSpaceIfExists($ts);
$this->parseCommentIfExists($ts);
$this->errorIfNextIsNotNewlineOrEOS($ts);
}
}
private function parseKeyName(TokenStream $ts) : string
{
if ($ts->isNext('T_UNQUOTED_KEY')) {
return $this->matchNext('T_UNQUOTED_KEY', $ts);
}
if ($ts->isNext('T_INTEGER')) {
return $this->parseInteger($ts);
}
return $this->parseBasicString($ts);
}
/**
* @return object An object with two public properties: value and type.
*/
private function parseSimpleValue(TokenStream $ts)
{
if ($ts->isNext('T_BOOLEAN')) {
$type = 'boolean';
$value = $this->parseBoolean($ts);
} elseif ($ts->isNext('T_INTEGER')) {
$type = 'integer';
$value = $this->parseInteger($ts);
} elseif ($ts->isNext('T_FLOAT')) {
$type = 'float';
$value = $this->parseFloat($ts);
} elseif ($ts->isNext('T_QUOTATION_MARK')) {
$type = 'string';
$value = $this->parseBasicString($ts);
} elseif ($ts->isNext('T_3_QUOTATION_MARK')) {
$type = 'string';
$value = $this->parseMultilineBasicString($ts);
} elseif ($ts->isNext('T_APOSTROPHE')) {
$type = 'string';
$value = $this->parseLiteralString($ts);
} elseif ($ts->isNext('T_3_APOSTROPHE')) {
$type = 'string';
$value = $this->parseMultilineLiteralString($ts);
} elseif ($ts->isNext('T_DATE_TIME')) {
$type = 'datetime';
$value = $this->parseDatetime($ts);
} else {
$this->unexpectedTokenError(
$ts->moveNext(),
'Expected boolean, integer, long, string or datetime.'
);
}
$valueStruct = new class() {
public $value;
public $type;
};
$valueStruct->value = $value;
$valueStruct->type = $type;
return $valueStruct;
}
private function parseBoolean(TokenStream $ts) : bool
{
return $this->matchNext('T_BOOLEAN', $ts) == 'true' ? true : false;
}
private function parseInteger(TokenStream $ts) : int
{
$token = $ts->moveNext();
$value = $token->getValue();
if (preg_match('/([^\d]_[^\d])|(_$)/', $value)) {
$this->syntaxError(
'Invalid integer number: underscore must be surrounded by at least one digit.',
$token
);
}
$value = str_replace('_', '', $value);
if (preg_match('/^0\d+/', $value)) {
$this->syntaxError(
'Invalid integer number: leading zeros are not allowed.',
$token
);
}
return (int) $value;
}
private function parseFloat(TokenStream $ts): float
{
$token = $ts->moveNext();
$value = $token->getValue();
if (preg_match('/([^\d]_[^\d])|_[eE]|[eE]_|(_$)/', $value)) {
$this->syntaxError(
'Invalid float number: underscore must be surrounded by at least one digit.',
$token
);
}
$value = str_replace('_', '', $value);
if (preg_match('/^0\d+/', $value)) {
$this->syntaxError(
'Invalid float number: leading zeros are not allowed.',
$token
);
}
return (float) $value;
}
private function parseBasicString(TokenStream $ts): string
{
$this->matchNext('T_QUOTATION_MARK', $ts);
$result = '';
while (!$ts->isNext('T_QUOTATION_MARK')) {
if ($ts->isNextAny(self::$tokensNotAllowedInBasicStrings)) {
$this->unexpectedTokenError($ts->moveNext(), 'This character is not valid.');
}
$value = $ts->isNext('T_ESCAPED_CHARACTER') ? $this->parseEscapedCharacter($ts) : $ts->moveNext()->getValue();
$result .= $value;
}
$this->matchNext('T_QUOTATION_MARK', $ts);
return $result;
}
private function parseMultilineBasicString(TokenStream $ts) : string
{
$this->matchNext('T_3_QUOTATION_MARK', $ts);
$result = '';
if ($ts->isNext('T_NEWLINE')) {
$ts->moveNext();
}
while (!$ts->isNext('T_3_QUOTATION_MARK')) {
if ($ts->isNext('T_EOS')) {
$this->unexpectedTokenError($ts->moveNext(), 'Expected token "T_3_QUOTATION_MARK".');
}
if ($ts->isNext('T_ESCAPE')) {
$ts->skipWhileAny(['T_ESCAPE','T_SPACE', 'T_NEWLINE']);
}
if ($ts->isNext('T_EOS')) {
$this->unexpectedTokenError($ts->moveNext(), 'Expected token "T_3_QUOTATION_MARK".');
}
if (!$ts->isNext('T_3_QUOTATION_MARK')) {
$value = $ts->isNext('T_ESCAPED_CHARACTER') ? $this->parseEscapedCharacter($ts) : $ts->moveNext()->getValue();
$result .= $value;
}
}
$this->matchNext('T_3_QUOTATION_MARK', $ts);
return $result;
}
private function parseLiteralString(TokenStream $ts) : string
{
$this->matchNext('T_APOSTROPHE', $ts);
$result = '';
while (!$ts->isNext('T_APOSTROPHE')) {
if ($ts->isNextAny(self::$tokensNotAllowedInLiteralStrings)) {
$this->unexpectedTokenError($ts->moveNext(), 'This character is not valid.');
}
$result .= $ts->moveNext()->getValue();
}
$this->matchNext('T_APOSTROPHE', $ts);
return $result;
}
private function parseMultilineLiteralString(TokenStream $ts) : string
{
$this->matchNext('T_3_APOSTROPHE', $ts);
$result = '';
if ($ts->isNext('T_NEWLINE')) {
$ts->moveNext();
}
while (!$ts->isNext('T_3_APOSTROPHE')) {
if ($ts->isNext('T_EOS')) {
$this->unexpectedTokenError($ts->moveNext(), 'Expected token "T_3_APOSTROPHE".');
}
$result .= $ts->moveNext()->getValue();
}
$this->matchNext('T_3_APOSTROPHE', $ts);
return $result;
}
private function parseEscapedCharacter(TokenStream $ts) : string
{
$token = $ts->moveNext();
$value = $token->getValue();
switch ($value) {
case '\b':
return "\b";
case '\t':
return "\t";
case '\n':
return "\n";
case '\f':
return "\f";
case '\r':
return "\r";
case '\"':
return '"';
case '\\\\':
return '\\';
}
if (strlen($value) === 6) {
return json_decode('"'.$value.'"');
}
preg_match('/\\\U([0-9a-fA-F]{4})([0-9a-fA-F]{4})/', $value, $matches);
return json_decode('"\u'.$matches[1].'\u'.$matches[2].'"');
}
private function parseDatetime(TokenStream $ts) : \Datetime
{
$date = $this->matchNext('T_DATE_TIME', $ts);
return new \Datetime($date);
}
private function parseArray(TokenStream $ts) : array
{
$result = [];
$leaderType = '';
$this->matchNext('T_LEFT_SQUARE_BRAKET', $ts);
while (!$ts->isNext('T_RIGHT_SQUARE_BRAKET')) {
$ts->skipWhileAny(['T_NEWLINE', 'T_SPACE']);
$this->parseCommentsInsideBlockIfExists($ts);
if ($ts->isNext('T_LEFT_SQUARE_BRAKET')) {
if ($leaderType === '') {
$leaderType = 'array';
}
if ($leaderType !== 'array') {
$this->syntaxError(sprintf(
'Data types cannot be mixed in an array. Value: "%s".',
$valueStruct->value
));
}
$result[] = $this->parseArray($ts);
} else {
$valueStruct = $this->parseSimpleValue($ts);
if ($leaderType === '') {
$leaderType = $valueStruct->type;
}
if ($valueStruct->type !== $leaderType) {
$this->syntaxError(sprintf(
'Data types cannot be mixed in an array. Value: "%s".',
$valueStruct->value
));
}
$result[] = $valueStruct->value;
}
$ts->skipWhileAny(['T_NEWLINE', 'T_SPACE']);
$this->parseCommentsInsideBlockIfExists($ts);
if (!$ts->isNext('T_RIGHT_SQUARE_BRAKET')) {
$this->matchNext('T_COMMA', $ts);
}
$ts->skipWhileAny(['T_NEWLINE', 'T_SPACE']);
$this->parseCommentsInsideBlockIfExists($ts);
}
$this->matchNext('T_RIGHT_SQUARE_BRAKET', $ts);
return $result;
}
private function parseInlineTable(TokenStream $ts, string $keyName) : void
{
$this->matchNext('T_LEFT_CURLY_BRACE', $ts);
$this->tomlArray->beginInlineTableKey($keyName);
$this->parseSpaceIfExists($ts);
if (!$ts->isNext('T_RIGHT_CURLY_BRACE')) {
$this->parseKeyValue($ts, true);
$this->parseSpaceIfExists($ts);
}
while ($ts->isNext('T_COMMA')) {
$ts->moveNext();
$this->parseSpaceIfExists($ts);
$this->parseKeyValue($ts, true);
$this->parseSpaceIfExists($ts);
}
$this->matchNext('T_RIGHT_CURLY_BRACE', $ts);
$this->tomlArray->endCurrentInlineTableKey();
}
private function parseTable(TokenStream $ts) : void
{
$this->matchNext('T_LEFT_SQUARE_BRAKET', $ts);
$fullTableName = $this->tomlArray->escapeKey($key = $this->parseKeyName($ts));
while ($ts->isNext('T_DOT')) {
$ts->moveNext();
$key = $this->tomlArray->escapeKey($this->parseKeyName($ts));
$fullTableName .= ".$key";
}
if (!$this->keyStore->isValidTableKey($fullTableName)) {
$this->syntaxError("The key \"{$fullTableName}\" has already been defined previously.");
}
$this->keyStore->addTableKey($fullTableName);
$this->tomlArray->addTableKey($fullTableName);
$this->matchNext('T_RIGHT_SQUARE_BRAKET', $ts);
$this->parseSpaceIfExists($ts);
$this->parseCommentIfExists($ts);
$this->errorIfNextIsNotNewlineOrEOS($ts);
}
private function parseArrayOfTables(TokenStream $ts) : void
{
$this->matchNext('T_LEFT_SQUARE_BRAKET', $ts);
$this->matchNext('T_LEFT_SQUARE_BRAKET', $ts);
$fullTableName = $key = $this->tomlArray->escapeKey($this->parseKeyName($ts));
while ($ts->isNext('T_DOT')) {
$ts->moveNext();
$key = $this->tomlArray->escapeKey($this->parseKeyName($ts));
$fullTableName .= ".$key";
}
if (!$this->keyStore->isValidArrayTableKey($fullTableName)) {
$this->syntaxError("The key \"{$fullTableName}\" has already been defined previously.");
}
if ($this->keyStore->isTableImplicitFromArryTable($fullTableName)) {
$this->syntaxError("The array of tables \"{$fullTableName}\" has already been defined as previous table");
}
$this->keyStore->addArrayTableKey($fullTableName);
$this->tomlArray->addArrayTableKey($fullTableName);
$this->matchNext('T_RIGHT_SQUARE_BRAKET', $ts);
$this->matchNext('T_RIGHT_SQUARE_BRAKET', $ts);
$this->parseSpaceIfExists($ts);
$this->parseCommentIfExists($ts);
$this->errorIfNextIsNotNewlineOrEOS($ts);
}
private function matchNext(string $tokenName, TokenStream $ts) : string
{
if (!$ts->isNext($tokenName)) {
$this->unexpectedTokenError($ts->moveNext(), "Expected \"$tokenName\".");
}
return $ts->moveNext()->getValue();
}
private function parseSpaceIfExists(TokenStream $ts) : void
{
if ($ts->isNext('T_SPACE')) {
$ts->moveNext();
}
}
private function parseCommentIfExists(TokenStream $ts) : void
{
if ($ts->isNext('T_HASH')) {
$this->parseComment($ts);
}
}
private function parseCommentsInsideBlockIfExists(TokenStream $ts) : void
{
$this->parseCommentIfExists($ts);
while ($ts->isNext('T_NEWLINE')) {
$ts->moveNext();
$ts->skipWhile('T_SPACE');
$this->parseCommentIfExists($ts);
}
}
private function errorIfNextIsNotNewlineOrEOS(TokenStream $ts) : void
{
if (!$ts->isNextAny(['T_NEWLINE', 'T_EOS'])) {
$this->unexpectedTokenError($ts->moveNext(), 'Expected T_NEWLINE or T_EOS.');
}
}
private function unexpectedTokenError(Token $token, string $expectedMsg) : void
{
$name = $token->getName();
$line = $token->getLine();
$value = $token->getValue();
$msg = sprintf('Syntax error: unexpected token "%s" at line %s with value "%s".', $name, $line, $value);
if (!empty($expectedMsg)) {
$msg = $msg.' '.$expectedMsg;
}
throw new SyntaxErrorException($msg);
}
private function syntaxError($msg, Token $token = null) : void
{
if ($token !== null) {
$name = $token->getName();
$line = $token->getLine();
$value = $token->getValue();
$tokenMsg = sprintf('Token: "%s" line: %s value "%s".', $name, $line, $value);
$msg .= ' '.$tokenMsg;
}
throw new SyntaxErrorException($msg);
}
}

116
vendor/yosymfony/toml/src/Toml.php vendored Normal file
View file

@ -0,0 +1,116 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml;
use Yosymfony\ParserUtils\SyntaxErrorException;
use Yosymfony\Toml\Exception\ParseException;
/**
* Parser for TOML format.
*
* @author Victor Puertas <vpgugr@vpgugr.com>
*/
class Toml
{
/**
* Parses TOML into a PHP array.
*
* Usage:
* <code>
* $array = Toml::parse('key = "[1,2,3]"');
* print_r($array);
* </code>
*
* @param string $input A string containing TOML
* @param bool $resultAsObject (optional) Returns the result as an object
*
* @return mixed The TOML converted to a PHP value
*
* @throws ParseException If the TOML is not valid
*/
public static function parse(string $input, bool $resultAsObject = false)
{
try {
$data = self::doParse($input, $resultAsObject);
} catch (SyntaxErrorException $e) {
$exception = new ParseException($e->getMessage(), -1, null, null, $e);
if ($token = $e->getToken()) {
$exception->setParsedLine($token->getLine());
}
throw $exception;
}
return $data;
}
/**
* Parses a TOML file into a PHP array.
*
* Usage:
* <code>
* $array = Toml::parseFile('config.toml');
* print_r($array);
* </code>
*
* @param string $input A string containing TOML
* @param bool $resultAsObject (optional) Returns the result as an object
*
* @return mixed The TOML converted to a PHP value
*
* @throws ParseException If the TOML file is not valid
*/
public static function parseFile(string $filename, bool $resultAsObject = false)
{
if (!is_file($filename)) {
throw new ParseException(sprintf('File "%s" does not exist.', $filename));
}
if (!is_readable($filename)) {
throw new ParseException(sprintf('File "%s" cannot be read.', $filename));
}
try {
$data = self::doParse(file_get_contents($filename), $resultAsObject);
} catch (SyntaxErrorException $e) {
$exception = new ParseException($e->getMessage());
$exception->setParsedFile($filename);
if ($token = $e->getToken()) {
$exception->setParsedLine($token->getLine());
}
throw $exception;
}
return $data;
}
private static function doParse(string $input, bool $resultAsObject = false)
{
$parser = new Parser(new Lexer());
$values = $parser->parse($input);
if ($resultAsObject) {
$object = new \stdClass();
foreach ($values as $key => $value) {
$object->$key = $value;
}
return $object;
}
return empty($values) ? null : $values;
}
}

131
vendor/yosymfony/toml/src/TomlArray.php vendored Normal file
View file

@ -0,0 +1,131 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml;
/**
* Internal class for managing a Toml array
*
* @author Victor Puertas <vpgugr@vpgugr.com>
*/
class TomlArray
{
private const DOT_ESCAPED = '%*%';
private $result = [];
private $currentPointer;
private $originInlineTableCurrentPointer;
private $ArrayTableKeys = [];
private $inlineTablePointers = [];
public function __construct()
{
$this->resetCurrentPointer();
}
public function addKeyValue(string $name, $value) : Void
{
$this->currentPointer[$name] = $value;
}
public function addTableKey(string $name) : Void
{
$this->resetCurrentPointer();
$this->goToKey($name);
}
public function beginInlineTableKey(string $name) : Void
{
$this->inlineTablePointers[] = &$this->currentPointer;
$this->goToKey($name);
}
public function endCurrentInlineTableKey() : Void
{
$indexLastElement = $this->getKeyLastElementOfArray($this->inlineTablePointers);
$this->currentPointer = &$this->inlineTablePointers[$indexLastElement];
unset($this->inlineTablePointers[$indexLastElement]);
}
public function addArrayTableKey(string $name) : Void
{
$this->resetCurrentPointer();
$this->goToKey($name);
$this->currentPointer[] = [];
$this->setCurrentPointerToLastElement();
if (!$this->existsInArrayTableKey($name)) {
$this->ArrayTableKeys[] = $name;
}
}
public function escapeKey(string $name) : string
{
return \str_replace('.', self::DOT_ESCAPED, $name);
}
public function getArray() : array
{
return $this->result;
}
private function unescapeKey(string $name) : string
{
return \str_replace(self::DOT_ESCAPED, '.', $name);
}
private function goToKey(string $name) : Void
{
$keyParts = explode('.', $name);
$accumulatedKey = '';
$countParts = count($keyParts);
foreach ($keyParts as $index => $keyPart) {
$keyPart = $this->unescapeKey($keyPart);
$isLastKeyPart = $index == $countParts -1;
$accumulatedKey .= $accumulatedKey == '' ? $keyPart : '.'.$keyPart;
if (\array_key_exists($keyPart, $this->currentPointer) === false) {
$this->currentPointer[$keyPart] = [];
}
$this->currentPointer = &$this->currentPointer[$keyPart];
if ($this->existsInArrayTableKey($accumulatedKey) && !$isLastKeyPart) {
$this->setCurrentPointerToLastElement();
continue;
}
}
}
private function setCurrentPointerToLastElement() : void
{
$indexLastElement = $this->getKeyLastElementOfArray($this->currentPointer);
$this->currentPointer = &$this->currentPointer[$indexLastElement];
}
private function resetCurrentPointer() : Void
{
$this->currentPointer = &$this->result;
}
private function existsInArrayTableKey($name) : bool
{
return \in_array($this->unescapeKey($name), $this->ArrayTableKeys);
}
private function getKeyLastElementOfArray(array &$arr)
{
end($arr);
return key($arr);
}
}

View file

@ -0,0 +1,425 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml;
use Yosymfony\Toml\Exception\DumpException;
/**
* Create inline TOML strings.
*
* @author Victor Puertas <vpgugr@gmail.com>
*
* Usage:
* <code>
* $tomlString = new TomlBuilder()
* ->addTable('server.mail')
* ->addValue('ip', '192.168.0.1', 'Internal IP')
* ->addValue('port', 25)
* ->getTomlString();
* </code>
*/
class TomlBuilder
{
protected $prefix = '';
protected $output = '';
protected $currentKey;
/** @var KeyStore */
protected $keyStore;
private $currentLine = 0;
/** @var array */
private static $specialCharacters;
/** @var array */
private static $escapedSpecialCharacters;
private static $specialCharactersMapping = [
'\\' => '\\\\',
"\b" => '\\b',
"\t" => '\\t',
"\n" => '\\n',
"\f" => '\\f',
"\r" => '\\r',
'"' => '\\"',
];
/**
* Constructor.
*
* @param int $indent The amount of spaces to use for indentation of nested nodes
*/
public function __construct(int $indent = 4)
{
$this->keyStore = new KeyStore();
$this->prefix = $indent ? str_repeat(' ', $indent) : '';
}
/**
* Adds a key value pair
*
* @param string $key The key name
* @param string|int|bool|float|array|Datetime $val The value
* @param string $comment Comment (optional argument).
*
* @return TomlBuilder The TomlBuilder itself
*/
public function addValue(string $key, $val, string $comment = '') : TomlBuilder
{
$this->currentKey = $key;
$this->exceptionIfKeyEmpty($key);
$this->addKey($key);
if (!$this->isUnquotedKey($key)) {
$key = '"'.$key.'"';
}
$line = "{$key} = {$this->dumpValue($val)}";
if (!empty($comment)) {
$line .= ' '.$this->dumpComment($comment);
}
$this->append($line, true);
return $this;
}
/**
* Adds a table.
*
* @param string $key Table name. Dot character have a special mean. e.g: "fruit.type"
*
* @return TomlBuilder The TomlBuilder itself
*/
public function addTable(string $key) : TomlBuilder
{
$this->exceptionIfKeyEmpty($key);
$addPreNewline = $this->currentLine > 0 ? true : false;
$keyParts = explode('.', $key);
foreach ($keyParts as $keyPart) {
$this->exceptionIfKeyEmpty($keyPart, "Table: \"{$key}\".");
$this->exceptionIfKeyIsNotUnquotedKey($keyPart);
}
$line = "[{$key}]";
$this->addTableKey($key);
$this->append($line, true, false, $addPreNewline);
return $this;
}
/**
* This method has been marked as deprecated and will be deleted in version 2.0.0
* @deprecated 2.0.0 Use the method "addArrayOfTable" instead
*/
public function addArrayTables(string $key) : TomlBuilder
{
return $this->addArrayOfTable($key);
}
/**
* Adds an array of tables element
*
* @param string $key The name of the array of tables
*
* @return TomlBuilder The TomlBuilder itself
*/
public function addArrayOfTable(string $key) : TomlBuilder
{
$this->exceptionIfKeyEmpty($key);
$addPreNewline = $this->currentLine > 0 ? true : false;
$keyParts = explode('.', $key);
foreach ($keyParts as $keyPart) {
$this->exceptionIfKeyEmpty($keyPart, "Array of table: \"{$key}\".");
$this->exceptionIfKeyIsNotUnquotedKey($keyPart);
}
$line = "[[{$key}]]";
$this->addArrayOfTableKey($key);
$this->append($line, true, false, $addPreNewline);
return $this;
}
/**
* Adds a comment line
*
* @param string $comment The comment
*
* @return TomlBuilder The TomlBuilder itself
*/
public function addComment(string $comment) : TomlBuilder
{
$this->append($this->dumpComment($comment), true);
return $this;
}
/**
* Gets the TOML string
*
* @return string
*/
public function getTomlString() : string
{
return $this->output;
}
/**
* Returns the escaped characters for basic strings
*/
protected function getEscapedCharacters() : array
{
if (self::$escapedSpecialCharacters !== null) {
return self::$escapedSpecialCharacters;
}
return self::$escapedSpecialCharacters = \array_values(self::$specialCharactersMapping);
}
/**
* Returns the special characters for basic strings
*/
protected function getSpecialCharacters() : array
{
if (self::$specialCharacters !== null) {
return self::$specialCharacters;
}
return self::$specialCharacters = \array_keys(self::$specialCharactersMapping);
}
/**
* Adds a key to the store
*
* @param string $key The key name
*
* @return void
*/
protected function addKey(string $key) : void
{
if (!$this->keyStore->isValidKey($key)) {
throw new DumpException("The key \"{$key}\" has already been defined previously.");
}
$this->keyStore->addKey($key);
}
/**
* Adds a table key to the store
*
* @param string $key The table key name
*
* @return void
*/
protected function addTableKey(string $key) : void
{
if (!$this->keyStore->isValidTableKey($key)) {
throw new DumpException("The table key \"{$key}\" has already been defined previously.");
}
if ($this->keyStore->isRegisteredAsArrayTableKey($key)) {
throw new DumpException("The table \"{$key}\" has already been defined as previous array of tables.");
}
$this->keyStore->addTableKey($key);
}
/**
* Adds an array of table key to the store
*
* @param string $key The key name
*
* @return void
*/
protected function addArrayOfTableKey(string $key) : void
{
if (!$this->keyStore->isValidArrayTableKey($key)) {
throw new DumpException("The array of table key \"{$key}\" has already been defined previously.");
}
if ($this->keyStore->isTableImplicitFromArryTable($key)) {
throw new DumpException("The key \"{$key}\" has been defined as a implicit table from a previous array of tables.");
}
$this->keyStore->addArrayTableKey($key);
}
/**
* Dumps a value
*
* @param string|int|bool|float|array|Datetime $val The value
*
* @return string
*/
protected function dumpValue($val) : string
{
switch (true) {
case is_string($val):
return $this->dumpString($val);
case is_array($val):
return $this->dumpArray($val);
case is_int($val):
return $this->dumpInteger($val);
case is_float($val):
return $this->dumpFloat($val);
case is_bool($val):
return $this->dumpBool($val);
case $val instanceof \Datetime:
return $this->dumpDatetime($val);
default:
throw new DumpException("Data type not supporter at the key: \"{$this->currentKey}\".");
}
}
/**
* Adds content to the output
*
* @param string $val
* @param bool $addPostNewline Indicates if add a newline after the value
* @param bool $addIndentation Indicates if add indentation to the line
* @param bool $addPreNewline Indicates if add a new line before the value
*
* @return void
*/
protected function append(string $val, bool $addPostNewline = false, bool $addIndentation = false, bool $addPreNewline = false) : void
{
if ($addPreNewline) {
$this->output .= "\n";
++$this->currentLine;
}
if ($addIndentation) {
$val = $this->prefix.$val;
}
$this->output .= $val;
if ($addPostNewline) {
$this->output .= "\n";
++$this->currentLine;
}
}
private function dumpString(string $val) : string
{
if ($this->isLiteralString($val)) {
return "'".preg_replace('/@/', '', $val, 1)."'";
}
$normalized = $this->normalizeString($val);
if (!$this->isStringValid($normalized)) {
throw new DumpException("The string has an invalid charters at the key \"{$this->currentKey}\".");
}
return '"'.$normalized.'"';
}
private function isLiteralString(string $val) : bool
{
return strpos($val, '@') === 0;
}
private function dumpBool(bool $val) : string
{
return $val ? 'true' : 'false';
}
private function dumpArray(array $val) : string
{
$result = '';
$first = true;
$dataType = null;
$lastType = null;
foreach ($val as $item) {
$lastType = gettype($item);
$dataType = $dataType == null ? $lastType : $dataType;
if ($lastType != $dataType) {
throw new DumpException("Data types cannot be mixed in an array. Key: \"{$this->currentKey}\".");
}
$result .= $first ? $this->dumpValue($item) : ', '.$this->dumpValue($item);
$first = false;
}
return '['.$result.']';
}
private function dumpComment(string $val) : string
{
return '#'.$val;
}
private function dumpDatetime(\Datetime $val) : string
{
return $val->format('Y-m-d\TH:i:s\Z'); // ZULU form
}
private function dumpInteger(int $val) : string
{
return strval($val);
}
private function dumpFloat(float $val) : string
{
return strval($val);
}
private function isStringValid(string $val) : bool
{
$noSpecialCharacter = \str_replace($this->getEscapedCharacters(), '', $val);
$noSpecialCharacter = \preg_replace('/\\\\u([0-9a-fA-F]{4})/', '', $noSpecialCharacter);
$noSpecialCharacter = \preg_replace('/\\\\u([0-9a-fA-F]{8})/', '', $noSpecialCharacter);
$pos = strpos($noSpecialCharacter, '\\');
if ($pos !== false) {
return false;
}
return true;
}
private function normalizeString(string $val) : string
{
$normalized = \str_replace($this->getSpecialCharacters(), $this->getEscapedCharacters(), $val);
return $normalized;
}
private function exceptionIfKeyEmpty(string $key, string $additionalMessage = '') : void
{
$message = 'A key, table name or array of table name cannot be empty or null.';
if ($additionalMessage != '') {
$message .= " {$additionalMessage}";
}
if (empty(trim($key))) {
throw new DumpException($message);
}
}
private function exceptionIfKeyIsNotUnquotedKey($key) : void
{
if (!$this->isUnquotedKey($key)) {
throw new DumpException("Only unquoted keys are allowed in this implementation. Key: \"{$key}\".");
}
}
private function isUnquotedKey(string $key) : bool
{
return \preg_match('/^([-A-Z_a-z0-9]+)$/', $key) === 1;
}
}

View file

@ -0,0 +1,96 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml\tests;
use PHPUnit\Framework\TestCase;
use Yosymfony\Toml\KeyStore;
class KeyStoreTest extends TestCase
{
private $keyStore;
public function setUp()
{
$this->keyStore = new KeyStore();
}
public function testIsValidKeyMustReturnTrueWhenTheKeyDoesNotExist()
{
$this->assertTrue($this->keyStore->isValidKey('a'));
}
public function testIsValidKeyMustReturnFalseWhenDuplicateKeys()
{
$this->keyStore->addKey('a');
$this->assertFalse($this->keyStore->isValidKey('a'));
}
public function testIsValidTableKeyMustReturnTrueWhenTheTableKeyDoesNotExist()
{
$this->assertTrue($this->keyStore->isValidTableKey('a'));
}
public function testIsValidTableKeyMustReturnTrueWhenSuperTableIsNotDireclyDefined()
{
$this->keyStore->addTableKey('a.b');
$this->keyStore->addKey('c');
$this->assertTrue($this->keyStore->isValidTableKey('a'));
}
public function testIsValidTableKeyMustReturnFalseWhenDuplicateTableKeys()
{
$this->keyStore->addTableKey('a');
$this->assertFalse($this->keyStore->isValidTableKey('a'));
}
public function testIsValidTableKeyMustReturnFalseWhenThereIsAKeyWithTheSameName()
{
$this->keyStore->addTableKey('a');
$this->keyStore->addKey('b');
$this->assertFalse($this->keyStore->isValidTableKey('a.b'));
}
public function testIsValidArrayTableKeyMustReturnFalseWhenThereIsAPreviousKeyWithTheSameName()
{
$this->keyStore->addKey('a');
$this->assertFalse($this->keyStore->isValidArrayTableKey('a'));
}
public function testIsValidArrayTableKeyMustReturnFalseWhenThereIsAPreviousTableWithTheSameName()
{
$this->keyStore->addTableKey('a');
$this->assertFalse($this->keyStore->isValidArrayTableKey('a'));
}
public function testIsValidTableKeyMustReturnFalseWhenAttemptingToDefineATableKeyEqualToPreviousDefinedArrayTable()
{
$this->keyStore->addArrayTableKey('a');
$this->keyStore->addArrayTableKey('a.b');
$this->assertFalse($this->keyStore->isValidTableKey('a.b'));
}
public function testIsValidTableKeyMustReturnTrueWithTablesInsideArrayOfTables()
{
$this->keyStore->addArrayTableKey('a');
$this->keyStore->addTableKey('a.b');
$this->keyStore->addArrayTableKey('a');
$this->assertTrue($this->keyStore->isValidTableKey('a.b'));
}
}

View file

@ -0,0 +1,299 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml\tests;
use PHPUnit\Framework\TestCase;
use Yosymfony\Toml\Lexer;
class LexerTest extends TestCase
{
private $lexer;
public function setUp()
{
$this->lexer = new Lexer();
}
public function testTokenizeMustRecognizeEqualToken()
{
$ts = $this->lexer->tokenize('=');
$this->assertTrue($ts->isNext('T_EQUAL'));
}
public function testTokenizeMustRecognizeBooleanTokenWhenThereIsATrueValue()
{
$ts = $this->lexer->tokenize('true');
$this->assertTrue($ts->isNext('T_BOOLEAN'));
}
public function testTokenizeMustRecognizeBooleanTokenWhenThereIsAFalseValue()
{
$ts = $this->lexer->tokenize('false');
$this->assertTrue($ts->isNext('T_BOOLEAN'));
}
public function testTokenizeMustRecognizeUnquotedKeyToken()
{
$ts = $this->lexer->tokenize('title');
$this->assertTrue($ts->isNext('T_UNQUOTED_KEY'));
}
public function testTokenizeMustRecognizeIntegerTokenWhenThereIsAPositiveNumber()
{
$ts = $this->lexer->tokenize('25');
$this->assertTrue($ts->isNext('T_INTEGER'));
}
public function testTokenizeMustRecognizeIntegerTokenWhenThereIsANegativeNumber()
{
$ts = $this->lexer->tokenize('-25');
$this->assertTrue($ts->isNext('T_INTEGER'));
}
public function testTokenizeMustRecognizeIntegerTokenWhenThereIsNumberWithUnderscoreSeparator()
{
$ts = $this->lexer->tokenize('2_5');
$this->assertTrue($ts->isNext('T_INTEGER'));
}
public function testTokenizeMustRecognizeFloatTokenWhenThereIsAFloatNumber()
{
$ts = $this->lexer->tokenize('2.5');
$this->assertTrue($ts->isNext('T_FLOAT'));
}
public function testTokenizeMustRecognizeFloatTokenWhenThereIsAFloatNumberWithUnderscoreSeparator()
{
$ts = $this->lexer->tokenize('9_224_617.445_991_228_313');
$this->assertTrue($ts->isNext('T_FLOAT'));
}
public function testTokenizeMustRecognizeFloatTokenWhenThereIsANegativeFloatNumber()
{
$ts = $this->lexer->tokenize('-2.5');
$this->assertTrue($ts->isNext('T_FLOAT'));
}
public function testTokenizeMustRecognizeFloatTokenWhenThereIsANumberWithExponent()
{
$ts = $this->lexer->tokenize('5e+22');
$this->assertTrue($ts->isNext('T_FLOAT'));
}
public function testTokenizeMustRecognizeFloatTokenWhenThereIsANumberWithExponentAndUnderscoreSeparator()
{
$ts = $this->lexer->tokenize('1e1_000');
$this->assertTrue($ts->isNext('T_FLOAT'));
}
public function testTokenizeMustRecognizeFloatTokenWhenThereIsAFloatNumberWithExponent()
{
$ts = $this->lexer->tokenize('6.626e-34');
$this->assertTrue($ts->isNext('T_FLOAT'));
}
public function testTokenizeMustRecognizeDataTimeTokenWhenThereIsRfc3339Datetime()
{
$ts = $this->lexer->tokenize('1979-05-27T07:32:00Z');
$this->assertTrue($ts->isNext('T_DATE_TIME'));
}
public function testTokenizeMustRecognizeDataTimeTokenWhenThereIsRfc3339DatetimeWithOffset()
{
$ts = $this->lexer->tokenize('1979-05-27T00:32:00-07:00');
$this->assertTrue($ts->isNext('T_DATE_TIME'));
}
public function testTokenizeMustRecognizeDataTimeTokenWhenThereIsRfc3339DatetimeWithOffsetSecondFraction()
{
$ts = $this->lexer->tokenize('1979-05-27T00:32:00.999999-07:00');
$this->assertTrue($ts->isNext('T_DATE_TIME'));
}
public function testTokenizeMustRecognizeQuotationMark()
{
$ts = $this->lexer->tokenize('"');
$this->assertTrue($ts->isNext('T_QUOTATION_MARK'));
}
public function testTokenizeMustRecognize3QuotationMark()
{
$ts = $this->lexer->tokenize('"""');
$this->assertTrue($ts->isNextSequence(['T_3_QUOTATION_MARK', 'T_EOS']));
}
public function testTokenizeMustRecognizeApostrophe()
{
$ts = $this->lexer->tokenize("'");
$this->assertTrue($ts->isNext('T_APOSTROPHE'));
}
public function testTokenizeMustRecognize3Apostrophe()
{
$ts = $this->lexer->tokenize("'''");
$this->assertTrue($ts->isNext('T_3_APOSTROPHE'));
}
public function testTokenizeMustRecognizeEscapedCharacterWhenThereIsBackspace()
{
$ts = $this->lexer->tokenize('\b');
$this->assertTrue($ts->isNext('T_ESCAPED_CHARACTER'));
}
public function testTokenizeMustRecognizeEscapedCharacterWhenThereIsTab()
{
$ts = $this->lexer->tokenize('\t');
$this->assertTrue($ts->isNext('T_ESCAPED_CHARACTER'));
}
public function testTokenizeMustRecognizeEscapedCharacterWhenThereIsLinefeed()
{
$ts = $this->lexer->tokenize('\n');
$this->assertTrue($ts->isNext('T_ESCAPED_CHARACTER'));
}
public function testTokenizeMustRecognizeEscapedCharacterWhenThereIsFormfeed()
{
$ts = $this->lexer->tokenize('\f');
$this->assertTrue($ts->isNext('T_ESCAPED_CHARACTER'));
}
public function testTokenizeMustRecognizeEscapedCharacterWhenThereIsCarriageReturn()
{
$ts = $this->lexer->tokenize('\r');
$this->assertTrue($ts->isNext('T_ESCAPED_CHARACTER'));
}
public function testTokenizeMustRecognizeEscapedCharacterWhenThereIsQuote()
{
$ts = $this->lexer->tokenize('\"');
$this->assertTrue($ts->isNext('T_ESCAPED_CHARACTER'));
}
public function testTokenizeMustRecognizeEscapedCharacterWhenThereIsBackslash()
{
$ts = $this->lexer->tokenize('\\\\');
$this->assertTrue($ts->isNext('T_ESCAPED_CHARACTER'));
}
public function testTokenizeMustRecognizeEscapedCharacterWhenThereIsUnicodeUsingFourCharacters()
{
$ts = $this->lexer->tokenize('\u00E9');
$this->assertTrue($ts->isNext('T_ESCAPED_CHARACTER'));
}
public function testTokenizeMustRecognizeEscapedCharacterWhenThereIsUnicodeUsingEightCharacters()
{
$ts = $this->lexer->tokenize('\U00E90000');
$this->assertTrue($ts->isNext('T_ESCAPED_CHARACTER'));
}
public function testTokenizeMustRecognizeBasicUnescapedString()
{
$ts = $this->lexer->tokenize('@text');
$this->assertTrue($ts->isNextSequence([
'T_BASIC_UNESCAPED',
'T_EOS'
]));
}
public function testTokenizeMustRecognizeHash()
{
$ts = $this->lexer->tokenize('#');
$this->assertTrue($ts->isNext('T_HASH'));
}
public function testTokenizeMustRecognizeEscape()
{
$ts = $this->lexer->tokenize('\\');
$this->assertTrue($ts->isNextSequence(['T_ESCAPE', 'T_EOS']));
}
public function testTokenizeMustRecognizeEscapeAndEscapedCharacter()
{
$ts = $this->lexer->tokenize('\\ \b');
$this->assertTrue($ts->isNextSequence([
'T_ESCAPE',
'T_SPACE',
'T_ESCAPED_CHARACTER',
'T_EOS'
]));
}
public function testTokenizeMustRecognizeLeftSquareBraket()
{
$ts = $this->lexer->tokenize('[');
$this->assertTrue($ts->isNext('T_LEFT_SQUARE_BRAKET'));
}
public function testTokenizeMustRecognizeRightSquareBraket()
{
$ts = $this->lexer->tokenize(']');
$this->assertTrue($ts->isNext('T_RIGHT_SQUARE_BRAKET'));
}
public function testTokenizeMustRecognizeDot()
{
$ts = $this->lexer->tokenize('.');
$this->assertTrue($ts->isNext('T_DOT'));
}
public function testTokenizeMustRecognizeLeftCurlyBrace()
{
$ts = $this->lexer->tokenize('{');
$this->assertTrue($ts->isNext('T_LEFT_CURLY_BRACE'));
}
public function testTokenizeMustRecognizeRightCurlyBrace()
{
$ts = $this->lexer->tokenize('}');
$this->assertTrue($ts->isNext('T_RIGHT_CURLY_BRACE'));
}
}

View file

@ -0,0 +1,575 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml\tests;
use PHPUnit\Framework\TestCase;
use Yosymfony\Toml\Parser;
use Yosymfony\Toml\Lexer;
class ParserInvalidTest extends TestCase
{
private $parser;
public function setUp()
{
$this->parser = new Parser(new Lexer());
}
public function tearDown()
{
$this->parser = null;
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_EQUAL" at line 1 with value "=".
*/
public function testKeyEmpty()
{
$this->parser->parse('= 1');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_HASH" at line 1 with value "#".
*/
public function testParseMustFailWhenKeyHash()
{
$this->parser->parse('a# = 1');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_NEWLINE" at line 1
*/
public function testParseMustFailWhenKeyNewline()
{
$this->parser->parse("a\n= 1");
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage The key "dupe" has already been defined previously.
*/
public function testDuplicateKeys()
{
$toml = <<<'toml'
dupe = false
dupe = true
toml;
$this->parser->parse($toml);
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_SPACE" at line 1
*/
public function testParseMustFailWhenKeyOpenBracket()
{
$this->parser->parse('[abc = 1');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_EOS" at line 1
*/
public function testParseMustFailWhenKeySingleOpenBracket()
{
$this->parser->parse('[');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_UNQUOTED_KEY" at line 1 with value "b".
*/
public function testParseMustFailWhenKeySpace()
{
$this->parser->parse('a b = 1');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_SPACE" at line 2 with value " ".
*/
public function testParseMustFailWhenKeyStartBracket()
{
$this->parser->parse("[a]\n[xyz = 5\n[b]");
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_EQUAL" at line 1 with value "=".
*/
public function testParseMustFailWhenKeyTwoEquals()
{
$this->parser->parse('key= = 1');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_UNQUOTED_KEY" at line 1 with value "the".
*/
public function testParseMustFailWhenTextAfterInteger()
{
$this->parser->parse('answer = 42 the ultimate answer?');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Invalid integer number: leading zeros are not allowed. Token: "T_INTEGER" line: 1 value "042".
*/
public function testParseMustFailWhenIntegerLeadingZeros()
{
$this->parser->parse('answer = 042');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_UNQUOTED_KEY" at line 1 with value "_42".
*/
public function testParseMustFailWhenIntegerLeadingUnderscore()
{
$this->parser->parse('answer = _42');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Invalid integer number: underscore must be surrounded by at least one digit.
*/
public function testParseMustFailWhenIntegerFinalUnderscore()
{
$this->parser->parse('answer = 42_');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Invalid integer number: leading zeros are not allowed. Token: "T_INTEGER" line: 1 value "0_42".
*/
public function testParseMustFailWhenIntegerLeadingZerosWithUnderscore()
{
$this->parser->parse('answer = 0_42');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_DOT" at line 1 with value ".".
*/
public function testParseMustFailWhenFloatNoLeadingZero()
{
$toml = <<<'toml'
answer = .12345
neganswer = -.12345
toml;
$this->parser->parse($toml);
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_DOT" at line 1 with value ".".
*/
public function testParseMustFailWhenFloatNoTrailingDigits()
{
$toml = <<<'toml'
answer = 1.
neganswer = -1.
toml;
$this->parser->parse($toml);
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_UNQUOTED_KEY" at line 1 with value "_1".
*/
public function testParseMustFailWhenFloatLeadingUnderscore()
{
$this->parser->parse('number = _1.01');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Invalid float number: underscore must be surrounded by at least one digit.
*/
public function testParseMustFailWhenFloatFinalUnderscore()
{
$this->parser->parse('number = 1.01_');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Invalid float number: underscore must be surrounded by at least one digit.
*/
public function testParseMustFailWhenFloatUnderscorePrefixE()
{
$this->parser->parse('number = 1_e6');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_UNQUOTED_KEY" at line 1 with value "e_6".
*/
public function testParseMustFailWhenFloatUnderscoreSufixE()
{
$this->parser->parse('number = 1e_6');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_INTEGER" at line 1 with value "-7".
*/
public function testParseMustFailWhenDatetimeMalformedNoLeads()
{
$this->parser->parse('no-leads = 1987-7-05T17:45:00Z');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_UNQUOTED_KEY" at line 1 with value "T17".
*/
public function testParseMustFailWhenDatetimeMalformedNoSecs()
{
$this->parser->parse('no-secs = 1987-07-05T17:45Z');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_INTEGER" at line 1 with value "17".
*/
public function testParseMustFailWhenDatetimeMalformedNoT()
{
$this->parser->parse('no-t = 1987-07-0517:45:00Z');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_INTEGER" at line 1 with value "-07".
*/
public function testParseMustFailWhenDatetimeMalformedWithMilli()
{
$this->parser->parse('with-milli = 1987-07-5T17:45:00.12Z');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_ESCAPE" at line 1 with value "\". This character is not valid.
*/
public function testParseMustFailWhenBasicStringHasBadByteEscape()
{
$this->parser->parse('naughty = "\xAg"');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_ESCAPE" at line 1 with value "\". This character is not valid.
*/
public function testParseMustFailWhenBasicStringHasBadEscape()
{
$this->parser->parse('invalid-escape = "This string has a bad \a escape character."');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_ESCAPE" at line 1 with value "\". This character is not valid.
*/
public function testParseMustFailWhenBasicStringHasByteEscapes()
{
$this->parser->parse('answer = "\x33"');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_EOS" at line 1 with value "". This character is not valid.
*/
public function testParseMustFailWhenBasicStringIsNotClose()
{
$this->parser->parse('no-ending-quote = "One time, at band camp');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_UNQUOTED_KEY" at line 1 with value "No". Expected T_NEWLINE or T_EOS.
*/
public function testParseMustFailWhenThereIsTextAfterBasicString()
{
$this->parser->parse('string = "Is there life after strings?" No.');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Data types cannot be mixed in an array. Value: "1".
*/
public function testParseMustFailWhenThereIsAnArrayWithMixedTypesArraysAndInts()
{
$this->parser->parse('arrays-and-ints = [1, ["Arrays are not integers."]]');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Data types cannot be mixed in an array. Value: "1.1".
*/
public function testParseMustFailWhenThereIsAnArrayWithMixedTypesIntsAndFloats()
{
$this->parser->parse('ints-and-floats = [1, 1.1]');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Data types cannot be mixed in an array. Value: "42".
*/
public function testParseMustFailWhenThereIsAnArrayWithMixedTypesStringsAndInts()
{
$this->parser->parse('strings-and-ints = ["hi", 42]');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_UNQUOTED_KEY" at line 2 with value "No".
*/
public function testParseMustFailWhenAppearsTextAfterArrayEntries()
{
$toml = <<<'toml'
array = [
"Is there life after an array separator?", No
"Entry"
]
toml;
$this->parser->parse($toml);
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_UNQUOTED_KEY" at line 2 with value "No".
*/
public function testParseMustFailWhenAppearsTextBeforeArraySeparator()
{
$toml = <<<'toml'
array = [
"Is there life before an array separator?" No,
"Entry"
]
toml;
$this->parser->parse($toml);
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_UNQUOTED_KEY" at line 3 with value "I".
*/
public function testParseMustFailWhenAppearsTextInArray()
{
$toml = <<<'toml'
array = [
"Entry 1",
I don't belong,
"Entry 2",
]
toml;
$this->parser->parse($toml);
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage The key "fruit.type" has already been defined previously.
*/
public function testParseMustFailWhenDuplicateKeyTable()
{
$toml = <<<'toml'
[fruit]
type = "apple"
[fruit.type]
apple = "yes"
toml;
$this->parser->parse($toml);
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage The key "a" has already been defined previously.
*/
public function testParseMustFailWhenDuplicateTable()
{
$toml = <<<'toml'
[a]
[a]
toml;
$this->parser->parse($toml);
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_RIGHT_SQUARE_BRAKET" at line 1 with value "]".
*/
public function testParseMustFailWhenTableEmpty()
{
$this->parser->parse('[]');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_SPACE" at line 1 with value " ".
*/
public function testParseMustFailWhenTableWhitespace()
{
$this->parser->parse('[invalid key]');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_DOT" at line 1 with value ".".
*/
public function testParseMustFailWhenEmptyImplicitTable()
{
$this->parser->parse('[naughty..naughty]');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_HASH" at line 1 with value "#".
*/
public function testParseMustFailWhenTableWithPound()
{
$this->parser->parse("[key#group]\nanswer = 42");
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_UNQUOTED_KEY" at line 1 with value "this".
*/
public function testParseMustFailWhenTextAfterTable()
{
$this->parser->parse('[error] this shouldn\'t be here');
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_LEFT_SQUARE_BRAKET" at line 1 with value "[".
*/
public function testParseMustFailWhenTableNestedBracketsOpen()
{
$toml = <<<'toml'
[a[b]
zyx = 42
toml;
$this->parser->parse($toml);
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_UNQUOTED_KEY" at line 1 with value "b".
*/
public function testParseMustFailWhenTableNestedBracketsClose()
{
$toml = <<<'toml'
[a]b]
zyx = 42
toml;
$this->parser->parse($toml);
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_NEWLINE" at line 1
*/
public function testParseMustFailWhenInlineTableWithNewline()
{
$toml = <<<'toml'
name = { first = "Tom",
last = "Preston-Werner"
}
toml;
$this->parser->parse($toml);
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage The key "fruit.variety" has already been defined previously.
*/
public function testParseMustFailWhenTableArrayWithSomeNameOfTable()
{
$toml = <<<'toml'
[[fruit]]
name = "apple"
[[fruit.variety]]
name = "red delicious"
# This table conflicts with the previous table
[fruit.variety]
name = "granny smith"
toml;
$this->parser->parse($toml);
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_RIGHT_SQUARE_BRAKET" at line 1 with value "]".
*/
public function testParseMustFailWhenTableArrayMalformedEmpty()
{
$toml = <<<'toml'
[[]]
name = "Born to Run"
toml;
$this->parser->parse($toml);
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage Syntax error: unexpected token "T_NEWLINE" at line 1
*/
public function testParseMustFailWhenTableArrayMalformedBracket()
{
$toml = <<<'toml'
[[albums]
name = "Born to Run"
toml;
$this->parser->parse($toml);
}
/**
* @expectedException Yosymfony\ParserUtils\SyntaxErrorException
* @expectedExceptionMessage The array of tables "albums" has already been defined as previous table
*/
public function testParseMustFailWhenTableArrayImplicit()
{
$toml = <<<'toml'
# This test is a bit tricky. It should fail because the first use of
# `[[albums.songs]]` without first declaring `albums` implies that `albums`
# must be a table. The alternative would be quite weird. Namely, it wouldn't
# comply with the TOML spec: "Each double-bracketed sub-table will belong to
# the most *recently* defined table element *above* it."
#
# This is in contrast to the *valid* test, table-array-implicit where
# `[[albums.songs]]` works by itself, so long as `[[albums]]` isn't declared
# later. (Although, `[albums]` could be.)
[[albums.songs]]
name = "Glory Days"
[[albums]]
name = "Born in the USA"
toml;
$this->parser->parse($toml);
}
}

View file

@ -0,0 +1,936 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml\tests;
use PHPUnit\Framework\TestCase;
use Yosymfony\Toml\Parser;
use Yosymfony\Toml\Lexer;
class ParserTest extends TestCase
{
private $parser;
public function setUp()
{
$this->parser = new Parser(new Lexer());
}
public function tearDown()
{
$this->parser = null;
}
public function testParseMustReturnAnEmptyArrayWhenEmptyInput()
{
$array = $this->parser->parse('');
$this->assertEquals([], $array);
}
public function testParseMustParseBooleans()
{
$toml = <<<'toml'
t = true
f = false
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
't' => true,
'f' => false,
], $array);
}
public function testParseMustParseIntegers()
{
$toml = <<<'toml'
answer = 42
neganswer = -42
positive = +90
underscore = 1_2_3_4_5
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'answer' => 42,
'neganswer' => -42,
'positive' => 90,
'underscore' => 12345,
], $array);
}
public function testParseMustParseLongIntegers()
{
$toml = <<<'toml'
answer = 9223372036854775807
neganswer = -9223372036854775808
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'answer' => 9223372036854775807,
'neganswer' => -9223372036854775808,
], $array);
}
public function testParseMustParseFloats()
{
$toml = <<<'toml'
pi = 3.14
negpi = -3.14
positive = +1.01
exponent1 = 5e+22
exponent2 = 1e6
exponent3 = -2E-2
exponent4 = 6.626e-34
underscore = 6.6_26e-3_4
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'pi' => 3.14,
'negpi' => -3.14,
'positive' => 1.01,
'exponent1' => 4.9999999999999996E+22,
'exponent2' => 1000000.0,
'exponent3' => -0.02,
'exponent4' => 6.6259999999999998E-34,
'underscore' => 6.6259999999999998E-34,
], $array);
}
public function testParseMustParseLongFloats()
{
$toml = <<<'toml'
longpi = 3.141592653589793
neglongpi = -3.141592653589793
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'longpi' => 3.141592653589793,
'neglongpi' => -3.141592653589793
], $array);
}
public function testParseMustParseBasicStringsWithASimpleString()
{
$array = $this->parser->parse('answer = "You are not drinking enough whisky."');
$this->assertEquals([
'answer' => 'You are not drinking enough whisky.',
], $array);
}
public function testParseMustParseAnEmptyString()
{
$array = $this->parser->parse('answer = ""');
$this->assertEquals([
'answer' => '',
], $array);
}
public function testParseMustParseStringsWithEscapedCharacters() : void
{
$toml = <<<'toml'
backspace = "This string has a \b backspace character."
tab = "This string has a \t tab character."
newline = "This string has a \n new line character."
formfeed = "This string has a \f form feed character."
carriage = "This string has a \r carriage return character."
quote = "This string has a \" quote character."
backslash = "This string has a \\ backslash character."
notunicode1 = "This string does not have a unicode \\u escape."
notunicode2 = "This string does not have a unicode \\u0075 escape."
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'backspace' => "This string has a \b backspace character.",
'tab' => "This string has a \t tab character.",
'newline' => "This string has a \n new line character.",
'formfeed' => "This string has a \f form feed character.",
'carriage' => "This string has a \r carriage return character.",
'quote' => 'This string has a " quote character.',
'backslash' => 'This string has a \\ backslash character.',
'notunicode1' => 'This string does not have a unicode \\u escape.',
'notunicode2' => 'This string does not have a unicode \\u0075 escape.',
], $array);
}
public function testParseMustParseStringsWithPound()
{
$toml = <<<'toml'
pound = "We see no # comments here."
poundcomment = "But there are # some comments here." # Did I # mess you up?
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'pound' => 'We see no # comments here.',
'poundcomment' => 'But there are # some comments here.'
], $array);
}
public function testParseMustParseWithUnicodeCharacterEscaped()
{
$toml = <<<'toml'
answer4 = "\u03B4"
answer8 = "\U000003B4"
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'answer4' => json_decode('"\u03B4"'),
'answer8' => json_decode('"\u0000\u03B4"'),
], $array);
}
public function testParseMustParseStringWithALiteralUnicodeCharacter()
{
$array = $this->parser->parse('answer = "δ"');
$this->assertEquals([
'answer' => 'δ',
], $array);
}
public function testParseMustParseMultilineStrings()
{
$toml = <<<'toml'
multiline_empty_one = """"""
multiline_empty_two = """
"""
multiline_empty_three = """\
"""
multiline_empty_four = """\
\
\
"""
equivalent_one = "The quick brown fox jumps over the lazy dog."
equivalent_two = """
The quick brown \
fox jumps over \
the lazy dog."""
equivalent_three = """\
The quick brown \
fox jumps over \
the lazy dog.\
"""
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'multiline_empty_one' => '',
'multiline_empty_two' => '',
'multiline_empty_three' => '',
'multiline_empty_four' => '',
'equivalent_one' => 'The quick brown fox jumps over the lazy dog.',
'equivalent_two' => 'The quick brown fox jumps over the lazy dog.',
'equivalent_three' => 'The quick brown fox jumps over the lazy dog.',
], $array);
}
public function testParseMustParseLiteralStrings()
{
$toml = <<<'toml'
backspace = 'This string has a \b backspace character.'
tab = 'This string has a \t tab character.'
newline = 'This string has a \n new line character.'
formfeed = 'This string has a \f form feed character.'
carriage = 'This string has a \r carriage return character.'
slash = 'This string has a \/ slash character.'
backslash = 'This string has a \\ backslash character.'
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'backspace' => 'This string has a \b backspace character.',
'tab' => 'This string has a \t tab character.',
'newline' => 'This string has a \n new line character.',
'formfeed' => 'This string has a \f form feed character.',
'carriage' => 'This string has a \r carriage return character.',
'slash' => 'This string has a \/ slash character.',
'backslash' => 'This string has a \\\\ backslash character.',
], $array);
}
public function testParseMustParseMultilineLiteralStrings()
{
$toml = <<<'toml'
oneline = '''This string has a ' quote character.'''
firstnl = '''
This string has a ' quote character.'''
multiline = '''
This string
has ' a quote character
and more than
one newline
in it.'''
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'oneline' => "This string has a ' quote character.",
'firstnl' => "This string has a ' quote character.",
'multiline' => "This string\nhas ' a quote character\nand more than\none newline\nin it.",
], $array);
}
public function testDatetime()
{
$toml = <<<'toml'
bestdayever = 1987-07-05T17:45:00Z
bestdayever2 = 1979-05-27T00:32:00-07:00
bestdayever3 = 1979-05-27T00:32:00.999999-07:00
bestdayever4 = 1979-05-27T07:32:00
bestdayever5 = 1979-05-27T00:32:00.999999
bestdayever6 = 1979-05-27
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'bestdayever' => new \Datetime('1987-07-05T17:45:00Z'),
'bestdayever2' => new \Datetime('1979-05-27T00:32:00-07:00'),
'bestdayever3' => new \Datetime('1979-05-27T00:32:00.999999-07:00'),
'bestdayever4' => new \Datetime('1979-05-27T07:32:00'),
'bestdayever5' => new \Datetime('1979-05-27T00:32:00.999999'),
'bestdayever6' => new \Datetime('1979-05-27'),
], $array);
}
public function testParseMustParseArraysWithNoSpaces()
{
$array = $this->parser->parse('ints = [1,2,3]');
$this->assertEquals([
'ints' => [1,2,3],
], $array);
}
public function testParseMustParseHeterogeneousArrays()
{
$array = $this->parser->parse('mixed = [[1, 2], ["a", "b"], [1.1, 2.1]]');
$this->assertEquals([
'mixed' => [
[1,2],
['a', 'b'],
[1.1, 2.1],
],
], $array);
}
public function testParseMustParseArraysNested()
{
$array = $this->parser->parse('nest = [["a"], ["b"]]');
$this->assertEquals([
'nest' => [
['a'],
['b']
],
], $array);
}
public function testArrayEmpty()
{
$array = $this->parser->parse('thevoid = [[[[[]]]]]');
$this->assertEquals([
'thevoid' => [
[
[
[
[],
],
],
],
],
], $array);
}
public function testParseMustParseArrays()
{
$toml = <<<'toml'
ints = [1, 2, 3]
floats = [1.1, 2.1, 3.1]
strings = ["a", "b", "c"]
allStrings = ["all", 'strings', """are the same""", '''type''']
MultilineBasicString = ["all", """
Roses are red
Violets are blue""",]
dates = [
1987-07-05T17:45:00Z,
1979-05-27T07:32:00Z,
2006-06-01T11:00:00Z,
]
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'ints' => [1, 2, 3],
'floats' => [1.1, 2.1, 3.1],
'strings' => ['a', 'b', 'c'],
'allStrings' => ['all', 'strings', 'are the same', 'type'],
'MultilineBasicString' => [
'all',
"Roses are red\nViolets are blue",
],
'dates' => [
new \DateTime('1987-07-05T17:45:00Z'),
new \DateTime('1979-05-27T07:32:00Z'),
new \DateTime('2006-06-01T11:00:00Z'),
],
], $array);
}
public function testParseMustParseAKeyWithoutNameSpacesAroundEqualSign()
{
$array = $this->parser->parse('answer=42');
$this->assertEquals([
'answer' => 42,
], $array);
}
public function testParseMustParseKeyWithSpace()
{
$array = $this->parser->parse('"a b" = 1');
$this->assertNotNull($array);
$this->assertEquals([
'a b' => 1,
], $array);
}
public function testParseMustParseKeyWithSpecialCharacters()
{
$array = $this->parser->parse('"~!@$^&*()_+-`1234567890[]|/?><.,;:\'" = 1');
$this->assertEquals([
'~!@$^&*()_+-`1234567890[]|/?><.,;:\'' => 1,
], $array);
}
public function testParseMustParseBareIntegerKeys()
{
$toml = <<<'toml'
[sequence]
-1 = 'detect person'
0 = 'say hello'
1 = 'chat'
10 = 'say bye'
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'sequence' => [
'-1' => 'detect person',
'0' => 'say hello',
'1' => 'chat',
'10' => 'say bye'
]
], $array);
}
public function testParseMustParseAnEmptyTable()
{
$array = $this->parser->parse('[a]');
$this->assertEquals([
'a' => [],
], $array);
}
public function testParseMustParseATableWithAWhiteSpaceInTheName()
{
$array = $this->parser->parse('["valid key"]');
$this->assertEquals([
'valid key' => [],
], $array);
}
public function testParseMustParseATableAQuotedName()
{
$toml = <<<'toml'
[dog."tater.man"]
type = "pug"
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'dog' => [
'tater.man' => [
'type' => 'pug',
],
],
], $array);
}
public function testParseMustParseATableWithAPoundInTheName()
{
$toml = <<<'toml'
["key#group"]
answer = 42
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'key#group' => [
'answer' => 42,
],
], $array);
}
public function testParseMustParseATableAndASubtableEmpties()
{
$toml = <<<'toml'
[a]
[a.b]
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'a' => [
'b' => [],
],
], $array);
}
public function testParseMustParseATableWithImplicitGroups()
{
$toml = <<<'toml'
[a.b.c]
answer = 42
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'a' => [
'b' => [
'c' => [
'answer' => 42,
],
],
],
], $array);
}
public function testParseMustParseAImplicitAndExplicitAfterTable()
{
$toml = <<<'toml'
[a.b.c]
answer = 42
[a]
better = 43
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'a' => [
'better' => 43,
'b' => [
'c' => [
'answer' => 42,
],
],
],
], $array);
}
public function testParseMustParseImplicitAndExplicitTableBefore()
{
$toml = <<<'toml'
[a]
better = 43
[a.b.c]
answer = 42
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'a' => [
'better' => 43,
'b' => [
'c' => [
'answer' => 42,
],
],
],
], $array);
}
public function testParseMustParseInlineTableEmpty()
{
$array = $this->parser->parse('name = {}');
$this->assertEquals([
'name' => [],
], $array);
}
public function testParseMustParseInlineTableOneElement()
{
$array = $this->parser->parse('name = { first = "Tom" }');
$this->assertEquals([
'name' => [
'first' => 'Tom'
],
], $array);
}
public function testParseMustParseAnInlineTableDefinedInATable()
{
$toml = <<<'toml'
[tab1]
key1 = {name='Donald Duck'}
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'tab1' => [
'key1' => [
'name' => 'Donald Duck'
],
],
], $array);
}
public function testParseMustParseInlineTableExamples()
{
$toml = <<<'toml'
name = { first = "Tom", last = "Preston-Werner" }
point = { x = 1, y = 2 }
strings = { key1 = """
Roses are red
Violets are blue""", key2 = """
The quick brown \
fox jumps over \
the lazy dog.""" }
inline = { x = 1, y = { a = 2, "b.deep" = 'my value' } }
another = {number = 1}
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'name' => [
'first' => 'Tom',
'last' => 'Preston-Werner',
],
'point' => [
'x' => 1,
'y' => 2,
],
'strings' => [
'key1' => "Roses are red\nViolets are blue",
'key2' => 'The quick brown fox jumps over the lazy dog.',
],
'inline' => [
'x' => 1,
'y' => [
'a' => 2,
'b.deep' => 'my value',
],
],
'another' => [
'number' => 1,
],
], $array);
}
public function testParseMustParseTableArrayImplicit()
{
$toml = <<<'toml'
[[albums.songs]]
name = "Glory Days"
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'albums' => [
'songs' => [
[
'name' => 'Glory Days'
],
],
],
], $array);
}
public function testParseMustParseTableArrayOne()
{
$toml = <<<'toml'
[[people]]
first_name = "Bruce"
last_name = "Springsteen"
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'people' => [
[
'first_name' => 'Bruce',
'last_name' => 'Springsteen',
],
],
], $array);
}
public function testParseMustParseTableArrayMany()
{
$toml = <<<'toml'
[[people]]
first_name = "Bruce"
last_name = "Springsteen"
[[people]]
first_name = "Eric"
last_name = "Clapton"
[[people]]
first_name = "Bob"
last_name = "Seger"
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'people' => [
[
'first_name' => 'Bruce',
'last_name' => 'Springsteen',
],
[
'first_name' => 'Eric',
'last_name' => 'Clapton',
],
[
'first_name' => 'Bob',
'last_name' => 'Seger',
],
],
], $array);
}
public function testParseMustParseTableArrayNest()
{
$toml = <<<'toml'
[[albums]]
name = "Born to Run"
[[albums.songs]]
name = "Jungleland"
[[albums.songs]]
name = "Meeting Across the River"
[[albums]]
name = "Born in the USA"
[[albums.songs]]
name = "Glory Days"
[[albums.songs]]
name = "Dancing in the Dark"
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'albums' => [
[
'name' => 'Born to Run',
'songs' => [
['name' => 'Jungleland'],
['name' => 'Meeting Across the River'],
],
],
[
'name' => 'Born in the USA',
'songs' => [
['name' => 'Glory Days'],
['name' => 'Dancing in the Dark'],
],
],
],
], $array);
}
/**
* @see https://github.com/yosymfony/toml/issues/12
*/
public function testParseMustParseATableAndArrayOfTables()
{
$toml = <<<'toml'
[fruit]
name = "apple"
[[fruit.variety]]
name = "red delicious"
[[fruit.variety]]
name = "granny smith"
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'fruit' => [
'name' => 'apple',
'variety' => [
['name' => 'red delicious'],
['name' => 'granny smith'],
],
],
], $array);
}
/**
* @see https://github.com/yosymfony/toml/issues/23
*/
public function testParseMustParseTablesContainedWithinArrayTables()
{
$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;
$array = $this->parser->parse($toml);
$this->assertEquals([
'tls' => [
[
'entrypoints' => ['https'],
'certificate' => [
'certFile' => 'certs/foo.crt',
'keyFile' => 'keys/foo.key',
],
],
[
'entrypoints' => ['https'],
'certificate' => [
'certFile' => 'certs/bar.crt',
'keyFile' => 'keys/bar.key',
],
],
],
], $array);
}
public function testParseMustParseCommentsEverywhere()
{
$toml = <<<'toml'
# Top comment.
# Top comment.
# Top comment.
# [no-extraneous-groups-please]
[group] # Comment
answer = 42 # Comment
# no-extraneous-keys-please = 999
# Inbetween comment.
more = [ # Comment
# What about multiple # comments?
# Can you handle it?
#
# Evil.
# Evil.
42, 42, # Comments within arrays are fun.
# What about multiple # comments?
# Can you handle it?
#
# Evil.
# Evil.
# ] Did I fool you?
] # Hopefully not.
toml;
$array = $this->parser->parse($toml);
$this->assertNotNull($array);
$this->assertArrayHasKey('answer', $array['group']);
$this->assertArrayHasKey('more', $array['group']);
$this->assertEquals($array['group']['answer'], 42);
$this->assertEquals($array['group']['more'][0], 42);
$this->assertEquals($array['group']['more'][1], 42);
}
public function testParseMustParseASimpleExample()
{
$toml = <<<'toml'
best-day-ever = 1987-07-05T17:45:00Z
emptyName = ""
[numtheory]
boring = false
perfection = [6, 28, 496]
toml;
$array = $this->parser->parse($toml);
$this->assertEquals([
'best-day-ever' => new \DateTime('1987-07-05T17:45:00Z'),
'emptyName' => '',
'numtheory' => [
'boring' => false,
'perfection' => [6, 28, 496],
],
], $array);
}
}

View file

@ -0,0 +1,71 @@
<?php
/*
* This file is part of the Yosymfony Toml.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml\tests;
use PHPUnit\Framework\TestCase;
use Yosymfony\Toml\TomlArray;
class TomlArrayTest extends TestCase
{
/** @var TomlArray */
private $tomlArray;
public function setUp()
{
$this->tomlArray = new TomlArray();
}
public function tearDown()
{
$this->tomlArray = null;
}
public function testGetArrayMustReturnTheKeyValueAdded() : void
{
$this->tomlArray->addKeyValue('company', 'acme');
$this->assertEquals([
'company' => 'acme'
], $this->tomlArray->getArray());
}
public function testGetArrayMustReturnTheTableWithTheKeyValue() : void
{
$this->tomlArray->addTableKey('companyData');
$this->tomlArray->addKeyValue('company', 'acme');
$this->assertEquals([
'companyData' => [
'company' => 'acme'
],
], $this->tomlArray->getArray());
}
public function testGetArrayMustReturnAnArrayOfTables() : void
{
$this->tomlArray->addArrayTableKey('companyData');
$this->tomlArray->addKeyValue('company', 'acme1');
$this->tomlArray->addArrayTableKey('companyData');
$this->tomlArray->addKeyValue('company', 'acme2');
$this->assertEquals([
'companyData' => [
[
'company' => 'acme1'
],
[
'company' => 'acme2'
],
]
], $this->tomlArray->getArray());
}
}

View file

@ -0,0 +1,174 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml\tests;
use PHPUnit\Framework\TestCase;
use Yosymfony\Toml\TomlBuilder;
class TomlBuilderInvalidTest extends TestCase
{
private $builder;
public function setUp() : void
{
$this->builder = new TomlBuilder();
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage A key, table name or array of table name cannot be empty or null.
*/
public function testAddValueMustFailWhenEmptyKey()
{
$this->builder->addValue('', 'value');
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage A key, table name or array of table name cannot be empty or null.
*/
public function testAddTableMustFailWhenEmptyKey()
{
$this->builder->addTable('');
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage A key, table name or array of table name cannot be empty or null.
*/
public function testAddArrayOfTableMustFailWhenEmptyKey()
{
$this->builder->addArrayOfTable('');
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage A key, table name or array of table name cannot be empty or null.
*/
public function testAddValueMustFailWhenKeyWithJustWhiteSpaces()
{
$whiteSpaceKey = ' ';
$this->builder->addValue($whiteSpaceKey, 'value');
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage A key, table name or array of table name cannot be empty or null.
*/
public function testAddTableMustFailWhenKeyWithJustWhiteSpaces()
{
$whiteSpaceKey = ' ';
$this->builder->addTable($whiteSpaceKey);
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage A key, table name or array of table name cannot be empty or null.
*/
public function testAddArrayOfTableMustFailWhenKeyWithJustWhiteSpaces()
{
$whiteSpaceKey = ' ';
$this->builder->addArrayOfTable($whiteSpaceKey);
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage Data types cannot be mixed in an array. Key: "strings-and-ints".
*/
public function testAddValueMustFailWhenMixedTypes()
{
$this->builder->addValue('strings-and-ints', ["uno", 1]);
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage The table key "a" has already been defined previously.
*/
public function testAddTableMustFailWhenDuplicateTables()
{
$this->builder->addTable('a')
->addTable('a');
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage The table key "fruit.type" has already been defined previously.
*/
public function testAddTableMustFailWhenDuplicateKeyTable()
{
$this->builder->addTable('fruit')
->addValue('type', 'apple')
->addTable('fruit.type');
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage The key "dupe" has already been defined previously.
*/
public function testAddValueMustFailWhenDuplicateKeys()
{
$this->builder->addValue('dupe', false)
->addValue('dupe', true);
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage A key, table name or array of table name cannot be empty or null. Table: "naughty..naughty".
*/
public function testEmptyImplicitKeyGroup()
{
$this->builder->addTable('naughty..naughty');
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage Data type not supporter at the key: "theNull".
*/
public function testAddValueMustFailWithNullValue()
{
$this->builder->addValue('theNull', null);
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage Data type not supporter at the key: "theNewClass".
*/
public function testAddValueMustFailWithUnsuportedValueType()
{
$this->builder->addValue('theNewClass', new class {
});
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage The key "albums" has been defined as a implicit table from a previous array of tables.
*/
public function testaddArrayOfTableMustFailWhenThereIsATableArrayImplicit()
{
$this->builder->addArrayOfTable('albums.songs')
->addValue('name', 'Glory Days')
->addArrayOfTable('albums')
->addValue('name', 'Born in the USA');
}
/**
* @expectedException Yosymfony\Toml\Exception\DumpException
* @expectedExceptionMessage Only unquoted keys are allowed in this implementation. Key: "valid key".
*/
public function testAddTableMustFailWithNoUnquotedKeys()
{
$this->builder->addTable('valid key');
}
}

View file

@ -0,0 +1,208 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml\tests;
use PHPUnit\Framework\TestCase;
use Yosymfony\Toml\TomlBuilder;
use Yosymfony\Toml\Toml;
class TomlBuilderTest extends TestCase
{
public function testExample()
{
$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('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())))
->getTomlString();
$this->assertNotNull(Toml::Parse($result));
}
public function testArrayEmpty()
{
$tb = new TomlBuilder();
$result = $tb->addComment('Toml file')
->addValue('thevoid', array())
->getTomlString();
$this->assertNotNull(Toml::Parse($result));
}
public function testImplicitAndExplicitAfter()
{
$tb = new TomlBuilder();
$result = $tb->addTable('a.b.c')
->addValue('answer', 42)
->addTable('a')
->addValue('better', 43)
->getTomlString();
$this->assertNotNull(Toml::Parse($result));
}
public function testImplicitAndExplicitBefore()
{
$tb = new TomlBuilder();
$result = $tb->addTable('a')
->addValue('better', 43)
->addTable('a.b.c')
->addValue('answer', 42)
->getTomlString();
$this->assertNotNull(Toml::Parse($result));
}
public function testTableEmpty()
{
$tb = new TomlBuilder();
$result = $tb->addTable('a')
->getTomlString();
$this->assertNotNull(Toml::Parse($result));
}
public function testTableSubEmpty()
{
$tb = new TomlBuilder();
$result = $tb->addTable('a')
->addTable('a.b')
->getTomlString();
$this->assertNotNull(Toml::Parse($result));
}
public function testKeyWhitespace()
{
$tb = new TomlBuilder();
$result = $tb->addValue('valid key', 2)
->getTomlString();
$this->assertNotNull(Toml::Parse($result));
}
public function testStringEscapesDoubleQuote()
{
$tb = new TomlBuilder();
$result = $tb->addValue('backspace', "This string has a \b backspace character.")
->addValue('tab', "This string has a \t tab character.")
->addValue('newline', "This string has a \n new line character.")
->addValue('formfeed', "This string has a \f form feed character.")
->addValue('carriage', "This string has a \r carriage return character.")
->addValue('quote', 'This string has a " quote character.')
->addValue('slash', "This string has a / slash character.")
->addValue('backslash', 'This string has a \\ backslash character.')
->getTomlString();
$this->assertNotNull(Toml::Parse($result));
}
public function testKeyLiteralString()
{
$tb = new TomlBuilder();
$result = $tb->addValue('regex', "@<\i\c*\s*>")
->getTomlString();
$array = Toml::Parse($result);
$this->assertNotNull($array);
$this->assertEquals('<\i\c*\s*>', $array['regex']);
}
public function testKeyLiteralStringEscapingAt()
{
$tb = new TomlBuilder();
$result = $tb->addValue('regex', "@@<\i\c*\s*>")
->getTomlString();
$array = Toml::Parse($result);
$this->assertNotNull($array);
$this->assertEquals('@<\i\c*\s*>', $array['regex']);
}
public function testKeySpecialChars()
{
$tb = new TomlBuilder();
$result = $tb->addValue('~!@$^&*()_+-`1234567890[]|/?><.,;:\'', 1)
->getTomlString();
$this->assertNotNull(Toml::Parse($result));
}
public function testStringEscapesSingleQuote()
{
$tb = new TomlBuilder();
$result = $tb->addValue('backspace', 'This string has a \b backspace character.')
->addValue('tab', 'This string has a \t tab character.')
->addValue('newline', 'This string has a \n new line character.')
->addValue('formfeed', 'This string has a \f form feed character.')
->addValue('carriage', 'This string has a \r carriage return character.')
->addValue('quote', 'This string has a \" quote character.')
->addValue('slash', 'This string has a \/ slash character.')
->addValue('backslash', 'This string has a \\ backslash character.')
->getTomlString();
$this->assertNotNull(Toml::Parse($result));
}
public function testArrayOfTables()
{
$tb = new TomlBuilder();
$result = $tb->addArrayOfTable('fruit')
->addValue('name', 'apple')
->addArrayOfTable('fruit.variety')
->addValue('name', 'red delicious')
->addArrayOfTable('fruit.variety')
->addValue('name', 'granny smith')
->addArrayOfTable('fruit')
->addValue('name', 'banana')
->addArrayOfTable('fruit.variety')
->addValue('name', 'plantain')
->getTomlString();
$this->assertNotNull(Toml::Parse($result));
}
}

View file

@ -0,0 +1,75 @@
<?php
/*
* This file is part of the Yosymfony\Toml package.
*
* (c) YoSymfony <http://github.com/yosymfony>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Yosymfony\Toml\tests;
use PHPUnit\Framework\TestCase;
use Yosymfony\Toml\Toml;
class TomlTest extends TestCase
{
public function testParseMustParseAString()
{
$array = Toml::parse('data = "question"');
$this->assertEquals([
'data' => 'question',
], $array);
}
public function testParseMustReturnEmptyArrayWhenStringEmpty()
{
$array = Toml::parse('');
$this->assertNull($array);
}
public function testParseFileMustParseFile()
{
$filename = __DIR__.'/fixtures/simple.toml';
$array = Toml::parseFile($filename);
$this->assertEquals([
'name' => 'Víctor',
], $array);
}
public function testParseMustReturnAnObjectWhenArgumentResultAsObjectIsTrue()
{
$actual = Toml::parse('name = "Víctor"', true);
$expected = new \stdClass();
$expected->name = 'Víctor';
$this->assertEquals($expected, $actual);
}
public function testParseFileMustReturnAnObjectWhenArgumentResultAsObjectIsTrue()
{
$filename = __DIR__.'/fixtures/simple.toml';
$actual = Toml::parseFile($filename, true);
$expected = new \stdClass();
$expected->name = 'Víctor';
$this->assertEquals($expected, $actual);
}
/**
* @expectedException Yosymfony\Toml\Exception\ParseException
*/
public function testParseFileMustFailWhenFilenameDoesNotExists()
{
$filename = __DIR__.'/fixtures/does-not-exists.toml';
Toml::parseFile($filename);
}
}

View file

@ -0,0 +1 @@
name = "Víctor"