public function getAsXML()
    {
        // root
        $this->dom = new \DOMDocument(); // reset so we don't continually to add to the options node
        $root = $this->dom->createElement('options');
        $root->setAttribute('xmlns', 'http://marklogic.com/appservices/search');
        $this->dom->appendChild($root);

        // constraints
        foreach ($this->constraints as $constraint) {
            $root->appendChild($constraint->getAsElem($this->dom));
        }

        // values
        foreach ($this->values as $value) {
            $root->appendChild($value->getValuesAsElem($this->dom));
        }

        // metadata extracts
        if(isset($this->extracts)) {
            $extractsElem = $this->extracts->getExtractsAsElem($this->dom);
            $root->appendChild($extractsElem);
        }

        // transform results (snippetting)
        if(isset($this->transformResults)) {
            $transElem = $this->transformResults->getTransformResultsAsElem($this->dom);
            $root->appendChild($transElem);
        }

        // term
        if(isset($this->term)) {
            $termElem = $this->term->getAsElem($this->dom);
            $root->appendChild($termElem);
        }

        $this->addOptionXML($root, 'additional-query', $this->additionalQuery);
        $this->addOption($root, 'concurrency-level', $this->concurrencyLevel);
        $this->addOption($root, 'debug', $this->debug);
        $this->addOption($root, 'forest', $this->forest);
        $this->addOption($root, 'page-length', $this->pageLength);
        $this->addOption($root, 'quality-weight', $this->qualityWeight);
        $this->addOption($root, 'return-constraints', $this->returnConstraints);
        $this->addOption($root, 'return-facets', $this->returnFacets);
        $this->addOption($root, 'return-metrics', $this->returnMetrics);
        $this->addOption($root, 'return-plan', $this->returnPlan);
        $this->addOption($root, 'return-qtext', $this->returnQtext);
        $this->addOption($root, 'return-query', $this->returnQuery);
        $this->addOption($root, 'return-results', $this->returnResults);
        $this->addOption($root, 'return-similar', $this->returnSimilar);
        if (!empty($this->searchOptions)) {
            foreach($this->searchOptions as $opt) {
                $this->addOption($root, 'search-option', $this->returnSimilar);
            }
        }
        return $this->dom->saveXML();
    }

Get the query options as XML.

@return string The query options as XML.


public function addOption($root, $name, $value)
    {
        if (isset($value)) {
            $elem = $this->dom->createElement($name);
            $elem->nodeValue = $value;
            $root->appendChild($elem);
        }
    }

public function addOption ( $ root , $ name , $ value ) { if ( isset ( $ value ) ) { $ elem = $ this -> dom -> createElement ( $ name ) ; $ elem -> nodeValue = $ value ; $ root -> appendChild ( $ elem ) ; } }

If an option value is set, create a DOM element with an option name
and value and append it to the root element of the options node.

@param DOMElement $root The root element of the options node.
@param string $name The element name (option name).
@param string $value The node value.

If an option value is set create a DOM element with an option name and value and append it to the root element of the options node .


public function addOptionXML($root, $name, $xmlString)
    {
        if (isset($xmlString)) {
            $elem = $this->dom->createElement($name);
            $xmlDoc = new \DOMDocument();
            $xmlDoc->loadXML($xmlString);
            // http://stackoverflow.com/questions/5783716/php-xml-dom-uncaught-exception-domexception-with-message-wrong-document-error
            $elem->appendChild($this->dom->importNode($xmlDoc->documentElement, true));
            $root->appendChild($elem);
        }
    }

If an option value is set, create a DOM element with an option name
and XML string value and append it to the root element of the options node.

@param DOMElement $root The root element of the options node.
@param string $name The element name (option name).
@param string $value The node value as an XML string.

If an option value is set create a DOM element with an option name and XML string value and append it to the root element of the options node .


public function read($name = null)
    {
        $name = $name ? $name : $this->name;
        try {
            $params = array('format' => 'xml');
            $request = new RESTRequest('GET', 'config/query/' . $name, $params);
            $response = $this->client->send($request);
            return $response->getBody();
        } catch(Exception $e) {
            echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . PHP_EOL;
        }
    }

public
function
read
(
$
name
=
)
{
$
name
=
$
name
$
name
:
$
this
->
name
;
try
{
$
params
=
array
(
'format'
=>
'xml'
)
;
$
request
=
new
RESTRequest
(
'GET'
,
'config/query/'
.
$
name
,
$
params
)
;
$
response
=
$
this
->
client
->
send
(
$
request
)
;
return
$
response
->
getBody
(
)
;
}
catch
(
Exception
$
e
)
{
echo
$
e
->
getMessage
(
)
.
' in '
.
$
e
->
getFile
(
)
.
' on line '
.
$
e
->
getLine
(
)
.
PHP_EOL
;
}
}

Read the query options from the database.

@param string $name The query options name.
@return string The query options as XML.

Read the query options from the database .


public function write($name = null)
    {
        $name = $name ? $name : $this->name;
        try {
            $params = array('format' => 'xml');
            $headers = array('Content-type' => 'application/xml');
            $request = new RESTRequest('PUT', 'config/query/' . $name, $params, $this->getAsXML(), $headers);
            $this->response = $this->client->send($request);
            return $this;
        } catch(Exception $e) {
            echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . PHP_EOL;
        }
    }

public
function
write
(
$
name
=
)
{
$
name
=
$
name
$
name
:
$
this
->
name
;
try
{
$
params
=
array
(
'format'
=>
'xml'
)
;
$
headers
=
array
(
'Content-type'
=>
'application/xml'
)
;
$
request
=
new
RESTRequest
(
'PUT'
,
'config/query/'
.
$
name
,
$
params
,
$
this
->
getAsXML
(
)
,
$
headers
)
;
$
this
->
response
=
$
this
->
client
->
send
(
$
request
)
;
return
$
this
;
}
catch
(
Exception
$
e
)
{
echo
$
e
->
getMessage
(
)
.
' in '
.
$
e
->
getFile
(
)
.
' on line '
.
$
e
->
getLine
(
)
.
PHP_EOL
;
}
}

Write the query options to the database.

@param string $name The query options name.
@return Options $this

Write the query options to the database .


public function delete($name)
    {
        $name = $name ? $name : $this->name;
        try {
            $request = new RESTRequest('DELETE', 'config/query/' . $name);
            $this->response = $response = $this->client->send($request);
            return $this;
        } catch(Exception $e) {
            echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . PHP_EOL;
        }
    }

public
function
delete
(
$
name
)
{
$
name
=
$
name
$
name
:
$
this
->
name
;
try
{
$
request
=
new
RESTRequest
(
'DELETE'
,
'config/query/'
.
$
name
)
;
$
this
->
response
=
$
response
=
$
this
->
client
->
send
(
$
request
)
;
return
$
this
;
}
catch
(
Exception
$
e
)
{
echo
$
e
->
getMessage
(
)
.
' in '
.
$
e
->
getFile
(
)
.
' on line '
.
$
e
->
getLine
(
)
.
PHP_EOL
;
}
}

Delete the query options from the database.

@param string $name The query options name.
@return Options $this

Delete the query options from the database .


public function setSearchOptions($searchOptions)
    {
        if (is_array($searchOptions)) {
            $this->searchOptions = array_unique(array_merge($this->searchOptions, $searchOptions));
        } else {
            $this->searchOptions[] = $searchOptions;
            $this->searchOptions = array_unique($this->searchOptions);
        }
        return $this;
    }

public function setSearchOptions ( $ searchOptions ) { if ( is_array ( $ searchOptions ) ) { $ this -> searchOptions = array_unique ( array_merge ( $ this -> searchOptions , $ searchOptions ) ) ; } else { $ this -> searchOptions [ ] = $ searchOptions ; $ this -> searchOptions = array_unique ( $ this -> searchOptions ) ; } return $ this ; }

Set the query options.

@see http://docs.marklogic.com/search:search#opt-search-option

@param string|array $searchOptions The query options as a string (single option) or array of strings.
@return Options $this


public function read($uri = null, $params = array())
    {
        $this->uri = (isset($uri)) ? (string)$uri : $this->uri;
        try {
            $params = array_merge(array('uri' => $this->uri), $params);
            $request = new RESTRequest('GET', 'documents', $params);
            $this->response = $this->client->send($request);
            $this->content = $this->response->getBody();
            $this->contentType = $this->response->getContentType();
            return $this->content;
        } catch(\Exception $e) {
            // TODO: error codes for not-found and other reasonable, unexceptional errors.
            $this->logger->warning( $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() );
            return false;
        }
    }

Read a document from the database.

@see Document::getContent()

@param string $uri A document URI.
@param array $params Optional additional parameters to pass when reading.
@return string|bool The document content or false on failure.


public function write($uri = null, $params = array())
    {
        $this->uri = (isset($uri)) ? (string)$uri : $this->uri;
        try {
            $params = array_merge(array('uri' => $this->uri), $params);
            $headers = array();
            if ($this->getContentType()) {
                $headers = array('Content-type' => $this->getContentType());
            }
            $request = new RESTRequest('PUT', 'documents', $params, $this->content, $headers);
            $this->response = $this->client->send($request);
        } catch(\Exception $e) {
            $this->logger->error( $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() );
            throw $e;
        }
        return $this;
    }

public
function
write
(
$
uri
=
,
$
params
=
array
(
)
)
{
$
this
->
uri
=
(
isset
(
$
uri
)
)
(
string
)
$
uri
:
$
this
->
uri
;
try
{
$
params
=
array_merge
(
array
(
'uri'
=>
$
this
->
uri
)
,
$
params
)
;
$
headers
=
array
(
)
;
if
(
$
this
->
getContentType
(
)
)
{
$
headers
=
array
(
'Content-type'
=>
$
this
->
getContentType
(
)
)
;
}
$
request
=
new
RESTRequest
(
'PUT'
,
'documents'
,
$
params
,
$
this
->
content
,
$
headers
)
;
$
this
->
response
=
$
this
->
client
->
send
(
$
request
)
;
}
catch
(
\
Exception
$
e
)
{
$
this
->
logger
->
error
(
$
e
->
getMessage
(
)
.
' in '
.
$
e
->
getFile
(
)
.
' on line '
.
$
e
->
getLine
(
)
)
;
throw
$
e
;
}
return
$
this
;
}

Write a document to the database.

@param string $uri A document URI.
@param array $params Optional additional parameters to pass when writing.
@return Document $this


public function delete($uri = null)
    {
        $this->uri = (isset($uri)) ? (string)$uri : $this->uri;
        try {
            $params = array('uri' => $this->uri);
            $request = new RESTRequest('DELETE', 'documents', $params);
            $this->response = $this->client->send($request);
        } catch(\Exception $e) {
            $this->logger->error(  $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() );
        }
        return $this;
    }

public
function
delete
(
$
uri
=
)
{
$
this
->
uri
=
(
isset
(
$
uri
)
)
(
string
)
$
uri
:
$
this
->
uri
;
try
{
$
params
=
array
(
'uri'
=>
$
this
->
uri
)
;
$
request
=
new
RESTRequest
(
'DELETE'
,
'documents'
,
$
params
)
;
$
this
->
response
=
$
this
->
client
->
send
(
$
request
)
;
}
catch
(
\
Exception
$
e
)
{
$
this
->
logger
->
error
(
$
e
->
getMessage
(
)
.
' in '
.
$
e
->
getFile
(
)
.
' on line '
.
$
e
->
getLine
(
)
)
;
}
return
$
this
;
}

Delete a document from the database. Note that no properties for object are changed.

@param string $uri The document URI.
@return Document $this

Delete a document from the database . Note that no properties for object are changed .


public function readMetadata()
    {
        try {
            $params = array('uri' => $this->uri, 'category' => 'metadata');
            $request = new RESTRequest('GET', 'documents', $params);
            $this->response = $this->client->send($request);
            $metadata = new Metadata();
            $metadata->loadFromXML($this->response->getBody());
            return $metadata;
        } catch(\Exception $e) {
            $this->logger->error( $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() );
            return null;
        }
    }

