> ## 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 中未 commit 的檔案      |
| `--diff=[branch]`   | 只針對與指定分支有差異的檔案             |
| `--repair`          | 修正樣式錯誤，若有修正則回傳非零結束碼        |
| `--parallel`        | 使用平行執行模式（實驗性）以提升效能         |
| `--max-processes=4` | 與 `--parallel` 搭配指定最大處理程序數 |
| `-v`                | 顯示變更內容的詳細資訊                |
| `--config`          | 指定要使用的 `pint.json` 路徑      |
| `--preset`          | 指定要使用的 preset              |

```shell theme={null}
# 只檢查不變更檔案
./vendor/bin/pint --test

# 只針對未 commit 的檔案
./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
```

### Preset

Preset 是一組規則集。預設為 `laravel` preset，會套用最適合 Laravel 專案的規則。

| Preset    | 說明                   |
| --------- | -------------------- |
| `laravel` | Laravel 推薦的程式碼樣式（預設） |
| `psr12`   | PSR-12 撰寫標準          |
| `per`     | PER Coding Style     |
| `symfony` | Symfony 的程式碼樣式       |
| `empty`   | 無規則。自行定義規則後使用        |

```shell theme={null}
# 在命令列指定 preset
./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 或介面 import 來開關功能，因此先加入 `false`，再依各套件狀況改為 `true` 的做法很方便。
</Info>

## 在 composer.json 設定 scripts

若在 `composer.json` 註冊 `pint` 用的 scripts，就能只用 `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 在每次推送時自動修正程式碼樣式並 commit。

<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，並自動 commit 修正樣式違規的檔案。

<Tip>
  由於在 Pull Request review 前就已自動修正，可減少關於程式碼樣式的 review 留言。團隊導入時，建議先在本機一次修正所有檔案再加入工作流程，避免產生多餘的 commit。
</Tip>


## Related topics

- [Laravel 與 AI 開發](/zh-TW/ai.md)
- [Laravel Package Skeleton — 官方套件用起始模板](/zh-TW/blog/package-skeleton-introduction.md)
- [Laravel Boost](/zh-TW/boost.md)
- [cpx 2.0 — Composer Package Executor 全面重寫](/zh-TW/blog/cpx-introduction.md)
- [Laravel Telescope](/zh-TW/telescope.md)
