예제 #1
0
 /**
  * {@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;
 }
예제 #2
0
 public function testToArray()
 {
     $array = array('asd');
     $iterator = \Nette\Utils\ArrayHash::from($array);
     $this->assertSame($array, Arrays::toArray($array));
     $this->assertSame($array, Arrays::toArray($iterator));
 }
예제 #3
0
 /**
  * @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);
 }
예제 #4
0
파일: Row.php 프로젝트: jave007/test
 /**
  * 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);
 }
예제 #5
0
 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);
 }
예제 #6
0
 /**
  * @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);
     }
 }
예제 #7
0
 /**
  * @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);
 }
예제 #8
0
 /**
  * @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;
 }
예제 #9
0
파일: Udaje.php 프로젝트: petak23/echo-msz
  {
      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
예제 #10
0
 /**
  * @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;
 }
예제 #11
0
 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);
 }
예제 #12
0
 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;
 }
예제 #13
0
 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());
 }
예제 #14
0
 /**
  * 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;
                     }
                 }
             }
         }
     }
 }
예제 #15
0
 /**
  * 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);
 }
예제 #16
0
 /**
  * @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);
 }
예제 #17
0
 public function handleInsert()
 {
     $this->fooFacade->save(ArrayHash::from(['fooName' => 'Test insert']));
     $this->redirect('default');
 }
예제 #18
0
파일: Facebook.php 프로젝트: kdyby/facebook
 /**
  * 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;
 }
예제 #19
0
 /**
  * @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;
 }
예제 #20
0
 /**
  * @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);
 }
예제 #21
0
파일: Repository.php 프로젝트: vhrb/git
 /**
  * @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;
 }
예제 #22
0
 /**
  * @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)]);
 }
예제 #23
0
 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);
     }
 }
예제 #24
0
 /**
  * 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');
     }
 }
예제 #25
0
 /**
  * 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;
     }
 }
예제 #26
0
 /**
  * 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;
     }
 }
예제 #27
0
	/**
	 * 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;
	}
예제 #28
0
 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");
 }
예제 #29
0
파일: Parameters.php 프로젝트: b4nan/utils
 /**
  * @param array $parameters
  */
 public function __construct(array $parameters)
 {
     $this->parameters = ArrayHash::from($parameters);
 }
예제 #30
0
 /**
  * @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;
     }
 }