返回介绍

Static Code Analysis

发布于 2024-06-22 20:04:58 字数 4822 浏览 0 评论 0 收藏 0

Static code analysis is the process of analyzing the source code against a set of rules to find bugs, code smells, and security vulnerabilities. This is a great way to improve the quality of your code and to find potential issues before they are deployed to production. An example is validating the typings of a function to ensure that the function is called with the correct arguments.

Flarum provides a static code analysis package based on PHPStan that can be added to your extension. In this guide, we will show you how to add the package to your extension and how to run the analysis.

Setup

Flarum CLI

You can use the CLI to automatically add and update the infrastructure for phpstan to your code:

$ flarum-cli infra phpstan

First you need to require the flarum/phpstan package in your extension. You can do this by running the following command in the root of our extension:

composer require --dev flarum/phpstan:^1.0

Next, you need to create a phpstan.neon file in the root of your extension. This file contains the configuration for PHPStan. You can copy the following configuration into the file:

includes:
  - vendor/flarum/phpstan/extension.neon

parameters:
  # The level will be increased in Flarum 2.0
  level: 5
  paths:
    - src
    - extend.php
  excludePaths:
    - *.blade.php
  checkMissingIterableValueType: false
  databaseMigrationsPath: ['migrations']

Finally, you need to add the following script to your composer.json file:

{
  "scripts": {
    "analyse:phpstan": "phpstan analyse",
    "clear-cache:phpstan": "phpstan clear-result-cache"
  },
  "scripts-descriptions": {
    "analyse:phpstan": "Run static analysis"
  }
}

Running the analysis

To run the analysis, you can run the following command in the root of your extension:

composer analyse:phpstan

If you want to clear the cache before running the analysis, you can run the following command:

composer clear-cache:phpstan && composer analyse:phpstan

GitHub Actions

You can also run the analysis using GitHub Actions. Checkout the page on GitHub Actions for more information.

Tips

Extended model attribute types

PHPStan needs to be able to determine the type of an attribute added to an existing model. To do this you can use the Extend\Model(...)->cast(...) method.

For example, if your extension were to add a is_cool attribute to the User model, you can use attribute casting to explicitly define the attribute as boolean. The flarum/phpstan package will automatically detect this and communicate it to PHPStan.

(new Extend\Model(User::class))
    ->cast('is_cool', 'bool'),

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文