PHP code example of contentstack / utils

1. Go to this page and download the library: Download contentstack/utils library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

contentstack / utils example snippets


  

declare(strict_types=1);  

namespace Sample\App;  
  
use Contentstack\Utils\Resource\EntryEmbedable;  
use Contentstack\Utils\Resource\RenderableInterface;  
use Contentstack\Utils\Resource\EmbeddedObject;  
use Contentstack\Utils\Model\Option;  
use Contentstack\Utils\Model\Metadata;  
use Contentstack\Utils\Enum\StyleType;
use Contentstack\Utils\Enum\NodeType;
use Contentstack\Utils\Enum\MarkType;

class  CustomOption  extends  Option {  
	function renderMark(MarkType $markType, string $text): string 
    {
        switch ($markType)
        {
            case MarkType::get(MarkType::BOLD):
                return "<b>".$text."</b>";
            default:
                return parent::renderMark($markType, $text);
        }
    }
    function renderNode(string $nodeType, object $node, string $innerHtml): string 
    {
        switch ($nodeType)
        {
            case "p":
                return "<p class='class-id'>".$innerHtml."</p>";
            case "h1":
                return "<h1 class='class-id'>".$innerHtml."</h1>";
            default:
                return parent::renderNode($nodeType, $node, $innerHtml);
        }
    }
	function renderOptions(array $embeddedObject, Metadata $metadata): string  
	{  
		switch ($metadata->getStyleType()) {  
			case StyleType::get(StyleType::BLOCK):  
				if ($metadata->contentTypeUID === 'product') {  
					return  "<div>  
							<h2 >".$embeddedObject["title"]."</h2>  
							<img src=".$embeddedObject["product_image"]["url"]. "alt=".$embeddedObject["product_image"]["title"]."/>  
							<p>".$embeddedObject["price"]."</p>  
							</div>"  
				}  
			case StyleType::get(StyleType::INLINE):  
				return  "<span><b>".$embeddedObject["title"]."</b> -".$embeddedObject["description"]."</span>";  
			case StyleType::get(StyleType::LINK):  
				return  "<a href=".$metadata->getAttribute("href")->value  
.">".$metadata->getText()."</a>"  
			case StyleType::get(StyleType::DISPLAY):  
				return  "<img src=".$metadata->getAttribute("src")->value." alt='".$metadata->getAttribute("alt")->value." />";  
			case StyleType::get(StyleType::DOWNLOAD):  
				return  "<a href=".$metadata->getAttribute("href")->value  
.">".$metadata->getText()."</a>"  
		}  
        return parent::renderOptions($embeddedObject, $metadata);
	}  
}

use Contentstack\Contentstack;  
use Contentstack\Utils\Model\Option;  
  
$stack = Contentstack::Stack('<API_KEY>', '<ENVIRONMENT_SPECIFIC_DELIVERY_TOKEN>', '<ENVIRONMENT>');  
$entry = $stack->ContentType('<CONTENT_TYPE_UID>')->Entry('<ENTRY_UID>')->

$rendered_rich_text = Contentstack.renderContent($entry['rte_field_uid'], new CustomOption($entry));

use Contentstack\Contentstack;  
use Contentstack\Utils\Model\Option;  
  
$stack = Contentstack::Stack('<API_KEY>', '<ENVIRONMENT_SPECIFIC_DELIVERY_TOKEN>', '<ENVIRONMENT>');  
$entry = $stack->ContentType('<CONTENT_TYPE_UID>')->Entry('<ENTRY_UID>')->

$rendered_rich_text = Contentstack.jsonToHtml($entry['rte_field_uid'], new CustomOption($entry));

use Contentstack\Contentstack;  
use Contentstack\Utils\Model\Option;  
  
$stack = Contentstack::Stack('<API_KEY>', '<ENVIRONMENT_SPECIFIC_DELIVERY_TOKEN>', '<ENVIRONMENT>');  
$result = $stack->ContentType('<CONTENT_TYPE_UID>')->Query()->toJSON()->

use Contentstack\Contentstack;  
use Contentstack\Utils\Model\Option;  
  
$stack = Contentstack::Stack('<API_KEY>', '<ENVIRONMENT_SPECIFIC_DELIVERY_TOKEN>', '<ENVIRONMENT>');  
$result = $stack->ContentType('<CONTENT_TYPE_UID>')->Query()->toJSON()->

use Contentstack\Utils\GQL;
use Contentstack\Utils\Model\Option;  
// GQL fetch API
... 
	$render_html_text = GQL::jsonToHtml($entry->rich_text_content,, new Option());
...

use Contentstack\Utils\Endpoint;
use Contentstack\Utils\Utils;

