coderofsalvation/typeshave

PHP/JS 轻量级类型安全的函数包装器。使用 jsonschema(http://coderofsalvation.github.io/typeshave)验证表单、API 等嵌套数据

dev-master 2020-05-28 19:30 UTC

This package is not auto-updated.

Last update: 2024-09-18 09:12:56 UTC


README

防止函数因垃圾输入而崩溃。

使用 typeshave 包装器在 JS & PHP 中保护函数的输入数据(typeshave 网站

用法

$ echo '{ "minimum-stability": "dev" }' > composer.json
$ composer require coderofsalvation/typeshave

然后

use coderofsalvation\TypeShave;

function foo2($foo){
  TypeShave::check( $foo, (object)array(
    "foo" => (object)array( "type" => "string", "minLength" => 1, "regex" => "/foo/" )
  ));
}

foo2( 123 );       // will throw exception 

或者,我们甚至可以内联编写 jsonschema

function foo2($foo){
  TypeShave::check( $foo, '{ "foo": { "type": "string", "minLength":1, "regex": "/foo/"}  }' );
}

typeshave 使用成熟的 jsonschema 验证格式,它甚至支持验证嵌套数据结构。可重用于许多其他领域(数据库、REST 请求体、表单验证等)

或者

// multiple arguments at once 

function foo($foo, $bar){
  TypeShave::check( func_get_args(), '{
    "foo": { "type": "string"  },
    "bar": { "type": "integer" }
  }');
  // do stuff
}

foo( true, true ); // will throw exception

或者,关于如何使用 单独的 jsonschema 文件 通过 separate jsonschema file 传递 PHAT 嵌套容器而无需冗长

function phat($container){
  TypeShave::check( $container, __DIR__."/test.json" ); 
}

$container = (object)array(
  "foo" => "foo",
  "bar" => "bar2",
  "records" => array(
    (object)array( "foo" => "foo" )
  )
);

phat($container);

请参阅 test.json 这里

为什么非类型安全很好,但与 PHAT 嵌套对象一起使用时却不是这样

例如

  • REST 有效载荷
  • 代表配置或选项的对象
  • 用于 HTML 渲染或处理的数据结构和结果集

您还在“交叉手指”式地传递 PHAT 数据吗?还在想知道为什么这样的函数有时会崩溃吗? :D

foo( (object)array( "foo"=>"bar", "bar"=>123, "records": array( 1, 2 )) );

您尝试过用 if/else 检查将 PITA 代码转换为 PITA 吗?

function foo($data){
  if( isset($data)          && 
      is_object($data)      && 
      isset($data->foo)     && 
      is_string($data->foo) &&
      .. 
      && 
      .. 
      && Argh this is a big PITA 
  // omg how do I even check properties recursively?
  foreach( $data->records as $record ){
    // PITA 
    // PITA 
    // PITA 
    // PITA 
  }
  ...
  // now finally we can do what the function should do :/
}

结论

没有更多

  • 失去控制的函数
  • 函数内的断言膨胀
  • 抱怨 JavaScript 不是类型安全的
  • 类型安全的嵌套数据结构
  • 冗长的单元测试做类型安全的事情

Typeshave 在出现问题时立即处理这些问题,以防止这种情况发生

注意:数组

v4 jsonschema 验证器通过注意 'items' 变量支持数组,因此请省略在旧版 jsonschema 格式中可以找到的 type: "array"

   "myarray": {
//   "type": array,     *REMOVE ME*
     "items": [{
        "type": "integer"  
      }]
   }