public
function
readMetadata
(
)
{
try
{
$
params
=
array
(
'uri'
=>
$
this
->
uri
,
'category'
=>
'metadata'
)
;
$
request
=
new
RESTRequest
(
'GET'
,
'documents'
,
$
params
)
;
$
this
->
response
=
$
this
->
client
->
send
(
$
request
)
;
$
metadata
=
new
Metadata
(
)
;
$
metadata
->
loadFromXML
(
$
this
->
response
->
getBody
(
)
)
;
return
$
metadata
;
}
catch
(
\
Exception
$
e
)
{
$
this
->
logger
->
error
(
$
e
->
getMessage
(
)
.
' in '
.
$
e
->
getFile
(
)
.
' on line '
.
$
e
->
getLine
(
)
)
;
return
;
}
}

Read document metadata from the database.

@return Metadata A Metadata object.

Read document metadata from the database .


public function writeMetadata($metadata)
    {
        $metaxml = $metadata->getAsXML();
        try {
            $params = array('uri' => $this->uri, 'category' => 'metadata', 'format' => 'xml');
            $headers = array('Content-type' => 'application/xml');
            $request = new RESTRequest('PUT', 'documents', $params, $metaxml, $headers);
            $this->response = $this->client->send($request);
        } catch(\Exception $e) {
            $this->logger->error( $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() );
        }
        return $this;
    }

public
function
writeMetadata
(
$
metadata
)
{
$
metaxml
=
$
metadata
->
getAsXML
(
)
;
try
{
$
params
=
array
(
'uri'
=>
$
this
->
uri
,
'category'
=>
'metadata'
,
'format'
=>
'xml'
)
;
$
headers
=
array
(
'Content-type'
=>
'application/xml'
)
;
$
request
=
new
RESTRequest
(
'PUT'
,
'documents'
,
$
params
,
$
metaxml
,
$
headers
)
;
$
this
->
response
=
$
this
->
client
->
send
(
$
request
)
;
}
catch
(
\
Exception
$
e
)
{
$
this
->
logger
->
error
(
$
e
->
getMessage
(
)
.
' in '
.
$
e
->
getFile
(
)
.
' on line '
.
$
e
->
getLine
(
)
)
;
}
return
$
this
;
}

Write document metadata to the database.

@param Metadata $metadata A Metadata object.
@return Document $this

Write document metadata to the database .


public function deleteMetadata()
    {
        try {
            $params = array('uri' => $this->uri, 'category' => 'metadata');
            $request = new RESTRequest('DELETE', 'documents', $params);
            $this->response = $this->client->send($request);
        } catch(\Exception $e) {
            $this->logger->error( $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() );
        }
        return $this;
    }

public
function
deleteMetadata
(
)
{
try
{
$
params
=
array
(
'uri'
=>
$
this
->
uri
,
'category'
=>
'metadata'
)
;
$
request
=
new
RESTRequest
(
'DELETE'
,
'documents'
,
$
params
)
;
$
this
->
response
=
$
this
->
client
->
send
(
$
request
)
;
}
catch
(
\
Exception
$
e
)
{
$
this
->
logger
->
error
(
$
e
->
getMessage
(
)
.
' in '
.
$
e
->
getFile
(
)
.
' on line '
.
$
e
->
getLine
(
)
)
;
}
return
$
this
;
}

Delete document metadata. Metadata reverts to default metadata state.

@return Document $this

Delete document metadata . Metadata reverts to default metadata state .


public function setContentFile($file)
    {
        try {
            $content = file_get_contents((string)$file);
        } catch(\Exception $e) {
            $this->logger->error( $e->getMessage() );
        }
        $this->setContent($content);
        return $this;
    }

public function setContentFile ( $ file ) { try { $ content = file_get_contents ( ( string ) $ file ) ; } catch ( \ Exception $ e ) { $ this -> logger -> error ( $ e -> getMessage ( ) ) ; } $ this -> setContent ( $ content ) ; return $ this ; }

Set the document content from the file system.

@param string $file The file location.
@return Document $this

Set the document content from the file system .


public function getFileMimeType($file)
    {
        if (function_exists('finfo_file')) {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $type = finfo_file($finfo, $file);
            finfo_close($finfo);
        } else if (function_exists('mime_content_type')) {
            $type = mime_content_type($file);
        } else {
        	$type = '';
        }
        return $type;
    }

public function getFileMimeType ( $ file ) { if ( function_exists ( 'finfo_file' ) ) { $ finfo = finfo_open ( FILEINFO_MIME_TYPE ) ; $ type = finfo_file ( $ finfo , $ file ) ; finfo_close ( $ finfo ) ; } else if ( function_exists ( 'mime_content_type' ) ) { $ type = mime_content_type ( $ file ) ; } else { $ type = '' ; } return $ type ; }

Get the mimetype of a file.

@param string $file The file.
@return string The the mimetype of the file.


private function log_soap_call($CALL, $TIME, $QUERY, $REPLY)
    {
        array_push($this->SOAPCALLS,
                    [
                        'call'     => $CALL,
                        'time'     => $TIME,
                        'query'    => $QUERY,
                        'reply'    => $REPLY,
                    ]
            );

        return count($this->SOAPCALLS);
    }

private function log_soap_call ( $ CALL , $ TIME , $ QUERY , $ REPLY ) { array_push ( $ this -> SOAPCALLS , [ 'call' => $ CALL , 'time' => $ TIME , 'query' => $ QUERY , 'reply' => $ REPLY , ] ) ; return count ( $ this -> SOAPCALLS ) ; }

Keep track of our soap calls for performance and debugging


public function decode_soap_reply($SOAPREPLY)
    {
        if (!is_object($SOAPREPLY)) {
            throw new \Exception('SOAP reply is not an object');
        }
        if (!property_exists($SOAPREPLY, 'return')) {
            throw new \Exception('SOAP reply does not have the property return');
        }
        $SOAPRETURN = $SOAPREPLY->return;
        $SOAPOBJVARS = get_object_vars($SOAPRETURN);
        $RETURN = reset($SOAPOBJVARS);
        if (is_object($RETURN)) {
            // Single objects mean we recieved exactly one element in the reply
            $RETURN = [$this->object_to_assoc($RETURN)];
        } else {
            // Otherwise we recieved multiple elements in the reply.
            $RETURN = $this->object_to_assoc($RETURN);
        }

        return $RETURN;
    }

Every response will be an array of the responses, even if its just one response

Every response will be an array of the responses even if its just one response


public function assoc_key_values_to_array($ASSOC, $AKEY, $STOPONERROR = true)
    {
        $RETURN = [];

        // Make sure its $ASSOC is an array or it errors out.
        if (is_array($ASSOC)) {
            // Loop through the array of key=>value pairs
            foreach ($ASSOC as $KEY => $VALUE) {
                if (isset($VALUE[$AKEY]) && $VALUE[$AKEY] !== '') {
                    if (isset($VALUE['uuid']) && $VALUE['uuid']) {
                        // If the query returns a UUID, use that as our array key!
                        $RETURN[$VALUE['uuid']] = $VALUE[$AKEY];
                    } else {
                        // If the query does NOT return a UUID, use sequencial keys
                        array_push($RETURN, $VALUE[$AKEY]);
                    }
                } elseif ($STOPONERROR) {
                    throw new \Exception("Assoc array value does not have key {$KEY}");
                }
            }
        }

        return $RETURN;
    }

This converts an array of key=>value pairs into a flat array of one of the keys values

This converts an array of key = > value pairs into a flat array of one of the keys values


public function do_ldap_sync($NAME, $BOOLEAN)
    {
        $SEARCH = ['name' => $NAME, 'sync' => $BOOLEAN];
        // Search the CUCM for all phones
        $BASETIME = $this->microtimeTicks();
        $RETURN = $this->SOAPCLIENT->doLdapSync($SEARCH);
        $DIFFTIME = $this->microtimeTicks() - $BASETIME;
        // log our soap call
        $this->log_soap_call('doLdapSync', $DIFFTIME, $SEARCH, $RETURN);

        if (!is_object($RETURN)) {
            throw new \Exception('SOAP reply is not an object');
        } else {
            return $RETURN;
        }
    }

public
function
do_ldap_sync
(
$
NAME
,
$
BOOLEAN
)
{
$
SEARCH
=
[
'name'
=>
$
NAME
,
'sync'
=>
$
BOOLEAN
]
;
// Search the CUCM for all phones
$
BASETIME
=
$
this
->
microtimeTicks
(
)
;
$
RETURN
=
$
this
->
SOAPCLIENT
->
doLdapSync
(
$
SEARCH
)
;
$
DIFFTIME
=
$
this
->
microtimeTicks
(
)
$
BASETIME
;
// log our soap call
$
this
->
log_soap_call
(
'doLdapSync'
,
$
DIFFTIME
,
$
SEARCH
,
$
RETURN
)
;
if
(
!
is_object
(
$
RETURN
)
)
{
throw
new
\
Exception
(
'SOAP reply is not an object'
)
;
}
else
{
return
$
RETURN
;
}
}

Kick off LDAP Sync Process in CUCM - Name of LDAP Dirctory and true to start or false to stop.

Kick off LDAP Sync Process in CUCM - Name of LDAP Dirctory and true to start or false to stop .


public function get_phone_names()
    {
        $SEARCH = $this->axl_search_return_array(['devicePoolName' => '%'], ['name' => '']);
        // Search the CUCM for all phones
        $BASETIME = $this->microtimeTicks();
        $RETURN = $this->SOAPCLIENT->listPhone($SEARCH);
        $DIFFTIME = $this->microtimeTicks() - $BASETIME;
        // log our soap call
        $this->log_soap_call('listPhone', $DIFFTIME, $SEARCH, $RETURN);
        // Decode the reply into an array of results
        $RETURN = $this->decode_soap_reply($RETURN);
        // Turn the associative arrays into a single simensional array list
        $RETURN = $this->assoc_key_values_to_array($RETURN, 'name');

        return $RETURN;
    }

Get a complete list of the names of all phones


public function list_all_phones_summary_by_site($SITE)
    {
        $SEARCH = $this->axl_search_return_array(['devicePoolName' => "%{$SITE}%"], [
                                                                    'name'                   => '',
                                                                    'description'            => '',
                                                                    'product'                => '',
                                                                    'callingSearchSpaceName' => '',
                                                                    'devicePoolName'         => '',
                                                                    'locationName'           => '',
                                                                    'phoneTemplateName'      => '',
                                                                    'ownerUserName'          => '',
                                                                ]);
        // Search the CUCM for phones from Site Device Pool
        $BASETIME = $this->microtimeTicks();
        $RETURN = $this->SOAPCLIENT->listPhone($SEARCH);
        $DIFFTIME = $this->microtimeTicks() - $BASETIME;
        // log our soap call
        $this->log_soap_call('listPhone', $DIFFTIME, $SEARCH, $RETURN);
        // Decode the reply into an array of results
        $RETURN = $this->decode_soap_reply($RETURN);
        // Turn the associative arrays into a single simensional array list
        //$RETURN = $this->assoc_key_values_to_array($RETURN, 'name');

        return $RETURN;
    }

Including specific fields to return in the list function.

Including specific fields to return in the list function .


public function phone_search_by_name($NAME)
    {
        $SEARCH = $this->axl_search_return_array(['name'    => "%{$NAME}%"], [
                                                                    'name'                   => '',
                                                                    'description'            => '',
                                                                    'product'                => '',
                                                                    'callingSearchSpaceName' => '',
                                                                    'devicePoolName'         => '',
                                                                    'locationName'           => '',
                                                                    'phoneTemplateName'      => '',
                                                                    'ownerUserName'          => '',
                                                                ]);
        // Search the CUCM for phones from Site Device Pool
        $BASETIME = $this->microtimeTicks();
        $RETURN = $this->SOAPCLIENT->listPhone($SEARCH);
        $DIFFTIME = $this->microtimeTicks() - $BASETIME;
        // log our soap call
        $this->log_soap_call('listPhone', $DIFFTIME, $SEARCH, $RETURN);
        // Decode the reply into an array of results
        $RETURN = $this->decode_soap_reply($RETURN);
        // Turn the associative arrays into a single simensional array list
        //$RETURN = $this->assoc_key_values_to_array($RETURN, 'name');

        return $RETURN;
    }


