1<?php 2 3$cluster = new \Couchbase\Cluster('couchbase://192.168.1.194'); 4$cluster->authenticateAs('Administrator', 'password'); 5 6$bucket = $cluster->openBucket('travel-sample'); 7 8// Add key-value pairs to hotel_10138, representing traveller-Ids and associated discount percentages 9$bucket->mutateIn('hotel_10138') 10 ->upsert('discounts.jsmith123', '20', ['xattr' => true, 'createPath' => true]) 11 ->upsert('discounts.pjones356', '30', ['xattr' => true, 'createPath' => true]) 12 // The following lines, "insert" and "remove", simply demonstrate insertion and 13 // removal of the same path and value 14 ->insert('discounts.jbrown789', '25', ['xattr' => true, 'createPath' => true]) 15 ->remove('discounts.jbrown789', ['xattr' => true]) 16 ->execute(); 17 18// Add key - value pairs to hotel_10142, again representing traveller - Ids and associated discount percentages 19$bucket->mutateIn('hotel_10142') 20 ->upsert('discounts.jsmith123', '15', ['xattr' => true, 'createPath' => true]) 21 ->upsert('discounts.pjones356', '10', ['xattr' => true, 'createPath' => true]) 22 ->execute(); 23 24// Create a user and assign roles. This user will search for their available discounts. 25$userSettings = new \Couchbase\UserSettings(); 26$userSettings 27 ->password('jsmith123pwd') 28 ->role('data_reader', 'travel-sample') 29 ->role('query_select', 'travel-sample'); 30$cluster->manager()->upsertUser('cbtestuser', $userSettings); 31 32// reconnect using new user 33$cluster = new \Couchbase\Cluster('couchbase://192.168.1.194'); 34$cluster->authenticateAs('jsmith123', 'jsmith123pwd'); 35 36$bucket = $cluster->openBucket('travel-sample'); 37 38// Perform a N1QL Query to return document IDs from the bucket. These IDs will be 39// used to reference each document in turn, and check for extended attributes 40// corresponding to discounts. 41$query = \Couchbase\N1qlQuery::fromString('SELECT id, meta(`travel-sample`).id AS docID FROM `travel-sample`'); 42$result = $bucket->query($query); 43$results = ''; 44 45foreach ($result->rows as $row) { 46 // get row document ID 47 $docID = $row->docID; 48 49 // Determine whether a hotel-discount has been applied to this user. 50 $res = $bucket->lookupIn($docID) 51 ->exists('discounts.jsmith123', ['xattr' => true]) 52 ->execute(); 53 if ($res->value[0]['code'] == COUCHBASE_SUCCESS) { 54 // If so, get the discount-percentage. 55 $res = $bucket->lookupIn($docID) 56 ->get('discounts.jsmith123', ['xattr' => true]) 57 ->execute(); 58 $discount = $res->value[0]['value']; 59 60 // If the percentage - value is greater than 15, include the document in the 61 // results to be returned. 62 $results = sprintf("%s\n%s - %s", $results, $discount, $docID); 63 } 64} 65printf("Results returned are: %s\n", $results);