driade / phpfmt8 Goto Github PK
View Code? Open in Web Editor NEWPHP formatter for Sublime Text 4, with PHP 8 support.
License: BSD 3-Clause "New" or "Revised" License
PHP formatter for Sublime Text 4, with PHP 8 support.
License: BSD 3-Clause "New" or "Revised" License
before format
<?php
class Server
{
protected array $handlers = [];
public function withHandler(callable | string $handler): static
{
$this->handlers[] = $this->createHandlerItem($handler);
return $this;
}
}
after format
<?php
class Server
{
protected array $handlers = [];
public function withHandler(callable | string $handler): static
{
$this->handlers[] = $this->createHandlerItem($handler);
return $this;
}
}
2 spaces are formatted after the callable type declaration
This is a code breaking bug.
Basically if you have something like this:
class Cache extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Primary Handler
* --------------------------------------------------------------------------
*
* The name of the preferred handler that should be used. If for some reason
* it is not available, the $backupHandler will be used in its place.
*/
public string $handler = 'file';
/**
* --------------------------------------------------------------------------
* Backup Handler
* --------------------------------------------------------------------------
*
* The name of the handler that will be used in case the first one is
* unreachable. Often, 'file' is used here since the filesystem is
* always available, though that's not always practical for the app.
*/
public string $backupHandler = 'dummy';
}
In turn this will be changed into this:
class Cache extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Primary Handler
* --------------------------------------------------------------------------
*
* The name of the preferred handler that should be used. If for some reason
* it is not available, the $backupHandler will be used in its place.
*/
stringpublic $handler = 'file';
/**
* --------------------------------------------------------------------------
* Backup Handler
* --------------------------------------------------------------------------
*
* The name of the handler that will be used in case the first one is
* unreachable. Often, 'file' is used here since the filesystem is
* always available, though that's not always practical for the app.
*/
stringpublic $backupHandler = 'dummy';
}
before format
<?php
namespace App\Enums;
enum Mq: string
{
case ORDER_PAYMENT_EXPIRED = 'order-payment-expired';
public function getExchangeName(Mq $queue)
{
return 'ex-'.$queue->value;
}
}
after format
<?php
namespace App\Enums;
enum Mq:string {
case ORDER_PAYMENT_EXPIRED = 'order-payment-expired';
public function getExchangeName(Mq $queue)
{
return 'ex-' . $queue->value;
}
}
<?php
class B
{
public int|string $a;
public null|string $b;
public ?|string $b;
public null|\stdClass $b;
}
becomes
<?php
class B
{
public int|string $a;
public null|string $b;
?public |string $b;
\stdClasspublic null| $b;
}
ICollection::ELSE
becomes
ICollection::ELSE{
;
}
I just installed the phpfmt on my latest update of the Sublime Text and I appreciate the developers for the work done thus far.
Some of my switch cases are like this:
switch ($action_to_perform) {
case 'save_dataload':
// Code for 'save_dataload' case
break;
}
but I want to achieve this:
switch ($action_to_perform) {
case 'save_dataload':
// Code for 'save_dataload' case
break;
}
I didn't find a settings to achieve this, so chat-GPT gave me a custom function to add to C:\Users\Michael\AppData\Roaming\Sublime Text\Packages\phpfmt
<?php
use Fmt\AdditionalPass;
class UnindentSwitchCaseBreak extends AdditionalPass
{
public function candidate($source, $foundTokens)
{
// Check if the source code contains switch statements
return (bool) strpos($source, 'switch');
}
public function format($source)
{
// Remove indentation from case and break statements
$source = preg_replace('/\n(\s*)(case|break)/', "\n$1$2", $source);
return $source;
}
}
and I added UnindentSwitchCaseBreak
to my [passes section], but it throws this error
[08-Aug-2023 11:00:31 Europe/Berlin] PHP Warning: Undefined array key "_" in C:\Users\Michael\AppData\Roaming\Sublime Text\Packages\phpfmt\fmt.stub.php on line 3397
[08-Aug-2023 11:00:31 Europe/Berlin] PHP Notice: fwrite(): Write of 56371 bytes failed with errno=32 Broken pipe in C:\Users\Michael\AppData\Roaming\Sublime Text\Packages\phpfmt\fmt.stub.php on line 3412
This is my settings file
{
"excludes":
[
"PSR2ModifierVisibilityStaticOrder"
],
"passes":
[
"UnindentSwitchCaseBreak",
],
"php_bin": "C:/xampp/php/php.exe",
"switch_case_space" : 1,
}
I am on a windows 11 machine running PHP 8.1.2
Pls help
match ($x) {
$a => function () {
};
};
$a = function () {
function () {
};
};
instead of
match ($x) {
$a => function () {
}
};
$a = function () {
function () {
}
};
class foo
{
#[JsonSerialize('call it Jackson')]
public string $myValue;
function a()
{
}
}
instead of
class foo
{
#[JsonSerialize('call it Jackson')]
public string $myValue;
public function a()
{
}
}
before format
<?php
class Message extends App\Services\Kernel\Message
{
}
after format
<?php
class Message extends App\Services\Kernel\Message
{
}
match ($x) {
$a => 1,
$b => 2,
};
match ($x) {
$a => 1,
$b => 2,
}
expected
match ($x) {
$a => 1,
$b => 2,
};
match ($x) {
$a => 1,
$b => 2,
};
There're references in the code to this "fmt-external.php" call, also seen in phpfmt-next, but it's utility seem to got lost.
$expressionResult = match ($condition) {
1, 2 => foo(),
default=> baz(),
};
instead of
$expressionResult = match ($condition) {
1, 2 => foo(),
default => baz(),
};
before format
<?php
class Server
{
protected ServerRequestInterface $request;
public function __construct(protected Merchant $merchant, ?ServerRequestInterface $request)
{
$this->request = $request ?? RequestUtil::createDefaultServerRequest();
}
}
after format
<?php
class Server
{
protected ServerRequestInterface $request;
public function __construct(protected Merchant $merchant, ? ServerRequestInterface $request)
{
$this->request = $request ?? RequestUtil::createDefaultServerRequest();
}
}
optional arguments, there are space between question mark.
T_NAME_FULLY_QUALIFIED was added in php 8. Check if the formatted needs to use it in any rule
This
return $action->handle(
id: intval($id), class: TicketApiClassEnum::from($class)
);
becomes
return $action->handle(
id: intval($id), class :TicketApiClassEnum::from($class)
);
match ($a) {
1 => 2,
3 => 4,
// comment
/** comment **/
default => 5
};
function a()
{
$this->call()
}
insteadof
function a()
{
$this->call();
}
use Vendor\Package\SomeNamespace\{
SubnamespaceOne\ClassA,
SubnamespaceOne\ClassB,
SubnamespaceTwo\ClassY,
ClassZ,
};
becomes
use Vendor\Package\SomeNamespace\SubnamespaceTwo\ClassY;
before format
<?php
class Message
{
protected $merchant;
public function getMerchant(): Merchant
{
if (!$this->merchant) {
$this->merchant = new Merchant(
mchId: $this->config['mch_id'],
serial: $this->config['serial']
);
}
return $this->merchant;
}
}
after format
<?php
class Message
{
protected $merchant;
public function getMerchant(): Merchant
{
if (!$this->merchant) {
$this->merchant = new Merchant(
mchId:$this->config['mch_id'],
serial:$this->config['serial']
);
}
return $this->merchant;
}
}
Check https://github.com/Shaked/php.tools (already in a branch) and make them work
$instance = new class {}
should become
$instance = new class {};
Using typed functions where I want a fallback return or the params will have more than one type it does not work.
Example:
protected function allData(object|null $proposal): object|null
{
return $proposal;
}
Basically it says that I have a syntax error and it does not run the auto format in this file.
My current local PHP version being used by FMT is the following:
php -v
PHP 8.2.2 (cli) (built: Feb 1 2023 08:33:04) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.2, Copyright (c) Zend Technologies
enumA {
}
instead of
enum A {
}
class Foo {
public const BAR = 'bar';
private const BAZ = 'baz';
}
After format
class Foo
{
const='bar';const='baz';}
return new class {
}
instead of
return new class {
};
If the class if now a FQN, it formats this way
try {
} catch (Exception $e) {
}
but if we use a FQN the whitespace between the classname and the variable is removed
try {
} catch (\Exception$e) {
}
As per WordPress Coding Standard, an array should be defined like this: (space at the beginning and closing of parentheses or square brackets)
Source: https://developer.wordpress.org/coding-standards/wordpress-coding-standards/php/#declaring-arrays
As per WordPress Coding Standard, spaces while accessing array items will be like this:
Source: https://developer.wordpress.org/coding-standards/wordpress-coding-standards/php/#space-usage
Please, solve this issue by introducing some configurations regarding "[]" (Square brackets) so that WordPress Developers can write PHP and use the vscode-phpfmt with more ease.
Thank you.
$instance = new class {};
becomes
$instance = new class
{};
In the settings when I do:
Preferences / Package Settings / Phpfmt-8/default settings
Its still trying to open the phpfmt instead of phpfmt-8 default settings file.
Before
<?php
class Message
{
public function test()
{
$campaign_data = ['enabled' = false];
$campaign->status = $campaign_data['enabled'] ? Campaign::STATUS_ACTIVE : Campaign::STATUS_PAUSED;
return $campaign;
}
}
After
<?php
class Test
{
public function test()
{
$campaign_data = ['enabled' = false];
$campaign->status = $campaign_data['enabled']?Campaign::STATUS_ACTIVE: Campaign::STATUS_PAUSED;
return $campaign;
}
}
Configs:
{
"version": 4,
"php_bin": "/opt/homebrew/opt/php@7.4/bin/php",
"format_on_save": false,
"autocomplete": true,
"autoimport": true,
"disable_auto_align": true,
"indent_with_space": true,
"passes":
[
"StripExtraCommaInArray",
"RemoveSemicolonAfterCurly",
"NewLineBeforeReturn",
"AddMissingParentheses",
"ReindentSwitchBlocks",
"OrderAndRemoveUseClauses",
"DocBlockToComment",
"PSR2EmptyFunction",
"StripSpaceWithinControlStructures",
"ShortArray",
"AutoSemicolon",
"OrderMethod", // 2023-06-05
"OrganizeClass", // 2023-06-05
"OrderMethodAndVisibility", // 2023-06-05
"SortUseNameSpace", // 2023-06-05
"SpaceBetweenMethods", // 2023-06-05
"TrimSpaceBeforeSemicolon", // 2023-06-05
"DoubleToSingleQuote"
],
"psr1": false,
"psr2": true,
"smart_linebreak_after_curly": true,
"visibility_order": true,
"yoda": false,
}
match ($x) {
$a => function () {
};
}
instead of
match ($x) {
$a => function () {
}
};
Route::namespace ('App\Http\Controllers\Admin\Leads');
instead of
Route::namespace('App\Http\Controllers\Admin\Leads');
enum MyEnum:string {
case FINISH = 'finish';
public function a()
{}
}
instead of
enum MyEnum:string {
case FINISH = 'finish';
function a()
{}
}
#[. \AllowDynamicProperties ];
class foo {
}
instead of
#[\AllowDynamicProperties]
class foo {
}
When running cmd:
php fmt.stub.php --psr2 --indent_with_space=4 --passes=SpaceAfterExclamationMark --exclude=PSR2ModifierVisibilityStaticOrder
it prints Could not open input file: xxx/fmt-external.stub.php
Add semicolon in theses cases
$data['total'] = 1
/** comment **/
$data['total'] = 1
// comment
When formatting
Collection::FOREACH;
We get into an infinite loop
match ($x) {
$a => 1,
$b => 2,
default=> true
};
instead of
match ($x) {
$a => 1,
$b => 2,
default=> true;
};
$foo = function () {
match ($x) {
$a => function () {
};
};
};
instead of
$foo = function () {
match ($x) {
$a => function () {
}
};
};
before format
<?php
class Application
{
protected Qrcode|null $qrcode = null;
}
after format
<?php
class Application
{
|protected Qrcodenull $qrcode = null;
}
Collection::PUBLIC;
becomes
Collection::;
Basically I uninstalled the other plugin. Installed this one by cloning the repo into the packages folder.
Added the user config file.
Changed the path to php 8.
Format on save was not working and there was no errors in the console.
Environment: Linux
What more info can I give you about the system?
$a ??= ($b = 4) + 5;
instead of
$a??=($b = 4) + 5;
return new class {
};
insteadof
return new class {
}
According to php7mar these arre the only issues to fix if we want this tool to work with php 5.6
# nuance
#### /Users/davidfernandez/htdocs/phpfmt8/fmt.stub.php
* funcGetArg
* Line 863: ` $params = array_slice(func_get_args(), 1);`
* Line 2215: ` $args = func_get_args();`
* Line 2240: ` $args = func_get_args();`
This
$a = []
(new
should become
$a = [];
(new
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.