public function phone_search($KEY, $SEARCH)
    {
        /*
            $KEYS =
                ['name',
                'description',
                'protocol',
                'callingSearchSpaceName',
                'devicePoolName',
                'securityProfileName']

        */
        $SEARCH = $this->axl_search_return_array([$KEY    => "%{$SEARCH}%"], [
                                                                    'name'                   => '',
                                                                    'description'            => '',
                                                                    'product'                => '',
                                                                    'callingSearchSpaceName' => '',
                                                                    'devicePoolName'         => '',
                                                                    'locationName'           => '',
                                                                    'ownerUserName'          => '',
                                                                ]);
        // Search the CUCM for phones from Site Device Pool
        $BASETIME = $this->microtimeTicks();
        $RETURN = $this->SOAPCLIENT->listPhone($SEARCH);
        $DIFFTIME = $this->microtimeTicks() - $BASETIME;
        // log our soap call
        $this->log_soap_call('listPhone', $DIFFTIME, $SEARCH, $RETURN);
        // Decode the reply into an array of results
        $RETURN = $this->decode_soap_reply($RETURN);
        // Turn the associative arrays into a single simensional array list
        //$RETURN = $this->assoc_key_values_to_array($RETURN, 'name');

        return $RETURN;
    }


public function get_phone_by_name($NAME)
    {
        $SEARCH = ['name' => $NAME];
        $BASETIME = $this->microtimeTicks();
        $RETURN = $this->SOAPCLIENT->getPhone($SEARCH);
        $DIFFTIME = $this->microtimeTicks() - $BASETIME;
        // log our soap call
        $this->log_soap_call('getPhone', $DIFFTIME, $SEARCH, $RETURN);
        // Decode the reply into an array of results
        $RETURN = $this->decode_soap_reply($RETURN);
        // Count the number of replies we recieved...
        $COUNT = count($RETURN);
        // It should be EXACTLY one result
        if ($COUNT !== 1) {
            throw new \Exception("Search returned {$COUNT} results, not exactly 1 as expected");
        }
        // Strip off the outer array
        $RETURN = reset($RETURN);

        return $RETURN;
    }

Get all the information regarding one specific phone by name


public function get_directory_numbers_by_name($NAME)
    {
        // Get our phone by name from the previous function
        $PHONE = $this->get_phone_by_name($NAME);
        if (!isset($PHONE['lines'])) {
            throw new \Exception('Phone record does not contain the lines element');
        }
        if (!is_array($PHONE['lines'])) {
            throw new \Exception('Phone record lines element is not an array');
        }
        // Suck out the array of phone numbers
        $RETURN = reset($PHONE['lines']);
        // Turn them into a flat array of DIRNs
        $RETURN = $this->assoc_key_values_to_array($RETURN, 'dirn');
        // Turn the DIRNs into patterns of phone numbers
        $RETURN = $this->assoc_key_values_to_array($RETURN, 'pattern');

        return $RETURN;
    }

Get an array of directory numbers by phone name


public function get_device_pool_names()
    {
        $SEARCH = $this->axl_search_return_array(['name' => '%'], ['name' => '']);
        // Search the CUCM for all device pools
        $BASETIME = $this->microtimeTicks();
        $RETURN = $this->SOAPCLIENT->listDevicePool($SEARCH);
        $DIFFTIME = $this->microtimeTicks() - $BASETIME;
        // log our soap call
        $this->log_soap_call('listDevicePool', $DIFFTIME, $SEARCH, $RETURN);
        // Decode the reply into an array of results
        $RETURN = $this->decode_soap_reply($RETURN);
        // Turn the associative arrays into a single simensional array list
        $RETURN = $this->assoc_key_values_to_array($RETURN, 'name');

        return $RETURN;
    }


public function get_site_names()
    {
        // Get the list of device pools
        $DEVICEPOOLS = $this->get_device_pool_names();
        $SITES = [];
        // Loop through all of the device pools
        foreach ($DEVICEPOOLS as $DP) {
            // Detect the DP_SITECODE format and put it into an array
            $REGEX = "/^DP_(\w+)/";
            if (preg_match($REGEX, $DP, $HITS)) {
                array_push($SITES, $HITS[1]);
            } else {
                //print "{$DP} did not match {$REGEX}!<br>\n";
            }
        }
        // Return our array of sites
        return $SITES;
    }


public function get_lines_by_site($SITE)
    {
        // Get all the phone object uuid=>names for a given site (based on device pool)
        $PHONES = $this->get_object_type_by_site($SITE, 'Phone');
        $LINES = [];
        // Loop through our phones at a site and use the UUID to get its detailed object information
        foreach ($PHONES as $UUID => $NAME) {
            $PHONE = $this->get_object_type_by_uuid($UUID, 'Phone');
            // if there are lines in the phone go get the uuid and name for each line dirn
            if (isset($PHONE['lines']) && is_array($PHONE['lines']) && count($PHONE['lines'])) {
                // loop through each line on the phone and suck out the uuid and dial pattern
                foreach ($PHONE['lines'] as $PHONELINE) {
                    // If the phone has a dirn element with elements
                    if (isset($PHONELINE['dirn']) && is_array($PHONELINE['dirn']) && count($PHONELINE['dirn'])) {
                        // And the dirn has a uuid and pattern with value
                        if (isset($PHONELINE['dirn']['pattern']) && $PHONELINE['dirn']['pattern'] && isset($PHONELINE['dirn']['uuid']) && $PHONELINE['dirn']['uuid']) {
                            // Save this line to the list of site lines we return
                            $LINES[$PHONELINE['dirn']['uuid']] = $PHONELINE['dirn']['pattern'];
                        }
                    }
                }
            }
        }

        return $LINES;
    }

This function will need to get every phone in a device pool and then build a list of every LINE that is returned.

This function will need to get every phone in a device pool and then build a list of every LINE that is returned .


public function get_lines_details_by_phone_name($NAME)
    {
        // Get all the phone object uuid=>names for a given site (based on device pool)
        $LINES = [];

        // get phone Line detailed object information
        $PHONE = $this->get_object_type_by_name($NAME, 'Phone');
        // if there are lines in the phone go get the uuid and name for each line dirn
        if (isset($PHONE['lines']) && is_array($PHONE['lines']) && count($PHONE['lines'])) {
            // loop through each line on the phone and suck out the uuid and dial pattern
            foreach ($PHONE['lines'] as $PHONELINE) {
                if (isset($PHONELINE['dirn']['pattern']) && $PHONELINE['dirn']['pattern'] && isset($PHONELINE['dirn']['uuid']) && $PHONELINE['dirn']['uuid']) {
                    // Phone has single linee
                    $UUID = $PHONELINE['dirn']['uuid'];
                    $LINE = $this->get_object_type_by_uuid($UUID, 'Line');
                    $LINES[$PHONELINE['dirn']['uuid']] = $LINE;
                } else {
                    // Phone has multiple lines
                    foreach ($PHONELINE as $SUBLINE) {
                        if (isset($SUBLINE['dirn']['pattern']) && $SUBLINE['dirn']['pattern'] && isset($SUBLINE['dirn']['uuid']) && $SUBLINE['dirn']['uuid']) {
                            // Save this line to the list of site lines we return
                            //$LINES[$SUBLINE['dirn']['uuid']] = $SUBLINE['dirn']['pattern'];
                            $UUID = $SUBLINE['dirn']['uuid'];
                            $LINE = $this->get_object_type_by_uuid($UUID, 'Line');
                            $LINES[$SUBLINE['dirn']['uuid']] = $LINE;
                        }
                    }
                }
            }
        }

        return $LINES;
    }

Get Phone Line Details of the phone by Name


public function get_all_object_types_by_site($SITE)
    {
        // Get our valid object types
        $TYPES = $this->object_types();

        // Do not get these objects by site. - They need to be requested directly.
        $DISCARD_TYPES = [
                    'Phone',
                    'Line',
                    //'CtiRoutePoint',
                    ];

        $RETURN = [];
        foreach ($TYPES as $TYPE) {
            if (in_array($TYPE, $DISCARD_TYPES)) {
                continue;
            }
            if (php_sapi_name() === 'cli') {
                //print "Getting {$SITE}s {$TYPE}...".PHP_EOL;
            }
            /*
            if ($TYPE == 'Line') {
                continue;
            }*/
            try {
                $RETURN[$TYPE] = $this->get_object_type_by_site($SITE, $TYPE);
            } catch (\Exception $E) {
                $RETURN[$TYPE] = [];
            }
        }

        return $RETURN;
    }

/*
            if ($TYPE == 'Line') {
                continue;
            }*/

This returns an associative array for each of the above types


public function get_object_type_by_name($NAME, $TYPE)
    {
        // Get our valid object types
        $TYPES = $this->object_types();
        // TransPattern is not valid for get-item-by-NAME, must use UUID or a combination of name and routepartitionname
        $TYPES = array_diff($TYPES, ['TransPattern']);
        // Lines is not valid for get-item-by-name, must be UUID
        $TYPES = array_diff($TYPES, ['Line']);
        // Check to see if the one we were passed is valid for this function
        if (!in_array($TYPE, $TYPES)) {
            throw new \Exception("Object type provided {$TYPE} is not supported");
        }

        $QUERY = ['name' => $NAME];
        $FUNCTION = 'get'.$TYPE;
        $BASETIME = $this->microtimeTicks();
        $RETURN = $this->SOAPCLIENT->$FUNCTION($QUERY);
        $DIFFTIME = $this->microtimeTicks() - $BASETIME;
        $this->log_soap_call($FUNCTION, $DIFFTIME, $QUERY, $RETURN);
        $RETURN = $this->decode_soap_reply($RETURN);
        $RETURN = reset($RETURN);

        return $RETURN;
    }


public function delete_object_type_by_uuid($UUID, $TYPE)
    {
        // Get our valid object types
        $TYPES = $this->object_types();
        // Check to see if the one we were passed is valid for this function
        if (!in_array($TYPE, $TYPES)) {
            throw new \Exception("Object type provided {$TYPE} is not supported");
        }

        $QUERY = ['uuid' => $UUID];
        $FUNCTION = 'remove'.$TYPE;
        $BASETIME = $this->microtimeTicks();
        $RETURN = $this->SOAPCLIENT->$FUNCTION($QUERY);
        $DIFFTIME = $this->microtimeTicks() - $BASETIME;
        $this->log_soap_call($FUNCTION, $DIFFTIME, $QUERY, $RETURN);

        return $RETURN;
    }

Only way I want to support removing items is by UUID, this is for safety because object names may not be unique

Only way I want to support removing items is by UUID this is for safety because object names may not be unique


public function addCapabilities($capabilities)
    {
        if (is_array($capabilities)) {
            $this->capabilities = array_merge((array)$this->capabilities, (array)$capabilities);
        } else {
            $this->capabilities[] = (string)$capabilities;
        }
    }

public function addCapabilities ( $ capabilities ) { if ( is_array ( $ capabilities ) ) { $ this -> capabilities = array_merge ( ( array ) $ this -> capabilities , ( array ) $ capabilities ) ; } else { $ this -> capabilities [ ] = ( string ) $ capabilities ; } }

Add capabilities.

@param array|string $capabilities An array of capability strings or a single capability string.


public function getLatitude()
    {
        if (isset($this->exif)) {
            return (float)$this->getGps($this->exif['GPSLatitude'], $this->exif['GPSLatitudeRef']);
        } else {
            return null;
        }
    }

public function getLatitude ( ) { if ( isset ( $ this -> exif ) ) { return ( float ) $ this -> getGps ( $ this -> exif [ 'GPSLatitude' ] , $ this -> exif [ 'GPSLatitudeRef' ] ) ; } else { return null ; } }

Get the latitude metadata.

@return float The latitude as a single numeric value.


public function getLongitude()
    {
        if (isset($this->exif)) {
            return (float)$this->getGps($this->exif['GPSLongitude'], $this->exif['GPSLongitudeRef']);
        } else {
            return null;
        }
    }

public function getLongitude ( ) { if ( isset ( $ this -> exif ) ) { return ( float ) $ this -> getGps ( $ this -> exif [ 'GPSLongitude' ] , $ this -> exif [ 'GPSLongitudeRef' ] ) ; } else { return null ; } }

Get the longitude metadata.

@return float The longitude as a single numeric value.


public function getBodyType()
    {
        $result = '';
        if (json_decode($this->body)) {
            $result = 'json';
        } else if (substr(trim($this->body), 0, 1) === '<') {
            $result = 'xml';
        } else {
            $result = 'other';
        }
        return $result;
    }

