Example #1
0
 public function validate()
 {
     $result = \Jsv4::validate(json_decode($this->getJSONString()), json_decode(static::SCHEMA));
     if ($result->valid == true) {
         return true;
     } else {
         throw new ModelFormatException('invalid JSON format for ' . get_class($this) . ': ' . $result->errors[0]->dataPath . ": " . $result->errors[0]->message);
     }
 }
Example #2
0
 public function validate($data)
 {
     if (empty($data)) {
         $objData = new \stdClass();
     } else {
         $objData = json_decode(json_encode($data));
     }
     $result = \Jsv4::coerce($objData, $this->schemaObj);
     if (!$result->valid) {
         throw new \Exception($result->errors[0]->message, 400);
     }
     return $result->value;
 }
Example #3
0
function runJsonTest($key, $test)
{
    global $totalTestCount;
    global $failedTests;
    $totalTestCount++;
    try {
        if ($test->method == "validate") {
            $result = Jsv4::validate($test->data, $test->schema);
        } else {
            if ($test->method == "isValid") {
                $result = Jsv4::isValid($test->data, $test->schema);
            } else {
                if ($test->method == "coerce") {
                    $result = Jsv4::coerce($test->data, $test->schema);
                } else {
                    $failedTests[$key][] = "Unknown method: {$test->method}";
                    return;
                }
            }
        }
        if (is_object($test->result)) {
            foreach ($test->result as $path => $expectedValue) {
                $actualValue = pointerGet($result, $path, TRUE);
                if (!recursiveEqual($actualValue, $expectedValue)) {
                    $failedTests[$key][] = "{$path} does not match - should be:\n    " . json_encode($expectedValue) . "\nwas:\n    " . json_encode($actualValue);
                }
            }
        } else {
            if (!recursiveEqual($test->result, $result)) {
                $failedTests[$key][] = "{$path} does not match - should be:\n    " . json_encode($test->result) . "\nwas:\n    " . json_encode($result);
            }
        }
    } catch (Exception $e) {
        $failedTests[$key][] = $e->getMessage();
        $failedTests[$key][] .= "    " . str_replace("\n", "\n    ", $e->getTraceAsString());
    }
}
Example #4
0
 public static function schemaSearch($configName, $schemaObj, $orderBy = NULL, $limit = NULL)
 {
     $config = self::$mysqlConfigs[$configName];
     $search = new JsonStoreSearch($config, $schemaObj);
     $sql = $search->mysqlQuery(NULL, $orderBy, $limit);
     $results = self::mysqlQuery($sql);
     foreach ($results as $index => $item) {
         $results[$index] = self::loadObject($item, $config, TRUE);
     }
     self::executePending();
     if (strpos($sql, JsonStoreSearch::$INCOMPLETE_TAG)) {
         if (self::$problemSchemasFile) {
             $data = date('r') . "\n\nConfig: {$configName}\n\nSchema:\n" . json_encode($schemaObj) . "\n\nQuery:\n" . $sql;
             file_put_contents(self::$problemSchemasFile, $data);
         }
         $newResults = array();
         foreach ($results as $item) {
             $validation = Jsv4::validate($item, $schemaObj);
             if ($validation->valid) {
                 $newResults[] = $item;
             }
         }
         $results = $newResults;
     }
     return $results;
 }
 /**
  * parse a nodelist-format
  *
  * @param string $comName Name of community
  * @param string $comUrl url to fetch data from
  */
 private function _getFromNodelist($comName, $comUrl)
 {
     $result = simpleCachedCurl($comUrl, $this->_curlCacheTime, $this->_debug);
     $responseObject = json_decode($result);
     if (!$responseObject) {
         $this->_addCommunityMessage($comUrl . ' returns no valid json');
         return false;
     }
     $schemaVersion = $responseObject->version;
     $this->_addCommunityMessage($comUrl . ' has schema version ' . $schemaVersion);
     // arguably we shouldn't load a file from disk based on raw user input...
     // it would be more efficient to keep all schema strings in memory anway
     $schemaString = file_get_contents(__DIR__ . '/../schema/nodelist-schema-' . $schemaVersion . '.json');
     $schema = json_decode($schemaString);
     $validationResult = Jsv4::validate($responseObject, $schema);
     if (!$validationResult) {
         $this->_addCommunityMessage($comUrl . ' is no valid nodelist');
         return false;
     }
     if (empty($responseObject->nodes)) {
         $this->_addCommunityMessage($comUrl . ' contains no nodes');
         return false;
     }
     $routers = $responseObject->nodes;
     // add community to the list of nodelist-communities
     // this will make us skipp further search for other formats
     $this->_nodelistCommunities[] = $comName;
     $counter = 0;
     $skipped = 0;
     $duplicates = 0;
     $added = 0;
     $dead = 0;
     foreach ($routers as $router) {
         $counter++;
         // apparently the field could be named lon or long (even though that would not be sticking to the schema correctly)
         $nodeLon = null;
         if (!empty($router->position->lon)) {
             $nodeLon = $router->position->lon;
         } else {
             if (!empty($router->position->long)) {
                 $nodeLon = $router->position->long;
             }
         }
         $nodeHasLocation = !empty($router->position->lat) && !empty($nodeLon);
         if (!$nodeHasLocation) {
             $skipped++;
             continue;
         }
         $thisRouter = array('id' => (string) $router->id, 'lat' => (string) $router->position->lat, 'long' => (string) $nodeLon, 'name' => (string) $router->name, 'community' => $comName, 'status' => 'unknown', 'clients' => 0);
         $nodeHasAltitude = !empty($router->position->alt);
         if ($nodeHasAltitude) {
             $thisRouter['alt'] = $router->position->alt;
         }
         if (isset($router->status)) {
             if (isset($router->status->clients)) {
                 $thisRouter['clients'] = (int) $router->status->clients;
             }
             if (isset($router->status->online)) {
                 $thisRouter['status'] = (bool) $router->status->online ? 'online' : 'offline';
             }
         }
         if ($thisRouter['status'] == 'offline') {
             $isDead = false;
             if (empty($router->status->lastcontact)) {
                 $isDead = true;
             } else {
                 $date = date_create((string) $router->status->lastcontact);
                 // was online in last days? ?
                 $isDead = time() - $date->getTimestamp() > 60 * 60 * 24 * $this->_maxAge;
             }
             if ($isDead) {
                 $dead++;
                 continue;
             }
         }
         // add to routerlist for later use in JS
         if ($this->_addOrForget($thisRouter)) {
             $added++;
         } else {
             $duplicates++;
         }
     }
     $this->_addCommunityMessage('parsing done. ' . $counter . ' nodes found, ' . $added . ' added, ' . $skipped . ' skipped, ' . $duplicates . ' duplicates, ' . $dead . ' dead');
     return true;
 }
