lmnt / philo-cli
使用可扩展且富有表现力的philo语法从终端处理数据
dev-master
2020-06-03 04:13 UTC
Requires
- docopt/docopt: ^1.0
- lmnt/philo: @dev
- psy/psysh: ^0.10.4
This package is auto-updated.
Last update: 2024-09-29 05:36:21 UTC
README
使用可扩展且富有表现力的philo语法从终端处理数据
需要PHP 7.4+
全局安装
如果您没有使用cgr
进行全局安装,请考虑采用它
composer global require consolidation/cgr
然后通过cgr
全局安装philo
cgr --stability dev lmnt/philo-cli
交互式模式
使用repl进行实验
> philo
谓词与类型
让我们定义几个类型
⏂ > $Age = all(is_int, gt(0), lt(150)) ⏂ > $Person = ['name' => is_string, 'age' => $Age, 'website' => maybe(is_url)] ⏂ > $Contacts = every($Person)
现在我们可以做一些断言了
⏂ > is($Person, ['name' => 'bob', 'age' => 50]) => true ⏂ > is($Person, ['name' => 'bob', 'age' => 50, 'extra' => 1]) => true ⏂ > is(strict($Person), ['name' => 'bob', 'age' => 50, 'extra' => 1]) => false ⏂ > is($Person, ['name' => 'bob', 'age' => -1]) => false ⏂ > is($Person, ['name' => 'bob', 'age' => 50, 'website' => 'google.com']) => false ⏂ > is($Person, ['name' => 'bob', 'age' => 50, 'website' => 'http://google.com']) => true ⏂ > is($Contacts, [['name' => 'bob', 'age' => 50]]) => true ⏂ > is($Contacts, [['name' => 'bob', 'age' => 50], 'barb']) => false
对于内置类型也是一样
⏂ > $x = new \ArrayObject() ⏂ > is(\ArrayObject::class, $x) => true ⏂ > is(\Countable::class, $x) => true
通过ctrl + c
或输入exit
返回终端。
加载数据
将数据从本地文件或URL加载到philo中。
让我们用来自公共端点的json重新启动repl
> philo http://data.cdc.gov/data.json
检查数据源
⏂ > $x
最后3个条目的关键词是什么?
⏂ > pipe(to_array(pluck('keyword')), slice(-3))($x['dataset'])
非交互式模式
通过管道输入数据
> echo '[{"a":1,"b":3},{"a":2,"b":4}]' | philo 'to_array(pluck(a), true)' [{"a":1},{"a":2}]
或者通过输入重定向发送
> curl https://newton.now.sh/factor/x^2-1 > /tmp/math > cat /tmp/math {"operation":"factor","expression":"x^2-1","result":"(x - 1) (x + 1)"} > philo 'pipe(to_array(values), spread(fn($a, $b, $c) => [$c, $b, $a]))' < /tmp/math ["(x - 1) (x + 1)","x^2-1","factor"]
扩展philo
在编辑器中打开~/philo-lib.php
并定义一个新类型
<?php namespace philo; const size = 'philo\size'; function size($x) { return is_string($x) ? strlen($x) : (is_countable($x) ? count($x) : null); } return [ 'Thing' => ['name' => pipe(size, gte(5))] ];
保存后完成!试试看
> echo '[{"name": "abc"},{"name":"01234"}]' | \ > philo --lib ~/philo-lib.php 'to_array(map(match($Thing, "thing")))' [null,"thing"]