public function getBodyType ( ) { $ result = '' ; if ( json_decode ( $ this -> body ) ) { $ result = 'json' ; } else if ( substr ( trim ( $ this -> body ) , 0 , 1 ) === '<' ) { $ result = 'xml' ; } else { $ result = 'other' ; } return $ result ; }

Get the format type of the body.

@return string The type:
'json', 'xml', or 'other' (for non-JSON, non-XML text)


public function getErrorMessage()
    {
        $result = '';
        switch ($this->getBodyType())
        {
            case 'json':
                $obj = json_decode($this->body);
                $statusCode = $obj->errorResponse->statusCode;
                $status = $obj->errorResponse->status;
                $message = $obj->errorResponse->message;
                $result = 'Error ' . $statusCode . ': ' . $status . ' - ' . $message;
                break;
            case 'xml':
                $dom = new \DOMDocument($this->body);
                $dom->loadXML($this->body);
                // $statusCode = $dom->getElementsByTagNameNS('http://marklogic.com/rest-api', 'status-code')->item(0)->nodeValue;
                // $status = $dom->getElementsByTagNameNS('http://marklogic.com/rest-api', 'status')->item(0)->nodeValue;
                // $message = $dom->getElementsByTagNameNS('http://marklogic.com/rest-api', 'message')->item(0)->nodeValue;
                // $result = 'Error ' . $statusCode . ': ' . $status . ' - ' . $message;
                // @todo XML won't necessarily be http://marklogic.com/rest-api format
                // For now, just return body of response
                $result = 'Error: ' . $this->body;
                break;
            default:
                $result = 'Error: ' . $this->body;
        }
        return $result;
    }

Get error message from REST response body.

@see http://docs.marklogic.com/guide/rest-dev/service#id_61169
@todo error message formats seem unpredictable from server

@return array The message.

Get error message from REST response body .


public function getUrlStr()
    {
        $str = (!empty($this->resource)) ? $this->resource : '';

        /* x-www-form-encoded posts encodes query params in the body */
        if (!$this->isWWWFormURLEncodedPost()) {
            $str .= (!empty($this->params)) ? ('?' . $this->buildQuery()) : '';
        }
        return $str;
    }

Get the resource and params as a URL string.

@return string The request body.

Get the resource and params as a URL string .


public function create($client = null)
    {
        if ($this->exists()) {
            $this->logger->debug(
                'A REST API named "' . $this->name . '" already exists'
            );
            return $this;
        }
        $this->client = $client ?: $this->client;
        $params = array();
        $headers = array('Content-type' => 'application/json');
        $body = '
            {
                "rest-api": {
                    "name": "' . $this->name . '",
                    "database": "' . $this->db . '",
                    "modules-database": "' . $this->db . '-modules",
                    "port": "' . $this->port . '",
                    "forests-per-host": 1,
                    "error-format": "json"
                }
            }
        ';
        $request = new RESTRequest('POST', 'rest-apis', $params, $body, $headers);
        $this->logger->debug(
            "Setting up REST API: " . $this->name .
            ' (' . $this->db . ') port ' . $this->port
        );
        $this->client->send($request); // Set up REST API
        return $this;
    }

'",
                    "modules-database": "'

'-modules",
                    "port": "'

Create a REST API via a post to the MarkLogic rest-apis endpoint.
It will not create an API if there already exists one with the
same name.

@param RESTClient client Optional custom REST client object.

Create a REST API via a post to the MarkLogic rest - apis endpoint . It will not create an API if there already exists one with the same name .


public function delete($client = null)
    {
        $this->client = $client ?: $this->client;
        // Delete content and modules as well
        $params = array('include' => array('content', 'modules'));
        $body = null;
        $headers = array();
        $request = new RESTRequest(
            'DELETE', 'rest-apis/' . $this->name, $params, $body, $headers
        );

        $this->client->send($request);

        // Wait for server reboot
        $requestWait = new RESTRequest('GET', 'rest-apis');
        $this->waitUntilSuccess($requestWait, 3, 10);
    }

public
function
delete
(
$
client
=
)
{
$
this
->
client
=
$
client
:
$
this
->
client
;
// Delete content and modules as well
$
params
=
array
(
'include'
=>
array
(
'content'
,
'modules'
)
)
;
$
body
=
;
$
headers
=
array
(
)
;
$
request
=
new
RESTRequest
(
'DELETE'
,
'rest-apis/'
.
$
this
->
name
,
$
params
,
$
body
,
$
headers
)
;
$
this
->
client
->
send
(
$
request
)
;
// Wait for server reboot
$
requestWait
=
new
RESTRequest
(
'GET'
,
'rest-apis'
)
;
$
this
->
waitUntilSuccess
(
$
requestWait
,
3
,
10
)
;
}

Delete a REST API.

@param boolean module Optional custom REST client object.


protected function waitUntilSuccess($request, $secs, $limit)
    {
        sleep($secs);
        $limit--;
        try {
            $response = $this->client->send($request);
        } catch(\Exception $e) {
            if ($limit > 0) {
                $this->waitUntilSuccess($request, $secs, $limit);
            } else {
                throw new Exception('waitUntilSuccess() timed out');
            }
        }
        return;
    }

protected
function
waitUntilSuccess
(
$
request
,
$
secs
,
$
limit
)
{
sleep
(
$
secs
)
;
$
limit
;
try
{
$
response
=
$
this
->
client
->
send
(
$
request
)
;
}
catch
(
\
Exception
$
e
)
{
if
(
$
limit
>
0
)
{
$
this
->
waitUntilSuccess
(
$
request
,
$
secs
,
$
limit
)
;
}
else
{
throw
new
Exception
(
'waitUntilSuccess() timed out'
)
;
}
}
return
;
}

Sleep until a request is successful.

@param RESTRequest $request The request to send.
@param int $time Time in secs to wait between requests.
@param int $limit Cycles to complete before timing out.


public function exists()
    {
        try {
            $params = array();
            $body = null;
            $headers = array();
            $request = new RESTRequest(
                'GET', 'rest-apis/' . $this->name, $params, $body, $headers
            );
            $response = $this->client->send($request);
        } catch(\Exception $e) {
            return false;
        }
        return true;
    }

public function exists ( ) { try { $ params = array ( ) ; $ body = null ; $ headers = array ( ) ; $ request = new RESTRequest ( 'GET' , 'rest-apis/' . $ this -> name , $ params , $ body , $ headers ) ; $ response = $ this -> client -> send ( $ request ) ; } catch ( \ Exception $ e ) { return false ; } return true ; }

Check if a REST API with the same name exists on the server.

@param string name Name of the REST API to check.
@return boolean true|false

Check if a REST API with the same name exists on the server .


public function getAsElem($dom)
    {
        $termElem = $dom->createElement('term');
        $emptyElem = $dom->createElement('empty');
        $emptyElem->setAttribute('apply', $this->empty);
        $termElem->appendChild($emptyElem);
        if (!empty($this->termOptions)) {
            foreach($this->termOptions as $opt) {
                $termOptElem = $dom->createElement('term-option');
                $termOptElem->nodeValue = $opt;
                $termElem->appendChild($termOptElem);
            }
        }
        if (!empty($this->default)) {
            $constraint = $this->default->getAsElem($dom);
            /* pluck out child nodes of the <constraint/> */
            if ($constraint->hasChildNodes()) {
                $defElem = $dom->createElement('default');
                foreach ($constraint->childNodes as $child) {
                    if ($child->nodeType == XML_ELEMENT_NODE) {
                        $defElem->appendChild($child);
                    }
                }
                $termElem->appendChild($defElem);
            }
        }
        /* <term>
               <empty apply="no-results" />
               <term-option>diacritic-insensitive</term-option>
               <term-option>unwildcarded</term-option>
               <default>....</default>
            </term> */
        return $termElem;
    }

Get the term as a DOMElement object.

@param DOMDocument $dom The DOMDocument object with which to create the element.


protected function addTermOptions($dom, $elem)
    {
        if (!empty($this->termOptions)) {
            foreach ($this->termOptions as $opt) {
                $termElem = $dom->createElement('term-option');
                $termElem->nodeValue = $opt;
                $elem->appendChild($termElem);
            }
        }
        return $elem;
    }

protected function addTermOptions ( $ dom , $ elem ) { if ( ! empty ( $ this -> termOptions ) ) { foreach ( $ this -> termOptions as $ opt ) { $ termElem = $ dom -> createElement ( 'term-option' ) ; $ termElem -> nodeValue = $ opt ; $ elem -> appendChild ( $ termElem ) ; } } return $ elem ; }

Add term options to an element.

@param DOMDocument $dom A DOM document.
@param DOMElement $elem A DOM element.
@return DOMElement The updated element.


protected function addFacetOptions($dom, $elem)
    {
        if (!empty($this->facetOptions)) {
            foreach ($this->facetOptions as $opt) {
                $facetElem = $dom->createElement('facet-option');
                $facetElem->nodeValue = $opt;
                $elem->appendChild($facetElem);
            }
        }
        return $elem;
    }

protected function addFacetOptions ( $ dom , $ elem ) { if ( ! empty ( $ this -> facetOptions ) ) { foreach ( $ this -> facetOptions as $ opt ) { $ facetElem = $ dom -> createElement ( 'facet-option' ) ; $ facetElem -> nodeValue = $ opt ; $ elem -> appendChild ( $ facetElem ) ; } } return $ elem ; }

Add facet options to an element.

@param DOMDocument $dom A DOM document.
@param DOMElement $elem A DOM element.
@return DOMElement The updated element.


protected function addFragmentScope($dom, $elem)
    {
        if (!empty($this->fragmentScope)) {
            $fragScopeElem = $dom->createElement('fragment-scope');
            $fragScopeElem->nodeValue = $this->fragmentScope;
            $elem->appendChild($fragScopeElem);
        }
        return $elem;
    }

protected function addFragmentScope ( $ dom , $ elem ) { if ( ! empty ( $ this -> fragmentScope ) ) { $ fragScopeElem = $ dom -> createElement ( 'fragment-scope' ) ; $ fragScopeElem -> nodeValue = $ this -> fragmentScope ; $ elem -> appendChild ( $ fragScopeElem ) ; } return $ elem ; }

Add a fragment-scope setting to an element.

@param DOMDocument $dom A DOM document.
@param DOMElement $elem A DOM element.
@return DOMElement The updated element.

Add a fragment - scope setting to an element .


public function setContentFile($file)
    {
        $type = $this->getFileMimeType($file);
        // Check for $type === '' to address MIME check not working on XAMPP Windows
        if ($type === 'image/jpeg' || $type === 'image/tiff' || $type === '') {
            if (function_exists('exif_read_data')) {
                $this->exif = exif_read_data((string)$file);
            }
        }
        parent::setContentFile((string)$file);
    }

Set the image content from the file system and also set the EXIF data.

@param string $file The file location.

Set the image content from the file system and also set the EXIF data .


public function getResultByURI($uri)
    {
        $res = null;
        foreach ($this->results as $result) {
            if ($result->getURI() === $uri) {
                $res = $result;
            }
        }
        return $res;
    }

public function getResultByURI ( $ uri ) { $ res = null ; foreach ( $ this -> results as $ result ) { if ( $ result -> getURI ( ) === $ uri ) { $ res = $ result ; } } return $ res ; }

Get a search result corresponding to a URI.

@param string $uri A document URI.
@return SearchResult A search result object or null if none found.

Get a search result corresponding to a URI .


public function getResultByIndex($index)
    {
        $res = null;
        foreach ($this->results as $result) {
            if ($result->getIndex() == $index) {
                $res = $result;
            }
        }
        return $res;
    }

public function getResultByIndex ( $ index ) { $ res = null ; foreach ( $ this -> results as $ result ) { if ( $ result -> getIndex ( ) == $ index ) { $ res = $ result ; } } return $ res ; }

Get a search result corresponding to an index.

@param int $index A search result index.
@return SearchResult A search result object or null if none found.

Get a search result corresponding to an index .


public function getFacet($name)
    {
        $result = null;
        foreach ($this->facets as $facet) {
            if ($facet->getName() === $name) {
                $result = $facet;
            }
        }
        return $result;
    }

public function getFacet ( $ name ) { $ result = null ; foreach ( $ this -> facets as $ facet ) { if ( $ facet -> getName ( ) === $ name ) { $ result = $ facet ; } } return $ result ; }

