Upgrade to Pro — share decks privately, control downloads, hide ads and more …

HHVM/Hack ShapeとTypeAssertで堅実なアプリケーション

HHVM/Hack ShapeとTypeAssertで堅実なアプリケーション

HHVM/Hack勉強会Vol.1 slide
https://istyle.connpass.com/event/80398/

yuuki takezawa

April 23, 2018
Tweet

More Decks by yuuki takezawa

Other Decks in Programming

Transcript

  1. shapeͱTypeAssertͰ
    ݎ࿚ͳΞϓϦέʔγϣϯ
    yuuki takezawa (ytake)

    View Slide

  2. εϥΠυͰར༻͍ͯ͠Δαϯϓϧίʔυ
    https://github.com/istyle-inc/example-hack-
    strict-api

    View Slide

  3. ෆ࣮֬ͳAPI

    View Slide

  4. Ͳ͏΍ͬͯܕΛࢦఆ͢Δ͔
    • Collection (Map, Vector etc)
    • Generics
    • shape
    • tuple

    View Slide

  5. [
    ‘message’ => ‘hackstudy’,
    ‘date’ => ‘2018/04/20’
    ];

    View Slide

  6. ഑ྻ͸อূ͞ΕΔ͔
    • ͍ΘΏΔPHPͷ഑ྻ͸ɺܕͷ੍໿͕ͳ͍

    ࣗ༝ͳϋογϡςʔϒϧ
    • ഑ྻͰ͋Ε͹serialize -> json response
    • messageʹint͕ೖͬͨΒʁ
    • date͕intͩͬͨΒʁ
    • Ωʔ͕૿͑ͨΓݮͬͨΓ
    • typo?

    View Slide

  7. ෆ࣮֬Ͱ͔͠ͳ͍ʂ

    View Slide

  8. shape

    View Slide

  9. shape(
    'message' => string,
    'date' => string,
    );

    View Slide

  10. class Serialize {
    public function execute(shape(
    'message' => string,
    'date' => string,
    ) $shape): string {
    return serialize($shape);
    }
    }

    View Slide

  11. $serialize = new \Serialize();
    $serialize->execute(shape(
    'message' => 'hackstudy',
    'date' => '2018/04/20',
    ));

    View Slide

  12. shapeΛ౉ͯ͠΋େৎ෉
    • ഑ྻͱಉ౳ʹར༻͢Δ͜ͱ͕Ͱ͖ΔͷͰɺ

    ઃఆ஋ͳͲΛ౉͢ɺ֎෦Ϧιʔεʹର੍ͯ͠໿Λ͔͚Δ
    ͳͲʹ༻్ʹόονϦ
    • foreach͸shapeʹର࣮ͯ͠ߦͰ͖ͳ͍
    • it doesn't implement Traversable or Container.
    • []͸࢖͑·ͤΜ
    • toArrayͰม׵ͯ͠΋ྑ͍

    View Slide

  13. foreach͍ͨ͠ΜͰ͚͢Ͳ

    View Slide

  14. shape + Collection

    View Slide

  15. type CollectableShape = shape(
    'id' => int,
    'name' => string,
    );

    View Slide

  16. public function executeCollection(shape(
    'message' => string,
    'date' => string,
    'tables' => Vector,
    ) $shape): string {
    $v = Shapes::idx($shape, 'tables', Vector{ });
    return serialize(
    array_merge(
    Shapes::toArray($shape),
    ['tables' => $v->toArray()]
    )
    );
    }

    View Slide

  17. CollectionΛ૊Έ߹Θͤͯଟछଟ༷ʹ
    • ഑ྻʹม׵ͨ͠Γɺ΋͘͠͸഑ྻΛදݱͨ͠Γ
    • ৭ʑͳ༻్Ͱ৭ʑ੍໿Λ͔͚Δ͜ͱ͕Ͱ͖Δ
    • Ͱ΋shape

    View Slide

  18. ֎෦Ϧιʔε͸shapeͰ͸ͳ͍

    View Slide

  19. function nullthrows(
    ?T $data,
    string $message = 'unexpected null’
    ): T {
    invariant(
    $data !== null,
    $message,
    );
    return $data;
    }

    View Slide

  20. APIͷ໭Γ஋ͷνΣοΫʁ
    • ഑ྻʹม׵ͨ͋͠ͱʹgenerics+invariant͢Δʁ
    • ҰͭҰͭεΩϟϯʁ

    View Slide

  21. hhvm/type-assert

    View Slide

  22. ෆ࣮֬ͳ஋ΛΞαʔτʂ
    • primitiveܕ͸΋ͪΖΜɺmapͳͲʹ΋
    • is_aͳͲ΋ந৅Խ
    • Ұ൪ͷ໨ۄ͸ matches_type_structure

    View Slide

  23. use namespace Facebook\TypeAssert;
    class Foo {
    const type TAPIResponse = shape(
    'id' => int,
    'user' => string,
    'data' => shape(/* ... */),
    );
    public static function getAPIResponse(): self::TAPIResponse {
    $json_string = file_get_contents('https://api.example.com');
    $array = json_decode($json_string, /* associative = */ true);
    return TypeAssert\matches_type_structure(
    type_structure(self::class, 'TAPIResponse'),
    $array,
    );
    }
    }

    View Slide

  24. matches_type_structure
    • ReflectionTypeAlias ΫϥεͷgetTypeStructureϝιου͸഑ྻΛ
    ฦͨ͢Ίਏ͍(HackͳΒجຊstirctͰॻ͘͜ͱ͕ଟ͍)

    https://github.com/facebook/hhvm/blob/master/hphp/hack/hhi/
    reflection.hhi#L308
    • ܕ௨ΓͩͬͨΒͦͷ··௨աͯ͠ཉ͍͠ͷͰɺ

    Genericsʹͯ͠΄͍͠ʂ

    type_structure ؔ਺ར༻ͷΈରԠ

    https://github.com/facebook/hhvm/blob/master/hphp/hack/hhi/
    typestructure.hhi#L94

    View Slide

  25. matches_type_structure
    • ݕࠪ͢Δܕ͸const stringͰ͋Δඞཁ͕͋ΔͷͰɺ

    ಈతʹੜ੒͸Ͱ͖ͳ͍

    • shapeͰͻͨ͢Βॻ͔͘͠ͳ͍


    View Slide

  26. json decodeʹؔͯ͠
    • ίʔϧͨ͠APIͷ໭Γ஋ͳͲʹ΋࢖͏͜ͱ͕Ͱ͖Δ

    • JSONʹؔͯ͠͸json_decodeͰ

    ͍͔ͭ͘Hack޲͚Φϓγϣϯ͕͋Γ

    • JSON_FB_COLLECTIONS => Map

    JSON_FB_HACK_ARRAYS => dict

    https://github.com/facebook/hhvm/blob/master/hphp/
    hack/hhi/stdlib/builtins_json.hhi#L41

    View Slide

  27. ΞϓϦέʔγϣϯ͕ฦ٫͢Δ΋ͷʹ
    ద༻
    ݎ࿚ͳϨεϙϯεΛఏڙ͢Δ

    View Slide

  28. ΞϓϦέʔγϣϯͰ࣮༻͢Δʹ͸
    • HackͳΒϚΠΫϩαʔϏεʹ͓͚ΔAPI Gatewayͱ͔

    • ฦ٫͢Δ஋Λ୲อͯ͋͛͠ΔΑ͏ʹͨ͠΄͏͕ྑ͍

    • Ϟμϯͳ΋ͷͰ͋Ε͹ϛυϧ΢ΣΞΛ༻ҙͯ͠ɺ

    ࣗΒͷϨεϙϯεΛௐ΂Δ

    View Slide

  29. ΦϨΦϨHackϑϨʔϜϫʔΫͰ
    ૊ΈࠐΜͰΈͨ
    https://github.com/ytake/nazg-skeleton

    View Slide

  30. ࣮ફ
    • ΞΠελΠϧͰ͸HAL - Hypertext Application Language
    Λ࠾༻͍ͯ͠Δ

    • ߏ଄ΛshapeͰදݱ͢Δ
    • https://techblog.istyle.co.jp/2018/04/18/
    hack%E3%81%A7%E4%BD%9C%E3%82%8B%E5%A0
    %85%E5%AE%9F%E3%81%AAapi/


    View Slide

  31. // goal
    {
    "id":1234,
    "name":"ytake",
    "title":"type-assert for api response",
    "_links":{
    "self":{
    “href":"/",
    "type":"application/json"
    }
    },
    "_embedded":{
    "enviroments":[
    {
    "name":"HHVM/Hack",
    "_links":{
    "self":{
    "href":"https://docs.hhvm.com/"
    }
    }
    }
    ]
    }
    }

    View Slide

  32. // shapeͰhal+jsonΛදݱ͢Δ
    const type embeddedLinks = shape(
    'name' => string,
    '_links' => shape(
    'self' => shape(
    'href' => string
    )
    )
    );
    const type hateoasStructure = shape(
    'id' => int,
    'name' => string,
    'title' => string,
    '_links' => shape(
    'self' => shape(
    'href' => string,
    'type' => string
    )
    ),
    '_embedded' => shape(
    'enviroments' => array
    )
    );

    View Slide

  33. // ར༻ྫɹ͜͜Ͱ͸ImmMap
    new ImmMap([
    'id' => 1234,
    'name' => 'ytake',
    'title' => 'type-assert for api response',
    'embedded' => [
    [
    'name' => 'HHVM/Hack',
    'url' => 'https://docs.hhvm.com/'
    ],
    ]
    ]);

    View Slide

  34. ࣮ફ
    • ImmMapΛड͚औΓhal+jsonʹม׵

    • HalରԠϥΠϒϥϦ͸PHPͰ͍͔ͭ͋͘Δ

    Hack͸PHP͔Β཭Ε͍ͯͬͯΔͨΊɺ

    PHPϥΠϒϥϦ࢖͏ཧ༝΋ͳ͍ͷͰࣗ෼Ͱ࡞Δ(ͨ)

    • https://github.com/ytake/hhhal


    View Slide

  35. protected Vector $vec = Vector{};
    public function __construct(
    protected ImmMap $resource
    ) {}

    View Slide

  36. $map = $this->resource
    ->filterWithKey(($k, $v) ==> $k != 'embedded')
    ->toMap();
    $hal = new HalResource($map);
    $hal->withLink(new Link(
    'self',
    new Vector([
    new LinkResource(
    '/',
    shape('type' => 'application/json'))
    ]),
    ));
    // hal+jsonରԠϥΠϒϥϦ࣮૷ྫ (Hack)

    View Slide

  37. $embedded = $this->resource->get('embedded');
    if(is_array($embedded)) {
    foreach($embedded as $row) {
    $embeddedResource = new HalResource();
    foreach($row as $key => $value) {
    if($key === 'url') {
    $embeddedResource->withLink(
    new Link('self', new Vector([new LinkResource($value)]))
    );
    continue;
    }
    $embeddedResource->addResource(strval($key), $value);
    }
    $this->vec->add($embeddedResource);
    }
    }

    View Slide

  38. // γϦΞϥΠζ͢Δͱhal+jsonରԠͷjson͕ग़ྗ͞Ε·͢(Hack)
    $hal = $hal->withEmbedded('enviroments', $this->vec);
    $serialize = new Serializer(new JsonSerializer(), $hal);
    return $serialize->toArray();

    View Slide

  39. ࣮ફ
    • ϛυϧ΢ΣΞͷ࠷ޙʹ࣮ߦ͢ΔΑ͏ʹ͢Δ

    • PSR-15४ڌͷϛυϧ΢ΣΞͰ͋Ε͹ͳΜͰ΋


    View Slide

  40. public function process(
    ServerRequestInterface $request,
    RequestHandlerInterface $handler,
    ): ResponseInterface {
    $response = $handler->handle($request);
    // ϛυϧ΢ΣΞͷޙ൒Ͱಈ͘
    $decode = json_decode($response->getBody()->getContents(), true);
    TypeAssert\matches_type_structure(
    type_structure(self::class, 'hateoasStructure'),
    $decode,
    );
    return $response;
    }

    View Slide

  41. use Psr\Log\LoggerInterface;
    use Ytake\HHContainer\Scope;
    use Ytake\HHContainer\ServiceModule;
    use Ytake\HHContainer\FactoryContainer;
    use App\Middleware\ResponseAssertMiddleware;
    final class MiddlewareServiceModule extends ServiceModule {
    public function provide(FactoryContainer $container): void {
    $container->set(
    ResponseAssertMiddleware::class,
    $container ==> new ResponseAssertMiddleware()
    );
    // container΁ͷόΠϯυྫ
    }
    }

    View Slide

  42. // route΋shapeͰෆ࣮֬͞Λͳ͘͢ʂ
    \Nazg\Http\HttpMethod::GET => ImmMap {
    '/' => shape(
    'middleware' => ImmVector {
    App\Middleware\ResponseAssertMiddleware::class,
    App\Action\IndexAction::class,
    },
    )
    },

    View Slide

  43. ·ͱΊ
    • strictҎ֎͸ͭΒ͍
    • mixed΋ͭΒ͍
    • ϚΠΫϩαʔϏεͰ౤ೖ͢ΔͳΒtype-assertΛ͓קΊ
    • inputͱoutput ৴༻͗ͯ͢͠͸͍͚ͳ͍
    • null͕ʂܕ͕ʂͱݴΘΕͨΒHackͰఏڙͯ͠Έ·͠ΐ͏


    View Slide