> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Laravel Pint

> 基于 PHP CS Fixer 构建的代码风格自动修复工具。介绍如何在团队中保持一致的编码风格。

## 什么是 Laravel Pint

[Laravel Pint](https://github.com/laravel/pint) 是基于 PHP CS Fixer 构建的代码风格自动修复工具。它以「无需配置即可上手」为目标进行设计，会依照 Laravel 编码风格自动格式化代码。

将团队开发中常见的「代码风格 review 评论」自动化，可以让大家专注于更本质的代码评审。

```mermaid theme={null}
flowchart LR
    A["PHP 文件"] --> B["运行 pint"]
    B --> C{存在<br>风格错误？}
    C -- 是 --> D["自动修复"]
    C -- 否 --> E["无变更"]
    D --> F["格式化后的文件"]
    E --> F
```

## 安装

新创建的 Laravel 应用中已经默认安装了 Pint。对于旧版本项目，可以通过 Composer 安装。

```shell theme={null}
composer require laravel/pint --dev
```

## 运行方式

### 基本用法

自动修复项目中所有的 `.php` 文件。

```shell theme={null}
./vendor/bin/pint
```

也可以只对特定文件或目录进行处理。

```shell theme={null}
./vendor/bin/pint app/Models
./vendor/bin/pint app/Models/User.php
```

### 选项一览

| 选项                  | 说明                          |
| ------------------- | --------------------------- |
| `--test`            | 不修改文件，仅检测风格错误。若存在错误则返回非零退出码 |
| `--dirty`           | 只对 Git 中未提交的文件进行处理          |
| `--diff=[branch]`   | 只处理与指定分支有差异的文件              |
| `--repair`          | 修复风格错误的同时，若产生修复则返回非零退出码     |
| `--parallel`        | 并行执行模式（实验性），提升性能            |
| `--max-processes=4` | 与 `--parallel` 一起使用，指定最大进程数 |
| `-v`                | 显示修改的详细信息                   |
| `--config`          | 指定要使用的 `pint.json` 路径       |
| `--preset`          | 指定要使用的预设                    |

```shell theme={null}
# 只检查不修改
./vendor/bin/pint --test

# 只处理未提交的文件
./vendor/bin/pint --dirty

# 并行运行
./vendor/bin/pint --parallel
```

## 配置

在项目根目录创建 `pint.json` 可以自定义行为。

```json theme={null}
{
    "preset": "laravel"
}
```

也可以显式指定配置文件路径。

```shell theme={null}
./vendor/bin/pint --config vendor/my-company/coding-style/pint.json
```

### 预设

预设即一组规则的集合。默认是 `laravel` 预设，包含最适合 Laravel 项目的规则。

| 预设        | 说明                  |
| --------- | ------------------- |
| `laravel` | Laravel 推荐的编码风格（默认） |
| `psr12`   | PSR-12 编码标准         |
| `per`     | PER Coding Style    |
| `symfony` | Symfony 编码风格        |
| `empty`   | 不带任何规则，可自行逐条定义      |

```shell theme={null}
# 通过命令行指定预设
./vendor/bin/pint --preset psr12
```

### 自定义规则

`pint.json` 可以逐条启用或关闭规则。可用规则请参阅 [PHP CS Fixer Configurator](https://mlocati.github.io/php-cs-fixer-configurator)。

```json theme={null}
{
    "preset": "laravel",
    "rules": {
        "simplified_null_return": true,
        "array_indentation": false,
        "new_with_parentheses": {
            "anonymous_class": true,
            "named_class": true
        }
    }
}
```

### 排除文件或目录

可以从检查中排除特定目录。

```json theme={null}
{
    "exclude": [
        "my-specific/folder"
    ]
}
```

按文件名模式排除可以使用 `notName`。

```json theme={null}
{
    "notName": [
        "*-my-file.php"
    ]
}
```

按特定文件路径排除可以使用 `notPath`。

```json theme={null}
{
    "notPath": [
        "path/to/excluded-file.php"
    ]
}
```

## 推荐配置

以下是一份在实际开发中效果不错的 `pint.json` 配置示例。

```json theme={null}
{
    "preset": "laravel",
    "rules": {
        "no_unused_imports": false,
        "strict_comparison": true,
        "declare_strict_types": true
    }
}
```

各规则的目的说明：

| 规则                     | 作用                                                                        |
| ---------------------- | ------------------------------------------------------------------------- |
| `no_unused_imports`    | 设置为 `false` 时，不会删除未使用的 `use`。Pint 的默认值为 `true`（会删除），常规 Laravel 项目通常无需重复配置 |
| `strict_comparison`    | 将 `==` 转为 `===`、`!=` 转为 `!==`，避免意外的类型转换 bug                               |
| `declare_strict_types` | 在文件开头自动添加 `declare(strict_types=1);`，提升类型安全性                              |

<Tip>
  `strict_comparison` 与 `declare_strict_types` 会强制更严格的类型代码，若在已有项目中启用，首次修改量可能较大。新项目建议一开始就引入。
</Tip>

<Info>
  **`no_unused_imports` 主要面向包开发场景。** Pint 默认已经是 `true`（删除未使用的 `use`），因此常规 Laravel 项目并不需要显式配置。在包开发中，可能会通过 trait 或接口导入来开关功能，此时先加上 `false`，再根据各包实际情况改为 `true` 更加灵活。
</Info>

## 在 composer.json 中注册脚本

在 `composer.json` 中注册 `pint` 相关脚本后，就可以直接通过 `composer pint` 执行。

```json theme={null}
{
    "scripts": {
        "pint": "./vendor/bin/pint",
        "pint:test": "./vendor/bin/pint --test"
    }
}
```

注册后可像下面这样运行：

```shell theme={null}
# 自动修复
composer pint

# 仅检查（不修改）
composer pint:test
```

<Info>
  在 CI 环境中可以使用 `composer pint:test`，它会在不修改文件的情况下检测风格违规。`--test` 选项在有错误时会返回非零退出码，可用于 CI 的通过判断。
</Info>

## 在 GitHub Actions 中自动执行

可以借助 GitHub Actions，在每次推送时自动修复代码风格并提交。

<Steps>
  <Step title="设置 Workflow 权限">
    在 GitHub 仓库 **Settings > Actions > General > Workflow permissions** 中启用「Read and write permissions」。
  </Step>

  <Step title="创建 Workflow 文件">
    创建 `.github/workflows/lint.yml`。

    ```yaml theme={null}
    name: Fix Code Style

    on: [push]

    jobs:
      lint:
        runs-on: ubuntu-latest
        strategy:
          fail-fast: true
          matrix:
            php: [8.4]

        steps:
          - name: Checkout code
            uses: actions/checkout@v5

          - name: Setup PHP
            uses: shivammathur/setup-php@v2
            with:
              php-version: ${{ matrix.php }}
              tools: pint

          - name: Run Pint
            run: pint

          - name: Commit linted files
            uses: stefanzweifel/git-auto-commit-action@v6
    ```
  </Step>
</Steps>

该工作流会在每次推送时运行 Pint，并自动提交修复后的文件。

<Tip>
  由于在 Pull Request 评审前就完成了自动修复，可以显著减少关于代码风格的评论。团队引入时，先在本地对全部文件修复一次，再添加工作流，可以避免额外的提交。
</Tip>


## Related topics

- [Laravel 与 AI 开发](/zh/ai.md)
- [Laravel Package Skeleton — 官方包开发用启动模板](/zh/blog/package-skeleton-introduction.md)
- [Laravel Boost](/zh/boost.md)
- [Laravel Telescope](/zh/telescope.md)
- [Laravel Bluesky](/zh/packages/laravel-bluesky/index.md)
