sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function trigger($event, $target = null, $params = null)
{
if (!$event instanceof Event) {
$event = new Event($event, $target, $params);
}
if (false !== strpos($event->getName(), ':')) {
$namespace = substr($event->getName(), 0, strpos($event->getName(), ':'));
if (isset($this->listeners[$namespace])) {
$this->fire($this->listeners[$namespace], $event);
}
}
if (isset($this->listeners[$event->getName()])) {
$this->fire($this->listeners[$event->getName()], $event);
}
return $event->getTarget();
} | Trigger event
@param string|Event $event
@param string|object $target
@param array|object $params
@return string|object
@throws EventException | entailment |
protected function fire($listeners, $event): void
{
ksort($listeners);
foreach ($listeners as $list) {
foreach ($list as $listener) {
$result = $listener($event);
if (null === $result) {
// continue;
} elseif (false === $result) {
break 2;
} else {
$event->setTarget($result);
}
}
}
} | Fire!
@param array $listeners
@param Event $event
@return void | entailment |
public function getOption($key, ...$keys)
{
$method = 'get' . Str::toCamelCase($key);
if (method_exists($this, $method)) {
return $this->$method($key, ...$keys);
}
return Collection::get($this->options, $key, ...$keys);
} | Get option by key
@param string $key
@param array $keys
@return mixed | entailment |
public function setOption($key, $value): void
{
$method = 'set' . Str::toCamelCase($key);
if (method_exists($this, $method)) {
$this->$method($value);
} else {
$this->options[$key] = $value;
}
} | Set option by key over setter
@param string $key
@param string $value
@return void | entailment |
public function setOptions(array $options = null): void
{
// store options by default
$this->options = (array)$options;
// apply options
foreach ($this->options as $key => $value) {
$this->setOption($key, $value);
}
} | Setup, check and init options
Requirements
- options must be a array
- options can be null
@param array $options
@return void | entailment |
public static function get(array $array, ...$keys)
{
$key = array_shift($keys);
if (!isset($array[$key])) {
return null;
}
if (empty($keys)) {
return $array[$key] ?? null;
}
if (!\is_array($array[$key])) {
return null;
}
return self::get($array[$key], ...$keys);
} | Get an element to array by key and sub-keys
@param array $array
@param array ...$keys
@return mixed|null | entailment |
public static function has(array $array, ...$keys): bool
{
$key = array_shift($keys);
if (!isset($array[$key])) {
return false;
}
if (empty($keys)) {
return isset($array[$key]);
}
if (!\is_array($array[$key])) {
return false;
}
return self::has($array[$key], ...$keys);
} | Check an element of array by key and sub-keys
@param array $array
@param array ...$keys
@return bool | entailment |
public static function set(array &$array, ...$keys): void
{
if (\count($keys) < 2) {
throw new \InvalidArgumentException('Method `Collection::set()` is required minimum one key and value');
}
$value = array_pop($keys);
while (\count($keys) > 1) {
$key = array_shift($keys);
if (!isset($array[$key]) || !\is_array($array[$key])) {
$array[$key] = [];
}
$array = &$array[$key];
}
$array[array_shift($keys)] = $value;
} | Set an element of array by key and sub-keys
@param array $array
@param array ...$keys
@return void
@throws \InvalidArgumentException | entailment |
public function open($savePath, $sessionName): bool
{
$this->prefix = $sessionName . ':';
$this->ttl = (int)ini_get('session.gc_maxlifetime');
// No more action necessary because connection is injected
// in constructor and arguments are not applicable.
return true;
} | Initialize session
@param string $savePath
@param string $sessionName
@return bool | entailment |
public function validate($input): bool
{
if (!\is_array($input)) {
return false;
}
$filtered = array_filter($input, $this->callback);
return \count($input) === \count($filtered);
} | Check input data
@param mixed $input
@return bool | entailment |
public function linkTo($key, $model, $foreign): void
{
Relations::setRelation($this->model, $key, $model, $foreign);
} | Setup relation "one to one" or "one to many"
@param string $key
@param string $model
@param string $foreign
@return void | entailment |
public function linkToMany($model, $link): void
{
Relations::setRelations($this->model, $model, [$link]);
} | Setup relation "many to many"
[table1-key] [table1_key-table2-table3_key] [table3-key]
@param string $model
@param string $link
@return void | entailment |
protected function filterData($data): array
{
if (empty($this->getFields())) {
return $data;
}
return array_intersect_key($data, array_flip($this->getFields()));
} | Filter input Fields
@param array $data Request
@return array | entailment |
protected function filterRow(RowInterface $row): RowInterface
{
if (empty($this->getFields())) {
return $row;
}
$fields = array_keys($row->toArray());
$toDelete = array_diff($fields, $this->getFields());
foreach ($toDelete as $field) {
unset($row->$field);
}
return $row;
} | Filter output Row
@param RowInterface $row from database
@return RowInterface | entailment |
public static function fromGlobals(
array $server = null,
array $query = null,
array $body = null,
array $cookies = null,
array $files = null
) : ServerRequest {
$request = parent::fromGlobals($server, $query, $body, $cookies, $files);
$contentType = current($request->getHeader('Content-Type'));
// support header like "application/json" and "application/json; charset=utf-8"
if (false !== $contentType && false !== stripos($contentType, Request::TYPE_JSON)) {
$input = file_get_contents('php://input');
$data = (array) json_decode($input);
} elseif ($request->getMethod() === RequestMethod::POST) {
$data = $_POST;
} else {
$input = file_get_contents('php://input');
parse_str($input, $data);
}
return $request->withParsedBody($body ?: $data);
} | {@inheritdoc} | entailment |
public static function exception($exception): void
{
self::getInstance()->error(
$exception->getMessage() . ' [' .
$exception->getFile() . ':' .
$exception->getLine() . ']'
);
} | exception
@param \Exception $exception
@return void | entailment |
public function create(): PHPMailer
{
// can initial, can't use
if (!class_exists(PHPMailer::class)) {
throw new ComponentException(
"PHPMailer library is required for `Bluz\\Mailer` package. <br/>\n" .
"Read more: <a href='https://github.com/bluzphp/framework/wiki/Mailer'>" .
"https://github.com/bluzphp/framework/wiki/Mailer</a>"
);
}
$mail = new PHPMailer();
$mail->WordWrap = 920; // RFC 2822 Compliant for Max 998 characters per line
$fromEmail = $this->getOption('from', 'email');
$fromName = $this->getOption('from', 'name') ?: '';
// setup options from config
$mail->setFrom($fromEmail, $fromName, false);
// setup options
if ($settings = $this->getOption('settings')) {
foreach ($settings as $name => $value) {
$mail->set($name, $value);
}
}
// setup custom headers
if ($headers = $this->getOption('headers')) {
foreach ($headers as $header => $value) {
$mail->addCustomHeader($header, $value);
}
}
return $mail;
} | Creates new instance of PHPMailer and set default options from config
@return PHPMailer
@throws ComponentException
@throws \PHPMailer\PHPMailer\Exception | entailment |
public function send(PHPMailer $mail)
{
if ($template = $this->getOption('subjectTemplate')) {
/** @var string $template */
$mail->Subject = Translator::translate($template, $mail->Subject);
}
if (!$mail->send()) {
// Why you don't use "Exception mode" of PHPMailer
// Because we need our Exception in any case
throw new MailerException('Error mail send: ' . $mail->ErrorInfo);
}
return true;
} | Send email
@todo Add mail to queue
@param PHPMailer $mail
@return bool
@throws MailerException
@throws \PHPMailer\PHPMailer\Exception | entailment |
public static function setRelation($modelOne, $keyOne, $modelTwo, $keyTwo): void
{
$relations = [$modelOne => $keyOne, $modelTwo => $keyTwo];
self::setRelations($modelOne, $modelTwo, $relations);
} | Setup relation between two models
@param string $modelOne
@param string $keyOne
@param string $modelTwo
@param string $keyTwo
@return void | entailment |
public static function setRelations($modelOne, $modelTwo, $relations): void
{
$name = [$modelOne, $modelTwo];
sort($name);
$name = implode(':', $name);
// create record in static variable
self::$relations[$name] = $relations;
} | Setup multi relations
@param string $modelOne
@param string $modelTwo
@param array $relations
@return void | entailment |
public static function getRelations($modelOne, $modelTwo)
{
$name = [$modelOne, $modelTwo];
sort($name);
$name = implode(':', $name);
return self::$relations[$name] ?? false;
} | Get relations
@param string $modelOne
@param string $modelTwo
@return array|false | entailment |
public static function findRelation($row, $relation): array
{
$model = $row->getTable()->getModel();
/** @var \Bluz\Db\Table $relationTable */
$relationTable = self::getModelClass($relation);
$relationTable::getInstance();
if (!$relations = self::getRelations($model, $relation)) {
throw new RelationNotFoundException(
"Relations between model `$model` and `$relation` is not defined"
);
}
// check many-to-many relations
if (\count($relations) === 1) {
$relations = self::getRelations($model, current($relations));
}
$field = $relations[$model];
$key = $row->{$field};
return self::findRelations($model, $relation, [$key]);
} | findRelation
@param Row $row
@param string $relation
@return array
@throws Exception\TableNotFoundException
@throws Exception\RelationNotFoundException | entailment |
public static function findRelations($modelOne, $modelTwo, $keys): array
{
$keys = (array)$keys;
if (!$relations = self::getRelations($modelOne, $modelTwo)) {
throw new RelationNotFoundException("Relations between model `$modelOne` and `$modelTwo` is not defined");
}
/* @var Table $tableOneClass name */
$tableOneClass = self::getModelClass($modelOne);
/* @var string $tableOneName */
$tableOneName = $tableOneClass::getInstance()->getName();
/* @var Table $tableTwoClass name */
$tableTwoClass = self::getModelClass($modelTwo);
/* @var string $tableTwoName */
$tableTwoName = $tableTwoClass::getInstance()->getName();
/* @var Query\Select $tableTwoSelect */
$tableTwoSelect = $tableTwoClass::getInstance()::select();
// check many to many relation
if (\is_int(\array_keys($relations)[0])) {
// many to many relation over third table
$modelThree = $relations[0];
// relations between target table and third table
$relations = self::getRelations($modelTwo, $modelThree);
/* @var Table $tableThreeClass name */
$tableThreeClass = self::getModelClass($modelThree);
/* @var string $tableTwoName */
$tableThreeName = $tableThreeClass::getInstance()->getName();
// join it to query
$tableTwoSelect->join(
$tableTwoName,
$tableThreeName,
$tableThreeName,
$tableTwoName . '.' . $relations[$modelTwo] . '=' . $tableThreeName . '.' . $relations[$modelThree]
);
// relations between source table and third table
$relations = self::getRelations($modelOne, $modelThree);
// join it to query
$tableTwoSelect->join(
$tableThreeName,
$tableOneName,
$tableOneName,
$tableThreeName . '.' . $relations[$modelThree] . '=' . $tableOneName . '.' . $relations[$modelOne]
);
// set source keys
$tableTwoSelect->where($tableOneName . '.' . $relations[$modelOne] . ' IN (?)', $keys);
} else {
// set source keys
$tableTwoSelect->where($relations[$modelTwo] . ' IN (?)', $keys);
}
return $tableTwoSelect->execute();
} | Find Relations between two tables
@param string $modelOne Table
@param string $modelTwo Target table
@param array $keys Keys from first table
@return array
@throws Exception\RelationNotFoundException | entailment |
public static function getModelClass($model): string
{
if (!isset(self::$modelClassMap[$model])) {
// try to detect
$className = '\\Application\\' . $model . '\\Table';
if (!class_exists($className)) {
throw new RelationNotFoundException("Related class for model `$model` not found");
}
self::$modelClassMap[$model] = $className;
}
return self::$modelClassMap[$model];
} | Get information about Model classes
@param string $model
@return string
@throws Exception\RelationNotFoundException | entailment |
public static function createRow($modelName, $data): RowInterface
{
$tableClass = self::getModelClass($modelName);
/* @var Table $tableClass name */
return $tableClass::getInstance()::create($data);
} | Get information about Table classes
@param string $modelName
@param array $data
@return RowInterface
@throws Exception\RelationNotFoundException | entailment |
public static function fetch($input): array
{
$output = [];
$map = [];
foreach ($input as $i => $row) {
$model = '';
foreach ($row as $key => $value) {
if (strpos($key, '__') === 0) {
$model = substr($key, 2);
continue;
}
$map[$i][$model][$key] = $value;
}
foreach ($map[$i] as $model => &$data) {
$data = self::createRow($model, $data);
}
$output[] = $map;
}
return $output;
} | Fetch by Divider
@param array $input
@return array
@throws Exception\RelationNotFoundException | entailment |
public function setContent($content): void
{
try {
$this->content = value($content);
} catch (\Exception $e) {
$this->content = $e->getMessage();
}
} | Set content
@param View|callable $content
@return void | entailment |
public function get(...$keys)
{
// configuration is missed
if (empty($this->container)) {
throw new ConfigException('System configuration is missing');
}
if (!\count($keys)) {
return $this->container;
}
return Collection::get($this->container, ...$keys);
} | Return configuration by key
@param array $keys
@return array|mixed
@throws ConfigException | entailment |
public function getClientId($clientId = null)
{
// Return given parameter
if ($clientId) {
return $clientId;
}
// If clientId is null and no clientId has previously been set
if (!$this->clientId) {
throw new RequestRequiresClientIdException();
}
// Return clientId that has previously been set
return $this->clientId;
} | Get clientId.
@param string clientId optional
@return string clientId | entailment |
public function sendRequest($type = 'GET', $path = '', $token = false, $options = [], $availableOptions = [])
{
/**
* TODO: $availableOptions is currently not being used, as it's
* just a limitation in case Twitch adds to, or makes changes to them.
* This variable can either be removed completed or used for something
* more useful, like telling developers what options they have.
*/
// URL parameters
//$path = $this->generateUrl($path, $token, $options, $availableOptions);
$path = $this->generateUrl($path, $token, $options, $availableOptions);
// Headers
$data = [
'headers' => [
'Client-ID' => $this->getClientId(),
'Accept' => 'application/vnd.twitchtv.v5+json',
],
];
// Twitch token
if ($token) {
$data['headers']['Authorization'] = 'OAuth '.$this->getToken($token);
}
try{
// Request object
$request = new Request($type, $path, $data);
// Send request
$response = $this->client->send($request);
// Return body in JSON data
return json_decode($response->getBody(), true);
}
catch(RequestException $e){
if ($e->hasResponse()) {
$exception = (string) $e->getResponse()->getBody();
$exception = json_decode($exception);
return $exception;
} else {
//503
return array(
'error' => 'Service Unavailable',
'status' => 503,
'message' => $e->getMessage()
);
}
}
} | Send request to Twitch API.
@param string $type Request type
@param string $path Request URL path
@param bool $token Twitch token
@param array $options URL queries
@param array $availableOptions Available URL queries
@return JSON JSON object from Twitch | entailment |
public function generateUrl($url, $token, $options, $availableOptions)
{
// Append client id
$url .= (parse_url($url, PHP_URL_QUERY) ? '&' : '?').'client_id='.$this->getClientId();
// Append token if provided
if ($token) {
$url .= (parse_url($url, PHP_URL_QUERY) ? '&' : '?').'oauth_token='.$this->getToken($token);
}
// Add options to the URL
foreach ($options as $key => $value) {
$url .= (parse_url($url, PHP_URL_QUERY) ? '&' : '?').$key.'='.$value;
}
return $url;
} | Generate URL with queries.
@param string $url Original URL
@param array $options Parameter values
@param array $availableOptions Parameters
@return string URL with queries | entailment |
public function channelsSubscriptions($channel, $options = [], $token = null)
{
$availableOptions = ['limit', 'offset', 'direction'];
return $this->sendRequest('GET', 'channels/'.$channel.'/subscriptions', $this->getToken($token), $options, $availableOptions);
} | List of channel subscribers.
@param string $channel Channel name
@param array $options Subscriber list options
@param string $token Twitch token
@return JSON List of subscribers | entailment |
public function channelSubscriptionUser($channel, $user, $token = null)
{
return $this->sendRequest('GET', 'channels/'.$channel.'/subscriptions/'.$user, $this->getToken($token));
} | Get subscription object of a single channel subscriber.
@param string $channel Channel name
@param string $user Username
@param string $token Twitch name
@return JSON A channel subscriber | entailment |
public function userSubscriptionChannel($channel, $user, $token = null)
{
return $this->sendRequest('GET', 'users/'.$user.'/subscriptions/'.$channel, $this->getToken($token));
} | Get user object of a single channel subscriber.
@param string $channel Channel name
@param string $user Username
@param string $token Twitch token
@return JSON User object | entailment |
public function getAuthenticationUrl($state = null, $forceVerify = false)
{
return 'https://api.twitch.tv/kraken/oauth2/authorize?response_type=code'
.'&client_id='.config('twitch-api.client_id')
.'&redirect_uri='.config('twitch-api.redirect_url')
.'&scope='.implode(config('twitch-api.scopes'), '+')
.'&state='.$state
.'&force_verify='.($forceVerify ? 'true' : 'false');
} | Get the Twitch OAuth url where the user signs in through Twitch.
@param string $state Will be appended to the redirect_uri to help avoid cross-stire scripting
@param bool $forceVerify Prompt user to confirm authorization, allowing users to switch accounts
@return string Authentication url | entailment |
public function getAccessToken($code, $state = null)
{
$response = $this->getAccessObject($code, $state);
return $response['access_token'];
} | Get access_token from Twitch.
@deprecated Use getAccessObject() instead
@param string $code code from redirect_uri
@param string $state optional state OAuth2 parameter to prevent cross-site scripting attacks
@return JSON JSON response object containing the access token | entailment |
public function getAccessObject($code, $state = null)
{
$availableOptions = ['client_secret', 'grant_type', 'state', 'code', 'redirect_uri'];
$options = [
'client_secret' => config('twitch-api.client_secret'),
'grant_type' => 'authorization_code',
'code' => $code,
'state' => $state,
'redirect_uri' => config('twitch-api.redirect_url'),
];
return $this->sendRequest('POST', 'oauth2/token', false, $options, $availableOptions);
} | Returns access_token, refresh_token and scope from Twitch.
@param string $code code from redirect_uri
@param string $state optional state OAuth2 parameter to prevent cross-site scripting attacks
@return JSON JSON response object from Twitch | entailment |
public function putChannel($channel, $rawOptions, $token = null)
{
$options = [];
foreach ($rawOptions as $key => $value) {
$options['channel['.$key.']'] = $value;
}
return $this->sendRequest('PUT', 'channels/'.$channel, $this->getToken($token), $options);
} | Update channel.
@param string $channel Channel name
@param array $options Channel options
@param string $token Twitch token
@return JSON Request result | entailment |
public function deleteStreamKey($channel, $token = null)
{
return $this->sendRequest('DELETE', 'channels/'.$channel.'/stream_key', $this->getToken($token));
} | Reset stream key.
@param string $channel Channel name
@param string $token Twitch token
@return JSON Request result with new stream key | entailment |
public function postCommercial($channel, $length = 30, $token = null)
{
$availableOptions = ['length'];
$options = ['length' => $length];
return $this->sendRequest('POST', 'channels/'.$channel.'/commercial', $this->getToken($token), $options, $availableOptions);
} | Run commercial.
@param string $channel Channel name
@param number $length Commercial length
@param string $token Twitch token
@return JSON Request result | entailment |
public function channelFollows($channel, $options = [])
{
$availableOptions = ['limit', 'offset', 'direction'];
return $this->sendRequest('GET', 'channels/'.$channel.'/follows', false, $options, $availableOptions);
} | Get channel's list of following users.
@param string $channel Channel name
@param array $options List options
@return JSON List of followers | entailment |
public function userFollowsChannels($user, $options = [])
{
$availableOptions = ['limit', 'offset', 'direction', 'sortby'];
return $this->sendRequest('GET', 'users/'.$user.'/follows/channels', false, $options, $availableOptions);
} | Get list of who the user is following.
@param string $user Username
@param array $options List options
@return JSON List of who the user is following | entailment |
public function authenticatedUserFollowsChannel($user, $channel, $options = [], $token = null)
{
$availableOptions = ['notifications'];
return $this->sendRequest('PUT', 'users/'.$user.'/follows/channels/'.$channel, $this->getToken($token), $options, $availableOptions);
} | Follow a channel.
@param string $user Username
@param string $channel Target channel's name
@param array $options Follow options
@param string $token Twitch token
@return JSON Request result | entailment |
public function authenticatedUserUnfollowsChannel($user, $channel, $token = null)
{
return $this->sendRequest('DELETE', 'users/'.$user.'/follows/channels/'.$channel, $this->getToken($token));
} | Unfollow a channel.
@param string $user Username
@param string $channel Target channel's name
@param string $token Twitch token
@return JSON Response result | entailment |
public function blocks($user, $token = null)
{
return $this->sendRequest('GET', 'users/'.$user.'/blocks', $this->getToken($token));
} | Get user's block list.
@param string $user Username
@param string $token Twitch token
@return JSON List of ignored users | entailment |
public function putBlock($user, $target, $token = null)
{
return $this->sendRequest('PUT', 'users/'.$user.'/blocks/'.$target, $this->getToken($token));
} | Add target to user's block list.
@param string $user Username
@param string $target Target's username
@param string $token Twitch token
@return JSON Request result | entailment |
public function deleteBlock($user, $target, $token = null)
{
return $this->sendRequest('DELETE', 'users/'.$user.'/blocks/'.$target, $this->getToken($token));
} | Delete target from user's block list.
@param string $user Username
@param string $target Target's username
@param string $token Twitch token
@return JSON Request result | entailment |
public function channelVideos($channel, $options = [])
{
$availableOptions = ['limit', 'offset', 'broadcasts', 'hls'];
return $this->sendRequest('GET', 'channels/'.$channel.'/videos', false, $options, $availableOptions);
} | Get list of video objects belonging to channel.
@param string $channel Channel name
@param array $options Video list options
@return JSON List of videos | entailment |
public function getAuthenticationUrl($state = null, $forceVerify = false)
{
$authentication = new Authentication();
return $authentication->getAuthenticationUrl($state, $forceVerify);
} | Authentication. | entailment |
public function ignoreList($user, $token = null)
{
$blocks = new Blocks($this->getToken($token));
return $blocks->blocks($user);
} | Blocks. | entailment |
public function subscribers($channel, $options = [], $token = null)
{
$subscriptions = new Subscriptions();
return $subscriptions->channelsSubscriptions($channel, $options, $this->getToken($token));
} | Subscriptions. | entailment |
public function init()
{
parent::init();
if ($this->owner->swatch) {
$this->addComponents(array('swatch' => $this->owner->swatch));
}
} | / }}} | entailment |
public function addButton($label = null, $options = array())
{
/** @type Button $but */
$but = $this->add('Button', $options);
$but->set($label);
if ($this->vertical) {
$but->js(true)->css('margin-top', '-3px');
}
return $but;
} | Add button to buttonset.
@param string $label Label of button
@param array $options Options to pass to button
@return Button | entailment |
public function addButton($label, $class = 'Button')
{
if (!$this->buttonset) {
$this->buttonset = $this->add('ButtonSet', null, 'grid_buttons')->setClass('atk-actions');
}
return $this->buttonset
->add($class, 'gbtn'.count($this->elements))
->set($label);
} | Adds button.
@param string|array $label label of button
@param string $class optional name of button class
@return Button | entailment |
public function addColumn($formatters, $name = null, $descr = null)
{
if ($name === null) {
$name = $formatters;
$formatters = 'text';
}
if ($formatters === null) {
$formatters = 'text';
}
if ($descr === null) {
$descr = ucwords(str_replace('_', ' ', $name));
}
if (is_array($descr)) {
$descr['descr'] = $this->app->_($descr['descr']);
} else {
$descr = $this->app->_($descr);
}
$this->columns[$name] = array('type' => $formatters);
if (is_array($descr)) {
$this->columns[$name] = array_merge($this->columns[$name], $descr);
} else {
$this->columns[$name]['descr'] = $descr;
}
if ($this->columns[$name]['icon']) {
if ($this->columns[$name]['icon'][0] != '<') {
$this->columns[$name]['icon'] = '<i class="icon-'.
$this->columns[$name]['icon'].'"></i> ';
} else {
throw $this->exception('obsolete way of using icon. Do not specify HTML code, but juts the icon');
}
}
$this->last_column = $name;
if (!is_string($formatters) && is_callable($formatters)) {
$this->columns[$name]['fx'] = $formatters;
return $this;
}
// TODO call addFormatter instead!
$subtypes = explode(',', $formatters);
foreach ($subtypes as $subtype) {
if (strpos($subtype, '\\') || strpos($subtype, '/')) {
// add-on functionality:
// http://agiletoolkit.org/codepad/gui/grid#codepad_gui_grid_view_example_7_ex
if (!$this->elements[$subtype.'_'.$name]) {
$addon = $this->app->normalizeClassName($subtype, 'Controller_Grid_Format');
$this->elements[$subtype.'_'.$name] = $this->add($addon);
}
$addon = $this->getElement($subtype.'_'.$name);
if (!$addon instanceof Controller_Grid_Format) {
throw $this->exception('Grid formatter class should extend Controller_Grid_Format class')
->addMoreInfo('formater', $subtype);
}
$addon->initField($name, $descr);
return $addon;
} elseif (!$this->hasMethod($m = 'init_'.$subtype)) {
if (!$this->hasMethod($m = 'format_'.$subtype)) {
// exception if formatter doesn't exist
throw $this->exception('No such formatter')
->addMoreInfo('formater', $subtype);
}
} else {
// execute formatter init_*
$this->$m($name, $descr);
}
}
return $this;
} | Add column to grid.
@param mixed $formatters
@param string $name
@param string|array $descr
@return $this|Controller_Grid_Format | entailment |
public function removeColumn($name)
{
unset($this->columns[$name]);
if ($this->last_column == $name) {
$this->last_column = null;
}
return $this;
} | Remove column from grid.
@param string $name
@return $this | entailment |
public function setFormatter($field, $formatter, $options = null)
{
// support for field names as array
if (is_array($field)) {
foreach ($field as $f) {
$this->setFormatter($f, $formatter, $options);
}
return $this;
}
if (!isset($this->columns[$field])) {
throw new BaseException('Cannot format nonexistant field '.$field);
}
$this->columns[$field]['type'] = '';
$this->addFormatter($field, $formatter, $options);
$this->last_column = $field;
return $this;
} | Replace current formatter for field.
@param string|array $field
@param mixed $formatter
@return $this | entailment |
public function addFormatter($field, $formatter, $options = null)
{
// support for field names as array
if (is_array($field)) {
foreach ($field as $f) {
$this->setFormatter($f, $formatter, $options);
}
return $this;
}
if (!isset($this->columns[$field])) {
throw new BaseException('Cannot format nonexistant field '.$field);
}
if ($formatter instanceof Closure) {
$m_name = uniqid();
$this->addMethod('format_'.$m_name, $formatter);
$formatter = $m_name;
}
if ($this->columns[$field]['type']) {
$this->columns[$field]['type'] .= ','.$formatter;
} else {
$this->columns[$field]['type'] = $formatter;
}
if ($options) {
$this->columns[$field] = array_merge($this->columns[$field], $options);
}
$descr = $this->columns[$field];
if (strpos($formatter, '\\') || strpos($formatter, '/')) {
// add-on functionality:
// http://agiletoolkit.org/codepad/gui/grid#codepad_gui_grid_view_example_7_ex
if (!$this->elements[$formatter.'_'.$field]) {
$addon = $this->app->normalizeClassName($formatter, 'Controller_Grid_Format');
$this->elements[$formatter.'_'.$field] = $this->add($addon, $formatter);
}
$addon = $this->getElement($formatter.'_'.$field);
if (!$addon instanceof Controller_Grid_Format) {
throw $this->exception('Grid formatter class should extend Controller_Grid_Format class')
->addMoreInfo('formater', $formatter);
}
$addon->initField($field, $descr);
return $addon;
} elseif ($this->hasMethod($m = 'init_'.$formatter)) {
// execute formatter
$this->$m($field, $descr);
}
return $this;
} | Add extra formatter to existing field.
@param string|array $field
@param mixed $formatter
@param array $options
@return $this || Controller_Grid_Format | entailment |
public function renderRows()
{
// precache template chunks
$this->precacheTemplate();
// extend CompleteLister renderRows method
parent::renderRows();
// if we have at least one data row rendered, then remove not_found message
if ($this->total_rows) {
$this->template->del('not_found');
} elseif ($this->no_records_message) {
$this->template->del('header');
$this->template->set('not_found_message', $this->no_records_message);
}
} | Render grid rows.
Extends renderRows method of CompleteLister | entailment |
public function precacheTemplate()
{
// Extract template chunks from grid template
// header
$header = $this->template->cloneRegion('header');
$header_col = $header->cloneRegion('col');
$header_sort = $header_col->cloneRegion('sort');
$header->del('cols');
// data row and column
$row = $this->row_t;
$col = $row->cloneRegion('col');
$row->setHTML('row_id', '{$id}');
$row->trySetHTML('odd_even', '{$odd_even}');
$row->del('cols');
// totals row and column
if ($t_row = $this->totals_t) {
$t_col = $t_row->cloneRegion('col');
$t_row->del('cols');
}
// Add requested columns to row templates
foreach ($this->columns as $name => $column) {
// header row
$header_col
->set('descr', $column['descr'])
->trySet('type', $column['type']);
// sorting
// TODO: rewrite this (and move into Advanced)
if (isset($column['sortable'])) {
$s = $column['sortable'];
$header_sort
->trySet('order', $s[0])
->trySet('sorticon', $this->sort_icons[$s[0]]);
$header_col
->trySet('sortid', $sel = $this->name.'_sort_'.$name)
->setHTML('sort', $header_sort->render());
$this->js('click', $this->js()->reload(array($this->name.'_sort' => $s[1])))
->_selector('#'.$sel);
} else {
$header_col
->del('sort')
->tryDel('sortid')
->tryDel('sort_del');
}
// add thparams for header columns
if ($column['thparam']) {
$header_col->trySetHTML('thparam', $column['thparam']);
} else {
$header_col->tryDel('thparam');
}
$header->appendHTML('cols', $header_col->render());
// data row
$col->del('content')
->setHTML('content', '{$'.$name.'}')
->setHTML('tdparam', '{tdparam_'.$name.'}style="white-space:nowrap"{/}');
$row->appendHTML('cols', $col->render());
// totals row
if (isset($t_row) && isset($t_col)) {
$t_col
->del('content')
->setHTML('content', '{$'.$name.'}')
->trySetHTML('tdparam', '{tdparam_'.$name.'}style="white-space:nowrap"{/}');
$t_row
->appendHTML('cols', $t_col->render());
}
}
// Generate templates from rendered strings
// header
$this->template->setHTML('header', $this->show_header ? $header->render() : '');
// data row
$this->row_t = $this->app->add('GiTemplate');
/** @type GiTemplate $this->row_t */
$this->row_t->loadTemplateFromString($row->render());
// totals row
if (isset($t_row) && $this->totals_t) {
$this->totals_t = $this->app->add('GiTemplate');
/** @type GiTemplate $this->totals_t */
$this->totals_t->loadTemplateFromString($t_row->render());
}
} | Precaches template chunks. | entailment |
public function formatRow()
{
// execute CompleteLister row formating
parent::formatRow();
if (empty($this->columns)) {
throw $this->exception('No columns defined for grid');
}
foreach ($this->columns as $field => $column) {
if ((is_array($this->current_row) || $this->current_row instanceof ArrayAccess)
&& array_key_exists($field, $this->current_row)
) {
$this->current_row[$field.'_original'] = $this->current_row[$field];
}
// if model field has listData structure, then get value instead of key
if ($this->model && $f = $this->model->hasElement($field)) {
$v = $this->current_row[$field];
if ($this->model instanceof \atk4\data\Model) {
/** @type \atk4\data\Field $f */
if (isset($f->enum) && $values = $f->enum) {
$this->current_row[$field] = isset($f->ui['valueList'][$v])
? $f->ui['valueList'][$v]
: $values[$v];
}
} else {
/** @type Field $f */
if ($f->type() !== 'boolean' && $values = $f->listData()) {
$this->current_row[$field] = $values[$v];
}
}
}
// process formatters
$this->executeFormatters($field, $column, 'format_');
// setting cell parameters (tdparam)
$this->applyTDParams($field);
}
} | Format grid row.
Extends formatRow method of CompleteLister | entailment |
public function executeFormatters($field, $column, $formatter_prefix = 'format_', $silent = false)
{
if (is_object($column['type']) && $column['type'] instanceof Closure) {
return $this->current_row[$field] = call_user_func($column['type'], $this->current);
}
$formatters = explode(',', $column['type']);
foreach ($formatters as $formatter) {
if (!$formatter) {
continue;
}
if ($this->hasMethod($m = $formatter_prefix.$formatter)) {
// formatter method is included in this class
$this->$m($field, $column);
} elseif (strpos($formatter, '\\') || strpos($formatter, '/')) {
// add-on support:
// http://agiletoolkit.org/codepad/gui/grid#codepad_gui_grid_view_example_7_ex
/** @type Controller_Grid_Format $c */
$c = $this->getElement($formatter.'_'.$field);
$c->formatField($field, $column);
} else {
if (!$silent) {
throw new BaseException('Grid does not know how to format type: '.$formatter);
}
}
}
} | Format field value using appropriate formatters.
@param string $field field name
@param array $column column configuration
@param string $formatter_prefix prefix of formatter methods
@param bool $silent don't throw exception if formatter not found | entailment |
public function allow($user, $pass = null)
{
// creates fictional model to allow specified user and password
// TODO: test this
if ($this->model) {
$this->model->table[] = array($this->login_field => $user, $this->password_field => $pass);
return $this;
}
/** @type Model $m */
$m = $this->add('Model');
$m->id_field = $this->login_field;
$m->setSource('Array', array(
is_array($user)
? $user
: array($this->login_field => $user, $this->password_field => $pass)
));
$this->setModel($m);
return $this;
} | Configure this Auth controller with a generic Model based on static
collection of user/password combinations. Use this method if you
only want one or few accounts to access the system.
@param string|array $user Either string username or associative array with data
@param string $pass Password if username is string
@return $this | entailment |
public function setModel($model, $login_field = null, $password_field = null)
{
parent::setModel($model);
// Set login field and password field or use default ones
if ($login_field !== null) {
$this->login_field = $login_field;
}
if ($password_field !== null) {
$this->password_field = $password_field;
}
// Load model from session
if ($this->info && $this->recall('id')) {
if ($this->recall('class', false) == get_class($this->model)) {
$this->debug('Loading model from cache');
if ($this->model instanceof \atk4\data\Model) {
$this->model->unload();
foreach ($this->info as $field => $value) {
$f = $this->model->hasElement($field);
if ($f && !$f->read_only) {
$f->set($value);
}
}
} else {
$this->model->set($this->info);
$this->model->dirty = array();
}
$this->model->id = $this->recall('id', null);
} else {
// Class changed, re-fetch data from database
$this->debug('Class changed, loading from database');
$this->model->tryLoad($this->recall('id'));
if (!$this->model->loaded()) {
$this->logout();
}
$this->memorizeModel();
}
}
$id = $this->hook('tryLogin', array($model, $login_field, $password_field));
if ($id && is_numeric($id)) {
$this->model->tryLoad($id);
$this->memorizeModel();
}
$t = $this;
// If model is saved, update our cache too, but don't store password
$this->model->addHook('afterSave', function ($m) use ($t) {
// after this model is saved, re-cache the info
$tmp = $m->get();
unset($tmp[$t->password_field]);
if ($t->app instanceof App_Web) {
$t->memorize('info', $tmp);
}
});
$this->addEncryptionHook($this->model);
if (strtolower($this->app->page) == 'logout') {
$this->logout();
$this->app->redirect('/');
}
return $this->model;
} | Associate model with authentication class. Username / password
check will be performed against the model in the following steps:
Model will attempt to load record where login_field matches
specified. Password is then loaded and verified using configured
encryption method.
@param string|object $model
@param string $login_field
@param string $password_field
@return Model | entailment |
public function addEncryptionHook($model)
{
// If model is saved, encrypt password
$t = $this;
if (isset($model->has_encryption_hook) && $model->has_encryption_hook) {
return;
}
$model->has_encryption_hook = true;
$model->addHook('beforeSave', function ($m) use ($t) {
if ($m->isDirty($t->password_field) && $m[$t->password_field]) {
$m[$t->password_field] = $t->encryptPassword($m[$t->password_field], $m[$t->login_field]);
}
});
} | Adds a hook to specified model which will encrypt password before save.
This method will be applied on $this->model, so you should not call
it manually. You can call it on a fresh model, however.
@param Model $model | entailment |
public function get($property = null, $default = null)
{
if (is_null($property)) {
return $this->info;
}
if (!isset($this->info[$property])) {
return $default;
}
return $this->info[$property];
} | Auth memorizes data about a logged-in user in session. You can either use this function to access
that data or $auth->model (preferred). $auth->get('username') will always point to the login field
value of the user regardless of how your field is named.
@param string $property
@param mixed $default
@return mixed | entailment |
public function allowPage($page)
{
if (is_array($page)) {
foreach ($page as $p) {
$this->allowPage($p);
}
return $this;
}
$this->allowed_pages[] = $page;
return $this;
} | Specify page or array of pages which will exclude authentication. Add your registration page here
or page containing terms and conditions.
@param string|array $page
@return $this | entailment |
public function isPageAllowed($page)
{
if ($this->hook('isPageAllowed', array($page)) === true) {
return true;
}
return in_array($page, $this->allowed_pages) || in_array(str_replace('_', '/', $page), $this->allowed_pages);
} | Verifies if the specified page is allowed to be accessed without
authentication.
@param string $page
@return bool | entailment |
public function encryptPassword($password, $salt = null)
{
if (!is_string($this->password_encryption) && is_callable($this->password_encryption)) {
$e = $this->password_encryption;
return $e($password, $salt);
}
if ($this->password_encryption) {
$this->debug("Encrypting password: '$password' with ".$this->password_encryption.' salt='.$salt);
}
switch ($this->password_encryption) {
case null:
return $password;
case 'php':
// returns false on failure
return password_hash($password, $this->hash_algo, $this->hash_options);
case 'sha256/salt':
if ($salt === null) {
throw $this->exception(
'sha256 requires salt (2nd argument to encryptPassword and is normaly an email)'
);
}
$key = $this->app->getConfig('auth/key', $this->app->name);
if ($this->password_encryption) {
$this->debug('Using key '.$key);
}
return hash_hmac('sha256', $password.$salt, $key);
case 'sha1':
return sha1($password);
case 'md5':
return md5($password);
case 'rot13':
return str_rot13($password);
default:
throw $this->exception('No such encryption method')
->addMoreInfo('encryption', $this->password_encryption);
}
} | Manually encrypt password
@param string $password
@param string $salt
@return string|bool Returns false on failure, encrypted string otherwise | entailment |
public function check()
{
if ($this->isPageAllowed($this->app->page)) {
return;
} // no authentication is required
// Check if user's session contains authentication information
if (!$this->isLoggedIn()) {
$this->memorizeURL();
// Brings up additional verification methods, such as cookie
// authentication, token or OpenID. In case of successful login,
// breakHook($user_id) must be used
$user_id = $this->hook('check');
if (!is_array($user_id) && !is_bool($user_id) && $user_id) {
$this->model->load($user_id);
//$this->loggedIn();
$this->memorizeModel();
return true;
}
$this->processLogin();
return true;
} else {
$this->debug('User is already authenticated');
}
} | Call this function to perform a check for logged in user. This will also display a login-form
and will verify user's credential. If you want to handle log-in form on your own, use
auth->isLoggedIn() to check and redirect user to a login page.
check() returns true if user have just logged in and will return "null" for requests when user
continues to use his session. Use that to perform some calculation on log-in
@return bool | entailment |
public function addInfo($key, $val = null)
{
if (is_array($key)) {
foreach ($key as $a => $b) {
$this->addInfo($a, $b);
}
return $this;
}
$this->debug("Gathered info: $key=$val");
$this->info[$key] = $val;
return $this;
} | Add additional info to be stored in user session.
@param string|array $key
@param mixed $val
@return $this | entailment |
public function verifyCredentials($user, $password)
{
$this->debug('verifying credentials for '.$user.' '.$password);
// First, perhaps model has a method for verifying credentials.
if ($this->model->hasMethod('verifyCredentials')) {
return $this->model->verifyCredentials($user, $password);
}
// If password field is not defined in the model for security
// reasons, let's add it for authentication purpose.
$password_existed = true;
if (!$this->model->hasElement($this->password_field)) {
$this->model->addField($this->password_field)->type('password');
$password_existed = false;
}
// Attempt to load user data by username. If not found, return false
/** @type Model $data User model */
$data = clone $this->model;
$data->tryLoadBy($this->login_field, $user);
if (!$data->loaded()) {
$this->debug('user with login '.$user.' could not be loaded');
if (!$password_existed) {
$data->getElement($this->password_field)->destroy();
}
return false;
}
$hash = $data[$this->password_field];
$this->debug('loaded user entry with hash: '.$hash);
// Verify password first
$result = false;
$rehash = false;
if ($this->password_encryption == 'php') {
// Get information about the hash
$info = password_get_info($hash);
// Backwards-compatibility with older ATK encryption methods
if ($info['algo'] == 0) {
// Determine type of hash by length
if (strlen($hash) == 64) {
$this->password_encryption = 'sha256/salt';
} elseif (strlen($hash) == 32) {
$this->password_encryption = 'md5';
} elseif (strlen($hash) == 40) {
$this->password_encryption = 'sha1';
} else {
$this->password_encryption = null;
$this->debug('Unable to identify password hash type, using plain-text matching');
/*
$this->password_encryption='php';
$data->unload();
if (!$password_existed) {
$data->getElement($this->password_field)->destroy();
}
return false;
*/
}
// Convert password hash
$this->debug('Old password found with algo='.$this->password_encryption);
$ep = $this->encryptPassword($password, $user);
$this->password_encryption = 'php';
$rehash = true;
$result = $hash == $ep;
} else {
$result = password_verify($password, $ep = $data[$this->password_field]);
$this->debug('Native password hash with info: '.json_encode($info));
$rehash = password_needs_rehash(
$hash,
$this->hash_algo,
$this->hash_options
);
}
if ($result) {
$this->debug('Verify is a SUCCESS');
if ($rehash) {
$hash = $data[$this->password_field] = $password;
$data->setDirty($this->password_field);
$data->save();
$this->debug('Rehashed into '.$data[$this->password_field]);
}
}
} else {
$ep = $this->encryptPassword($password, $user);
$result = $hash == $ep;
$this->debug('Attempting algo='.$this->password_encryption.' hash='.$hash.' newhash='.$ep);
}
if (!$result) {
$this->debug('Verify is a FAIL');
$data->unload();
if (!$password_existed) {
$data->getElement($this->password_field)->destroy();
}
return false;
}
// Leave record loaded, but hide password
$data[$this->password_field] = '';
$data->dirty[$this->password_field] = false;
return $data[$this->model->id_field];
} | This function verifies credibility of supplied authentication data.
It will search based on user and verify the password. It's also
possible that the function will re-hash user password with
updated hash.
if default authentication method is used, the function will
automatically determine hash used for password generation and will
upgrade to a new php5.5-compatible syntax.
This function return false OR the id of the record matching user.
@param string $user
@param string $password
@return mixed | entailment |
public function memorizeURL()
{
if ($this->app->page !== 'index' && !$this->recall('page', false)) {
$this->memorize('page', $this->app->page);
$g = $_GET;
unset($g['page']);
$this->memorize('args', $g);
}
} | Memorize current URL. Called when the first unsuccessful check is executed. | entailment |
public function getURL()
{
$p = $this->recall('page');
// If there is a login page, no need to return to it
if ($p == 'login') {
return $this->app->url('/');
}
$url = $this->app->url($p, $this->recall('args', null));
$this->forget('page');
$this->forget('args');
return $url;
} | Return originally requested URL.
@return string | entailment |
public function loggedIn($user = null, $pass = null)
{
if ($this->hook('loggedIn', array($user, $pass)) !== false) {
$this->app->redirect($this->getURL());
}
} | This function is always executed after successful login through a normal means (login form or plugin).
It will create cache model data.
@param string $user
@param string $pass | entailment |
public function memorizeModel()
{
if (!$this->model->loaded()) {
throw $this->exception('Authentication failure', 'AccessDenied');
}
// Don't store password in model / memory / session
$this->model['password'] = null;
unset($this->model->dirty['password']);
// Cache memory. Should we use controller?
$this->info = $this->model->get();
$this->info['username'] = $this->info[$this->login_field];
if ($this->app->hasMethod('initializeSession') || session_id()) {
$this->memorize('info', $this->info);
$this->memorize('class', get_class($this->model));
$this->memorize('id', $this->model->id);
}
$this->hook('login');
} | Store model in session data so that it can be retrieved faster. | entailment |
public function loginBy($field, $value)
{
$this->model->tryLoadBy($field, $value);
$this->memorizeModel();
return $this;
} | Manually Log in with specified condition.
@param string $field
@param mixed $value
@return $this | entailment |
public function login($user)
{
if (is_object($user)) {
if (!$this->model) {
throw $this->exception('Auth Model should be set');
}
$c = get_class($this->model);
if (!$user instanceof $c) {
throw $this->exception('Specified model with incompatible class')
->addMoreInfo('required', $c)
->addMoreInfo('supplied', get_class($user));
}
$this->model = $user;
$this->memorizeModel();
return $this;
}
return $this->loginBy($this->login_field, $user);
} | Manually Log in as specified users by using login name.
@param string $user
@return $this | entailment |
public function logout()
{
$this->hook('logout');
$this->model->unload();
// maybe can use $this->app->destroySession() here instead?
$this->forget('info');
$this->forget('id');
setcookie(session_name(), '', time() - 42000, '/');
if (session_status() === PHP_SESSION_ACTIVE) {
session_destroy();
}
$this->info = false;
return $this;
} | Manually log out user.
@return $this | entailment |
public function createForm($page)
{
/** @type Form $form */
$form = $page->add('Form', null, null, array('form/minimal'));
/** @type Field $email */
$email = $this->model->hasElement($this->login_field);
/** @type Field $password */
$password = $this->model->hasElement($this->password_field);
// set captions
if ($this->model instanceof \atk4\data\Model) {
$email = $email && isset($email->caption) ? $email->caption : 'E-mail';
$password = $password && isset($password->caption) ? $password->caption : 'Password';
} else {
$email = $email ? $email->caption() : 'E-mail';
$password = $password ? $password->caption() : 'Password';
}
$form->addField('Line', 'username', $email);
$form->addField('Password', 'password', $password);
$form->addSubmit('Login')->addClass('atk-jackscrew')->addClass('atk-swatch-green');
return $form;
} | Creates log-in form.
Override if you want to use your own form. If you need to change template used by a log-in form,
add template/default/page/login.html.
@param Page $page
@return Form | entailment |
public function showLoginForm()
{
$this->app->template->trySet('page_title', 'Login');
if ($this->app->layout && $this->login_layout_class) {
$this->app->layout->destroy();
$this->app->add($this->login_layout_class);
/** @type Page $p */
$p = $this->app->layout->add('Page', null, null, array('page/login'));
} else {
/** @type Page $p */
$p = $this->app->add('Page', null, null, array('page/login'));
}
$this->app->page_object = $p;
// hook: createForm use this to build basic login form
$this->form = $this->hook('createForm', array($p))[0];
// If no hook, build standard form
if (!is_object($this->form)) {
$this->form = $this->createForm($p);
}
$this->hook('updateForm');
$f = $this->form;
if ($f->isSubmitted()) {
$id = $this->verifyCredentials($f->get('username'), $f->get('password'));
if ($id) {
$this->loginByID($id);
$this->loggedIn($f->get('username'), $f->get('password'));
exit;
}
$f->getElement('password')->displayFieldError('Incorrect login information');
}
return $p;
} | Do not override this function.
@return Page | entailment |
public function processLogin()
{
$this->memorizeURL();
$this->app->template->tryDel('Menu');
$this->showLoginForm();
$this->app->hook('post-init');
$this->app->hook('pre-exec');
if (isset($_GET['submit']) && $_POST) {
$this->app->hook('submitted');
}
$this->app->hook('post-submit');
$this->app->execute();
exit;
} | Do not override this function. | entailment |
public function setModel($model, $actual_fields = null)
{
parent::setModel($model);
if ($this->model instanceof \atk4\data\Model) {
// Switch to Agile Data implementation
if (isset($this->default_controller)) {
$this->default_controller = str_replace('MVC', 'AD', $this->default_controller);
} else {
$this->default_controller = 'ADView';
}
}
// Some models will want default controller to be associated
if (isset($this->model->default_controller)) {
$this->controller
= $this->model->setController($this->model->default_controller);
}
// Use our default controller if present
if ($this->default_controller) {
$this->controller = $this->setController($this->default_controller);
}
if ($this->controller) {
if ($this->controller->hasMethod('setActualFields')) {
$this->controller->setActualFields($actual_fields);
}
if ($this->controller->hasMethod('_bindView')) {
$this->controller->_bindView();
}
}
if ($this->model instanceof SQL_Model) {
$this->dq = $this->model->_dsql(); // compatibility
}
$this->hook('set-model', [$this->model, $actual_fields]);
return $this->model;
} | Associate view with a model. Additionally may initialize a controller
which would copy fields from the model into the View.
@param object|string $model Class without "Model_" prefix or object
@param array|string|null $actual_fields List of fields in order to populate
@return AbstractModel object | entailment |
public function getHTML($destroy = true, $execute_js = true)
{
$this->addHook('output', array($this, '_tsBuffer'));
$this->recursiveRender();
$this->removeHook('output', array($this, '_tsBuffer'));
$ret = $this->_tsBuffer;
$this->_tsBuffer = '';
if ($execute_js && isset($this->app->jquery)) {
/** @type App_Web $this->app */
$this->app->jquery->getJS($this);
}
if ($destroy) {
$this->destroy();
}
return $ret;
} | Converting View into string will render recursively and produce HTML.
If argument is passed, JavaScript will be added into on_ready section
of your document like when rendered normally. Note that you might
require to destroy object if you don't want it's HTML to appear normally.
@param bool $destroy Destroy object preventing it from rendering
@param bool $execute_js Also capture JavaScript chains of object
@return string HTML | entailment |
public function initializeTemplate($template_spot = null, $template_branch = null)
{
if ($template_spot === null) {
$template_spot = $this->defaultSpot();
}
$this->spot = $template_spot;
if (@$this->owner->template
&& !$this->owner->template->is_set($this->spot)
) {
throw $this->owner->template->exception(
'Spot is not found in owner\'s template'
)->addMoreInfo('spot', $this->spot);
}
if (!isset($template_branch)) {
$template_branch = $this->defaultTemplate();
}
if (isset($template_branch)) {
// template branch would tell us what kind of template we have to
// use. Let's look at several cases:
if (is_object($template_branch)) {
// it might be already template instance (object)
$this->template = $template_branch;
} elseif (is_array($template_branch)) {
// it might be array with [0]=template, [1]=tag
if (is_object($template_branch[0])) {
// if [0] is object, we'll use that
$this->template = $template_branch[0];
} else {
$this->template = $this->app->add('Template');
/** @type Template $this->template */
$this->template->loadTemplate($template_branch[0]);
}
// Now that we loaded it, let's see which tag we need to cut out
$this->template = $this->template->cloneRegion(
isset($template_branch[1]) ? $template_branch[1] : '_top'
);
} else {
// brach could be just a string - a region to clone off parent
if (isset($this->owner->template)) {
$this->template
= $this->owner->template->cloneRegion($template_branch);
} else {
$this->template = $this->add('Template');
}
}
/** @type Template $this->template */
$this->template->owner = $this;
}
// Now that the template is loaded, let's take care of parent's template
if ($this->owner
&& (isset($this->owner->template))
&& (!empty($this->owner->template))
) {
$this->owner->template->del($this->spot);
}
// Cool, now let's set _name of this template
if ($this->template) {
$this->template->trySet('_name', $this->getJSID());
}
} | Called automatically during init for template initalization.
@param string $template_spot Where object's output goes
@param string|array $template_branch Where objects gets it's template
@return AbstractView $this
@internal | entailment |
public function initTemplateTags()
{
if ($this->template
&& $this->app->hasMethod('setTags')
) {
/** @type App_Web $this->app */
$this->app->setTags($this->template);
}
} | This method is called to automatically fill in some of the tags in this
view. Normally the call is bassed to $app->setTags(), however you can
extend and add more tags to fill. | entailment |
public function recursiveRender()
{
if ($this->hook('pre-recursive-render')) {
return;
}
$cutting_here = false;
$cutting_output = '';
$this->initTemplateTags();
if (isset($_GET['cut_object'])
&& ($_GET['cut_object'] == $this->name
|| $_GET['cut_object'] == $this->short_name)
) {
// If we are cutting here, render childs and then we are done
unset($_GET['cut_object']);
$cutting_here = true;
$this->addHook('output', function ($self, $output) use (&$cutting_output) {
$cutting_output .= $output;
});
}
if ($this->model
&& is_object($this->model)
&& $this->model->loaded()
) {
$this->modelRender();
}
foreach ($this->elements as $key => $obj) {
if ($obj instanceof self) {
$obj->recursiveRender();
$obj->moveJStoParent();
}
}
if (!isset($_GET['cut_object'])) {
if (isset($_GET['cut_region'])) {
$this->region_render();
} else {
$this->render();
}
}
if ($cutting_here) {
//$result=$this->owner->template->cloneRegion($this->spot)->render();
if (isset($this->app->jquery)) {
/** @type App_Web $this->app */
$this->app->jquery->getJS($this);
}
throw new Exception_StopRender($cutting_output);
}
// if template wasn't cut, we move all JS chains to parent
} | Recursively renders all views. Calls render() for all or for the one
being cut. In some cases you may want to redefine this function instead
of render(). The difference is that this function is called before
sub-views are rendered, but render() is called after.
function recursiveRender(){
$this->add('Text')->set('test');
return parent::recursiveRender(); // will render Text also
}
When cut_object is specified in the GET arguments, then output
of HTML would be limited to object with matching $name or $short_name.
This method will be called instead of default render() and it will
stop rendering process and output object's HTML once it finds
a suitable object. Exception_StopRender is used to terminate
rendering process and bubble up to the APP. This exception is
not an error. | entailment |
public function modelRender()
{
if ($this->model instanceof \atk4\data\Model) {
if ($this->controller instanceof Controller_ADView) {
return;
}
$data = $this->model->persistence->typecastSaveRow($this->model, $this->model->get());
} else {
$data = $this->model->get();
}
$this->template->set($data);
} | When model is specified for a view, values of the model is
inserted inside the template if corresponding tags exist.
This is used as default values and filled out before
the actual render kicks in. | entailment |
public function moveJStoParent()
{
/** @type AbstractView $this->owner */
$this->owner->js = array_merge_recursive($this->owner->js, $this->js);
} | Append our chains to owner's chains. JS chains bubble up to
app, which plugs them into template. If the object is being
"cut" then only relevant chains will be outputed. | entailment |
public function render()
{
if (!($this->template)) {
throw $this->exception('You should specify template for this object')
->addMoreInfo('object', $this->name)
->addMoreInfo('spot', $this->spot);
}
$this->output(($render = $this->template->render()));
if (@$this->debug) {
echo '<font color="blue">'.htmlspecialchars($render).'</font>';
}
} | Default rendering method. Generates HTML presentation of $this view.
For most views, rendering the $this->template would be sufficient.
If your view requires to do some heavy-duty work, please be sure to do
it inside render() method. This way would save some performance in cases
when your object is not being rendered.
render method relies on method output(), which appeends HTML chunks
to the parent's template. | entailment |
public function output($txt)
{
if (!is_null($this->hook('output', array($txt)))) {
if (isset($this->owner->template)
&& !empty($this->owner->template)
) {
$this->owner->template->append($this->spot, $txt, false);
} elseif ($this->owner instanceof App_CLI) {
echo $txt;
}
}
} | Low level output function which append's to the parent object's
template. For normal objects, you simply need to specify a suitable
template.
@param string $txt HTML chunk | entailment |
public function js($when = null, $code = null, $instance = null)
{
// Create new jQuery_Chain object
if (!isset($this->app->jquery)) {
throw new BaseException('requires jQuery or jUI support');
}
/** @type App_Web $this->app */
// Substitute $when to make it better work as a array key
if ($when === true) {
$when = 'always';
}
if ($when === false || $when === null) {
$when = 'never';
}
if ($instance !== null && isset($this->js[$when][$instance])) {
$js = $this->js[$when][$instance];
} else {
$js = $this->app->jquery->chain($this);
}
if ($code) {
$js->_prepend($code);
}
if ($instance !== null) {
$this->js[$when][$instance] = $js;
} else {
$this->js[$when][] = $js;
}
return $js;
} | Views in Agile Toolkit can assign javascript actions to themselves. This
is done by calling $view->js() method.
Method js() will return jQuery_Chain object which would record all calls
to it's non-existant methods and convert them into jQuery call chain.
js([action], [other_chain]);
Action can represent javascript event, such as "click" or "mouseenter".
If you specify action = true, then the event will ALWAYS be executed on
pageload. It will also be executed if respective view is being reloaded
by js()->reload()
(Do not make mistake by specifying "true" instead of true)
action = false will still return jQuery chain but will not bind it.
You can bind it by passing to a different object's js() call as 2nd
argument or output the chain in response to AJAX-ec call by calling
execute() method.
1. Calling with arguments:
$view->js(); // does nothing
$a = $view->js()->hide(); // creates chain for hiding $view but does not
// bind to event yet.
2. Binding existing chains
$img->js('mouseenter', $a); // binds previously defined chain to event on
// event of $img.
Produced code: $('#img_id').click(function(ev){ ev.preventDefault();
$('view1').hide(); });
3. $button->js('click',$form->js()->submit());
// clicking button will result in form submit
4. $view->js(true)->find('.current')->text($text);
Will convert calls to jQuery chain into JavaScript string:
$('#view').find('.current').text('abc'); // The $text will be json-encoded
// to avoid JS injection.
5. ON YOUR OWN RISK
$view->js(true,'alert(123)');
Will inject javascript un-escaped portion of javascript into chain.
If you need to have a custom script then put it into file instead,
save into templates/js/myfile.js and then include:
$view->js()->_load('myfile');
It's highly suggested to bind your libraries with jQuery namespace by
registered them as plugins, this way you can call your function easily:
$view->js(true)->_load('myfile')->myplugin('myfunc',array($arg,$arg));
This approach is compatible with jQuery UI Widget factory and will keep
your code clean
@param string|bool|null $when Event when chain will be executed
@param array|jQuery_Chain|string $code JavaScript chain(s) or code
@param string $instance Obsolete
@link http://agiletoolkit.org/doc/js
@return jQuery_Chain | entailment |
public function on($event, $selector = null, $js = null)
{
/** @type App_Web $this->app */
if (!is_string($selector) && is_null($js)) {
$js = $selector;
$selector = null;
}
if (is_callable($js)) {
/** @type VirtualPage $p */
$p = $this->add('VirtualPage');
$p->set(function ($p) use ($js) {
/** @type VirtualPage $p */
// $js is an actual callable
$js2 = $p->js()->_selectorRegion();
$js3 = call_user_func($js, $js2, $_POST);
// If method returns something, execute that instead
if ($js3) {
$p->js(null, $js3)->execute();
} else {
$js2->execute();
}
});
$js = $this->js()->_selectorThis()->univ()->ajaxec($p->getURL(), true);
}
if ($js) {
$ret_js = $this->js(null, $js)->_selectorThis();
} else {
$ret_js = $this->js()->_selectorThis();
}
$on_chain = $this->js(true);
$fired = false;
$this->app->jui->addHook(
'pre-getJS',
function ($app) use ($event, $selector, $ret_js, $on_chain, &$fired) {
if ($fired) {
return;
}
$fired = true;
$on_chain->on($event, $selector, $ret_js->_enclose(null, true));
}
);
return $ret_js;
} | Views in Agile Toolkit can assign javascript actions to themselves. This
is done by calling $view->js() or $view->on().
on() method implements implementation of jQuery on() method.
on(event, [selector], [other_chain])
Returned is a javascript chain wich is executed when event is triggered
on specified selector (or all of the view if selector is ommitted).
Optional other_chain argument can contain one or more chains (in array)
which will also be executed.
The chain returned by on() will properly select affected element. For
example if the following view would contain multiple <a> elements, then
only the clicked-one will be hidden.
on('click','a')->hide();
Other_chain can also be specified as a Callable. In this case the
executable code you have specified here will be called with several
arguments:
function($js, $data){
$js->hide();
}
In this case javascript method is executed on a clicked event but
in a more AJAX-way
If your method returns a javascript chain, it will be executed
instead. You can execute both if you embed $js inside returned
chain.
The third argument passed to your method contains | entailment |
public function init()
{
parent::init();
$that = $this;
if ($this->owner instanceof Controller_Validator) {
$this->owner->addHook('extraRules', array($this, 'extraRules'));
return; // no source, simply extend rules.
}
if ((
$this->owner instanceof \Model ||
$this->owner instanceof \Form
) && !$this->owner->hasMethod('is')) {
$this->source = $this->owner; // must support set/get interface
$this->owner->validator = $this;
$this->source->addMethod('is', function ($m) use ($that) {
$args = func_get_args();
array_shift($args);
call_user_func_array(array($that, 'is'), $args);
$that->on('beforeSave', null, true);
return $m;
});
}
} | {{{ Initialization method | entailment |
public function is()
{
$args = func_get_args();
// If only first argument is specified, then it's array of rulesets.
// We will call ourselves with every element.
if (count($args) == 1 && is_array($args[0])) {
foreach ($args[0] as $ruleset) {
// $ruleset here is either array or string with pipes
if (!is_array($ruleset)) {
$ruleset = array($ruleset);
}
call_user_func_array(array($this, 'is'), $ruleset);
}
return $this;
}
// If ruleset is specified as a string, we need to expand it
// into an array.
if (count($args) == 1) {
list($field_definition, $rules) = $this->normalizeRules($args[0]);
} else {
$rules = $args;
$field_definition = array_shift($rules);
}
// Convert field defintion into list of fields
$fields = $this->expandFieldDefinition($field_definition, $rules);
// Save rules for each field
foreach ($fields as $field) {
$this->rules[$field][] = $rules;
}
return $this;
} | This method will go through all the rules you specify, expand
and normalize them and assign into array indexed by field name.
You do not need to have your fields defined at this point, unless
you specify wildcards.
This method takes various arguments as described in documentation. | entailment |
public function normalizeRules($rules)
{
// If you want to use a pipe in a regex, custom message etc,
// single-quote the string (escaping would be too confusing in regexes):
//
// This works with:
//
// 'foo?\'my piped | string\''
// "foo?'my piped | string'"
//
// BIG NOTE: There is a reason why there are 2 formats. I don't
// want developres to use ONLY the pipe format. There is always
// multi-argument format, where argument can be anything, and
// we don't complicate things and try to get around regexps
//
// is('name|required?my pipe|string') // Bad
// is('name','required?my pipe|string') // Good
// is('name','required?','my pipe|string') // Best
// TODO: clean up
$rules = preg_split('/[|,:]/', $rules);
$field = array_shift($rules);
return array($field, $rules);
} | Provided with string containing rules, this will convert it into
normal (array) form.
In: "int|required|alphanum|save" (Basic)
In: "int!|a-z|" (Advanced)
Out: array('int','required','alphanum','save') | entailment |
public function applyRulesets()
{
// List of fields which actually need validation at this time.
$fields = $this->getActualFields();
foreach ($fields as $field) {
$rulesets = $this->getRules($field);
$this->active_field = $field;
$this->prefix = '';
$this->caption = '';
foreach ($rulesets as $rules) {
$this->applyRules($field, $rules);
}
}
return $this;
} | Go through the list of defined rules and call the corresponding
filters and convertors. | entailment |
public function pullRule($alias = false)
{
$v = array_shift($this->current_ruleset);
if ($alias && $v[0] == '$') {
$v = $this->get(substr($v, 1));
}
return $this->consumed[] = $v;
} | Pulls next rule out of the rule stack (current_ruleset)
May allow alias ($name). | entailment |
public function pushRule()
{
$args = func_get_args();
// TODO: this can probably be done by args+current_ruleset
foreach (array_reverse($args) as $arg) {
array_unshift($this->current_ruleset, $arg);
}
} | Adds new rule into a rule-set, which will be executed next.
You can specify single or multiple rules, this method accepts
variable arguments.
Rules must be normalized. | entailment |
public function fail()
{
$args = func_get_args();
$str = ucfirst(
$this->prefix.
($this->caption ?: str_replace('_', ' ', $this->active_field)).' '.
lcfirst(array_shift($args))
);
// Insert any args into placeholders
if (count($args) > 0) {
$n = 1;
foreach ($args as $arg) {
$tag = sprintf('{{arg%s}}', $n);
$str = str_replace($tag, $arg, $str);
++$n;
}
}
/** @type Exception_ValidityCheck $e */
$e = $this->exception((string) ($this->custom_error ?: $str));
throw $e->setField($this->active_field);
} | {{{ Methods which are called by the rules | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.