_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q244800 | Attribute.mutateValue | validation | protected function mutateValue($value, $dir = 'setter')
{
$mutator = $this->getMutator($value, $dir, $this->attributes['meta_type']);
if (method_exists($this, $mutator)) {
return $this->{$mutator}($value);
}
return static::$attributeMutator->mutate($value, $mutator);
} | php | {
"resource": ""
} |
q244801 | Attribute.getValueType | validation | protected function getValueType($value)
{
$type = is_object($value) ? get_class($value) : gettype($value);
// use float instead of deprecated double
return ($type == 'double') ? 'float' : $type;
} | php | {
"resource": ""
} |
q244802 | Attribute.getMutatedType | validation | protected function getMutatedType($value, $dir = 'setter')
{
foreach ($this->{"{$dir}Mutators"} as $mutated => $mutator) {
if ($this->getValueType($value) == $mutated || $value instanceof $mutated) {
return $mutated;
}
}
} | php | {
"resource": ""
} |
q244803 | Attribute.hasMutator | validation | protected function hasMutator($value, $dir = 'setter', $type = null)
{
return (bool) $this->getMutator($value, $dir, $type);
} | php | {
"resource": ""
} |
q244804 | Attribute.getMutator | validation | protected function getMutator($value, $dir = 'setter', $type = null)
{
$type = $type ?: $this->getValueType($value);
foreach ($this->{"{$dir}Mutators"} as $mutated => $mutator) {
if ($type == $mutated || $value instanceof $mutated) {
return $mutator;
}
}
} | php | {
"resource": ""
} |
q244805 | Attribute.castToString | validation | public function castToString()
{
if ($this->attributes['meta_type'] == 'array') {
return $this->attributes['meta_value'];
}
$value = $this->getValue();
if ($this->isStringable($value) || is_object($value) && method_exists($value, '__toString')) {
return (string) $value;
}
return '';
} | php | {
"resource": ""
} |
q244806 | Hooks.getAttribute | validation | public function getAttribute()
{
return function ($next, $value, $args) {
$key = $args->get('key');
if (is_null($value)) {
$value = $this->getMeta($key);
}
return $next($value, $args);
};
} | php | {
"resource": ""
} |
q244807 | Hooks.setAttribute | validation | public function setAttribute()
{
return function ($next, $value, $args) {
$key = $args->get('key');
if (!$this->hasColumn($key) && $this->allowsMeta($key) && !$this->hasSetMutator($key)) {
return $this->setMeta($key, $value);
}
return $next($value, $args);
};
} | php | {
"resource": ""
} |
q244808 | Hooks.toArray | validation | public function toArray()
{
return function ($next, $attributes) {
unset($attributes['meta_attributes'], $attributes['metaAttributes']);
$attributes = array_merge($attributes, $this->getMetaAttributesArray());
return $next($attributes);
};
} | php | {
"resource": ""
} |
q244809 | Hooks.replicate | validation | public function replicate()
{
return function ($next, $copy, $args) {
$metaAttributes = $args->get('original')
->getMetaAttributes()
->replicate($args->get('except'));
$copy->setRelation('metaAttributes', $metaAttributes);
return $next($copy, $args);
};
} | php | {
"resource": ""
} |
q244810 | Hooks.__issetHook | validation | public function __issetHook()
{
return function ($next, $isset, $args) {
$key = $args->get('key');
if (!$isset) {
$isset = (bool) $this->hasMeta($key);
}
return $next($isset, $args);
};
} | php | {
"resource": ""
} |
q244811 | Hooks.__unsetHook | validation | public function __unsetHook()
{
return function ($next, $value, $args) {
$key = $args->get('key');
if ($this->hasMeta($key)) {
return $this->setMeta($key, null);
}
return $next($value, $args);
};
} | php | {
"resource": ""
} |
q244812 | Hooks.queryHook | validation | public function queryHook()
{
return function ($next, $query, $bag) {
$method = $bag->get('method');
$args = $bag->get('args');
$column = $args->get('column');
if (!$this->hasColumn($column) && $this->allowsMeta($column) && $this->isMetaQueryable($method)) {
return call_user_func_array([$this, 'metaQuery'], [$query, $method, $args]);
}
if (in_array($method, ['select', 'addSelect'])) {
call_user_func_array([$this, 'metaSelect'], [$query, $args]);
}
return $next($query, $bag);
};
} | php | {
"resource": ""
} |
q244813 | AttributeBag.set | validation | public function set($key, $value = null, $group = null)
{
if ($key instanceof Attribute) {
return $this->setInstance($key);
}
if ($this->has($key)) {
$this->update($key, $value, $group);
} else {
$this->items[$key] = $this->newAttribute($key, $value, $group);
}
return $this;
} | php | {
"resource": ""
} |
q244814 | AttributeBag.setInstance | validation | protected function setInstance(Attribute $attribute)
{
if ($this->has($attribute->getMetaKey())) {
$this->update($attribute);
} else {
$this->items[$attribute->getMetaKey()] = $attribute;
}
return $this;
} | php | {
"resource": ""
} |
q244815 | AttributeBag.update | validation | protected function update($key, $value = null, $group = null)
{
if ($key instanceof Attribute) {
$value = $key->getValue();
$group = $key->getMetaGroup();
$key = $key->getMetaKey();
}
$this->get($key)->setValue($value);
$this->get($key)->setMetaGroup($group);
return $this;
} | php | {
"resource": ""
} |
q244816 | AttributeBag.forget | validation | public function forget($key)
{
if ($attribute = $this->get($key)) {
$attribute->setValue(null);
}
return $this;
} | php | {
"resource": ""
} |
q244817 | AttributeBag.replicate | validation | public function replicate($except = null)
{
$except = $except ? array_combine($except, $except) : [];
$attributes = [];
foreach (array_diff_key($this->items, $except) as $attribute) {
$attributes[] = $attribute->replicate();
}
return new static($attributes);
} | php | {
"resource": ""
} |
q244818 | Metable.metaQuery | validation | protected function metaQuery(Builder $query, $method, ArgumentBag $args)
{
if (in_array($method, ['pluck', 'value', 'aggregate', 'orderBy', 'lists'])) {
return $this->metaJoinQuery($query, $method, $args);
}
return $this->metaHasQuery($query, $method, $args);
} | php | {
"resource": ""
} |
q244819 | Metable.metaSelect | validation | protected function metaSelect(Builder $query, ArgumentBag $args)
{
$columns = $args->get('columns');
foreach ($columns as $key => $column) {
list($column, $alias) = $this->extractColumnAlias($column);
if ($this->hasColumn($column)) {
$select = "{$this->getTable()}.{$column}";
if ($column !== $alias) {
$select .= " as {$alias}";
}
$columns[$key] = $select;
} elseif (is_string($column) && $column != '*' && strpos($column, '.') === false) {
$table = $this->joinMeta($query, $column);
$columns[$key] = "{$table}.meta_value as {$alias}";
}
}
$args->set('columns', $columns);
} | php | {
"resource": ""
} |
q244820 | Metable.metaJoinQuery | validation | protected function metaJoinQuery(Builder $query, $method, ArgumentBag $args)
{
$alias = $this->joinMeta($query, $args->get('column'));
// For aggregates we need the actual function name
// so it can be called directly on the builder.
$method = $args->get('function') ?: $method;
return (in_array($method, ['orderBy', 'lists', 'pluck']))
? $this->{"{$method}Meta"}($query, $args, $alias)
: $this->metaSingleResult($query, $method, $alias);
} | php | {
"resource": ""
} |
q244821 | Metable.orderByMeta | validation | protected function orderByMeta(Builder $query, $args, $alias)
{
$query->with('metaAttributes')->getQuery()->orderBy("{$alias}.meta_value", $args->get('direction'));
return $query;
} | php | {
"resource": ""
} |
q244822 | Metable.pluckMeta | validation | protected function pluckMeta(Builder $query, ArgumentBag $args, $alias)
{
list($column, $key) = [$args->get('column'), $args->get('key')];
$query->select("{$alias}.meta_value as {$column}");
if (!is_null($key)) {
$this->metaSelectListsKey($query, $key);
}
return $query->callParent('pluck', $args->all());
} | php | {
"resource": ""
} |
q244823 | Metable.metaSelectListsKey | validation | protected function metaSelectListsKey(Builder $query, $key)
{
if (strpos($key, '.') !== false) {
return $query->addSelect($key);
} elseif ($this->hasColumn($key)) {
return $query->addSelect($this->getTable() . '.' . $key);
}
$alias = $this->joinMeta($query, $key);
return $query->addSelect("{$alias}.meta_value as {$key}");
} | php | {
"resource": ""
} |
q244824 | Metable.joinMeta | validation | protected function joinMeta(Builder $query, $column)
{
$query->prefixColumnsForJoin();
$alias = $this->generateMetaAlias();
$table = (new Attribute)->getTable();
$query->leftJoin("{$table} as {$alias}", function ($join) use ($alias, $column) {
$join->on("{$alias}.metable_id", '=', $this->getQualifiedKeyName())
->where("{$alias}.metable_type", '=', $this->getMorphClass())
->where("{$alias}.meta_key", '=', $column);
});
return $alias;
} | php | {
"resource": ""
} |
q244825 | Metable.metaHasQuery | validation | protected function metaHasQuery(Builder $query, $method, ArgumentBag $args)
{
$boolean = $this->getMetaBoolean($args);
$operator = $this->getMetaOperator($method, $args);
if (in_array($method, ['whereBetween', 'where'])) {
$this->unbindNumerics($args);
}
return $query
->has('metaAttributes', $operator, 1, $boolean, $this->getMetaWhereConstraint($method, $args))
->with('metaAttributes');
} | php | {
"resource": ""
} |
q244826 | Metable.getMetaOperator | validation | protected function getMetaOperator($method, ArgumentBag $args)
{
if ($not = $args->get('not')) {
$args->set('not', false);
}
return ($not ^ $this->isWhereNull($method, $args)) ? '<' : '>=';
} | php | {
"resource": ""
} |
q244827 | Metable.unbindNumerics | validation | protected function unbindNumerics(ArgumentBag $args)
{
if (($value = $args->get('value')) && (is_int($value) || is_float($value))) {
$args->set('value', $this->raw($value));
} elseif ($values = $args->get('values')) {
foreach ($values as $key => $value) {
if (is_int($value) || is_float($value)) {
$values[$key] = $this->raw($value);
}
}
$args->set('values', $values);
}
} | php | {
"resource": ""
} |
q244828 | Metable.getMetaWhereConstraint | validation | protected function getMetaWhereConstraint($method, ArgumentBag $args)
{
$column = $args->get('column');
$args->set('column', 'meta_value');
if ($method === 'whereBetween') {
return $this->getMetaBetweenConstraint($column, $args->get('values'));
}
return function ($query) use ($column, $method, $args) {
$query->where('meta_key', $column);
if ($args->get('value') || $args->get('values')) {
call_user_func_array([$query, $method], $args->all());
}
};
} | php | {
"resource": ""
} |
q244829 | Metable.getMetaBetweenConstraint | validation | protected function getMetaBetweenConstraint($column, array $values)
{
$min = $values[0];
$max = $values[1];
return function ($query) use ($column, $min, $max) {
$query->where('meta_key', $column)
->where('meta_value', '>=', $min)
->where('meta_value', '<=', $max);
};
} | php | {
"resource": ""
} |
q244830 | Metable.saveMeta | validation | protected function saveMeta()
{
foreach ($this->getMetaAttributes() as $attribute) {
if (is_null($attribute->getValue())) {
$attribute->delete();
} else {
$this->metaAttributes()->save($attribute);
}
}
} | php | {
"resource": ""
} |
q244831 | Metable.allowsMeta | validation | public function allowsMeta($key)
{
$allowed = $this->getAllowedMeta();
return empty($allowed) || in_array($key, $allowed);
} | php | {
"resource": ""
} |
q244832 | Metable.setMeta | validation | public function setMeta($key, $value, $group = null)
{
$this->getMetaAttributes()->set($key, $value, $group);
} | php | {
"resource": ""
} |
q244833 | Metable.loadMetaAttributes | validation | protected function loadMetaAttributes()
{
if (!array_key_exists('metaAttributes', $this->relations)) {
$this->reloadMetaAttributes();
}
$attributes = $this->getRelation('metaAttributes');
if (!$attributes instanceof AttributeBag) {
$this->setRelation('metaAttributes', (new Attribute)->newBag($attributes->all()));
}
} | php | {
"resource": ""
} |
q244834 | MacAddress.setFakeMacAddress | validation | public static function setFakeMacAddress($interface, $mac = null)
{
// if a valid mac address was not passed then generate one
if (!self::validateMacAddress($mac)) {
$mac = self::generateMacAddress();
}
// bring the interface down, set the new mac, bring it back up
self::runCommand("ifconfig {$interface} down");
self::runCommand("ifconfig {$interface} hw ether {$mac}");
self::runCommand("ifconfig {$interface} up");
// TODO: figure out if there is a better method of doing this
// run DHCP client to grab a new IP address
self::runCommand("dhclient {$interface}");
// run a test to see if the operation was a success
if (self::getCurrentMacAddress($interface) == $mac) {
return true;
}
// by default just return false
return false;
} | php | {
"resource": ""
} |
q244835 | MacAddress.getCurrentMacAddress | validation | public static function getCurrentMacAddress($interface)
{
$ifconfig = self::runCommand("ifconfig {$interface}");
preg_match("/" . self::$valid_mac . "/i", $ifconfig, $ifconfig);
if (isset($ifconfig[0])) {
return trim(strtoupper($ifconfig[0]));
}
return false;
} | php | {
"resource": ""
} |
q244836 | Sitemap.registerCpUrlRules | validation | public function registerCpUrlRules(RegisterUrlRulesEvent $event)
{
// only register CP URLs if the user is logged in
if (!\Craft::$app->user->identity)
return;
$rules = [
// register routes for the settings tab
'settings/sitemap' => [
'route'=>'sitemap/settings',
'params'=>['source' => 'CpSettings']],
'settings/sitemap/save-sitemap' => [
'route'=>'sitemap/settings/save-sitemap',
'params'=>['source' => 'CpSettings']],
];
$event->rules = array_merge($event->rules, $rules);
} | php | {
"resource": ""
} |
q244837 | Install.createTables | validation | protected function createTables()
{
$tablesCreated = false;
// sitemap_sitemaprecord table
$tableSchema = Craft::$app->db->schema->getTableSchema('{{%dolphiq_sitemap_entries}}');
if ($tableSchema === null) {
$tablesCreated = true;
$this->createTable(
'{{%dolphiq_sitemap_entries}}',
[
'id' => $this->primaryKey(),
'dateCreated' => $this->dateTime()->notNull(),
'dateUpdated' => $this->dateTime()->notNull(),
'uid' => $this->uid(),
// Custom columns in the table
'linkId' => $this->integer()->notNull(),
'type' => $this->string(30)->notNull()->defaultValue(''),
'priority' => $this->double(2)->notNull()->defaultValue(0.5),
'changefreq' => $this->string(30)->notNull()->defaultValue(''),
]
);
}
return $tablesCreated;
} | php | {
"resource": ""
} |
q244838 | Install.createIndexes | validation | protected function createIndexes()
{
// sitemap_sitemaprecord table
$this->createIndex(
$this->db->getIndexName(
'{{%dolphiq_sitemap_entries}}',
['type', 'linkId'],
true
),
'{{%dolphiq_sitemap_entries}}',
['type', 'linkId'],
true
);
// Additional commands depending on the db driver
switch ($this->driver) {
case DbConfig::DRIVER_MYSQL:
break;
case DbConfig::DRIVER_PGSQL:
break;
}
} | php | {
"resource": ""
} |
q244839 | HttpHandler.parserHttpRequest | validation | public function parserHttpRequest(HttpRequest $httpRequest)
{
$json = \json_decode($httpRequest->getContent(), true);
if (JSON_ERROR_NONE !== \json_last_error()) {
throw new Exceptions\ParseException();
}
/**
* Create new JsonRequest.
*
* @param array $json
*
* @return JsonRequest
*/
$createJsonRequest = function ($json) use ($httpRequest) {
$id = null;
$method = null;
$params = [];
if (\is_array($json)) {
$id = \array_key_exists('id', $json) ? $json['id'] : null;
$method = \array_key_exists('method', $json) ? $json['method'] : null;
$params = \array_key_exists('params', $json) ? $json['params'] : [];
}
$request = new JsonRequest($method, $params, $id);
$request->headers()->add($httpRequest->headers->all());
return $request;
};
// If batch request
if (\array_keys($json) === \range(0, \count($json) - 1)) {
$requests = [];
foreach ($json as $part) {
$requests[] = $createJsonRequest($part);
}
} else {
$requests = $createJsonRequest($json);
}
return $requests;
} | php | {
"resource": ""
} |
q244840 | HttpHandler.handleHttpRequest | validation | public function handleHttpRequest(HttpRequest $httpRequest)
{
// @var Event\HttpRequestEvent $event
$event = $this->dispatch(Event\HttpRequestEvent::EVENT, new Event\HttpRequestEvent($httpRequest));
$httpRequest = $event->getHttpRequest();
try {
$jsonRequests = $this->parserHttpRequest($httpRequest);
} catch (Exceptions\ParseException $e) {
return $this->createHttpResponseFromException($e);
}
$jsonResponses = $this->jsonHandler->handleJsonRequest($jsonRequests);
$httpResponse = HttpResponse::create();
if ($this->profiler) {
/**
* @param JsonResponse|JsonResponse[] $jsonResponse
*/
$collect = function ($jsonResponse) use (&$collect, $httpRequest, $httpResponse) {
if (\is_array($jsonResponse)) {
foreach ($jsonResponse as $value) {
$collect($value);
}
} else {
if ($jsonResponse->isError()) {
$this->collectException(
$httpRequest,
$httpResponse,
new Exceptions\ErrorException($jsonResponse->getErrorMessage(), $jsonResponse->getErrorCode(), $jsonResponse->getErrorData(), $jsonResponse->getId())
);
}
}
};
$collect($jsonResponses);
}
// Set httpResponse content.
if (\is_array($jsonResponses)) {
$results = [];
foreach ($jsonResponses as $jsonResponse) {
if ($jsonResponse->isError() || $jsonResponse->getId()) {
$results[] = $jsonResponse;
}
if ($jsonResponse->isError()) {
$httpResponse->setStatusCode($this->errorCode);
}
}
$httpResponse->setContent(\json_encode($results));
} else {
if ($jsonResponses->isError() || $jsonResponses->getId()) {
$httpResponse->setContent(\json_encode($jsonResponses));
}
if ($jsonResponses->isError()) {
$httpResponse->setStatusCode($this->errorCode);
}
}
// Set httpResponse headers
if (\is_array($jsonResponses)) {
foreach ($jsonResponses as $jsonResponse) {
if ($jsonResponse->isError() || $jsonResponse->getId()) {
$httpResponse->headers->add($jsonResponse->headers()->all());
}
}
} else {
$httpResponse->headers->add($jsonResponses->headers()->all());
}
$httpResponse->headers->set('Content-Type', 'application/json');
$this->dispatch(
Event\HttpResponseEvent::EVENT,
new Event\HttpResponseEvent($httpResponse)
);
return $httpResponse;
} | php | {
"resource": ""
} |
q244841 | HttpHandler.createHttpResponseFromException | validation | public function createHttpResponseFromException(\Exception $exception)
{
$httpResponse = HttpResponse::create();
$json = [];
$json['jsonrpc'] = '2.0';
$json['error'] = [];
if ($exception instanceof Exceptions\ErrorException) {
$json['error']['code'] = $exception->getCode();
$json['error']['message'] = $exception->getMessage();
if ($exception->getData()) {
$json['error']['data'] = $exception->getData();
}
$json['id'] = $exception->getId();
} else {
$json['error']['code'] = -32603;
$json['error']['message'] = 'Internal error';
$json['id'] = null;
}
$httpResponse->headers->set('Content-Type', 'application/json');
$httpResponse->setContent(\json_encode($json));
$httpResponse->setStatusCode($this->errorCode);
$this->dispatch(
Event\HttpResponseEvent::EVENT,
new Event\HttpResponseEvent($httpResponse)
);
return $httpResponse;
} | php | {
"resource": ""
} |
q244842 | HttpHandler.collectException | validation | private function collectException($httpRequest, $httpResponse, $exception)
{
if ($this->profiler) {
$collector = new ExceptionDataCollector();
$collector->collect($httpRequest, $httpResponse, $exception);
$this->profiler->add($collector);
}
} | php | {
"resource": ""
} |
q244843 | JsonHandler.isDebug | validation | public function isDebug()
{
if (null !== $this->container && $this->container->has('kernel')) {
return $this->container->get('kernel')->isDebug();
}
return true;
} | php | {
"resource": ""
} |
q244844 | JsonHandler.createJsonResponseFromException | validation | public function createJsonResponseFromException(\Exception $exception, JsonRequest $jsonRequest = null)
{
$jsonResponse = new JsonResponse();
if ($exception instanceof Exceptions\ErrorException) {
$jsonResponse->setErrorCode(0 !== $exception->getCode() ? $exception->getCode() : -32603);
$jsonResponse->setErrorMessage(!empty($exception->getMessage()) ? $exception->getMessage() : 'Internal error');
$jsonResponse->setErrorData($exception->getData());
} else {
$jsonResponse->setErrorCode(0 !== $exception->getCode() ? $exception->getCode() : -32603);
$jsonResponse->setErrorMessage(!empty($exception->getMessage()) ? $exception->getMessage() : 'Internal error');
}
if ($jsonRequest) {
$jsonResponse->setId($jsonRequest->getId());
}
return $jsonResponse;
} | php | {
"resource": ""
} |
q244845 | JsonHandler.handleJsonRequest | validation | public function handleJsonRequest($jsonRequest)
{
// Batch requests
if (\is_array($jsonRequest)) {
$jsonResponse = [];
foreach ($jsonRequest as $request) {
$jsonResponse[] = $this->handleJsonRequest($request);
}
return $jsonResponse;
}
if ($this->stopwatch) {
$this->stopwatch->start('rpc.execute');
}
try {
$this->dispatch(Event\JsonRequestEvent::EVENT, new Event\JsonRequestEvent($jsonRequest));
$metadata = $this->getMethod($jsonRequest);
$isCache = $this->isCacheSupport($jsonRequest);
$cacheId = $jsonRequest->getHash();
$jsonResponse = new JsonResponse($jsonRequest);
// Cache
if (true === $isCache && true === $this->getCache()->contains($cacheId)) {
$jsonResponse->setResult($this->getCache()->fetch($cacheId));
$isCache = false; // we don't want warm check without left ttl
}
$result = $jsonResponse->getResult();
if (null === $result) { // if not cache
$result = $this->executeJsonRequest($metadata, $jsonRequest);
}
if ($result instanceof JsonResponse) {
$jsonResponse = $result;
$jsonResponse->setRequest($jsonRequest);
} else {
$jsonResponse->setResult($this->serialize($result));
}
// Save cache
$isCache && $this->cache->save($cacheId, $jsonResponse->getResult(), $metadata->getCache());
$this->dispatch(Event\JsonResponseEvent::EVENT, new Event\JsonResponseEvent($jsonResponse));
} catch (\Exception $exception) {
$jsonResponse = $this->createJsonResponseFromException($exception, $jsonRequest);
}
if ($this->stopwatch) {
$this->stopwatch->stop('rpc.execute');
}
return $jsonResponse;
} | php | {
"resource": ""
} |
q244846 | JsonHandler.isCacheSupport | validation | private function isCacheSupport(JsonRequest $jsonRequest)
{
try {
return $jsonRequest->getId()
&& null !== $this->getMethod($jsonRequest)->getCache()
&& !$this->isDebug()
&& $this->getCache();
} catch (\Exception $e) {
return false;
}
} | php | {
"resource": ""
} |
q244847 | HttpHandlerRegistry.get | validation | public function get($name)
{
if (!isset($this->httpHandlers[$name])) {
throw new \Exception("HttpHandler {$name} not found");
}
return $this->httpHandlers[$name];
} | php | {
"resource": ""
} |
q244848 | Pgsql.getTableNames | validation | protected function getTableNames()
{
$schemas = DB::getConfig('used_schemas') ?: [DB::getConfig('schema')];
$schemaCount = count($schemas);
$binds = implode(',', array_fill(0, $schemaCount, '?'));
return collect(
DB::select("SELECT schemaname || '.' || tablename AS table FROM pg_catalog.pg_tables WHERE schemaname IN (".$binds.')', $schemas)
)->pluck('table')->reject(function ($value, $key) {
$tableName = explode('.', $value)[1];
return $tableName === 'spatial_ref_sys';
});
} | php | {
"resource": ""
} |
q244849 | Microsoft.getResourceOwnerDetailsUrl | validation | public function getResourceOwnerDetailsUrl(AccessToken $token)
{
$uri = new Uri($this->urlResourceOwnerDetails);
return (string) Uri::withQueryValue($uri, 'access_token', (string) $token);
} | php | {
"resource": ""
} |
q244850 | Nest.getUserLocations | validation | public function getUserLocations() {
$this->prepareForGet();
$structures = (array) $this->last_status->structure;
$user_structures = array();
$class_name = get_class($this);
$topaz = isset($this->last_status->topaz) ? $this->last_status->topaz : array();
foreach ($structures as $struct_id => $structure) {
// Nest Protects at this location (structure)
$protects = array();
foreach ($topaz as $protect) {
if ($protect->structure_id == $struct_id) {
$protects[] = $protect->serial_number;
}
}
$weather_data = $this->getWeather($structure->postal_code, $structure->country_code);
$user_structures[] = (object) array(
'name' => isset($structure->name)?$structure->name:'',
'address' => !empty($structure->street_address) ? $structure->street_address : NULL,
'city' => $structure->location,
'postal_code' => $structure->postal_code,
'country' => $structure->country_code,
'outside_temperature' => $weather_data->outside_temperature,
'outside_humidity' => $weather_data->outside_humidity,
'away' => $structure->away,
'away_last_changed' => date(DATETIME_FORMAT, $structure->away_timestamp),
'thermostats' => array_map(array($class_name, 'cleanDevices'), $structure->devices),
'protects' => $protects,
);
}
return $user_structures;
} | php | {
"resource": ""
} |
q244851 | Nest.getDeviceSchedule | validation | public function getDeviceSchedule($serial_number = NULL) {
$this->prepareForGet();
$serial_number = $this->getDefaultSerial($serial_number);
$schedule_days = $this->last_status->schedule->{$serial_number}->days;
$schedule = array();
foreach ((array)$schedule_days as $day => $scheduled_events) {
$events = array();
foreach ($scheduled_events as $scheduled_event) {
if ($scheduled_event->entry_type == 'setpoint') {
$events[(int)$scheduled_event->time] = (object) array(
'time' => $scheduled_event->time/60, // in minutes
'target_temperature' => $scheduled_event->type == 'RANGE' ? array($this->temperatureInUserScale((float)$scheduled_event->{'temp-min'}), $this->temperatureInUserScale((float)$scheduled_event->{'temp-max'})) : $this->temperatureInUserScale((float) $scheduled_event->temp),
'mode' => $scheduled_event->type == 'HEAT' ? TARGET_TEMP_MODE_HEAT : ($scheduled_event->type == 'COOL' ? TARGET_TEMP_MODE_COOL : TARGET_TEMP_MODE_RANGE)
);
}
}
if (!empty($events)) {
ksort($events);
$schedule[(int) $day] = array_values($events);
}
}
ksort($schedule);
$sorted_schedule = array();
foreach ($schedule as $day => $events) {
$sorted_schedule[$this->days_maps[(int) $day]] = $events;
}
return $sorted_schedule;
} | php | {
"resource": ""
} |
q244852 | Nest.getNextScheduledEvent | validation | public function getNextScheduledEvent($serial_number = NULL) {
$schedule = $this->getDeviceSchedule($serial_number);
$next_event = FALSE;
$time = date('H') * 60 + date('i');
for ($i = 0, $day = date('D'); $i++ < 7; $day = date('D', strtotime("+ $i days"))) {
if (isset($schedule[$day])) {
foreach ($schedule[$day] as $event) {
if ($event->time > $time) {
return $event;
}
}
}
$time = 0;
}
return $next_event;
} | php | {
"resource": ""
} |
q244853 | Nest.setTargetTemperatureMode | validation | public function setTargetTemperatureMode($mode, $temperature = NULL, $serial_number = NULL) {
$serial_number = $this->getDefaultSerial($serial_number);
if ($temperature !== NULL) {
if ($mode == TARGET_TEMP_MODE_RANGE) {
if (!is_array($temperature) || count($temperature) != 2 || !is_numeric($temperature[0]) || !is_numeric($temperature[1])) {
echo "Error: when using TARGET_TEMP_MODE_RANGE, you need to set the target temperatures (second argument of setTargetTemperatureMode) using an array of two numeric values.\n";
return FALSE;
}
$temp_low = $this->temperatureInCelsius($temperature[0], $serial_number);
$temp_high = $this->temperatureInCelsius($temperature[1], $serial_number);
$data = json_encode(array('target_change_pending' => TRUE, 'target_temperature_low' => $temp_low, 'target_temperature_high' => $temp_high));
$set_temp_result = $this->doPOST("/v2/put/shared." . $serial_number, $data);
} elseif ($mode != TARGET_TEMP_MODE_OFF) {
// heat or cool
if (!is_numeric($temperature)) {
echo "Error: when using TARGET_TEMP_MODE_HEAT or TARGET_TEMP_MODE_COLD, you need to set the target temperature (second argument of setTargetTemperatureMode) using an numeric value.\n";
return FALSE;
}
$temperature = $this->temperatureInCelsius($temperature, $serial_number);
$data = json_encode(array('target_change_pending' => TRUE, 'target_temperature' => $temperature));
$set_temp_result = $this->doPOST("/v2/put/shared." . $serial_number, $data);
}
}
$data = json_encode(array('target_change_pending' => TRUE, 'target_temperature_type' => $mode));
return $this->doPOST("/v2/put/shared." . $serial_number, $data);
} | php | {
"resource": ""
} |
q244854 | Nest.setTargetTemperature | validation | public function setTargetTemperature($temperature, $serial_number = NULL) {
$serial_number = $this->getDefaultSerial($serial_number);
$temperature = $this->temperatureInCelsius($temperature, $serial_number);
$data = json_encode(array('target_change_pending' => TRUE, 'target_temperature' => $temperature));
return $this->doPOST("/v2/put/shared." . $serial_number, $data);
} | php | {
"resource": ""
} |
q244855 | Nest.setTargetTemperatures | validation | public function setTargetTemperatures($temp_low, $temp_high, $serial_number = NULL) {
$serial_number = $this->getDefaultSerial($serial_number);
$temp_low = $this->temperatureInCelsius($temp_low, $serial_number);
$temp_high = $this->temperatureInCelsius($temp_high, $serial_number);
$data = json_encode(array('target_change_pending' => TRUE, 'target_temperature_low' => $temp_low, 'target_temperature_high' => $temp_high));
return $this->doPOST("/v2/put/shared." . $serial_number, $data);
} | php | {
"resource": ""
} |
q244856 | Nest.setEcoTemperatures | validation | public function setEcoTemperatures($temp_low, $temp_high, $serial_number = NULL) {
$serial_number = $this->getDefaultSerial($serial_number);
$temp_low = $this->temperatureInCelsius($temp_low, $serial_number);
$temp_high = $this->temperatureInCelsius($temp_high, $serial_number);
$data = array();
if ($temp_low === FALSE) {
$data['away_temperature_low_enabled'] = FALSE;
} elseif ($temp_low != NULL) {
$data['away_temperature_low_enabled'] = TRUE;
$data['away_temperature_low'] = $temp_low;
}
if ($temp_high === FALSE) {
$data['away_temperature_high_enabled'] = FALSE;
} elseif ($temp_high != NULL) {
$data['away_temperature_high_enabled'] = TRUE;
$data['away_temperature_high'] = $temp_high;
}
$data = json_encode($data);
return $this->doPOST("/v2/put/device." . $serial_number, $data);
} | php | {
"resource": ""
} |
q244857 | Nest.setFanMode | validation | public function setFanMode($mode, $serial_number = NULL) {
$duty_cycle = NULL;
$timer = NULL;
if (is_array($mode)) {
$modes = $mode;
$mode = $modes[0];
if (count($modes) > 1) {
if ($mode == FAN_MODE_MINUTES_PER_HOUR) {
$duty_cycle = (int) $modes[1];
} else {
$timer = (int) $modes[1];
}
} else {
throw new Exception("setFanMode(array \$mode[, ...]) needs at least a mode and a value in the \$mode array.");
}
} elseif (!is_string($mode)) {
throw new Exception("setFanMode() can only take a string or an array as it's first parameter.");
}
return $this->_setFanMode($mode, $duty_cycle, $timer, $serial_number);
} | php | {
"resource": ""
} |
q244858 | Nest.setFanModeMinutesPerHour | validation | public function setFanModeMinutesPerHour($mode, $serial_number = NULL) {
$modes = explode(',', $mode);
$mode = $modes[0];
$duty_cycle = $modes[1];
return $this->_setFanMode($mode, $duty_cycle, NULL, $serial_number);
} | php | {
"resource": ""
} |
q244859 | Nest.setFanModeOnWithTimer | validation | public function setFanModeOnWithTimer($mode, $serial_number = NULL) {
$modes = explode(',', $mode);
$mode = $modes[0];
$timer = (int) $modes[1];
return $this->_setFanMode($mode, NULL, $timer, $serial_number);
} | php | {
"resource": ""
} |
q244860 | Nest.cancelFanModeOnWithTimer | validation | public function cancelFanModeOnWithTimer($serial_number = NULL) {
$serial_number = $this->getDefaultSerial($serial_number);
$data = json_encode(array('fan_timer_timeout' => 0));
return $this->doPOST("/v2/put/device." . $serial_number, $data);
} | php | {
"resource": ""
} |
q244861 | Nest.setFanEveryDaySchedule | validation | public function setFanEveryDaySchedule($start_hour, $end_hour, $serial_number = NULL) {
$serial_number = $this->getDefaultSerial($serial_number);
$data = json_encode(array('fan_duty_start_time' => $start_hour*3600, 'fan_duty_end_time' => $end_hour*3600));
return $this->doPOST("/v2/put/device." . $serial_number, $data);
} | php | {
"resource": ""
} |
q244862 | Nest.useEcoTempWhenAway | validation | public function useEcoTempWhenAway($enabled, $serial_number = NULL) {
$serial_number = $this->getDefaultSerial($serial_number);
$data = json_encode(array('auto_away_enable' => $enabled));
return $this->doPOST("/v2/put/device." . $serial_number, $data);
} | php | {
"resource": ""
} |
q244863 | Nest.enableHumidifier | validation | public function enableHumidifier($enabled, $serial_number = NULL) {
$serial_number = $this->getDefaultSerial($serial_number);
$data = json_encode(array('target_humidity_enabled' => ((boolean)$enabled)));
return $this->doPOST("/v2/put/device." . $serial_number, $data);
} | php | {
"resource": ""
} |
q244864 | Nest.temperatureInCelsius | validation | public function temperatureInCelsius($temperature, $serial_number = NULL) {
$serial_number = $this->getDefaultSerial($serial_number);
$temp_scale = $this->getDeviceTemperatureScale($serial_number);
if ($temp_scale == 'F') {
return ($temperature - 32) / 1.8;
}
return $temperature;
} | php | {
"resource": ""
} |
q244865 | Nest.temperatureInUserScale | validation | public function temperatureInUserScale($temperature_in_celsius, $serial_number = NULL) {
$serial_number = $this->getDefaultSerial($serial_number);
$temp_scale = $this->getDeviceTemperatureScale($serial_number);
if ($temp_scale == 'F') {
return ($temperature_in_celsius * 1.8) + 32;
}
return $temperature_in_celsius;
} | php | {
"resource": ""
} |
q244866 | Nest.getDevices | validation | public function getDevices($type = DEVICE_TYPE_THERMOSTAT) {
$this->prepareForGet();
if ($type == DEVICE_TYPE_PROTECT) {
$protects = array();
$topaz = isset($this->last_status->topaz) ? $this->last_status->topaz : array();
foreach ($topaz as $protect) {
$protects[] = $protect->serial_number;
}
return $protects;
}
$devices_serials = array();
foreach ($this->last_status->user->{$this->userid}->structures as $structure) {
list(, $structure_id) = explode('.', $structure);
foreach ($this->last_status->structure->{$structure_id}->devices as $device) {
list(, $device_serial) = explode('.', $device);
$devices_serials[] = $device_serial;
}
}
return $devices_serials;
} | php | {
"resource": ""
} |
q244867 | Nest.getDefaultSerial | validation | protected function getDefaultSerial($serial_number) {
if (empty($serial_number)) {
$devices_serials = $this->getDevices();
if (count($devices_serials) == 0) {
$devices_serials = $this->getDevices(DEVICE_TYPE_PROTECT);
}
$serial_number = $devices_serials[0];
}
return $serial_number;
} | php | {
"resource": ""
} |
q244868 | Nest.getDeviceNetworkInfo | validation | protected function getDeviceNetworkInfo($serial_number = NULL) {
$this->prepareForGet();
$serial_number = $this->getDefaultSerial($serial_number);
$connection_info = $this->last_status->track->{$serial_number};
return (object) array(
'online' => $connection_info->online,
'last_connection' => date(DATETIME_FORMAT, $connection_info->last_connection/1000),
'last_connection_UTC' => gmdate(DATETIME_FORMAT, $connection_info->last_connection/1000),
'wan_ip' => @$connection_info->last_ip,
'local_ip' => $this->last_status->device->{$serial_number}->local_ip,
'mac_address' => $this->last_status->device->{$serial_number}->mac_address
);
} | php | {
"resource": ""
} |
q244869 | Nest.getCURLCerts | validation | protected static function getCURLCerts() {
$url = 'https://curl.haxx.se/ca/cacert.pem';
$certs = @file_get_contents($url);
if (!$certs) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE); // for security this should always be set to true.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // for security this should always be set to 2.
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] == 200) {
$certs = $response;
}
}
return $certs;
} | php | {
"resource": ""
} |
q244870 | Nest.secureTouch | validation | protected static function secureTouch($fname) {
if (file_exists($fname)) {
return;
}
$temp = tempnam(sys_get_temp_dir(), 'NEST');
rename($temp, $fname);
} | php | {
"resource": ""
} |
q244871 | TypeValidator.validateItems | validation | protected function validateItems(array $items, $type)
{
foreach ($items as $item) {
$this->validateItem($item, $type);
}
} | php | {
"resource": ""
} |
q244872 | ServerController.events | validation | public function events(Request $request): array
{
// 1 server event
// 2 swoole event
$type = (int)$request->query('type');
if ($type === 1) {
return ServerListenerCollector::getCollector();
}
if ($type === 2) {
return SwooleListenerCollector::getCollector();
}
return [
'server' => ServerListenerCollector::getCollector(),
'swoole' => SwooleListenerCollector::getCollector(),
];
} | php | {
"resource": ""
} |
q244873 | AppController.config | validation | public function config(Request $request)
{
if ($key = $request->query('key')) {
/** @see Config::get() */
return \config($key);
}
/** @see Config::toArray() */
return \bean('config')->toArray();
} | php | {
"resource": ""
} |
q244874 | AppController.pools | validation | public function pools(Request $request): array
{
if ($name = $request->query('name')) {
if (!App::hasPool($name)) {
return [];
}
/** @var PoolConfigInterface $poolConfig */
$poolConfig = App::getPool($name)->getPoolConfig();
return $poolConfig->toArray();
}
return PoolCollector::getCollector();
} | php | {
"resource": ""
} |
q244875 | AppController.events | validation | public function events(Request $request): array
{
/** @var \Swoft\Event\Manager\EventManager $em */
$em = \bean('eventManager');
if ($event = \trim($request->query('name'))) {
if (!$queue = $em->getListenerQueue($event)) {
return ['msg' => 'event name is invalid: ' . $event];
}
$classes = [];
foreach ($queue->getIterator() as $listener) {
$classes[] = \get_class($listener);
}
return $classes;
}
return $em->getListenedEvents();
} | php | {
"resource": ""
} |
q244876 | AppController.httpMiddles | validation | public function httpMiddles(Request $request): array
{
/** @var \Swoft\Http\Server\HttpDispatcher $dispatcher */
$dispatcher = \bean('serverDispatcher');
$middleType = (int)$request->query('type');
// 1: only return user's
if ($middleType === 1) {
return $dispatcher->getMiddlewares();
}
return $dispatcher->requestMiddleware();
} | php | {
"resource": ""
} |
q244877 | AppController.rpcMiddles | validation | public function rpcMiddles(Request $request): array
{
$beanName = 'serviceDispatcher';
if (!\Swoft::hasBean($beanName)) {
return [];
}
/** @var \Swoft\Rpc\Server\ServiceDispatcher $dispatcher */
$dispatcher = \bean($beanName);
$middleType = (int)$request->query('type');
// 1 only return user's
if ($middleType === 1) {
return $dispatcher->getMiddlewares();
}
return $dispatcher->requestMiddleware();
} | php | {
"resource": ""
} |
q244878 | AppCommand.initApp | validation | public function initApp(): void
{
$tmpDir = \Swoft::getAlias('@runtime');
$names = [
'logs',
'uploadfiles'
];
\output()->writeln('Create runtime directories: ' . \implode(',', $names));
foreach ($names as $name) {
DirHelper::make($tmpDir . '/' . $name);
}
\output()->writeln('<success>OK</success>');
} | php | {
"resource": ""
} |
q244879 | AppCommand.env | validation | public function env(Output $output): void
{
$info = [
// "<bold>System environment info</bold>\n",
'OS' => \PHP_OS,
'Php version' => \PHP_VERSION,
'Swoole version' => \SWOOLE_VERSION,
'Swoft version' => \Swoft::VERSION,
'App Name' => \config('name', 'unknown'),
'Base Path' => \BASE_PATH,
];
Show::aList($info, 'System Environment Info');
} | php | {
"resource": ""
} |
q244880 | AppCommand.check | validation | public function check(Output $output): void
{
// Env check
[$code, $return,] = Sys::run('php --ri swoole');
$asyncRdsEnabled = $code === 0 ? \strpos($return, 'redis client => enabled') : false;
$list = [
"<bold>Runtime environment check</bold>\n",
'PHP version is greater than 7.1?' => self::wrap(\PHP_VERSION_ID > 70100, 'current is ' .
\PHP_VERSION),
'Swoole extension is installed?' => self::wrap(\extension_loaded('swoole')),
'Swoole version is greater than 4.3?' => self::wrap(\version_compare(\SWOOLE_VERSION, '4.3.0', '>='),
'current is ' . \SWOOLE_VERSION),
'Swoole async redis is enabled?' => self::wrap($asyncRdsEnabled),
'Swoole coroutine is enabled?' => self::wrap(\class_exists('Swoole\Coroutine', false)),
"\n<bold>Extensions that conflict with 'swoole'</bold>\n",
// ' extensions' => 'installed',
' - zend' => self::wrap(!\extension_loaded('zend'),
'Please disabled it, otherwise swoole will be affected!', true),
' - xdebug' => self::wrap(!\extension_loaded('xdebug'),
'Please disabled it, otherwise swoole will be affected!', true),
' - xhprof' => self::wrap(!\extension_loaded('xhprof'),
'Please disabled it, otherwise swoole will be affected!', true),
' - blackfire' => self::wrap(!\extension_loaded('blackfire'),
'Please disabled it, otherwise swoole will be affected!', true),
];
$buffer = [];
$pass = $total = 0;
foreach ($list as $question => $value) {
if (\is_int($question)) {
$buffer[] = $value;
continue;
}
$total++;
if ($value[0]) {
$pass++;
}
$question = \str_pad($question, 45);
$buffer[] = \sprintf(' <comment>%s</comment> %s', $question, $value[1]);
}
$buffer[] = "\nCheck total: <bold>$total</bold>, Pass the check: <success>$pass</success>";
$output->writeln($buffer);
} | php | {
"resource": ""
} |
q244881 | Binput.all | validation | public function all(bool $trim = true, bool $clean = true)
{
$values = $this->request->all();
return $this->clean($values, $trim, $clean);
} | php | {
"resource": ""
} |
q244882 | Binput.get | validation | public function get(string $key, $default = null, bool $trim = true, bool $clean = true)
{
$value = $this->request->input($key, $default);
return $this->clean($value, $trim, $clean);
} | php | {
"resource": ""
} |
q244883 | Binput.only | validation | public function only($keys, bool $trim = true, bool $clean = true)
{
$values = [];
foreach ((array) $keys as $key) {
$values[$key] = $this->get($key, null, $trim, $clean);
}
return $values;
} | php | {
"resource": ""
} |
q244884 | Binput.except | validation | public function except($keys, bool $trim = true, bool $clean = true)
{
$values = $this->request->except((array) $keys);
return $this->clean($values, $trim, $clean);
} | php | {
"resource": ""
} |
q244885 | Binput.map | validation | public function map(array $keys, bool $trim = true, bool $clean = true)
{
$values = $this->only(array_keys($keys), $trim, $clean);
$new = [];
foreach ($keys as $key => $value) {
$new[$value] = array_get($values, $key);
}
return $new;
} | php | {
"resource": ""
} |
q244886 | Binput.old | validation | public function old(string $key, $default = null, bool $trim = true, bool $clean = true)
{
$value = $this->request->old($key, $default);
return $this->clean($value, $trim, $clean);
} | php | {
"resource": ""
} |
q244887 | Binput.clean | validation | public function clean($value, bool $trim = true, bool $clean = true)
{
if (is_bool($value) || is_int($value) || is_float($value)) {
return $value;
}
$final = null;
if ($value !== null) {
if (is_array($value)) {
$all = $value;
$final = [];
foreach ($all as $key => $value) {
if ($value !== null) {
$final[$key] = $this->clean($value, $trim, $clean);
}
}
} else {
if ($value !== null) {
$final = $this->process((string) $value, $trim, $clean);
}
}
}
return $final;
} | php | {
"resource": ""
} |
q244888 | Binput.process | validation | protected function process(string $value, bool $trim = true, bool $clean = true)
{
if ($trim) {
$value = trim($value);
}
if ($clean) {
$value = $this->security->clean($value);
}
return $value;
} | php | {
"resource": ""
} |
q244889 | BinputServiceProvider.registerBinput | validation | protected function registerBinput()
{
$this->app->singleton('binput', function (Container $app) {
$request = $app['request'];
$security = $app['security'];
$binput = new Binput($request, $security);
$app->refresh('request', $binput, 'setRequest');
return $binput;
});
$this->app->alias('binput', Binput::class);
} | php | {
"resource": ""
} |
q244890 | UtmCookie.get | validation | public static function get(?string $key = null)
{
self::init();
if ($key === null) {
return self::$utmCookie;
} else {
if (mb_strpos($key, 'utm_') !== 0) {
$key = 'utm_' . $key;
}
if (false === array_key_exists($key, self::$utmCookie)) {
throw new UnexpectedValueException(sprintf('Argument $key has unexpecte value "%s". Utm value with key "%s" does not exists.', $key, $key));
} else {
return self::$utmCookie[$key];
}
}
} | php | {
"resource": ""
} |
q244891 | Template.getTemplate | validation | protected function getTemplate($strTemplate, $strFormat = 'html5', $blnFailIfNotFound = false)
{
$strTemplate = basename($strTemplate);
$strCustom = 'templates';
// Check for a theme folder.
if (TL_MODE == 'FE') {
$tmpDir = str_replace('../', '', $GLOBALS['objPage']->templateGroup);
if (!empty($tmpDir)) {
$strCustom = $tmpDir;
}
}
try {
return \TemplateLoader::getPath($strTemplate, $strFormat, $strCustom);
} catch (\Exception $exception) {
if ($blnFailIfNotFound) {
throw new \RuntimeException(
sprintf('Could not find template %s.%s', $strTemplate, $strFormat),
1,
$exception
);
}
}
return null;
} | php | {
"resource": ""
} |
q244892 | Template.callParseTemplateHook | validation | protected function callParseTemplateHook()
{
if (isset($GLOBALS['METAMODEL_HOOKS']['parseTemplate'])
&& is_array($GLOBALS['METAMODEL_HOOKS']['parseTemplate'])
) {
foreach ($GLOBALS['METAMODEL_HOOKS']['parseTemplate'] as $callback) {
list($strClass, $strMethod) = $callback;
$objCallback = (in_array('getInstance', get_class_methods($strClass)))
? call_user_func(array($strClass, 'getInstance'))
: new $strClass();
$objCallback->$strMethod($this);
}
}
} | php | {
"resource": ""
} |
q244893 | Template.parse | validation | public function parse($strOutputFormat, $blnFailIfNotFound = false)
{
if ($this->strTemplate == '') {
return '';
}
// Set the format.
$this->strFormat = $strOutputFormat;
// HOOK: add custom parse filters.
$this->callParseTemplateHook();
$strBuffer = '';
// Start with the template itself
$this->strParent = $this->strTemplate;
// Include the parent templates
while ($this->strParent !== null) {
$strCurrent = $this->strParent;
$strParent = $this->strDefault
?: $this->getTemplate($this->strParent, $this->strFormat, $blnFailIfNotFound);
// Check if we have the template.
if (empty($strParent)) {
return sprintf(
'Template %s not found (it is maybe within a unreachable theme folder?).',
$this->strParent
);
}
// Reset the flags
$this->strParent = null;
$this->strDefault = null;
ob_start();
include($strParent);
// Capture the output of the root template
if ($this->strParent === null) {
$strBuffer = ob_get_contents();
} elseif ($this->strParent == $strCurrent) {
$this->strDefault = $this->getTemplate($this->strParent, $this->strFormat, $blnFailIfNotFound);
}
ob_end_clean();
}
// Reset the internal arrays
$this->arrBlocks = array();
// Add start and end markers in debug mode
if (\Config::get('debugMode') && in_array($this->strFormat, ['html5', 'xhtml'])) {
$strRelPath = str_replace(TL_ROOT . '/', '', $this->getTemplate($this->strTemplate, $this->strFormat));
$strBuffer = <<<EOF
<!-- TEMPLATE START: $strRelPath -->
$strBuffer
<!-- TEMPLATE END: $strRelPath -->
EOF;
}
return $strBuffer;
} | php | {
"resource": ""
} |
q244894 | Template.render | validation | public static function render($strTemplate, $strOutputFormat, $arrTplData, $blnFailIfNotFound = false)
{
$objTemplate = new self($strTemplate);
$objTemplate->setData($arrTplData);
return $objTemplate->parse($strOutputFormat, $blnFailIfNotFound);
} | php | {
"resource": ""
} |
q244895 | PurgeAssets.purge | validation | public function purge()
{
foreach ($GLOBALS['TL_PURGE']['folders']['metamodels_assets']['affected'] as $folderName) {
// Purge the folder
$folder = new \Folder($folderName);
$folder->purge();
}
/** @var EventDispatcherInterface $dispatcher */
$dispatcher = $GLOBALS['container']['event-dispatcher'];
$dispatcher->dispatch(
ContaoEvents::SYSTEM_LOG,
new LogEvent('Purged the MetaModels assets', __METHOD__, TL_CRON)
);
} | php | {
"resource": ""
} |
q244896 | ModelToLabelListener.getLabelText | validation | private function getLabelText($type)
{
$label = $this->translator->trans(
'tl_metamodel_dcasetting_condition.typedesc.' . $type,
[],
'contao_tl_metamodel_dcasetting_condition'
);
if ($label === 'tl_metamodel_dcasetting_condition.typedesc.' . $type) {
$label = $this->translator->trans(
'tl_metamodel_dcasetting_condition.typedesc._default_',
[],
'contao_tl_metamodel_dcasetting_condition'
);
if ($label === 'tl_metamodel_dcasetting_condition.typedesc._default_') {
return $type;
}
}
return $label;
} | php | {
"resource": ""
} |
q244897 | SubSystemBoot.boot | validation | public function boot()
{
/** @var Environment $environment */
$environment = System::getContainer()->get('contao.framework')->getAdapter(Environment::class);
$script = explode('?', $environment->get('relativeRequest'), 2)[0];
// There is no need to boot in login or install screen.
if (('contao/login' === $script) || ('contao/install' === $script)) {
return;
}
// Ensure all tables are created.
$connection = System::getContainer()->get('database_connection');
if (!$connection->getSchemaManager()->tablesExist(
[
'tl_metamodel',
'tl_metamodel_dca',
'tl_metamodel_dca_sortgroup',
'tl_metamodel_dcasetting',
'tl_metamodel_dcasetting_condition',
'tl_metamodel_attribute',
'tl_metamodel_filter',
'tl_metamodel_filtersetting',
'tl_metamodel_rendersettings',
'tl_metamodel_rendersetting',
'tl_metamodel_dca_combine',
]
)) {
System::getContainer()
->get('logger')
->error('MetaModels startup interrupted. Not all MetaModels tables have been created.');
return;
}
$event = new MetaModelsBootEvent();
$this->tryDispatch(MetaModelsEvents::SUBSYSTEM_BOOT, $event);
$determinator = System::getContainer()->get('cca.dc-general.scope-matcher');
switch (true) {
case $determinator->currentScopeIsFrontend():
$this->tryDispatch(MetaModelsEvents::SUBSYSTEM_BOOT_FRONTEND, $event);
break;
case $determinator->currentScopeIsBackend():
$this->tryDispatch(MetaModelsEvents::SUBSYSTEM_BOOT_BACKEND, $event);
break;
default:
}
} | php | {
"resource": ""
} |
q244898 | SubSystemBoot.tryDispatch | validation | private function tryDispatch($eventName, MetaModelsBootEvent $event)
{
$dispatcher = System::getContainer()->get('event_dispatcher');
if ($dispatcher->hasListeners($eventName)) {
// @codingStandardsIgnoreStart
@trigger_error('Event "' . $eventName . '" has been deprecated - Use registered services.', E_USER_DEPRECATED);
// @codingStandardsIgnoreEnd
$dispatcher->dispatch($eventName, $event);
}
} | php | {
"resource": ""
} |
q244899 | FixSortingListener.handle | validation | public function handle(EncodePropertyValueFromWidgetEvent $event)
{
if (('tl_metamodel_dca_combine' !== $event->getEnvironment()->getDataDefinition()->getName())
|| ('rows' !== $event->getProperty())) {
return;
}
$values = $event->getValue();
$index = 0;
$time = time();
foreach (array_keys($values) as $key) {
$values[$key]['sorting'] = $index;
$values[$key]['tstamp'] = $time;
$index += 128;
}
$event->setValue($values);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.