From bb8607eddfb6dfdcb86ef51c865277bc86f5d29d Mon Sep 17 00:00:00 2001 From: Nathan Macnamara Date: Mon, 29 Jun 2015 22:18:11 +0100 Subject: [PATCH] Add mask processor and tests --- src/Parser.php | 31 +++++++++++++++++++++++++++++++ tests/ParserTest.php | 15 +++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/Parser.php b/src/Parser.php index 24fcb61..e2ae98f 100644 --- a/src/Parser.php +++ b/src/Parser.php @@ -125,6 +125,37 @@ public function get($key = null, $default = null) return $default; } + /** + * Mask input data with a given mapping. + * + * @param array $mask + * + * @return array + */ + public function mask(array $mask) + { + $keys = array(); + foreach ($mask as $key => $value) { + $keys[] = $key . (is_array($value) ? $this->process_mask($value) : ''); + } + + return $this->only($keys); + } + + /** + * Recursive processor for processing user masks. + * + * @param array $mask + * + * @return string + */ + private function process_mask($mask) + { + foreach ($mask as $key => $value) { + return '.' . $key . (is_array($value) ? $this->process_item($value) : ''); + } + } + /** * Parse the HTTP payload data, autodetect format and return all data in array. * Override the format by providing a content type. diff --git a/tests/ParserTest.php b/tests/ParserTest.php index 3fe1fe4..4c6a00b 100644 --- a/tests/ParserTest.php +++ b/tests/ParserTest.php @@ -15,6 +15,21 @@ protected function tearDown() m::close(); } + /** @test */ + public function mask_payload() + { + $parser = m::mock('Nathanmac\Utilities\Parser\Parser') + ->shouldDeferMissing() + ->shouldAllowMockingProtectedMethods(); + + $parser->shouldReceive('getPayload') + ->andReturn('{"message": {"title": "Hello World", "body": "Some message content"}, "comments": [{ "title": "hello", "message": "hello world"}, {"title": "world", "message": "hello world"}]}'); + + $this->assertEquals(array("message" => array("title" => "Hello World")), $parser->mask(array('message' => array('title' => '*')))); + $this->assertEquals(array("comments" => array(array("title" => "hello", "message" => "hello world"), array("title" => "world", "message" => "hello world"))), $parser->mask(array('comments' => '*'))); + $this->assertEquals(array('posts' => null), $parser->mask(array('posts' => '*'))); + } + /** @test */ public function wildcards_with_simple_structure_json() {