code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
protected function encode($var)
{
$string = '';
foreach ($var as $key => $value) {
$string .= $key . '="' . preg_replace(
['/"/', '/\\\/', "/\t/", "/\n/", "/\r/"],
['\"', '\\\\', '\t', '\n', '\r'],
$value
) . "\"\n";
}
return $string;
}
|
Encode configuration object into RAW string (INI).
@param array $var
@return string
@throws \RuntimeException
|
protected function decode($var)
{
$decoded = file_exists($this->filename) ? @parse_ini_file($this->filename) : [];
if ($decoded === false) {
throw new \RuntimeException("Decoding file '{$this->filename}' failed'");
}
return $decoded;
}
|
Decode INI file into contents.
@param string $var
@return array
@throws \RuntimeException
|
public function offsetUnset($offset)
{
// Hack to make Iterator trait work together with unset.
if (isset($this->iteratorUnset) && $offset == key($this->items)) {
$this->iteratorUnset = true;
}
unset($this->items[$offset]);
}
|
Unsets an offset.
@param mixed $offset The offset to unset.
|
public function start($deviceUUID, array $options = array())
{
// @throws InvalidArgumentException
$this->checkArgument($deviceUUID, 'deviceUUID');
list($code, $session) = $this->httpClient->post('/sync/start', null, array_merge($options, ['headers' => $this->buildHeaders($deviceUUID)]));
if ($code == 204) return null;
return $session;
}
|
Start synchronization flow
post '/sync/start'
Starts a new synchronization session.
This is the first endpoint to call, in order to start a new synchronization session.
@param string $deviceUUID Device's UUID for which to perform synchronization.
@param array $options Additional request's options.
@return array The resulting object representing synchronization session or null if there is nothing to synchronize.
|
public function fetch($deviceUUID, $sessionId, $queue = 'main', array $options = array())
{
// @throws InvalidArgumentException
$this->checkArgument($deviceUUID, 'deviceUUID');
$this->checkArgument($sessionId, 'sessionId');
$this->checkArgument($queue, 'queue');
$options = array_merge($options, [
'headers' => $this->buildHeaders($deviceUUID),
'raw' => true
]);
list($code, $root) = $this->httpClient->get("/sync/{$sessionId}/queues/{$queue}", null, $options);
if ($code == 204) return [];
return $root['items'];
}
|
Get data from queue
get '/sync/{sessionId}/queues/main'
Fetch fresh data from the named queue.
Using session identifier you call continously the `#fetch` method to drain the named queue.
@param string $deviceUUID Device's UUID for which to perform synchronization.
@param string $sessionId Unique identifier of a synchronization session.
@param string $queue Queue name.
@param array $options Additional request's options.
@return array The list of resources and associated meta data or an empty array if there is no more data to synchronize.
|
public function ack($deviceUUID, array $ackKeys, array $options = array())
{
// @throws InvalidArgumentException
$this->checkArgument($deviceUUID, 'deviceUUID');
// fast path - nothing to acknowledge
if (!$ackKeys) return true;
$attributes = ['ack_keys' => $ackKeys];
list($code,) = $this->httpClient->post('/sync/ack', $attributes, array_merge($options, ['headers' => $this->buildHeaders($deviceUUID)]));
return $code == 202;
}
|
Acknowledge received data
post '/sync/ack'
Send acknowledgement keys to let know the Sync service which data you have.
As you fetch new data, you need to send acknowledgement keys.
@param string $deviceUUID Device's UUID for which to perform synchronization.
@param array $ackKeys The list of acknowledgement keys.
@param array $options Additional request's options.
@return boolean Status of the operation.
|
public function create(array $source, array $options = array())
{
$attributes = array_intersect_key($source, array_flip(self::$keysToPersist));
list($code, $createdSource) = $this->httpClient->post("/sources", $attributes, $options);
return $createdSource;
}
|
Create a source
post '/sources'
Creates a new source
<figure class="notice">
Source's name **must** be unique
</figure>
@param array $source This array's attributes describe the object to be created.
@param array $options Additional request's options.
@return array The resulting object representing created resource.
|
public function update($id, array $source, array $options = array())
{
$attributes = array_intersect_key($source, array_flip(self::$keysToPersist));
list($code, $updatedSource) = $this->httpClient->put("/sources/{$id}", $attributes, $options);
return $updatedSource;
}
|
Update a source
put '/sources/{id}'
Updates source information
If the specified source does not exist, the request will return an error
<figure class="notice">
If you want to update a source, you **must** make sure source's name is unique
</figure>
@param integer $id Unique identifier of a Source
@param array $source This array's attributes describe the object to be updated.
@param array $options Additional request's options.
@return array The resulting object representing updated resource.
|
public function create(array $order, array $options = array())
{
$attributes = array_intersect_key($order, array_flip(self::$keysToPersist));
list($code, $createdOrder) = $this->httpClient->post("/orders", $attributes, $options);
return $createdOrder;
}
|
Create an order
post '/orders'
Create a new order for a deal
User needs to have access to the deal to create an order
Each deal can have at most one order and error is returned when attempting to create more
@param array $order This array's attributes describe the object to be created.
@param array $options Additional request's options.
@return array The resulting object representing created resource.
|
public function update($id, array $order, array $options = array())
{
$attributes = array_intersect_key($order, array_flip(self::$keysToPersist));
list($code, $updatedOrder) = $this->httpClient->put("/orders/{$id}", $attributes, $options);
return $updatedOrder;
}
|
Update an order
put '/orders/{id}'
Updates order information
If the specified order does not exist, the request will return an error
@param integer $id Unique identifier of a Order
@param array $order This array's attributes describe the object to be updated.
@param array $options Additional request's options.
@return array The resulting object representing updated resource.
|
public function create(array $lead, array $options = array())
{
$attributes = array_intersect_key($lead, array_flip(self::$keysToPersist));
if (isset($attributes['custom_fields']) && empty($attributes['custom_fields'])) unset($attributes['custom_fields']);
list($code, $createdLead) = $this->httpClient->post("/leads", $attributes, $options);
return $createdLead;
}
|
Create a lead
post '/leads'
Creates a new lead
A lead may represent a single individual or an organization
@param array $lead This array's attributes describe the object to be created.
@param array $options Additional request's options.
@return array The resulting object representing created resource.
|
public function update($id, array $lead, array $options = array())
{
$attributes = array_intersect_key($lead, array_flip(self::$keysToPersist));
if (isset($attributes['custom_fields']) && empty($attributes['custom_fields'])) unset($attributes['custom_fields']);
list($code, $updatedLead) = $this->httpClient->put("/leads/{$id}", $attributes, $options);
return $updatedLead;
}
|
Update a lead
put '/leads/{id}'
Updates lead information
If the specified lead does not exist, this query returns an error
<figure class="notice">
In order to modify tags, you need to supply the entire set of tags
`tags` are replaced every time they are used in a request
</figure>
@param integer $id Unique identifier of a Lead
@param array $lead This array's attributes describe the object to be updated.
@param array $options Additional request's options.
@return array The resulting object representing updated resource.
|
public function header(array $var = null)
{
$content = $this->content();
if ($var !== null) {
$content['header'] = $var;
$this->content($content);
}
return $content['header'];
}
|
Get/set file header.
@param array $var
@return array
|
public function markdown($var = null)
{
$content = $this->content();
if ($var !== null) {
$content['markdown'] = (string) $var;
$this->content($content);
}
return $content['markdown'];
}
|
Get/set markdown content.
@param string $var
@return string
|
public function frontmatter($var = null)
{
$content = $this->content();
if ($var !== null) {
$content['frontmatter'] = (string) $var;
$this->content($content);
}
return $content['frontmatter'];
}
|
Get/set frontmatter content.
@param string $var
@return string
|
protected function encode($var)
{
// Create Markdown file with YAML header.
$o = (!empty($var['header']) ? "---\n" . trim(YamlParser::dump($var['header'], 20)) . "\n---\n\n" : '') . $var['markdown'];
// Normalize line endings to Unix style.
$o = preg_replace("/(\r\n|\r)/", "\n", $o);
return $o;
}
|
Encode contents into RAW string.
@param array $var
@return string
|
protected function decode($var)
{
$content = [
'header' => false,
'frontmatter' => ''
];
$frontmatter_regex = "/^---\n(.+?)\n---\n{0,}(.*)$/uis";
// Normalize line endings to Unix style.
$var = preg_replace("/(\r\n|\r)/", "\n", $var);
// Parse header.
preg_match($frontmatter_regex, ltrim($var), $m);
if(!empty($m)) {
// Normalize frontmatter.
$content['frontmatter'] = $frontmatter = preg_replace("/\n\t/", "\n ", $m[1]);
// Try native PECL YAML PHP extension first if available.
if (\function_exists('yaml_parse') && $this->setting('native')) {
// Safely decode YAML.
$saved = @ini_get('yaml.decode_php');
@ini_set('yaml.decode_php', 0);
$content['header'] = @yaml_parse("---\n" . $frontmatter . "\n...");
@ini_set('yaml.decode_php', $saved);
}
if ($content['header'] === false) {
// YAML hasn't been parsed yet (error or extension isn't available). Fall back to Symfony parser.
try {
$content['header'] = (array) YamlParser::parse($frontmatter);
} catch (ParseException $e) {
if (!$this->setting('compat', true)) {
throw $e;
}
$content['header'] = (array) FallbackYamlParser::parse($frontmatter);
}
}
$content['markdown'] = $m[2];
} else {
$content['header'] = [];
$content['markdown'] = $var;
}
return $content;
}
|
Decode RAW string into contents.
@param string $var
@return array mixed
|
public function start()
{
// Protection against invalid session cookie names throwing exception: http://php.net/manual/en/function.session-id.php#116836
if (isset($_COOKIE[session_name()]) && !preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $_COOKIE[session_name()])) {
unset($_COOKIE[session_name()]);
}
if (!session_start()) {
throw new \RuntimeException('Failed to start session.', 500);
}
$this->started = true;
return $this;
}
|
Starts the session storage
@return $this
@throws \RuntimeException
|
public function invalidate()
{
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params['path'], $params['domain'],
$params['secure'], $params['httponly']
);
session_unset();
session_destroy();
$this->started = false;
return $this;
}
|
Invalidates the current session.
@return $this
|
public function updateCMSFields(FieldList $fields)
{
$pageInfoTitle = _t(__CLASS__ . '.PAGEINFO', 'Page info and SEO');
$boostTitle = _t(__CLASS__ . '.SearchBoost', 'Boost Keywords');
$boostNote = _t(
__CLASS__ . '.SearchBoostNote',
'(Only applies to the search results on this site e.g. not on Google search)'
);
$boostDescription = _t(
__CLASS__ . '.SearchBoostDescription',
'Enter keywords separated by comma ( , ) for which to boost the ranking of this page '
. 'within the search results on this site.'
);
$boostField = TextareaField::create('SearchBoost', $boostTitle)
->setRightTitle($boostNote)
->setDescription($boostDescription);
if ($meta = $fields->fieldByName('Root.Main.Metadata')) {
// Rename metafield if it exists
$meta->setTitle($pageInfoTitle);
$fields->insertBefore('MetaDescription', $boostField);
} else {
// Else create new field to store SEO
$fields->addFieldToTab(
'Root.Main',
ToggleCompositeField::create(
'Metadata',
$pageInfoTitle,
[
$boostField,
]
)
);
}
}
|
Adds boost fields to this page
@param FieldList $fields
|
public function create(array $lossReason, array $options = array())
{
$attributes = array_intersect_key($lossReason, array_flip(self::$keysToPersist));
list($code, $createdLossReason) = $this->httpClient->post("/loss_reasons", $attributes, $options);
return $createdLossReason;
}
|
Create a loss reason
post '/loss_reasons'
Create a new loss reason
<figure class="notice">
Loss reason's name **must** be unique
</figure>
@param array $lossReason This array's attributes describe the object to be created.
@param array $options Additional request's options.
@return array The resulting object representing created resource.
|
public function get($id, array $options = array())
{
list($code, $loss_reason) = $this->httpClient->get("/loss_reasons/{$id}", null, $options);
return $loss_reason;
}
|
Retrieve a single reason
get '/loss_reasons/{id}'
Returns a single loss reason available to the user by the provided id
If a loss reason with the supplied unique identifier does not exist, it returns an error
@param integer $id Unique identifier of a LossReason
@param array $options Additional request's options.
@return array Searched LossReason.
|
public function update($id, array $lossReason, array $options = array())
{
$attributes = array_intersect_key($lossReason, array_flip(self::$keysToPersist));
list($code, $updatedLossReason) = $this->httpClient->put("/loss_reasons/{$id}", $attributes, $options);
return $updatedLossReason;
}
|
Update a loss reason
put '/loss_reasons/{id}'
Updates a loss reason information
If the specified loss reason does not exist, the request will return an error
<figure class="notice">
If you want to update loss reason you **must** make sure name of the reason is unique
</figure>
@param integer $id Unique identifier of a LossReason
@param array $lossReason This array's attributes describe the object to be updated.
@param array $options Additional request's options.
@return array The resulting object representing updated resource.
|
public function all($deal_id, $params = [], array $options = array())
{
list($code, $associated_contacts) = $this->httpClient->get("/deals/{$deal_id}/associated_contacts", $params, $options);
return $associated_contacts;
}
|
Retrieve deal's associated contacts
get '/deals/{deal_id}/associated_contacts'
Returns all deal associated contacts
@param integer $deal_id Unique identifier of a Deal
@param array $params Search options
@param array $options Additional request's options.
@return array The list of AssociatedContacts for the first page, unless otherwise specified.
|
public function create($deal_id, array $associatedContact, array $options = array())
{
$attributes = array_intersect_key($associatedContact, array_flip(self::$keysToPersist));
list($code, $createdAssociatedContact) = $this->httpClient->post("/deals/{$deal_id}/associated_contacts", $attributes, $options);
return $createdAssociatedContact;
}
|
Create an associated contact
post '/deals/{deal_id}/associated_contacts'
Creates a deal's associated contact and its role
If the specified deal or contact does not exist, the request will return an error
@param integer $deal_id Unique identifier of a Deal
@param array $associatedContact This array's attributes describe the object to be created.
@param array $options Additional request's options.
@return array The resulting object representing created resource.
|
public function destroy($deal_id, $contact_id, array $options = array())
{
list($code, $payload) = $this->httpClient->delete("/deals/{$deal_id}/associated_contacts/{$contact_id}", null, $options);
return $code == 204;
}
|
Remove an associated contact
delete '/deals/{deal_id}/associated_contacts/{contact_id}'
Remove a deal's associated contact
If a deal with the supplied unique identifier does not exist, it returns an error
This operation cannot be undone
@param integer $deal_id Unique identifier of a Deal
@param integer $contact_id Unique identifier of a Contact
@param array $options Additional request's options.
@return boolean Status of the operation.
|
public function create(array $tag, array $options = array())
{
$attributes = array_intersect_key($tag, array_flip(self::$keysToPersist));
list($code, $createdTag) = $this->httpClient->post("/tags", $attributes, $options);
return $createdTag;
}
|
Create a tag
post '/tags'
Creates a new tag
**Notice** the tag's name **must** be unique within the scope of the resource_type
@param array $tag This array's attributes describe the object to be created.
@param array $options Additional request's options.
@return array The resulting object representing created resource.
|
public function update($id, array $tag, array $options = array())
{
$attributes = array_intersect_key($tag, array_flip(self::$keysToPersist));
list($code, $updatedTag) = $this->httpClient->put("/tags/{$id}", $attributes, $options);
return $updatedTag;
}
|
Update a tag
put '/tags/{id}'
Updates a tag's information
If the specified tag does not exist, this query will return an error
**Notice** if you want to update a tag, you **must** make sure the tag's name is unique within the scope of the specified resource
@param integer $id Unique identifier of a Tag
@param array $tag This array's attributes describe the object to be updated.
@param array $options Additional request's options.
@return array The resulting object representing updated resource.
|
public function create(array $dealUnqualifiedReason, array $options = array())
{
$attributes = array_intersect_key($dealUnqualifiedReason, array_flip(self::$keysToPersist));
list($code, $createdDealUnqualifiedReason) = $this->httpClient->post("/deal_unqualified_reasons", $attributes, $options);
return $createdDealUnqualifiedReason;
}
|
Create a deal unqualified reason
post '/deal_unqualified_reasons'
Create a new deal unqualified reason
<figure class="notice">
Deal unqualified reason's name **must** be unique
</figure>
@param array $dealUnqualifiedReason This array's attributes describe the object to be created.
@param array $options Additional request's options.
@return array The resulting object representing created resource.
|
public function update($id, array $dealUnqualifiedReason, array $options = array())
{
$attributes = array_intersect_key($dealUnqualifiedReason, array_flip(self::$keysToPersist));
list($code, $updatedDealUnqualifiedReason) = $this->httpClient->put("/deal_unqualified_reasons/{$id}", $attributes, $options);
return $updatedDealUnqualifiedReason;
}
|
Update a deal unqualified reason
put '/deal_unqualified_reasons/{id}'
Updates a deal unqualified reason information
If the specified deal unqualified reason does not exist, the request will return an error
<figure class="notice">
If you want to update deal unqualified reason you **must** make sure name of the reason is unique
</figure>
@param integer $id Unique identifier of a DealUnqualifiedReason
@param array $dealUnqualifiedReason This array's attributes describe the object to be updated.
@param array $options Additional request's options.
@return array The resulting object representing updated resource.
|
public function uploadConfig($store)
{
parent::uploadConfig($store);
// Upload configured synonyms {@see SynonymsSiteConfig}
$siteConfig = SiteConfig::current_site_config();
if ($siteConfig->SearchSynonyms) {
$store->uploadString(
$this->getIndexName(),
'synonyms.txt',
$siteConfig->SearchSynonyms
);
}
}
|
Upload config for this index to the given store
@param SolrConfigStore $store
|
public function parse($value, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false)
{
if (false === preg_match('//u', $value)) {
throw new ParseException('The YAML value does not appear to be valid UTF-8.');
}
$this->refs = array();
$mbEncoding = null;
$e = null;
$data = null;
if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
$mbEncoding = mb_internal_encoding();
mb_internal_encoding('UTF-8');
}
try {
$data = $this->doParse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap);
} catch (\Exception $e) {
} catch (\Throwable $e) {
}
if (null !== $mbEncoding) {
mb_internal_encoding($mbEncoding);
}
$this->lines = array();
$this->currentLine = '';
$this->refs = array();
$this->skippedLineNumbers = array();
$this->locallySkippedLineNumbers = array();
if (null !== $e) {
throw $e;
}
return $data;
}
|
Parses a YAML string to a PHP value.
@param string $value A YAML string
@param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
@param bool $objectSupport True if object support is enabled, false otherwise
@param bool $objectForMap True if maps should return a stdClass instead of array()
@return mixed A PHP value
@throws ParseException If the YAML is not valid
|
private function getRealCurrentLineNb()
{
$realCurrentLineNumber = $this->currentLineNb + $this->offset;
foreach ($this->skippedLineNumbers as $skippedLineNumber) {
if ($skippedLineNumber > $realCurrentLineNumber) {
break;
}
++$realCurrentLineNumber;
}
return $realCurrentLineNumber;
}
|
Returns the current line number (takes the offset into account).
@return int The current line number
|
private function cleanup($value)
{
$value = str_replace(array("\r\n", "\r"), "\n", $value);
// strip YAML header
$count = 0;
$value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count);
$this->offset += $count;
// remove leading comments
$trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count);
if (1 == $count) {
// items have been removed, update the offset
$this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
$value = $trimmedValue;
}
// remove start of the document marker (---)
$trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count);
if (1 == $count) {
// items have been removed, update the offset
$this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
$value = $trimmedValue;
// remove end of the document marker (...)
$value = preg_replace('#\.\.\.\s*$#', '', $value);
}
return $value;
}
|
Cleanups a YAML string to be parsed.
@param string $value The input YAML string
@return string A cleaned up YAML string
|
private function isNextLineUnIndentedCollection()
{
$currentIndentation = $this->getCurrentLineIndentation();
$notEOF = $this->moveToNextLine();
while ($notEOF && $this->isCurrentLineEmpty()) {
$notEOF = $this->moveToNextLine();
}
if (false === $notEOF) {
return false;
}
$ret = $this->getCurrentLineIndentation() === $currentIndentation && $this->isStringUnIndentedCollectionItem();
$this->moveToPreviousLine();
return $ret;
}
|
Returns true if the next line starts unindented collection.
@return bool Returns true if the next line starts unindented collection, false otherwise
|
public function save($data = null)
{
parent::save($data);
// Invalidate configuration file from the opcache.
if (\function_exists('opcache_invalidate')) {
// PHP 5.5.5+
@opcache_invalidate($this->filename, true);
} elseif (\function_exists('apc_invalidate')) {
// APC
@apc_invalidate($this->filename);
}
}
|
Saves PHP file and invalidates opcache.
@param mixed $data Optional data to be saved, usually array.
@throws \RuntimeException
|
protected function encodeArray(array $a, $level = 0)
{
$r = [];
foreach ($a as $k => $v) {
if (\is_array($v) || \is_object($v)) {
$r[] = var_export($k, true) . ' => ' . $this->encodeArray((array) $v, $level + 1);
} else {
$r[] = var_export($k, true) . ' => ' . var_export($v, true);
}
}
$space = str_repeat(' ', $level);
return "[\n {$space}" . implode(",\n {$space}", $r) . "\n{$space}]";
}
|
Method to get an array as an exported string.
@param array $a The array to get as a string.
@param int $level Used internally to indent rows.
@return string
|
public static function instance($filename)
{
if (!\is_string($filename) && $filename) {
throw new \InvalidArgumentException('Filename should be non-empty string');
}
if (!isset(static::$instances[$filename])) {
static::$instances[$filename] = new static;
static::$instances[$filename]->init($filename);
}
return static::$instances[$filename];
}
|
Get file instance.
@param string $filename
@return static
|
public function settings(array $settings = null)
{
if ($settings !== null) {
$this->settings = $settings;
}
return $this->settings;
}
|
Set/get settings.
@param array $settings
@return array
|
public function free()
{
if ($this->locked) {
$this->unlock();
}
$this->content = null;
$this->raw = null;
unset(static::$instances[$this->filename]);
}
|
Free the file instance.
|
public function lock($block = true)
{
if (!$this->handle) {
if (!$this->mkdir(\dirname($this->filename))) {
throw new \RuntimeException('Creating directory failed for ' . $this->filename);
}
$this->handle = @fopen($this->filename, 'cb+');
if (!$this->handle) {
$error = error_get_last();
throw new \RuntimeException("Opening file for writing failed on error {$error['message']}");
}
}
$lock = $block ? LOCK_EX : LOCK_EX | LOCK_NB;
// Some filesystems do not support file locks, only fail if another process holds the lock.
$this->locked = flock($this->handle, $lock, $wouldblock) || !$wouldblock;
return $this->locked;
}
|
Lock file for writing. You need to manually unlock().
@param bool $block For non-blocking lock, set the parameter to false.
@return bool
@throws \RuntimeException
|
public function writable()
{
return file_exists($this->filename) ? is_writable($this->filename) && is_file($this->filename) : $this->writableDir(\dirname($this->filename));
}
|
Check if file can be written.
@return bool
|
public function load()
{
$this->raw = $this->exists() ? (string) file_get_contents($this->filename) : '';
$this->content = null;
return $this->raw;
}
|
(Re)Load a file and return RAW file contents.
@return string
|
public function raw($var = null)
{
if ($var !== null) {
$this->raw = (string) $var;
$this->content = null;
}
if (!\is_string($this->raw)) {
$this->raw = $this->load();
}
return $this->raw;
}
|
Get/set raw file contents.
@param string $var
@return string
|
public function content($var = null)
{
if ($var !== null) {
$this->content = $this->check($var);
// Update RAW, too.
$this->raw = $this->encode($this->content);
} elseif ($this->content === null) {
// Decode RAW file.
try {
$this->content = $this->decode($this->raw());
} catch (\Exception $e) {
throw new \RuntimeException(sprintf('Failed to read %s: %s', $this->filename, $e->getMessage()), 500, $e);
}
}
return $this->content;
}
|
Get/set parsed file contents.
@param mixed $var
@return string|array
@throws \RuntimeException
|
public function save($data = null)
{
if ($data !== null) {
$this->content($data);
}
$filename = $this->filename;
$dir = \dirname($filename);
if (!$this->mkdir($dir)) {
throw new \RuntimeException('Creating directory failed for ' . $filename);
}
try {
if ($this->handle) {
$tmp = true;
// As we are using non-truncating locking, make sure that the file is empty before writing.
if (@ftruncate($this->handle, 0) === false || @fwrite($this->handle, $this->raw()) === false) {
// Writing file failed, throw an error.
$tmp = false;
}
} else {
// Create file with a temporary name and rename it to make the save action atomic.
$tmp = $this->tempname($filename);
if (file_put_contents($tmp, $this->raw()) === false) {
$tmp = false;
} elseif (@rename($tmp, $filename) === false) {
@unlink($tmp);
$tmp = false;
}
}
} catch (\Exception $e) {
$tmp = false;
}
if ($tmp === false) {
throw new \RuntimeException('Failed to save file ' . $filename);
}
// Touch the directory as well, thus marking it modified.
@touch($dir);
}
|
Save file.
@param mixed $data Optional data to be saved, usually array.
@throws \RuntimeException
|
public function rename($filename)
{
if ($this->exists() && !@rename($this->filename, $filename)) {
return false;
}
unset(static::$instances[$this->filename]);
static::$instances[$filename] = $this;
$this->filename = $filename;
return true;
}
|
Rename file in the filesystem if it exists.
@param $filename
@return bool
|
public function register()
{
defined('XS_APP_ROOT') || define('XS_APP_ROOT', config_path());
$this->app->singleton(XunsearchService::class, function ($app) {
return new XunsearchService();
});
$this->app->alias(XunsearchService::class, 'xunsearch');
}
|
Register any application services.
@return void
|
public function self(array $options = array())
{
list($code, $resource) = $this->httpClient->get("/users/self", null, $options);
return $resource;
}
|
Retrieve an authenticating user
get '/users/self'
Returns a single authenticating user, according to the authentication credentials provided
@param array $options Additional request's options.
@return array Resource object.
|
public function add($message, $scope = 'default')
{
$key = md5($scope.'~'.$message);
$item = ['message' => $message, 'scope' => $scope];
// don't add duplicates
if (!array_key_exists($key, $this->messages)) {
$this->messages[$key] = $item;
}
return $this;
}
|
Add message to the queue.
@param string $message
@param string $scope
@return $this
|
public function clear($scope = null)
{
if ($scope === null) {
$this->messages = array();
} else {
foreach ($this->messages as $key => $message) {
if ($message['scope'] === $scope) {
unset($this->messages[$key]);
}
}
}
return $this;
}
|
Clear message queue.
@param string $scope
@return $this
|
public function all($scope = null)
{
if ($scope === null) {
return array_values($this->messages);
}
$messages = array();
foreach ($this->messages as $message) {
if ($message['scope'] === $scope) {
$messages[] = $message;
}
}
return $messages;
}
|
Fetch all messages.
@param string $scope
@return array
|
public function fetch($scope = null)
{
$messages = $this->all($scope);
$this->clear($scope);
return $messages;
}
|
Fetch and clear message queue.
@param string $scope
@return array
|
public function set($name, $value, $separator = null)
{
$path = explode($separator ?: $this->nestedSeparator, $name);
$current = &$this->items;
foreach ($path as $field) {
if (\is_object($current)) {
// Handle objects.
if (!isset($current->{$field})) {
$current->{$field} = [];
}
$current = &$current->{$field};
} else {
// Handle arrays and scalars.
if (!\is_array($current)) {
$current = [$field => []];
} elseif (!isset($current[$field])) {
$current[$field] = [];
}
$current = &$current[$field];
}
}
$current = $value;
return $this;
}
|
Set value by using dot notation for nested arrays/objects.
@example $data->set('this.is.my.nested.variable', $value);
@param string $name Dot separated path to the requested value.
@param mixed $value New value.
@param string $separator Separator, defaults to '.'
@return $this
|
public function def($name, $default = null, $separator = null)
{
$this->set($name, $this->get($name, $default, $separator), $separator);
return $this;
}
|
Set default value by using dot notation for nested arrays/objects.
@example $data->def('this.is.my.nested.variable', 'default');
@param string $name Dot separated path to the requested value.
@param mixed $default Default value (or null).
@param string $separator Separator, defaults to '.'
@return $this
|
public function all($params = [], array $options = array())
{
list($code, $deals) = $this->httpClient->get("/deals", $params, $options);
if (isset($options['raw']) && $options['raw']) {
return $deals;
}
$dealsData = array_map(array($this, 'coerceNestedDealData'), $deals);
return $dealsData;
}
|
Retrieve all deals
get '/deals'
Returns all deals available to the user according to the parameters provided
@param array $params Search options
@param array $options Additional request's options.
@return array The list of Deals for the first page, unless otherwise specified.
|
public function create(array $deal, array $options = array())
{
$attributes = array_intersect_key($deal, array_flip(self::$keysToPersist));
if (isset($attributes['custom_fields']) && empty($attributes['custom_fields'])) unset($attributes['custom_fields']);
if (isset($attributes['value'])) $attributes["value"] = Coercion::toStringValue($attributes['value']);
list($code, $createdDeal) = $this->httpClient->post("/deals", $attributes, $options);
if (isset($options['raw']) && $options['raw']) {
return $createdDeal;
}
$createdDeal = $this->coerceDealData($createdDeal);
return $createdDeal;
}
|
Create a deal
post '/deals'
Create a new deal
@param array $deal This array's attributes describe the object to be created.
@param array $options Additional request's options.
@return array The resulting object representing created resource.
|
public function get($id, array $options = array())
{
list($code, $deal) = $this->httpClient->get("/deals/{$id}", null, $options);
if (isset($options['raw']) && $options['raw']) {
return $deal;
}
$deal = $this->coerceDealData($deal);
return $deal;
}
|
Retrieve a single deal
get '/deals/{id}'
Returns a single deal available to the user, according to the unique deal ID provided
If the specified deal does not exist, the request will return an error
@param integer $id Unique identifier of a Deal
@param array $options Additional request's options.
@return array Searched Deal.
|
public function update($id, array $deal, array $options = array())
{
$attributes = array_intersect_key($deal, array_flip(self::$keysToPersist));
if (isset($attributes['custom_fields']) && empty($attributes['custom_fields'])) unset($attributes['custom_fields']);
if (isset($attributes["value"])) $attributes["value"] = Coercion::toStringValue($attributes['value']);
list($code, $updatedDeal) = $this->httpClient->put("/deals/{$id}", $attributes, $options);
if (isset($options['raw']) && $options['raw']) {
return $updatedDeal;
}
$updatedDeal = $this->coerceDealData($updatedDeal);
return $updatedDeal;
}
|
Update a deal
put '/deals/{id}'
Updates deal information
If the specified deal does not exist, the request will return an error
<figure class="notice">
In order to modify tags used on a record, you need to supply the entire set
`tags` are replaced every time they are used in a request
</figure>
@param integer $id Unique identifier of a Deal
@param array $deal This array's attributes describe the object to be updated.
@param array $options Additional request's options.
@return array The resulting object representing updated resource.
|
public function create(array $product, array $options = array())
{
$attributes = array_intersect_key($product, array_flip(self::$keysToPersist));
list($code, $createdProduct) = $this->httpClient->post("/products", $attributes, $options);
return $createdProduct;
}
|
Create a product
post '/products'
Create a new product
@param array $product This array's attributes describe the object to be created.
@param array $options Additional request's options.
@return array The resulting object representing created resource.
|
public function update($id, array $product, array $options = array())
{
$attributes = array_intersect_key($product, array_flip(self::$keysToPersist));
list($code, $updatedProduct) = $this->httpClient->put("/products/{$id}", $attributes, $options);
return $updatedProduct;
}
|
Update a product
put '/products/{id}'
Updates product information
If the specified product does not exist, the request will return an error
<figure class="notice"><p>In order to modify prices used on a record, you need to supply the entire set
<code>prices</code> are replaced every time they are used in a request
</p></figure>
@param integer $id Unique identifier of a Product
@param array $product This array's attributes describe the object to be updated.
@param array $options Additional request's options.
@return array The resulting object representing updated resource.
|
public function destroy($id, array $options = array())
{
list($code, $payload) = $this->httpClient->delete("/products/{$id}", null, $options);
return $code == 204;
}
|
Delete a product
delete '/products/{id}'
Delete an existing product from the catalog
Existing orders and line items are not affected
If the specified product does not exist, the request will return an error
This operation cannot be undone
Products can be removed only by an account administrator
@param integer $id Unique identifier of a Product
@param array $options Additional request's options.
@return boolean Status of the operation.
|
public function load($extends = null)
{
// Only load and extend blueprint if it has not yet been loaded.
if (empty($this->items) && $this->filename) {
// Get list of files.
$files = $this->getFiles($this->filename);
// Load and extend blueprints.
$data = $this->doLoad($files, $extends);
$this->items = (array) array_shift($data);
foreach ($data as $content) {
$this->extend($content, true);
}
}
// Import blueprints.
$this->deepInit($this->items);
return $this;
}
|
Load blueprint.
@return $this
|
public function init()
{
foreach ($this->dynamic as $key => $data) {
// Locate field.
$path = explode('/', $key);
$current = &$this->items;
foreach ($path as $field) {
if (\is_object($current)) {
// Handle objects.
if (!isset($current->{$field})) {
$current->{$field} = [];
}
$current = &$current->{$field};
} else {
// Handle arrays and scalars.
if (!\is_array($current)) {
$current = [$field => []];
} elseif (!isset($current[$field])) {
$current[$field] = [];
}
$current = &$current[$field];
}
}
// Set dynamic property.
foreach ($data as $property => $call) {
$action = 'dynamic' . ucfirst($call['action']);
if (method_exists($this, $action)) {
$this->{$action}($current, $property, $call);
}
}
}
return $this;
}
|
Initialize blueprints with its dynamic fields.
@return $this
|
public function fields()
{
$fields = $this->get('form/fields');
if ($fields === null) {
$field = $this->get('form/field');
$fields = $field !== null ? ['' => (array) $field] : $fields;
}
return (array) $fields;
}
|
Get form fields.
@return array
|
public function extend($extends, $append = false)
{
if ($extends instanceof self) {
$extends = $extends->toArray();
}
if ($append) {
$a = $this->items;
$b = $extends;
} else {
$a = $extends;
$b = $this->items;
}
$this->items = $this->deepMerge($a, $b);
return $this;
}
|
Extend blueprint with another blueprint.
@param BlueprintForm|array $extends
@param bool $append
@return $this
|
public function resolve(array $path, $separator = '/')
{
$fields = false;
$parts = [];
$current = $this['form/fields'];
$result = [null, null, null];
while (($field = current($path)) !== null) {
if (!$fields && isset($current['fields'])) {
if (!empty($current['array'])) {
$result = [$current, $parts, $path ? implode($separator, $path) : null];
// Skip item offset.
$parts[] = array_shift($path);
}
$current = $current['fields'];
$fields = true;
} elseif (isset($current[$field])) {
$parts[] = array_shift($path);
$current = $current[$field];
$fields = false;
} elseif (isset($current[$index = '.' . $field])) {
$parts[] = array_shift($path);
$current = $current[$index];
$fields = false;
} else {
break;
}
}
return $result;
}
|
Get blueprints by using slash notation for nested arrays/objects.
@example $value = $this->resolve('this/is/my/nested/variable');
returns ['this/is/my', 'nested/variable']
@param array $path
@param string $separator
@return array
|
protected function deepMerge(array $a, array $b)
{
$bref_stack = [&$a];
$head_stack = [$b];
do {
end($bref_stack);
$bref = &$bref_stack[key($bref_stack)];
$head = array_pop($head_stack);
unset($bref_stack[key($bref_stack)]);
foreach ($head as $key => $value) {
if (strpos($key, '@') !== false) {
// Remove @ from the start and the end. Key syntax `import@2` is supported to allow multiple operations of the same type.
$list = explode('-', preg_replace('/^(@*)?([^@]+)(@\d*)?$/', '\2', $key), 2);
$action = array_shift($list);
$property = array_shift($list);
switch ($action) {
case 'unset':
case 'replace':
if (!$property) {
$bref = ['unset@' => true];
} else {
unset($bref[$property]);
}
continue 2;
}
}
if (isset($key, $bref[$key]) && \is_array($bref[$key]) && \is_array($head[$key])) {
$bref_stack[] = &$bref[$key];
$head_stack[] = $head[$key];
} else {
$bref = array_merge($bref, [$key => $head[$key]]);
}
}
} while (\count($head_stack));
return $a;
}
|
Deep merge two arrays together.
@param array $a
@param array $b
@return array
|
protected function doLoad(array $files, $extends = null)
{
$filename = array_shift($files);
$content = $this->loadFile($filename);
$key = '';
if (isset($content['extends@'])) {
$key = 'extends@';
} elseif (isset($content['@extends'])) {
$key = '@extends';
} elseif (isset($content['@extends@'])) {
$key = '@extends@';
}
$override = (bool)$extends;
$extends = (array)($key && !$extends ? $content[$key] : $extends);
unset($content['extends@'], $content['@extends'], $content['@extends@']);
$data = $extends ? $this->doExtend($filename, $files, $extends, $override) : [];
$data[] = $content;
return $data;
}
|
Internal function that handles loading extended blueprints.
@param array $files
@param string|array|null $extends
@return array
|
protected function doExtend($filename, array $parents, array $extends, $override = false)
{
if (\is_string(key($extends))) {
$extends = [$extends];
}
$data = [[]];
foreach ($extends as $value) {
// Accept array of type and context or a string.
$type = !\is_string($value) ? (!isset($value['type']) ? null : $value['type']) : $value;
if (!$type) {
continue;
}
if ($type === '@parent' || $type === 'parent@') {
if (!$parents) {
throw new RuntimeException("Parent blueprint missing for '{$filename}'");
}
$files = $parents;
} else {
$files = $this->getFiles($type, isset($value['context']) ? $value['context'] : null);
if ($override && !$files) {
throw new RuntimeException("Blueprint '{$type}' missing for '{$filename}'");
}
// Detect extend loops.
if ($files && array_intersect($files, $parents)) {
// Let's check if user really meant extends@: parent@.
$index = \array_search($filename, $files, true);
if ($index !== false) {
// We want to grab only the parents of the file which is currently being loaded.
$files = \array_slice($files, $index + 1);
}
if ($files !== $parents) {
throw new RuntimeException("Loop detected while extending blueprint file '{$filename}'");
}
if (!$parents) {
throw new RuntimeException("Parent blueprint missing for '{$filename}'");
}
}
}
if ($files) {
$data[] = $this->doLoad($files);
}
}
// TODO: In PHP 5.6+ use array_merge(...$data);
return call_user_func_array('array_merge', $data);
}
|
Internal function to recursively load extended blueprints.
@param string $filename
@param array $parents
@param array $extends
@return array
|
protected function doReorder(array $items, array $keys)
{
$reordered = array_keys($items);
foreach ($keys as $item => $ordering) {
if ((string)(int) $ordering === (string) $ordering) {
$location = array_search($item, $reordered, true);
$rel = array_splice($reordered, $location, 1);
array_splice($reordered, $ordering, 0, $rel);
} elseif (isset($items[$ordering])) {
$location = array_search($item, $reordered, true);
$rel = array_splice($reordered, $location, 1);
$location = array_search($ordering, $reordered, true);
array_splice($reordered, $location + 1, 0, $rel);
}
}
return array_merge(array_flip($reordered), $items);
}
|
Internal function to reorder items.
@param array $items
@param array $keys
@return array
|
protected function generateSearchRecord()
{
$searchPage = CwpSearchPage::create();
$searchPage->URLSegment = 'search';
$searchPage->Title = _t('SilverStripe\\CMS\\Search\\SearchForm.SearchResults', 'Search Results');
$searchPage->ID = -1;
return $searchPage;
}
|
Create the dummy search record for this page
@return CwpSearchPage
|
public function create(array $leadSource, array $options = array())
{
$attributes = array_intersect_key($leadSource, array_flip(self::$keysToPersist));
list($code, $createdLeadSource) = $this->httpClient->post("/lead_sources", $attributes, $options);
return $createdLeadSource;
}
|
Create a new source
post '/lead_sources'
Creates a new source
<figure class="notice">
Source's name **must** be unique
</figure>
@param array $leadSource This array's attributes describe the object to be created.
@param array $options Additional request's options.
@return array The resulting object representing created resource.
|
public function update($id, array $leadSource, array $options = array())
{
$attributes = array_intersect_key($leadSource, array_flip(self::$keysToPersist));
list($code, $updatedLeadSource) = $this->httpClient->put("/lead_sources/{$id}", $attributes, $options);
return $updatedLeadSource;
}
|
Update a source
put '/lead_sources/{id}'
Updates source information
If the specified source does not exist, the request will return an error
<figure class="notice">
If you want to update a source, you **must** make sure source's name is unique
</figure>
@param integer $id Unique identifier of a LeadSource
@param array $leadSource This array's attributes describe the object to be updated.
@param array $options Additional request's options.
@return array The resulting object representing updated resource.
|
public function init()
{
parent::init();
$routes = $this->findAvailableRoutes();
$route = $this->getRequest()->getVar('endpoint') ?: $this->config()->default_route;
// Legacy. Find the first route mapped to the controller.
if (!$route && !empty($routes)) {
$route = $routes[0];
}
if (!$route) {
throw new \RuntimeException("There are no routes set up for a GraphQL server. You will need to add one to the SilverStripe\Control\Director.rules config setting.");
}
$route = trim($route, '/');
$jsonRoutes = json_encode($routes);
$securityID = Controller::config()->enable_csrf_protection
? "'" . SecurityToken::inst()->getValue() . "'"
: 'null';
Requirements::customScript(
<<<JS
var GRAPHQL_ROUTE = '{$route}';
var GRAPHQL_ROUTES = $jsonRoutes;
var SECURITY_ID = $securityID;
JS
);
Requirements::javascript('silverstripe/graphql-devtools: client/dist/graphiql.js');
}
|
Initialise the controller, sanity check, load javascript.
Note that permission checks are handled by DevelopmentAdmin.
|
protected function findAvailableRoutes()
{
$routes = [];
$rules = Director::config()->get('rules');
foreach ($rules as $pattern => $controllerInfo) {
$routeClass = (is_string($controllerInfo)) ? $controllerInfo : $controllerInfo['Controller'];
try {
$routeController = Injector::inst()->get($routeClass);
if ($routeController instanceof Controller) {
$routes[] = $pattern;
}
} catch (InjectorNotFoundException $ex) {
}
}
return $routes;
}
|
Find all available graphql routes
@return string[]
|
public function all($order_id, $params = [], array $options = array())
{
list($code, $line_items) = $this->httpClient->get("/orders/{$order_id}/line_items", $params, $options);
return $line_items;
}
|
Retrieve order's line items
get '/orders/{order_id}/line_items'
Returns all line items associated to order
@param integer $order_id Unique identifier of a Order
@param array $params Search options
@param array $options Additional request's options.
@return array The list of LineItems for the first page, unless otherwise specified.
|
public function create($order_id, array $lineItem, array $options = array())
{
$attributes = array_intersect_key($lineItem, array_flip(self::$keysToPersist));
list($code, $createdLineItem) = $this->httpClient->post("/orders/{$order_id}/line_items", $attributes, $options);
return $createdLineItem;
}
|
Create a line item
post '/orders/{order_id}/line_items'
Adds a new line item to an existing order
Line items correspond to products in the catalog, so first you must create products
Because products allow defining different prices in different currencies, when creating a line item, the parameter currency is required
@param integer $order_id Unique identifier of a Order
@param array $lineItem This array's attributes describe the object to be created.
@param array $options Additional request's options.
@return array The resulting object representing created resource.
|
public function get($order_id, $id, array $options = array())
{
list($code, $line_item) = $this->httpClient->get("/orders/{$order_id}/line_items/{$id}", null, $options);
return $line_item;
}
|
Retrieve a single line item
get '/orders/{order_id}/line_items/{id}'
Returns a single line item of an order, according to the unique line item ID provided
@param integer $order_id Unique identifier of a Order
@param integer $id Unique identifier of a LineItem
@param array $options Additional request's options.
@return array Searched LineItem.
|
public function create(array $contact, array $options = array())
{
$attributes = array_intersect_key($contact, array_flip(self::$keysToPersist));
if (isset($attributes['custom_fields']) && empty($attributes['custom_fields'])) unset($attributes['custom_fields']);
list($code, $createdContact) = $this->httpClient->post("/contacts", $attributes, $options);
return $createdContact;
}
|
Create a contact
post '/contacts'
Create a new contact
A contact may represent a single individual or an organization
@param array $contact This array's attributes describe the object to be created.
@param array $options Additional request's options.
@return array The resulting object representing created resource.
|
public function update($id, array $contact, array $options = array())
{
$attributes = array_intersect_key($contact, array_flip(self::$keysToPersist));
if (isset($attributes['custom_fields']) && empty($attributes['custom_fields'])) unset($attributes['custom_fields']);
list($code, $updatedContact) = $this->httpClient->put("/contacts/{$id}", $attributes, $options);
return $updatedContact;
}
|
Update a contact
put '/contacts/{id}'
Updates contact information
If the specified contact does not exist, the request will return an error
**Notice** When updating contact tags, you need to provide all tags
Any missing tag will be removed from a contact's tags
@param integer $id Unique identifier of a Contact
@param array $contact This array's attributes describe the object to be updated.
@param array $options Additional request's options.
@return array The resulting object representing updated resource.
|
public function validate(ValidationResult $validationResult)
{
$validator = new SynonymValidator(array(
'SearchSynonyms',
));
$validator->php(array(
'SearchSynonyms' => $this->owner->SearchSynonyms
));
$errors = $validator->getErrors();
if (is_array($errors) || $errors instanceof Traversable) {
foreach ($errors as $error) {
$validationResult->addError($error['message']);
}
}
}
|
@inheritdoc
@param ValidationResult $validationResult
|
public function create(array $dealSource, array $options = array())
{
$attributes = array_intersect_key($dealSource, array_flip(self::$keysToPersist));
list($code, $createdDealSource) = $this->httpClient->post("/deal_sources", $attributes, $options);
return $createdDealSource;
}
|
Create a new source
post '/deal_sources'
Creates a new source
<figure class="notice">
Source's name **must** be unique
</figure>
@param array $dealSource This array's attributes describe the object to be created.
@param array $options Additional request's options.
@return array The resulting object representing created resource.
|
public function update($id, array $dealSource, array $options = array())
{
$attributes = array_intersect_key($dealSource, array_flip(self::$keysToPersist));
list($code, $updatedDealSource) = $this->httpClient->put("/deal_sources/{$id}", $attributes, $options);
return $updatedDealSource;
}
|
Update a source
put '/deal_sources/{id}'
Updates source information
If the specified source does not exist, the request will return an error
<figure class="notice">
If you want to update a source, you **must** make sure source's name is unique
</figure>
@param integer $id Unique identifier of a DealSource
@param array $dealSource This array's attributes describe the object to be updated.
@param array $options Additional request's options.
@return array The resulting object representing updated resource.
|
public function init()
{
foreach ($this->dynamic as $key => $data) {
$field = &$this->items[$key];
foreach ($data as $property => $call) {
$action = 'dynamic' . ucfirst($call['action']);
if (method_exists($this, $action)) {
$this->{$action}($field, $property, $call);
}
}
}
return $this;
}
|
Initialize blueprints with its dynamic fields.
@return $this
|
public function get($name, $default = null, $separator = '.')
{
$name = $separator !== '.' ? str_replace($separator, '.', $name) : $name;
return isset($this->items[$name]) ? $this->items[$name] : $default;
}
|
Get value by using dot notation for nested arrays/objects.
@example $value = $data->get('this.is.my.nested.variable');
@param string $name Dot separated path to the requested value.
@param mixed $default Default value (or null).
@param string $separator Separator, defaults to '.'
@return mixed Value.
|
public function set($name, $value, $separator = '.')
{
$name = $separator !== '.' ? str_replace($separator, '.', $name) : $name;
$this->items[$name] = $value;
$this->addProperty($name);
}
|
Set value by using dot notation for nested arrays/objects.
@example $value = $data->set('this.is.my.nested.variable', $newField);
@param string $name Dot separated path to the requested value.
@param mixed $value New value.
@param string $separator Separator, defaults to '.'
|
public function def($name, $value, $separator = '.')
{
$this->set($name, $this->get($name, $value, $separator), $separator);
}
|
Define value by using dot notation for nested arrays/objects.
@example $value = $data->set('this.is.my.nested.variable', true);
@param string $name Dot separated path to the requested value.
@param mixed $value New value.
@param string $separator Separator, defaults to '.'
|
public function getState()
{
return [
'items' => $this->items,
'rules' => $this->rules,
'nested' => $this->nested,
'dynamic' => $this->dynamic,
'filter' => $this->filter
];
}
|
Convert object into an array.
@return array
|
public function embed($name, array $value, $separator = '.', $merge = false)
{
if (isset($value['rules'])) {
$this->rules = array_merge($this->rules, $value['rules']);
}
$name = $separator !== '.' ? str_replace($separator, '.', $name) : $name;
if (isset($value['form'])) {
$form = array_diff_key($value['form'], ['fields' => 1, 'field' => 1]);
} else {
$form = [];
}
$items = isset($this->items[$name]) ? $this->items[$name] : ['type' => '_root', 'form_field' => false];
$this->items[$name] = $items;
$this->addProperty($name);
$prefix = $name ? $name . '.' : '';
$params = array_intersect_key($form, $this->filter);
$location = [$name];
if (isset($value['form']['field'])) {
$this->parseFormField($name, $value['form']['field'], $params, $prefix, '', $merge, $location);
} elseif (isset($value['form']['fields'])) {
$this->parseFormFields($value['form']['fields'], $params, $prefix, '', $merge, $location);
}
$this->items[$name] += ['form' => $form];
return $this;
}
|
Embed an array to the blueprint.
@param $name
@param array $value
@param string $separator
@param bool $merge Merge fields instead replacing them.
@return $this
|
public function mergeData(array $data1, array $data2, $name = null, $separator = '.')
{
$nested = $this->getNested($name, $separator);
if (!\is_array($nested)) {
$nested = [];
}
return $this->mergeArrays($data1, $data2, $nested);
}
|
Merge two arrays by using blueprints.
@param array $data1
@param array $data2
@param string $name Optional
@param string $separator Optional
@return array
|
public function getProperty($path = null, $separator = '.')
{
$name = $this->getPropertyName($path, $separator);
$property = $this->get($name);
$nested = $this->getNested($name);
return $this->getPropertyRecursion($property, $nested);
}
|
Get the property with given path.
@param string $path
@param string $separator
@return mixed
|
public function getPropertyName($path = null, $separator = '.')
{
$parts = explode($separator, $path);
$nested = $this->nested;
$result = [];
while (($part = array_shift($parts)) !== null) {
if (!isset($nested[$part])) {
if (isset($nested['*'])) {
$part = '*';
} else {
return implode($separator, array_merge($result, [$part], $parts));
}
}
$result[] = $part;
$nested = $nested[$part];
}
return implode('.', $result);
}
|
Returns name of the property with given path.
@param string $path
@param string $separator
@return string
|
public function extra(array $data, $prefix = '')
{
$rules = $this->nested;
// Drill down to prefix level
if (!empty($prefix)) {
$parts = explode('.', trim($prefix, '.'));
foreach ($parts as $part) {
$rules = isset($rules[$part]) ? $rules[$part] : [];
}
}
// Check if the form cannot have extra fields.
if (isset($rules[''])) {
$rule = $this->items[''];
if (isset($rule['type']) && $rule['type'] !== '_root') {
return [];
}
}
return $this->extraArray($data, $rules, $prefix);
}
|
Return data fields that do not exist in blueprints.
@param array $data
@param string $prefix
@return array
|
protected function getPropertyRecursion($property, $nested)
{
if (empty($nested) || !\is_array($nested) || !isset($property['type'])) {
return $property;
}
if ($property['type'] === '_root') {
foreach ($nested as $key => $value) {
if ($key === '') {
continue;
}
$name = \is_array($value) ? $key : $value;
$property['fields'][$key] = $this->getPropertyRecursion($this->get($name), $value);
}
} elseif ($property['type'] === '_parent' || !empty($property['array'])) {
foreach ($nested as $key => $value) {
$name = \is_array($value) ? "{$property['name']}.{$key}" : $value;
$property['fields'][$key] = $this->getPropertyRecursion($this->get($name), $value);
}
}
return $property;
}
|
Get the property with given path.
@param $property
@param $nested
@return mixed
|
protected function getNested($path = null, $separator = '.')
{
if (!$path) {
return $this->nested;
}
$parts = explode($separator, $path);
$item = array_pop($parts);
$nested = $this->nested;
foreach ($parts as $part) {
if (!isset($nested[$part])) {
$part = '*';
if (!isset($nested[$part])) {
return [];
}
}
$nested = $nested[$part];
}
return isset($nested[$item]) ? $nested[$item] : (isset($nested['*']) ? $nested['*'] : null);
}
|
Get property from the definition.
@param string $path Comma separated path to the property.
@param string $separator
@return array|string|null
@internal
|
protected function parseFormFields(array $fields, array $params, $prefix = '', $parent = '', $merge = false, array $formPath = [])
{
if (isset($fields['type']) && !\is_array($fields['type'])) {
return;
}
// Go though all the fields in current level.
foreach ($fields as $key => $field) {
$this->parseFormField($key, $field, $params, $prefix, $parent, $merge, $formPath);
}
}
|
Gets all field definitions from the blueprints.
@param array $fields Fields to parse.
@param array $params Property parameters.
@param string $prefix Property prefix.
@param string $parent Parent property.
@param bool $merge Merge fields instead replacing them.
@param array $formPath
|
protected function addProperty($path)
{
$parts = explode('.', $path);
$item = array_pop($parts);
$nested = &$this->nested;
foreach ($parts as $part) {
if (!isset($nested[$part]) || !\is_array($nested[$part])) {
$nested[$part] = [];
}
$nested = &$nested[$part];
}
if (!isset($nested[$item])) {
$nested[$item] = $path;
}
}
|
Add property to the definition.
@param string $path Comma separated path to the property.
@internal
|
public function toYaml($inline = 3, $indent = 2)
{
return Yaml::dump($this->toArray(), $inline, $indent, true, false);
}
|
Convert object into YAML string.
@param int $inline The level where you switch to inline YAML.
@param int $indent The amount of spaces to use for indentation of nested nodes.
@return string A YAML string representing the object.
@throws DumpException
|
public function php($data)
{
foreach ($this->fieldNames as $fieldName) {
if (empty($data[$fieldName])) {
return;
}
$this->validateField($fieldName, $data[$fieldName]);
}
}
|
@inheritdoc
@param array $data
@return mixed
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.