PHP code example of gcgov / arcgisphpsdk

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

    

gcgov / arcgisphpsdk example snippets


use gcgov\arcgis\config;
use gcgov\arcgis\MajorMinorFeatureService;

// baseUrl, username, password, development flag
$config  = new config( 'https://gis.garrettcounty.org/', 'username', 'password', false );
$service = new MajorMinorFeatureService( $config );

// fetch every feature on the layer (automatically pages through transfer limits)
$features = $service->getAllFeatures();

foreach( $features as $feature ) {
	// $feature->properties is typed to the layer schema
	echo $feature->properties->countystructurenumber . ' — ' . $feature->properties->roadname . PHP_EOL;

	// geometry is GeoJSON: coordinates are [ longitude, latitude ] in WGS84
	$coordinates = $feature->geometry?->coordinates;
}

try {
	$features = $service->getAllFeatures();
}
catch( \GuzzleHttp\Exception\GuzzleException | \andrewsauder\jsonDeserialize\exceptions\jsonDeserializeException $e ) {
	// log and handle
}

$config = new \gcgov\arcgis\config(
	baseUrl:     'https://gis.garrettcounty.org/', // default
	username:    'serviceAccount',
	password:    'secret',
	development: false
);

$arcgisServiceConfig = new \gcgov\arcgis\config(
	config::getEnvironmentConfig()->appDictionary['arcgisBaseUrl'],
	config::getEnvironmentConfig()->appDictionary['arcgisUsername'],
	config::getEnvironmentConfig()->appDictionary['arcgisPassword'],
	config::getEnvironmentConfig()->isLocal()
);
$majorMinorFeatureService = new \gcgov\arcgis\MajorMinorFeatureService( $arcgisServiceConfig );

$roadsService = new \gcgov\arcgis\CenterLinesCulvertsFeatureService( $config );

/** @var \gcgov\arcgis\CenterLinesFeatureService\Feature[] $roads */
$roads = $roadsService->getAllFeatures();

// convenience helper: distinct, sorted local road names
$roadNames = $roadsService->getAllRoadNames();

use gcgov\arcgis\DPUWaterSystemEditorFeatureService;

$waterSystemService = new DPUWaterSystemEditorFeatureService( $config );

/** @var \gcgov\arcgis\DPUWaterSystemEditorFeatureService\FireHydrant\Feature[] $hydrants */
$hydrants = $waterSystemService->getAllFireHydrantFeatures();

$updateResponse = $waterSystemService->updateFeatures( $hydrants, DPUWaterSystemEditorFeatureService::LAYER_FIRE_HYDRANT );

// tables hydrate the same way — rows are Features with null geometry, and edits post attribute-only payloads
$inspections = $waterSystemService->getAllHydrantMaintenanceInspectionFeatures();

/** @var \gcgov\arcgis\DPUWaterSystemEditorFeatureService\ServiceMeter\Feature[] $meters */
$meters = $waterSystemService->getServiceMeterFeaturesWhere( "meterid='81234567'" );

$feature = new \gcgov\arcgis\MajorMinorFeatureService\Feature();
$feature->properties->roadname              = 'Bumble Bee Road';
$feature->properties->countystructurenumber = 'G-0042';
$feature->geometry->coordinates             = [ -79.344935, 39.522503 ]; // [ lon, lat ]

$addResponse = $service->addFeatures( [ $feature ] );

if( isset( $addResponse->error ) ) {
	throw new \Exception( $addResponse->error->message ?? 'Top level error' );
}
elseif( !isset( $addResponse->addResults[0] ) ) {
	throw new \Exception( 'No result returned' );
}
elseif( isset( $addResponse->addResults[0]->error ) ) {
	throw new \Exception( $addResponse->addResults[0]->error->description ?? 'Feature error' );
}

$structure->esriObjectId = $addResponse->addResults[0]->objectId;
$structure->esriGlobalId = $addResponse->addResults[0]->globalId;

$features = $service->getAllFeatures();

foreach( $features as $feature ) {
	if( $feature->properties->globalid === $myRecord->esriGlobalId ) {
		$feature->properties->rating       = '7';
		$feature->properties->roadname     = $myRecord->roadName;
		$feature->geometry->coordinates[0] = round( $myRecord->longitude, 5 );
		$feature->geometry->coordinates[1] = round( $myRecord->latitude, 5 );

		$updateResponse = $service->updateFeatures( [ $feature ] );
	}
}

$deleteResponse = $service->deleteFeatures( $featuresToDelete );

$attachmentInfos = $service->getAttachmentInfos( $objectId, $layerId );
foreach( $attachmentInfos->attachmentInfos ?? [] as $attachmentInfo ) {
	echo $attachmentInfo->id . ': ' . $attachmentInfo->name . ' (' . $attachmentInfo->contentType . ', ' . $attachmentInfo->size . ' bytes)' . PHP_EOL;
}

