public function testToArray() { $array = array('asd'); $iterator = \Nette\Utils\ArrayHash::from($array); $this->assertSame($array, Arrays::toArray($array)); $this->assertSame($array, Arrays::toArray($iterator)); }
/** * @param bool $asArray * @return array|ArrayHash */ public function getValues($asArray = FALSE) { if ($asArray) { return (array) $this->getSection()->values; } else { return ArrayHash::from((array) $this->getSection()->values); } }
/** * @return Nette\Utils\ArrayHash */ public function findAllByKeys() { $keys = $this->dao->findBy([]); $result = []; foreach ($keys as $key) { $result[$key->key] = is_numeric($key->value) ? (double) $key->value : $key->value; } return Nette\Utils\ArrayHash::from($result); }
/** * {@inheritdoc} */ public function isAllowed($element) { // Check annotations only if element have to be secured if (is_array($element)) { $element = Utils\ArrayHash::from($element); return $this->checkUser($element) && $this->checkResources($element) && $this->checkPrivileges($element) && $this->checkPermission($element) && $this->checkRoles($element); } else { return TRUE; } }
/** * @param bool|FALSE $forceObject * @return array|object */ public function getRawContent($forceObject = FALSE) { $out = []; foreach ($this->data as $k => $v) { if (is_null($v)) { continue; } $out[$k] = $v->getRawContent($forceObject); } return $forceObject ? Nette\Utils\ArrayHash::from($out) : $out; }
/** * @return ArrayHash|null */ public function loadOptions() { $options = $this->cache->load(Option::getCacheKey(), function () use(&$dependencies) { $options = $this->em->createQuery('SELECT o FROM ' . Option::class . ' o')->getArrayResult(); if (empty($options)) { return null; } $options = ArrayHash::from(Arrays::associate($options, 'name=value')); $dependencies = [Cache::TAGS => Option::getCacheKey()]; return $options; }); return $options; }
public function updateSucceeded(Form $form) { $valuesForm = $form->getValues(true); $valuesHttp = $form->getHttpData(); if (!$valuesForm['photo']->isImage() && $valuesForm['photo']->isOK()) { $form->addError('Toto není obrázek'); return; } $valuesForm['underSubSection'] = (int) $valuesHttp['underSubSection']; $valuesForm['underSerial'] = (int) $valuesHttp['underSerial']; $values = Nette\Utils\ArrayHash::from($valuesForm); $this->articleManager->updateArticle($values); }
public function testData() { // Array $sender = $this->thePay->createSender(100); $data = ['customer' => 1]; $sender->setMerchantData($data); $this->assertSame($data, $sender->getMerchantData()); // String $sender->setMerchantData('data'); $this->assertSame('data', $sender->getMerchantData()); // Traversable $arrayAccess = \Nette\Utils\ArrayHash::from($data); $sender->setMerchantData($arrayAccess); $this->assertSame($data, $sender->getMerchantData()); }
public function formSucceeded(BaseForm $form, $values) { //return false; if ($values->password != $values->confirm_password) { $form->addError("Hesla se neshodují"); return; } $id = $this->userManager->add($values->email, $values->password); $contactId = $this->userManager->addContact(array('id' => $id, 'email' => $values->email)); $this->userManager->update(Nette\Utils\ArrayHash::from(array('id' => $id, 'contactId' => $contactId))); $template = $this->emailModel->getTemplate(\Natsu\Model\emailModel::REGISTER_CMPL); $template->body = $this->emailModel->replace(array("%EMAIL%" => $values->email, '%PASSWORD%' => $values->password), $template->body); $this->emailModel->sendEmail(\Natsu\Model\EmailModel::FROM, $values->email, $template); // print_r($values); exit; }
/** * Returns PayPal's cart items in Nette\ArrayHash or false if there are no items. * * @param $data Data from PayPal response * @return Nette\ArrayHash or boolean */ public function getCartItems() { $patternKeys = ''; $iterator = new CachingIterator($this->CART_ITEM_KEYS); for ($iterator->rewind(); $iterator->valid(); $iterator->next()) { if ($iterator->isFirst()) { $patternKeys .= '('; } $patternKeys .= $iterator->current(); if ($iterator->hasNext()) { $patternKeys .= '|'; } if ($iterator->isLast()) { $patternKeys .= ')'; } } $pattern = '/^' . $patternKeys . '[0-9]+$/'; $itemsData = Utils::array_keys_by_ereg($this->responseData, $pattern); $items = array(); $itemsCount = count($items); if (!empty($itemsData)) { $itemsCount = count($itemsData) / count($this->CART_ITEM_KEYS); } // We must control if the result of division is integer. // Because if not, it means the count of keys in PayPal cart item changed. assert(is_int($itemsCount)); for ($i = 0; $i < $itemsCount; ++$i) { $keys = array(); foreach ($this->CART_ITEM_KEYS as $key) { $keys[] = $key . $i; } if (Utils::array_keys_exist($itemsData, $keys)) { $items[] = array('name' => $itemsData['l_name' . $i], 'quantity' => $itemsData['l_qty' . $i], 'taxAmount' => $itemsData['l_taxamt' . $i], 'amount' => $itemsData['l_amt' . $i], 'description' => $itemsData['l_desc' . $i], 'weightValue' => $itemsData['l_itemweightvalue' . $i], 'lengthValue' => $itemsData['l_itemlengthvalue' . $i], 'widthValue' => $itemsData['l_itemwidthvalue' . $i], 'heightValue' => $itemsData['l_itemheightvalue' . $i]); } } return ArrayHash::from($items); }
/** * Make an API call. * * @param string|array $pathOrParams * @param string $method * @param array $params * @throws \Kdyby\Facebook\FacebookApiException * @return ArrayHash|bool|NULL The decoded response */ public function api($pathOrParams, $method = NULL, array $params = array()) { if (is_array($pathOrParams) && empty($this->config->graphVersion)) { $response = $this->apiClient->restServer($pathOrParams); // params } else { $response = $this->apiClient->graph($pathOrParams, $method, $params); } return !is_scalar($response) ? ArrayHash::from($response) : $response; }
/** * @param int $id * @throws ForbiddenRequestException */ public function actionEdit($id = 0) { $this->documentTemplate = ArrayHash::from(['name' => Random::generate(10), 'content' => Random::generate(100), 'id' => $id]); $this->template->documentTemplate = $this->documentTemplate; }
/** * @param bool $collectionKeys when field contains collection, return only array of PKs * @param bool $includeCollections * @param array $ignoreKeys * @return ArrayHash */ public function toArray($collectionKeys = TRUE, $includeCollections = TRUE, $ignoreKeys = []) { $ret = get_object_vars($this); $unset = []; if (method_exists($this, 'getId')) { $ret['id'] = $this->getId(); } foreach ($ret as $key => &$value) { if (in_array($key, $ignoreKeys)) { continue; } if ($value instanceof BaseEntity) { $value = $value->getId(); } elseif ($value instanceof PersistentCollection) { if ($includeCollections && $collectionKeys) { $keys = []; foreach ($value as $subEntity) { $keys[] = $subEntity->getId(); } $value = $keys; } else { $unset[] = $key; } } } if (!$includeCollections) { foreach ($unset as $key) { unset($ret[$key]); } } $ret = Common::unsetKeys($ret, $ignoreKeys); return ArrayHash::from($ret, FALSE); }
/** * @param array $params * @return NULL|ArrayHash */ public function getPermissions(array $params = array()) { $params = array_merge($params, array('access_token' => $this->facebook->getAccessToken())); try { $response = $this->facebook->api("/{$this->profileId}/permissions", 'GET', $params); if ($response && !empty($response->data)) { $items = array(); if (isset($response->data[0]['permission'])) { foreach ($response->data as $permissionsItem) { $items[$permissionsItem->permission] = $permissionsItem->status === 'granted'; } } elseif (isset($response->data[0])) { $items = (array) $response->data[0]; } return ArrayHash::from($items); } } catch (FacebookApiException $e) { return NULL; } }
public function handleAddNewAjaxSection($name = '', $underSection = '', $underSubSection = '') { if (!$name || !$underSection || !$underSubSection) { throw new Nette\Application\BadRequestException(); } if (!$this->user->isAllowed('Section', 'moderate')) { throw new \Nette\Application\ForbiddenRequestException(); } $form = $this->presenter->action; $id = $this->articleManager->addSerial(ArrayHash::from(['name' => $name, 'underSection' => $underSection, 'underSubSection' => $underSubSection, 'byUser' => $this->user->id, 'articleId' => $this->updateId])); if ($this->user->isAllowed(self::RES, 'moderate')) { $items = $this->articleManager->getSerialList($underSubSection); } else { $items = $this->articleManager->getSerialList($underSubSection, $this->user->getId()); } $this[$form]['underSerial']->setItems($items + [0 => 'Žádná'])->setValue($id); $this->redrawAjax(['underSerialSnippet', 'jsUpdate']); }
/** * Parses phpDoc comment. * @param string * @return array */ private static function parseComment($comment) { static $tokens = array('true' => TRUE, 'false' => FALSE, 'null' => NULL, '' => TRUE); $res = array(); $comment = preg_replace('#^\s*\*\s?#ms', '', trim($comment, '/*')); $parts = preg_split('#^\s*(?=@'.self::RE_IDENTIFIER.')#m', $comment, 2); $description = trim($parts[0]); if ($description !== '') { $res['description'] = array($description); } $matches = Strings::matchAll( isset($parts[1]) ? $parts[1] : '', '~ (?<=\s|^)@('.self::RE_IDENTIFIER.')[ \t]* ## annotation ( \((?>'.self::RE_STRING.'|[^\'")@]+)+\)| ## (value) [^(@\r\n][^@\r\n]*|) ## value ~xi' ); foreach ($matches as $match) { list(, $name, $value) = $match; if (substr($value, 0, 1) === '(') { $items = array(); $key = ''; $val = TRUE; $value[0] = ','; while ($m = Strings::match( $value, '#\s*,\s*(?>(' . self::RE_IDENTIFIER . ')\s*=\s*)?(' . self::RE_STRING . '|[^\'"),\s][^\'"),]*)#A') ) { $value = substr($value, strlen($m[0])); list(, $key, $val) = $m; $val = rtrim($val); if ($val[0] === "'" || $val[0] === '"') { $val = substr($val, 1, -1); } elseif (is_numeric($val)) { $val = 1 * $val; } else { $lval = strtolower($val); $val = array_key_exists($lval, $tokens) ? $tokens[$lval] : $val; } if ($key === '') { $items[] = $val; } else { $items[$key] = $val; } } $value = count($items) < 2 && $key === '' ? $val : $items; } else { $value = trim($value); if (is_numeric($value)) { $value = 1 * $value; } else { $lval = strtolower($value); $value = array_key_exists($lval, $tokens) ? $tokens[$lval] : $value; } } $res[$name][] = is_array($value) ? Nette\Utils\ArrayHash::from($value) : $value; } return $res; }
/** * @param string $address * @return ArrayHash|NULL */ public static function matchFullAddress($address) { if (!($m = Strings::match(trim($address), '~^' . self::RE_STREET . '\\s*' . self::RE_NUMBER . '?(?:\\,\\s?' . self::RE_POSTAL_CODE . '|\\,)(?:\\s?' . self::RE_CITY . ')\\,~i'))) { return NULL; } if (preg_match('~^[\\d\\s]{5,6}$~', $m['city']) && empty($m['postalCode'])) { // Brno 2, 602 00, Česká republika $m['postalCode'] = $m['city']; $m['city'] = $m['street']; unset($m['city_name']); } $m = self::normalizeNumber($m); return ArrayHash::from(['city' => !empty($m['city']) ? !empty($m['city_name']) ? $m['city_name'] : $m['city'] : NULL, 'street' => !empty($m['street']) ? $m['street'] : NULL, 'number' => !empty($m['number']) ? $m['number'] : NULL, 'on' => !empty($m['on']) ? $m['on'] : NULL, 'hn' => !empty($m['hn']) ? $m['hn'] : NULL, 'postalCode' => Strings::replace(trim(!empty($m['postalCode']) ? $m['postalCode'] : NULL), '#\\s#') ?: NULL, 'country' => self::matchCountry($address)]); }
public function thumbate(FileUpload $file, Thumb $thumb) { /** @var $image Image */ $image = $file->toImage(); $dimension = $thumb->getDimension(); // Resize to thumb dimension $image->resize($dimension->getWidth(), $dimension->getHeight(), $dimension->getFlag()); // Image name $imagename = $thumb->getImagename(); // File name $filename = $imagename . '.' . Utils::ext($file->name); // Gets properly directory $path = Utils::dirs($this->repository, $thumb->getPath(), $filename); // Store image data $this->images[] = ArrayHash::from(['path' => Utils::dirs($this->repository, $thumb->getPath()), 'fullpath' => $path, 'filename' => $filename, 'name' => $imagename, 'ext' => Utils::ext($file->name)]); // Save to file $image->save($path); }
/** * Load content and save file * * @param Entities\IFile[] $files * @param string $contentType * * @return Utils\ArrayHash */ public function generate(array $files, $contentType) { // Init vars $name = $this->getFilename($files); $hash = $this->getHash($files); $lastModified = $this->getLastModified($files); if ($this->cache->load($hash) === NULL) { $before = memory_get_peak_usage(); $content = $this->getContent($files); // Add compiled files into diagnostics panel if ($this->debugPanel) { $this->debugPanel->addFile($files, $hash, $this->type, $lastModified, memory_get_peak_usage() - $before); } $this->cache->save($hash, [Caching\AssetCache::CONTENT_TYPE => $contentType, Caching\AssetCache::CONTENT => $content], [Caching\AssetCache::TAGS => ['ipub.assetsloader', 'ipub.assetsloader.assets'], Caching\AssetCache::FILES => array_keys($files)]); } return Utils\ArrayHash::from(['file' => $name, 'hash' => $hash, 'lastModified' => $lastModified, 'sourceFiles' => $files]); }
public function formAdminSucceeded(BaseForm $form, $values) { // print_R($values); exit; $this->em->setTable("user"); $this->em->update(ArrayHash::from(array('id' => $values->userId, 'roleId' => $values->roleId, 'statusId' => $values->statusId))); $contact = $this->em->fetchWhere(array("id" => $values->userId)); $values->id = $contact[0]->contactId; unset($values->userId); unset($values->roleId); unset($values->statusId); $this->em->setTable("contact"); $this->em->update($values); }
public function publicNewWriter($id) { $data = $this->database->table('newWriter')->where('id', $id)->fetch(); if (!$data) { return null; } $updateData = ['title' => $data->title ? $data->title : 'Nenastavený titulek', 'text' => $data->text, 'description' => $data->aboutUser, 'keyWords' => '', 'photo' => '', 'commentsAllow' => 0, 'voteAllow' => 0, 'published' => 0, 'underSection' => null, 'underSubSection' => null, 'underSerial' => null]; if ($data->byUser) { $updateData['byUser'] = $data->byUser; $rId = $this->addArticle($data->byUser, \Nette\Utils\ArrayHash::from($updateData)); } else { $rId = $this->addArticle(null, \Nette\Utils\ArrayHash::from($updateData)); } $this->delNewWriter($id); return $rId; }
public function handleInsert() { $this->fooFacade->save(ArrayHash::from(['fooName' => 'Test insert'])); $this->redirect('default'); }
/** * {@inheritdoc} */ public function fillEntity(Utils\ArrayHash $values, Entities\IEntity $entity, $isNew = FALSE) { $classMetadata = $this->managerRegistry->getManagerForClass(get_class($entity))->getClassMetadata(get_class($entity)); foreach (array_merge($classMetadata->getFieldNames(), $classMetadata->getAssociationNames()) as $fieldName) { $propertyReflection = new Nette\Reflection\Property(get_class($entity), $fieldName); /** @var Doctrine\Mapping\Annotation\Crud $crud */ if ($crud = $this->annotationReader->getPropertyAnnotation($propertyReflection, self::EXTENSION_ANNOTATION)) { if ($isNew && $crud->isRequired() && !$values->offsetExists($fieldName)) { throw new Exceptions\InvalidStateException('Missing required key "' . $fieldName . '"'); } if (!$values->offsetExists($fieldName) || !$isNew && !$crud->isWritable() || $isNew && !$crud->isRequired()) { continue; } $value = $values->offsetGet($fieldName); if ($value instanceof Utils\ArrayHash || is_array($value)) { if (!$classMetadata->getFieldValue($entity, $fieldName) instanceof Entities\IEntity) { $propertyAnnotations = $this->annotationReader->getPropertyAnnotations($propertyReflection); $annotations = array_map(function ($annotation) { return get_class($annotation); }, $propertyAnnotations); if (in_array('Doctrine\\ORM\\Mapping\\OneToOne', $annotations, TRUE)) { $className = $this->annotationReader->getPropertyAnnotation($propertyReflection, 'Doctrine\\ORM\\Mapping\\OneToOne')->targetEntity; } elseif (in_array('Doctrine\\ORM\\Mapping\\ManyToOne', $annotations, TRUE)) { $className = $this->annotationReader->getPropertyAnnotation($propertyReflection, 'Doctrine\\ORM\\Mapping\\ManyToOne')->targetEntity; } else { $className = $propertyReflection->getAnnotation('var'); } // Check if class is callable if (class_exists($className)) { $classMetadata->setFieldValue($entity, $fieldName, new $className()); } else { $classMetadata->setFieldValue($entity, $fieldName, $value); } } // Check again if entity was created if (($fieldValue = $classMetadata->getFieldValue($entity, $fieldName)) && $fieldValue instanceof Entities\IEntity) { $classMetadata->setFieldValue($entity, $fieldName, $this->fillEntity(Utils\ArrayHash::from((array) $value), $fieldValue, $isNew)); } } else { if ($crud->validator !== NULL) { $value = $this->validateProperty($crud->validator, $value); } $classMetadata->setFieldValue($entity, $fieldName, $value); } } } return $entity; }
/** * Replaces or appends a item. * * @param mixed * @param mixed */ public function offsetSet($index, $value) { if ($index === null) { $this->data[] = is_array($value) ? ArrayHash::from($value, true) : $value; } else { $this->data[$index] = is_array($value) ? ArrayHash::from($value, true) : $value; } }
public function getParams($vars) { if ($vars == NULL || count($vars) == 0) { return ""; } else { $arr = []; foreach (ArrayHash::from($vars) as $key => $item) { if (is_numeric($key)) { $arr[] = "\${$item}"; } else { $arr[] = "\${$key} = " . $this->parseValue($item); } } return implode(', ', $arr); } }
<?php use Nette\Utils\ArrayHash; use Nette\Utils\Strings; $View = new ArrayHash(); $View->parameters = ArrayHash::from($App->parameters); define('THEME_DIR', dirname(__FILE__)); define('THEME_UTILS_DIR', THEME_DIR . '/utils'); define('ADMIN_UTILS_DIR', THEME_DIR . '/admin'); define('API_DIR', THEME_DIR . '/api'); define('FORMS_DIR', THEME_DIR . '/forms'); define('THEME_VIEWS_DIR', THEME_DIR . '/views'); define('NEON_WP_DIR', __DIR__ . '/define'); foreach (glob(THEME_UTILS_DIR . '/*.php') as $filename) { require_once $filename; } $Forms = new ArrayHash(); foreach (glob(FORMS_DIR . '/*.php') as $filename) { $Forms[basename($filename, '.php')] = (require_once $filename); } $View->Forms = $Forms; if (is_admin()) { foreach (glob(ADMIN_UTILS_DIR . '/*.php') as $filename) { require_once $filename; } } // CSRF protection $App->session->start(); if (Strings::startsWith($Url->pathInfo, 'api/')) { $ApiRequest = Strings::split(Strings::trim($Url->pathInfo, '~/+~'), '~/~'); array_shift($ApiRequest);
/** * Returns the global configuration. * @param string key * @param mixed default value * @return mixed */ public static function getConfig($key = NULL, $default = NULL) { $params = Nette\Utils\ArrayHash::from(self::getContext()->parameters); if (func_num_args()) { return isset($params[$key]) ? $params[$key] : $default; } else { return $params; } }
public function __construct(\Oli\GoogleAPI\IMapAPI $mapApi, \Oli\GoogleAPI\IMarkers $markers) { $this->map = $mapApi; $this->markers = $markers; $this->markersFromDb = Nette\Utils\ArrayHash::from($this->markersFromDb); }
/** * @param array $parameters */ public function __construct(array $parameters) { $this->parameters = ArrayHash::from($parameters); }
/** * @return Template */ private function buildTemplate() { if ($this->builtTemplate === NULL) { $options = $this->configuration->getOptions(); $template = new Template($this->latteEngine); $template->setParameters(['config' => ArrayHash::from($options), 'basePath' => $options[CO::TEMPLATE][TCO::TEMPLATES_PATH]]); $this->builtTemplate = $template; } return $this->templateElementsLoader->addElementsToTemplate($this->builtTemplate); }