Menu
CoddyTech

项目:连接处理流程

Coddy 面向 Ruby 开发者的 PHP 课程的第 46 课,共 48 课。

challenge icon

挑战

简单

输入 [4,rows]。完成 Reporter::report(array):string。使用 Parser 解析每一行,忽略无效行,每次调用时都使用一个新的 Ledger 汇总有效条目,并用换行符连接排序后的行,或返回 empty。保留之前的所有 API。

提供的 main 脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并打印结果。实现模块声明,不要打印内容;不要替换启动器,也不要从模块读取输入。输入符合指定的类型和范围。

编辑 Entry.php、Parser.php、Ledger.php、Reporter.php。main.php 是锁定的入口文件。依赖项使用 require_once __DIR__ 和相对文件名。

亲手试试

<?php
declare(strict_types=1);
require_once __DIR__."/Entry.php";
require_once __DIR__."/Parser.php";
require_once __DIR__."/Ledger.php";
require_once __DIR__."/Reporter.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function projectReport(array $input):string{
 [$stage,$data]=$input;
 if($stage===1){$e=(new Parser())->parse($data);return $e===null?"invalid":$e->name.":".$e->minutes;}
 if($stage===2){$l=new Ledger();foreach($data[0] as [$name,$minutes])$l->add(new Entry($name,$minutes));return (string)$l->total($data[1]);}
 if($stage===3){$l=new Ledger();foreach($data as [$name,$minutes])$l->add(new Entry($name,$minutes));$out=$l->lines();return $out===[]?"empty":implode("\n",$out);}
 return (new Reporter())->report($data);
}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$stage=$input[0];$parser=new Parser();$e=$parser->parse("tea:007");ensure($e instanceof Entry && $e->name==="tea" && $e->minutes===7 && $parser->parse("tea:-1")===null && $parser->parse(" tea:2")===null,"parser API");
if($stage>=2){$l=new Ledger();$l->add(new Entry("b",4));$l->add(new Entry("b",3));$l->add(new Entry("a",0));ensure($l->total("b")===7 && $l->total("x")===0,"aggregation API");}
if($stage>=3){ensure($l->lines()===["a:0","b:7"] && $l->lines()===["a:0","b:7"],"ordered snapshot");}
if($stage>=4){$r=new Reporter();ensure($r->report(["z:3","bad","z:2"])==="z:5" && $r->report([])==="empty","fresh report state");}
echo projectReport($input),"\n";

面向 Ruby 开发者的 PHP中的所有课

自己练习: PHP 在线编译器