Skip to content

Commit

Permalink
#18 add flag to get assoc array result as json_decode offers
Browse files Browse the repository at this point in the history
  • Loading branch information
firegate666 committed Jul 27, 2014
1 parent 6eca629 commit 351e435
Showing 1 changed file with 38 additions and 3 deletions.
41 changes: 38 additions & 3 deletions src/Seld/JsonLint/JsonParser.php
Expand Up @@ -10,7 +10,6 @@
*/

namespace Seld\JsonLint;

use stdClass;

/**
Expand All @@ -30,6 +29,7 @@ class JsonParser
{
const DETECT_KEY_CONFLICTS = 1;
const ALLOW_DUPLICATE_KEYS = 2;
const ASSOC_INSTEADOF_OBJECT = 4;

private $flags;
private $stack;
Expand Down Expand Up @@ -303,6 +303,9 @@ public function parse($input, $flags = 0)
$r = $this->performAction($yyval, $yytext, $yyleng, $yylineno, $action[1], $this->vstack, $this->lstack);

if (!$r instanceof Undefined) {
if ($this->isAssocInsteadOfObject()) {
$r = $this->toArray($r);
}
return $r;
}

Expand Down Expand Up @@ -331,6 +334,26 @@ protected function parseError($str, $hash)
throw new ParsingException($str, $hash);
}

/**
* Convert object to array, deep inspection
*
* @param stdClass $object
* @return array
*/
private function toArray(stdClass $object)
{
$array = array();
foreach ($object as $key => $value) {
if ($value instanceof stdClass) {
$array[$key] = $this->toArray($value);
} else {
$array[$key] = $value;
}
}

return $array;
}

// $$ = $tokens // needs to be passed by ref?
// $ = $token
// _$ removed, useless?
Expand Down Expand Up @@ -378,12 +401,12 @@ private function performAction(stdClass $yyval, $yytext, $yyleng, $yylineno, $yy
case 17:
$yyval->token = $tokens[$len-2];
$key = $tokens[$len][0] === '' ? '_empty_' : $tokens[$len][0];
if (($this->flags & self::DETECT_KEY_CONFLICTS) && isset($tokens[$len-2]->{$key})) {
if (($this->isDetectKeyConflicts()) && isset($tokens[$len-2]->{$key})) {
$errStr = 'Parse error on line ' . ($yylineno+1) . ":\n";
$errStr .= $this->lexer->showPosition() . "\n";
$errStr .= "Duplicate key: ".$tokens[$len][0];
throw new ParsingException($errStr);
} elseif (($this->flags & self::ALLOW_DUPLICATE_KEYS) && isset($tokens[$len-2]->{$key})) {
} elseif (($this->isAllowDuplicateKeys()) && isset($tokens[$len-2]->{$key})) {
$duplicateCount = 1;
do {
$duplicateKey = $key . '.' . $duplicateCount++;
Expand All @@ -410,6 +433,18 @@ private function performAction(stdClass $yyval, $yytext, $yyleng, $yylineno, $yy
return new Undefined();
}

private function isAllowDuplicateKeys() {
return $this->flags & self::ALLOW_DUPLICATE_KEYS;
}

private function isDetectKeyConflicts() {
return $this->flags & self::DETECT_KEY_CONFLICTS;
}

private function isAssocInsteadOfObject() {
return $this->flags & self::ASSOC_INSTEADOF_OBJECT;
}

private function stringInterpolation($match)
{
switch ($match[0]) {
Expand Down

0 comments on commit 351e435

Please sign in to comment.