2024년 7월 10일 수요일

Laravel : 바른 친구 php-cs-fixer

Laravel : 바른 친구 php-cs-fixer

바른 친구 php-cs-fixer 를 사용해보자.

각기 다른 팀원들이 자기만의 스타일로 일하는 경우가 있다. 같은 스타일로 코드품질을 높여보자.

php-cs-fixer 라는 php lint 툴이 있다. 설치도 쉽고 사용도 쉽고 내용은 디테일하다.

써보자.

개발때에만 사용해야 되므로 dev옵션을 꼭 붙이자.

composer require --dev friendsofphp/php-cs-fixer

여기에 설치된다.
./vendor/friendsofphp/php-cs-fixer/php-cs-fixer

사용법은 간단하다.
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer?tab=readme-ov-file#installation

php-cs-fixer fix myfileeeees(or mydirecccctory)  

이렇게 하면 기본값으로 파일을 막 고쳐 주는데 고치는건 내가 하려고 할때는 --dry-run 을 붙이고 화면에 뭐가 잘못된건지 보고 싶을때는 --diff 를 붙인다.

php-cs-fixer fix myfileeeees(or mydirecccctory)   --dry-run --diff 

이렇게 하면 이렇단다.

Loaded config default.
Using cache file ".php-cs-fixer.cache".
 1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

   1) app/Http/Controllers/TotController.php (function_declaration, braces_position)
      ---------- begin diff ----------
--- /var/www/html/app/Http/Controllers/TotController.php
+++ /var/www/html/app/Http/Controllers/TotController.php
@@ -12,7 +12,8 @@
     protected $searchPresenter;
 
 
-    public function __construct(TotTopBannerPresenter $bannerPresenter, TotSearchPresenter $searchPresenter)    {
+    public function __construct(TotTopBannerPresenter $bannerPresenter, TotSearchPresenter $searchPresenter)
+    {
         $this->bannerPresenter = $bannerPresenter;
         $this->searchPresenter = $searchPresenter;
     }

      ----------- end diff -----------

괄호가 이상한 위치라는걸 잡았단다.

그럼, 괄호가 위치가 어떤 기준에서 볼때 잘못된 거냐고 판단하는거야? 라고 묻는다면. --config=.php-cs-fixer.dist.php 옵션을 붙이고 .php-cs-fixer.dist.php 파일을 생성해서 입맛에 맞는 규칙을 추가해 주면된다.
룰은 정말 다양하게 제공된다. if의 앞뒤 공백, 함수인자사이의 공백, array 와 [] 등등 있다.
여기서 찾아보자. https://mlocati.github.io/php-cs-fixer-configurator/#version:3.59

<?php

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

return (new PhpCsFixer\Config())
    ->setRules([
        '@PER-CS' => true,
        '@PHP82Migration' => true,
    ])
    ->setFinder($finder)
;

./vendor/friendsofphp/php-cs-fixer/php-cs-fixer fix ./app/Http/Controllers/TotController.php --diff --dry-run --verbose --config=.php-cs-fixer.dist.php

git 에 올릴때 pre-commit 으로 체크해서 오류가 나면 올리지 못하게 하자.

.git/hooks/pre-commit 파일을 만들거나 수정해 보자.

#!/bin/bash

  

# Stash staged changes

git  stash  -q  --keep-index

  

# Run PHP CS Fixer on staged PHP files

files=$(git  diff  --cached  --name-only  --diff-filter=ACM  "*.php")

if [ -n "$files" ]; then

echo  "Running php-cs-fixer..."

docker  exec  procjet-php-1  /var/www/html/vendor/friendsofphp/php-cs-fixer/php-cs-fixer  fix  --dry-run  --diff  --using-cache=no  $files

if [ $? -ne 0 ]; then

echo  "PHP CS Fixer found issues. Please fix them and try again."

git  stash  pop  -q

exit  1

fi

fi

  

# Restore staged changes

git  stash  pop  -q

“docker exec procjet-php-1 /var/www/html/vendor/friendsofphp/php-cs-fixer/php-cs-fixer” 이부분은 내가 docker를 쓰고 있어서 그런거다. 로컬에서 php 깔아서 한다면 필요없으미 삭제하면 된다.

git 으로 커밋해보면

> git -c user.useConfigOnly=true commit --quiet --allow-empty-message --file -
Running php-cs-fixer...
PHP CS Fixer 3.59.3 7th Gear by Fabien Potencier, Dariusz Ruminski and contributors.
PHP runtime: 7.4.1
Running analysis on 1 core sequentially.
You can enable parallel runner and speed up the analysis! Please see https://cs.symfony.com/doc/usage.html for more information.
Loaded config default.
 0/1 [░░░░░░░░░░░░░░░░░░░░░░░░░░░░]   0%
 1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

   1) app/Http/Controllers/TotController.php
      ---------- begin diff ----------
--- /var/www/html/app/Http/Controllers/TotController.php
+++ /var/www/html/app/Http/Controllers/TotController.php
@@ -12,7 +12,8 @@
     protected $searchPresenter;
 
 
-    public function __construct(TotTopBannerPresenter $bannerPresenter, TotSearchPresenter $searchPresenter)    {
+    public function __construct(TotTopBannerPresenter $bannerPresenter, TotSearchPresenter $searchPresenter)
+    {
         $this->bannerPresenter = $bannerPresenter;
         $this->searchPresenter = $searchPresenter;
     }

      ----------- end diff -----------


Found 1 of 1 files that can be fixed in 0.035 seconds, 20.00 MB memory used
PHP CS Fixer found issues. Please fix them and try again.

응 그래. 잘못된 파일은 올리면 안돼.

vscode 에서 사용하기

php cs fixerv0.3.13
junstyle

이라는 익스텐션을 다운받고, settings.json 에 아래 항목이 있다면 ${workspace}/vendor/bin/php-cs-fixer 를 지정하면된다.
그리고 나서 작업중인 파일에서 F1 을 누르고 php-cs-fixer:diff 혹은 php-cs-fixer:fix를 선택하면 된다.

"php-cs-fixer.executablePath": "${workspaceFolder}/docker-exex-php-cs-fixer.sh",

docker에 php를 실행하고 있다면

docker에 php를 실행하고 있다면 스크립트를 만들어서 스크립트에서 php의 도커에서 실행한다.

"php-cs-fixer.executablePath": "${workspaceFolder}/docker-exex-php-cs-fixer.sh",

스크립트는 아래와 같다.

#!/bin/bash 
# Docker 컨테이너 이름

CONTAINER_NAME="project-php-1"

# PHP-CS-Fixer 경로
PHP_CS_FIXER_PATH="/var/www/html/vendor/bin/php-cs-fixer"

# 컨테이너 내부의 프로젝트 경로
PROJECT_PATH="/var/www/html"

  

for  arg  in  "$@"; do
args+=("${arg/\/Users\/blabla\/pnm_docker\/procjet\/myweb/$PROJECT_PATH}")
done 

# 실행

docker  exec  procjet-php-1  $PHP_CS_FIXER_PATH  --diff  "${args[@]}"  --format=txt

0 comments:

댓글 쓰기