PHP code example of sanity / sanity-php

1. Go to this page and download the library: Download sanity/sanity-php 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/ */

    

sanity / sanity-php example snippets




use Sanity\Client as SanityClient;

$client = new SanityClient([
  'projectId' => 'your-project-id',
  'dataset' => 'your-dataset-name',
  // Whether or not to use the API CDN for queries. Default is false.
  'useCdn' => true,
  // If you are starting a new project, using the current UTC date is usually
  // a good idea. See "Specifying API version" section for more details
  'apiVersion' => '2019-01-29',
]);

$client = new SanityClient([
  'projectId' => 'your-project-id',
  'dataset' => 'your-dataset-name',
  'useCdn' => false,
  'apiVersion' => '2019-01-29',
  // Note that you cannot combine a token with the `useCdn` option set to true,
  // as authenticated requests cannot be cached
  'token' => 'sanity-auth-token',
]);

$document = $client->getDocument('someDocumentId');

$results = $client->fetch(
  '*[_type == $type][0...3]', // Query
  ['type' => 'product'] // Params (optional)
);

foreach ($product in $results) {
  echo $product['title'] . '\n';
}

$client = new SanityClient([
  // ...config...
  'useCdn' => true,
  'perspective' => 'published',
]);

$authors = $client->fetch('*[_type == "author"]');

$client = new SanityClient([
  // ...config...
  'useCdn' => false, // the `previewDrafts` perspective 

$authors = $client->fetch('*[_type == "author"]{..., "status": select(
  _originalId in path("drafts.**") => "draft",
  "published"
)}');

$doc = [
  '_type' => 'bike',
  'name'  => 'Bengler Tandem Extraordinaire',
  'seats' => 2,
];

$newDocument = $client->create($doc);
echo 'Bike was created, document ID is ' . $newDocument['_id'];

$doc = [
  '_id'   => 'my-document-id',
  '_type' => 'bike',
  'name'  => 'Amazing bike',
  'seats' => 3,
];

$newDocument = $client->createIfNotExists($doc);

$doc = [
  '_id'   => 'my-document-id',
  '_type' => 'bike',
  'name'  => 'Amazing bike',
  'seats' => 3,
];

$newDocument = $client->createOrReplace($doc);

use Sanity\Exception\BaseException;

try {
  $updatedBike = $client
    ->patch('bike-123') // Document ID to patch
    ->set(['inStock' => false]) // Shallow merge
    ->inc(['numSold' => 1]) // Increment field by count
    ->commit(); // Perform the patch and return the modified document
} catch (BaseException $error) {
  echo 'Oh no, the update failed: ';
  var_dump($error);
}

use Sanity\Exception\BaseException;

try {
  $client->delete('bike-123');
} catch (BaseException $error) {
  echo 'Delete failed: ';
  var_dump($error);
}

$namePatch = $client->patch('bike-310')->set(['name' => 'A Bike To Go']);

try {
  $client->transaction()
    ->create(['name' => 'Bengler Tandem Extraordinaire', 'seats' => 2])
    ->delete('bike-123')
    ->patch($namePatch)
    ->commit();

  echo 'A whole lot of stuff just happened!';
} catch (BaseException $error) {
  echo 'Transaction failed:';
  var_dump($error);
}

use Sanity\Patch;
use Sanity\Transaction;

// Patches:
$patch = new Patch('<documentId>');
$patch->inc(['count' => 1])->unset(['visits']);
$client->mutate($patch);

// Transactions:
$transaction = new Transaction();
$transaction
  ->create(['_id' => '123', 'name' => 'FooBike'])
  ->delete('someDocId');

$client->mutate($transaction);

$asset = $client->uploadAssetFromFile('image', '/some/path/to/image.png');
echo $asset['_id'];

$image = file_get_contents('/some/path/to/image.png');
$asset = $client->uploadAssetFromString('image', $buffer, [
    // Will be set in the `originalFilename` property on the image asset
    // The filename in the URL will still be a hash
    'filename' => 'magnificent-bridge.png'
]);
echo $asset['_id'];

$asset = $client->uploadAssetFromFile('image', '/some/path/to/image.png', [
    'extract' => ['exif', 'palette']
]);

var_dump($asset['metadata']);

$asset = $client->uploadAssetFromFile('file', '/path/to/raspberry-pi-specs.pdf', [
    // Including a mime type is not _

$image = file_get_contents('/path/to/app-release.apk');
$asset = $client->uploadAssetFromString('file', $buffer, [
    // Will be set in the `originalFilename` property on the image asset
    // The filename in the URL will still be a hash
    'filename' => 'dog-walker-pro-v1.4.33.apk',
    // Including a mime type is not _

// Create a new document with the referenced image in the "image" field:
$asset = $client->uploadAssetFromFile('image', '/some/path/to/image.png');
$document = $client->create([
    '_type' => 'blogPost',
    'image' => [
        '_type' => 'image',
        'asset' => ['_ref' => $asset['_id']]
    ]
]);
echo $document['_id'];

// Patch existing document, setting the `heroImage` field
$asset = $client->uploadAssetFromFile('image', '/some/path/to/image.png');
$updatedBike = $client
    ->patch('bike-123') // Document ID to patch
    ->set([
        'heroImage' => [
            '_type' => 'image',
            'asset' => ['_ref' => $asset['_id']]
        ]
    ])
    ->commit();

$asset = $client->uploadAssetFromFile('image', '/some/path/to/image.png');
$updatedHotel = $client
    ->patch('hotel-coconut-lounge') // Document ID to patch
    ->setIfMissing(['roomPhotos' => []]) // Ensure we have an array to append to
    ->append('roomPhotos', [
        [
            '_type' => 'image',
            '_key' => bin2hex(random_bytes(5)),
            'asset' => ['_ref' => $image['_id']]
        ]
    ])
    ->commit();

$config = $client->config();
echo $config['dataset'];

$client->config(['dataset' => 'newDataset']);

use Sanity\BlockContent;

$document = $client->getDocument('some-doc');
$article = $document['article']; // The field that contains your block content

$html = BlockContent::toHtml($article, [
    'projectId'    => 'abc123',
    'dataset'      => 'bikeshop',
    'imageOptions' => ['w' => 320, 'h' => 240]
]);

$html = BlockContent::toHtml($article, [
  'serializers' => [
    'listItem' => function ($item, $parent, $htmlBuilder) {
      return '<li class="my-list-item">' . implode('\n', $item['children']) . '</li>';
    },
    'geopoint' => function ($item) {
      $attrs = $item['attributes']
      $url = 'https://www.google.com/maps/embed/v1/place?key=someApiKey&center='
      $url .= $attrs['lat'] . ',' . $attrs['lng'];
      return '<iframe class="geomap" src="' . $url . '" allowfullscreen></iframe>'
    },
    'pet' => function ($item, $parent, $htmlBuilder) {
      return '<p class="pet">' . $htmlBuilder->escape($item['attributes']['name']) . '</p>';
    }
  ]
]);
bash
composer