sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function getAttribute(Mage_Shipping_Model_Rate_Request $request, $attribute) { // Check if an appropriate product attribute has been assigned in the backend and, if not, // just return the default weight value as later code won't work $attributeCode = Mage::getStoreConfig('carriers/australiapost/' . $attribute . '_attribute'); if (!$attributeCode) { return Mage::getStoreConfig('carriers/australiapost/default_' . $attribute); } $items = $this->getAllSimpleItems($request); if (count($items) == 1) { $attributeValue = $items[0]->getData($attributeCode); if (empty($attributeValue)) { return Mage::getStoreConfig('carriers/australiapost/default_' . $attribute); } return $attributeValue; } else { return Mage::getStoreConfig('carriers/australiapost/default_' . $attribute); } }
Get the attribute value for a product, e.g. its length attribute. If the order only has one item and we've set which product attribute we want to to get the attribute value from, use that product attribute. For all other cases just use the default config setting, since we can't assume the dimensions of the order. @param Mage_Shipping_Model_Rate_Request $request Order object @param string $attribute Attribute code @return string Attribute value
entailment
public function getQueryText() { if (is_null($this->_queryText)) { if ($this->_getRequest()->getParam('billing')) { $tmp = $this->_getRequest()->getParam('billing'); $this->_queryText = $tmp['city']; } elseif ($this->_getRequest()->getParam('shipping')) { $tmp = $this->_getRequest()->getParam('shipping'); $this->_queryText = $tmp['city']; } else { $this->_queryText = $this->_getRequest()->getParam('city'); } $this->_queryText = trim($this->_queryText); if (Mage::helper('core/string')->strlen($this->_queryText) > self::MAX_QUERY_LEN) { $this->_queryText = Mage::helper('core/string')->substr($this->_queryText, 0, self::MAX_QUERY_LEN); } } return $this->_queryText; }
Gets the query text for city lookups in the postcode database. @return string
entailment
public function getValidationStatusDescription($status) { $options = $this->getValidationStatusOptions(); if (!isset($options[$status])) { $status = static::ADDRESS_UNKNOWN; } return $options[$status]; }
Returns the label for the given validation status code. Defaults to 'Unknown' if the code isn't found. @param int $status Validation status code @return string Status label
entailment
public function validate(array $street, $state, $suburb, $postcode, $country) { try { $validatorClass = Mage::getStoreConfig(self::XML_PATH_ADDRESS_VALIDATION_BACKEND); if (!$validatorClass) { Mage::helper('australia')->logMessage('Address validator class not set'); return array(); } /** @var Fontis_Australia_Model_Address_Interface $validator */ $validator = Mage::getModel($validatorClass); return $validator->validateAddress($street, $state, $suburb, $postcode, $country); } catch (Exception $err) { $message = "Error validating address\nStreet: " . print_r($street, true) . "\n" . "State: $state\nSuburb: $suburb\nPostcode: $postcode\nCountry: $country\n" . $err->getMessage() . "\n" . $err->getTraceAsString(); Mage::helper('australia')->logMessage($message); return array(); } }
Validates an address. Instantiates the selected address validator and passes our arguments to it, as well as doing some error checking. @see Fontis_Australia_Model_Address_Interface @param string[] $street Array of street address lines @param string $state State @param string $suburb City/suburb @param string $postcode Postcode @param string $country Country @return array Array of validated address data
entailment
public function validateOrderAddress(Mage_Sales_Model_Order $order) { /** @var Mage_Sales_Model_Order_Address $address */ $address = $order->getShippingAddress(); $countryModel = $address->getCountryModel(); $result = $this->validate( $address->getStreet(), $address->getRegionCode(), $address->getCity(), $address->getPostcode(), $countryModel->getName() ); if (!$result || !isset($result['ValidAustralianAddress'])) { $status = static::ADDRESS_UNKNOWN; } else if (isset($result['validAddress']) && $result['validAddress']) { $status = static::ADDRESS_VALID; } else { $status = static::ADDRESS_INVALID; } $order->setAddressValidated($status); return $result; }
Validates the order's address and updates its 'address valid' value. @param Mage_Sales_Model_Order $order @return array Address validation results @throws Exception
entailment
public function addValidationMessageToSession(array $result, Mage_Core_Model_Session_Abstract $session) { if (isset($result[Fontis_Australia_Helper_Address::ADDRESS_OVERRIDE_FLAG])) { $session->addSuccess(' Address successfully overridden without validation.'); } else if (!$result || !isset($result['ValidAustralianAddress'])) { $session->addWarning('Unable to validate address.'); } else if (isset($result['validAddress']) && $result['validAddress']) { $session->addSuccess(' Address successfully validated.'); } else if (isset($result['suggestion'])) { $session->addWarning("Address is not valid; did you mean: {$result['suggestion']}"); } else { $session->addWarning('Address is not valid; no suggestions available.'); } }
Adds a status message to the session, based on a validation result. Success messages should have a leading space, since the new message is appended to the 'The order address has been updated.' message. @param array $result Address validation result array. @param Mage_Core_Model_Session_Abstract $session Session object
entailment
public function addExportToBulkAction($observer) { if (! $observer->block instanceof Mage_Adminhtml_Block_Sales_Order_Grid) { return; } $observer->block->getMassactionBlock()->addItem('eparcelexport', array( 'label' => $observer->block->__('Export to CSV (eParcel)'), 'url' => $observer->block->getUrl('*/australia_eparcel/export') )); }
Event Observer. Triggered before an adminhtml widget template is rendered. We use this to add our action to bulk actions in the sales order grid instead of overridding the class.
entailment
public function initialize(array $config) { $controller = $this->_registry->getController(); $this->setEventManager($controller->getEventManager()); $this->Captchas = $controller->Captchas; }
Initialize properties. @param array $config The config data. @return void
entailment
public function prepare($captcha) { if ($captcha->result === null || $captcha->result === '') { $generated = $this->_getEngine()->generate(); $captcha = $this->Captchas->patchEntity($captcha, $generated); } return $this->Captchas->save($captcha); }
@param \Captcha\Model\Entity\Captcha $captcha @return bool|\Captcha\Model\Entity\Captcha
entailment
public function addFilter($name, $options = []) { $_options = $this->config('_default'); $_options['field'] = $name; $_options['column'] = $name; $options = array_merge($_options, $options); $this->config('filters.' . $name, $options, true); }
addFilter Adds a filter to the Search Component. ### Options: - field Field to use. - column Column to use from the table. - operator The operator to use like: 'Like' or '='. - options List for a select-box. - attributes Attributes for the input-field. @param string $name Name of the filter. @param array $options Options. @return void
entailment
public function removeFilter($name) { $filters = $this->config('filters'); unset($filters[$name]); $this->config('filters', $filters, false); }
removeFilter Removes an filter. @param string $name Name of the filter. @return void
entailment
public function search(\Cake\ORM\Query $query, $options = []) { $_query = $this->Controller->request->query; $this->Controller->request->data = $_query; $params = $_query; $filters = $this->_normalize($this->config('filters')); foreach ($filters as $field => $options) { $hash = Hash::get($params, $options['column']); if (!empty($hash)) { $key = $this->_buildKey($field, $options); $value = $this->_buildValue($field, $options, $params); $query->where([$key => $value]); $this->_setValue($field, $options, $params); } } return $query; }
Search The search-method itself. Needs a Query-object, adds filters and returns the Query-object. @param \Cake\ORM\Query $query Query Object. @param type $options Options. @return \Cake\ORM\Query
entailment
protected function _buildValue($field, $options, $params) { $string = null; if ($options['operator'] === 'LIKE') { $string .= '%'; } $string .= Hash::get($params, $options['column']); if ($options['operator'] === 'LIKE') { $string .= '%'; } return $string; }
_buildKey Builds the value-side of the `where()`-method. @param string $field The fieldname. @param array $options Options of the field. @param array $params Parameters. @return string
entailment
protected function _setValue($field, $options, $params) { $key = 'filters.' . $field . '.attributes.value'; $value = Hash::get($params, $options['column']); $this->config($key, $value); }
_setValue Sets the value to the current filter. @param string $field The fieldname. @param array $options Options of the field. @param type $params Parameters. @return void
entailment
protected function _normalize($filters, $options = []) { foreach ($filters as $key => $filter) { if ($filter['options']) { $filter['operator'] = '='; $filter['attributes']['empty'] = true; } if (is_null($filter['attributes']['placeholder'])) { $filter['attributes']['placeholder'] = $filter['column']; } $filters[$key] = $filter; } return $filters; }
_normalize Normalizes the filters-array. This can be helpfull to use automated settings. @param array $filters List of filters. @param array $options Options @return array
entailment
public function createAppropriateIterator(Response $response) { $this->checkResponseFormat($response); set_error_handler(function() { /* ignore errors */ }); $arr = json_decode($response->getBody(), true, 512, 1); restore_error_handler(); $objects = []; foreach ($arr['objects'] as $object) { if (isset($this->apiEntities[$object['type']])) { $class = $this->apiEntities[$object['type']]; } else { $class = $this->apiEntities['*']; } $objects[] = new $class($object); } return new EntityIterator($objects, $response); }
Creates an appropriate Entity from a given Response If no valid Entity can be found for typo of API, the Wildcard entity is selected @todo: remove error avoidance when issue 12 is fixed: https://github.com/Swader/diffbot-php-client/issues/12 @param Response $response @return EntityIterator @throws DiffbotException
entailment
protected function checkResponseFormat(Response $response) { set_error_handler(function() { /* ignore errors */ }); $arr = json_decode($response->getBody(), true, 512, 1); restore_error_handler(); if (isset($arr['error'])) { throw new DiffbotException('Diffbot returned error ' . $arr['errorCode'] . ': ' . $arr['error']); } $required = [ 'objects' => 'Objects property missing - cannot extract entity values', 'request' => 'Request property not found in response!' ]; foreach ($required as $k=>$v) { if (!isset($arr[$k])) { throw new DiffbotException($v); } } }
Makes sure the Diffbot response has all the fields it needs to work properly @todo: remove error avoidance when issue 12 is fixed: https://github.com/Swader/diffbot-php-client/issues/12 @param Response $response @throws DiffbotException
entailment
public function setContainer($container) { if (!is_array($container) && !$container instanceof \ArrayAccess) { throw new InvalidArgumentException('array or ArrayAccess Object', 0); } $this->container = $container; return $this; }
Set the receiving container of the parsed htaccess @api @param mixed $container Can be an array, an ArrayObject or an object that implements ArrayAccess @return $this @throws InvalidArgumentException
entailment
public function parse(\SplFileObject $file = null, $optFlags = null, $rewind = null) { //Prepare passed options $file = ($file !== null) ? $file : $this->file; $optFlags = ($optFlags !== null) ? $optFlags : $this->mode; $rewind = ($rewind !== null) ? !!$rewind : $this->rewind; if (!$file instanceof \SplFileObject) { throw new Exception(".htaccess file is not set. You must set it (with Prser::setFile) before calling parse"); } if (!$file->isReadable()) { $path = $file->getRealPath(); throw new Exception(".htaccess file '$path'' is not readable"); } // Rewind file pointer if ($rewind) { $file->rewind(); } // Current Parse Mode $this->_cpMode = $optFlags; // Modes $asArray = (AS_ARRAY & $optFlags); // Container if ($asArray) { $htaccess = array(); } else { $htaccess = ($this->container != null) ? $this->container : new HtaccessContainer(); } //Dump file line by line into $htaccess while ($file->valid()) { //Get line $line = $file->getCurrentLine(); //Parse Line $parsedLine = $this->parseLine($line, $file); if (!is_null($parsedLine)) { $htaccess[] = $parsedLine; } } return $htaccess; }
Parse a .htaccess file @api @param \SplFileObject $file [optional] The .htaccess file. If null is passed and the file wasn't previously set, it will raise an exception @param int $optFlags [optional] Option flags - IGNORE_WHITELINES [2] Ignores whitelines (default) - IGNORE_COMMENTS [4] Ignores comments @param bool $rewind [optional] If the file pointer should be moved to the start (default is true) @return array|\ArrayAccess|HtaccessContainer @throws Exception
entailment
protected function isBlockEnd($line, $blockName = null) { $line = trim($line); $pattern = '/^\<\/'; $pattern .= ($blockName) ? $blockName : '[^\s\>]+'; $pattern .= '\>$/'; return (preg_match($pattern, $line) > 0); }
Check if line is a Block end @param string $line @param string $blockName [optional] The block's name @return bool
entailment
protected function parseMultiLine($line, \SplFileObject $file, &$lineBreaks) { while ($this->isMultiLine($line) && $file->valid()) { $lineBreaks[] = strlen($line); $line2 = $file->getCurrentLine(); // trim the ending slash $line = rtrim($line, '\\'); // concatenate with next line $line = trim($line . $line2); } return $line; }
Parse a Multi Line @param $line @param \SplFileObject $file @param $lineBreaks @return string
entailment
protected function parseCommentLine($line, $lineBreaks) { $comment = new Comment(); $comment->setText($line) ->setLineBreaks($lineBreaks); return $comment; }
Parse a Comment Line @param string $line @param array $lineBreaks @return Comment
entailment
protected function parseDirectiveLine($line, \SplFileObject $file, $lineBreaks) { $directive = new Directive(); $args = $this->directiveRegex($line); $name = array_shift($args); if ($name === null) { $lineNum = $file->key(); throw new SyntaxException($lineNum, $line, "Could not parse the name of the directive"); } $directive->setName($name) ->setArguments($args) ->setLineBreaks($lineBreaks); return $directive; }
Parse a Directive Line @param string $line @param \SplFileObject $file @return Directive @throws SyntaxException
entailment
protected function parseBlockLine($line, \SplFileObject $file, $lineBreaks) { $block = new Block(); $args = $this->blockRegex($line); $name = array_shift($args); if ($name === null) { $lineNum = $file->key(); throw new SyntaxException($lineNum, $line, "Could not parse the name of the block"); } $block->setName($name) ->setArguments($args) ->setLineBreaks($lineBreaks); // Now we parse the children $newLine = $file->getCurrentLine(); while (!$this->isBlockEnd($newLine, $name)) { $parsedLine = $this->parseLine($newLine, $file); if (!is_null($parsedLine)) { $block->addChild($parsedLine); } $newLine = $file->getCurrentLine(); } return $block; }
Parse a Block Line @param string $line @param \SplFileObject $file @return Block @throws SyntaxException
entailment
public function filterForm($filters = [], $options = []) { $html = ''; // create $html .= $this->Form->create(null, $options + ['type' => 'GET']); foreach ($filters as $field) { // if field is select-box because of the options-key if ($field['options']) { $field['attributes']['options'] = $field['options']; } $html .= $this->Form->input($field['column'], $field['attributes']); $html .= ' '; } // end $html .= $this->Form->button(__('Filter')); $html .= $this->Form->end(); return $html; }
filterForm Generates a form for the SearchComponent. ### Example: `$this->Search->filterForm($searchFilters);` Use the variable `$searchFilters` to add the generated filtes to the form. @param array $filters Filters. @param array $options Options. @return string
entailment
public function from($table) { if ($this->tableReadOnly) { throw new Exception\InvalidArgumentException( 'Since this object was created with a table and/or schema in the constructor, it is read only.' ); } if (!is_string($table) && !is_array($table) && !$table instanceof TableIdentifier && !$table instanceof Select ) { throw new Exception\InvalidArgumentException( '$table must be a string, array, an instance of TableIdentifier, or an instance of Select' ); } if ($table instanceof TableIdentifier) { $table = $table->getTable(); // Ignore schema because it is not supported by SphinxQL } $this->table = $table; return $this; }
Create from clause @param string|array|TableIdentifier $table @throws Exception\InvalidArgumentException @return Select
entailment
public function columns(array $columns, $prefixColumnsWithTable = false) { $this->columns = $columns; if ($prefixColumnsWithTable) { throw new Exception\InvalidArgumentException( 'SphinxQL syntax does not support prefixing columns with table name' ); } return $this; }
Specify columns from which to select Possible valid states: array(*) array(value, ...) value can be strings or Expression objects array(string => value, ...) key string will be use as alias, value can be string or Expression objects @param array $columns @param bool $prefixColumnsWithTable @return Select @throws Exception\InvalidArgumentException
entailment
public function option(array $values, $flag = self::OPTIONS_MERGE) { if ($values == null) { throw new Exception\InvalidArgumentException('option() expects an array of values'); } if ($flag == self::OPTIONS_SET) { $this->option = []; } foreach ($values as $k => $v) { if (!is_string($k)) { throw new Exception\InvalidArgumentException('option() expects a string for the value key'); } $this->option[$k] = $v; } return $this; }
Set key/value pairs to option @param array $values Associative array of key values @param string $flag One of the OPTIONS_* constants @throws Exception\InvalidArgumentException @return Select
entailment
protected function processSelect( PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null ) { $expr = 1; // process table columns $columns = []; foreach ($this->columns as $columnIndexOrAs => $column) { $colName = ''; if ($column === self::SQL_STAR) { $columns[] = [self::SQL_STAR]; // Sphinx doesn't not support prefix column with table, yet continue; } if ($column instanceof Expression) { $columnParts = $this->processExpression( $column, $platform, $driver, $parameterContainer, $this->processInfo['paramPrefix'] . ((is_string($columnIndexOrAs)) ? $columnIndexOrAs : 'column') ); $colName .= $columnParts; } else { // Sphinx doesn't not support prefix column with table, yet $colName .= $platform->quoteIdentifier($column); } // process As portion $columnAs = null; if (is_string($columnIndexOrAs)) { $columnAs = $columnIndexOrAs; } elseif (stripos($colName, ' as ') === false && !is_string($column)) { $columnAs = 'Expression' . $expr++; } $columns[] = isset($columnAs) ? [$colName, $platform->quoteIdentifier($columnAs)] : [$colName]; } if ($this->table) { $tableList = $this->table; if (is_string($tableList) && strpos($tableList, ',') !== false) { $tableList = preg_split('#,\s+#', $tableList); } elseif (!is_array($tableList)) { $tableList = [$tableList]; } foreach ($tableList as &$table) { // create quoted table name to use in FROM clause if ($table instanceof Select) { $table = '(' . $this->processSubselect($table, $platform, $driver, $parameterContainer) . ')'; } else { $table = $platform->quoteIdentifier($table); } } $tableList = implode(', ', $tableList); return [$columns, $tableList]; } return [$columns]; }
Process the select part @param PlatformInterface $platform @param DriverInterface $driver @param ParameterContainer $parameterContainer @return null|array
entailment
protected function processExpression( ExpressionInterface $expression, PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null, $namedParameterPrefix = null ) { if ($expression instanceof ExpressionDecorator) { $expressionDecorator = $expression; } else { $expressionDecorator = new ExpressionDecorator($expression, $platform); } return parent::processExpression($expressionDecorator, $platform, $driver, $parameterContainer, $namedParameterPrefix); }
{@inheritdoc}
entailment
public function setArguments(array $array = array()) { foreach ($array as $arg) { if (!is_scalar($arg)) { $type = gettype($arg); throw new DomainException("Arguments array should be an array of scalar, but found $type"); } $this->addArgument($arg); } return $this; }
Set the Directive's arguments @param array $array [required] An array of string arguments @return $this @throws DomainException
entailment
public function addArgument($arg, $unique = false) { if (!is_scalar($arg)) { throw new InvalidArgumentException('scalar', 0); } // escape arguments with spaces if (strpos($arg, ' ') !== false && (strpos($arg, '"') === false) ) { $arg = "\"$arg\""; } if (in_array($arg, $this->arguments) && $unique) { return $this; } $this->arguments[] = $arg; return $this; }
Add an argument to the Directive arguments array @param mixed $arg [required] A scalar @param bool $unique [optional] If this argument is unique @return $this @throws InvalidArgumentException
entailment
public function removeArgument($arg) { if (($name = array_search($arg, $this->arguments)) !== false) { unset($this->arguments[$name]); } return $this; }
Remove an argument from the Directive's arguments array @param string $arg @return $this
entailment
public function objectToString($object, $options = array()) { $bitMask = isset($options['bitmask']) ? $options['bitmask'] : 0; // The depth parameter is only present as of PHP 5.5 if (version_compare(PHP_VERSION, '5.5', '>=')) { $depth = isset($options['depth']) ? $options['depth'] : 512; return json_encode($object, $bitMask, $depth); } return json_encode($object, $bitMask); }
Converts an object into a JSON formatted string. @param object $object Data source object. @param array $options Options used by the formatter. @return string JSON formatted string. @since 1.0
entailment
public function stringToObject($data, array $options = array('processSections' => false)) { $data = trim($data); // Because developers are clearly not validating their data before pushing it into a Registry, we'll do it for them if (empty($data)) { return new \stdClass; } if ($data !== '' && $data[0] !== '{') { return AbstractRegistryFormat::getInstance('Ini')->stringToObject($data, $options); } $decoded = json_decode($data); // Check for an error decoding the data if ($decoded === null && json_last_error() !== JSON_ERROR_NONE) { throw new \RuntimeException(sprintf('Error decoding JSON data: %s', json_last_error_msg())); } return (object) $decoded; }
Parse a JSON formatted string and convert it into an object. If the string is not in JSON format, this method will attempt to parse it as INI format. @param string $data JSON formatted string to convert. @param array $options Options used by the formatter. @return object Data object. @since 1.0 @throws \RuntimeException
entailment
public function Link($action = null) { if ($this->data()->virtualOwner) { $controller = ElementController::create($this->data()->virtualOwner); return $controller->Link($action); } return parent::Link($action); }
@param string $action @return string
entailment
public function redirect($url, $code = 302) { if ($this->data()->virtualOwner) { $parts = explode('#', $url); if (isset($parts[1])) { $url = $parts[0] . '#' . $this->data()->virtualOwner->ID; } } return parent::redirect($url, $code); }
if this is a virtual request, change the hash if set. @param string $url @param int $code @return HTTPResponse
entailment
public function initialize(array $options) { $controller = $this->_registry->getController(); $this->authUser = $controller->Auth->user(); Configure::write('GlobalAuth', $this->authUser); }
initialize @param array $options Options. @return void
entailment
public function setSamplingRate($samplingRate) { if ($samplingRate <= 0.0 || 1.0 < $samplingRate) { throw new \LogicException('Sampling rate shall be within ]0, 1]'); } $this->samplingRate = $samplingRate; $this->samplingFunction = function($min, $max){ return rand($min, $max); }; }
Actually defines the sampling rate used by the service. If set to 0.1, the service will automatically discard 10% of the incoming metrics. It will also automatically flag these as sampled data to statsd. @param float $samplingRate
entailment
public function timing($key, $time) { $this->appendToBuffer( $this->factory->timing($key, $time) ); return $this; }
{@inheritdoc}
entailment
public function gauge($key, $value) { $this->appendToBuffer( $this->factory->gauge($key, $value) ); return $this; }
{@inheritdoc}
entailment
public function set($key, $value) { $this->appendToBuffer( $this->factory->set($key, $value) ); return $this; }
{@inheritdoc}
entailment
public function updateCount($key, $delta) { $this->appendToBuffer( $this->factory->updateCount($key, $delta) ); return $this; }
{@inheritdoc}
entailment
public static function recursiveUnlink(string $folder, bool $remove_folder = true): bool { try { self::emptyFolder($folder); if ( $remove_folder && rmdir($folder) === false ) { throw new Exception("Error deleting folder: $folder"); } return true; } catch (Exception $e) { throw $e; } }
Unlink a folder recursively @param string $folder The folder to be removed @param bool $remove_folder If true, the folder itself will be removed @return bool @throws Exception
entailment
public function beforeSave($event, $entity, $options) { $uploads = []; $fields = $this->getFieldList(); foreach ($fields as $field => $data) { if (!is_string($entity->get($field))) { $uploads[$field] = $entity->get($field); $entity->set($field, null); } if (!$entity->isNew()) { $dirtyField = $entity->dirty($field); $originalField = $entity->getOriginal($field); if ($dirtyField && !is_null($originalField) && !is_array($originalField)) { $fieldConfig = $this->config($field); if ($fieldConfig['removeFileOnUpdate']) { $this->_removeFile($entity->getOriginal($field)); } } } } $this->_uploads = $uploads; }
beforeSave callback @param \Cake\Event\Event $event Event. @param \Cake\ORM\Entity $entity The Entity. @param array $options Options. @return void
entailment
public function afterSave($event, $entity, $options) { $fields = $this->getFieldList(); $storedToSave = []; foreach ($fields as $field => $data) { if ($this->_ifUploaded($entity, $field)) { if ($this->_uploadFile($entity, $field)) { if (!key_exists($field, $this->_savedFields)) { $this->_savedFields[$field] = true; $storedToSave[] = $this->_setUploadColumns($entity, $field); } } } } foreach ($storedToSave as $toSave) { $event->subject()->save($toSave); } $this->_savedFields = []; }
afterSave callback @param \Cake\Event\Event $event Event. @param \Cake\ORM\Entity $entity The Entity who has been saved. @param array $options Options. @return void
entailment
public function beforeDelete($event, $entity, $options) { $fields = $this->getFieldList(); foreach ($fields as $field => $data) { $fieldConfig = $this->config($field); if ($fieldConfig['removeFileOnDelete']) { $this->_removeFile($entity->get($field)); } } }
beforeDelete callback @param \Cake\Event\Event $event Event. @param \Cake\ORM\Entity $entity Entity. @param array $options Options. @return void
entailment
public function getFieldList($options = []) { $_options = [ 'normalize' => true, ]; $options = Hash::merge($_options, $options); $list = []; foreach ($this->config() as $key => $value) { if (!in_array($key, $this->_presetConfigKeys) || is_integer($key)) { if (is_integer($key)) { $field = $value; } else { $field = $key; } if ($options['normalize']) { $fieldConfig = $this->_normalizeField($field); } else { $fieldConfig = (($this->config($field) == null) ? [] : $this->config($field)); } $list[$field] = $fieldConfig; } } return $list; }
Returns a list of all registered fields to upload ### Options - normalize boolean if each field should be normalized. Default set to true @param array $options Options. @return array
entailment
protected function _ifUploaded($entity, $field) { if (array_key_exists($field, $this->_uploads)) { $data = $this->_uploads[$field]; if (!empty($data['tmp_name'])) { return true; } } return false; }
_ifUploaded Checks if an file has been uploaded by user. @param \Cake\ORM\Entity $entity Entity to check on. @param string $field Field to check on. @return bool
entailment
protected function _uploadFile($entity, $field, $options = []) { $_upload = $this->_uploads[$field]; $uploadPath = $this->_getPath($entity, $field, ['file' => true]); // creating the path if not exists if (!is_dir($this->_getPath($entity, $field, ['root' => false, 'file' => false]))) { $this->_mkdir($this->_getPath($entity, $field, ['root' => false, 'file' => false]), 0777, true); } // upload the file and return true if ($this->_moveUploadedFile($_upload['tmp_name'], $uploadPath)) { return true; } return false; }
_uploadFile Uploads the file to the directory @param \Cake\ORM\Entity $entity Entity to upload from. @param string $field Field to use. @param array $options Options. @return bool
entailment
protected function _setUploadColumns($entity, $field, $options = []) { $fieldConfig = $this->config($field); $_upload = $this->_uploads[$field]; // set all columns with values foreach ($fieldConfig['fields'] as $key => $column) { if ($column) { if ($key == "url") { $entity->set($column, $this->_getUrl($entity, $field)); } if ($key == "directory") { $entity->set($column, $this->_getPath($entity, $field, ['root' => false, 'file' => false])); } if ($key == "type") { $entity->set($column, $_upload['type']); } if ($key == "size") { $entity->set($column, $_upload['size']); } if ($key == "fileName") { $entity->set($column, $this->_getFileName($entity, $field, $options = [])); } if ($key == "filePath") { $entity->set($column, $this->_getPath($entity, $field, ['root' => false, 'file' => true])); } } } return $entity; }
_setUploadColumns Writes all data of the upload to the entity Returns the modified entity @param \Cake\ORM\Entity $entity Entity to check on. @param string $field Field to check on. @param array $options Options. @return \Cake\ORM\Entity
entailment
protected function _normalizeField($field, $options = []) { $_options = [ 'save' => true, ]; $options = Hash::merge($_options, $options); $data = $this->config($field); if (is_null($data)) { foreach ($this->config() as $key => $config) { if ($config == $field) { if ($options['save']) { $this->config($field, []); $this->_configDelete($key); } $data = []; } } } // adding the default directory-field if not set if (is_null(Hash::get($data, 'fields.filePath'))) { $data = Hash::insert($data, 'fields.filePath', $field); } $data = Hash::merge($this->config('defaultFieldConfig'), $data); if ($options['save']) { $this->config($field, $data); } return $data; }
_normalizeField Normalizes the requested field. ### Options - save boolean if the normalized data should be saved in config default set to true @param string $field Field to normalize. @param array $options Options. @return array
entailment
protected function _getPath($entity, $field, $options = []) { $_options = [ 'root' => true, 'file' => false, ]; $options = Hash::merge($_options, $options); $config = $this->config($field); $path = $config['path']; $replacements = [ '{ROOT}' => ROOT, '{WEBROOT}' => 'webroot', '{field}' => $entity->get($config['field']), '{model}' => Inflector::underscore($this->_Table->alias()), '{DS}' => DIRECTORY_SEPARATOR, '\\' => DIRECTORY_SEPARATOR, ]; $builtPath = str_replace(array_keys($replacements), array_values($replacements), $path); if (!$options['root']) { $builtPath = str_replace(ROOT . DS . 'webroot' . DS, '', $builtPath); } if ($options['file']) { $builtPath = $builtPath . $this->_getFileName($entity, $field); } return $builtPath; }
_getPath Returns the path of the given field. ### Options - `root` - If root should be added to the path. - `file` - If the file should be added to the path. @param \Cake\ORM\Entity $entity Entity to check on. @param string $field Field to check on. @param array $options Options. @return string
entailment
protected function _getUrl($entity, $field) { $path = '/' . $this->_getPath($entity, $field, ['root' => false, 'file' => true]); return str_replace(DS, '/', $path); }
_getUrl Returns the URL of the given field. @param \Cake\ORM\Entity $entity Entity to check on. @param string $field Field to check on. @return string
entailment
protected function _getFileName($entity, $field, $options = []) { $_options = [ ]; $options = Hash::merge($_options, $options); $config = $this->config($field); $_upload = $this->_uploads[$field]; $fileInfo = explode('.', $_upload['name']); $extension = end($fileInfo); $fileName = $config['fileName']; $replacements = [ '{ORIGINAL}' => $_upload['name'], '{field}' => $entity->get($config['field']), '{extension}' => $extension, '{DS}' => DIRECTORY_SEPARATOR, '//' => DIRECTORY_SEPARATOR, '/' => DIRECTORY_SEPARATOR, '\\' => DIRECTORY_SEPARATOR, ]; $builtFileName = str_replace(array_keys($replacements), array_values($replacements), $fileName); return $builtFileName; }
_getFileName Returns the fileName of the given field. @param \Cake\ORM\Entity $entity Entity to check on. @param string $field Field to check on. @param array $options Options. @return string
entailment
protected function _removeFile($file) { $_file = new File($file); if ($_file->exists()) { $_file->delete(); $folder = $_file->folder(); if (count($folder->find()) === 0) { $folder->delete(); } return true; } return false; }
_removeFile @param string $file Path of the file @return bool
entailment
public function objectToString($object, $options = array()) { $options = array_merge(self::$options, $options); $supportArrayValues = $options['supportArrayValues']; $local = array(); $global = array(); $variables = get_object_vars($object); $last = \count($variables); // Assume that the first element is in section $inSection = true; // Iterate over the object to set the properties. foreach ($variables as $key => $value) { // If the value is an object then we need to put it in a local section. if (\is_object($value)) { // Add an empty line if previous string wasn't in a section if (!$inSection) { $local[] = ''; } // Add the section line. $local[] = '[' . $key . ']'; // Add the properties for this section. foreach (get_object_vars($value) as $k => $v) { if (\is_array($v) && $supportArrayValues) { $assoc = ArrayHelper::isAssociative($v); foreach ($v as $arrayKey => $item) { $arrayKey = $assoc ? $arrayKey : ''; $local[] = $k . '[' . $arrayKey . ']=' . $this->getValueAsIni($item); } } else { $local[] = $k . '=' . $this->getValueAsIni($v); } } // Add empty line after section if it is not the last one if (--$last !== 0) { $local[] = ''; } } elseif (\is_array($value) && $supportArrayValues) { $assoc = ArrayHelper::isAssociative($value); foreach ($value as $arrayKey => $item) { $arrayKey = $assoc ? $arrayKey : ''; $global[] = $key . '[' . $arrayKey . ']=' . $this->getValueAsIni($item); } } else { // Not in a section so add the property to the global array. $global[] = $key . '=' . $this->getValueAsIni($value); $inSection = false; } } return implode("\n", array_merge($global, $local)); }
Converts an object into an INI formatted string - Unfortunately, there is no way to have ini values nested further than two levels deep. Therefore we will only go through the first two levels of the object. @param object $object Data source object. @param array $options Options used by the formatter. @return string INI formatted string. @since 1.0
entailment
public function stringToObject($data, array $options = array()) { $options = array_merge(self::$options, $options); // Check the memory cache for already processed strings. $hash = md5($data . ':' . (int) $options['processSections']); if (isset(self::$cache[$hash])) { return self::$cache[$hash]; } // If no lines present just return the object. if (empty($data)) { return new stdClass; } $obj = new stdClass; $section = false; $array = false; $lines = explode("\n", $data); // Process the lines. foreach ($lines as $line) { // Trim any unnecessary whitespace. $line = trim($line); // Ignore empty lines and comments. if (empty($line) || ($line[0] === ';')) { continue; } if ($options['processSections']) { $length = \strlen($line); // If we are processing sections and the line is a section add the object and continue. if ($line[0] === '[' && ($line[$length - 1] === ']')) { $section = substr($line, 1, $length - 2); $obj->$section = new stdClass; continue; } } elseif ($line[0] === '[') { continue; } // Check that an equal sign exists and is not the first character of the line. if (!strpos($line, '=')) { // Maybe throw exception? continue; } // Get the key and value for the line. list($key, $value) = explode('=', $line, 2); // If we have an array item if (substr($key, -1) === ']' && ($openBrace = strpos($key, '[', 1)) !== false) { if ($options['supportArrayValues']) { $array = true; $arrayKey = substr($key, $openBrace + 1, -1); // If we have a multi-dimensional array or malformed key if (strpos($arrayKey, '[') !== false || strpos($arrayKey, ']') !== false) { // Maybe throw exception? continue; } $key = substr($key, 0, $openBrace); } else { continue; } } // Validate the key. if (preg_match('/[^A-Z0-9_]/i', $key)) { // Maybe throw exception? continue; } // If the value is quoted then we assume it is a string. $length = \strlen($value); if ($length && ($value[0] === '"') && ($value[$length - 1] === '"')) { // Strip the quotes and Convert the new line characters. $value = stripcslashes(substr($value, 1, $length - 2)); $value = str_replace('\n', "\n", $value); } else { // If the value is not quoted, we assume it is not a string. // If the value is 'false' assume boolean false. if ($value === 'false') { $value = false; } elseif ($value === 'true') { // If the value is 'true' assume boolean true. $value = true; } elseif ($options['parseBooleanWords'] && \in_array(strtolower($value), array('yes', 'no'), true)) { // If the value is 'yes' or 'no' and option is enabled assume appropriate boolean $value = (strtolower($value) === 'yes'); } elseif (is_numeric($value)) { // If the value is numeric than it is either a float or int. // If there is a period then we assume a float. if (strpos($value, '.') !== false) { $value = (float) $value; } else { $value = (int) $value; } } } // If a section is set add the key/value to the section, otherwise top level. if ($section) { if ($array) { if (!isset($obj->$section->$key)) { $obj->$section->$key = array(); } if (!empty($arrayKey)) { $obj->$section->{$key}[$arrayKey] = $value; } else { $obj->$section->{$key}[] = $value; } } else { $obj->$section->$key = $value; } } else { if ($array) { if (!isset($obj->$key)) { $obj->$key = array(); } if (!empty($arrayKey)) { $obj->{$key}[$arrayKey] = $value; } else { $obj->{$key}[] = $value; } } else { $obj->$key = $value; } } $array = false; } // Cache the string to save cpu cycles -- thus the world :) self::$cache[$hash] = clone $obj; return $obj; }
Parse an INI formatted string and convert it into an object. @param string $data INI formatted string to convert. @param array $options An array of options used by the formatter, or a boolean setting to process sections. @return object Data object. @since 1.0
entailment
protected function getValueAsIni($value) { $string = ''; switch (\gettype($value)) { case 'integer': case 'double': $string = $value; break; case 'boolean': $string = $value ? 'true' : 'false'; break; case 'string': // Sanitize any CRLF characters.. $string = '"' . str_replace(array("\r\n", "\n"), '\\n', $value) . '"'; break; } return $string; }
Method to get a value in an INI format. @param mixed $value The value to convert to INI format. @return string The value in INI format. @since 1.0
entailment
protected function getConfig($services) { if ($this->config !== null) { return $this->config; } if (!$services->has('Config')) { $this->config = []; return $this->config; } $config = $services->get('Config'); if (!isset($config['sphinxql']) || !is_array($config['sphinxql']) ) { $this->config = []; return $this->config; } $config = $config['sphinxql']; if (!isset($config['adapters']) || !is_array($config['adapters']) ) { $this->config = []; return $this->config; } $this->config = $config['adapters']; return $this->config; }
Get db configuration, if any @param ServiceLocatorInterface|ContainerInterface $services @return array
entailment
public function createServiceWithName(ServiceLocatorInterface $services, $name, $requestedName) { $config = $this->getConfig($services); return AdapterServiceFactory::factory($config[$requestedName]); }
Create a DB adapter @param ServiceLocatorInterface $services @param string $name @param string $requestedName @throws Exception\UnsupportedDriverException @return \Zend\Db\Adapter\Adapter
entailment
public function menu($area, $helper, $options = []) { $_options = [ 'showChildren' => false ]; $options = Hash::merge($_options, $options); $builder = $this->_View->helpers()->load($helper); $menu = $this->_View->viewVars['menu'][$area]; $showChildren = $options['showChildren']; unset($options['showChildren']); $html = ''; $html .= $builder->beforeMenu($menu, $options); foreach ($menu as $item) { $html .= $builder->beforeItem($item); $html .= $builder->item($item); if ($showChildren && $item['children']) { $html .= $builder->beforeSubItem($item); foreach ($item['children'] as $subItem) { $html .= $builder->subItem($subItem); } $html .= $builder->afterSubItem($item); } $html .= $builder->afterItem($item); } $html .= $builder->afterMenu($menu); return $html; }
menu The menu method who builds up the menu. This method will return html code. The binded template to an area is used to style the menu. @param string $area Area to build. @param string $helper Helper to use. @param array $options Options. @return string
entailment
public function objectToString($object, $params = array()) { // A class must be provided $class = !empty($params['class']) ? $params['class'] : 'Registry'; // Build the object variables string $vars = ''; foreach (get_object_vars($object) as $k => $v) { if (is_scalar($v)) { $vars .= "\tpublic $" . $k . " = '" . addcslashes($v, '\\\'') . "';\n"; } elseif (\is_array($v) || \is_object($v)) { $vars .= "\tpublic $" . $k . ' = ' . $this->getArrayString((array) $v) . ";\n"; } } $str = "<?php\n"; // If supplied, add a namespace to the class object if (isset($params['namespace']) && $params['namespace'] !== '') { $str .= 'namespace ' . $params['namespace'] . ";\n\n"; } $str .= 'class ' . $class . " {\n"; $str .= $vars; $str .= '}'; // Use the closing tag if it not set to false in parameters. if (!isset($params['closingtag']) || $params['closingtag'] !== false) { $str .= "\n?>"; } return $str; }
Converts an object into a php class string. - NOTE: Only one depth level is supported. @param object $object Data Source Object @param array $params Parameters used by the formatter @return string Config class formatted string @since 1.0
entailment
public function isPreparedStatementUsed() { if ($this->executeMode === self::QUERY_MODE_AUTO) { // Mysqli doesn't support client side prepared statement emulation if ($this->getAdapter()->getDriver() instanceof ZendMysqliDriver) { return false; } // By default, we use PDO prepared statement emulation return true; } if ($this->executeMode === self::QUERY_MODE_PREPARED) { return true; } return false; }
Are we using prepared statement? @return boolean
entailment
protected function write(array $record) { $records = is_array($record['formatted']) ? $record['formatted'] : array($record['formatted']); foreach ($records as $record) { if (!empty($record)) { $this->buffer[] = $this->statsDFactory->increment(sprintf('%s.%s', $this->getPrefix(), $record)); } } }
{@inheritdoc}
entailment
public function getFirstWords($message) { $glue = '-'; $pieces = explode(' ', $message); array_splice($pieces, $this->numberOfWords); $shortMessage = preg_replace("/[^A-Za-z0-9?![:space:]]/", "-", implode($glue, $pieces)); return $shortMessage; }
This function converts a long message into a string with the first N-words. eg. from: "Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener" to: "Notified event" @param string $message The message to shortify. @return string
entailment
public function format(array $record) { $vars = $this->normalize($record); $firstRow = $this->format; $output = array(); $vars['short_message'] = $this->getFirstWords($vars['message']); foreach ($vars as $var => $val) { $firstRow = str_replace('%' . $var . '%', $this->convertToString($val), $firstRow); } $output[] = $firstRow; // creating more rows for context content if ($this->logContext && isset($vars['context'])) { foreach ($vars['context'] as $key => $parameter) { if (!is_string($parameter)) { $parameter = json_encode($parameter); } $output[] = sprintf("%s.context.%s.%s", $firstRow, $key, $parameter); } } // creating more rows for extra content if ($this->logExtra && isset($vars['extra'])) { foreach ($vars['extra'] as $key => $parameter) { if (!is_string($parameter)) { $parameter = json_encode($parameter); } $output[] = sprintf("%s.extra.%s.%s", $firstRow, $key, $parameter); } } return $output; }
{@inheritdoc}
entailment
public function formatBatch(array $records) { $output = array(); foreach ($records as $record) { $output = array_merge($output, $this->format($record)); } return $output; }
{@inheritdoc}
entailment
public function setLineBreaks(array $lineBreaks) { foreach ($lineBreaks as $lb) { if (!is_int($lb)) { throw new DomainException("lineBreaks array is expected to contain only integers"); } $this->lineBreaks[] = $lb; } return $this; }
Set the line breaks @param int[] $lineBreaks Array of integers @throws DomainException @return $this
entailment
public function quoteTrustedValue($value) { if (is_int($value)) { return (string)$value; } elseif (is_float($value)) { return $this->floatConversion ? $this->toFloatSinglePrecision($value) : (string)$value; } elseif (is_null($value)) { return 'NULL'; // Not supported by SphinxQL, but included for consistency with prepared statement behavior } return parent::quoteTrustedValue($value); }
Quotes trusted value The ability to quote values without notices @param $value @return string
entailment
public function setArguments(array $arguments) { foreach ($arguments as $arg) { if (!is_scalar($arg)) { $type = gettype($arg); throw new DomainException("Arguments array should be an array of scalar, but found $type"); } } $this->arguments = $arguments; return $this; }
Set the block's arguments @param array $arguments [required] An array of arguments @return $this @throws DomainException
entailment
public function addArgument($arg) { if (!is_scalar($arg)) { throw new InvalidArgumentException('scalar', 0); } if (!in_array($arg, $this->arguments)) { $this->arguments[] = $arg; } return $this; }
Add an argument to the Block arguments array @param mixed $arg [required] A scalar @return $this @throws InvalidArgumentException
entailment
public function removeArgument($arg) { if (($key = array_search($arg, $this->arguments)) !== false) { unset($this->arguments[$key]); } return $this; }
Remove an argument from the Block arguments array @param string [required] $arg @return $this
entailment
public function removeChild(TokenInterface $child, $strict = true) { $index = array_search($child, $this->children, !!$strict); if ($index !== false) { unset($this->children[$index]); } return $this; }
Remove a child from this block @param TokenInterface $child [required] The child to remove @param bool $strict [optional] Default true. If the comparison should be strict. A non strict comparsion will remove a child if it has the same properties with the same values @return $this
entailment
public function offsetGet($offset) { if (!is_scalar($offset)) { throw new InvalidArgumentException('scalar', 0); } if (!$this->offsetExists($offset)) { throw new \DomainException("$offset is not set"); } return $this->children[$offset]; }
Offset to retrieve @link http://php.net/manual/en/arrayaccess.offsetget.php @param mixed $offset The offset to retrieve. @return mixed Can return all argument types. @throws InvalidArgumentException
entailment
public function offsetSet($offset, $argument) { if (!is_null($offset) && !is_scalar($offset)) { throw new InvalidArgumentException('scalar', 0); } if (!$argument instanceof TokenInterface) { throw new InvalidArgumentException('TokenInterface', 1); } if (!in_array($argument, $this->children)) { $this->children[$offset] = $argument; } }
Offset to set @link http://php.net/manual/en/arrayaccess.offsetset.php @param mixed $offset The offset to assign the argument to. @param mixed $argument The argument to set. @throws InvalidArgumentException
entailment
function jsonSerialize() { $array = [ 'arguments' => $this->arguments, 'children' => array() ]; foreach ($this->children as $child) { if (!$child instanceof WhiteLine & !$child instanceof Comment) { $array['children'][$child->getName()] = $child->jsonSerialize(); } } return $array; }
Return an array ready for serialization. Ignores comments and whitelines @link http://php.net/manual/en/jsonserializable.jsonserialize.php @return mixed data which can be serialized by <b>json_encode</b>, which is a argument of any type other than a resource.
entailment
public function toArray() { $array = [ 'name' => $this->getName(), 'arguments' => $this->getArguments(), 'children' => array() ]; foreach ($this->children as $child) { $array['children'][] = $child->toArray(); } return $array; }
Get the array representation of the Token @return array
entailment
public function setMode($mode) { if (!in_array($mode, ['article', 'product', 'image', 'auto'])) { $error = 'Only "article", "product" and "image" modes supported.'; throw new \InvalidArgumentException($error); } $this->otherOptions['mode'] = $mode; return $this; }
By default the Analyze API will fully extract all pages that match an existing Automatic API -- articles, products or image pages. Set mode to a specific page-type (e.g., mode=article) to extract content only from that specific page-type. All other pages will simply return the default Analyze fields. @param string $mode article, product or image @return $this
entailment
public function prepareStatement(AdapterInterface $adapter, StatementContainerInterface $statementContainer) { $driver = $adapter->getDriver(); $platform = $adapter->getPlatform(); $parameterContainer = $statementContainer->getParameterContainer(); if (!$parameterContainer instanceof ParameterContainer) { $parameterContainer = new ParameterContainer(); $statementContainer->setParameterContainer($parameterContainer); } $table = $this->table; $table = $platform->quoteIdentifier($table); $set = $this->set; $setSql = []; foreach ($set as $column => $value) { if ($value instanceof Predicate\Expression) { $exprData = $this->processExpression($value, $platform, $driver, $parameterContainer); $setSql[] = $platform->quoteIdentifier($column) . ' = ' . $exprData; } else { $setSql[] = $platform->quoteIdentifier($column) . ' = ' . $driver->formatParameterName($column); $parameterContainer->offsetSet($column, $value); } } $set = implode(', ', $setSql); $sql = sprintf($this->specifications[self::SPECIFICATION_UPDATE], $table, $set); // Process where if ($this->where->count() > 0) { $whereParts = $this->processExpression($this->where, $platform, $driver, $parameterContainer, 'where'); $sql .= ' ' . sprintf($this->specifications[self::SPECIFICATION_WHERE], $whereParts); } // Process option $optionParts = $this->processOption($platform, $driver, $parameterContainer); if (is_array($optionParts)) { $sql .= ' ' . $this->createSqlFromSpecificationAndParameters( $this->specifications[self::SPECIFICATION_OPTION], $optionParts ); } $statementContainer->setSql($sql); }
Prepare statement @param AdapterInterface $adapter @param StatementContainerInterface $statementContainer @return void
entailment
public function getSqlString(PlatformInterface $adapterPlatform = null) { $adapterPlatform = ($adapterPlatform) ? : new Sql92; $table = $this->table; $table = $adapterPlatform->quoteIdentifier($table); $set = $this->set; $setSql = []; foreach ($set as $col => $val) { if ($val instanceof Predicate\Expression) { $exprData = $this->processExpression($val, $adapterPlatform); $setSql[] = $adapterPlatform->quoteIdentifier($col) . ' = ' . $exprData; } elseif ($val === null) { $setSql[] = $adapterPlatform->quoteIdentifier($col) . ' = NULL'; } else { $setSql[] = $adapterPlatform->quoteIdentifier($col) . ' = ' . $adapterPlatform->quoteValue($val); } } $set = implode(', ', $setSql); $sql = sprintf($this->specifications[self::SPECIFICATION_UPDATE], $table, $set); if ($this->where->count() > 0) { $whereParts = $this->processExpression($this->where, $adapterPlatform, null, null, 'where'); $sql .= ' ' . sprintf($this->specifications[self::SPECIFICATION_WHERE], $whereParts); } $optionParts = $this->processOption($adapterPlatform, null, null); if (is_array($optionParts)) { $sql .= ' ' . $this->createSqlFromSpecificationAndParameters( $this->specifications[self::SPECIFICATION_OPTION], $optionParts ); } return $sql; }
Get SQL string for statement @param null|PlatformInterface $adapterPlatform If null, defaults to Sql92 @return string
entailment
public function exists($path) { // Return default value if path is empty if (empty($path)) { return false; } // Explode the registry path into an array $nodes = explode($this->separator, $path); // Initialize the current node to be the registry root. $node = $this->data; $found = false; // Traverse the registry to find the correct node for the result. foreach ($nodes as $n) { if (\is_array($node) && isset($node[$n])) { $node = $node[$n]; $found = true; continue; } if (!isset($node->$n)) { return false; } $node = $node->$n; $found = true; } return $found; }
Check if a registry path exists. @param string $path Registry path (e.g. joomla.content.showauthor) @return boolean @since 1.0
entailment
public function get($path, $default = null) { // Return default value if path is empty if (empty($path)) { return $default; } if (!strpos($path, $this->separator)) { return (isset($this->data->$path) && $this->data->$path !== null && $this->data->$path !== '') ? $this->data->$path : $default; } // Explode the registry path into an array $nodes = explode($this->separator, trim($path)); // Initialize the current node to be the registry root. $node = $this->data; $found = false; // Traverse the registry to find the correct node for the result. foreach ($nodes as $n) { if (\is_array($node) && isset($node[$n])) { $node = $node[$n]; $found = true; continue; } if (!isset($node->$n)) { return $default; } $node = $node->$n; $found = true; } if (!$found || $node === null || $node === '') { return $default; } return $node; }
Get a registry value. @param string $path Registry path (e.g. joomla.content.showauthor) @param mixed $default Optional default value, returned if the internal value is null. @return mixed Value of entry or null @since 1.0
entailment
public static function getInstance($id) { if (empty(self::$instances[$id])) { self::$instances[$id] = new self; } return self::$instances[$id]; }
Returns a reference to a global Registry object, only creating it if it doesn't already exist. This method must be invoked as: <pre>$registry = Registry::getInstance($id);</pre> @param string $id An ID for the registry instance @return Registry The Registry object. @since 1.0 @deprecated 2.0 Instantiate a new Registry instance instead
entailment
public function loadArray($array, $flattened = false, $separator = null) { if (!$flattened) { $this->bindData($this->data, $array); return $this; } foreach ($array as $k => $v) { $this->set($k, $v, $separator); } return $this; }
Load an associative array of values into the default namespace @param array $array Associative array of value to load @param boolean $flattened Load from a one-dimensional array @param string $separator The key separator @return Registry Return this object to support chaining. @since 1.0
entailment
public function loadFile($file, $format = 'JSON', $options = array()) { $data = file_get_contents($file); return $this->loadString($data, $format, $options); }
Load the contents of a file into the registry @param string $file Path to file to load @param string $format Format of the file [optional: defaults to JSON] @param array $options Options used by the formatter @return Registry Return this object to support chaining. @since 1.0
entailment
public function loadString($data, $format = 'JSON', $options = array()) { // Load a string into the given namespace [or default namespace if not given] $handler = AbstractRegistryFormat::getInstance($format, $options); $obj = $handler->stringToObject($data, $options); // If the data object has not yet been initialized, direct assign the object if (!$this->initialized) { $this->data = $obj; $this->initialized = true; return $this; } $this->loadObject($obj); return $this; }
Load a string into the registry @param string $data String to load into the registry @param string $format Format of the string @param array $options Options used by the formatter @return Registry Return this object to support chaining. @since 1.0
entailment
public function extract($path) { $data = $this->get($path); if ($data === null) { return null; } return new Registry($data); }
Method to extract a sub-registry from path @param string $path Registry path (e.g. joomla.content.showauthor) @return Registry|null Registry object if data is present @since 1.2.0
entailment
public function set($path, $value, $separator = null) { if (empty($separator)) { $separator = $this->separator; } /* * Explode the registry path into an array and remove empty * nodes that occur as a result of a double separator. ex: joomla..test * Finally, re-key the array so they are sequential. */ $nodes = array_values(array_filter(explode($separator, $path), 'strlen')); if (!$nodes) { return; } // Initialize the current node to be the registry root. $node = $this->data; // Traverse the registry to find the correct node for the result. for ($i = 0, $n = \count($nodes) - 1; $i < $n; $i++) { if (\is_object($node)) { if (!isset($node->{$nodes[$i]}) && ($i !== $n)) { $node->{$nodes[$i]} = new \stdClass; } // Pass the child as pointer in case it is an object $node = &$node->{$nodes[$i]}; continue; } if (\is_array($node)) { if (($i !== $n) && !isset($node[$nodes[$i]])) { $node[$nodes[$i]] = new \stdClass; } // Pass the child as pointer in case it is an array $node = &$node[$nodes[$i]]; } } // Get the old value if exists so we can return it switch (true) { case \is_object($node): $result = $node->{$nodes[$i]} = $value; break; case \is_array($node): $result = $node[$nodes[$i]] = $value; break; default: $result = null; break; } return $result; }
Set a registry value. @param string $path Registry Path (e.g. joomla.content.showauthor) @param mixed $value Value of entry @param string $separator The key separator @return mixed The value of the that has been set. @since 1.0
entailment
public function append($path, $value) { $result = null; /* * Explode the registry path into an array and remove empty * nodes that occur as a result of a double dot. ex: joomla..test * Finally, re-key the array so they are sequential. */ $nodes = array_values(array_filter(explode('.', $path), 'strlen')); if ($nodes) { // Initialize the current node to be the registry root. $node = $this->data; // Traverse the registry to find the correct node for the result. // TODO Create a new private method from part of code below, as it is almost equal to 'set' method for ($i = 0, $n = \count($nodes) - 1; $i <= $n; $i++) { if (\is_object($node)) { if (!isset($node->{$nodes[$i]}) && ($i !== $n)) { $node->{$nodes[$i]} = new \stdClass; } // Pass the child as pointer in case it is an array $node = &$node->{$nodes[$i]}; } elseif (\is_array($node)) { if (($i !== $n) && !isset($node[$nodes[$i]])) { $node[$nodes[$i]] = new \stdClass; } // Pass the child as pointer in case it is an array $node = &$node[$nodes[$i]]; } } if (!\is_array($node)) { // Convert the node to array to make append possible $node = get_object_vars($node); } $node[] = $value; $result = $value; } return $result; }
Append value to a path in registry @param string $path Parent registry Path (e.g. joomla.content.showauthor) @param mixed $value Value of entry @return mixed The value of the that has been set. @since 1.4.0
entailment
public function remove($path) { // Cheap optimisation to direct remove the node if there is no separator if (!strpos($path, $this->separator)) { $result = (isset($this->data->$path) && $this->data->$path !== null && $this->data->$path !== '') ? $this->data->$path : null; unset($this->data->$path); return $result; } /* * Explode the registry path into an array and remove empty * nodes that occur as a result of a double separator. ex: joomla..test * Finally, re-key the array so they are sequential. */ $nodes = array_values(array_filter(explode($this->separator, $path), 'strlen')); if (!$nodes) { return; } // Initialize the current node to be the registry root. $node = $this->data; $parent = null; // Traverse the registry to find the correct node for the result. for ($i = 0, $n = \count($nodes) - 1; $i < $n; $i++) { if (\is_object($node)) { if (!isset($node->{$nodes[$i]}) && ($i !== $n)) { continue; } $parent = &$node; $node = $node->{$nodes[$i]}; continue; } if (\is_array($node)) { if (($i !== $n) && !isset($node[$nodes[$i]])) { continue; } $parent = &$node; $node = $node[$nodes[$i]]; continue; } } // Get the old value if exists so we can return it switch (true) { case \is_object($node): $result = isset($node->{$nodes[$i]}) ? $node->{$nodes[$i]} : null; unset($parent->{$nodes[$i]}); break; case \is_array($node): $result = isset($node[$nodes[$i]]) ? $node[$nodes[$i]] : null; unset($parent[$nodes[$i]]); break; default: $result = null; break; } return $result; }
Delete a registry value @param string $path Registry Path (e.g. joomla.content.showauthor) @return mixed The value of the removed node or null if not set @since 1.6.0
entailment
public function flatten($separator = null) { $array = array(); if (empty($separator)) { $separator = $this->separator; } $this->toFlatten($separator, $this->data, $array); return $array; }
Dump to one dimension array. @param string $separator The key separator. @return string[] Dumped array. @since 1.3.0
entailment
public function setSkipMode(string $mode): ZipInterface { $mode = strtoupper($mode); if ( !in_array($mode, $this->supported_skip_modes) ) { throw new ZipException("Unsupported skip mode: $mode"); } $this->skip_mode = $mode; return $this; }
Set files to skip Supported skip modes: Zip::SKIP_NONE - skip no files Zip::SKIP_HIDDEN - skip hidden files Zip::SKIP_ALL - skip HIDDEN + COMODOJO ghost files Zip::SKIP_COMODOJO - skip comodojo ghost files @param string $mode Skip file mode @return Zip @throws ZipException
entailment
public function addZip(Zip $zip): string { $id = UniqueId::generate(32); $this->zip_archives[$id] = $zip; return $id; }
Add a Zip object to manager and return its id @param Zip $zip @return string
entailment
public function removeZip(Zip $zip): bool { $archive_key = array_search($zip, $this->zip_archives, true); if ( $archive_key === false ) { throw new ZipException("Archive not found"); } unset($this->zip_archives[$archive_key]); return true; }
Remove a Zip object from manager @param Zip $zip @return bool @throws ZipException
entailment
public function removeZipById(string $id): bool { if ( isset($this->zip_archives[$id]) === false ) { throw new ZipException("Archive: $id not found"); } unset($this->zip_archives[$id]); return true; }
Remove a Zip object from manager by Zip id @param string $id @return bool @throws ZipException
entailment
public function listZips(): array { return array_column( array_map(function($key, $archive) { return [ "key" => $key, "file" => $archive->getZipFile() ]; }, array_keys($this->zip_archives), $this->zip_archives), "file", "key"); }
Get a list of all registered Zips filenames as an array @return array
entailment
public function getZip(string $id): Zip { if ( array_key_exists($id, $this->zip_archives) === false ) { throw new ZipException("Archive id $id not found"); } return $this->zip_archives[$id]; }
Get a Zip object by Id @param string $id The zip id @return Zip @throws ZipException
entailment
public function setPath(string $path): ZipManager { try { foreach ( $this->zip_archives as $archive ) { $archive->setPath($path); } return $this; } catch (ZipException $ze) { throw $ze; } }
Set current base path (to add relative files to zip archive) for all Zips @param string $path @return ZipManager @throws ZipException
entailment
public function getPath(): array { return array_column( array_map(function($key, $archive) { return [ "key" => $key, "path" => $archive->getPath() ]; }, array_keys($this->zip_archives), $this->zip_archives), "path", "key"); }
Get a list of paths used by Zips @return array
entailment