Example #6
0
 /**
  * parse a nodelist-format
  *
  * @param string $comName Name of community
  * @param string $comUrl url to fetch data from
  */
 private function _getFromNodelist($comName, $comUrl)
 {
     $result = simpleCachedCurl($comUrl, $this->_curlCacheTime, $this->_debug);
     $responseObject = json_decode($result);
     if (!$responseObject) {
         $this->_addCommunityMessage($comUrl . ' returns no valid json');
         return false;
     }
     $schemaString = file_get_contents(__DIR__ . '/../schema/nodelist-schema-1.0.0.json');
     $schema = json_decode($schemaString);
     $validationResult = Jsv4::validate($responseObject, $schema);
     if (!$validationResult) {
         $this->_addCommunityMessage($comUrl . ' is no valid nodelist');
         return false;
     }
     if (empty($responseObject->nodes)) {
         $this->_addCommunityMessage($comUrl . ' contains no nodes');
         return false;
     }
     $routers = $responseObject->nodes;
     // add community to the list of nodelist-communities
     // this will make us skipp further search for other formats
     $this->_nodelistCommunities[] = $comName;
     $counter = 0;
     $skipped = 0;
     $duplicates = 0;
     $added = 0;
     $dead = 0;
     foreach ($routers as $router) {
         $counter++;
         if (empty($router->position->lat) || empty($router->position->lon) && empty($router->position->long)) {
             // router has no location
             $skipped++;
             continue;
         }
         $thisRouter = array('id' => (string) $router->id, 'lat' => (string) $router->position->lat, 'long' => !empty($router->position->lon) ? (string) $router->position->lon : (string) $router->position->long, 'name' => (string) $router->name, 'community' => $comName, 'status' => 'unknown', 'clients' => 0);
         if (isset($router->status)) {
             if (isset($router->status->clients)) {
                 $thisRouter['clients'] = (int) $router->status->clients;
             }
             if (isset($router->status->online)) {
                 $thisRouter['status'] = (bool) $router->status->online ? 'online' : 'offline';
             }
         }
         if ($thisRouter['status'] == 'offline') {
             $isDead = false;
             if (empty($router->status->lastcontact)) {
                 $isDead = true;
             } else {
                 $date = date_create((string) $router->status->lastcontact);
                 // was online in last days? ?
                 $isDead = time() - $date->getTimestamp() > 60 * 60 * 24 * $this->_maxAge;
             }
             if ($isDead) {
                 $dead++;
                 continue;
             }
         }
         // add to routerlist for later use in JS
         if ($this->_addOrForget($thisRouter)) {
             $added++;
         } else {
             $duplicates++;
         }
     }
     $this->_addCommunityMessage('parsing done. ' . $counter . ' nodes found, ' . $added . ' added, ' . $skipped . ' skipped, ' . $duplicates . ' duplicates, ' . $dead . ' dead');
     return true;
 }