Get a facet by its name.

@return array Array of Facet objects.


public function addConstraints($constraints) {
        if (is_array($constraints)) {
            $this->constraints = array_merge($this->constraints, $constraints);
        } else {
            $this->constraints[] = (string)$constraints;
        }
    }

public function addConstraints ( $ constraints ) { if ( is_array ( $ constraints ) ) { $ this -> constraints = array_merge ( $ this -> constraints , $ constraints ) ; } else { $ this -> constraints [ ] = ( string ) $ constraints ; } }

Add constraint metadata.

@param array|string $constraints An array of constraint names or a constraint name.


public function getExtractsAsElem($dom) {
        $extractsElem = $dom->createElement('extract-metadata');
        // constraints
        foreach ($this->constraints as $constraint) {
            $constraintValElem = $dom->createElement('constraint-value');
            $constraintValElem->setAttribute('ref', $constraint);
            $extractsElem->appendChild($constraintValElem);
        }
        // qnames
        foreach ($this->qnames as $qname) {
            $qnameElem = $dom->createElement('qname');
            $qnameElem->setAttribute('elem-name', $qname->getElement());
            $qnameElem->setAttribute('elem-ns', $qname->getNs());
            if($qname->getAttribute() !== '') {
                $qnameElem->setAttribute('attr-name', $qname->getAttribute());
                $qnameElem->setAttribute('attr-ns', $qname->getAttributeNs());
            }
            $extractsElem->appendChild($qnameElem);
        }
        return $extractsElem;
    }

public
function
getExtractsAsElem
(
$
dom
)
{
$
extractsElem
=
$
dom
->
createElement
(
'extract-metadata'
)
;
// constraints
foreach
(
$
this
->
constraints
as
$
constraint
)
{
$
constraintValElem
=
$
dom
->
createElement
(
'constraint-value'
)
;
$
constraintValElem
->
setAttribute
(
'ref'
,
$
constraint
)
;
$
extractsElem
->
appendChild
(
$
constraintValElem
)
;
}
// qnames
foreach
(
$
this
->
qnames
as
$
qname
)
{
$
qnameElem
=
$
dom
->
createElement
(
'qname'
)
;
$
qnameElem
->
setAttribute
(
'elem-name'
,
$
qname
->
getElement
(
)
)
;
$
qnameElem
->
setAttribute
(
'elem-ns'
,
$
qname
->
getNs
(
)
)
;
if
(
$
qname
->
getAttribute
(
)
!==
''
)
{
$
qnameElem
->
setAttribute
(
'attr-name'
,
$
qname
->
getAttribute
(
)
)
;
$
qnameElem
->
setAttribute
(
'attr-ns'
,
$
qname
->
getAttributeNs
(
)
)
;
}
$
extractsElem
->
appendChild
(
$
qnameElem
)
;
}
return
$
extractsElem
;
}

Get the metadata extracts as a DOMElement object.

@param DOMDocument $dom The DOMDocument object in which to create the element.

Get the metadata extracts as a DOMElement object .


public function addPreferredElements($elements)
    {
        if (is_array($elements)) {
            $this->preferredElements = array_merge($this->preferredElements, $elements);
        } else {
            $this->preferredElements[] = $elements;
        }
    }

public function addPreferredElements ( $ elements ) { if ( is_array ( $ elements ) ) { $ this -> preferredElements = array_merge ( $ this -> preferredElements , $ elements ) ; } else { $ this -> preferredElements [ ] = $ elements ; } }

Add one or more preferred elements for snippetting.

@param array|string $elements An array of preferred-element objects or a single preferred-element object.

Add one or more preferred elements for snippetting .


public function getTransformResultsAsElem($dom)
    {
        $transElem = $dom->createElement('transform-results');
        $transElem->setAttribute('apply', $this->apply);
        $prefElem = $dom->createElement('preferred-elements');
        // preferred elements
        foreach ($this->preferredElements as $elem) {
            $element = $dom->createElement('element');
            $element->setAttribute('name', $elem->getElement());
            $element->setAttribute('ns', $elem->getElementNs());
            $prefElem->appendChild($element);
        }
        $transElem->appendChild($prefElem);
        return $transElem;
    }

public
function
getTransformResultsAsElem
(
$
dom
)
{
$
transElem
=
$
dom
->
createElement
(
'transform-results'
)
;
$
transElem
->
setAttribute
(
'apply'
,
$
this
->
apply
)
;
$
prefElem
=
$
dom
->
createElement
(
'preferred-elements'
)
;
// preferred elements
foreach
(
$
this
->
preferredElements
as
$
elem
)
{
$
element
=
$
dom
->
createElement
(
'element'
)
;
$
element
->
setAttribute
(
'name'
,
$
elem
->
getElement
(
)
)
;
$
element
->
setAttribute
(
'ns'
,
$
elem
->
getElementNs
(
)
)
;
$
prefElem
->
appendChild
(
$
element
)
;
}
$
transElem
->
appendChild
(
$
prefElem
)
;
return
$
transElem
;
}

Get the results transformation settings as a DOMElement object.

@param DOMDocument $dom The DOMDocument object in which to create the element.

Get the results transformation settings as a DOMElement object .


public function addCollections($collections)
    {
        if (is_array($collections)) {
            $this->collections = array_merge($this->collections, $collections);
        } else {
            $this->collections[] = (string)$collections;
        }
        return $this;
    }

public function addCollections ( $ collections ) { if ( is_array ( $ collections ) ) { $ this -> collections = array_merge ( $ this -> collections , $ collections ) ; } else { $ this -> collections [ ] = ( string ) $ collections ; } return $ this ; }

Add collections metadata.

@param array|string $collections An array of collection strings or a collection string.
@return Metadata $this


public function deleteCollections($collections)
    {
        if (is_array($collections)) {
            foreach($collections as $coll) {
                $pos = array_search($coll, $this->collections);
                if($pos !== FALSE) {
                    array_splice($this->collections, $pos, 1);
                }
            }
        } else {
            $pos = array_search($collections, $this->collections);
            if($pos !== FALSE) {
                array_splice($this->collections, $pos, 1);
            }
        }
        return $this;
    }

public function deleteCollections ( $ collections ) { if ( is_array ( $ collections ) ) { foreach ( $ collections as $ coll ) { $ pos = array_search ( $ coll , $ this -> collections ) ; if ( $ pos !== FALSE ) { array_splice ( $ this -> collections , $ pos , 1 ) ; } } } else { $ pos = array_search ( $ collections , $ this -> collections ) ; if ( $ pos !== FALSE ) { array_splice ( $ this -> collections , $ pos , 1 ) ; } } return $ this ; }

Delete collections metadata.

@param array|string $collections An array of collection strings or a collection string.
@return Metadata $this


public function addPermissions($permissions)
    {
        if (is_array($permissions)) {
            foreach($permissions as $perm) {
                $this->permissions[$perm->getRoleName()] = $perm;
            }
        } else {
            $this->permissions[$permissions->getRoleName()] = $permissions;
        }
        return $this;
    }

public function addPermissions ( $ permissions ) { if ( is_array ( $ permissions ) ) { foreach ( $ permissions as $ perm ) { $ this -> permissions [ $ perm -> getRoleName ( ) ] = $ perm ; } } else { $ this -> permissions [ $ permissions -> getRoleName ( ) ] = $ permissions ; } return $ this ; }

Add permissions metadata.

@param array|Permission $permissions An array of Permission objects or a Permission object.
@return Metadata $this


public function deletePermissions($roleNames)
    {
        if (is_array($roleNames)) {
            foreach($roleNames as $name) {
                unset($this->permissions[$name]);
            }
        } else {
            unset($this->permissions[$roleNames]);
        }
        return $this;
    }

public function deletePermissions ( $ roleNames ) { if ( is_array ( $ roleNames ) ) { foreach ( $ roleNames as $ name ) { unset ( $ this -> permissions [ $ name ] ) ; } } else { unset ( $ this -> permissions [ $ roleNames ] ) ; } return $ this ; }

Delete permissions metadata.

@param array|string $roleNames An array of role names or a role name string.
@return Metadata $this


public function deleteProperties($properties)
    {
        if (is_array($properties)) {
            foreach($properties as $prop) {
                unset($this->properties[$prop]);
            }
        } else {
            unset($this->properties[$properties]);
        }
        return $this;
    }

public function deleteProperties ( $ properties ) { if ( is_array ( $ properties ) ) { foreach ( $ properties as $ prop ) { unset ( $ this -> properties [ $ prop ] ) ; } } else { unset ( $ this -> properties [ $ properties ] ) ; } return $ this ; }

Delete property metadata.

@param array|string $properties An array of property keys or a property key.
@return Metadata $this


public function getAsXML()
    {

        // root
        $dom = new \DOMDocument();
        $root = $dom->createElement('metadata');
        $root->setAttribute('xmlns', 'http://marklogic.com/rest-api');
        $dom->appendChild($root);

        // collections
        $collElem = $dom->createElement('collections');
        foreach($this->collections as $v) {
            $collElem->appendChild($dom->createElement('collection', $v));
        }
        $root->appendChild($collElem);

        // permissions
        $permElem = $dom->createElement('permissions');
        foreach($this->permissions as $rn => $p) {
            $pElem = $dom->createElement('permission');
            $pElem->appendChild($dom->createElement('role-name', $p->getRoleName()));
            foreach($p->getCapabilities() as $c) {
                $pElem->appendChild($dom->createElement('capability', $c));
            }
            $permElem->appendChild($pElem);
        }
        $root->appendChild($permElem);

        // properties
        $propElem = $dom->createElement('prop:properties');
        $propElem->setAttribute('xmlns:prop', 'http://marklogic.com/xdmp/property');
        foreach($this->properties as $k => $v) {
            $pElem = $dom->createElement($k, $v);
            $pElem->setAttribute('xmlns', '');
            $propElem->appendChild($pElem);
        }
        $root->appendChild($propElem);

        // quality
        if(!empty($this->quality)) {
            $qElem = $dom->createElement('quality', $this->quality);
            $root->appendChild($qElem);
        }

        return $dom->saveXML();
    }

public
function
getAsXML
(
)
{
// root
$
dom
=
new
\
DOMDocument
(
)
;
$
root
=
$
dom
->
createElement
(
'metadata'
)
;
$
root
->
setAttribute
(
'xmlns'
,
'http://marklogic.com/rest-api'
)
;
$
dom
->
appendChild
(
$
root
)
;
// collections
$
collElem
=
$
dom
->
createElement
(
'collections'
)
;
foreach
(
$
this
->
collections
as
$
v
)
{
$
collElem
->
appendChild
(
$
dom
->
createElement
(
'collection'
,
$
v
)
)
;
}
$
root
->
appendChild
(
$
collElem
)
;
// permissions
$
permElem
=
$
dom
->
createElement
(
'permissions'
)
;
foreach
(
$
this
->
permissions
as
$
rn
=>
$
p
)
{
$
pElem
=
$
dom
->
createElement
(
'permission'
)
;
$
pElem
->
appendChild
(
$
dom
->
createElement
(
'role-name'
,
$
p
->
getRoleName
(
)
)
)
;
foreach
(
$
p
->
getCapabilities
(
)
as
$
c
)
{
$
pElem
->
appendChild
(
$
dom
->
createElement
(
'capability'
,
$
c
)
)
;
}
$
permElem
->
appendChild
(
$
pElem
)
;
}
$
root
->
appendChild
(
$
permElem
)
;
// properties
$
propElem
=
$
dom
->
createElement
(
'prop:properties'
)
;
$
propElem
->
setAttribute
(
'xmlns:prop'
,
'http://marklogic.com/xdmp/property'
)
;
foreach
(
$
this
->
properties
as
$
k
=>
$
v
)
{
$
pElem
=
$
dom
->
createElement
(
$
k
,
$
v
)
;
$
pElem
->
setAttribute
(
'xmlns'
,
''
)
;
$
propElem
->
appendChild
(
$
pElem
)
;
}
$
root
->
appendChild
(
$
propElem
)
;
// quality
if
(
!
empty
(
$
this
->
quality
)
)
{
$
qElem
=
$
dom
->
createElement
(
'quality'
,
$
this
->
quality
)
;
$
root
->
appendChild
(
$
qElem
)
;
}
return
$
dom
->
saveXML
(
)
;
}

