Giter Site home page Giter Site logo

sublimephpcsfixer's Introduction

Sublime PHP CS Fixer

This is a plugin for Sublime Text 3/4, to format PHP code through php-cs-fixer command on any view.

Features

  • It works inside a temporal view (ie: on an new, non-saved file)
  • Fast
  • Easy
  • Configurable through rules or a config file
  • Tested on Windows and Linux

Configuration

You have to install the actual php-cs-fixer (the actual tool made by sensiolabs, not this plugin)

You can install php-cs-fixer directly with composer by running:

composer global require friendsofphp/php-cs-fixer

Also you can create a config file as explained here https://github.com/FriendsOfPHP/PHP-CS-Fixer

for example in: $HOME/.php-cs-fixer.php

<?php

return (new PhpCsFixer\Config)
    ->setRules([
        '@Symfony' => true,
        'array_syntax' => ['syntax' => 'short'],
    ]);

If you've created a config file, you have to configure its path in the plugin's settings.

In Menu -> Preferences -> Package Settings -> PHP CS Fixer -> Settings - user

{
    "config": "/path/to/.php-cs-fixer.php"
}

When using multiple projects with different configurations, it's possible to configure the path relative to the Sublime project folder:

{
    "config": "${folder}/.php-cs-fixer.php",
    "php": "${packages}/User/php",
    "path": "${packages}/User/php-cs-fixer.php"
}

It's also possible to specify multiple config paths. In that case, the first readable file is used:

{
    "config": [
        "${file_path}/.php-cs-fixer.php",
        "${folder}/.php-cs-fixer.php",
        "/path/to/.php-cs-fixer.php"
    ]
}

See extract_variables in the Sublime API Reference for the supported replacement variables. The value of the ${folder} points the path of the first project in Sublime API. Here, it's beforehand replaced with the path of the project the target file belongs.

Please note:

  • rules and config directives are excluding.
  • This plugin don't try to find the config file automatically. If you want to create a config file, you have to specify its path in the plugin settings.

Rules

{
    "rules": {
        "@PhpCsFixer": true,
    },
    // or
    "rules": "@PhpCsFixer",
    // or
    "rules": [
        "@PhpCsFixer"
    ]
}

Please note that rules and config directives are excluding.

For more information see: https://github.com/FriendsOfPHP/PHP-CS-Fixer#usage

Exclude files

Since all php files are passed directly to the php-cs-fixer executable, a configured PhpCsFixer\Finder gets ignored. In order to exclude files from php-cs-fixer, you can use the "exclude" setting:

{
    "exclude": [
        ".*[\\\\/]vendor[\\\\/].*", // vendor-path (used by Composer)
        ".*\\.phtml$" // files ending with ".phtml"
    ]
}

The exclude-filter uses python regular expressions. For more information see: https://docs.python.org/2/library/re.html

On Windows:

The plugin tries to find the executable in:

%APPDATA%\composer\vendor\bin\php-cs-fixer.bat

If it isn't working, you can locate your composer global packages path by running:

composer config -g home

On Linux:

After installing php-cs-fixer you have to specify the full path to the executable in the configuration page.

The plugin tries to find the executable in:

$HOME/.composer/vendor/bin/php-cs-fixer

However, if it isn't working, you can create a symbolic link to the php-cs-fixer executable

ln -s $HOME/.composer/vendor/bin/php-cs-fixer $HOME/bin/php-cs-fixer

Note

I've checked this on Linux and Windows, but I cannot check it on OSX. I'll thank you if someone tells me if it's working on OSX and give me some details on how to configure it.

Acknowledgements

I would like to thank to sensiolabs and contributors for their awesome package. It works flawlessly. All the work here belongs to them.

Check them at:

I'd also learned some of the sublime package structure from:

sublimephpcsfixer's People

Contributors

adael avatar asccc avatar bshaffer avatar eroluysal avatar gh640 avatar godric-cz avatar hakanersu avatar husanjun avatar predragnikolic avatar rockymontana avatar sander3 avatar sylbru avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

sublimephpcsfixer's Issues

on_save won't auto save

When using the on_save option, it formats on saving but won't save the changes.
So we have to save the file twice to fix the changes.
Is there a way to fix it?

Pass option to PHP CS Fixer

Hello, as I would like to use some risky rules, I have to pass an argument to PHP CS Fixer, namely the --allow-risky=yes.

I can't immediately see how to do that via the documentation or the default settings, can you help me out with that?

Error on execute

$ whereis php

php: /home/ubuntu/.asdf/shims/php


$ whereis php-cs-fixer

php-cs-fixer: /home/ubuntu/bin/php-cs-fixer

PHP CS Fixer: Formatting view...
PHP CS Fixer: autodetected: /home/ubuntu/.composer/vendor/bin/php-cs-fixer
PHP CS Fixer: Using config: /home/ubuntu/.phpcsfixer
PHP CS Fixer: There was an error formatting the view
PHP CS Fixer: Command: ['/home/ubuntu/.composer/vendor/bin/php-cs-fixer', 'fix', '--using-cache=off', '/tmp/tmphp_7eg', '--config=/home/ubuntu.phpcsfixer']
PHP CS Fixer: Error output: b'/usr/bin/env: \xe2\x80\x98php\xe2\x80\x99: No such file or directory\n'
PHP CS Fixer: Done. No changes