Example #7
0
 /**
  * Examines the contents of the `export` property, which is an object of the following form:
  * { type: "N", settings: {} }. "N" is the folder name of the desired Export Type (see
  * /plugins/axportTypes); `settings` is an object containing whatever settings have been specified by that
  * Export Type's schema.json file.
  * @param $json
  * @return array
  */
 private function validateExportTypeSettings($json)
 {
     // first, find the Export Type and check it's valid
     if (!property_exists($json->export, "type")) {
         return array("error" => ErrorCodes::API_INVALID_JSON_CONTENT, "error_details" => "Missing `type` property in the `export` object");
     }
     $exportTypeFolders = ExportTypePluginHelper::getExportTypeFolders();
     $exportType = $json->export->type;
     if (!in_array($exportType, $exportTypeFolders)) {
         return array("error" => ErrorCodes::API_UNKNOWN_EXPORT_TYPE, "error_details" => "invalid `type` attribute of the `export` object: `{$exportType}`");
     }
     $exportType = ExportTypePluginHelper::getExportTypeByFolder($exportType);
     $schema = json_decode($exportType->getSchema());
     // only validate if there's actually a schema for this Export Type
     if ($schema !== null) {
         $json = property_exists($json->export, "settings") ? $json->export->settings : json_decode("{}");
         // verify the settings for this data type
         $result = Jsv4::validate($json, $schema);
         if (!$result->valid) {
             return array("error" => ErrorCodes::API_INVALID_EXPORT_TYPE_JSON, "error_details" => "Invalid Export Type JSON `settings` content passed", "path" => $result->errors[0]->dataPath, "validation_error" => $result->errors[0]->message);
         }
     }
 }
/**
 * Tests the JSON crossword data
 *
 * @param string $json Raw json string.
 * @param array(string) &$msg By reference. List of debug error messages.
 *
 * @return mixed {
 *     Crossword metadata or false if not valid.
 *
 *     @type string $name Crossword name.
 *     @type int $name Difficulty level.
 * }
 */
function crw_verify_json($json, &$msg)
{
    $easy_directions = array('right', 'down');
    include 'schema/jsv4.php';
    include 'schema/schema-store.php';
    include 'l10n.php';
    //schema loading
    $raw_schema = json_decode(file_get_contents(CRW_PLUGIN_DIR . 'schema/schema.json'));
    $url = $raw_schema->id;
    $store = new SchemaStore();
    $store->add($url, $raw_schema);
    $schema = $store->get($url);
    $locale_data = crw_get_locale_data();
    $schema->definitions->word->properties->letter->pattern = $locale_data["letterRegEx"];
    // json string decoding
    try {
        $crossword = json_decode($json);
    } catch (Exception $e) {
        $msg = array('decode exception');
        return false;
    }
    // schema validation
    $answer = Jsv4::validate($crossword, $schema);
    if (!$answer->valid) {
        $msg = array('schema error:');
        foreach ($answer->errors as $err) {
            array_push($msg, $err->dataPath . " " . $err->message);
        }
        return false;
    }
    // verify width and height are consistent
    if ($crossword->size->height !== count($crossword->table)) {
        $msg = array('height inconsistency');
        return false;
    }
    foreach ($crossword->table as $line) {
        if ($crossword->size->width !== count($line)) {
            $msg = array('width inconsistency');
            return false;
        }
    }
    foreach ($crossword->words as $key => $word) {
        // verify keys match ID content
        if ((int) $key !== $word->ID) {
            $msg = array('word key inconsistency');
            return false;
        }
        // verify word lengths are consistent with start/stop positions
        $computed_length = max(abs($word->stop->x - $word->start->x), abs($word->stop->y - $word->start->y)) + 1;
        if ($computed_length !== count($word->fields)) {
            $msg = array('word length inconsistency');
            return false;
        }
        // verify direction restriction by level
        if (!($crossword->level & 1) && !in_array($word->direction, $easy_directions)) {
            $msg = array('word level and direction inconsistency');
            return false;
        }
        // even more you could test:
        // direction fits start/stop position
        // each letter is in the right position
    }
    return array('name' => $crossword->name, 'level' => $crossword->level);
}
Example #9
0
#!/usr/bin/php5
<?php 
require __DIR__ . "/vendor/autoload.php";
$schemaStore = new SchemaStore();
foreach (glob(__DIR__ . "/../resources/openeyes/schema/*.json") as $schemaPath) {
    $schemaStore->add("oe:" . str_replace(".json", "", basename($schemaPath)), json_decode(file_get_contents($schemaPath)));
}
$testVal = (object) array("numerator" => 6, "denominator" => 6);
var_dump(Jsv4::validate($testVal, $schemaStore->get("oe:VisualAcuityValueSnellenMetre")));