/** * @param array $data * @return integer number of records that were imported */ public function importCollection($data) { if (!is_array($data)) { throw new InvalidParamException('Data must be an array.'); } // Validate /** @var RequestForm[] $requests */ $requests = []; /** @var ResponseRecord[] $responses */ $responses = []; foreach ($data as $tag => $row) { if (!preg_match('/^[a-f0-9]+$/', $tag)) { throw new InvalidParamException("Tag {$tag} must be a string and contains a-f0-9 symbols only."); } if (!isset($row['request'], $row['response'])) { throw new InvalidParamException("Row {$tag} must contains request and response."); } $request = new RequestForm(); $request->setAttributes($row['request']); if (!$request->validate()) { $errors = $request->getFirstErrors(); throw new InvalidParamException(reset($errors)); } $requests[$tag] = $request; $response = new ResponseRecord(); try { $response->status = $row['response']['status']; $response->duration = $row['response']['duration']; $response->headers = $row['response']['headers']; $response->content = $row['response']['content']; } catch (\Exception $e) { throw new InvalidParamException($e->getMessage(), $e->getCode(), $e); } $responses[$tag] = $response; } // Save $count = 0; $this->_collection = $this->readCollection(); foreach ($requests as $tag => $request) { if (!$this->exists($tag)) { $this->writeData($tag, $request->getAttributes(), get_object_vars($responses[$tag])); $this->_collection[$tag] = ['method' => $request->method, 'endpoint' => $request->endpoint, 'description' => $request->description, 'status' => $responses[$tag]->status, 'time' => time()]; $count++; } } $this->writeCollection($this->_collection); return $count; }