Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
VincentLanglet committed Jul 4, 2021
0 parents commit fdf4701
Show file tree
Hide file tree
Showing 56 changed files with 4,320 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
root = true

[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
charset = utf-8
8 changes: 8 additions & 0 deletions .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Add tests for your changes
5. Push your changes to your feature branch (`git push origin my-new-feature`)
6. Create a new Pull Request (PR)
11 changes: 11 additions & 0 deletions .github/ISSUE_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
### Rule(s) related to or rule(s) missing

Write here.

### Expected behavior

Write here.

### Actual behavior

Write here.
42 changes: 42 additions & 0 deletions .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: Test

on:
push:
branches:
- master
pull_request:

jobs:
test:
name: PHP ${{ matrix.php-version }} + ${{ matrix.dependencies }}
runs-on: ubuntu-18.04

strategy:
matrix:
php-version:
- 7.4
- 8.0
dependencies: [highest]
include:
- php-version: 7.2
dependencies: lowest

steps:
- name: Checkout
uses: actions/checkout@v2

- name: Install PHP with extensions
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
coverage: pcov
tools: composer:v2

- name: Install Composer dependencies (PHP 7 ${{ matrix.dependencies }})
uses: ramsey/composer-install@v1
with:
dependency-versions: ${{ matrix.dependencies }}
composer-options: --prefer-dist --prefer-stable

- name: Run unit tests with PHPUnit
run: vendor/bin/phpunit
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.idea/
composer.lock
composer.phar
coverage/
vendor/
21 changes: 21 additions & 0 deletions LICENCE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Vincent Langlet

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.
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Twig CS Fixer

[![MIT Licence](https://badges.frapsoft.com/os/mit/mit.png?v=103)](https://opensource.org/licenses/mit-license.php)
[![Actions Status](https://github.com/VincentLanglet/Twig-CS-Fixer/workflows/Test/badge.svg)](https://github.com/RobDWaller/csp-generator/actions)

Documentation
-------------

## Installation

This standard can be installed with the [Composer](https://getcomposer.org/) dependency manager.

Add the coding standard as a dependency of your project
```
composer require --dev vincentlanglet/twig-cs-fixer
```

Then, use it!
```
bin/twig-cs-fixer lint /path/to/code
```

## Twig Coding Standard Rules

From the [official one](http://twig.sensiolabs.org/doc/coding_standards.html).

### Delimiter spacing

Put one (and only one) space after the start of a delimiter (`{{`, `{%`, and `{#`)
and before the end of a delimiter (`}}`, `%}`, and `#}`).

When using the whitespace control character, do not put any spaces between it and the delimiter

### Operator spacing

Put one (and only one) space before and after the following operators:
comparison operators (`==`, `!=`, `<`, `>`, `>=`, `<=`), math operators (`+`, `-`, `/`, `*`, `%`, `//`, `**`),
logic operators (`not`, `and`, `or`), `~`, `is`, `in`, and the ternary operator (`?:`)

Do not put any spaces before and after the operator `..`.

### Punctuation spacing

Put one (and only one) space after the `:` sign in hashes and `,` in arrays and hashes

Do not put any spaces after an opening parenthesis and before a closing parenthesis in expressions

Do not put any spaces before and after the following operators: `|`, `.`, `[]`

Do not put any spaces before and after the opening and the closing of arrays and hashes
23 changes: 23 additions & 0 deletions bin/twig-cs-fixer
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#!/usr/bin/env php
<?php

if (file_exists(__DIR__.'/../../../autoload.php')) {
require_once __DIR__.'/../../../autoload.php';
} elseif (file_exists(__DIR__.'/../vendor/autoload.php')) {
require_once __DIR__.'/../vendor/autoload.php';
} else {
echo 'You must set up the project dependencies, run the following commands:'.PHP_EOL.
'curl -s http://getcomposer.org/installer | php'.PHP_EOL.
'php composer.phar install'.PHP_EOL;
exit(1);
}

use Symfony\Component\Console\Application;
use TwigCsFixer\Command\TwigCsFixerCommand;

$command = new TwigCsFixerCommand();

$application = new Application();
$application->add($command);
$application->setDefaultCommand($command->getName());
$application->run();
36 changes: 36 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "vincentlanglet/twig-cs-fixer",
"type": "coding-standard",
"description": "A tool to automatically fix Twig code style",
"homepage": "https://github.com/VincentLanglet/Twig-CS-Fixer",
"license": "MIT",
"authors": [
{
"name": "Vincent Langlet"
}
],
"bin": ["bin/twig-cs-fixer"],
"require": {
"php": ">=7.2",
"ext-mbstring": "*",
"symfony/console": "^4.4 || ^5.0",
"symfony/twig-bridge": "^4.4 || ^5.0",
"twig/twig": "^2.12 || ^3.0"
},
"require-dev": {
"phpunit/phpunit": "^7.0"
},
"config": {
"sort-packages": true
},
"autoload": {
"psr-4": {
"TwigCsFixer\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"TwigCsFixer\\Tests\\": "tests/"
}
}
}
21 changes: 21 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>

<!-- https://phpunit.readthedocs.io/en/latest/configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
colors="true"
bootstrap="vendor/autoload.php"
convertDeprecationsToExceptions="false"
>
<testsuites>
<testsuite name="all">
<directory>tests</directory>
</testsuite>
</testsuites>

<filter>
<whitelist>
<directory>./src</directory>
</whitelist>
</filter>
</phpunit>
91 changes: 91 additions & 0 deletions src/Command/TwigCsFixerCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<?php

declare(strict_types=1);

namespace TwigCsFixer\Command;

use Exception;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use TwigCsFixer\Config\Config;
use TwigCsFixer\Environment\StubbedEnvironment;
use TwigCsFixer\Report\TextFormatter;
use TwigCsFixer\Ruleset\Ruleset;
use TwigCsFixer\Runner\Linter;
use TwigCsFixer\Token\Tokenizer;

/**
* TwigCsFixer stands for "Twig Code Sniffer Fixer" and will check twig template of your project.
*/
class TwigCsFixerCommand extends Command
{
/**
* @return void
*/
protected function configure(): void
{
$this
->setName('lint')
->setDescription('Lints a template and outputs encountered errors')
->setDefinition([
new InputOption(
'level',
'l',
InputOption::VALUE_OPTIONAL,
'Allowed values are notice, warning or error',
'notice'
),
new InputOption(
'fix',
'f',
InputOption::VALUE_NONE,
'Automatically fix all the fixable violations'
),
])
->addArgument(
'paths',
InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
'Paths of files and folders to parse'
);
}

/**
* @param InputInterface $input
* @param OutputInterface $output
*
* @return int
*
* @throws Exception
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$paths = $input->getArgument('paths');
$level = $input->getOption('level');
$fix = $input->getOption('fix');

$config = new Config($paths);

// Get the rules to apply.
$ruleset = new Ruleset();
$ruleset->addStandard();

// Execute the linter.
$twig = new StubbedEnvironment();
$linter = new Linter($twig, new Tokenizer($twig));
$report = $linter->run($config->findFiles(), $ruleset, $fix);

// Format the output.
$reporter = new TextFormatter($input, $output);
$reporter->display($report, $level);

// Return a meaningful error code.
if ($report->getTotalErrors()) {
return 1;
}

return 0;
}
}
58 changes: 58 additions & 0 deletions src/Config/Config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

declare(strict_types=1);

namespace TwigCsFixer\Config;

use Exception;

/**
* TwigCsFixer configuration data.
*/
class Config
{
/**
* @var array
*/
protected $paths = [];

/**
* @param array $paths
*
* @return void
*/
public function __construct(array $paths = [])
{
$this->paths = $paths;
}

/**
* @return array
*
* @throws Exception
*/
public function findFiles(): array
{
$files = [];
foreach ($this->paths as $path) {
if (is_dir($path)) {
$flags = \RecursiveDirectoryIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS;
$directoryIterator = new \RecursiveDirectoryIterator($path, $flags);
$filter = new TwigFileFilter($directoryIterator);
$iterator = new \RecursiveIteratorIterator($filter);

/** @var \SplFileInfo $file */
foreach ($iterator as $k => $file) {
$files[] = $file->getRealPath();
}
} elseif (is_file($path)) {
$file = new \SplFileInfo($path);
$files[] = $file->getRealPath();
} else {
throw new Exception(sprintf('Unknown path: "%s"', $path));
}
}

return $files;
}
}
Loading

0 comments on commit fdf4701

Please sign in to comment.