Skip to content

Commit

Permalink
fix tests, fix else support, deprecate methods, update readme (finall…
Browse files Browse the repository at this point in the history
…y), license
  • Loading branch information
matronator committed Jun 5, 2024
1 parent 58ba4c7 commit 279ae50
Show file tree
Hide file tree
Showing 7 changed files with 451 additions and 239 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ vendor
parsem.sketch
.DS_Store
dump.log
.idea/
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2022 Matronator
Copyright (c) 2022-2024 Matronator

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
79 changes: 35 additions & 44 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

![Pars'Em logo](.github/parsem-logo.png)

Simple lightweight templating engine made for (primarily) JSON, YAML and NEON templates.
Simple lightweight templating engine made in PHP.

Enhance your JSON/YAML/NEON files with variables and PHP functions as filters. Create re-usable templates by adding variable `<% placeholder %>`'s anywhere in your file and have the content change dynamically based on the arguments you provide.
Enhance your files with variables, conditional blocks and PHP functions as filters. Create re-usable templates by adding variable `<% placeholder %>`'s anywhere in your file and have the content change dynamically based on the arguments you provide.

<!-- @import "[TOC]" {cmd="toc" depthFrom=2 depthTo=6 orderedList=false} -->

Expand All @@ -18,16 +18,14 @@ Enhance your JSON/YAML/NEON files with variables and PHP functions as filters. C
- [Template syntax](#template-syntax)
- [Conditions](#conditions)
- [Variables](#variables)
- [Default values](#default-values)
- [Default values](#default-values)
- [Filters](#filters)
- [Built-in filters](#built-in-filters)
- [Use in code](#use-in-code)
- [Parse string or file](#parse-string-or-file)
- [Methods](#methods)
- [`Parser::parseString`](#parserparsestring)
- [`Parser::parseFile`](#parserparsefile)
- [`Parser::parseFileToString`](#parserparsefiletostring)
- [Using custom parser](#using-custom-parser)
- [`Parser::parse`](#parserparse)

<!-- /code_chunk_output -->

Expand All @@ -36,14 +34,13 @@ Enhance your JSON/YAML/NEON files with variables and PHP functions as filters. C
- Parse string templates to string
- Replace variable placeholders with provided arguments
- Apply filter functions to variables
- Use [built-in filters](#built-in-filters) or provide custom functions
- Use `<% if %>` blocks to conditionally parse the template
- Use `<% else %>` blocks to provide an alternative content if the condition is not met
- Parse template files to string
- Parse the entire file as a string regardless of extension
- Parse the entire file as a string
- Provide a custom regex pattern to parse functions to use a custom syntax
- Convert JSON, YAML and NEON files to a PHP object
- Convert any file type to a PHP object by providing a custom parsing function
- Get all variable placeholders from a string
- Validate a template file against the [mtrgen-template-schema](https://www.mtrgen.com/storage/schemas/template/latest/mtrgen-template-schema.json)
- Get all variables from a template

## Requirements

Expand All @@ -66,7 +63,7 @@ use Matronator\Parsem\Parser;

### Templates Syntax Highlighting for VS Code

To get syntax highlighting for template files (highlight `<% variable|placeholders %>` even inside strings), you can download the [MTRGen Templates Syntax Highlighting](https://marketplace.visualstudio.com/items?itemName=matronator.mtrgen-yaml-templates) extension for VS Code.
To get syntax highlighting for template files (highlight `<% variable|placeholders %>` and `<% if %><% else %><% endif %>` even inside strings), you can download the [MTRGen Templates Syntax Highlighting](https://marketplace.visualstudio.com/items?itemName=matronator.mtrgen-yaml-templates) extension for VS Code.

## Usage

Expand All @@ -76,6 +73,8 @@ To get syntax highlighting for template files (highlight `<% variable|placeholde

You can use conditions in your templates by using the `<% if %>` and `<% endif %>` tags. The condition must be a valid PHP expression that will be evaluated and if it returns `true`, the content between the tags will be included in the final output.

You can also use the `<% else %>` tag to provide an alternative content if the condition is not met.

To use a variable provided in the arguments array in a condition, you must use the `$` sign before the variable name, like this: `<% if $variable == 'value' %>`. The `$` sign is used to differentiate between the template variable and a keyword such as `true` or `null`.

##### Example:
Expand All @@ -85,6 +84,8 @@ some:
key
<% if $variable == 'value' %>
with value
<% else %>
without value
<% endif %>
```
Expand All @@ -96,6 +97,14 @@ some:
with value
```

And if you provide an argument `['variable' => 'other value']`, the final output will be this:

```yaml
some:
key
without value
```

#### Variables

Variables are wrapped in `<%` and `%>` with optional space on either side (both `<%nospace%>` and `<% space %>` are valid) and the name must be an alphanumeric string with optional underscore/s (this regex `[a-zA-Z0-9_]+?`).
Expand All @@ -106,6 +115,8 @@ Variables can optionally have a default value that will be used if no argument i

If you're going to use filters, the default value comes before the filter, ie.: `<% variable='Default'|filter %>`

If default value is empty (ie. `<% var= %>`), it will be treated as null.

#### Filters

You can optionally provide filter to a variable by placing the pipe symbol `|` right after the variable name and the filter right after that (no space around the `|` pipe symbol), like this: `<% variable|filter %>`.
Expand Down Expand Up @@ -164,23 +175,22 @@ There are a few built-in filters that you can use:

#### Parse string or file

There are three main functions that will be of most interest to you: `parseString`, `parseFile` and `parseFileToString`. Both are static functions and are used like this:
There are two main functions that will be of most interest to you: `parseString` and `parse`. Both are static functions and are used like this:

```php
use Matronator\Parsem\Parser;
// parseString()
echo Parser::parseString('some <%text%>.', ['text' => 'value']);
// Output: some value.
// parse()
$arguments = [
'variableName' => 'value',
'key' => 'other value',
];
$object = Parser::parseFile('filename.yaml', $arguments);
// Output: The YAML file converted to an object with all
// variable placeholders replaced by the provided arguments.
echo Parser::parseFileToString('filename.yaml', $arguments);
$parsedFile = Parser::parse('filename.yaml', $arguments);
echo $parsedFile;
// Output: Will print the parsed contents of the file as string.
```

Expand All @@ -194,38 +204,19 @@ echo Parser::parseFileToString('filename.yaml', $arguments);
* @return mixed The parsed string or the original `$string` value if it's not string
* @param mixed $string String to parse. If not provided with a string, the function will return this value
* @param array $arguments Array of arguments to find and replace while parsing `['key' => 'value']`
* @param bool $strict [optional] If set to `true`, the function will throw an exception if a variable is not found in the `$arguments` array. If set to `false` null will be used.
* @param string|null $pattern [optional] You can provide custom regex with two matching groups (for the variable name and for the filter) to use custom template syntax instead of the default one `<% name|filter %>`
* @throws RuntimeException If a variable is not found in the `$arguments` array and `$strict` is set to `true`
*/
Parser::parseString(mixed $string, array $arguments = [], ?string $pattern = null): mixed
```
##### `Parser::parseFile`

```php
/**
* @see Parser::parseString() for parameter descriptions
*/
Parser::parseFile(string $filename, array $arguments = [], ?string $pattern = null): object
Parser::parseString(mixed $string, array $arguments = [], bool $strict = true, ?string $pattern = null): mixed
```
##### `Parser::parseFileToString`
##### `Parser::parse`

```php
/**
* @see Parser::parseString() for parameter descriptions
* @param string $filename Path to the file to parse
* @see Parser::parseString() for rest of the parameter descriptions
*/
Parser::parseFileToString(string $filename, array $arguments = [], ?string $pattern = null): string
```

#### Using custom parser

You can parse any file type to object, not only JSON/YAML/NEON, by providing a custom parser function as a callback to `Parser::customParse()` function.

```php
use Matronator\Parsem\Parser;
// Parse XML file
$object = Parser::customParse('filename.xml', function($contents) {
return simplexml_load_string($contents);
});
Parser::parse(string $filename, array $arguments = [], bool $strict = true, ?string $pattern = null): string
```
38 changes: 19 additions & 19 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions helpers.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
<?php

$GLOBALS['debug'] = false;

if (!function_exists('dump')) {
function dump($var)
{
if ($GLOBALS['debug'] === false) {
return;
}
$logFile = __DIR__ . '/dump.log';
file_put_contents($logFile, print_r($var, true) . PHP_EOL, FILE_APPEND | LOCK_EX);
}
Expand Down
Loading

0 comments on commit 279ae50

Please sign in to comment.