legalthings/data-enricher

通过处理特殊属性来丰富对象

v0.8.3 2020-10-30 19:37 UTC

README

Build Status Scrutinizer Code Quality Code Coverage

通过处理称为数据指令的特殊属性来丰富对象。

  • <ref> - 使用点键路径解析文档另一部分的引用
  • <ifset> - 检查引用是否为null。如果是,则将对象替换为null。
  • <switch> - 根据文档中的属性选择一个子属性
  • <src> - 通过HTTP加载外部资源
  • <merge> - 合并一组对象
  • <enrich> - 通过匹配属性用额外数据丰富对象
  • <tpl> - 将文本解析为 Mustache 模板
  • <transform> - 使用函数转换输入。以下函数可用。您可以传递以下格式的字符串 <function>:<arg> 或者您可以传递一个对象来传递多个参数 { function: <string>, args: [...] }
  • <jmespath> - 使用 JMESPath 查询语言投影对象
  • <dateformat> - 接收日期和格式(默认为 Y-m-d)并相应地格式化。如果需要输出时区信息,您可以设置时区。

安装

composer require legalthings/data-enricher

用法

源代码

{
  "foo": {
    "bar": {
      "qux": 12345,
    },
    "term": "data enrichment",
    "city": "Amsterdam",
    "country": "Netherlands"
  },
  "amount": {
    "<ref>" : "foo.bar.qux"
  },
  "message": {
    "<tpl>": "I want to go to {{ foo.city }}, {{ foo.country }}"
  },
  "shipping": {
    "<switch>": "foo.country",
    "USA": "UPS",
    "Netherlands": "PostNL",
    "_other": "DHL"
  },
  "user" : {
    "<src>": "https://api.example.com/users/9870"
  },
  "search_results": {
    "<src>": {
      "<tpl>": "http://api.duckduckgo.com/?q={{ foo.term }}&format=json"
    },
    "<jmespath>": "RelatedTopics[].{url: FirstURL, description: Text}"
  },
  "profile": {
    "<merge>": [
      { "<ref>": "foo.bar" },
      { "<src>": "https://api.example.com/zoo/99" },
      {
        "apples": 100,
        "pears": 220
      }
    ]
  }
}

PHP 脚本

$json = file_get_contents('source.json');
$object = json_decode($json);

$enricher = new DataEnricher();
$enricher->applyTo($object);

echo json_encode($object, JSON_PRETTY_PRINT);

结果

{
  "foo": {
    "bar": {
      "qux": 12345,
    },
    "term": "data enrichment",
    "city": "Amsterdam",
    "country": "Netherlands"
  },
  "amount": 12345,
  "message": "I want to go to Amsterdam, Netherlands",
  "shipping": "PostNL",
  "user" : {
    "id": "9870",
    "name": "John Doe",
    "email": "john@example.com"
  },
  "search_results": [
    {
      "url": "https://duckduckgo.com/Names_Database",
      "description": "Names Database - The Names Database is a partially defunct social network, owned and operated by Classmates.com, a wholly owned subsidiary of United Online. The site does not appear to be significantly updated since 2008, and has many broken links and display issues."
    },
    {
      "url": "https://duckduckgo.com/c/Tor_hidden_services",
      "description": "Tor hidden services"
    },
    {
      "url": "https://duckduckgo.com/c/Internet_privacy_software",
      "description": "Internet privacy software"
    }
  ],
  "profile": {
    "qux": 12345,
    "zoop": "P99",
    "zooq": "Q99",
    "apples": 100,
    "pears": 220
  }
}