Get the metadata object as XML.

@return string The metadata as XML.


public function loadFromXML($xml)
    {

        // root
        $dom = new \DOMDocument();
        $dom->loadXML($xml);

        // collections
        $collElems = $dom->getElementsByTagName('collections')->item(0)->getElementsByTagName('collection');
        foreach ($collElems as $elem) {
            if($elem->nodeType === XML_ELEMENT_NODE) {
                $this->addCollections($elem->nodeValue);
            }
        }

        // permissions
        $permElems = $dom->getElementsByTagName('permissions')->item(0)->getElementsByTagName('permission');
        $permissions = array();
        foreach($permElems as $elem) {
            if($elem->nodeType === XML_ELEMENT_NODE) {
                $role_name = $elem->getElementsByTagName('role-name')->item(0)->nodeValue;
                $capElems = $elem->getElementsByTagName('capability');
                $capabilities = array();
                foreach($capElems as $c) {
                    $capabilities[] = $c->nodeValue;
                }
                $permission = new Permission($role_name, $capabilities);
                $permissions[] = $permission;
            }
        }
        $this->addPermissions($permissions);

        // properties
        $propElems = $dom->getElementsByTagName('properties')->item(0)->childNodes;
        foreach($propElems as $elem) {
            if($elem->nodeType === XML_ELEMENT_NODE) {
                $this->addProperties(array($elem->tagName => $elem->nodeValue));
            }
        }

        // quality
        $qElem = $dom->getElementsByTagName('quality')->item(0);
        $this->setQuality($qElem->nodeValue);

        return $this;
    }

public
function
loadFromXML
(
$
xml
)
{
// root
$
dom
=
new
\
DOMDocument
(
)
;
$
dom
->
loadXML
(
$
xml
)
;
// collections
$
collElems
=
$
dom
->
getElementsByTagName
(
'collections'
)
->
item
(
0
)
->
getElementsByTagName
(
'collection'
)
;
foreach
(
$
collElems
as
$
elem
)
{
if
(
$
elem
->
nodeType
===
XML_ELEMENT_NODE
)
{
$
this
->
addCollections
(
$
elem
->
nodeValue
)
;
}
}
// permissions
$
permElems
=
$
dom
->
getElementsByTagName
(
'permissions'
)
->
item
(
0
)
->
getElementsByTagName
(
'permission'
)
;
$
permissions
=
array
(
)
;
foreach
(
$
permElems
as
$
elem
)
{
if
(
$
elem
->
nodeType
===
XML_ELEMENT_NODE
)
{
$
role_name
=
$
elem
->
getElementsByTagName
(
'role-name'
)
->
item
(
0
)
->
nodeValue
;
$
capElems
=
$
elem
->
getElementsByTagName
(
'capability'
)
;
$
capabilities
=
array
(
)
;
foreach
(
$
capElems
as
$
c
)
{
$
capabilities
[
]
=
$
c
->
nodeValue
;
}
$
permission
=
new
Permission
(
$
role_name
,
$
capabilities
)
;
$
permissions
[
]
=
$
permission
;
}
}
$
this
->
addPermissions
(
$
permissions
)
;
// properties
$
propElems
=
$
dom
->
getElementsByTagName
(
'properties'
)
->
item
(
0
)
->
childNodes
;
foreach
(
$
propElems
as
$
elem
)
{
if
(
$
elem
->
nodeType
===
XML_ELEMENT_NODE
)
{
$
this
->
addProperties
(
array
(
$
elem
->
tagName
=>
$
elem
->
nodeValue
)
)
;
}
}
// quality
$
qElem
=
$
dom
->
getElementsByTagName
(
'quality'
)
->
item
(
0
)
;
$
this
->
setQuality
(
$
qElem
->
nodeValue
)
;
return
$
this
;
}

Load the metadata object from XML.

@param string $xml The metadata as XML.
@return Metadata $this


public function enable($rootNamespace = self::ROOT_NAMESPACE_GLOBAL)
    {
        // If XStatic is already enabled, this is a no-op
        if ($this->aliasLoader->isRegistered()) {
            return true;
        }

        // Register the loader to handle aliases and link the proxies to the container
        if ($this->aliasLoader->register($rootNamespace)) {
            StaticProxy::setContainer($this->container);
        }

        return $this->aliasLoader->isRegistered();
    }

Enables the Static Proxies by injecting the Container object and registering the Alias Loader for autoloading

@param bool|string $rootNamespace The namespace that the alias should be created in

@return bool
@see \XStatic\AliasLoaderInterface::register()


public function setContainer(ContainerInterface $container)
    {
        $this->container = $container;
        StaticProxy::setContainer($this->container);

        return $this;
    }

public function setContainer ( ContainerInterface $ container ) { $ this -> container = $ container ; StaticProxy :: setContainer ( $ this -> container ) ; return $ this ; }

Sets the Container object that provides the actual subjects' instances

@param ContainerInterface $container Instance of a Container (or Service Locator)

@return $this

Sets the Container object that provides the actual subjects instances


protected function _compareConstraints(array $fixtureConstraints, array $liveConstraints, $fixtureTable) {
		if (!$fixtureConstraints && !$liveConstraints) {
			return;
		}

		$fixtureConstraints = $this->normalizeConstraints($fixtureConstraints);
		$liveConstraints = $this->normalizeConstraints($liveConstraints);

		if ($fixtureConstraints === $liveConstraints) {
			return;
		}

		$errors = [];
		foreach ($liveConstraints as $key => $liveConstraint) {
			if (!isset($fixtureConstraints[$key])) {
				$errors[] = ' * ' . sprintf('Constraint %s is missing in fixture, but in live DB.', $this->_buildKey($key, $liveConstraint));
				continue;
			}

			if ($liveConstraint === $fixtureConstraints[$key]) {
				unset($fixtureConstraints[$key]);
				continue;
			}

			$errors[] = ' * ' . sprintf('Live DB constraint %s is not matching fixture one: %s.', $this->_buildKey($key, $liveConstraint), json_encode($fixtureConstraints[$key], true));
			unset($fixtureConstraints[$key]);
		}

		foreach ($fixtureConstraints as $key => $fixtureConstraint) {
			$errors[] = ' * ' . sprintf('Constraint %s is in fixture, but not live DB.', $this->_buildKey($key, $fixtureConstraint));
		}

		if (!$errors) {
			return;
		}

		$this->warn('The following constraints mismatch:');

		$this->out($errors);
		$this->_issuesFound[] = $fixtureTable;
		$this->out($this->nl(0));
	}

Compare the constraints present.

@param array $fixtureConstraints
@param array $liveConstraints
@param string $fixtureTable

@return void


protected function _compareIndexes(array $fixtureIndexes, array $liveIndexes, $fixtureTable) {
		if (!$fixtureIndexes && !$liveIndexes) {
			return;
		}

		if ($fixtureIndexes === $liveIndexes) {
			return;
		}

		$errors = [];
		foreach ($liveIndexes as $key => $liveIndex) {
			if (!isset($fixtureIndexes[$key])) {
				$errors[] = ' * ' . sprintf('Index %s is missing in fixture', $this->_buildKey($key, $liveIndex));
				continue;
			}

			if ($liveIndex === $fixtureIndexes[$key]) {
				unset($fixtureIndexes[$key]);
				continue;
			}

			$errors[] = ' * ' . sprintf('Live DB index %s is not matching fixture one.', $this->_buildKey($key, $liveIndex));
			unset($fixtureIndexes[$key]);
		}

		foreach ($fixtureIndexes as $key => $fixtureIndex) {
			$errors[] = ' * ' . sprintf('Index %s is in fixture, but not live DB.', $this->_buildKey($key, $fixtureIndex));
		}

		if (!$errors) {
			return;
		}

		$this->warn('The following indexes mismatch:');

		$this->out($errors);
		$this->_issuesFound[] = $fixtureTable;
		$this->out($this->nl(0));
	}

Compare the indexes present.

@param array $fixtureIndexes
@param array $liveIndexes
@param string $fixtureTable

@return void


protected function _doCompareFieldPresence($one, $two, $fixtureClass, $message, $fixtureTable) {
		$diff = array_diff_key($one, $two);
		if (!empty($diff)) {
			$this->warn(sprintf($message, $fixtureClass));
			foreach ($diff as $missingField => $type) {
				$this->out(' * ' . $missingField);
			}
			$this->out($this->nl(0));
			$this->_issuesFound[] = $fixtureTable;
		}
	}

protected
function
_doCompareFieldPresence
(
$
one
,
$
two
,
$
fixtureClass
,
$
message
,
$
fixtureTable
)
{
$
diff
=
array_diff_key
(
$
one
,
$
two
)
;
if
(
!
empty
(
$
diff
)
)
{
$
this
->
warn
(
sprintf
(
$
message
,
$
fixtureClass
)
)
;
foreach
(
$
diff
as
$
missingField
=>
$
type
)
{
$
this
->
out
(
' * '
.
$
missingField
)
;
}
$
this
->
out
(
$
this
->
nl
(
0
)
)
;
$
this
->
_issuesFound
[
]
=
$
fixtureTable
;
}
}

Compare if the fields are present in the fixtures.

@param array $one Array one
@param array $two Array two
@param string $fixtureClass Fixture class name.
@param string $message Message to display.
@param string $fixtureTable

@return void

Compare if the fields are present in the fixtures .


protected function _getFixtureFiles() {
		$fixtureFolder = TESTS . 'Fixture' . DS;
		$plugin = $this->param('plugin');
		if ($plugin) {
			$fixtureFolder = Plugin::path($plugin) . 'tests' . DS . 'Fixture' . DS;
		}

		$folder = new Folder($fixtureFolder);
		$content = $folder->read();

		$fixtures = [];
		foreach ($content[1] as $file) {
			$fixture = substr($file, 0, -4);
			if (substr($fixture, -7) !== 'Fixture') {
				continue;
			}
			$fixtures[] = $fixture;
		}

		return $fixtures;
	}

protected function _getFixtureFiles ( ) { $ fixtureFolder = TESTS . 'Fixture' . DS ; $ plugin = $ this -> param ( 'plugin' ) ; if ( $ plugin ) { $ fixtureFolder = Plugin :: path ( $ plugin ) . 'tests' . DS . 'Fixture' . DS ; } $ folder = new Folder ( $ fixtureFolder ) ; $ content = $ folder -> read ( ) ; $ fixtures = [ ] ; foreach ( $ content [ 1 ] as $ file ) { $ fixture = substr ( $ file , 0 , - 4 ) ; if ( substr ( $ fixture , - 7 ) !== 'Fixture' ) { continue ; } $ fixtures [ ] = $ fixture ; } return $ fixtures ; }

Gets a list of fixture files.

@return array Array of fixture files


protected function _compareFieldPresence($fixtureFields, $liveFields, $fixtureClass, $fixtureTable) {
		$message = '%s has fields that are not in the live DB:';
		$this->_doCompareFieldPresence($fixtureFields, $liveFields, $fixtureClass, $message, $fixtureTable);

		$message = 'Live DB has fields that are not in %s';
		$this->_doCompareFieldPresence($liveFields, $fixtureFields, $fixtureClass, $message, $fixtureTable);
	}

Compare the fields present.

@param array $fixtureFields The fixtures fields array.
@param array $liveFields The live DB fields
@param string $fixtureClass Fixture class name.
@param string $fixtureTable

@return void


protected function form($type = self::FORM_VERTICAL, $inputClass = '', $labelClass = '') {
		$this->formType = $type;
		$this->inputClass = $inputClass;
		$this->labelClass = $labelClass;
	}

protected function form ( $ type = self :: FORM_VERTICAL , $ inputClass = '' , $ labelClass = '' ) { $ this -> formType = $ type ; $ this -> inputClass = $ inputClass ; $ this -> labelClass = $ labelClass ; }

Set the form type

@param string $type
@param string $inputClass
@param string $labelClass

@return void


public function horizontal($inputClass = '', $labelClass = '') {
		$this->form(self::FORM_HORIZONTAL, $inputClass, $labelClass);

		return $this;
	}

public function horizontal ( $ inputClass = '' , $ labelClass = '' ) { $ this -> form ( self :: FORM_HORIZONTAL , $ inputClass , $ labelClass ) ; return $ this ; }

