Code Monkey home page Code Monkey logo

prismic-client's Introduction

PHP Api Client for Prismic.io

Stand With Ukraine

Build Status codecov Psalm Type Coverage Latest Stable Version Total Downloads

This is an unofficial PHP client for the Prismic.io headless CMS. In order to keep things simple, this library only supports version 2 of the api, so you'll have to make sure to specify your repository url in the format https://my-repo.prismic.io/api/v2

There is practically zero backwards compatibility with other prismic clients so this is in no way a drop-in replacement. That said, you should find that much of it remains similar.

Features

  • Uses a PSR-18 HTTP client for communicating with the API, so there is no dependency on a particular client implementation. The library depends on you either manually providing an HTTP client or falls back on HTTPlug Discovery to figure out an already available client.
  • Optional caching. You can choose to cache using an HTTP client that can cache responses for you like this little beauty, or provide a PSR cache pool to the named constructor.
  • Helpful methods in the primary interface to retrieve next/previous paginated result sets or merge all paginated results to a single result set.
  • Predictable and consistent exceptions to help you recover gracefully from error conditions.
  • Iterable and filterable collections to represent Slices, groups and RichText making it trivial to locate particular types of content.
  • Completely separate and replaceable HTML serialisation. In fact, the content objects do not have atHtml() or asText() methods at all. There is a shipped HTML serializer which is invokable, but you might not want to use it all, instead preferring to work with your documents in your view layer directly.
  • Easily implement your own result set and your own document types, replacing the default shipped implementations. Got a 'Case Study' type? Hydrate your documents to YourModel\CaseStudy objects so that you can build a robust content model to use in your views and elsewhere.
  • Much less nullability… All collections guarantee a return type of Prismic\Fragment which you can more easily test for a specific type or for its emptiness.

Limitations

  • Only supports V2 of the api as previously mentioned
  • No support for experiments (A/B Tests) because this feature is out-of-order at Prismic itself, it didn't make sense to implement a feature that can't be used (Sad face) - that said, if A/B tests ever become a reality again in the future, it'll be top of the pile.
  • No caching out-of-the-box (Also see "Features")

Installation

Install with composer: composer require netglue/prismic-client

You will also require a PSR-18 HTTP client implementation, of which there are many, for example:

To use the curl adapter from php-http, issue a composer require php-http/curl-client

Documentation

Docs are a work in progress and are hosted in a public prismic repository (obviously!)

You can view the docs by cloning the library, cd to the source and issue a composer install followed by a composer serve. This will start up PHP's built-in server on http://127.0.0.1:8080 showing the docs.

Samples & Examples

Take a look around in the ./samples directory; that's where you’ll find the document explorer used for rendering the documentation and examples for setting up hydrating result sets, link resolver implementations and other stuff.

It's worth mentioning that the document explorer also supports previews meaning you can add http://127.0.0.1/preview as a preview target in your Prismic repository and preview live changes.

Tests

