protected function renderWithoutTpl(Collection $collection) { $result = []; foreach ($this->clients as $client) { $result[$client] = $collection->getClient($client)->getAuthorizationUrl(); } return Json::encode($result); }
/** * Formats response data in JSONP format. * * @param Response $response * @throws ResponseException */ protected function formatJsonp($response) { $response->getHeaders()->set('Content-Type', 'application/javascript; charset=UTF-8'); if (is_array($response->data) && isset($response->data['data'], $response->data['callback'])) { $response->content = sprintf('%s(%s);', $response->data['callback'], Json::encode($response->data['data'])); } else { $response->content = ''; throw new ResponseException("The 'jsonp' response requires that the data be an array consisting of both 'data' and 'callback' elements."); } }
/** * Parses a HTTP request body. * @param string $rawBody the raw HTTP request body. * @param string $contentType the content type specified for the request body. * @return array parameters parsed from the request body * @throws RequestException */ public function parse($rawBody, $contentType) { try { return Json::decode($rawBody, $this->asArray); } catch (\Exception $e) { if ($this->throwException) { throw new RequestException('Invalid JSON data in request body: ' . $e->getMessage(), [], $e); } return null; } }
/** * {@inheritdoc} */ public function getAttributes($code = null) { if (!isset($code)) { $code = Request::get('code'); } if (empty($code)) { return []; } // This was a callback request from google, get the token $this->service->requestAccessToken($code); // Send a request with it try { return Json::decode($this->service->request($this->apiUrl)); } catch (JsonException $e) { if (class_exists('\\rock\\log\\Log')) { Log::err(BaseException::convertExceptionToString($e)); } } return []; }
/** * Executes Mongo command. * * @param array $command command specification. * @param array $options options in format: "name" => "value" * @return array database response. * @throws MongoException on failure. */ public function executeCommand($command, array $options = []) { $rawQuery = $this->getName() . '.$cmd(' . Json::encode($command) . ', ' . Json::encode($options) . ')'; $token = ['query' => $rawQuery, 'valid' => true, 'cache' => false]; //Log::info($token, __METHOD__); Trace::beginProfile('mongodb.query', $token); try { $result = $this->mongoDb->command($command, $options); $this->tryResultError($result); Trace::endProfile('mongodb.query', $token); Trace::trace('mongodb.query', $token); return $result; } catch (\Exception $e) { $message = $e->getMessage() . "\nThe query being executed was: {$rawQuery}"; Trace::endProfile('mongodb.query', $token); $token['valid'] = false; $token['exception'] = defined('ROCK_DEBUG') && ROCK_DEBUG === true ? $e : $message; Trace::trace('mongodb.query', $token); throw new MongoException($message, [], 0, $e); } }
/** * Callback to replace variables template. * * @param array $matches array of variables template. * @throws TemplateException * @return string */ protected function replaceCallback($matches) { if (!empty($matches['beforeSkip']) && !empty($matches['afterSkip'])) { return trim($matches[0], '{!} '); } // check: count quotes does not parity if (!NumericHelper::isParity(mb_substr_count($matches[0], '`', 'UTF-8'))) { return $matches[0]; } $matches[0] = preg_replace_callback('/ \\s*(?P<sugar> (?!`)\\*(?!`) | (?!`)\\*\\*(?!`) | (?!`)\\/(?!`) | (?!`)\\%(?!`) | \\s+(?!`)mod(?!`)\\s+ | (?!`)\\+(?!`) | (?!`)\\-(?!`) | (?!`)\\|(?!`) | (?!`)\\&(?!`) | (?!`)\\^(?!`) | (?!`)\\>\\>(?!`) | (?!`)\\<\\<(?!`) | (?!`)\\|\\|(?!`) | (?!`)\\&\\&(?!`) | \\s+(?!`)' . $this->_getInlineConditionNames() . '(?!`)\\s+ |`\\s+\\?\\s+|`\\s+\\:\\s+)\\s*` /x', [$this, 'replaceSugar'], $matches[0]); // replace `=` tpl mnemonics $matches[0] = preg_replace('/`([\\!\\<\\>]?)[\\=]+`/', '`$1=`', $matches[0]); // replace `text` to ““text”” $matches[0] = preg_replace(['/=\\s*\\`/', '/\\`/'], ['=““', '””'], $matches[0]); // replacement of internal recursion on {{{...}}} $i = 0; $dataRecursive = []; $matches[0] = preg_replace_callback('/\\“\\“(?:[^\\“\\”]++|(?R))*\\”\\”/iu', function ($value) use(&$dataRecursive, &$i) { $key = '{{{' . $i . '}}}'; $value = current($value); $dataRecursive[$key] = $value; $i++; return $key; }, $matches[0]); // Search params is variable of template $params = $this->_searchParams($matches[0], $dataRecursive); // Search of filters (modifiers) $filters = $this->_searchFilters($matches[0], $dataRecursive); $matches['name'] = trim($matches['name']); $params = Serialize::unserializeRecursive($params); // returns cache list($cacheKey, $cacheExpire, $cacheTags) = $this->calculateCacheParams($params); if (($resultCache = $this->getCacheContent($cacheKey)) !== false) { return $resultCache; } $filters = Serialize::unserializeRecursive($filters); $sanitize = $this->sanitize; if (isset($params['sanitize'])) { $sanitize = $params['sanitize']; } elseif (!empty($matches['sanitizeDisable'])) { $sanitize = self::SANITIZE_DISABLE; } // chunk if ($matches['type'] === '$') { $result = $this->getChunk($matches['name'], $params); // alias } elseif ($matches['type'] === '@@') { $result = Alias::getAlias("@{$matches['name']}"); // placeholder } elseif ($matches['type'] === '+') { $result = $this->getPlaceholder($matches['name'], $sanitize); // constant } elseif ($matches['type'] === '++') { $result = $this->getConst($matches['name'], $sanitize); // extension } elseif ($matches['type'] === '#') { $result = $this->getExtension($matches['name'], $params, $sanitize); // i18n } elseif ($matches['type'] === '%') { $result = $this->_calculateI18N($matches['name'], Helper::getValue($params['placeholders'], []), Helper::getValue($params['locale']), Helper::getValue($params['category'])); // link } elseif ($matches['type'] === '~') { $result = $this->_calculateLink($matches['name'], $params); // snippet } elseif (empty($matches['type'])) { $result = $this->getSnippet($matches['name'], $params, $sanitize); } else { return $matches[0]; } // make a filter if (!empty($filters)) { $result = $this->makeFilter($result, $filters); } if ($this->autoSerialize) { if (is_array($result) || is_object($result) && !$result instanceof \Closure) { $result = @serialize($result); } } if (!is_scalar($result) && !empty($result)) { throw new TemplateException('Wrong type is var: ' . Json::encode($result)); } // sets a content to cache $this->setCacheContent($cacheKey, $result, $cacheExpire, $cacheTags ?: []); return $result; }
/** * Converting array to JSON-object. * * @param array $array current array * @return string */ public static function arrayToJson($array) { if (empty($array)) { return null; } return Json::encode($array) ?: null; }
/** * Returns the number of records. * * @param string $q kept to match {@see \rock\db\common\QueryInterface}, its value is ignored. * @param ConnectionInterface|Connection $connection the Mongo connection used to execute the query. * If this parameter is not given, the `mongodb` application component will be used. * @return integer number of records * @throws MongoException on failure. */ public function count($q = '*', ConnectionInterface $connection = null) { $cursor = $this->buildCursor($connection); $rawQuery = 'find(' . Json::encode($cursor->info()) . ')'; $token = ['query' => $rawQuery, 'valid' => true, 'cache' => false]; //Log::info($token, __METHOD__); Trace::beginProfile('mongodb.query', $token); $cache = $cacheKey = null; $lock = true; if (($result = $this->getCache($rawQuery, $token, null, null, $cache, $cacheKey, $lock)) !== false) { return $result; } if ($lock === false) { return 0; } try { $result = $cursor->count(); $this->setCache($result, $cache, $cacheKey); Trace::endProfile('mongodb.query', $token); Trace::trace('mongodb.query', $token); return $result; } catch (\Exception $e) { $message = $e->getMessage() . "\nThe query being executed was: {$rawQuery}"; Trace::endProfile('mongodb.query', $token); $token['valid'] = false; $token['exception'] = defined('ROCK_DEBUG') && ROCK_DEBUG === true ? $e : $message; Trace::trace('mongodb.query', $token); if (isset($cache, $cacheKey) && $cache instanceof CacheInterface) { $cache->unlock($cacheKey); } throw new MongoException($message, [], 0, $e); } }
/** * Render template. * * @return string|null */ protected function renderTpl() { if (empty($this->tpl)) { return Json::encode($this->array); } $i = 1; $result = ''; $countItems = count($this->array); $addPlaceholders = $this->template->findPlaceholders($this->addPlaceholders); $addPlaceholders['countItems'] = $countItems; $placeholders = []; foreach ($this->array as $placeholders) { if (is_array($placeholders)) { $placeholders['currentItem'] = $i; $this->prepareItem($placeholders); $result .= $this->template->replaceByPrefix($this->tpl, array_merge($placeholders, $addPlaceholders)); ++$i; continue; } $result .= $this->template->replaceByPrefix($this->tpl, array_merge($addPlaceholders, ['output' => $placeholders, 'currentItem' => $i])); ++$i; } // Deleting placeholders if (is_array($placeholders)) { $this->template->removeMultiPlaceholders(array_keys($placeholders)); } // Inserting content into wrapper template (optional) if (!empty($this->wrapperTpl)) { $result = $this->renderWrapperTpl($result, $addPlaceholders); } // Concat pagination if (empty($this->pagination['toPlaceholder'])) { $result .= $this->template->getPlaceholder('pagination', false); } // Deleting placeholders $this->template->removePlaceholder('pagination'); $this->template->removeMultiPlaceholders(array_keys($addPlaceholders)); // To placeholder if (!empty($this->toPlaceholder)) { $this->template->addPlaceholder($this->toPlaceholder, $result, true); $this->template->cachePlaceholders[$this->toPlaceholder] = $result; return null; } return $result; }
protected function renderErrors() { $result = ''; if ($this->enableClientValidation) { $tag = isset($this->ngErrorOptions['tag']) ? $this->ngErrorOptions['tag'] : 'div'; unset($this->ngErrorOptions['tag']); $formName = isset($this->formName) ? $this->formName . '[' . $this->attribute . ']' : $this->attribute; if ($this->ngErrorMessages) { if (is_array($this->ngErrorMessages)) { $this->ngErrorMessages = Json::encode($this->ngErrorMessages); } $this->ngErrorOptions['data']['ng-repeat'] = "(rule, errorMsg) in {$this->ngErrorMessages}"; $this->ngErrorOptions['data']['ng-show'] = 'showError("' . $formName . '", rule)'; $this->ngErrorOptions['data']['ng-bind'] = "errorMsg"; $result .= ActiveHtml::tag($tag, '', $this->ngErrorOptions) . "\n"; } $result .= ActiveHtml::tag($tag, '', ['class' => $this->ngErrorOptions['class'], 'data' => ['ng-show' => "!!bindError(\"{$this->attribute}\")", 'ng-bind' => "bindError(\"{$this->attribute}\")"]]) . "\n"; $this->errorOptions['data']['ng-hide'] = 'true'; } $result .= ActiveHtml::error($this->model, $this->attribute, $this->errorOptions); return $result; }
/** * Drop indexes for specified column(s). * @param string|array $collection name of the collection * @param string|array $columns column name or list of column names. */ public function dropIndex($collection, $columns) { echo " > drop index on " . $this->composeCollectionLogName($collection) . " (" . Json::encode((array) $columns) . ") ..."; $time = microtime(true); $this->connection->getCollection($collection)->dropIndex($columns); echo " done (time: " . sprintf('%.3f', microtime(true) - $time) . "s)\n"; }
/** * Returns the cache group name. * This allows {@see \rock\db\Schema::refresh()} to invalidate all cached table schemas. * @return string the cache group name */ protected function getCacheTag() { return md5(Json::encode([__CLASS__, $this->connection->dsn, $this->connection->username])); }
/** * Renders the HTML tag attributes. * * Attributes whose values are of boolean type will be treated as * [boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes). * * Attributes whose values are null will not be rendered. * * The values of attributes will be HTML-encoded using {@see \rock\template\Html::encode()}. * * The "data" attribute is specially handled when it is receiving an array value. In this case, * the array will be "expanded" and a list data attributes will be rendered. For example, * if `'data' => ['id' => 1, 'name' => 'rock']`, then this will be rendered: * `data-id="1" data-name="rock"`. * Additionally `'data' => ['params' => ['id' => 1, 'name' => 'rock'], 'status' => 'ok']` will be rendered as: * `data-params='{"id":1,"name":"rock"}' data-status="ok"`. * * @param array $attributes attributes to be rendered. * The attribute values will be HTML-encoded using {@see \rock\template\Html::encode()} . * @return string the rendering result. If the attributes are not empty, they will be rendered * into a string with a leading white space (so that it can be directly appended to the tag name * in a tag. If there is no attribute, an empty string will be returned. */ public static function renderTagAttributes($attributes) { unset($attributes['wrapperTpl']); if (count($attributes) > 1) { $sorted = []; foreach (static::$attributeOrder as $name) { if (isset($attributes[$name])) { $sorted[$name] = $attributes[$name]; } } $attributes = array_merge($sorted, $attributes); } $html = ''; foreach ($attributes as $name => $value) { if (is_bool($value)) { if ($value) { $html .= " {$name}"; } } elseif (is_array($value) && $name === 'data') { foreach ($value as $n => $v) { $v = static::normalizeClientOptions($n, $v); if (is_array($v)) { $html .= " {$name}-{$n}='" . Json::encode($v, JSON_HEX_APOS) . "'"; } else { $html .= " {$name}-{$n}=\"" . static::encode($v) . '"'; } } } elseif ($value !== null) { $html .= " {$name}=\"" . static::encode($value) . '"'; } } return $html; }
protected function serialize($value) { if (!is_array($value)) { return $value; } if ($this->serializer & self::SERIALIZE_JSON) { return Json::encode($value); } return $value; }