Публикация была переведена автоматически. Исходный язык: Английский
Larastan — это обертка над PHPStan, предназначенная для статического анализа кода, которая поддерживает особенности Laravel. Использование Larastan позволяет выявить потенциальные ошибки в коде на ранних стадиях разработки, что улучшает качество кода и снижает затраты на исправление багов. В этом руководстве мы рассмотрим, как установить, настроить и использовать Larastan для повышения качества вашего Laravel-приложения до уровня 9.
Первым шагом является установка Larastan в ваш проект. Это делается с помощью Composer:
composer require larastan/larastan:^2.0 --dev
Этот шаг добавит Larastan как зависимость разработки в ваш проект. После этого необходимо создать файл конфигурации PHPStan.
В корне вашего проекта создайте файл phpstan.neon. Этот файл будет содержать конфигурацию для PHPStan и Larastan:
includes:
- vendor/larastan/larastan/extension.neon
parameters:
paths:
- app/
level: 0
В этом файле мы указываем, что будем использовать расширение Larastan и задаем начальный уровень проверки кода.
Теперь мы можем запустить первый анализ кода:
./vendor/bin/phpstan analyse
Этот анализ покажет ошибки и предупреждения в вашем коде. На начальном уровне (level 0) будет выявлено минимальное количество проблем. Ваша задача — исправить все выявленные ошибки перед тем, как повышать уровень.
Larastan и PHPStan поддерживают уровни анализа от 0 до 9. Каждый уровень включает в себя более строгие правила проверки кода. После того как вы исправите все ошибки на текущем уровне, можно повышать уровень в файле конфигурации:
neonКопировать кодparameters:
level: 1
После изменения уровня снова запустите анализ и исправьте выявленные ошибки. Повторяйте этот процесс, пока не достигнете уровня 9.
Помимо базовой проверки, Larastan предлагает дополнительные возможности для улучшения качества кода:
- Анализ типов: Larastan проверяет типы данных, что помогает избежать ошибок, связанных с неправильным использованием типов.
- Поддержка анотаций: Larastan понимает анотации в вашем коде, такие как @var, @param, @return, и использует их для проверки соответствия типов.
- Интеграция с тестами: Larastan можно интегрировать с вашими тестами, что позволяет выявлять ошибки еще до выполнения тестов.
Рассмотрим несколько примеров, как Larastan может помочь улучшить ваш код.
function add(int $a, int $b): int {
return $a + $b;
}
echo add(1, '2');
В этом примере функция ожидает два параметра типа int, но второй параметр передается как строка. Larastan выявит эту ошибку и предупредит вас.
/**
* @param int $a
* @param int $b
* @return int
*/
function add($a, $b) {
return $a + $b;
}
Если вы забудете указать типы параметров в функции, Larastan проверит анотации и укажет на несоответствие типов.
Использование Larastan в вашем Laravel-проекте позволяет значительно улучшить качество кода, выявляя ошибки на ранних стадиях разработки. Последовательное повышение уровня проверки от 0 до 9 поможет вам сделать код более надежным и безопасным.
Larastan is a wrapper over PHPStan designed for static code analysis that supports Laravel features. Using Larastan allows you to identify potential errors in the code at the early stages of development, which improves the quality of the code and reduces the cost of fixing bugs. In this guide, we will look at how to install, configure and use Larastan to improve the quality of your Laravel application to Level 9.
The first step is to install Larastan in your project. This is done using Composer:
composer require larastan/larastan:^2.0 --dev
This step will add Larastan as a development dependency to your project. After that, you need to create a PHPStan configuration file.
Create a phpstan.neon file in the root of your project. This file will contain the configuration for PHPStan and Larastan:
includes:
- vendor/larastan/larastan/extension.neon
parameters:
paths:
- app/
level: 0
In this file, we specify that we will use the Larastan extension and set the initial level of code verification.
Now we can run the first code analysis:
./vendor/bin/phpstan analyse
This analysis will show errors and warnings in your code. At the initial level (level 0), a minimum number of problems will be identified. Your task is to correct all identified errors before you level up.
Larastan and PHPStan support analysis levels from 0 to 9. Each level includes stricter code validation rules. After you fix all the errors at the current level, you can upgrade the level in the configuration file:
Copy the parameters code:
level: 1
After changing the level, run the analysis again and correct the identified errors. Repeat this process until you reach level 9.
In addition to basic verification, Larastan offers additional features to improve the quality of the code:
- Type analysis: Larastan verifies data types, which helps to avoid errors related to incorrect use of types.
- Support for anotations: Larastan understands anotations in your code, such as @var, @param, @return, and uses them to verify type matching.
- Integration with tests: Larastan can be integrated with your tests, which allows you to identify errors even before running tests.
Let's look at some examples of how Larastan can help improve your code.
function add(int $a, int $b): int {
return $a + $b;
}
echo add(1, '2');
In this example, the function expects two int type parameters, but the second parameter is passed as a string. Larastan will identify this error and warn you.
/**
* @param int $a
* @param int $b
* @return int
*/
function add($a, $b) {
return $a + $b;
}
If you forget to specify the parameter types in the function, Larastan will check the annotations and point out the type mismatch.
Using Larastan in your Laravel project allows you to significantly improve the quality of the code by identifying errors in the early stages of development. Consistently increasing the verification level from 0 to 9 will help you make the code more reliable and secure.