Endpoint::getContentstackEndpoint(string $region, string $service, bool $omitHttps): string|array
Utils::getContentstackEndpoint(string $region, string $service, bool $omitHttps): string|array

use Contentstack\Utils\Endpoint;

// AWS North America — Content Delivery
$url = Endpoint::getContentstackEndpoint('na', 'contentDelivery');
// → "https://cdn.contentstack.io"

// AWS Europe — Content Management
$url = Endpoint::getContentstackEndpoint('eu', 'contentManagement');
// → "https://eu-api.contentstack.com"

// Azure North America — GraphQL Delivery
$url = Endpoint::getContentstackEndpoint('azure-na', 'graphqlDelivery');
// → "https://azure-na-graphql.contentstack.com"

// GCP Europe — Auth
$url = Endpoint::getContentstackEndpoint('gcp-eu', 'auth');
// → "https://gcp-eu-auth-api.contentstack.com"

// All of these return the same NA content delivery URL
Endpoint::getContentstackEndpoint('us',     'contentDelivery'); // → https://cdn.contentstack.io
Endpoint::getContentstackEndpoint('na',     'contentDelivery'); // → https://cdn.contentstack.io
Endpoint::getContentstackEndpoint('aws-na', 'contentDelivery'); // → https://cdn.contentstack.io
Endpoint::getContentstackEndpoint('AWS_NA', 'contentDelivery'); // → https://cdn.contentstack.io

$host = Endpoint::getContentstackEndpoint('eu', 'contentDelivery', true);
// → "eu-cdn.contentstack.com"

$endpoints = Endpoint::getContentstackEndpoint('au');
// → [
//     'contentDelivery'    => 'https://au-cdn.contentstack.com',
//     'contentManagement'  => 'https://au-api.contentstack.com',
//     'graphqlDelivery'    => 'https://au-graphql.contentstack.com',
//     'auth'               => 'https://au-auth-api.contentstack.com',
//     ...17 more keys
//   ]

// With omitHttps
$hosts = Endpoint::getContentstackEndpoint('au', '', true);
// → [
//     'contentDelivery'   => 'au-cdn.contentstack.com',
//     'contentManagement' => 'au-api.contentstack.com',
//     ...
//   ]

use Contentstack\Utils\Utils;

$url = Utils::getContentstackEndpoint('gcp-na', 'contentDelivery');
// → "https://gcp-na-cdn.contentstack.com"

use Contentstack\Contentstack;
use Contentstack\Utils\Endpoint;

$region = 'eu'; // change this one value to switch regions

// Resolve the content delivery host for the chosen region
$host = Endpoint::getContentstackEndpoint($region, 'contentDelivery', true);
// → "eu-cdn.contentstack.com"

// Initialise the delivery SDK
$stack = Contentstack::Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
$stack->setHost($host);

// Fetch entries — all requests now go to the EU CDN
$result = $stack->ContentType('<CONTENT_TYPE_UID>')->Query()->toJSON()->find();

$regions = ['na', 'eu', 'au', 'azure-na', 'azure-eu', 'gcp-na', 'gcp-eu'];

foreach ($regions as $region) {
    $host  = Endpoint::getContentstackEndpoint($region, 'contentDelivery', true);
    $stack = Contentstack::Stack('<API_KEY>', '<DELIVERY_TOKEN>', '<ENVIRONMENT>');
    $stack->setHost($host);

    $result = $stack->ContentType('<CONTENT_TYPE_UID>')->Query()->toJSON()->find();
    echo "{$region}: " . count($result[0]) . " entries\n";
}

use Contentstack\Utils\Endpoint;

// Empty region
try {
    Endpoint::getContentstackEndpoint('');
} catch (\InvalidArgumentException $e) {
    echo $e->getMessage();
    // → "Empty region provided. Please put valid region."
}

// Unknown region
try {
    Endpoint::getContentstackEndpoint('unknown-region', 'contentDelivery');
} catch (\InvalidArgumentException $e) {
    echo $e->getMessage();
    // → "Invalid region: unknown-region"
}

// Unknown service
try {
    Endpoint::getContentstackEndpoint('na', 'unknownService');
} catch (\InvalidArgumentException $e) {
    echo $e->getMessage();
    // → "Service "unknownService" not found for region "na""
}

// regions.json missing and no network access
try {
    Endpoint::getContentstackEndpoint('na', 'contentDelivery');
} catch (\RuntimeException $e) {
    echo $e->getMessage();
    // → "contentstack/utils: regions.json not found and could not be downloaded.
    //    Run "composer install" or "composer refresh-regions" and ensure network access."
}