question

just curious, is this works per file or the entire project dir?
from the python code, i think it works per file.
but i want to make sure. i dont want to cause git conflict just because of codeformat.

Certain config options not working

Hello, I'm trying to use the plugin, I created my config like so

<?php

$finder = PhpCsFixer\Finder::create()
    ->in(__DIR__)
;

return PhpCsFixer\Config::create()
    ->setRules([
        '@PSR2' => true,
        '@Symfony' => true,
        'array_syntax' => ['syntax' => 'short'],
        'no_unused_imports' => true,
        'binary_operator_spaces' => ['default' => 'align'],
    ])
    ->setFinder($finder);

The config is working, however 'binary_operator_spaces' => ['default' => 'align'] doesn't. So for example

return Validator::make($data, [
                'name' =>    'required|string|max:255',
            'email' =>   'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);

doesn't change upon saving. What am I doing wrong?

Installed on windows10 with composer global but don't know what to change so it works

I have phpcs succesfully installed but when I tried to install phpcsfixer by doing:
composer global require friendsofphp/php-cs-fixer
It doesn't format nor does it pops any kind of error msg.
So then I tried 'composer config -g home' and the output isn't where the pluguin tries to find the executable, it is: C:/Users/myUser/AppData/Roaming/Composer
so now I'm not sure of what should I do to get it to work? Do I have to manually configure for every project or move the php-cs-fixer.bat to Composer folder or somehow change the composer config -g home? Sorry for the newbie question I just don't understand what should I do to fix it

There was an error formatting the view

Hi, am getting "There was an error formatting the view error."

PHP CS Fixer: Formatting view...
PHP CS Fixer: There was an error formatting the view
PHP CS Fixer: Command: ['/Users/xuma/.composer/vendor/bin/php-cs-fixer', 'fix', '--using-cache=off', '/var/folders/14/_x141cy97l3b731cc1lw30vr0000gn/T/tmpol83v5']
PHP CS Fixer: Error output: b''
PHP CS Fixer: Done. No changes

I did check exact command on actual file and its working. It seems there is a problem with reading temp file.

Don't run the command if it is not a php file

Helloo :)

I have the run on_save setting turned on. And currently if I save the file, reguardless if it is a .php file, or .html file, .js file, the command will run.

But the command should only run if it is a .php file.

I can make a PR if you like?

Doesn't work without project folder open

When I use PHPCSFixer: format this file, nothing happens. Here's what my config looks like:

{
    "config": "C:\\Users\\lucas.figueiredo\\.phpcsfixer",
    "on_save": true
}

Here's what .phpcsfixer looks like:

<?php
return PhpCsFixer\Config::create()
->setRules([
    '@PSR2' => true,
    'array_syntax' => ['syntax' => 'short'],
    'no_unused_imports' => true,
]);

PhpCsFixer is installed globally via composer. If I run php-cs-fixer fix file.php on cmd, it works.

The executable path is also correct, here's what php-cs-fixer.bat looks like:

@ECHO OFF
setlocal DISABLEDELAYEDEXPANSION
SET BIN_TARGET=%~dp0/../friendsofphp/php-cs-fixer/php-cs-fixer
php "%BIN_TARGET%" %*

/../friendsofphp/php-cs-fixer/php-cs-fixer -> exists

How can I further debug why nothing happens on Sublime?

-- Edit --

On Sublime Console I got this:

PHP CS Fixer: Formatting view...
PHP CS Fixer: autodetected: C:\Users\lucas.figueiredo\AppData\Roaming\composer\vendor\bin\php-cs-fixer.bat
Traceback (most recent call last):
  File "C:\Sublime Text 3\sublime_plugin.py", line 818, in run_
    return self.run(edit)
  File "SublimePhpCsFixer in C:\Users\lucas.figueiredo\AppData\Roaming\Sublime Text 3\Installed Packages\PHP CS Fixer.sublime-package", line 206, in run
  File "SublimePhpCsFixer in C:\Users\lucas.figueiredo\AppData\Roaming\Sublime Text 3\Installed Packages\PHP CS Fixer.sublime-package", line 112, in format_contents
  File "SublimePhpCsFixer in C:\Users\lucas.figueiredo\AppData\Roaming\Sublime Text 3\Installed Packages\PHP CS Fixer.sublime-package", line 149, in format_file
  File "SublimePhpCsFixer in C:\Users\lucas.figueiredo\AppData\Roaming\Sublime Text 3\Installed Packages\PHP CS Fixer.sublime-package", line 189, in get_project_folder
AttributeError: 'NoneType' object has no attribute 'get'

Which led me to use "Open folder with Sublime", which solved the problem:

PHP CS Fixer: Formatting view...
PHP CS Fixer: autodetected: C:\Users\lucas.figueiredo\AppData\Roaming\composer\vendor\bin\php-cs-fixer.bat
PHP CS Fixer: Using config: C:\Users\lucas.figueiredo\.phpcsfixer
PHP CS Fixer: Done. View formatted

Long story short, it only seems to work if there is a project folder on the sidebar?

Laravel Pint support

It would be super nice to have Laravel Pint support. Running it is as easy as pint $filename so should be very quick to implement (unfortunately one can't just set "path": "pint" as it needs only 1 param that should be a path or a filename). And it is based on PHP-CS-Fixer, so any PHP-CS-Fixer rules can be used in pint config.

UTF-8 formatting error e.g. German umlauts

Hi,

I found a little problem in the script, because everytime I used the plugin it changed my "ä" into "ä".

So I fixed it myself by adding in line 75 the encoding part:

with open(tmp_file, 'r', encoding='utf8') as file:

cheers

Variables not loaded

Hi there,

SublimePhpCsFixer stopped working for me yesterday since merging https://github.com/adael/SublimePhpCsFixer/pull/36/files#diff-1dd779ae4db47cc8b575f24096954620e8138e37fdcf66f7085abaf15f315281R278-R280

I believe plugin_loaded() fires too soon which makes it impossible to replace the ${folder} variable in the package config when using Sublime Text projects. Manually disabling and re-enabling the package resolves the issue.

Could you please revert the changes made to loading the variables during formatting files?

Exclude some directories

Is it possible to exclude some directories. I am using a laravel 5.5 project. The fixer flags all files in the tests directory as errors if I am using an underscore in for the method names.

thanks.

Reference Packages dir

Hello,

I have sublime installed on multiple machines. So it would be nice if I cound reference the config file of phpcsfixer relative to my Packages/User dir. What would be the proper path in such a case?

Also note that the home directory reference "~" doesnt work.

PHP CS Fixer stop working

Since today php cs fixer stop working, on Sublime Console I got this:

Traceback (most recent call last):
  File "C:\Program Files\Sublime Text\Lib\python33\sublime_plugin.py", line 1335, in is_enabled_
    ret = self.is_enabled()
  File "C:\Users\micha\AppData\Roaming\Sublime Text 3\Installed Packages\PHP CS Fixer.sublime-package\SublimePhpCsFixer.py", line 322, in is_enabled
  File "C:\Users\micha\AppData\Roaming\Sublime Text 3\Installed Packages\PHP CS Fixer.sublime-package\SublimePhpCsFixer.py", line 349, in is_supported_scope
  File "C:\Users\micha\AppData\Roaming\Sublime Text 3\Installed Packages\PHP CS Fixer.sublime-package\SublimePhpCsFixer.py", line 355, in is_excluded
  File "C:\Users\micha\AppData\Roaming\Sublime Text 3\Installed Packages\PHP CS Fixer.sublime-package\SublimePhpCsFixer.py", line 145, in get
AttributeError: 'NoneType' object has no attribute 'get'

I guess it's something with the PR which was merged today.

Exclude directory not working

Here is my .phpcsfixer file

$finder = PhpCsFixer\Finder::create()
    ->exclude(['test'])
    ->in(__DIR__);

return PhpCsFixer\Config::create()
    ->setRules([
        '@PSR2' => true,
        'array_syntax' => ['syntax' => 'short'],
        'no_unused_imports' => true,
        'not_operator_with_space' => true,
        'ordered_imports' => [
            'sortAlgorithm' => 'length'
        ]
    ])->setFinder($finder);

I'm wondering if PHP-CS-Fixer/PHP-CS-Fixer#2956 (comment) has anything to do with it?

formatting fails when .php-cs config defines a Finder

If I have this in my .php-cs config file:

<?php

$finder = PhpCsFixer\Finder::create()
    ->in('src')
    ->in('tests')
;

return PhpCsFixer\Config::create()
    ->setRules([
        '@Symfony' => true,
    ])
    ->setFinder($finder)
;

running the formatter fails with The "src" directory does not exist.

This is because the file to format is copied to a temp dir, where indeed these directories do not exist.

I don't really see how this can be fixed cleanly, but some ugly solutions come to mind:

  • recreate the (empty) directory structure of the entire project to the temp dir as well. (maybe only to a certain depth. I doubt more than 4 or 5 would ever be needed)
  • parse the .php-cs file beforehand, and add only the paths that are explicitly added in the Finder to the temp dir
  • parse the .php-cs file beforehand, and strip any Finders, and then use that modified config file.

Add additional configuration

1、php executable file path
2、php-cs-fixer extra pass options

For the above setting selection, you can refer to the settings related to vscode. In this way, the user can make more flexible settings without having to make any system links.

Error on OSX

With your package installed, I get modal errors on startup:

Error trying to parse file: Trailing comma before closing bracket in 
~/Library/Application Support/Sublime Text 2/Packages/PHP CS Fixer/Main.sublime-menu:8:13

Usage with .phar

Allow usage without composer instead use the php-cs-fixer.phar executable.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.