code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
public function getBasicValueForArrayProperty(PropertyDefinition $propertyDefinition, $rawValue) { if (!$propertyDefinition->getIsArray() || !is_array($rawValue)) { return []; } $values = []; foreach ($rawValue as $rawValueItem) { if ($propertyDefinition->getType() == PropertyDefinition::BASIC_TYPE_INTEGER) { if (is_numeric($rawValueItem) || is_bool($rawValueItem) || is_string($rawValueItem)) { $values[] = intval($rawValueItem); } } else if ($propertyDefinition->getType() == PropertyDefinition::BASIC_TYPE_FLOAT) { if (is_numeric($rawValueItem) || is_bool($rawValueItem) || is_string($rawValueItem)) { $values[] = floatval($rawValueItem); } } else if ($propertyDefinition->getType() == PropertyDefinition::BASIC_TYPE_STRING) { if (!is_array($rawValueItem) && !is_object($rawValueItem)) { $values[] = strval($rawValueItem); } } else if ($propertyDefinition->getType() == PropertyDefinition::BASIC_TYPE_BOOLEAN) { if (!is_array($rawValueItem) && !is_object($rawValueItem)) { $values[] = boolval($rawValueItem); } } else { // skip this value } } return $values; }
@param PropertyDefinition $propertyDefinition @param $rawValue @return array|mixed[]
public function getEmptyValueForArrayProperty(PropertyDefinition $propertyDefinition) { if ($propertyDefinition->getIsArray()) { return []; } else { if ($propertyDefinition->getIsObject()) { return $this->getEmptyObjectValueForProperty($propertyDefinition); } else { return $this->getEmptyBasicValueForProperty($propertyDefinition); } } }
@param PropertyDefinition $propertyDefinition @return array
public function fillObjectWithRawData($targetObject, stdClass $rawData) { $this->filler->fillObjectWithRawData($targetObject, $rawData); return $targetObject; }
@param object $targetObject POJO @param stdClass $rawData @return object the same as $targetObject
public function convert($value) { if (is_array(($value))) { $retval = []; foreach ($value as $object) { $retval[] = $this->convert($object); // force sequential indexing } return $retval; } else if (is_object($value)) { return $this->convertObject($value); } else { return $value; } }
@param object|array $value @return \stdClass
private function getPropertiesFromObjectOrParentClasses(\ReflectionObject $object) { $allProperties = array(); $currentClassReflection = $object; while ((bool)$currentClassReflection) // class without parent has null in getParentClass() { $properties = $currentClassReflection->getProperties(); foreach ($properties as $property) { // add only properties defined in current class // properties added in parent classes will be added later if ($property->getDeclaringClass()->getName() == $currentClassReflection->getName()) { $allProperties[] = $property; } } // go to parent class $currentClassReflection = $currentClassReflection->getParentClass(); } return $allProperties; }
@param \ReflectionObject $object @return array[]|\ReflectionProperty[] \ReflectionClass::getProperties() checks only properties from current class and all nonprivate properties from parent classes. So private properties from parent classes will not be found. We have workaround for this problem, by checking parent classes directly for their properties http://www.php.net/manual/en/reflectionclass.hasproperty.php#94038 http://stackoverflow.com/questions/9913680/does-reflectionclassgetproperties-also-get-properties-of-the-parent
public function buildFromClass($classname) { $reflectionClass = new ReflectionClass($classname); $classDefinition = new ClassDefinition(); $classDefinition->name = $reflectionClass->getName(); $classDefinition->namespace = $reflectionClass->getNamespaceName(); $reflectionProperties = $this->classPropertyFinder->findProperties($reflectionClass); foreach ($reflectionProperties as $reflectionProperty) { $classDefinition->properties[$reflectionProperty->getName()] = $this->buildPropertyDefinition($reflectionProperty); } return $classDefinition; }
@param string $classname @return ClassDefinition
public function fillObjectWithRawData($targetObject, $rawData) { $classDefinition = $this->classDefinitionBuilder->buildFromClass(get_class($targetObject)); $this->processObject($classDefinition, $targetObject, $rawData); }
@param object $targetObject @param \stdClass $rawData @throws ObjectFillingException - if class for property does not exist - if $rawData is not an object
public function init() { $git_repo = exec('basename `git rev-parse --show-toplevel`'); // Remove instructions for creating a new repo, because we've got one now. $readme_contents = file_get_contents('README.md'); $start_string = '### Initial build (new repo)'; $end_string = '### Initial build (existing repo)'; $from = $this->findAllTextBetween($start_string, $end_string, $readme_contents); $find_replaces = array( array( 'source' => 'composer.json', 'from' => '"name": "thinkshout/drupal-project",', 'to' => '"name": "thinkshout/' . $git_repo . '",', ), array( 'source' => '.env.dist', 'from' => 'TS_PROJECT="SITE"', 'to' => 'TS_PROJECT="' . $git_repo . '"', ), array( 'source' => 'README.md', 'from' => array($from, 'new-project-name'), 'to' => array($end_string, $git_repo), ), ); foreach ($find_replaces as $find_replace) { $this->taskReplaceInFile($find_replace['source']) ->from($find_replace['from']) ->to($find_replace['to']) ->run(); } }
Initialize the project for the first time. @return \Robo\Result
function install() { if(getenv('CIRCLECI')) { // Do nothing custom here. return $this->trueFreshInstall(); } elseif ($this->databaseSourceOfTruth()) { $this->prepareLocal(); } else { $this->trueFreshInstall(); $this->postInstall(); } }
Install or re-install the Drupal site. @return \Robo\Result
private function trueFreshInstall() { // Use user environment settings if we have them. if ($system_defaults = getenv('PRESSFLOW_SETTINGS')) { $settings = json_decode($system_defaults, TRUE); $admin_name = $this->projectProperties['admin_name']; $db_settings = $settings['databases']['default']['default']; $install_cmd = 'site-install --existing-config' . ' --db-url=mysql://' . $db_settings['username'] . ':' . $db_settings['password'] . '@' . $db_settings['host'] . ':' . $db_settings['port'] . '/' . $db_settings['database'] . ' -y --account-name=' . $admin_name; } else { $install_cmd = 'site-install standard -y'; } // Install dependencies. Only works locally. $this->taskComposerInstall() ->optimizeAutoloader() ->run(); $this->_chmod($this->projectProperties['web_root'] . '/sites/default', 0755); if (file_exists($this->projectProperties['web_root'] . '/sites/default/settings.php')) { $this->_chmod($this->projectProperties['web_root'] . '/sites/default/settings.php', 0755); } $install_cmd = 'drush ' . $install_cmd; // Run the installation. $result = $this->taskExec($install_cmd) ->dir($this->projectProperties['web_root']) ->run(); if ($result->wasSuccessful()) { $this->say('Install complete'); } return $result; }
Install or re-install the Drupal site. @return \Robo\Result
function setUpBehat() { // Ensure that this system has headless Chrome. if (!$this->taskExec('which chromedriver')->run()->wasSuccessful()) { $os = exec('uname'); // Here we assume either OS X (a dev's env) or not (a CI env). if ($os == 'Darwin') { $this->taskExec('brew install chromedriver') ->run(); } else { $version = exec('curl http://chromedriver.storage.googleapis.com/LATEST_RELEASE'); $this->taskExec("wget http://chromedriver.storage.googleapis.com/{$version}/chromedriver_linux64.zip") ->run(); $this->taskExec('unzip chromedriver_linux64.zip') ->run(); $this->taskFilesystemStack() ->rename('chromedriver', 'vendor/bin/chromedriver') ->run(); $this->taskFilesystemStack() ->remove('chromedriver_linux64.zip') ->run(); } } }
Ensure that the filesystem has everything Behat needs. At present, that's only chromedriver, AKA "Headless Chrome".
protected function replaceArraySetting($file, $key, $value) { $this->taskReplaceInFile($file) ->regex("/'$key' => '[^'\\\\]*(?:\\\\.[^'\\\\]*)*',/s") ->to("'$key' => '". $value . "',") ->run(); }
Use regex to replace a 'key' => 'value', pair in a file like a settings file. @param $file @param $key @param $value
protected function getPantheonSiteEnv($env = '') { $site = getenv('TERMINUS_SITE'); if (!$env) { $env = getenv('TERMINUS_ENV'); } return join('.', [$site, $env]); }
Get "<site>.<env>" commonly used in terminus commands.
private function findAllTextBetween($beginning, $end, $string) { $beginningPos = strpos($string, $beginning); $endPos = strpos($string, $end); if ($beginningPos === false || $endPos === false) { return ''; } $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos); return $textToDelete; }
Finds the text between two strings within a third string. @param $beginning @param $end @param $string @return string String containing $beginning, $end, and everything in between.
public function postDeploy() { $terminus_site_env = $this->getPantheonSiteEnv(); $pantheon_prefix = getenv('TERMINUS_SITE'); if ($terminus_site_env == $pantheon_prefix . '.develop' || $terminus_site_env == $pantheon_prefix . '.dev') { $drush_commands = [ 'drush_partial_config_import' => "terminus remote:drush $terminus_site_env -- config-import --partial -y", 'drush_cache_clear' => "terminus remote:drush $terminus_site_env -- cr", 'drush_entity_updates' => "terminus remote:drush $terminus_site_env -- entity-updates -y", 'drush_update_database' => "terminus remote:drush $terminus_site_env -- updb -y", 'drush_full_config_import' => "terminus remote:drush $terminus_site_env -- config-import -y", ]; // Run the installation. $result = $this->taskExec(implode(' && ', $drush_commands)) ->run(); } }
Clean up state of Pantheon dev & develop environments after deploying. Run this by adding the line: robo post:deploy right after this line: robo pantheon:deploy --y in your .circleci/config.yml file.
public function prepareLocal() { $do_composer_install = TRUE; $project_properties = $this->getProjectProperties(); $grab_database = $this->confirm("Load a database backup?"); if ($grab_database == 'y') { $do_composer_install = $this->getDatabaseOfTruth(); } if ($do_composer_install) { $this->taskComposerInstall() ->optimizeAutoloader() ->run(); $drush_commands = [ 'drush_clear_cache' => 'drush cr', 'drush_update_database' => 'drush updb', 'drush_grab_config_changes' => 'drush config-import -y', 'drush_grab_config_local_changes' => 'drush config-split:import local -y', ]; $this->taskExec(implode(' && ', $drush_commands)) ->dir($project_properties['web_root']) ->run(); } }
Prepare your local machine for development. Pulls the database of truth, brings the database in line with local config, and enables local development modules, including config suite.
private function getDatabaseOfTruth() { $project_properties = $this->getProjectProperties(); $default_database = $this->databaseSourceOfTruth(); if (file_exists('vendor/database.sql.gz')) { $default_database = 'local'; } $this->say('This command will drop all tables in your local database and re-populate from a backup .sql.gz file.'); $this->say('If you already have a database backup in your vendor folder, the "local" option will be available.'); $this->say('If you want to grab a more recent backup from Pantheon, type in the environment name (i.e. dev, test, live, my-multidev). This will be saved to your vendor folder for future re-installs.'); $this->say('Backups are generated on Pantheon regularly, but might be old.'); $this->say('If you need the very latest data from a Pantheon site, go create a new backup using either the Pantheon backend, or Terminus.'); $which_database = $this->askDefault( 'Which database backup should we load (i.e. local/dev/live)?', $default_database ); $getDB = TRUE; if ($which_database !== 'local') { $getDB = $this->downloadPantheonBackup($which_database); } if ($getDB) { $this->say('Emptying existing database.'); $empty_database = $this->taskExec('drush sql:drop -y')->dir($project_properties['web_root'])->run(); return $this->importLocal(); } else { $this->yell('Failed to download a Pantheon backup. Database was not refreshed.'); return false; } }
Helper function to pull the database of truth to your local machine. @return bool If the remote database was reached and downloaded, return TRUE.
private function downloadPantheonBackup($env) { $project_properties = $this->getProjectProperties(); $terminus_site_env = $this->getPantheonSiteEnv($env); $terminus_url_request = $this->taskExec('terminus backup:get ' . $terminus_site_env . ' --element="db"') ->dir($project_properties['web_root']) ->interactive(false) ->run(); if ($terminus_url_request->wasSuccessful()) { $terminus_url = $terminus_url_request->getMessage(); } else { $this->yell('Failed to find a recent backup for the ' . $terminus_site_env . ' site. Does one exist?'); return FALSE; } $wget_database = $this->taskExec('wget -O vendor/database.sql.gz "' . trim($terminus_url) . '"')->run(); if (!$wget_database->wasSuccessful()) { $this->yell('Remote database sync failed.'); return FALSE; } return TRUE; }
Grabs a backup from Pantheon. @param $env The environemnt to get the backup from. @return bool True if the backup was downloaded.
public function importLocal() { $project_properties = $this->getProjectProperties(); $drush_commands = [ 'drush_import_database' => 'zcat < ../vendor/database.sql.gz | drush @self sqlc # Importing local copy of db.' ]; $database_import = $this->taskExec(implode(' && ', $drush_commands))->dir($project_properties['web_root'])->run(); if ($database_import->wasSuccessful()) { return TRUE; } else { $this->yell('Could not read vendor/database.sql.gz into your local database. See if the command "zcat < vendor/database.sql.gz | drush @self sqlc" works outside of robo.'); return FALSE; } }
Imports a local database. @return bool True if import succeeded.
public function migrateCleanup($opts = ['migrations' => '']) { if ($opts['migrations'] && ($this->migrationSourceFolder() || $this->usesMigrationPlugins)) { $migrations = explode(',', $opts['migrations']); $project_properties = $this->getProjectProperties(); foreach ($migrations as $migration) { $this->taskExec('drush mrs ' . $migration) ->dir($project_properties['web_root']) ->run(); } } if ($this->migrationSourceFolder()) { $this->taskExec('drush mr --all && drush cim --partial --source=' . $this->migrationSourceFolder() . ' -y && drush ms') ->dir($project_properties['web_root']) ->run(); } else if ($this->usesMigrationPlugins) { $this->taskExec('drush cr && drush mr --all && drush ms') ->dir($project_properties['web_root']) ->run(); } else { $this->say('No migration sources configured.'); $this->say('To use this command, you must either return a folder path from the migrationSourceFolder() method or set $usesMigrationPlugins to TRUE in your project\'s RoboFile.php.'); return FALSE; } }
Cleanup migrations. @option string migrations Optional list of migrations to reset, separated by commmas.
public static function update($force = false) { if (!defined('SEMALT_UNIT_TESTING') && !self::isWritable()) { return; } if (!$force && !self::isOutdated()) { return; } self::doUpdate(); }
Try to update the blocked domains list. @param bool $force
public static function blocked($verbose = false) { $blocked = self::isRefererOnBlocklist(); if ($verbose === true) { return self::$reason; } return $blocked; }
@param bool $verbose Deprecated. Please use the explain() method instead. @return bool|string
public static function isRefererOnBlocklist() { $referer = self::getHttpReferer(); if ($referer === null) { self::$reason = 'Not blocking because referer header is not set or empty'; return false; } return self::isUrlOnBlocklist($referer, 'referer'); }
The public use of this function is undocumented. @return bool
public static function isUrlOnBlocklist($url, $entity = 'url') { $rootDomain = Domainparser::getRootDomain($url); if ($rootDomain === false) { self::$reason = "Not blocking because we couldn't parse root domain"; return false; } $blocklist = self::getConcatenateBlocklist(); if (substr_count($blocklist, self::SEPERATOR . $rootDomain . self::SEPERATOR)) { self::$reason = 'Blocking because ' . $entity . ' root domain (' . $rootDomain . ') is found on blocklist'; return true; } $hostname = Domainparser::getHostname($url); if (substr_count($blocklist, self::SEPERATOR . $hostname . self::SEPERATOR)) { self::$reason = 'Blocking because ' . $entity . ' hostname (' . $hostname . ') is found on blocklist'; return true; } $path = Domainparser::getPath($url); if (trim($path, '/')) { if (substr_count($blocklist, self::SEPERATOR . $rootDomain . $path . self::SEPERATOR)) { self::$reason = 'Blocking because ' . $entity . ' root domain/path (' . $rootDomain . $path . ') is found on blocklist'; return true; } if (substr_count($blocklist, self::SEPERATOR . $hostname . $path . self::SEPERATOR)) { self::$reason = 'Blocking because ' . $entity . ' hostname/path (' . $hostname . $path . ') is found on blocklist'; return true; } } self::$reason = 'Not blocking because ' . $entity . ' (' . $url . ') is not matched against blocklist'; return false; }
The public use of this function is undocumented. @param string $url @param string $entity @return bool
private static function concatenateBlocklist($blocklistContent) { return self::SEPERATOR . str_replace(PHP_EOL, self::SEPERATOR, strtolower($blocklistContent)) . self::SEPERATOR; }
@param string $blocklistContent @return string
public static function getRootDomain($url) { $host = $domain = self::getHostname($url); $root = false; if (($dotsCount = substr_count($host, '.')) > 0) { $last = $domain; while ($dotsCount > -1) { if (self::isHostInSuffixList($domain)) { $root = $last; break; } $last = trim($domain, '.'); $domain = substr($last, strpos($last, '.')); $dotsCount = $dotsCount - 1; } } return $root; }
Extracts lower-case ASCII root domain from URL if it is available and valid, returns false otherwise. @param string $url @return false|string
public static function getHostname($url) { if (!isset(self::$cache[$url]['hostname'])) { self::$cache[$url]['hostname'] = self::parseUrl($url, PHP_URL_HOST); } return self::$cache[$url]['hostname']; }
@param string $url @return string|false
public static function getPath($url) { if (!isset(self::$cache[$url]['path'])) { self::$cache[$url]['path'] = self::parseUrl($url, PHP_URL_PATH); } return self::$cache[$url]['path']; }
@param string $url @return string
private static function parseUrl($url, $component) { if (!isset(self::$cache[$url]['url'])) { // Strip protocol $scheme = parse_url($url, PHP_URL_SCHEME); $url = str_replace($scheme . '://', '', $url); $url = str_replace($scheme . ':', '', $url); // Punycode encode domain $host = parse_url('http://' . $url, PHP_URL_HOST); $punycode = new Punycode(); $url = str_replace($host, $punycode->encode($host), $url); // Add back normalized protocol $url = 'http://' . $url; // Remove all illegal characters from a url $url = filter_var($url, FILTER_SANITIZE_URL); // Sanity check if (($check = filter_var($url, FILTER_VALIDATE_URL)) === false) { $url = false; } self::$cache[$url]['url'] = $url; } return parse_url(strtolower(self::$cache[$url]['url']), $component); }
Checks an URL for validity, and punycode encode the returned component. @param string $url @param int $component @return string|false
protected function construct():void{ $traits = (new ReflectionClass($this))->getTraits(); foreach($traits as $trait){ $method = $trait->getShortName(); if(method_exists($this, $method)){ call_user_func([$this, $method]); } } }
calls a method with trait name as replacement constructor for each used trait (remember pre-php5 classname constructors? yeah, basically this.) @return void
public function complete(Node $node, TextDocument $source, ByteOffset $offset): Generator { /** @var TolerantCompletor $completor */ $completor = $this->completor; $count = 0; foreach ($completor->complete($node, $source, $offset) as $suggestion) { yield $suggestion; if (++$count === $this->limit) { break; } } }
{@inheritDoc}
public function complete(Node $node, TextDocument $source, ByteOffset $offset): Generator { $classes = get_declared_classes(); $classes = array_filter($classes, function ($class) use ($node) { $name = Name::fromString($class); return 0 === strpos($name->short(), $node->getText()); }); foreach ($classes as $class) { try { $reflectionClass = $this->reflector->reflectClass($class); } catch (NotFound $e) { continue; } yield Suggestion::createWithOptions( $class, [ 'type' => Suggestion::TYPE_CLASS, 'short_description' => $this->formatter->format($reflectionClass), ] ); } }
{@inheritDoc}
public function keysgroup(array $keysgroup): self { $this->transaction->asset['multisignature']['keysgroup'] = $keysgroup; $this->transaction->fee = (count($keysgroup) + 1) * $this->transaction->fee; return $this; }
Set the keysgroup of signatures. @param array $keysgroup @return \ArkEcosystem\Crypto\Transactions\Builder\MultiSignatureRegistration
public function serialize(): void { $delegateBytes = bin2hex($this->transaction['asset']['delegate']['username']); $this->buffer->writeUInt8(strlen($delegateBytes) / 2); $this->buffer->writeHexBytes($delegateBytes); }
Handle the serialization of "vote" data. @return string
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $voteLength = $this->buffer->readUInt8() & 0xff; $this->transaction->asset = ['votes' => []]; $vote = null; for ($i = 0; $i < $voteLength; $i++) { $this->buffer->position($this->assetOffset + 2 + $i * 2 * 34); $vote = $this->buffer->readHexRaw(34 * 2); $vote = ('1' === $vote[1] ? '+' : '-').substr($vote, 2); $this->transaction->asset['votes'][] = $vote; } return $this->parseSignatures($this->assetOffset + 2 + $voteLength * 34 * 2); }
Handle the deserialization of "second signature registration" data. @return object
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $this->transaction->asset = ['payments' => []]; $count = $this->buffer->readUInt16() & 0xff; $offset = $this->assetOffset / 2 + 1; for ($i = 0; $i < $count; $i++) { $this->transaction->asset['payments'][] = [ 'amount' => $this->buffer->readUInt64(), 'recipientId' => Base58::encodeCheck(new Buffer(hex2bin($this->buffer->readHex(21)))), ]; $offset += 22; } $this->transaction->amount = array_sum(array_column($this->transaction->asset['payments'], 'amount')); return $this->parseSignatures($offset * 2); }
Handle the deserialization of "multi payment" data. @return object
public function sign(string $passphrase): AbstractTransaction { $publicKey = PublicKey::fromPassphrase($passphrase); $this->transaction->asset['delegate']['publicKey'] = $publicKey->getHex(); parent::sign($passphrase); return $this; }
Sign the transaction using the given passphrase. @param string $passphrase @return \ArkEcosystem\Crypto\Transactions\Builder\AbstractTransaction
public function deserialize(): Transaction { $transaction = new Transaction(); $transaction->version = $this->buffer->readUInt8(); $transaction->network = $this->buffer->readUInt8(); $transaction->type = $this->buffer->readUInt8(); $transaction->timestamp = $this->buffer->readUInt32(); $transaction->senderPublicKey = $this->buffer->readHex(33); $transaction->fee = $this->buffer->readUInt64(); $vendorFieldLength = $this->buffer->readUInt8(); if ($vendorFieldLength > 0) { $transaction->vendorFieldHex = $this->buffer->readHex($vendorFieldLength); } $assetOffset = (41 + 8 + 1) * 2 + $vendorFieldLength * 2; $transaction = $this->handleType($assetOffset, $transaction); if (! isset($transaction->amount)) { $transaction->amount = 0; } if (! isset($transaction->version) || 1 === $transaction->version) { $transaction = $this->handleVersionOne($transaction); } if (2 === $transaction->version) { $transaction = $this->handleVersionTwo($transaction); } return $transaction; }
Perform AIP11 compliant deserialization. @return \ArkEcosystem\Crypto\Transactions\Transaction
public function handleType(int $assetOffset, Transaction $transaction): Transaction { $deserializer = $this->deserializers[$transaction->type]; return (new $deserializer($this->buffer, $assetOffset, $transaction))->deserialize(); }
Handle the deserialization of transaction data. @param int $assetOffset @param \ArkEcosystem\Crypto\Transaction $transaction @return \ArkEcosystem\Crypto\Transactions\Transaction
public function handleVersionOne(Transaction $transaction): Transaction { if (isset($transaction->secondSignature)) { $transaction->signSignature = $transaction->secondSignature; } if (Types::VOTE === $transaction->type) { $transaction->recipientId = Address::fromPublicKey($transaction->senderPublicKey, $transaction->network); } if (Types::MULTI_SIGNATURE_REGISTRATION === $transaction->type) { $transaction->asset['multisignature']['keysgroup'] = array_map(function ($key) { return '+'.$key; }, $transaction->asset['multisignature']['keysgroup']); } if (isset($transaction->vendorFieldHex)) { $transaction->vendorField = hex2bin($transaction->vendorFieldHex); } if (! isset($transaction->id)) { $transaction->id = $transaction->getId(); } if (Types::SECOND_SIGNATURE_REGISTRATION === $transaction->type) { $transaction->recipientId = Address::fromPublicKey($transaction->senderPublicKey, $transaction->network); } if (Types::MULTI_SIGNATURE_REGISTRATION === $transaction->type) { $transaction->recipientId = Address::fromPublicKey($transaction->senderPublicKey, $transaction->network); } return $transaction; }
Handle the deserialization of transaction data with a version of 1.0. @param \ArkEcosystem\Crypto\Transaction $transaction @return \ArkEcosystem\Crypto\Transactions\Transaction
public function handleVersionTwo(Transaction $transaction): Transaction { $transaction->id = Hash::sha256($transaction->serialize())->getHex(); return $transaction; }
Handle the deserialization of transaction data with a version of 2.0. @param \ArkEcosystem\Crypto\Transaction $transaction @return \ArkEcosystem\Crypto\Transactions\Transaction
public function serialize(): void { $dag = $this->transaction['asset']['ipfs']['dag']; $this->buffer->writeUInt8(strlen($dag) / 2); $this->buffer->writeHexBytes($dag); }
Handle the serialization of "ipfs" data. @return string
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $this->transaction->amount = $this->buffer->readUInt64(); $this->transaction->expiration = $this->buffer->readUInt32(); $this->transaction->recipientId = Base58::encodeCheck(new Buffer(hex2bin($this->buffer->readHex(21)))); return $this->parseSignatures($this->assetOffset + (8 + 4 + 21) * 2); }
Handle the deserialization of "transfer" data. @return object
public function sign(string $passphrase): self { $keys = PrivateKey::fromPassphrase($passphrase); $this->transaction->senderPublicKey = $keys->getPublicKey()->getHex(); $this->transaction = $this->transaction->sign($keys); $this->transaction->id = $this->transaction->getId(); return $this; }
Sign the transaction using the given passphrase. @param string $passphrase @return \ArkEcosystem\Crypto\Transactions\Builder\AbstractTransaction
public function secondSign(string $secondPassphrase): self { $this->transaction = $this->transaction->secondSign(PrivateKey::fromPassphrase($secondPassphrase)); $this->transaction->id = $this->transaction->getId(); return $this; }
Sign the transaction using the given second passphrase. @param string $secondPassphrase @return \ArkEcosystem\Crypto\Transactions\Builder\AbstractTransaction
public static function fromPassphrase(string $passphrase, AbstractNetwork $network = null): string { return static::fromPrivateKey(PrivateKey::fromPassphrase($passphrase), $network); }
Derive the address from the given passphrase. @param string $passphrase @param \ArkEcosystem\Crypto\Networks\AbstractNetwork|null $network @return string
public static function fromPublicKey(string $publicKey, $network = null): string { $network = $network ?? NetworkConfiguration::get(); $ripemd160 = Hash::ripemd160(PublicKey::fromHex($publicKey)->getBuffer()); $seed = Writer::bit8(Helpers::version($network)).$ripemd160->getBinary(); return Base58::encodeCheck(new Buffer($seed)); }
Derive the address from the given public key. @param string $publicKey @param \ArkEcosystem\Crypto\Networks\AbstractNetwork|null $network @return string
public static function fromPrivateKey(EccPrivateKey $privateKey, AbstractNetwork $network = null): string { $digest = Hash::ripemd160($privateKey->getPublicKey()->getBuffer()); return (new PayToPubKeyHashAddress($digest))->getAddress($network); }
Derive the address from the given private key. @param \BitWasp\Bitcoin\Crypto\EcAdapter\Impl\PhpEcc\Key\PrivateKey $privateKey @param ArkEcosystem\Crypto\Networks\AbstractNetwork|null $network @return string
public static function validate(string $address, $network = null): bool { try { $addressCreator = new AddressCreator(); $addressCreator->fromString($address, $network); return true; } catch (\Exception $e) { return false; } }
Validate the given address. @param string $address @param \ArkEcosystem\Crypto\Networks\AbstractNetwork|int|null $network @return bool
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $usernameLength = $this->buffer->readUInt8(); $this->transaction->asset = [ 'delegate' => [ 'username' => $this->buffer->position($this->assetOffset + 2)->readHexBytes($usernameLength * 2), ], ]; return $this->parseSignatures($this->assetOffset + ($usernameLength + 1) * 2); }
Handle the deserialization of "vote" data. @return object
public function serialize(): void { $voteBytes = []; foreach ($this->transaction['asset']['votes'] as $vote) { $voteBytes[] = '+' === substr($vote, 0, 1) ? '01'.substr($vote, 1) : '00'.substr($vote, 1); } $this->buffer->writeUInt8(count($this->transaction['asset']['votes'])); $this->buffer->writeHexBytes(implode('', $voteBytes)); }
Handle the serialization of "second signature registration" data. @return string
public static function fromPassphrase(string $passphrase, AbstractNetwork $network = null): string { return PrivateKey::fromPassphrase($passphrase)->toWif($network); }
Derive the WIF from the given passphrase. @param string $passphrase @param \ArkEcosystem\Crypto\Networks\AbstractNetwork|null $network @return string
public function serialize(): void { $this->buffer->writeUInt64($this->transaction['amount']); $this->buffer->writeUInt32($this->transaction['expiration'] ?? 0); $this->buffer->writeHex(Base58::decodeCheck($this->transaction['recipientId'])->getHex()); }
Handle the serialization of "transfer" data. @return string
public function serialize(): void { $this->buffer->writeUInt16(count($this->transaction['asset']['payments'])); foreach ($this->transaction['asset']['payments'] as $payment) { $this->buffer->writeUInt64($payment['amount']); $this->buffer->writeHex(Base58::decodeCheck($payment['recipientId'])->getHex()); } }
Handle the serialization of "multi payment" data. @return string
protected function parseSignatures(int $startOffset): object { return $this->transaction->parseSignatures($this->buffer->toHex(), $startOffset); }
Parse the signatures of the given transaction. @param int $startOffset @return object
public function add(string $recipientId, int $amount): self { $this->transaction->asset['payments'][] = compact('recipientId', 'amount'); return $this; }
Add a new payment to the collection. @param string $recipientId @param int $amount @return \ArkEcosystem\Crypto\Transactions\Builder\MultiPayment
public function serialize(): void { $keysgroup = []; if (! isset($this->transaction['version']) || 1 === $this->transaction['version']) { foreach ($this->transaction['asset']['multisignature']['keysgroup'] as $key) { $keysgroup[] = '+' === substr($key, 0, 1) ? substr($key, 1) : $key; } } else { $keysgroup = $this->transaction['asset']['multisignature']['keysgroup']; } $this->buffer->writeUInt8($this->transaction['asset']['multisignature']['min']); $this->buffer->writeUInt8(count($this->transaction['asset']['multisignature']['keysgroup'])); $this->buffer->writeUInt8($this->transaction['asset']['multisignature']['lifetime']); $this->buffer->writeHexBytes(implode('', $keysgroup)); }
Handle the serialization of "multi signature registration" data. @return string
public function sign(string $passphrase): AbstractTransaction { $this->transaction->recipientId = Address::fromPassphrase($passphrase, Network::get()); parent::sign($passphrase); return $this; }
Sign the transaction using the given passphrase. @param string $passphrase @return \ArkEcosystem\Crypto\Transactions\Builder\AbstractTransaction
public function signature(string $secondPassphrase): self { $this->transaction->asset = [ 'signature' => [ 'publicKey' => PublicKey::fromPassphrase($secondPassphrase)->getHex(), ], ]; return $this; }
Set the signature asset to register the second passphrase. @param string $secondPassphrase @return \ArkEcosystem\Crypto\Transactions\Builder\SecondSignatureRegistration
public function deserialize(): object { $this->buffer->position($this->assetOffset); $this->transaction->asset = [ 'signature' => [ 'publicKey' => $this->buffer->readHexRaw(66), ], ]; return $this->parseSignatures($this->assetOffset + 66); }
Handle the deserialization of "delegate registration" data. @return object
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $this->transaction->asset = [ 'multisignature' => [ 'min' => $this->buffer->readUInt8() & 0xff, 'lifetime' => $this->buffer->skip(1)->readUInt8() & 0xff, ], ]; $count = $this->buffer->readUInt8() & 0xff; for ($i = 0; $i < $count; $i++) { $indexStart = $this->assetOffset + 6; if ($i > 0) { $indexStart += $i * 66; } $this->transaction->asset['multisignature']['keysgroup'][] = $this->buffer->position($indexStart)->readHexRaw(66); } return $this->parseSignatures($this->assetOffset + 6 + $count * 66); }
Handle the deserialization of "multi signature registration" data. @return object
public function sign(PrivateKey $keys): self { $transaction = Hash::sha256($this->toBytes()); $this->signature = $keys->sign($transaction)->getBuffer()->getHex(); return $this; }
Sign the transaction using the given passphrase. @param \BitWasp\Bitcoin\Crypto\EcAdapter\Impl\PhpEcc\Key\PrivateKey $keys @return \ArkEcosystem\Crypto\Transactions\Transaction
public function secondSign(PrivateKey $keys): self { $transaction = Hash::sha256($this->toBytes(false)); $this->signSignature = $keys->sign($transaction)->getBuffer()->getHex(); return $this; }
Sign the transaction using the given second passphrase. @param \BitWasp\Bitcoin\Crypto\EcAdapter\Impl\PhpEcc\Key\PrivateKey $keys @return \ArkEcosystem\Crypto\Transactions\Transaction
public function verify(): bool { $factory = new PublicKeyFactory; $publicKey = $factory->fromHex($this->senderPublicKey); return $publicKey->verify( Hash::sha256($this->toBytes()), SignatureFactory::fromHex($this->signature) ); }
Verify the transaction. @return bool
public function secondVerify(string $secondPublicKey): bool { $factory = new PublicKeyFactory; $secondPublicKey = $factory->fromHex($secondPublicKey); return $secondPublicKey->verify( Hash::sha256($this->toBytes(false)), SignatureFactory::fromHex($this->signSignature) ); }
Verify the transaction with a second public key. @param string $secondPublicKey @return bool
public function parseSignatures(string $serialized, int $startOffset): self { $this->signature = substr($serialized, $startOffset); $multiSignatureOffset = 0; if (0 === strlen($this->signature)) { unset($this->signature); } else { $signatureLength = intval(substr($this->signature, 2, 2), 16) + 2; $this->signature = substr($serialized, $startOffset, $signatureLength * 2); $multiSignatureOffset += $signatureLength * 2; $this->secondSignature = substr($serialized, $startOffset + $signatureLength * 2); if (! $this->secondSignature || 0 === strlen($this->secondSignature)) { unset($this->secondSignature); } else { if ('ff' === substr($this->secondSignature, 0, 2)) { unset($this->secondSignature); } else { $secondSignatureLength = intval(substr($this->secondSignature, 2, 2), 16) + 2; $this->secondSignature = substr($this->secondSignature, 0, $secondSignatureLength * 2); $multiSignatureOffset += $secondSignatureLength * 2; } } $signatures = substr($serialized, $startOffset + $multiSignatureOffset); if (! $signatures || 0 === strlen($signatures)) { return $this; } if ('ff' !== substr($signatures, 0, 2)) { return $this; } $signatures = substr($signatures, 2); $this->signatures = []; $moreSignatures = true; while ($moreSignatures) { $mLength = intval(substr($signatures, 2, 2), 16); if ($mLength > 0) { $this->signatures[] = substr($signatures, 0, ($mLength + 2) * 2); } else { $moreSignatures = false; } $signatures = substr($signatures, ($mLength + 2) * 2); } } return $this; }
Parse the signature, second signature and multi signatures. @param string $serialized @param int $startOffset @return \ArkEcosystem\Crypto\Transactions\Transaction
public function toArray(): array { return array_filter([ 'amount' => $this->amount, 'asset' => $this->asset ?? null, 'fee' => $this->fee, 'id' => $this->id, 'network' => $this->network ?? Network::get()->version(), 'recipientId' => $this->recipientId ?? null, 'secondSignature' => $this->secondSignature ?? null, 'senderPublicKey' => $this->senderPublicKey, 'signature' => $this->signature, 'signatures' => $this->signatures ?? null, 'signSignature' => $this->signSignature ?? null, 'timestamp' => $this->timestamp, 'type' => $this->type, 'vendorField' => $this->vendorField ?? null, 'version' => $this->version ?? 1, ], function ($element) { if (null !== $element) { return true; } return false; }); }
Convert the transaction to its array representation. @return array
public function serialize(): Buffer { $buffer = new Writer(); $buffer->writeUInt8(0xff); $buffer->writeUInt8($this->transaction['version'] ?? 0x01); $buffer->writeUInt8($this->transaction['network'] ?? Network::version()); $buffer->writeUInt8($this->transaction['type']); $buffer->writeUInt32($this->transaction['timestamp']); $buffer->writeHex($this->transaction['senderPublicKey']); $buffer->writeUInt64($this->transaction['fee']); if (isset($this->transaction['vendorField'])) { $vendorFieldLength = strlen($this->transaction['vendorField']); $buffer->writeUInt8($vendorFieldLength); $buffer->writeString($this->transaction['vendorField']); } elseif (isset($this->transaction['vendorFieldHex'])) { $vendorFieldHexLength = strlen($this->transaction['vendorFieldHex']); $buffer->writeUInt8($vendorFieldHexLength / 2); $buffer->writeHex($this->transaction['vendorFieldHex']); } else { $buffer->writeUInt8(0x00); } $this->handleType($buffer); $this->handleSignatures($buffer); return new Buffer($buffer->toBytes()); }
Perform AIP11 compliant serialization. @return \BitWasp\Buffertools\Buffer
public function handleType(Writer $buffer): void { $serializer = $this->serializers[$this->transaction['type']]; (new $serializer($this->transaction, $buffer))->serialize(); }
Handle the serialization of transaction data. @param \BrianFaust\Binary\Buffer\Writer\Buffer $buffer @return string
public function handleSignatures(Writer $buffer): void { if (isset($this->transaction['signature'])) { $buffer->writeHexBytes($this->transaction['signature']); } if (isset($this->transaction['secondSignature'])) { $buffer->writeHexBytes($this->transaction['secondSignature']); } elseif (isset($this->transaction['signSignature'])) { $buffer->writeHexBytes($this->transaction['signSignature']); } if (isset($this->transaction['signatures'])) { $buffer->writeUInt8(0xff); $buffer->writeHexBytes(implode('', $this->transaction['signatures'])); } }
Handle the serialization of transaction data. @param \BrianFaust\Binary\Buffer\Writer\Buffer $buffer @return string
public static function fromPassphrase(string $passphrase): EcPrivateKey { $passphrase = Hash::sha256(new Buffer($passphrase)); return (new PrivateKeyFactory())->fromHexCompressed($passphrase->getHex()); }
Derive the private key for the given passphrase. @param string $passphrase @return \BitWasp\Bitcoin\Crypto\EcAdapter\Impl\PhpEcc\Key\PrivateKey
public static function fromWif(string $wif, AbstractNetwork $network = null): EcPrivateKey { return (new PrivateKeyFactory())->fromWif($wif, $network); }
Derive the private key for the given WIF. @param string $wif @param \ArkEcosystem\Crypto\Networks\AbstractNetwork|null $network @return \BitWasp\Bitcoin\Crypto\EcAdapter\Impl\PhpEcc\Key\PrivateKey
public static function new($message): self { if (is_object($message)) { return new static($message); } if (is_array($message)) { return new static(json_decode(json_encode($message))); } if (is_string($message)) { return new static(json_decode($message)); } throw new InvalidArgumentException('The given message was neither an object, array nor JSON.'); }
Create a new message instance. @param mixed $message @return \ArkEcosystem\Crypto\Message
public static function sign(string $message, string $passphrase): self { $keys = PrivateKey::fromPassphrase($passphrase); return static::new([ 'publickey' => $keys->getPublicKey()->getHex(), 'signature' => $keys->sign(Hash::sha256(new Buffer($message)))->getBuffer()->getHex(), 'message' => $message, ]); }
Sign a message using the given passphrase. @param string $message @param string $passphrase @return \ArkEcosystem\Crypto\Message
public function verify(): bool { $factory = new PublicKeyFactory; return $factory->fromHex($this->publicKey)->verify( new Buffer(hash('sha256', $this->message, true)), SignatureFactory::fromHex($this->signature) ); }
Verify the message contents. @return bool
protected function getSearchQuery($keywords, $classes) { $query = new SearchQuery(); $query->classes = $classes; $query->addSearchTerm($keywords); $query->addExclude(SiteTree::class . '_ShowInSearch', 0); // Artificially lower the amount of results to prevent too high resource usage. // on subsequent canView check loop. $query->setLimit(100); // Allow user code to modify the search query before returning it $this->extend('updateSearchQuery', $query); return $query; }
Build a SearchQuery for a new search @param string $keywords @param array $classes @return SearchQuery
protected function getSearchOptions($spellcheck) { $options = $this->config()->get('search_options'); if ($spellcheck) { $options = array_merge($options, $this->config()->get('spellcheck_options')); } return $options; }
Get solr search options for this query @param bool $spellcheck True if we should include spellcheck support @return array
protected function getResult($keywords, $classes, $searchIndex, $limit = -1, $start = 0, $spellcheck = false) { // Prepare options $query = $this->getSearchQuery($keywords, $classes); $options = $this->getSearchOptions($spellcheck); // Get results $solrResult = $searchIndex->search( $query, $start, $limit, $options ); return CwpSearchResult::create($keywords, $solrResult); }
Get results for a search term @param string $keywords @param array $classes @param SolrIndex $searchIndex @param int $limit Max number of results for this page @param int $start Skip this number of records @param bool $spellcheck True to enable spellcheck @return CwpSearchResult
public function search($keywords, $classes, $searchIndex, $limit = -1, $start = 0, $followSuggestions = false) { if (empty($keywords)) { return null; } try { // Begin search $result = $this->getResult($keywords, $classes, $searchIndex, $limit, $start, true); // Return results if we don't need to refine this any further if (!$followSuggestions || $result->hasResults() || !$result->getSuggestion()) { return $result; } // Perform new search with the suggested terms $suggested = $result->getSuggestion(); $newResult = $this->getResult($suggested, $classes, $searchIndex, $limit, $start, false); $newResult->setOriginal($keywords); // Compare new results to the original query if ($newResult->hasResults()) { return $newResult; } return $result; } catch (Exception $e) { Injector::inst()->get(LoggerInterface::class)->warning($e); } }
Get a CwpSearchResult for a given criterea @param string $keywords @param array $classes @param SolrIndex $searchIndex @param int $limit Max number of results for this page @param int $start Skip this number of records @param bool $followSuggestions True to enable suggested searches to be returned immediately @return CwpSearchResult|null
public function post($url, array $body = null, array $options = array()) { return $this->request('POST', $url, null, $body, $options); }
Perform a POST request @param string $url Url to send the request to. @param array $body Body params to send with the request. They are converted to json and sent in the body. @param array $options Additional request's options. @option array 'headers' Additional headers to send with the request @option boolean 'raw' Indicator whether to wrap and uwrap request in the envelope. @return array Array where first element is http status code and the second one is resource.
public function put($url, array $body = null, array $options = array()) { return $this->request('PUT', $url, null, $body, $options); }
Perform a POST request @param string $url Url to send the request to. @param array $body Body params to send with the request. They are converted to json and sent in the body. @param array $options Additional request's options. @option array 'headers' Additional headers to send with the request @option boolean 'raw' Indicator whether to wrap and uwrap request in the envelope. @return array Array where first element is http status code and the second one is resource.
public function delete($url, array $params = null, array $options = array()) { return $this->request('DELETE', $url, $params, null, $options); }
Perform a DELETE request @param string $url Url to send the request to. @param array $params Query params to send with the request. They are converted to a query string and attached to the url. @param array $options Additional request's options. @option array 'headers' Additional headers to send with the request @option boolean 'raw' Indicator whether to wrap and uwrap request in the envelope. @return array Array where first element is http status code and the second one is resource.
protected function unwrapEnvelope(array $body) { if (isset($body['data'])) { return $body['data']; } else if (isset($body['items'])) { $items = array(); foreach ($body['items'] as $item) { $items[] = $item; } return $items; } return $body; }
Perform envelope unwrapping @param array $body Associative array after json decoding. @return mixed Either single resource or array of associative resources. @ignore
protected function encodePayload(array $params) { $encoded = []; foreach ($params as $key => $value) { if (is_array($value)) $encoded[$key] = $this->encodePayload($value); else if ($value instanceof \DateTime) $encoded[$key] = $value->format(\DateTime::ISO8601); else $encoded[$key] = $value; } return $encoded; }
Ensure consistency in encoding between native PHP types and Base API expected types. @param array $params Associative array of either wrapped or unwrapped payload to be send. @return array Associative array with properly handled data types @ignore
protected function encodeQueryParams(array $params) { $encoded = []; foreach ($params as $key => $value) { if (is_array($value)) $encoded[$key] = $this->encodeQueryParams($value); else if (is_bool($value)) $encoded[$key] = $value ? 'true' : 'false'; else if ($value instanceof \DateTime) $encoded[$key] = $value->format(\DateTime::ISO8601); else $encoded[$key] = $value; } return $encoded; }
Ensure consistency in encoding between native PHP types and Base API expected query type format. @param array $params Associative array of query parameters to be send. @return array Associative array with properly handled data types @ignore
protected function handleResponse($code, $rawResponse) { try { $response = json_decode($rawResponse, true); } catch (Exception $e) { $msg = "Unknown error occurred. The response should be a json response. " . "HTTP response code={$code}. " . "HTTP response body={$rawResponse}."; throw new Exception($msg); } if ($code < 200 || $code >= 400) { $this->handleErrorResponse($code, $rawResponse, $response); } return $response; }
@param integer $code Http response code @param string $rawResponse Http response payload @throws \BaseCRM\Errors\RequestError if request was invalid @throws \BaseCRM\Errors\ResourceError if request's payload validation failed @throws \BaseCRM\Errors\ServerError if server error occurred @return mixed Decoded response @ignore
public function fetch(\Closure $callback) { // Set up a new synchronization session for a given device's UUID $session = $this->client->sync->start($this->deviceUUID); // Check if there is anything to synchronize if (!$session || !$session['id']) return; $sessionId = $session['id']; // Drain the main queue unitl there is no data (empty array) while (true) { // fetch the main queue $queueItems = $this->client->sync->fetch($this->deviceUUID, $sessionId); // nothing more to synchronize ? if (!$queueItems) break; // let client know about data and meta $ackKeys = array(); foreach ($queueItems as $item) { if ($callback($item['meta'], $item['data'])) { $ackKeys[] = $item['meta']['sync']['ack_key']; } } // As we fetch new data, we need to send acknowledgement keys - if any if ($ackKeys) $this->client->sync->ack($this->deviceUUID, $ackKeys); } }
Perform a full syncrhonization flow. See the following example: <code> <?php $client = new \BaseCRM\Client(['accessToken' => '<YOUR_PERSONAL_ACCESS_TOKEN>']); $sync = new \BaseCRM\Sync($client, '<YOUR_DEVICES_UUID>'); $sync.fetch(function ($meta, $resource){ $klass = classify($meta['type']); // e.g. \BaseCRM\User, \BaseCRM\Source etc.. call_user_func($klass . $meta['sync']['event_type'], $resource) ? \BaseCRM\Sync::ACK : \BaseCRM\Sync::NACK; }); ?> </code> @param Closure $callback Callback that will be called for every item in queue. Takes two input arguments: synchronization meta data and associated resource. It must return either ACK or NACK|null.
public function all($params = [], array $options = array()) { list($code, $tasks) = $this->httpClient->get("/tasks", $params, $options); return $tasks; }
Retrieve all tasks get '/tasks' Returns all tasks available to the user, according to the parameters provided If you ask for tasks without any parameter provided Base API will return you both **floating** and **related** tasks Although you can narrow the search set to either of them via query parameters @param array $params Search options @param array $options Additional request's options. @return array The list of Tasks for the first page, unless otherwise specified.
public function create(array $task, array $options = array()) { $attributes = array_intersect_key($task, array_flip(self::$keysToPersist)); list($code, $createdTask) = $this->httpClient->post("/tasks", $attributes, $options); return $createdTask; }
Create a task post '/tasks' Creates a new task You can create either a **floating** task or create a **related** task and associate it with one of the resource types below: * [Leads](/docs/rest/reference/leads) * [Contacts](/docs/rest/reference/contacts) * [Deals](/docs/rest/reference/deals) @param array $task 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 $task, array $options = array()) { $attributes = array_intersect_key($task, array_flip(self::$keysToPersist)); list($code, $updatedTask) = $this->httpClient->put("/tasks/{$id}", $attributes, $options); return $updatedTask; }
Update a task put '/tasks/{id}' Updates task information If the specified task does not exist, this query will return an error @param integer $id Unique identifier of a Task @param array $task 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.
protected function getLink($terms, $format = null) { if (!$terms) { return null; } $link = 'search/SearchForm?Search='.rawurlencode($terms); if ($format) { $link .= '&format='.rawurlencode($format); } return $link; }
Get a search link for given terms @param string $terms @return string|null
public function settings(array $settings = null) { if ($settings !== null) { $this->settings = $settings; } return $this->settings + static::$globalSettings; }
Set/get settings. @param array $settings @return array
public function setting($setting, $default = null) { $value = parent::setting($setting); if (null === $value) { $value = isset(static::$globalSettings[$setting]) ? static::$globalSettings[$setting] : $default; } return $value; }
Get setting. @param string $setting @param mixed $default @return mixed
protected function encode($var) { return (string) YamlParser::dump($var, $this->setting('inline', 5), $this->setting('indent', 2), true, false); }
Encode contents into RAW string. @param array $var @return string @throws DumpException
protected function decode($var) { // Try native PECL YAML PHP extension first if available. if (\function_exists('yaml_parse') && $this->setting('native', true)) { // Safely decode YAML. $saved = @ini_get('yaml.decode_php'); @ini_set('yaml.decode_php', 0); $data = @yaml_parse($var); @ini_set('yaml.decode_php', $saved); if ($data !== false) { return (array) $data; } } try { return (array) YamlParser::parse($var); } catch (ParseException $e) { if ($this->setting('compat', true)) { return (array) FallbackYamlParser::parse($var); } throw $e; } }
Decode RAW string into contents. @param string $var @return array mixed @throws ParseException
public function SearchForm() { $searchText = $this->owner->getRequest()->getVar('Search'); $fields = FieldList::create( TextField::create('Search', false, $searchText) ); $actions = FieldList::create( FormAction::create('results', _t('SilverStripe\\CMS\\Search\\SearchForm.GO', 'Go')) ); $form = SearchForm::create($this->owner, SearchForm::class, $fields, $actions); $form->setFormAction('search/SearchForm'); return $form; }
Site search form
public function results($data, $form, $request) { // Check parameters for terms, pagination, and if we should follow suggestions $keywords = empty($data['Search']) ? '' : $data['Search']; $start = isset($data['start']) ? $data['start'] : 0; $suggestions = isset($data['suggestions']) ? $data['suggestions'] : $this->config()->get('search_follow_suggestions'); $results = CwpSearchEngine::create() ->search( $keywords, $this->config()->get('classes_to_search'), Injector::inst()->get(CwpSearchEngine::class . '.search_index'), $this->config()->get('results_per_page'), $start, $suggestions ); // Customise content with these results $properties = [ 'MetaTitle' => _t(__CLASS__ . '.MetaTitle', 'Search {keywords}', ['keywords' => $keywords]), 'NoSearchResults' => _t(__CLASS__ . '.NoResult', 'Sorry, your search query did not return any results.'), 'EmptySearch' => _t(__CLASS__ . '.EmptySearch', 'Search field empty, please enter your search query.'), 'PdfLink' => '', 'Title' => _t('SilverStripe\\CMS\\Search\\SearchForm.SearchResults', 'Search Results'), ]; $this->owner->extend('updateSearchResults', $results, $properties); // Customise page /** @var ViewableData_Customised $response */ $response = $this->owner->customise($properties); if ($results) { $response = $response ->customise($results) ->customise(['Results' => $results->getResults()]); } // Render $templates = $this->getResultsTemplate($request); return $response->renderWith($templates); }
Process and render search results. @param array $data The raw request data submitted by user @param SearchForm $form The form instance that was submitted @param HTTPRequest $request Request generated for this action @return DBHTMLText
protected function getResultsTemplate($request) { $templates = [ Page::class . '_results', Page::class ]; if ($request->getVar('format') == 'rss') { array_unshift($templates, Page::class . '_results_rss'); } if ($request->getVar('format') == 'atom') { array_unshift($templates, Page::class . '_results_atom'); } return $templates; }
Select the template to render search results with @param HTTPRequest $request @return array
public function unescapeCharacter($value) { switch ($value[1]) { case '0': return "\x0"; case 'a': return "\x7"; case 'b': return "\x8"; case 't': return "\t"; case "\t": return "\t"; case 'n': return "\n"; case 'v': return "\xB"; case 'f': return "\xC"; case 'r': return "\r"; case 'e': return "\x1B"; case ' ': return ' '; case '"': return '"'; case '/': return '/'; case '\\': return '\\'; case 'N': // U+0085 NEXT LINE return "\xC2\x85"; case '_': // U+00A0 NO-BREAK SPACE return "\xC2\xA0"; case 'L': // U+2028 LINE SEPARATOR return "\xE2\x80\xA8"; case 'P': // U+2029 PARAGRAPH SEPARATOR return "\xE2\x80\xA9"; case 'x': return self::utf8chr(hexdec(substr($value, 2, 2))); case 'u': return self::utf8chr(hexdec(substr($value, 2, 4))); case 'U': return self::utf8chr(hexdec(substr($value, 2, 8))); default: @trigger_error('Not escaping a backslash in a double-quoted string is deprecated since Symfony 2.8 and will throw a ParseException in 3.0.', E_USER_DEPRECATED); return $value; } }
Unescapes a character that was found in a double-quoted string. @param string $value An escaped character @return string The unescaped character @internal This method is public to be usable as callback. It should not be used in user code. Should be changed in 3.0.
private static function utf8chr($c) { if (0x80 > $c %= 0x200000) { return chr($c); } if (0x800 > $c) { return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F); } if (0x10000 > $c) { return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F); } return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F); }
Get the UTF-8 character for the given code point. @param int $c The unicode code point @return string The corresponding UTF-8 character