/** * {@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; }
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 string $entityClass * @param string $key * @param null $column * @return StoredEntity|null * @throws NoReferenceException */ public function reference($entityClass, $key = null, $column = null) { if ($this->cachedReferences == null) { $this->cachedReferences = new ArrayHash(); } if ($this->isNewEntity()) { return null; } if ($key == null) { $columnToDiscoverReference = $entityClass; $reflectProperty = $this->getPropertyByColumnName($columnToDiscoverReference); if ($reflectProperty) { $entityClass = $this->getReferenceClassForProperty($reflectProperty); if (!$entityClass) { throw new NoReferenceException($columnToDiscoverReference); } $column = $columnToDiscoverReference; $key = $entityClass::getTableName($this->annotationReader); } } self::mustBeChildOf($entityClass, StoredEntity::class); if (!$this->cachedReferences->offsetExists($key)) { $reference = $entityClass::create($this, $this->row->getTable()->getReferencedTable($this->row, $key, $column)); $this->cachedReferences->offsetSet($key, $reference); } return $this->cachedReferences->offsetGet($key); }
/** * Checks if $key exists. * @param mixed key or index * @return bool */ public function offsetExists($key) { if (is_int($key)) { return (bool) current(array_slice((array) $this, $key, 1)); } return parent::offsetExists($key); }
public function offsetSet($key, $value) { if (!$value instanceof \UniMapper\Repository) { throw new \Exception("Repository must be instance of UniMapper\\Repository!"); } parent::offsetSet($value->getName(), $value); }
/** * @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); }
/** * @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 $this->getTable()->where(array('nazov' => $kluc))->update(array('text' => $data)); } /** Vrati vsetky dostupne udaje podla registracie * @param int $id_reg min. uroven registracie * @return \Nette\Database\Table\Selection */ public function vypisUdaje($id_reg = 0) { return $this->getTable()->where("id_registracia <= ?", $id_reg); } /** Funkcia vrati celociselnu hodnotu udaju s nazvom * @param string $nazov Nazov udaju * @return int */ public function getUdajInt($nazov = "") { $p = $this->findOneBy(array('nazov' => $nazov)); return $p !== FALSE ? (int) $p->text : 0; } /** Funkcia pre ulozenie udaju * @param Nette\Utils\ArrayHash $values
/** * @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 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; }
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()); }
/** * Create new entity from array or string which is JSON * @param string|array $data * @param bool $inverse * @throws \Nette\Utils\JsonException */ public function __construct($data = NULL, $inverse = false) { if ($data !== null) { if (is_string($data)) { $data = Json::decode($data); } $this->initMapping($inverse ? 'out' : 'in'); foreach ($data as $key => $value) { if ($value instanceof \stdClass) { $value = (array) $value; } $reflection = $this->getReflection(); if ($this->attributeNames->offsetExists($key)) { $propertyName = $this->attributeNames->offsetGet($key); if ($reflection->hasProperty($propertyName)) { $property = $reflection->getProperty($propertyName); $type = $property->getAnnotation('var'); if (Strings::endsWith($type, 'Entity')) { $classWithNamespace = sprintf("\\%s\\%s", $reflection->getNamespaceName(), (string) $type); if (is_array($value) && $property->hasAnnotation('collection')) { $arrayData = array(); foreach ($value as $valueData) { $arrayData[] = new $classWithNamespace($valueData, $inverse); } $this->{$propertyName} = $arrayData; } else { $this->{$propertyName} = new $classWithNamespace($value); } } else { $this->{$propertyName} = $value; } } } } } }
/** * 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); }
/** * @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); }
public function handleInsert() { $this->fooFacade->save(ArrayHash::from(['fooName' => 'Test insert'])); $this->redirect('default'); }
/** * 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); }
/** * @return array */ public function remoteList() { $command = $this->run([Remote::COMMAND_NAME, '-v']); $remotes = new ArrayHash(); foreach (explode("\n", $command->getOut()) as $remoteString) { if (empty($remoteString)) { continue; } $matches = Strings::match($remoteString, '~([a-z0-9]+)\\W(.+)\\W(push|fetch)~i'); if (count($matches) !== 4) { throw new InvalidStateException('Invalid remote: ' . $remoteString); } $name = $matches[1]; $url = $matches[2]; // $type = $matches[3]; if (!$remotes->offsetExists($name)) { $remote = new Remote($this, $name, $url); // var_dump($name); $remotes->{$name} = $remote; } // $remote->addType($type); } return $remotes; }
/** * @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 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); } }
/** * Zpracovani formulare s clankem * @param Form $form * @param Nette\Utils\ArrayHash $values */ public function formSucceeded(Form $form, $values) { //nastaveni datumu zverejneni if (empty($values->publishDate)) { $date = new DateTime(); } else { $date = DateTime::createFromFormat('d. m. Y, H:i', $values->publishDate); } $values->offsetSet('publishDate', $date); //novy clanek nebo jeho editace $result = empty($values->id) ? $this->newArticle($values) : $this->editArticle($values); if ($result) { $form->getPresenter()->flashMessage($form->getTranslator()->translate('system.requestS'), 'success'); } else { $form->getPresenter()->flashMessage($form->getTranslator()->translate('system.requestN'), 'danger'); } }
/** * 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; } }
/** * 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; } }
/** * 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; }
public function createEntry(ArrayHash $values, array $ids) { try { foreach ($ids as $id) { $values->offsetSet("owner", $id); $e = new MotivationEntry((array) $values); $e->setEditor($this->getUser()->getIdentity()); $this->entryService->createEntry($e); } } catch (Exceptions\DataErrorException $ex) { $this->handleDataLoad($values->id, "this", $ex); } $this->redirect("default"); }
/** * @param array $parameters */ public function __construct(array $parameters) { $this->parameters = ArrayHash::from($parameters); }
/** * @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; } }