/** * @deprecated 3.0 */ public function __construct($items = array()) { Deprecation::notice('3.0', 'Use DataList or ArrayList instead'); if ($items) { if (!is_array($items) || func_num_args() > 1) { $items = func_get_args(); } foreach ($items as $i => $item) { if ($item instanceof ViewableData) { continue; } if (is_object($item) || ArrayLib::is_associative($item)) { $items[$i] = new ArrayData($item); } else { user_error( "DataObjectSet::__construct: Passed item #{$i} is not an" . ' and object or associative array, can\'t be properly' . ' iterated on in templates', E_USER_WARNING ); } } } parent::__construct($items); }
public function getCMSFields() { $conf = SiteConfig::current_site_config(); $themes = $conf->getAvailableThemes(); $theme = new DropdownField('Theme', _t('Multisites.THEME', 'Theme'), $themes); $theme->setEmptyString(_t('Multisites.DEFAULTTHEME', '(Default theme)')); $fields = new FieldList(new TabSet('Root', new Tab('Main', new HeaderField('SiteConfHeader', _t('Multisites.SITECONF', 'Site Configuration')), new TextField('Title', _t('Multisites.TITLE', 'Title')), new TextField('Tagline', _t('Multisites.TAGLINE', 'Tagline/Slogan')), $theme, new HeaderField('SiteURLHeader', _t('Multisites.SITEURL', 'Site URL')), new OptionsetField('Scheme', _t('Multisites.SCHEME', 'Scheme'), array('any' => _t('Multisites.ANY', 'Any'), 'http' => _t('Multisites.HTTP', 'HTTP'), 'https' => _t('Multisites.HTTPS', 'HTTPS (HTTP Secure)'))), new TextField('Host', _t('Multisites.HOST', 'Host')), new MultiValueTextField('HostAliases', _t('Multisites.HOSTALIASES', 'Host Aliases')), new CheckboxField('IsDefault', _t('Multisites.ISDEFAULT', 'Is this the default site?')), new HeaderField('SiteAdvancedHeader', _t('Multisites.SiteAdvancedHeader', 'Advanced Settings')), TextareaField::create('RobotsTxt', _t('Multisites.ROBOTSTXT', 'Robots.txt'))->setDescription(_t('Multisites.ROBOTSTXTUSAGE', '<p>Please consult <a href="http://www.robotstxt.org/robotstxt.html" target="_blank">http://www.robotstxt.org/robotstxt.html</a> for usage of the robots.txt file.</p>'))))); $devIDs = Config::inst()->get('Multisites', 'developer_identifiers'); if (is_array($devIDs)) { if (!ArrayLib::is_associative($devIDs)) { $devIDs = ArrayLib::valuekey($devIDs); } $fields->addFieldToTab('Root.Main', DropdownField::create('DevID', _t('Multisites.DeveloperIdentifier', 'Developer Identifier'), $devIDs)); } if (Multisites::inst()->assetsSubfolderPerSite()) { $fields->addFieldToTab('Root.Main', new TreeDropdownField('FolderID', _t('Multisites.ASSETSFOLDER', 'Assets Folder'), 'Folder'), 'SiteURLHeader'); } if (!Permission::check('SITE_EDIT_CONFIGURATION')) { foreach ($fields->dataFields() as $field) { $fields->makeFieldReadonly($field); } } $this->extend('updateSiteCMSFields', $fields); return $fields; }
/** * Create a new DataObjectSet. If you pass one or more arguments, it will try to convert them into {@link ArrayData} objects. * @todo Does NOT automatically convert objects with complex datatypes (e.g. converting arrays within an objects to its own DataObjectSet) * * @param ViewableData|array|mixed $items Parameters to use in this set, either as an associative array, object with simple properties, or as multiple parameters. */ public function __construct($items = null) { if($items) { // if the first parameter is not an array, or we have more than one parameter, collate all parameters to an array // otherwise use the passed array $itemsArr = (!is_array($items) || count(func_get_args()) > 1) ? func_get_args() : $items; // We now have support for using the key of a data object set foreach($itemsArr as $i => $item) { if(is_subclass_of($item, 'ViewableData')) { $this->items[$i] = $item; } elseif(is_object($item) || ArrayLib::is_associative($item)) { $this->items[$i] = new ArrayData($item); } else { user_error( "DataObjectSet::__construct: Passed item #{$i} is not an object or associative array, can't be properly iterated on in templates", E_USER_WARNING ); $this->items[$i] = $item; } } } parent::__construct(); }
/** * Get a value from a given field * * @param string $f field key * @return mixed */ public function getField($f) { if (is_object($this->array[$f]) && !$this->array[$f] instanceof ViewableData || is_array($this->array[$f]) && ArrayLib::is_associative($this->array[$f])) { return new ArrayData($this->array[$f]); } return $this->array[$f]; }
/** * Add a mapping of nice short permalinks to a full long path * * <code> * DocumentationPermalinks::add(array( * 'debugging' => 'current/en/sapphire/topics/debugging' * )); * </code> * * Do not need to include the language or the version current as it * will add it based off the language or version in the session * * @param array */ public static function add($map = array()) { if (ArrayLib::is_associative($map)) { self::$mapping = array_merge(self::$mapping, $map); } else { user_error("DocumentationPermalinks::add() requires an associative array", E_USER_ERROR); } }
/** * @param string $name - Name of field * @return FormField */ protected function FieldCurrency($name) { $allowedCurrencies = $this->getAllowedCurrencies(); if ($allowedCurrencies) { $field = new DropdownField("{$name}[Currency]", _t('MoneyField.FIELDLABELCURRENCY', 'Currency'), ArrayLib::is_associative($allowedCurrencies) ? $allowedCurrencies : array_combine($allowedCurrencies, $allowedCurrencies)); } else { $field = new TextField("{$name}[Currency]", _t('MoneyField.FIELDLABELCURRENCY', 'Currency')); } return $field; }
/** * @param object|array $array Either an object with simple properties or an associative array. * Converts object-properties to indices of an associative array. */ public function __construct($array) { if (is_object($array)) { $this->array = self::object_to_array($array); } elseif (is_array($array) && ArrayLib::is_associative($array)) { $this->array = $array; } else { $this->array = $array; user_error("ArrayData::__construct: Parameter needs to be an object or associative array", E_USER_WARNING); } }
function testRefusesToWrapAnIndexedArray() { $array = array(0 => "One", 1 => "Two"); $this->assertFalse(ArrayLib::is_associative($array)); /* * Expect user_error() to be called below, if enabled * (tobych) That should be an exception. Something like: * $this->setExpectedException('InvalidArgumentException'); */ // $arrayData = new ArrayData($array); }
/** * Gets a field from this object. * * @param string $field * * If the value is an object but not an instance of * ViewableData, it will be converted recursively to an * ArrayData. * * If the value is an associative array, it will likewise be * converted recursively to an ArrayData. */ public function getField($f) { $value = $this->array[$f]; if (is_object($value) && !$value instanceof ViewableData) { return new ArrayData($value); } elseif (ArrayLib::is_associative($value)) { return new ArrayData($value); } else { return $value; } }
/** * Builds a new currency field based on the allowed currencies configured * * @return FormField */ protected function buildCurrencyField() { $name = $this->getName(); $allowedCurrencies = $this->getAllowedCurrencies(); if ($allowedCurrencies) { $field = new DropdownField("{$name}[Currency]", _t('MoneyField.FIELDLABELCURRENCY', 'Currency'), ArrayLib::is_associative($allowedCurrencies) ? $allowedCurrencies : array_combine($allowedCurrencies, $allowedCurrencies)); } else { $field = new TextField("{$name}[Currency]", _t('MoneyField.FIELDLABELCURRENCY', 'Currency')); } $field->setReadonly($this->isReadonly()); $field->setDisabled($this->isDisabled()); return $field; }
/** * @param string $name * @param string $title * @param DataObjectInterface $object * @param string $sort * @param SS_List $source * @param string $titleField */ public function __construct($name, $title, DataObjectInterface $object, $sort = false, SS_List $source = null, $titleField = 'Title') { $this->setSort($sort); if ($object->many_many($name)) { $dataSource = $object->{$name}(); // Check if we're dealing with an UnsavedRelationList $unsaved = $dataSource instanceof UnsavedRelationList; // Store the relation's class name $class = $dataSource->dataClass(); $this->dataClass = $class; // Sort the items if ($this->getSort()) { $dataSource = $dataSource->sort($this->getSort()); } // If we're dealing with an UnsavedRelationList, it'll be empty, so we // can skip this and just use an array of all available items if ($unsaved) { $dataSource = $class::get()->map()->toArray(); } else { // If we've been given a list source, filter on those IDs only. if ($source) { $dataSource = $dataSource->filter('ID', $source->column('ID')); } // Start building the data source from scratch. Currently selected items first, // in the correct sort order $dataSource = $dataSource->map('ID', $titleField)->toArray(); // Get the other items $theRest = $class::get(); // Exclude items that we've already found if (!empty($dataSource)) { $theRest = $theRest->exclude('ID', array_keys($dataSource)); } // If we've been given a list source, filter on those IDs only if ($source) { $theRest = $theRest->filter('ID', $source->column('ID')); } $theRest = $theRest->map('ID', $titleField)->toArray(); // ... we then add the remaining items in whatever order they come $dataSource = $dataSource + $theRest; } } elseif ($source instanceof SS_List) { $dataSource = $source->map('ID', $titleField)->toArray(); } elseif (is_array($source) && ArrayLib::is_associative($source)) { $dataSource = $source; } else { user_error('MultiSelectField::__construct(): MultiSelectField only supports many-to-many relations'); } parent::__construct($name, $title, $dataSource, '', null, true); }
/** * this method returns an associative array of payment methods * available for the current order. * * @return array */ public function SupportedMethods($order = null) { $hideTestPaymentMethods = false; if (Director::isLive()) { $hideTestPaymentMethods = false; } $supportedMethods = EcommerceConfig::get("EcommercePayment", "supported_methods"); if (ArrayLib::is_associative($supportedMethods)) { if ($hideTestPaymentMethods) { if (count($supportedMethods)) { foreach ($supportedMethods as $methodClass => $methodTitle) { if (is_subclass_of($methodClass, "EcommercePayment_Test")) { unset($supportedMethods[$methodClass]); } } } } } else { user_error('EcommercePayment::$supported_methods() requires an associative array. Right now the supported payments methods are: ' . print_r($supportedMethods, 1), E_USER_NOTICE); } return $supportedMethods; }
/** * Inject the given parameters into the string. This is lifted directly from {@link i18n::_t()}. * @param string $string * @param array $injectionArray * @return string */ protected function inject($string, $injectionArray) { $regex = '/\\{[\\w\\d]*\\}/i'; if (!preg_match($regex, $string)) { // Legacy mode: If no injection placeholders are found, // replace sprintf placeholders in fixed order. // Fail silently in case the translation is outdated preg_match_all('/%[s,d]/', $string, $returnValueArgs); if ($returnValueArgs) { foreach ($returnValueArgs[0] as $i => $returnValueArg) { if ($i >= count($injectionArray)) { $injectionArray[] = ''; } } } $replaced = vsprintf($string, array_values($injectionArray)); if ($replaced) { $string = $replaced; } } elseif (!ArrayLib::is_associative($injectionArray)) { // Legacy mode: If injection placeholders are found, // but parameters are passed without names, replace them in fixed order. $string = preg_replace_callback($regex, function ($matches) use(&$injectionArray) { return $injectionArray ? array_shift($injectionArray) : ''; }, $string); } else { // Standard placeholder replacement with named injections and variable order. foreach ($injectionArray as $variable => $injection) { $placeholder = '{' . $variable . '}'; $string = str_replace($placeholder, $injection, $string, $count); if (!$count) { SS_Log::log(sprintf("Couldn't find placeholder '%s' in translation string '%s' (id: '%s')", $placeholder, $string, $entity), SS_Log::NOTICE); } } } return $string; }
/** * This is the main translator function. Returns the string defined by $class and $entity according to the * currently set locale. * * @param string $entity Entity that identifies the string. It must be in the form "Namespace.Entity" where * Namespace will be usually the class name where this string is used and Entity identifies * the string inside the namespace. * @param string $string The original string itself. In a usual call this is a mandatory parameter, but if you are * reusing a string which has already been "declared" (using another call to this function, * with the same class and entity), you can omit it. * @param string $context (optional) If the string can be difficult to translate by any reason, you can help * translators with some more info using this param * @param string injectionArray (optional) array of key value pairs that are used to replace corresponding * expressions in {curly brackets} in the $string. The injection array can also be * used as the their argument to the _t() function * @return string The translated string, according to the currently set locale {@link i18n::set_locale()} */ public static function _t($entity, $string = "", $context = "", $injection = "") { if (is_numeric($context) && in_array($context, array(PR_LOW, PR_MEDIUM, PR_HIGH))) { Deprecation::notice('3.0', 'The $priority argument to _t() is deprecated, please use module inclusion priorities instead', Deprecation::SCOPE_GLOBAL); } //fetch the injection array out of the parameters (if it is present) $argList = func_get_args(); $argNum = func_num_args(); //_t($entity, $string = "", $context (optional), $injectionArray (optional)) $injectionArray = null; for ($i = 0; $i < $argNum; $i++) { if (is_array($argList[$i])) { //we have reached the injectionArray $injectionArray = $argList[$i]; //any array in the args will be the injection array } } // get current locale (either default or user preference) $locale = i18n::get_locale(); $lang = i18n::get_lang_from_locale($locale); // Only call getter if static isn't already defined (for performance reasons) $translatorsByPrio = self::$translators; if (!$translatorsByPrio) { $translatorsByPrio = self::get_translators(); } $returnValue = is_string($string) ? $string : ''; // Fall back to default string argument foreach ($translatorsByPrio as $priority => $translators) { foreach ($translators as $name => $translator) { $adapter = $translator->getAdapter(); // at this point, we need to ensure the language and locale are loaded // as include_by_locale() doesn't load a fallback. // TODO Remove reliance on global state, by refactoring into an i18nTranslatorManager // which is instanciated by core with a $clean instance variable. if (!$adapter->isAvailable($lang)) { i18n::include_by_locale($lang); } if (!$adapter->isAvailable($locale)) { i18n::include_by_locale($locale); } $translation = $adapter->translate($entity, $locale); // Return translation only if we found a match thats not the entity itself (Zend fallback) if ($translation && $translation != $entity) { $returnValue = $translation; break 2; } } } // inject the variables from injectionArray (if present) if ($injectionArray) { $regex = '/\\{[\\w\\d]*\\}/i'; if (!preg_match($regex, $returnValue)) { // Legacy mode: If no injection placeholders are found, // replace sprintf placeholders in fixed order. // Fail silently in case the translation is outdated preg_match_all('/%[s,d]/', $returnValue, $returnValueArgs); if ($returnValueArgs) { foreach ($returnValueArgs[0] as $i => $returnValueArg) { if ($i >= count($injectionArray)) { $injectionArray[] = ''; } } } $replaced = vsprintf($returnValue, array_values($injectionArray)); if ($replaced) { $returnValue = $replaced; } } else { if (!ArrayLib::is_associative($injectionArray)) { // Legacy mode: If injection placeholders are found, // but parameters are passed without names, replace them in fixed order. $returnValue = preg_replace_callback($regex, function ($matches) use(&$injectionArray) { return $injectionArray ? array_shift($injectionArray) : ''; }, $returnValue); } else { // Standard placeholder replacement with named injections and variable order. foreach ($injectionArray as $variable => $injection) { $placeholder = '{' . $variable . '}'; $returnValue = str_replace($placeholder, $injection, $returnValue, $count); if (!$count) { SS_Log::log(sprintf("Couldn't find placeholder '%s' in translation string '%s' (id: '%s')", $placeholder, $returnValue, $entity), SS_Log::NOTICE); } } } } } return $returnValue; }
/** * Load a value into this CheckboxSetField */ public function setValue($val, $obj = null) { // If we're not passed a value directly, // we can look for it in a relation method on the object passed as a second arg if (!$val && $obj && $obj instanceof DataObject && $obj->hasMethod($this->name)) { $funcName = $this->name; $val = array_values($obj->{$funcName}()->getIDList()); } if ($val) { if (!$this->multiple && is_array($val)) { throw new InvalidArgumentException('No array values allowed with multiple=false'); } if ($this->multiple) { $parts = is_array($val) ? $val : preg_split("/ *, */", trim($val)); if (ArrayLib::is_associative($parts)) { throw new InvalidArgumentException('No associative arrays allowed multiple=true'); } // Doesn't check against unknown values in order to allow for less rigid data handling. // They're silently ignored and overwritten the next time the field is saved. parent::setValue($parts); } else { if (!in_array($val, array_keys($this->getSource()))) { throw new InvalidArgumentException(sprintf('Invalid value "%s" for multiple=false', Convert::raw2xml($val))); } parent::setValue($val); } } else { parent::setValue($val); } return $this; }
function setValue($val) { if ($val) { if (!$this->multiple && is_array($val)) { throw new InvalidArgumentException('No array values allowed with multiple=false'); } if ($this->multiple) { $parts = is_array($val) ? $val : preg_split("/ *, */", trim($val)); if (ArrayLib::is_associative($parts)) { throw new InvalidArgumentException('No associative arrays allowed multiple=true'); } if ($diff = array_diff($parts, array_keys($this->source))) { throw new InvalidArgumentException(sprintf('Invalid keys "%s" in value array for multiple=true', Convert::raw2xml(implode(',', $diff)))); } parent::setValue($parts); } else { if (!in_array($val, array_keys($this->source))) { throw new InvalidArgumentException(sprintf('Invalid value "%s" for multiple=true', Convert::raw2xml($val))); } parent::setValue($val); } } else { parent::setValue($val); } }
/** * Merge some arbitrary data in with this object. This method returns a {@link ViewableData_Customised} instance * with references to both this and the new custom data. * * Note that any fields you specify will take precedence over the fields on this object. * * @param array|ViewableData $data * @return ViewableData_Customised */ public function customise($data) { if (is_array($data) && (empty($data) || ArrayLib::is_associative($data))) { $data = new ArrayData($data); } if ($data instanceof ViewableData) { return new ViewableData_Customised($this, $data); } throw new InvalidArgumentException('ViewableData->customise(): $data must be an associative array or a ViewableData instance'); }
/** * Set a property on all columns * @param string $property * @param array $arr * @return \TableFieldCommon */ public function setProperty($property, $arr) { if (!ArrayLib::is_associative($arr)) { $arr = array_combine($arr, $arr); } // Make sure all columns exists foreach ($arr as $colName => $value) { if (!isset($this->columns[$colName])) { $this->columns[$colName] = array(); } } // Assign values to columns foreach ($this->columns as $colName => $colData) { if (isset($arr[$colName])) { $colData[$property] = $arr[$colName]; $this->columns[$colName] = $colData; } } return $this; }
public function setValue($val, $obj = null) { if (!$val && $obj && $obj instanceof DataObject && $obj->hasMethod($this->name)) { $funcName = $this->name; if ($this->tags) { $val = array(); foreach ($obj->{$funcName}() as $o) { $val[] = $o->Title; } } else { $val = array_values($obj->{$funcName}()->getIDList()); } } if ($val && !is_array($val) && $this->multiple) { $val = explode(self::SEPARATOR, $val); } if ($val) { if (!$this->multiple && is_array($val)) { throw new InvalidArgumentException('Array values are not allowed (when multiple=false).'); } if ($this->multiple) { $parts = is_array($val) ? $val : preg_split("/ *, */", trim($val)); if (ArrayLib::is_associative($parts)) { // This is due to the possibility of accidentally passing an array of values (as keys) and titles (as values) when only the keys were intended to be saved. throw new InvalidArgumentException('Associative arrays are not allowed as values (when multiple=true), only indexed arrays.'); } $this->value = $parts; } else { $this->value = $val; } } else { $this->value = $val; } return $this; }
public function filterArray($q, $list, $class = null, $limit = null) { $results = []; $noOfResults = 0; if ($class && ($search = $this->scaffoldSearchFields($class))) { $context = explode(':', reset($search)); $pattern = ''; if ($q && isset($context[1])) { switch ($context[1]) { case 'StartsWith': $pattern = '/^' . $q . '/'; break; case 'EndsWith': $pattern = '/' . $q . '$/'; break; default: $pattern = '/' . $q . '/'; break; } } } else { $pattern = $q ? '/^' . $q . '/' : ''; } foreach ($list as $key => $item) { if ($limit && $noOfResults >= $limit) { break; } if (ArrayLib::is_associative($list) && is_array($item)) { $result = $this->filterArray($q, $item, $class, $limit); if ($noOfResult = count($result)) { if ($limit && $noOfResults + $noOfResult > $limit) { array_splice($result, 0, $noOfResult - $noOfResults); } $noOfResults += $noOfResult; $results[] = $this->resultGroupToMap($key, $result); } } elseif (is_array($item)) { if (!($value = $this->getValueFromItem($item, $this->refField, ' - ', true))) { $value = ''; } if (!($key = $this->getValueFromItem($item, $this->valField))) { $key = $noOfResults; } if (!is_string($value)) { continue; } if ($pattern && preg_match(preg_quote($pattern), $value)) { $results[] = $this->resultToMap($key, $value); $noOfResults++; } else { $results[] = $this->resultToMap($key, $value); $noOfResults++; } } else { $value = is_string($item) ? $item : $key; if (!is_string($value)) { continue; } if ($pattern && preg_match(preg_quote($pattern), $value)) { $results[] = $this->resultToMap($key, $value); $noOfResults++; } else { $results[] = $this->resultToMap($key, $value); $noOfResults++; } } } if ($this->sortArray) { $key = $this->sortArray === 'key' ? 'id' : 'text'; usort($results, function ($result1, $result2) use($key) { return strcmp($result1[$key], $result2[$key]); }); } return $results; }
/** * @return ArrayList */ public function Breadcrumbs($unlinked = false) { $items = parent::Breadcrumbs($unlinked); // Show the class name rather than ModelAdmin title as root node $models = $this->getManagedModels(); $modelSpec = ArrayLib::is_associative($models) ? $models[$this->modelClass] : null; if(is_array($modelSpec) && isset($modelSpec['title'])) { $items[0]->Title = $modelSpec['title']; } else { $items[0]->Title = singleton($this->modelClass)->i18n_singular_name(); } return $items; }
/** * This is the main translator function. Returns the string defined by $class and $entity according to the * currently set locale. * * @param string $entity Entity that identifies the string. It must be in the form "Namespace.Entity" where * Namespace will be usually the class name where this string is used and Entity identifies * the string inside the namespace. * @param string $string The original string itself. In a usual call this is a mandatory parameter, but if you are * reusing a string which has already been "declared" (using another call to this function, * with the same class and entity), you can omit it. * @param string $context (optional) If the string can be difficult to translate by any reason, you can help * translators with some more info using this param * @param string injectionArray (optional) array of key value pairs that are used to replace corresponding * expressions in {curly brackets} in the $string. The injection array can also be * used as the their argument to the _t() function * @return string The translated string, according to the currently set locale {@link i18n::set_locale()} */ public static function _t($entity, $string = "", $context = "", $injection = "") { if (is_numeric($context) && in_array($context, array(PR_LOW, PR_MEDIUM, PR_HIGH))) { Deprecation::notice('3.0', 'The $priority argument to _t() is deprecated, please use module inclusion priorities instead', Deprecation::SCOPE_GLOBAL); } //fetch the injection array out of the parameters (if it is present) $argList = func_get_args(); $argNum = func_num_args(); //_t($entity, $string = "", $context (optional), $injectionArray (optional)) $injectionArray = null; for ($i = 0; $i < $argNum; $i++) { if (is_array($argList[$i])) { //we have reached the injectionArray $injectionArray = $argList[$i]; //any array in the args will be the injection array } } // Find best translation $locale = i18n::get_locale(); $returnValue = static::with_translators(function (Zend_Translate_Adapter $adapter) use($entity, $locale) { // Return translation only if we found a match thats not the entity itself (Zend fallback) $translation = $adapter->translate($entity, $locale); if ($translation && $translation != $entity) { return $translation; } return null; }); // Fall back to default string argument if ($returnValue === null) { $returnValue = is_string($string) ? $string : ''; } // inject the variables from injectionArray (if present) if ($injectionArray) { $regex = '/\\{[\\w\\d]*\\}/i'; if (!preg_match($regex, $returnValue)) { // Legacy mode: If no injection placeholders are found, // replace sprintf placeholders in fixed order. // Fail silently in case the translation is outdated preg_match_all('/%[s,d]/', $returnValue, $returnValueArgs); if ($returnValueArgs) { foreach ($returnValueArgs[0] as $i => $returnValueArg) { if ($i >= count($injectionArray)) { $injectionArray[] = ''; } } } $replaced = vsprintf($returnValue, array_values($injectionArray)); if ($replaced) { $returnValue = $replaced; } } else { if (!ArrayLib::is_associative($injectionArray)) { // Legacy mode: If injection placeholders are found, // but parameters are passed without names, replace them in fixed order. $returnValue = preg_replace_callback($regex, function ($matches) use(&$injectionArray) { return $injectionArray ? array_shift($injectionArray) : ''; }, $returnValue); } else { // Standard placeholder replacement with named injections and variable order. foreach ($injectionArray as $variable => $injection) { $placeholder = '{' . $variable . '}'; $returnValue = str_replace($placeholder, $injection, $returnValue, $count); if (!$count) { Injector::inst()->get('Logger')->log('notice', sprintf("Couldn't find placeholder '%s' in translation string '%s' (id: '%s')", $placeholder, $returnValue, $entity)); } } } } } return $returnValue; }
/** * A quick way of adding required constraints to a number of fields * @param array $fieldNames - can be either indexed array of fieldnames, or associative array of fieldname => message * @return this */ public function addRequiredFields($fields) { if (ArrayLib::is_associative($fields)) { foreach ($fields as $k => $v) { $constraint = Constraint_required::create(); if ($v) { $constraint->setMessage($v); } $this->setConstraint($k, $constraint); } } else { foreach ($fields as $field) { $this->setConstraint($field, Constraint_required::create()); } } return $this; }
/** * Return a set of payment fields from all enabled * payment methods for this site, given the . {@link Payment::set_supported_methods()} * is used to define which methods are available. * * @return FieldSet */ static function combined_form_fields($amount) { // Create the initial form fields, which defines an OptionsetField // allowing the user to choose which payment method to use. $fields = new FieldSet(new HeaderField(_t('Payment.PAYMENTTYPE', 'Payment Type'), 3), new OptionsetField('PaymentMethod', '', self::$supported_methods, array_shift(array_keys(self::$supported_methods)))); // If the user defined an numerically indexed array, throw an error if (ArrayLib::is_associative(self::$supported_methods)) { foreach (self::$supported_methods as $methodClass => $methodTitle) { // Create a new CompositeField with method specific fields, // as defined on each payment method class using getPaymentFormFields() $methodFields = new CompositeField(singleton($methodClass)->getPaymentFormFields()); $methodFields->setID("MethodFields_{$methodClass}"); $methodFields->addExtraClass('paymentfields'); // Add those fields to the initial FieldSet we first created $fields->push($methodFields); } } else { user_error('Payment::set_supported_methods() requires an associative array.', E_USER_ERROR); } // Add the amount and subtotal fields for the payment amount $fields->push(new ReadonlyField('Amount', _t('Payment.AMOUNT', 'Amount'), $amount)); return $fields; }
protected function convertToArrayData(&$data) { foreach ($data as $key => $item) { if (is_array($item)) { if (!\ArrayLib::is_associative($item)) { $this->convertToArrayData($item); $data[$key] = \ArrayList::create($item); } else { $data[$key] = \ArrayData::create($item); } } } }
/** * if an object isn't already wrapped in Silverstripe's stuff, * wrap it appropriately either in a viewableWrapper or dataobject set */ protected function wrapObject($obj) { if (is_object($obj)) { // if it's an object, just check the type and wrap if needed if ($obj instanceof ViewableWrapper) { return $obj; } else { return new ViewableWrapper($obj); } } elseif (is_array($obj)) { // if it's an assoc array just wrap it, otherwise make a dataobjectset if (ArrayLib::is_associative($obj)) { return new ViewableWrapper($obj); } else { $set = new ArrayList(); foreach ($obj as $i => $item) { $wrap = $this->wrapObject($item); $set->push($wrap); } return $set; } } else { // it's a simple type, just return it return $obj; } }