Set the form type to horizontal

@param string $inputClass
@param string $labelClass

@return self


protected function label($name, $label = null, array $options = array(), $content = null) {
		$return = '';
		$options = array_merge(array('class' => 'control-label ' . $this->labelClass, 'for' => (!$content ? $name : null)), $options);

		if ($label !== null) {
			$return .= '<label' . $this->html->attributes($options) . '>' . $content . ucwords(str_replace('_', ' ', $label)) . '</label>' . "\n";
		}

		return $return;
	}

protected
function
label
(
$
name
,
$
label
=
,
array
$
options
=
array
(
)
,
$
content
=
)
{
$
return
=
''
;
$
options
=
array_merge
(
array
(
'class'
=>
'control-label '
.
$
this
->
labelClass
,
'for'
=>
(
!
$
content
$
name
:
)
)
,
$
options
)
;
if
(
$
label
!==
)
{
$
return
.=
'<label'
.
$
this
->
html
->
attributes
(
$
options
)
.
'>'
.
$
content
.
ucwords
(
str_replace
(
'_'
,
' '
,
$
label
)
)
.
'</label>'
.
"\n"
;
}
return
$
return
;
}

Create a form label field.

@param string $name
@param string $label
@param array  $options
@param string $content

@return string


protected function errors($name, $errors = null, $wrap = ':message') {
		$return = '';

		if ($errors && $errors->has($name)) {
			$return .= $errors->first($name, $wrap) . "\n";
		}

		return $return;
	}

Create a form error helper field.

@param string                         $name
@param \Illuminate\Support\MessageBag $errors
@param string                         $wrap

@return string


protected function group($name, $errors = null, $class = 'form-group', array $options = array())
	{
		$options = array_merge(array('class' => $class), $options);
		$options['class'] .= ($errors && $errors->has($name) ? ' has-error' : '');
		$return = '<div' . $this->html->attributes($options) . '>' . "\n";

		return $return;
	}

protected
function
group
(
$
name
,
$
errors
=
,
$
class
=
'form-group'
,
array
$
options
=
array
(
)
)
{
$
options
=
array_merge
(
array
(
'class'
=>
$
class
)
,
$
options
)
;
$
options
[
'class'
]
.=
(
$
errors
&&
$
errors
->
has
(
$
name
)
' has-error'
:
''
)
;
$
return
=
'<div'
.
$
this
->
html
->
attributes
(
$
options
)
.
'>'
.
"\n"
;
return
$
return
;
}

Create a form group element.

@param string                         $name
@param \Illuminate\Support\MessageBag $errors
@param string                         $class
@param array                          $options

@return string


protected function action($type, $value, array $attributes = array())
	{
		$return = '';
		$containerAttributes = $this->getContainerAttributes($attributes);

		switch ($type) {
			case 'submit':
				$attributes = array_merge(array('class' => 'btn btn-primary pull-right'), $attributes);
				break;
			case 'button':
			case 'reset':
			default:
				$attributes = array_merge(array('class' => 'btn btn-default'), $attributes);
		}

		if (!isset($containerAttributes['display'])) {
			$return .= $this->group('', null, 'form-group', $containerAttributes);
		}

		if ($this->formType == self::FORM_HORIZONTAL) {
			$return .= $this->group('', null, $this->inputClass);
		}

		$return .= $this->form->$type($value, $attributes) . "\n";

		if ($this->formType == self::FORM_HORIZONTAL) {
			$return .= '
' . "\n";
		}

		if (!isset($containerAttributes['display'])) {
			$return .= '
' . "\n";
		}

		return $return;
	}

protected
function
action
(
$
type
,
$
value
,
array
$
attributes
=
array
(
)
)
{
$
return
=
''
;
$
containerAttributes
=
$
this
->
getContainerAttributes
(
$
attributes
)
;
switch
(
$
type
)
{
case
'submit'
:
$
attributes
=
array_merge
(
array
(
'class'
=>
'btn btn-primary pull-right'
)
,
$
attributes
)
;
break
;
case
'button'
:
case
'reset'
:
default
:
$
attributes
=
array_merge
(
array
(
'class'
=>
'btn btn-default'
)
,
$
attributes
)
;
}
if
(
!
isset
(
$
containerAttributes
[
'display'
]
)
)
{
$
return
.=
$
this
->
group
(
''
,
,
'form-group'
,
$
containerAttributes
)
;
}
if
(
$
this
->
formType
==
self
::
FORM_HORIZONTAL
)
{
$
return
.=
$
this
->
group
(
''
,
,
$
this
->
inputClass
)
;
}
$
return
.=
$
this
->
form
->
$
type
(
$
value
,
$
attributes
)
.
"\n"
;
if
(
$
this
->
formType
==
self
::
FORM_HORIZONTAL
)
{
$
return
.=
'
'
.
"\n"
;
}
if
(
!
isset
(
$
containerAttributes
[
'display'
]
)
)
{
$
return
.=
'
'
.
"\n"
;
}
return
$
return
;
}

Create a form action button.

@param string $value
@param string $type
@param array  $attributes

@return string


protected function hyperlink($type, $location, $title = null, array $parameters = array(), array $attributes = array(), $secure = null)
	{
		$attributes = array_merge(array('class' => 'btn btn-default'), $attributes);

		switch ($type) {
			case 'linkRoute':
			case 'linkAction':
				$return = $this->html->$type($location, $title, $parameters, $attributes);
				break;
			case 'mailto':
				$return = $this->html->$type($location, $title, $attributes);
				break;
			case 'link':
			case 'secureLink':
			default:
				$return = $this->html->$type($location, $title, $attributes, $secure);
		}

		return $return;
	}

protected
function
hyperlink
(
$
type
,
$
location
,
$
title
=
,
array
$
parameters
=
array
(
)
,
array
$
attributes
=
array
(
)
,
$
secure
=
)
{
$
attributes
=
array_merge
(
array
(
'class'
=>
'btn btn-default'
)
,
$
attributes
)
;
switch
(
$
type
)
{
case
'linkRoute'
:
case
'linkAction'
:
$
return
=
$
this
->
html
->
$
type
(
$
location
,
$
title
,
$
parameters
,
$
attributes
)
;
break
;
case
'mailto'
:
$
return
=
$
this
->
html
->
$
type
(
$
location
,
$
title
,
$
attributes
)
;
break
;
case
'link'
:
case
'secureLink'
:
default
:
$
return
=
$
this
->
html
->
$
type
(
$
location
,
$
title
,
$
attributes
,
$
secure
)
;
}
return
$
return
;
}

Create a button link.

@param string $type
@param string $location
@param string $title
@param array  $parameters
@param string $secure
@param array  $attributes

@return string


protected function alert($type = 'message', $content = null, $emphasis = null, $dismissible = false, array $attributes = array())
	{
		$attributes = array_merge(array('class' => 'alert' . ($dismissible ? ' alert-dismissable' : '') . ' alert-' . ($type != 'message' ? $type : 'default')), $attributes);
		$return = '
html->attributes($attributes) . '>';

		if ($dismissible !== false) {
			$return .= '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
		}

		$return .= ($emphasis !== null && is_string($emphasis) ? '' . $emphasis . ' ' : '') . $content . '
';

		return $return;
	}

Create an alert item with optional emphasis.

@param string  $type
@param string  $content
@param string  $emphasis
@param boolean $dismissible
@param array   $attributes

@return string

Create an alert item with optional emphasis .


public function password($name, $label = null, $errors = null, array $options = array())
	{
		return $this->input('password', $name, $label, null, $errors, $options);
	}

public function password ( $ name , $ label = null , $ errors = null , array $ options = array ( ) ) { return $ this -> input ( 'password' , $ name , $ label , null , $ errors , $ options ) ; }

Create a form password field.

@param string                         $name
@param string                         $label
@param \Illuminate\Support\MessageBag $errors
@param array                          $options

@return string


public function file($name, $label = null, $errors = null, array $options = array())
	{
		return $this->input('file', $name, $label, null, $errors, $options);
	}

public function file ( $ name , $ label = null , $ errors = null , array $ options = array ( ) ) { return $ this -> input ( 'file' , $ name , $ label , null , $ errors , $ options ) ; }

Create a form file field.

@param string                         $name
@param string                         $label
@param \Illuminate\Support\MessageBag $errors
@param array                          $options

@return string


public function link($url, $title = null, array $attributes = array(), $secure = null)
	{
		return $this->hyperlink('link', $url, $title, $parameters = array(), $attributes, $secure);
	}

public function link ( $ url , $ title = null , array $ attributes = array ( ) , $ secure = null ) { return $ this -> hyperlink ( 'link' , $ url , $ title , $ parameters = array ( ) , $ attributes , $ secure ) ; }

Create a button link to url.

@param string $url
@param string $title
@param array  $attributes
@param string $secure

@return string


public function secureLink($url, $title = null, array $attributes = array(), $secure = null)
	{
		return $this->hyperlink('secureLink', $url, $title, array(), $attributes, $secure);
	}

public function secureLink ( $ url , $ title = null , array $ attributes = array ( ) , $ secure = null ) { return $ this -> hyperlink ( 'secureLink' , $ url , $ title , array ( ) , $ attributes , $ secure ) ; }

Create a secure button link to url.

@param string $url
@param string $title
@param array  $attributes
@param string $secure

@return string


public function linkRoute($name, $title = null, array $parameters = array(), array $attributes = array())
	{
		return $this->hyperlink('linkRoute', $name, $title, $parameters, $attributes, null);
	}

public function linkRoute ( $ name , $ title = null , array $ parameters = array ( ) , array $ attributes = array ( ) ) { return $ this -> hyperlink ( 'linkRoute' , $ name , $ title , $ parameters , $ attributes , null ) ; }

Create a button link to route.

@param string $name
@param string $title
@param array  $parameters
@param array  $attributes

@return string


public function linkAction($action, $title = null, array $parameters = array(), array $attributes = array())
	{
		return $this->hyperlink('linkAction', $action, $title, $parameters, $attributes, null);
	}

public function linkAction ( $ action , $ title = null , array $ parameters = array ( ) , array $ attributes = array ( ) ) { return $ this -> hyperlink ( 'linkAction' , $ action , $ title , $ parameters , $ attributes , null ) ; }

Create a button link to action.

@param string $action
@param string $title
@param array  $parameters
@param array  $attributes

@return string


public function mailto($email, $title = null, array $attributes = array())
	{
		return $this->hyperlink('mailto', $email, $title, array(), $attributes, null);
	}

public function mailto ( $ email , $ title = null , array $ attributes = array ( ) ) { return $ this -> hyperlink ( 'mailto' , $ email , $ title , array ( ) , $ attributes , null ) ; }

Create a button link to an email address.

@param string $email
@param string $title
@param array  $attributes

@return string

Create a button link to an email address .


public function none($content = null, $emphasis = null, $dismissible = false, array $attributes = array())
	{
		return $this->alert('message', $content, $emphasis, $dismissible, $attributes);
	}

public function none ( $ content = null , $ emphasis = null , $ dismissible = false , array $ attributes = array ( ) ) { return $ this -> alert ( 'message' , $ content , $ emphasis , $ dismissible , $ attributes ) ; }

Create a none alert item.

@param string  $content
@param string  $emphasis
@param boolean $dismissible
@param array   $attributes

@return string


private static function execReplace($pattern, $replacement, $subject, $option)
    {
        return (\is_object($replacement) || \is_array($replacement)) && \is_callable($replacement)
            ? \mb_ereg_replace_callback($pattern, $replacement, $subject, $option)
            : \mb_ereg_replace($pattern, $replacement, $subject, $option);
    }

private static function execReplace ( $ pattern , $ replacement , $ subject , $ option ) { return ( \ is_object ( $ replacement ) || \ is_array ( $ replacement ) ) && \ is_callable ( $ replacement ) ? \ mb_ereg_replace_callback ( $ pattern , $ replacement , $ subject , $ option ) : \ mb_ereg_replace ( $ pattern , $ replacement , $ subject , $ option ) ; }

Replace subject by callback or by string.

@param string          $pattern     Pattern
@param callable|string $replacement Replacement
@param string          $subject     Subject
@param string          $option      Option
@return string Replaced subject

Replace subject by callback or by string .