Once you have the library cloned and dependencies installed, you can run the unit tests. Smoke tests will be skipped by default, but you can run them against your own content repositories by either writing a configuration file in test/config/config.php (You'll find an example in there too) or by setting a couple of environment variables in order to run smoke tests against a single repo:

export PRISMIC_REPO="https://my-repo.prismic.io/api/v2"
export PRISMIC_TOKEN="Some access token or not"
vendor/bin/phpunit

Other Clients

The official kit can be found at prismicio/php-kit.

Another, abandoned fork of the official kit can be found at netglue/prismic-php-kit. The reason for abandoning the fork there was the desire to start from a clean slate and make use of the recent PSRs for HTTP factories and clients, completely separate the HTML serialisation process from the content model and provide more flexible ways of hydrating your content model to objects in your domain (Or not as the case may be!).

License

MIT Licensed.

prismic-client's People

Contributors

dependabot[bot] avatar github-actions[bot] avatar gsteel avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

prismic-client's Issues

Always in Preview Mode due to Prismic Toolbar Tracking Cookies

At some point prismic started setting the preview cookie to a JSON payload containing a tracking identifier anywhere you have the toolbar installed.

This meant that there is a cookie set with a value similar to {"_tracker":"SomeUUID"} whether you are logged into the dashboard or not.

The Api::inPreview() method needs to be updated to ignore the presence of the preview cookie when it only contains tracking information

Paginated Results are Unauthenticated

Attempting to retrieve the next or previous result set fails for repositories that require a token because the URIs provided in the current result set do not include the access_token parameter

"routers" parameter for queries

Apparently, you can provide a routers query parameter to the API and it will "resolve" urls for documents and links with this information on the server returning the urls in the payload.

This means that all types would possibly contain a top-level url property and url may also be present in links that have Document type.

The documentation is pretty scant:

… but it looks like you can provide router config during initialisation and then reuse the config for every request thereafter. I assume that the config will be included in the meta-data payload as default options for the forms property.

Currently, it looks like routers should be specified as a JSON array of objects, something like this:

let routers = [
    {
        "type": "my-type", // Name of document type
        "path": "/products/:range/:category/:uid", // Where ":category" is the UID of the linked category document and ":range" is the UID of the grandparent category.range document
        "resolvers": {
            "category": "parent-category", // Top-level content relationship to a "category" type where "parent-category" is the property name of "my-type"
            "range": "category.range" // "range" is a property of "category" in this example being a content-relationship to a range document.
        }
    },
    {
        "type": "blog-post",
        "path": "/:lang/blog/:uid" // :lang is the document locale ie 'en-gb'
    },
    // Not yet known whether other types/properties are feasible such as
    {
        "type": "whatever",
        "path": "/:id/:date-published/:tags" // <- Who knows?
    }
];

Investigate and implement the Custom Types API

Been waiting for this for ages, but looks like something is in beta at least:

Prismic Custom Types API

This will enable programatic CRUD of shared slices and document types and will be an invaluable development tool.

Initial thoughts:

  • Probably best implemented as a completely separate Client due to the fact that a specific token must be generated. Confusing the content api and a tool like this would be pretty crap
  • Being able to visually diff the local version and the remote version might be really handy - or, something that could be implemented in the cli tool
  • The cli tool is most likely target for consuming this feature…

Deal with BC Break in the Prismic API

Ref: #366

A new field has been added to the shape of images in the response called edit - this breaks the client because it expects the edit field to be an image view or thumbnail.

A fix is already implemented, but this edit property needs to be dealt with properly and we need new fixtures and tests for it.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Use matchDepNames instead of matchPackageNames

Pending Branch Automerge

These updates await pending status checks before automerging. Click on a checkbox to abort the branch automerge, and create a PR instead.

  • Lock file maintenance

Warning

Renovate failed to look up the following dependencies: Failed to look up packagist package psr/http-client-implementation.

Files affected: composer.json


Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

composer
composer.json
  • php ~8.1 || ~8.2 || ~8.3
  • laminas/laminas-escaper ^2.9
  • php-http/discovery ^1.18.0
  • psr/cache ^1.0.0 || ^2.0.0 || ^3.0.0
  • psr/http-client-implementation *
  • psr/http-client ^1.0
  • psr/http-factory ^1.0
  • psr/http-message ^1.0 || ^2.0
  • doctrine/coding-standard ^12.0
  • laminas/laminas-diactoros ^3.3.0
  • php-http/cache-plugin ^2.0.0
  • php-http/curl-client ^2.3.1
  • php-http/mock-client ^1.6
  • phpunit/phpunit ^10.5.9
  • psalm/plugin-phpunit ^0.19.0
  • squizlabs/php_codesniffer ^3.8.1
  • symfony/cache ^6.4.2 || ^7.0
  • vimeo/psalm ^5.20.0
github-actions
.github/workflows/continuous-integration.yml
  • actions/checkout v4.1.7
  • shivammathur/setup-php 2.31.1
  • ramsey/composer-install 3.0.0
  • codecov/codecov-action v4
  • actions/checkout v4.1.7
  • shivammathur/setup-php 2.31.1
  • ramsey/composer-install 3.0.0
.github/workflows/release-on-milestone-closed.yml

  • Check this box to trigger a request for Renovate to run again on this repository

Prismic have changed the token expiry error again

As usual, a breaking change has been made by @prismicio - When a preview token expires, the error becomes a 404 and the JSON message body is completely different.

The body now looks like this:

{
  "type":"api_security_error",
  "message":"This preview token has expired",
  "oauth_initiate":"https://something.prismic.io/auth",
  "oauth_token":"https://something.prismic.io/auth/token"
}

The PreviewTokenExpired exception needs to be updated to take this into account.

Make Query safe to serialise?

It could be very useful for queries to be serialisable. We should be able to get rid of the UriFactory usage pretty easily, and as they are immutable, queries as configuration might yield benefits for consumers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.