承接 nish/phpstan-safestring-rule 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

nish/phpstan-safestring-rule

Composer 安装命令:

composer require --dev nish/phpstan-safestring-rule

包简介

Extension of PHPStan: Warn about unsafe strings

README 文档

README

This package is a PHPStan extension for checking unsafe string, e.g. Check calling echo without calling htmlspecialchars, check calling database query without using prepared statement.

Notice

This package does not meet the "backward compatibility promise". Because it extends the basic processing of the core, it is not guaranteed to work with version differences.

https://phpstan.org/developing-extensions/backward-compatibility-promise

Install

composer require --dev nish/phpstan-safestring-rule

How to use

Add to phpstan.neon

includes:
  - vendor/nish/phpstan-safestring-rule/extension.neon

services:
  -
    class: Nish\PHPStan\Rules\EchoHtmlRule
    tags: [phpstan.rules.rule]
  -
    factory: Nish\PHPStan\Type\SafeHtmlStringReturnTypeExtension([htmlspecialchars, h, raw])
    tags: [nish.phpstan.broker.dynamicFunctionReturnTypeExtension]

composer.json is:

    "autoload": {
        "psr-4": { "App\\": "src" },
        "files": [
            "src/functions.php"
        ]
    },

Value Object class src/ProductDto.php:

<?php

namespace App;

class ProductDto
{
    /** @var int */
    public $product_id;
    /** @var string */
    public $name;
    /** @var ?string */
    public $description;
}

Html Template src/ProductHtml.php:

<?php
namespace App;
class ProductHtml {
    public function view(ProductDto $product): void {
?>

<div>
  <div>
    <?= $product->product_id ?>
  </div>
  <div>
    <?= $product->name ?>
  </div>
  <div>
    <?= $product->description ?>
  </div>
</div>

<?php
    }
}

The execution result of phpstan in this case is as followings:

 3/3 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

 ------ ---------------------------------------------------- 
  Line   ProductHtml.php                                     
 ------ ---------------------------------------------------- 
  12     Parameter #1 (string) is not safehtml-string.       
  15     Parameter #1 (string|null) is not safehtml-string.  
 ------ ---------------------------------------------------- 

                                                             
 [ERROR] Found 2 errors                                      

Then, can not call echo the string type directly.

safehtml-string is a virtual type, it can be fixed by adding a helper function.

src/functions.php:

<?php

/**
 * @param int|string|null $input
 */
function h($input): string
{
    return htmlspecialchars((string)$input);
}

/**
 * @param int|string|null $input
 */
function raw($input): string
{
    return (string)$input;
}

phpstan.neon

services:
# ...
  -
    factory: Nish\PHPStan\Type\SafeHtmlStringReturnTypeExtension([htmlspecialchars, h, raw])
    tags: [nish.phpstan.broker.dynamicFunctionReturnTypeExtension]

src/ProductHtml.php:

<?php
namespace App;
class ProductHtml {
    public function view(ProductDto $product): void {
?>

<div>
  <div>
    <?= $product->product_id ?>
  </div>
  <div>
    <?= h($product->name) ?>
  </div>
  <div>
    <?= h($product->description) ?>
  </div>
</div>

<?php
    }
}

run phpstan

an/phpstan.neon.
 3/3 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

                                                             
 [OK] No errors

OK, no errors and it's secure!

Tips

Constant String Type is not needs convert to safehtml-string.

<?php
namespace App;
class TypeHtml {
    const CURRENT_TYPE_ID = 2;
    const TYPES = [
        1 => 'TYPE 1',
        2 => 'TYPE 2',
        3 => 'TYPE 3',
    ];
    public function view(): void {
?>

<div>
  <div>
    <?= self::CURRENT_TYPE_ID ?>
  </div>
  <div>
    <?= self::TYPES[self::CURRENT_TYPE_ID] ?>
  </div>
</div>

<?php
    }
}

This is no error.

When used for methods instead of functions:

  -
    factory: Nish\PHPStan\Type\SafeHtmlStringReturnTypeExtension(DateTimeInterface::format)
    tags: [nish.phpstan.broker.dynamicMethodReturnTypeExtension]
  -
    factory: Nish\PHPStan\Type\SafeHtmlStringReturnTypeExtension(App\FormUtil::makeForm)
    tags: [nish.phpstan.broker.dynamicMethodReturnTypeExtension]

Cannot specify more than one at a time.

Important: Always use the custom nish.phpstan.* tags instead of PHPStan's core tags to avoid interference with PHPStan's internal processing.

Use safe-string Custom Type

If you have the following database access program

<?php

namespace App;

use PDO;

class ProductDb
{
    /** @var PDO */
    private $pdo;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    /**
     * @return array<int,ProductDto>
     */
    public function getProductList(string $where): array
    {
        $stmt = $this->pdo->query('select * from products ' . $where);
        if (!$stmt)
            return [];
        $ret = $stmt->fetchAll(PDO::FETCH_CLASS, ProductDto::class);
        if (!$ret)
            return [];

        /** @var array<int,ProductDto> $ret */
        return $ret;
    }
}

pdo->query() is not secure.

If the class is the following program,

<?php

namespace App;

use PDO;

class ProductPage
{
    /** @return mixed */
    public static function index(PDO $pdo, string $where)
    {
        $productModel = new ProductDb($pdo);
        $products = $productModel->getProductList($where);

        return [
            'templateData' => ['products' => $products],
        ];
    }
}

I want an error to be displayed.

Achieve that by writing the following settings to phpstan.neon.

services:
# ...
  -
    factory: Nish\PHPStan\Rules\SafeStringCallRule([
        'PDO::query': 0,
    ])
    tags: [phpstan.rules.rule]

0 is the index of the argument.

Run phpstan.

 6/6 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

 ------ ------------------------------------------- 
  Line   ProductDb.php                              
 ------ ------------------------------------------- 
  22     Parameter #1 (string) is not safe-string.  
 ------ ------------------------------------------- 

                                                             
 [ERROR] Found 1 error

More control, it can use the safe-string type.

    /**
     * @param safe-string $where
     * @return array<int,ProductDto>
     */
    public function getProductList(string $where): array

What happens if I write a hint?

 6/6 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

 ------ ------------------------------------------------------ 
  Line   ProductPage.php                                       
 ------ ------------------------------------------------------ 
  13     Parameter #1 $where of method                         
         App\ProductDb::getProductList() expects safe-string,  
         string given.                                         
 ------ ------------------------------------------------------ 
                                                              
 [ERROR] Found 1 error

Changed to caller error.

If the string is clearly known to be "constant string (and its derivatives)", no error is raised.

class ProductPage
{
    /** @return mixed */
    public static function index(PDO $pdo, int $id)
    {
        $productModel = new ProductDb($pdo);
        $where = sprintf('where product_id > %d', $id);
        $products = $productModel->getProductList($where);
 6/6 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

                                                               
 [OK] No errors

Tips

Add return type rules:

factory: Nish\PHPStan\Rules\SafeStringReturnTypeRule([
    App\Db\Utils::getSafeConditionString,
])
tags: [phpstan.rules.rule]

nish/phpstan-safestring-rule 适用场景与选型建议

nish/phpstan-safestring-rule 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 58 次下载、GitHub Stars 达 4, 最近一次更新时间为 2020 年 01 月 09 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「static analysis」 「code analysis」 「PHPStan」 「code analyse」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 nish/phpstan-safestring-rule 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 nish/phpstan-safestring-rule 我们能提供哪些服务?
定制开发 / 二次开发

基于 nish/phpstan-safestring-rule 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 58
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 4
  • 点击次数: 1
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 4
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-01-09