public function getShortMessage()
    {
        $msg = $this->getMessage();
        if (\strpos($msg, '(): ') !== false) {
            list(, $msg) = \explode('(): ', $msg);
        }

        return $msg;
    }

public
function
getShortMessage
(
)
{
$
msg
=
$
this
->
getMessage
(
)
;
if
(
\
strpos
(
$
msg
,
'(): '
)
!==
false
)
{
list
(
,
$
msg
)
=
\
explode
(
'(): '
,
$
msg
)
;
}
return
$
msg
;
}

Return exception message without function name.

Usual exception message looks like this:
<pre>
preg_match(): Some error occurred
</pre>
So we strip the "function(): " part.

@return string

Return exception message without function name .


public function get($type, $key)
    {
        $redisKey = "{$this->prefix}.$type.$key";
        $value = $this->redis->get($redisKey);

        if (is_null($value)) {
            return null;
        }

        return unserialize($value);
    }

public function get ( $ type , $ key ) { $ redisKey = "{$this->prefix}.$type.$key" ; $ value = $ this -> redis -> get ( $ redisKey ) ; if ( is_null ( $ value ) ) { return null ; } return unserialize ( $ value ) ; }

Retrieve a value from Redis

@param string $type The datatype
@param string $key  The key
@return mixed|NULL  The value


public function set($type, $key, $value, $expire = null)
    {
        $redisKey = "{$this->prefix}.$type.$key";
        $this->redis->set($redisKey, serialize($value));

        if (is_null($expire)) {
            $expire = time() + $this->lifeTime;
        }
        $this->redis->expireat($redisKey, $expire);
    }

public function set ( $ type , $ key , $ value , $ expire = null ) { $ redisKey = "{$this->prefix}.$type.$key" ; $ this -> redis -> set ( $ redisKey , serialize ( $ value ) ) ; if ( is_null ( $ expire ) ) { $ expire = time ( ) + $ this -> lifeTime ; } $ this -> redis -> expireat ( $ redisKey , $ expire ) ; }

Save a value to Redis

If no expiration time is given, then the expiration time is set to the
session duration.

@param string $type     The datatype
@param string $key      The key
@param mixed $value     The value
@param int|NULL $expire The expiration time (unix timestamp), or NULL if it never expires


public function actionRemoveBasket()
    {
        $rr = new RequestResponse();

        if ($rr->isRequestAjaxPost()) {
            $basket_id = \Yii::$app->request->post('basket_id');

            $shopBasket = ShopOrderItem::find()->where(['id' => $basket_id])->one();
            if ($shopBasket) {
                if ($shopBasket->delete()) {
                    $rr->success = true;
                    $rr->message = \Yii::t('skeeks/shop/app', 'Position successfully removed');
                }
            }

            \Yii::$app->shop->cart->shopOrder->link('cmsSite', \Yii::$app->cms->site);
            $rr->data = \Yii::$app->shop->cart->shopOrder->jsonSerialize();
            return (array)$rr;
        } else {
            return $this->goBack();
        }
    }

public
function
actionRemoveBasket
(
)
{
$
rr
=
new
RequestResponse
(
)
;
if
(
$
rr
->
isRequestAjaxPost
(
)
)
{
$
basket_id
=
\
Yii
::
$
app
->
request
->
post
(
'basket_id'
)
;
$
shopBasket
=
ShopOrderItem
::
find
(
)
->
where
(
[
'id'
=>
$
basket_id
]
)
->
one
(
)
;
if
(
$
shopBasket
)
{
if
(
$
shopBasket
->
delete
(
)
)
{
$
rr
->
success
=
true
;
$
rr
->
message
=
\
Yii
::
t
(
'skeeks/shop/app'
,
'Position successfully removed'
)
;
}
}
\
Yii
::
$
app
->
shop
->
cart
->
shopOrder
->
link
(
'cmsSite'
,
\
Yii
::
$
app
->
cms
->
site
)
;
$
rr
->
data
=
\
Yii
::
$
app
->
shop
->
cart
->
shopOrder
->
jsonSerialize
(
)
;
return
(
array
)
$
rr
;
}
else
{
return
$
this
->
goBack
(
)
;
}
}

Removing the basket position

@return array|\yii\web\Response
@throws \Exception


public function actionClear()
    {
        $rr = new RequestResponse();

        if ($rr->isRequestAjaxPost()) {
            foreach (\Yii::$app->shop->cart->shopOrder->shopOrderItems as $basket) {
                $basket->delete();
            }

            \Yii::$app->shop->cart->shopOrder->link('cmsSite', \Yii::$app->cms->site);
            $rr->data = \Yii::$app->shop->cart->shopOrder->jsonSerialize();
            $rr->success = true;
            $rr->message = "";

            return (array)$rr;
        } else {
            return $this->goBack();
        }
    }

public function actionClear ( ) { $ rr = new RequestResponse ( ) ; if ( $ rr -> isRequestAjaxPost ( ) ) { foreach ( \ Yii :: $ app -> shop -> cart -> shopOrder -> shopOrderItems as $ basket ) { $ basket -> delete ( ) ; } \ Yii :: $ app -> shop -> cart -> shopOrder -> link ( 'cmsSite' , \ Yii :: $ app -> cms -> site ) ; $ rr -> data = \ Yii :: $ app -> shop -> cart -> shopOrder -> jsonSerialize ( ) ; $ rr -> success = true ; $ rr -> message = "" ; return ( array ) $ rr ; } else { return $ this -> goBack ( ) ; } }

Cleaning the entire basket

@return array|\yii\web\Response
@throws \Exception


public function actionUpdateBasket()
    {
        $rr = new RequestResponse();

        if ($rr->isRequestAjaxPost()) {
            $basket_id = (int)\Yii::$app->request->post('basket_id');
            $quantity = (float)\Yii::$app->request->post('quantity');

            /**
             * @var $shopBasket ShopBasket
             */
            $shopBasket = ShopOrderItem::find()->where(['id' => $basket_id])->one();
            if ($shopBasket) {
                if ($quantity > 0) {
                    $product = $shopBasket->product;

                    if ($product->measure_ratio > 1) {
                        if ($quantity % $product->measure_ratio != 0) {
                            $quantity = $product->measure_ratio;
                        }
                    }

                    $shopBasket->quantity = $quantity;
                    if ($shopBasket->recalculate()->save()) {
                        $rr->success = true;
                        $rr->message = \Yii::t('skeeks/shop/app', 'Postion successfully updated');
                    }

                } else {
                    if ($shopBasket->delete()) {
                        $rr->success = true;
                        $rr->message = \Yii::t('skeeks/shop/app', 'Position successfully removed');
                    }
                }

            }

            \Yii::$app->shop->cart->shopOrder->link('cmsSite', \Yii::$app->cms->site);
            $rr->data = \Yii::$app->shop->cart->shopOrder->jsonSerialize();
            return (array)$rr;
        } else {
            return $this->goBack();
        }
    }

/**
             * @var $shopBasket ShopBasket
             */

Updating the positions of the basket, such as changing the number of

@return array|\yii\web\Response
@throws \Exception

Updating the positions of the basket such as changing the number of


public static function getLiteralValue ($literal)
    {
        preg_match("/^\"(.*)\"/", $literal, $match); //TODO: somehow the copied regex did not work. To be checked. Contained [^]
        if (empty($match)) {
            throw new \Exception($literal . ' is not a literal');
        }
        return $match[1];
    }

Gets the string value of a literal in the N3 library


public static function getLiteralType ($literal)
    {
        preg_match('/^".*"(?:\^\^([^"]+)|(@)[^@"]+)?$/s',$literal,$match);//TODO: somehow the copied regex did not work. To be checked. Contained [^] instead of the .
        if (empty($match))
            throw new \Exception($literal . ' is not a literal');
        if (!empty($match[1])) {
            return $match[1];
        } else {
            return !empty($match[2]) ? self::RDFLANGSTRING : self::XSDSTRING;
        }
    }

Gets the type of a literal in the N3 library


public static function getLiteralLanguage ($literal)
    {
        preg_match('/^".*"(?:@([^@"]+)|\^\^[^"]+)?$/s', $literal, $match);
        if (empty($match))
            throw new \Exception($literal . ' is not a literal');
        return isset($match[1]) ? strtolower($match[1]) : '';
    }

public
static
function
getLiteralLanguage
(
$
literal
)
{
preg_match
(
'/^".*"(?:@([^@"]+)|\^\^[^"]+)?$/s'
,
$
literal
,
$
match
)
;
if
(
empty
(
$
match
)
)
throw
new
\
Exception
(
$
literal
.
' is not a literal'
)
;
return
isset
(
$
match
[
1
]
)
strtolower
(
$
match
[
1
]
)
:
''
;
}

Gets the language of a literal in the N3 library


public static function createIRI ($iri)
    {
        return !empty($iri) && substr($iri,0,1) === '"' ? self::getLiteralValue($iri) : $iri;
    }

public static function createIRI ( $ iri ) { return ! empty ( $ iri ) && substr ( $ iri , 0 , 1 ) === '"' ? self :: getLiteralValue ( $ iri ) : $ iri ; }

Creates an IRI in N3 . js representation


public static function createLiteral ($value, $modifier = null)
    {
        if (!$modifier) {
            switch (gettype($value)) {
                case 'boolean':
                    $value = $value ? "true":"false";
                    $modifier = self::XSDBOOLEAN;
                    break;
                case 'integer':
                    $modifier = self::XSDINTEGER;
                    break;
                case 'double':
                    $modifier = self::XSDDOUBLE;
                    break;
                case 'float':
                    $modifier = self::XSDFLOAT;
                    break;
                default:
                    return '"' . $value . '"';
            }
        }
        return '"' . $value . (preg_match("/^[a-z]+(-[a-z0-9]+)*$/i", $modifier) ? '"@'  . strtolower($modifier) : '"^^' . $modifier);
    }

public static function createLiteral ( $ value , $ modifier = null ) { if ( ! $ modifier ) { switch ( gettype ( $ value ) ) { case 'boolean' : $ value = $ value ? "true" : "false" ; $ modifier = self :: XSDBOOLEAN ; break ; case 'integer' : $ modifier = self :: XSDINTEGER ; break ; case 'double' : $ modifier = self :: XSDDOUBLE ; break ; case 'float' : $ modifier = self :: XSDFLOAT ; break ; default : return '"' . $ value . '"' ; } } return '"' . $ value . ( preg_match ( "/^[a-z]+(-[a-z0-9]+)*$/i" , $ modifier ) ? '"@' . strtolower ( $ modifier ) : '"^^' . $ modifier ) ; }

Creates a literal in N3.js representation

Creates a literal in N3 . js representation


public function checkRequestMD5($request)
    {

        //return true;

        $str = $request['action'].";".
            $request['orderSumAmount'].";".$request['orderSumCurrencyPaycash'].";".
            $request['orderSumBankPaycash'].";".$request['shopId'].";".
            $request['invoiceId'].";".$request['customerNumber'].";".$this->shop_password;

        \Yii::info("String to md5: ".$str, static::class);

        $md5 = strtoupper(md5($str));
        if ($md5 != strtoupper($request['md5'])) {
            \Yii::error("Wait for md5:".$md5.", recieved md5: ".$request['md5'], self::class);
            return false;
        }
        return true;
    }

public
function
checkRequestMD5
(
$
request
)
{
//return true;
$
str
=
$
request
[
'action'
]
.
";"
.
$
request
[
'orderSumAmount'
]
.
";"
.
$
request
[
'orderSumCurrencyPaycash'
]
.
";"
.
$
request
[
'orderSumBankPaycash'
]
.
";"
.
$
request
[
'shopId'
]
.
";"
.
$
request
[
'invoiceId'
]
.
";"
.
$
request
[
'customerNumber'
]
.
";"
.
$
this
->
shop_password
;
\
Yii
::
info
(
"String to md5: "
.
$
str
,
static
::
class
)
;
$
md5
=
strtoupper
(
md5
(
$
str
)
)
;
if
(
$
md5
!=
strtoupper
(
$
request
[
'md5'
]
)
)
{
\
Yii
::
error
(
"Wait for md5:"
.
$
md5
.
", recieved md5: "
.
$
request
[
'md5'
]
,
self
::
class
)
;
return
false
;
}
return
true
;
}

Checking the MD5 sign.
@param  array $request payment parameters
@return bool true if MD5 hash is correct