public function parse($schema) { $data = Json::decode($schema); $document = new Document($data, $this->resolver, $this->basePath); $this->resolver->setRootDocument($document); return new Schema($document->getProperty()); }
public function testHandleNoParameter() { $response = $this->callEndpoint(array()); $data = Json::decode((string) $response->getBody()); $this->assertEquals(false, $data['success']); $this->assertEquals('PSX\\Oauth2\\Authorization\\Exception\\InvalidRequestException', $data['title']); }
public function request(Url $url, $mode, $host, $name, $header = array()) { if (empty($mode) || ($mode = self::getMode($mode)) === false) { throw new Exception('Invalid mode'); } // discover service $url = $this->discover($url); // headers if ($this->oauth !== null) { $header = Request::mergeHeader(array('Accept' => 'application/json', 'Authorization' => $this->oauth->getAuthorizationHeader($url, $this->cred->getConsumerKey(), $this->cred->getConsumerSecret(), $this->cred->getToken(), $this->cred->getTokenSecret(), 'HMAC-SHA1', 'POST')), $header); } else { $header = Request::mergeHeader(array('Accept' => 'application/json'), $header); } // body $body = array('relation.ns' => self::NS, 'relation.mode' => $mode, 'relation.host' => $host, 'relation.name' => $name); $request = new PostRequest($url, $header, $body); $response = $this->http->request($request); if ($response->getCode() == 200) { $data = Json::decode($response->getBody()); if (isset($data['success']) && $data['success'] === true) { return true; } else { $msg = isset($data['text']) ? $data['text'] : 'An error occured'; throw new Exception($msg); } } else { throw new Exception('Invalid response code ' . $response->getCode()); } }
public function getRequest($payload) { $response = Json::decode($payload); if (isset($response['repository']) && isset($response['repository']['name']) && isset($response['repository']['url'])) { $project = new Project(); $project->setName($response['repository']['name']); $project->setUrl($response['repository']['url']); if (isset($response['commits']) && is_array($response['commits'])) { foreach ($response['commits'] as $commit) { try { $revision = new Revision(); $revision->setMessage($commit['message']); $revision->setTimestamp($commit['timestamp']); $revision->setUrl($commit['url']); $revision->setAuthor($commit['author']['username']); $project->addCommit($revision); } catch (\Exception $e) { } } } return $project; } else { throw new Exception('Invalid request'); } }
public function testPost() { $body = 'grant_type=client_credentials&scope=authorization'; $response = $this->sendRequest('http://127.0.0.1/authorization/token', 'POST', ['User-Agent' => 'Fusio TestCase', 'Authorization' => 'Basic ' . base64_encode('5347307d-d801-4075-9aaa-a21a29a448c5:342cefac55939b31cd0a26733f9a4f061c0829ed87dae7caff50feaa55aff23d')], $body); $body = (string) $response->getBody(); $data = Json::decode($body); $this->assertEquals(200, $response->getStatusCode(), $body); $expireDate = strtotime('+6 hour'); $this->arrayHasKey('access_token', $data); $this->arrayHasKey('token_type', $data); $this->assertEquals('bearer', $data['token_type']); $this->arrayHasKey('expires_in', $data); $this->assertEquals(date('Y-m-d H:i', $expireDate), date('Y-m-d H:i', $data['expires_in'])); $this->arrayHasKey('scope', $data); $this->assertEquals('authorization', $data['scope']); // check whether the token was created $row = $this->connection->fetchAssoc('SELECT appId, userId, status, token, scope, expire, date FROM fusio_app_token WHERE token = :token', ['token' => $data['access_token']]); $this->assertEquals(2, $row['appId']); $this->assertEquals(2, $row['userId']); $this->assertEquals(Token::STATUS_ACTIVE, $row['status']); $this->assertEquals($data['access_token'], $row['token']); $this->assertEquals('authorization', $row['scope']); $this->assertEquals(date('Y-m-d H:i', $expireDate), date('Y-m-d H:i', strtotime($row['expire']))); $this->assertEquals(date('Y-m-d H:i'), substr($row['date'], 0, 16)); }
public function testPost() { $body = 'grant_type=client_credentials&scope=authorization'; $response = $this->sendRequest('http://127.0.0.1/backend/token', 'POST', ['User-Agent' => 'Fusio TestCase', 'Authorization' => 'Basic ' . base64_encode('Developer:3632465b3b5d1b8b4b8e56f74600da00cea92baf')], $body); $body = (string) $response->getBody(); $data = Json::decode($body); $this->assertEquals(200, $response->getStatusCode(), $body); $expireDate = strtotime('+1 hour'); $this->arrayHasKey('access_token', $data); $this->arrayHasKey('token_type', $data); $this->assertEquals('bearer', $data['token_type']); $this->arrayHasKey('expires_in', $data); $this->assertEquals(date('Y-m-d H:i', $expireDate), date('Y-m-d H:i', $data['expires_in'])); $this->arrayHasKey('scope', $data); $this->assertEquals('backend', $data['scope']); // check whether the token was created $row = $this->connection->fetchAssoc('SELECT appId, userId, status, token, scope, expire, date FROM fusio_app_token WHERE token = :token', ['token' => $data['access_token']]); $this->assertEquals(1, $row['appId']); $this->assertEquals(4, $row['userId']); $this->assertEquals(Token::STATUS_ACTIVE, $row['status']); $this->assertEquals($data['access_token'], $row['token']); $this->assertEquals('backend', $row['scope']); $this->assertEquals(date('Y-m-d H:i', $expireDate), date('Y-m-d H:i', strtotime($row['expire']))); $this->assertEquals(date('Y-m-d H:i'), substr($row['date'], 0, 16)); }
protected function unserializeData($data) { try { return Json::decode(base64_decode($data)); } catch (Exception $e) { return null; } }
public function read(MessageInterface $message) { $body = (string) $message->getBody(); if (!empty($body)) { return JsonParser::decode($body, false); } else { return null; } }
public function testWellKnownLocation() { $url = new Url($this->config['psx_url'] . '/' . $this->config['psx_dispatch'] . '.well-known/host-meta'); $request = new GetRequest($url); $response = $this->http->request($request); $this->assertEquals(200, $response->getCode()); $document = Json::decode($response->getBody()); $this->checkHostmeta($document); }
public function testGet() { $url = new Url($this->getEndpoint()); $response = $this->signedRequest('GET', $url); $this->assertEquals(200, $response->getCode()); $fields = Json::decode($response->getBody()); $this->assertEquals(true, is_array($fields)); $this->assertEquals(true, is_array($fields[0]['children'])); }
public function testDisplayExceptionNoDebug() { Environment::getService('config')->set('psx_debug', false); $response = $this->sendRequest('http://127.0.0.1/display_error', 'GET', ['Accept' => 'application/json']); $body = (string) $response->getBody(); $data = Json::decode($body); $this->assertEquals(null, $response->getStatusCode(), $body); $this->assertEquals(false, $data['success']); $this->assertEquals('foo', $data['message']); }
public function handle(Request $request, Parameters $configuration, Context $context) { // parse json $response = $this->templateParser->parse($request, $configuration, $context, $configuration->get('response')); if (!empty($response)) { $statusCode = $configuration->get('statusCode') ?: 200; return new Response($statusCode, [], Json::decode($response, false)); } else { throw new ConfigurationException('No response defined'); } }
public function testWellKnownLocation() { $url = new Url($this->config['psx_url'] . '/' . $this->config['psx_dispatch'] . '.well-known/webfinger'); $url->addParam('resource', $this->config['psx_url'] . '/' . $this->config['psx_dispatch'] . 'news'); $request = new GetRequest($url); $response = $this->http->request($request); $this->assertEquals(200, $response->getCode()); $document = Json::decode($response->getBody()); $this->assertArrayHasKey('subject', $document); $this->assertEquals($this->config['psx_url'] . '/' . $this->config['psx_dispatch'] . 'news', $document['subject']); }
public function handle(RequestInterface $request, ParametersInterface $configuration, ContextInterface $context) { // parse json $parser = $this->templateFactory->newTextParser(); $response = $parser->parse($request, $context, $configuration->get('patch')); // patch $patch = new Patch(Json::decode($response, false)); $body = $patch->patch(Transformer::toStdClass($request->getBody())); $body = Transformer::toRecord($body); return $this->processor->execute($configuration->get('action'), $request->withBody($body), $context); }
public function handle(RequestInterface $request, ParametersInterface $configuration, ContextInterface $context) { // parse json $parser = $this->templateFactory->newTextParser(); $response = $parser->parse($request, $context, $configuration->get('response')); if (!empty($response)) { $statusCode = $configuration->get('statusCode') ?: 200; return $this->response->build($statusCode, [], Json::decode($response, false)); } else { throw new ConfigurationException('No response defined'); } }
public function testGet() { $result = array(array('identity' => 'http://google.com', 'response' => array('handler' => 'openid', 'needPassword' => false)), array('identity' => '*****@*****.**', 'response' => array('handler' => 'system', 'needPassword' => true)), array('identity' => '*****@*****.**', 'response' => array('handler' => 'google', 'needPassword' => false)), array('identity' => '*****@*****.**', 'response' => array('handler' => 'yahoo', 'needPassword' => false))); foreach ($result as $row) { $url = new Url($this->getEndpoint() . '?identity=' . urlencode($row['identity'])); $request = new GetRequest($url); $response = $this->http->request($request); $this->assertEquals(200, $response->getCode()); $resp = Json::decode($response->getBody()); unset($resp['icon']); $this->assertEquals($resp, $row['response']); } }
public function testDelete() { $data = json_encode(array('id' => 1)); $response = $this->sendRequest('http://127.0.0.1/api', 'DELETE', ['Content-Type' => 'application/json'], $data); $body = Json::decode((string) $response->getBody()); $this->assertEquals(405, $response->getStatusCode()); $this->assertArrayHasKey('success', $body); $this->assertArrayHasKey('title', $body); $this->assertArrayHasKey('message', $body); $this->assertArrayHasKey('trace', $body); $this->assertArrayHasKey('context', $body); $this->assertEquals(false, $body['success']); $this->assertEquals('Method is not allowed', substr($body['message'], 0, 21)); }
public function resolve(Uri $uri, Document $source, RefResolver $resolver) { $name = ltrim($uri->getPath(), '/'); $row = $this->connection->fetchAssoc('SELECT name, source FROM fusio_schema WHERE name LIKE :name', array('name' => $name)); if (!empty($row)) { $data = Json::decode($row['source']); if (is_array($data)) { $document = new Document($data, $resolver, null, $uri); return $document; } else { throw new RuntimeException(sprintf('Schema %s must be an object', $row['name'])); } } else { throw new RuntimeException('Invalid schema reference ' . $name); } }
public function resolve(Uri $uri, Document $source, RefResolver $resolver) { if (!$uri->isAbsolute()) { $uri = UriResolver::resolve($source->getBaseUri(), $uri); } $request = new GetRequest($uri, array('Accept' => 'application/schema+json')); $response = $this->httpClient->request($request); if ($response->getStatusCode() == 200) { $schema = (string) $response->getBody(); $data = Json::decode($schema); $document = new Document($data, $resolver, null, $uri); return $document; } else { throw new RuntimeException('Could not load external schema ' . $uri->toString() . ' received ' . $response->getStatusCode()); } }
public function testExecute() { $memory = new Output\Memory(); $output = new Output\Composite(array($memory, new Output\Logger(Environment::getService('logger')))); Environment::getContainer()->set('command_output', $output); $response = $this->sendRequest('http://127.0.0.1/command?command=' . urlencode('PSX\\Command\\Foo\\Command\\FooCommand'), 'POST', ['Content-Type' => 'application/json', 'Accept' => 'application/json'], '{"foo": "bar"}'); $data = Json::decode((string) $response->getBody()); $messages = $memory->getMessages(); $this->assertArrayHasKey('output', $data); $this->assertEquals(2, count($messages)); $lines = explode("\n", trim($data['output'])); foreach ($lines as $key => $line) { $this->assertArrayHasKey($key, $messages); $this->assertContains(trim($messages[$key]), $line); } }
public function resolve(Uri $uri, Document $source, RefResolver $resolver) { if ($source->isRemote()) { throw new RuntimeException('Can not resolve file scheme from remote source'); } $path = str_replace('/', DIRECTORY_SEPARATOR, ltrim($uri->getPath(), '/')); $path = $source->getBasePath() !== null ? $source->getBasePath() . DIRECTORY_SEPARATOR . $path : $path; if (is_file($path)) { $basePath = pathinfo($path, PATHINFO_DIRNAME); $schema = file_get_contents($path); $data = Json::decode($schema); $document = new Document($data, $resolver, $basePath, $uri); return $document; } else { throw new RuntimeException('Could not load external schema ' . $path); } }
public function parse($file) { $definition = Json::decode(file_get_contents($file), false); $instructions = array(); if (!empty($definition)) { // get action class if (isset($definition->actionClass) && is_array($definition->actionClass)) { foreach ($definition->actionClass as $actionClass) { $instructions[] = new Instruction\ActionClass($actionClass); } } // get connection class if (isset($definition->connectionClass) && is_array($definition->connectionClass)) { foreach ($definition->connectionClass as $connectionClass) { $instructions[] = new Instruction\ConnectionClass($connectionClass); } } // get connection if (isset($definition->connection) && is_array($definition->connection)) { foreach ($definition->connection as $connection) { $instructions[] = new Instruction\Connection($connection); } } // get schema if (isset($definition->schema) && is_array($definition->schema)) { foreach ($definition->schema as $schema) { $instructions[] = new Instruction\Schema($schema); } } // get action if (isset($definition->action) && is_array($definition->action)) { foreach ($definition->action as $action) { $instructions[] = new Instruction\Action($action); } } // get routes if (isset($definition->routes) && is_array($definition->routes)) { foreach ($definition->routes as $route) { $instructions[] = new Instruction\Route($route); } } } return $instructions; }
protected function execute(InputInterface $input, OutputInterface $output) { $table = $this->tableManager->getTable('Phpsx\\Website\\Table\\Release'); $url = sprintf('%s/repos/%s/%s/releases', $this->config['git_api'], $this->config['git_owner'], $this->config['git_repo']); $request = new GetRequest($url, ['Accept' => 'application/vnd.github.v3+json', 'User-Agent' => 'PSX-Website-Updater (https://github.com/k42b3)']); $response = $this->http->request($request); if ($response->getStatusCode() == 200) { $count = 0; $releases = Json::decode((string) $response->getBody()); foreach ($releases as $release) { if ($release['draft'] === false) { $row = $table->getOneById($release['id']); if (!$row instanceof RecordInterface) { $asset = $this->getAsset($release); $table->create(['id' => $release['id'], 'tagName' => $release['tag_name'], 'htmlUrl' => $release['html_url'], 'publishedAt' => new DateTime($release['published_at']), 'authorName' => $release['author']['login'], 'authorUri' => $release['author']['html_url'], 'body' => $release['body'], 'assetName' => isset($asset['name']) ? $asset['name'] : null, 'assetUrl' => isset($asset['browser_download_url']) ? $asset['browser_download_url'] : null, 'assetSize' => isset($asset['size']) ? $asset['size'] : null, 'assetMime' => isset($asset['content_type']) ? $asset['content_type'] : null]); $count++; } } } $output->writeln(sprintf('Inserted %s release/s', $count)); } else { $output->writeln(sprintf('Received an status code %s', $response->getStatusCode())); } }
public function testGet() { $url = new Url($this->getEndpoint()); $url->addParam('format', 'jas'); $response = $this->signedRequest('GET', $url); $this->assertEquals(200, $response->getCode()); // check result $result = Json::decode($response->getBody()); $this->assertArrayHasKey('itemsPerPage', $result, $response->getBody()); $this->assertArrayHasKey('startIndex', $result, $response->getBody()); $this->assertArrayHasKey('items', $result, $response->getBody()); $this->assertEquals(true, count($result['items']) > 0); foreach ($result['items'] as $activity) { $this->assertArrayHasKey('actor', $activity); $this->assertArrayHasKey('object', $activity); $this->assertArrayHasKey('verb', $activity); } // try to create activitystream object $reader = new Reader\Json(); $result = $reader->read($response); $collection = new Collection(); $collection->import($result); $this->assertInstanceOf('PSX\\ActivityStream\\Collection', $collection); }
/** * Method wich tries to request an jrd document from the given url. Used * also in the webfinger class therefore it is here static * * @return PSX\Hostmeta\Document */ public static function requestJrd(Http $http, Url $url) { $request = new GetRequest($url, array('Accept' => 'application/jrd+json', 'User-Agent' => __CLASS__ . ' ' . Base::VERSION)); $request->setFollowLocation(true); $response = $http->request($request); if ($response->getStatusCode() == 200) { $contentType = $response->getHeader('Content-Type'); if (strpos($contentType, 'application/jrd+json') !== false || strpos($contentType, 'application/json') !== false) { $jrd = new Jrd(); $jrd->import(Json::decode($response->getBody())); return $jrd; } else { if (strpos($contentType, 'application/xrd+xml') !== false || strpos($contentType, 'application/xml') !== false) { $xrd = new Xrd(); $xrd->import(simplexml_load_string((string) $response->getBody())); return $xrd; } else { throw new Exception('Received unknown content type'); } } } else { throw new Exception('Invalid response code ' . $response->getStatusCode() . ' from ' . strval($url)); } }
public function testFormDelete() { $url = new Url($this->getEndpoint() . '/form?method=delete&id=1'); $response = $this->signedRequest('GET', $url); $this->assertEquals(200, $response->getCode()); $data = Json::decode($response->getBody()); $this->assertEquals(true, is_array($data)); $this->assertEquals('form', $data['class']); $this->assertEquals('DELETE', $data['method']); }
protected function request(array $header, $data) { $request = new PostRequest($this->url, $header, $data); $response = $this->http->request($request); if ($response->getStatusCode() == 200) { // import data return $this->importer->import($this->createAccessToken(), $response); } else { $resp = Json::decode($response->getBody()); self::throwErrorException($resp); } }
public function callback($code, $state, Closure $callback) { $params = $this->store->load('openid_connect_request'); if (empty($params)) { throw new Exception('Request was not initialized'); } if (empty($state)) { throw new Exception('State parameter not set'); } if ($params->getState() != $state) { throw new Exception('Invalid state'); } $auth = new AuthorizationCode($this->http, $this->creds->getAccessTokenUrl()); $auth->setClientPassword($this->creds->getClientId(), $this->creds->getClientSecret(), AuthorizationAbstract::AUTH_POST); $auth->setAccessTokenClass('PSX\\OpenId\\Connect\\AccessToken'); $token = $auth->getAccessToken($code, $params->getRedirectUri()); $webToken = $token->getIdToken(); if ($webToken instanceof WebToken) { $claim = Json::decode($webToken->getPayload()); $callback($claim); } else { throw new Exception('No id token given'); } }
public function testDeleteUnknownVersion() { $data = json_encode(array('id' => 1)); $response = $this->sendRequest('http://127.0.0.1/api', 'DELETE', ['Accept' => 'application/vnd.psx.v4+json', 'Content-Type' => 'application/json'], $data); $body = Json::decode((string) $response->getBody()); $this->assertEquals(406, $response->getStatusCode()); $this->assertArrayHasKey('success', $body); $this->assertArrayHasKey('title', $body); $this->assertArrayHasKey('message', $body); $this->assertArrayHasKey('trace', $body); $this->assertArrayHasKey('context', $body); $this->assertEquals(false, $body['success']); $this->assertEquals('Version is not available', substr($body['message'], 0, 24)); }
protected function assertNegativeResponse(Response $response) { //$this->assertEquals(200, $response->getCode(), $response->getBody()); $resp = Json::decode($response->getBody()); $this->assertEquals(true, isset($resp['text']), $response->getBody()); $this->assertEquals(true, isset($resp['success']), $response->getBody()); $this->assertEquals(false, $resp['success'], $response->getBody()); }