Inheritance: implements Neomerx\JsonApi\Contracts\Encoder\EncoderInterface
 public function serializeErrors($code, $message, $trace)
 {
     $error = new Error(null, null, null, '' . $code, $message, $trace);
     $message = Encoder::instance()->encodeError($error);
     $response = new JsonResponse($message, $code, ['content-type' => 'application/vnd.api+json']);
     return $response;
 }
示例#2
0
 /**
  * @param array $data
  */
 protected function encode($data)
 {
     $encoder = Encoder::instance($this->encoderConfig, new EncoderOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE, ''));
     $ret = $encoder->withMeta($this->getMeta())->encodeData($data) . PHP_EOL;
     // TODO add relationships
     return $ret;
 }
 /**
  * Adds support for the Server Responsibilities section of content negotiation
  * spec for json-api.
  *
  * @see http://jsonapi.org/format/#content-negotiation
  */
 public function handle(Request $request, Closure $next, MediaTypeGuard $guard = null)
 {
     //
     $guard = $guard ?? app(MediaTypeGuard::class);
     if (!$guard->validateExistingContentType($request) || !$guard->hasCorrectHeadersForData($request)) {
         $errors = (new ErrorCollection())->add(ErrorFactory::buildUnsupportedMediaType());
         $encoder = Encoder::instance([], new EncoderOptions(JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
         return new Response($encoder->encodeErrors($errors), 415, ['Content-Type' => $guard->getContentType()]);
     }
     if (!$guard->hasCorrectlySetAcceptHeader($request)) {
         $errors = (new ErrorCollection())->add(ErrorFactory::buildUnacceptable());
         $encoder = Encoder::instance([], new EncoderOptions(JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
         return new Response($encoder->encodeErrors($errors), 406, ['Content-Type' => $guard->getContentType()]);
     }
     $response = $next($request);
     $response->header('Content-Type', $guard->getContentType());
     return $response;
 }
示例#4
0
 /**
  * @inheritdoc
  */
 public function encodeIdentifiers($data, EncodingParametersInterface $parameters = null)
 {
     $data = $this->handleRelationshipStorageAndPagingData($data);
     return parent::encodeIdentifiers($data, $parameters);
 }
示例#5
0
 /**
  * @inheritdoc
  */
 public function createEncoder(ContainerInterface $container, EncoderOptions $encoderOptions = null)
 {
     $encoder = new Encoder($this, $container, $encoderOptions);
     $encoder->setLogger($this->logger);
     return $encoder;
 }
// use \Neomerx\JsonApi\Encoder;
require __DIR__ . '/../vendor/autoload.php';
class AuthorSchema extends \Neomerx\JsonApi\Schema\SchemaProvider
{
    protected $resourceType = 'people';
    public function getId($author)
    {
        /** @var Author $author */
        return $author->authorId;
    }
    public function getAttributes($author)
    {
        /** @var Author $author */
        return ['firstName' => $author->firstName, 'lastName' => $author->lastName];
    }
}
class Author
{
    public $firstName;
    public $lastName;
    function __construct($firstName, $lastName)
    {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->authorId = "{$firstName}@{$lastName}";
    }
}
$author = new \Author('Alexey', 'Kostarev');
$encoder = \Neomerx\JsonApi\Encoder\Encoder::instance(['Author' => '\\AuthorSchema'], new \Neomerx\JsonApi\Encoder\EncoderOptions(JSON_PRETTY_PRINT, 'http://flexberryJSONAPI.nevod.ru/v1'));
echo $encoder->encodeData($author) . PHP_EOL;
示例#7
0
/**
 * Services are globally registered in this file
 *
 * @globally \Phalcon\Config $config
 */
use Phalcon\Di\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Sqlite as DbAdapter;
use Neomerx\JsonApi\Encoder\Encoder;
use Neomerx\JsonApi\Encoder\EncoderOptions;
use Phalcon\JsonApi\Model\Author;
use Phalcon\JsonApi\Model\Comment;
use Phalcon\JsonApi\Model\Post;
use Phalcon\JsonApi\Model\Site;
use Phalcon\JsonApi\Schema\AuthorSchema;
use Phalcon\JsonApi\Schema\CommentSchema;
use Phalcon\JsonApi\Schema\PostSchema;
use Phalcon\JsonApi\Schema\SiteSchema;
$di = new FactoryDefault();
$di->set('config', $config);
$di->set('encoder', function ($schemas = null, EncoderOptions $options = null) {
    if (!$schemas) {
        $schemas = [Author::class => AuthorSchema::class, Comment::class => CommentSchema::class, Post::class => PostSchema::class, Site::class => SiteSchema::class];
    }
    return Encoder::instance($schemas, $options);
});
/**
 * Database connection is created based in the parameters defined in the configuration file
 */
$di->set('db', function () use($config) {
    return new DbAdapter($config->database->toArray());
});
示例#8
0
 /**
  * @param string|null $urlPrefix
  * @param integer $depth
  * @return EncoderInterface
  */
 public function getEncoder($urlPrefix = null, $depth = 512)
 {
     return Encoder::instance($this->configuration['schemas'], new EncoderOptions(JSON_PRETTY_PRINT, $urlPrefix, $depth));
 }
示例#9
0
 /**
  * Serialize view vars
  *
  * ### Special parameters
  * `_serialize` This holds the actual data to pass to the encoder
  * `_url` The base url of the api endpoint
  * `_entities` A list of entitites that are going to be mapped to Schemas
  * `_include` An array of hash paths of what should be in the 'included'
  *   section of the response. see: http://jsonapi.org/format/#fetching-includes
  *   eg: [ 'posts.author' ]
  * `_fieldsets` A hash path of fields a list of names that should be in the resultset
  *   eg: [ 'sites'  => ['name'], 'people' => ['first_name'] ]
  * `_meta` Metadata to add to the document
  * `_links' Links to add to the document
  *  this should be an array of Neomerx\JsonApi\Schema\Link objects.
  *  example:
  * ```
  * $this->set('_links', [
  *     Link::FIRST => new Link('/authors?page=1'),
  *     Link::LAST  => new Link('/authors?page=4'),
  *     Link::NEXT  => new Link('/authors?page=6'),
  *     Link::LAST  => new Link('/authors?page=9'),
  * ]);
  * ```
  *
  * @param string|null $view Name of view file to use
  * @param string|null $layout Layout to use.
  * @return string The serialized data
  * @throws MissingViewVarException when required view variable was not set
  */
 public function render($view = null, $layout = null)
 {
     $include = $fieldsets = $schemas = $links = $meta = [];
     $parameters = $serialize = $url = null;
     $jsonOptions = $this->_jsonOptions();
     if (isset($this->viewVars['_url'])) {
         $url = rtrim($this->viewVars['_url'], '/');
     }
     if (isset($this->viewVars['_entities'])) {
         $schemas = $this->_entitiesToSchema($this->viewVars['_entities']);
     } else {
         throw new MissingViewVarException(['_entities']);
     }
     if (isset($this->viewVars['_include'])) {
         $include = $this->viewVars['_include'];
     }
     if (isset($this->viewVars['_fieldsets'])) {
         $fieldsets = $this->viewVars['_fieldsets'];
     }
     if (isset($this->viewVars['_links'])) {
         $links = $this->viewVars['_links'];
     }
     if (isset($this->viewVars['_meta'])) {
         $meta = $this->viewVars['_meta'];
     }
     //        if (isset($this->viewVars['_serialize'])) {
     //            $serialize = $this->viewVars['_serialize'];
     //        }
     if (isset($this->viewVars['_serialize']) && $this->viewVars['_serialize'] !== false) {
         $serialize = $this->_dataToSerialize($this->viewVars['_serialize']);
     }
     $encoderOptions = new EncoderOptions($jsonOptions, $url);
     $encoder = Encoder::instance($schemas, $encoderOptions);
     if ($links) {
         $encoder->withLinks($links);
     }
     if ($meta) {
         if (empty($serialize)) {
             return $encoder->encodeMeta($meta);
         }
         $encoder->withMeta($meta);
     }
     $parameters = new EncodingParameters($include, $fieldsets);
     return $encoder->encodeData($serialize, $parameters);
 }
 static function jsonApiError($error_uid, $link, $status, $code, $title, $detail)
 {
     $error = new \Neomerx\JsonApi\Document\Error($error_uid, new \Neomerx\JsonApi\Schema\Link($link), $status, $code, $title, $detail, [], []);
     echo \Neomerx\JsonApi\Encoder\Encoder::instance([])->error($error) . PHP_EOL;
 }
        $user = \User::find($id);
        if ($user) {
            $user->usr_name = $name;
            $user->usr_email = $email;
            $user->save();
            $encoder = Encoder::instance([User::class => UserSchema::class], new EncoderOptions(JSON_PRETTY_PRINT));
            echo $encoder->encode($user) . PHP_EOL;
        } else {
            $app->jsonApiError('get#users', $app->request->getResourceUri(), '404', '0002', 'User not found.', 'The requested user was not found or even never existed.');
            $app->response->setStatus(404);
        }
    }
});
// DELETE#users
$app->delete('/users/:id', function ($id) use($app) {
    $id = filter_var(filter_var($id, FILTER_SANITIZE_NUMBER_INT), FILTER_VALIDATE_INT);
    if ($id === false) {
        $app->response->setStatus(400);
    } else {
        $user = \User::find($id);
        if ($user) {
            $user->delete();
            $encoder = Encoder::instance([User::class => UserSchema::class], new EncoderOptions(JSON_PRETTY_PRINT));
            echo $encoder->encode($user) . PHP_EOL;
        } else {
            $app->jsonApiError('get#users', $app->request->getResourceUri(), '404', '0002', 'User not found.', 'The requested user was not found or even never existed.');
            $app->response->setStatus(404);
        }
    }
});
$app->run();
示例#12
0
 /**
  * Get render that returns JSON API response with JSON API Error objects and specified HTTP status code.
  *
  * @param int $statusCode
  *
  * @return Closure
  */
 protected function getErrorsRender($statusCode)
 {
     /**
      * @param ErrorInterface[] $errors
      * @param EncoderOptions   $encodeOptions
      * @param array            $headers
      *
      * @return mixed
      */
     return function (array $errors, EncoderOptions $encodeOptions = null, array $headers = []) use($statusCode) {
         $extensionsClosure = $this->extensionsClosure;
         /** @var SupportedExtensionsInterface $supportedExtensions */
         $supportedExtensions = $extensionsClosure();
         $content = Encoder::instance([], $encodeOptions)->encodeErrors($errors);
         $mediaType = $this->factory->createMediaType(MediaTypeInterface::JSON_API_TYPE, MediaTypeInterface::JSON_API_SUB_TYPE);
         return $this->responses->getResponse($statusCode, $mediaType, $content, $supportedExtensions, $headers);
     };
 }
 /**
  * Returns the errors encoded in a JSON string format.
  *
  * @return string
  */
 private static function jsonError()
 {
     $encoder = Encoder::instance();
     return $encoder->encodeErrors(self::$errorsCollection);
 }
 /**
  * @param string $mediaType
  * @return $this
  */
 private function withMediaType($mediaType = MediaTypeInterface::JSON_API_MEDIA_TYPE)
 {
     $mediaType = MediaType::parse(0, $mediaType);
     $this->codecMatcher->registerEncoder($mediaType, function () {
         return Encoder::instance();
     });
     $this->codecMatcher->registerDecoder($mediaType, function () {
         return new DocumentDecoder();
     });
     return $this;
 }
 /**
  * Basic constructor.
  *
  * This will work for most situations. We need to set up Neomerx's
  * encoder so that we have it handy.
  */
 public function __construct()
 {
     //make an encoder with our configured options
     $this->encoder = Encoder::instance(\Config::get('fdisbrisk.jsonapi.classmap'), new EncoderOptions(\Config::get('fdisbrisk.jsonapi.json_opts'), \Config::get('fdisbrisk.jsonapi.api_base_url'), \Config::get('fdisbrisk.jsonapi.depth')));
 }