$addResponse = $service->addAttachment( $objectId, '/path/to/photo.jpg', 'photo.jpg', 'image/jpeg', $layerId );
if( $addResponse->error!==null || !( $addResponse->addAttachmentResult?->success ?? false ) ) {
	// handle failure: $addResponse->error?->message or $addResponse->addAttachmentResult?->error?->description
}

$layer = $service->getFeatureServerLayer( 0 );

foreach( $layer->fields as $field ) {
	echo $field->name . ' (' . $field->type . ')' . PHP_EOL;
	if( $field->domain !== null ) {
		foreach( $field->domain->codedValues as $codedValue ) {
			echo '  ' . $codedValue->code . ' => ' . $codedValue->name . PHP_EOL;
		}
	}
}

use gcgov\arcgis\sdk\FeatureServerLayer\CodedValue;
use gcgov\arcgis\sdk\FeatureServerLayer\Domain;
use gcgov\arcgis\sdk\FeatureServerLayer\Field;

$domain              = new Domain();
$domain->name        = 'structure_rating';
$domain->type        = 'codedValue';
$domain->splitPolicy = 'esriSPTDefaultValue';
$domain->mergePolicy = 'esriMPTDefaultValue';
$domain->codedValues = [];

$codedValue            = new CodedValue();
$codedValue->code      = '7';
$codedValue->name      = 'Good';
$domain->codedValues[] = $codedValue;

$field           = new Field();
$field->name     = 'rating';
$field->alias    = 'Current Overall Rating';
$field->type     = 'esriFieldTypeString'; // esriFieldTypeDouble, esriFieldTypeInteger, esriFieldTypeDate, ...
$field->length   = 256;
$field->nullable = true;
$field->editable = true;
$field->domain   = $domain;

$addDefinition    = $service->addFeatureLayerFields( [ $field ], 0 );    // POST {layer}/addToDefinition
$updateDefinition = $service->updateFeatureLayerFields( [ $field ], 0 ); // POST {layer}/updateDefinition

$featureServer = $service->getFeatureServer();       // service-level metadata: layers, extents, capabilities
foreach( $featureServer->layers as $layer ) {
	echo $layer->id . ': ' . $layer->name . ' (' . $layer->geometryType . ')' . PHP_EOL;
}

$layer = $service->getFeatureServerLayer( 0 );        // layer-level metadata: fields, indexes, renderer, templates

$field  = $layer->getField( 'lifecyclestatus' );                   // ?Field — � field-level domain, or the subtype domain when the field defines none

$code = $domain?->getCodedValueByName( 'In Service' )?->code;      // '8' — cast to int for integer fields
$validNames = $domain?->getCodedValueNames();                      // [ 'Unknown', 'Proposed', 'In Service', ... ]

$locator               = new \gcgov\arcgis\AddressLocator( $config );
$locator->singleLine   = '203 S 4th St, Oakland, MD 21550';
$locator->maxLocations = 5;

$response = $locator->findAddressCandidates();

foreach( $response->candidates as $candidate ) {
	echo $candidate->address . ' (score ' . $candidate->score . '): '
		. $candidate->location->x . ', ' . $candidate->location->y . PHP_EOL;
	// $candidate->attributes carries the full locator output (Match_addr, City, Postal, X/Y, ...)
}

namespace gcgov\arcgis;

use gcgov\arcgis\sdk\FeatureService;

class MyServiceFeatureService extends FeatureService {

	public function __construct( config $config ) {
		parent::__construct(
			$config,
			$config->getBaseUrl( 'server/rest/services/Hosted/My_Service/FeatureServer/' ),
			$config->getBaseUrl( 'server/rest/admin/services/Hosted/My_Service/FeatureServer/' )
		);
	}


	/** @return \gcgov\arcgis\MyServiceFeatureService\Feature[] */
	public function getAllFeatures( int $offset = 0, int $featuresPerCall = 1000, array $collections = [] ): array {
		$token  = $this->getConfig()->getToken();
		$url    = $this->getServiceUrl( '0/query?f=geojson&where=1%3D1&outFields=*&resultOffset=' . $offset . '&resultRecordCount=' . $featuresPerCall . '&token=' . $token );
		$client = new \GuzzleHttp\Client();
		$res    = $client->request( 'GET', $url );

		$collection    = \gcgov\arcgis\MyServiceFeatureService\FeatureQuery::jsonDeserialize( $res->getBody() );
		$collections[] = $collection;

		if( $collection->exceededTransferLimit ) {
			return $this->getAllFeatures( $offset + $featuresPerCall, $featuresPerCall, $collections );
		}

		$features = [];
		foreach( $collections as $collection ) {
			$features = array_merge( $features, $collection->features );
		}
		return $features;
	}

}

namespace gcgov\arcgis\MyServiceFeatureService;

class FeatureQuery extends \gcgov\arcgis\sdk\FeatureQuery {

	/** @var \gcgov\arcgis\MyServiceFeatureService\Feature[] $features */
	public ?array $features = [];

}