sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function hasTag($tag)
{
if ($this->isTopTag($tag)) {
return true;
}
return isset($this->tags[$tag]) && is_array($this->tags[$tag]);
} | Check if tag is present inside template | entailment |
public function rebuildTags()
{
$this->tags = array();
$this->updated_tag_list = array();
$this->rebuildTagsRegion($this->template);
return $this;
} | Rebuild tags of existing array structure
This function walks through template and rebuilds list of tags. You need it in case you
changed already parsed template.
@return $this | entailment |
public function addSubMenu($name)
{
/** @type View $li */
$li = $this->add('View');
$li->setElement('li');
/** @type Text $t */
$t = $li->add('Text');
$t->set($name);
return $li
->add(get_class($this));
} | @param string $name
@return self | entailment |
public function setterGetter($type, $value = UNDEFINED)
{
if ($value === UNDEFINED) {
return $this->$type;
}
$this->$type = $value;
return $this;
} | Implementation of generic setter-getter method which supports "UNDEFINED"
constant. This method is used by all other sette-getters.
@param string $type Corresponds to the name of property of a field
@param mixed $value New value for a property.
@return mixed|$this new or current pperty (if value is UNDEFINED) | entailment |
public function set($value = null)
{
$this->owner->set($this->short_name, $value);
return $this;
} | Sets the value of the field. Identical to $model[$fieldname]=$value.
@param mixed $value new value
@return Field $this | entailment |
public function get()
{
if ($this->owner->loaded()
|| isset($this->owner->data[$this->short_name])
) {
return $this->owner->get($this->short_name);
}
return $this->defaultValue();
} | Get the value of the field of a loaded model. If model is not loaded
will return default value instead.
@return mixed current value of a field | entailment |
public function caption($t = UNDEFINED)
{
if ($t === UNDEFINED && !$this->caption) {
return ucwords(strtr(
preg_replace('/_id$/', '', $this->short_name),
'_',
' '
));
}
return $this->setterGetter('caption', $t);
} | Sets field caption which will be used by forms, grids and other view
elements as a label. The caption will be localized through $app->_().
@param string $t new value
@return string|$this current value if $t=UNDEFINED | entailment |
public function system($t = UNDEFINED)
{
if ($t === true) {
$this->editable(false)->visible(false);
}
return $this->setterGetter('system', $t);
} | Marking field as system will cause it to always be loaded, even if
it's not requested through Actual Fields. It will also hide the field
making it dissapear from Grids and Forms. A good examples of system
fields are "id" or "created_dts".
@param bool $t new value
@return bool|$this current value if $t=UNDEFINED | entailment |
public function defaultValue($t = UNDEFINED)
{
if ($t !== UNDEFINED) {
$this->has_default_value = true;
}
return $this->setterGetter('defaultValue', $t);
} | Default Value is used inside forms when you present them without loaded
data. This does not change how model works, which will simply avoid
including unchanged field into insert/update queries.
@param bool $t new value
@return bool|$this current value if $t=UNDEFINED | entailment |
public function getBooleanValue($value)
{
if ($value === null) {
return;
}
if ($this->listData) {
reset($this->listData);
list(, $yes_value) = @each($this->listData);
list(, $no_value) = @each($this->listData);
if ($no_value === null) {
$no_value = '';
}
/* not to convert N to Y */
if ($yes_value == $value) {
return $yes_value;
}
if ($no_value == $value) {
return $no_value;
}
} else {
$yes_value = 1;
$no_value = 0;
}
return $value ? $yes_value : $no_value;
} | Converts true/false into boolean representation according to the "enum"
@param mixed $value
@return int|null | entailment |
public function mb_str_to_lower($a)
{
return ($this->is_mb) ? mb_strtolower($a, $this->encoding) : strtolower($a);
} | Is the PHP5 multibyte lib available? | entailment |
public function init()
{
parent::init();
$this->app->pathfinder = $this;
$this->addDefaultLocations();
// Unregister previously defined loader
if (function_exists('agile_toolkit_temporary_load_class')) {
spl_autoload_unregister('agile_toolkit_temporary_load_class');
// collect information about previusly loaded files
foreach ($GLOBALS['agile_toolkit_temporary_load_class_log'] as $class => $path) {
$this->info('Loaded class %s from file %s', $class, $path);
}
}
$self = $this;
// Register preceeding autoload method. We want to get a first shot at
// loading classes
spl_autoload_register(function ($class) use ($self) {
try {
$path = $self->loadClass($class);
if ($path) {
$self->info('Loaded class %s from file %s', $class, $path);
}
} catch (Exception $e) {
// ignore exceptions
}
}, true, true);
if (!$this->report_autoload_errors) {
return;
}
// If we couldn't load the class, let's throw exception
spl_autoload_register(function ($class) use ($self) {
try {
$self->loadClass($class);
} catch (Exception $e) {
// If due to your PHP version, it says that
// autoloader may not throw exceptions, then you should
// add PHP version check here and skip to next line.
// PHP 5.5 - throwing seems to work out OK
throw $e;
}
});
} | {@inheritdoc} | entailment |
public function addDefaultLocations()
{
// app->addAllLocations - will override creation of all locations
// app->addDefaultLocations - will let you add high-priority locations
// app->addSharedLocations - will let you add low-priority locations
if ($this->app->hasMethod('addAllLocations')) {
return $this->app->addAllLocations();
}
$base_directory = getcwd();
/// Add base location - where our private files are
if ($this->app->hasMethod('addDefaultLocations')) {
$this->app->addDefaultLocations($this, $base_directory);
}
$templates_folder = array('template', 'templates');
if ($this->app->compat_42 && is_dir($base_directory.'/templates/default')) {
$templates_folder = 'templates/default';
}
$this->base_location = $this->addLocation(array(
'php' => 'lib',
'page' => 'page',
'tests' => 'tests',
'template' => $templates_folder,
'mail' => 'mail',
'logs' => 'logs',
'dbupdates' => 'doc/dbupdates',
))->setBasePath($base_directory);
if (@$this->app->pm) {
// Add public location - assets, but only if
// we hav PageManager to identify it's location
if (is_dir($base_directory.'/public')) {
$this->public_location = $this->addLocation(array(
'public' => '.',
'js' => 'js',
'css' => 'css',
))
->setBasePath($base_directory.'/public')
->setBaseURL($this->app->pm->base_path);
} else {
$this->base_location
->setBaseURL($this->app->pm->base_path);
$this->public_location = $this->base_location;
$this->public_location->defineContents(array('js' => 'templates/js', 'css' => 'templates/css'));
}
if (basename($this->app->pm->base_path) == 'public') {
$this->base_location
->setBaseURL(dirname($this->app->pm->base_path));
}
}
if ($this->app->hasMethod('addSharedLocations')) {
$this->app->addSharedLocations($this, $base_directory);
}
// Add shared locations
if (is_dir(dirname($base_directory).'/shared')) {
$this->shared_location = $this->addLocation(array(
'php' => 'lib',
'addons' => 'addons',
'template' => $templates_folder,
))->setBasePath(dirname($base_directory).'/shared');
}
$atk_base_path = dirname(dirname(__FILE__));
$this->atk_location = $this->addLocation(array(
'php' => 'lib',
'template' => $templates_folder,
'tests' => 'tests',
'mail' => 'mail',
))
->setBasePath($atk_base_path)
;
if (@$this->app->pm) {
if ($this->app->compat_42 && is_dir($this->public_location->base_path.'/atk4/public/atk4')) {
$this->atk_public = $this->public_location->addRelativeLocation('atk4/public/atk4');
} elseif (is_dir($this->public_location->base_path.'/atk4')) {
$this->atk_public = $this->public_location->addRelativeLocation('atk4');
} elseif (is_dir($base_directory.'/vendor/atk4/atk4/public/atk4')) {
$this->atk_public = $this->base_location->addRelativeLocation('vendor/atk4/atk4/public/atk4');
} elseif (is_dir($base_directory.'/../vendor/atk4/atk4/public/atk4')) {
$this->atk_public = $this->base_location->addRelativeLocation('../vendor/atk4/atk4/public/atk4');
} else {
echo $this->public_location;
throw $this->exception('Unable to locate public/atk4 folder', 'Migration');
}
$this->atk_public->defineContents(array(
'public' => '.',
'js' => 'js',
'css' => 'css',
));
}
// Add sandbox if it is found
$this->addSandbox();
} | Agile Toolkit-based application comes with a predefined resource
structure. For new users it's easier if they use a consistest structure,
for example having all the PHP classes inside "lib" folder.
A more advanced developer might be willing to add additional locations
of resources to suit your own preferences. You might want to do
this if you are integrating with your existing application or
another framework or building multi-tiered project with extensive
structure.
To extend the default structure which this method defines - you should
look into :php:class:`App_CLI::addDefaultLocations` and
:php:class:`App_CLI::addSharedLocations` | entailment |
public function addLocation($contents = array(), $old_contents = null)
{
if ($old_contents && @$this->app->compat_42) {
return $this->base_location->addRelativeLocation($contents, $old_contents);
}
/** @type PathFinder_Location $loc */
$loc = $this->add('PathFinder_Location');
return $loc->defineContents($contents);
} | Cretes new PathFinder_Location object and specifies it's contents.
You can subsequentially add more contents by calling:
:php:meth:`PathFinder_Location::defineContents`.
@param array $contents
@param mixed $old_contents
@return PathFinder_Location | entailment |
public function locate($type, $filename = '', $return = 'relative', $throws_exception = true)
{
$attempted_locations = array();
if (!$return) {
$return = 'relative';
}
foreach ($this->elements as $key => $location) {
if (!($location instanceof PathFinder_Location)) {
continue;
}
$path = $location->locate($type, $filename, $return);
if (is_string($path) || is_object($path)) {
return $path;
} elseif (is_array($path)) {
if ($return === 'array' && @isset($path['name'])) {
return $path;
}
$attempted_locations = array_merge($attempted_locations, $path);
}
}
if ($throws_exception) {
throw $this->exception('File not found')
->addMoreInfo('file', $filename)
->addMoreInfo('type', $type)
->addMoreInfo('attempted_locations', $attempted_locations)
;
}
} | Search for a $filename inside multiple locations, associated with resource
$type. By default will return relative path, but 3rd argument can
change that.
The third argument can also be 'location', in which case a :php:class:`PathFinder_Location`
object will be returned.
If file is not found anywhere, then :php:class:`Exception_PathFinder` is thrown
unless you set $throws_exception to ``false``, and then method would return null.
@param string $type Type of resource to search surch as "php"
@param string $filename Name of the file to search for
@param string $return 'relative','url','path' or 'location'
@return string|object|array | entailment |
public function search($type, $filename = '', $return = 'relative')
{
$matches = array();
foreach ($this->elements as $location) {
if (!($location instanceof PathFinder_Location)) {
continue;
}
$path = $location->locate($type, $filename, $return);
if (is_string($path)) {
// file found!
$matches[] = $path;
}
}
return $matches;
} | Search is similar to locate, but will return array of all matching
files.
@param string $type Type of resource to search surch as "php"
@param string $filename Name of the file to search for
@param string $return 'relative','url','path' or 'location'
@return string|object as specified by $return | entailment |
public function searchDir($type, $directory = '')
{
$dirs = $this->search($type, $directory, 'path');
$files = array();
foreach ($dirs as $dir) {
$this->_searchDirFiles($dir, $files);
}
return $files;
} | Specify type and directory and it will return array of all files
of a matching type inside that directory. This will work even
if specified directory exists inside multiple locations. | entailment |
public function loadClass($className)
{
$origClassName = str_replace('-', '', $className);
/**/$this->app->pr->start('pathfinder/loadClass ');
/**/$this->app->pr->next('pathfinder/loadClass/convertpath ');
$className = ltrim($className, '\\');
$nsPath = '';
$namespace = '';
if ($lastNsPos = strripos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$nsPath = str_replace('\\', DIRECTORY_SEPARATOR, $namespace);
}
$classPath = str_replace('_', DIRECTORY_SEPARATOR, $className).'.php';
/**/$this->app->pr->next('pathfinder/loadClass/locate ');
try {
if ($namespace) {
if (strpos($className, 'page_') === 0) {
$path = $this->app->locatePath(
'addons',
$nsPath.DIRECTORY_SEPARATOR.$classPath
);
} else {
$path = $this->app->locatePath(
'addons',
$nsPath.DIRECTORY_SEPARATOR
.'lib'.DIRECTORY_SEPARATOR.$classPath
);
}
} else {
if (strpos($className, 'page_') === 0) {
$path = $this->app->locatePath(
'page',
substr($classPath, 5)
);
} else {
$path = $this->app->locatePath(
'php',
$classPath
);
}
}
} catch (Exception_PathFinder $e) {
$e
->addMoreInfo('class', $className)
->addMoreInfo('namespace', $namespace)
->addMoreInfo('orig_class', $origClassName)
;
throw $e;
}
if (!is_readable($path)) {
throw new Exception_PathFinder('addon', $path, $prefix);
}
/**/$this->app->pr->next('pathfinder/loadClass/include ');
/**/$this->app->pr->start('php parsing');
include_once $path;
if (!class_exists($origClassName, false) && !interface_exists($origClassName, false)) {
throw $this->exception('Class is not defined in file or extended class can not be found')
->addMoreInfo('file', $path)
->addMoreInfo('namespace', $namespace)
->addMoreInfo('class', $className)
;
}
/**/$this->app->pr->stop();
return $path;
} | Provided with a class name, this will attempt to
find and load it.
@return string path from where the class was loaded | entailment |
public function getURL($file_path = null)
{
if (!$this->base_url) {
throw new BaseException('Unable to determine URL');
}
if (!$file_path) {
return $this->base_url;
}
$u = $this->base_url;
if (substr($u, -1) != '/') {
$u .= '/';
}
return $u.$file_path;
} | Returns how this location or file can be accessed through web
base url + relative path + file_path. | entailment |
public function addRelativeLocation($relative_path, array $contents = array())
{
$location = $this->newInstance();
$location->setBasePath($this->base_path.'/'.$relative_path);
if ($this->base_url) {
$location->setBaseURL($this->base_url.'/'.$relative_path);
}
return $contents ? $location->defineContents($contents) : $location;
} | Adds a new location object which is relative to $this location.
@param string $relative_path
@param array $contents | entailment |
public function setParent(Pathfinder_Location $parent)
{
$this->setBasePath($parent->base_path.'/'.$this->_relative_path);
$this->setBaseURL($parent->base_url.'/'.$this->_relative_path);
return $this;
} | OBSOLETE - Compatiblity | entailment |
public function print_r($key, $gs, $ge, $ls, $le, $ind = ' ', $max_depth = 6)
{
$o = '';
if (strlen($ind) > $max_depth) {
return;
}
if (is_array($key)) {
$o = $gs;
foreach ($key as $a => $b) {
$o .= $ind.$ls.$a.': '.$this->print_r($b, $gs, $ge, $ls, $le, $ind.' ').$le;
}
$o .= $ge;
} elseif ($key instanceof Closure) {
$o .= '[closure]';
} elseif (is_object($key)) {
$o .= 'object('.get_class($key).'): ';
if (method_exists($key, '__debugInfo')) {
$o .= $this->print_r($key->__debugInfo(), $gs, $ge, $ls, $le, $ind.' ').$le;
}
} else {
$o .= $gs ? htmlspecialchars($key) : $key;
}
return $o;
} | Returns HTML formatted $key array.
@param mixed $key
@param string $gs List start tag
@param string $ge List end tag
@param string $ls Item start tag
@param string $le Item end tag
@param string $ind Identation
@return string | entailment |
public function Debug($filename)
{
if (is_null($filename)) {
$filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'debug.log';
}
$this->filename = $filename;
if (isset($_SERVER['REMOTE_ADDR'])) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$a = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$this->_current_ip = array_shift($a);
} else {
$this->_current_ip = $_SERVER['REMOTE_ADDR'];
}
}
} | Debug functions | entailment |
public function p($message, $file = null, $line = null)
{
$res = true;
$time_diff_str = '';
if (!empty($this->_prev_exec_time)) {
$time_diff = $this->_microtime_float() - $this->_prev_exec_time;
if ($time_diff < 1) {
$time_diff_str = $this->_sec2time($time_diff);
}
}
$details = ((empty($this->_current_ip)) ? '' : $this->_current_ip.' - ').
((!empty($file)) ? basename($file).' (line '.$line.')' : '');
if (!empty($details)) {
$details = ' ***** '.$details.' *****';
}
$message = '['.date('d-M-Y H:i:s').'] '.$time_diff_str.$details.
"\n\n".$message."\n\n";
$new_file = (file_exists($this->filename)) ? false : true;
$fh = @fopen($this->filename, 'a');
if (($fh !== false) && (is_resource($fh))) {
@flock($fh, LOCK_EX);
if (!@fwrite($fh, $message)) {
$this->err_message = "Cannot write to file ($this->filename)";
error_log($this->err_message.' in '.__FILE__.' on line '.__LINE__, 0);
$res = false;
}
@flock($fh, LOCK_UN);
@fclose($fh);
if ($new_file) {
chmod($this->filename, 0777);
}
} else {
$this->err_message = 'Cannot open file ('.$this->filename.')'.
' in '.__FILE__.' on line '.__LINE__.' for save message: '."\n".$message;
error_log($this->err_message, 0);
$res = false;
}
$this->_prev_exec_time = $this->_microtime_float();
return $res;
} | print | entailment |
public function init()
{
parent::init();
// template fixes
$this->addClass('atk-form atk-form-stacked atk-form-compact atk-move-right');
$this->template->trySet('fieldset', 'atk-row');
$this->template->tryDel('button_row');
$this->addClass('atk-col-3');
// add field
$this->search_field = $this->addField('Line', 'q', '')->setAttr('placeholder', 'Search')->setNoSave();
// cancel button
if ($this->show_cancel && $this->recall($this->search_field->short_name)) {
$this->add('View', null, 'cancel_button')
->setClass('atk-cell')
->add('HtmlElement')
->setElement('A')
->setAttr('href', 'javascript:void(0)')
->setClass('atk-button')
->setHtml('<span class="icon-cancel atk-swatch-red"></span>')
->js('click', array(
$this->search_field->js()->val(null),
$this->js()->submit(),
));
}
/** @type HtmlElement $b Search button */
$b = $this->add('HtmlElement', null, 'form_buttons');
$b->setElement('A')
->setAttr('href', 'javascript:void(0)')
->setClass('atk-button')
->setHtml('<span class="icon-search"></span>')
->js('click', $this->js()->submit());
} | Initialization. | entailment |
public function useFields($fields)
{
if (is_string($fields)) {
$fields = explode(',', $fields);
}
$this->fields = $fields;
return $this;
} | Set fields on which filtering will be done.
@param string|array $fields
@return QuickSearch $this | entailment |
public function postInit()
{
parent::postInit();
if (!($v = trim($this->get('q')))) {
return;
}
$m = $this->view->model;
// if model has method addConditionLike
if ($m->hasMethod('addConditionLike')) {
return $m->addConditionLike($v, $this->fields);
}
// if it is Agile Data model
if ($m instanceof \atk4\data\Model) {
if (!$m->hasMethod('expr')) {
return $m;
}
$expr = [];
foreach ($this->fields as $k => $field) {
// get rid of never_persist fields
$f = $m->hasElement($field);
if (!$f || $f->never_persist) {
unset($this->fields[$k]);
continue;
}
$expr[] = 'lower({' . $field . '}) like lower([])';
}
$expr = '('.implode(' or ', $expr).')';
$expr = $m->expr($expr, array_fill(0, count($this->fields), '%'.$v.'%'));
return $m->addCondition($expr); // @todo should use having instead
}
// if it is ATK 4.3 model or any other data source
if ($m instanceof SQL_Model) {
$q = $m->_dsql();
} else {
$q = $this->view->dq;
}
$or = $q->orExpr();
foreach ($this->fields as $field) {
$or->where($field, 'like', '%'.$v.'%');
}
$q->having($or);
} | Process received filtering parameters after init phase.
@return Model|void | entailment |
public function importFields($model, $fields = null)
{
$this->model = $model;
$this->grid = $this->owner;
if ($fields === false) {
return;
}
$fields_supplied = (boolean)$fields;
if (!$fields) {
if ($model->only_fields) {
$fields = $model->only_fields;
} else {
$fields = [];
// get all field-elements
foreach ($model->elements as $field => $f_object) {
if ($f_object instanceof \atk4\data\Field
&& $f_object->isVisible()
&& !$f_object->isHidden()
) {
$fields[] = $field;
}
}
}
}
if (!is_array($fields)) {
$fields = [$fields];
}
// import fields one by one
foreach ($fields as $field) {
$this->importField($field);
}
if ($fields_supplied) {
$model->onlyFields($fields);
}
return $this;
} | Import model fields in grid.
@param \atk4\data\Model $model
@param array|string|bool $fields
@return void|$this | entailment |
public function importField($field)
{
$field = $this->model->hasElement($field);
/** @type \atk4\data\Field $field */
if (!$field || !$field->isVisible() || $field->isHidden()) {
return;
}
$field_name = $field->short_name;
$field_type = $this->getFieldType($field);
$field_caption = isset($field->ui['caption']) ? $field->ui['caption'] : null;
$this->field_associations[$field_name] = $field;
$column = $this->owner->addColumn($field_type, $field_name, $field_caption);
if (isset($field->ui['sortable']) && $field->ui['sortable'] && $column->hasMethod('makeSortable')) {
$column->makeSortable();
}
return $column;
} | Import one field from model into grid.
@param string $field
@return void|Grid|Controller_Grid_Format | entailment |
public function getFieldType($field)
{
// default column type
$type = $field->type;
// try to find associated field type
if (isset($this->type_associations[$type])) {
$type = $this->type_associations[$type];
}
if ($type == 'text' && isset($field->allowHtml) && $field->allowHtml) {
$type = 'html';
}
// if grid column type/formatter explicitly set in model
if (isset($field->ui['display'])) {
// @todo this is wrong and obsolete, as hasOne uses display for way different purpose
$tmp = $field->ui['display'];
if (isset($tmp['grid'])) {
$tmp = $tmp['grid'];
}
if (is_string($tmp) && $tmp) {
$type = $tmp;
}
}
return $type;
} | Returns grid column type associated with model field.
Redefine this method to add special handling of your own fields.
@param \atk4\data\Field $field
@return string | entailment |
public function collectBasicData($code)
{
$this->name = get_class($this);
$this->my_backtrace = debug_backtrace();
array_shift($this->my_backtrace);
array_shift($this->my_backtrace);
} | Collect basic data of exception.
@param string|int $code Error code | entailment |
public function addAction($key, $descr)
{
if (is_array($key)) {
$this->recommendation = (string) $descr;
$this->actions = array_merge($this->actions, $key);
return $this;
}
$this->actions[$key] = $descr;
return $this;
} | Actions will be displayed as links on the exception page allowing viewer
to perform additional debug functions.
addAction('show info',array('info'=>true)) will result in link to &info=1.
@param string|array $key
@param string|array $descr
@return $this | entailment |
public function getHTML()
{
$e = $this;
$o = '<div class="atk-layout">';
$o .= $this->getHTMLHeader();
$o .= $this->getHTMLSolution();
//$o.=$this->getHTMLBody();
$o .= '<div class="atk-layout-row"><div class="atk-wrapper atk-section-small">';
if (isset($e->more_info)) {
$o .= '<h3>Additional information:</h3>';
$o .= $this->print_r($e->more_info, '<ul>', '</ul>', '<li>', '</li>', ' ');
}
if (method_exists($e, 'getMyFile')) {
$o .= '<div class="atk-effect-info">'.$e->getMyFile().':'.$e->getMyLine().'</div>';
}
if (method_exists($e, 'getMyTrace')) {
$o .= $this->backtrace(3, $e->getMyTrace());
} else {
$o .= $this->backtrace(@$e->shift, $e->getTrace());
}
if (isset($e->by_exception)) {
$o .= '<h3>This error was triggered by the following error:</h3>';
if ($e->by_exception instanceof self) {
$o .= $e->by_exception->getHTML();
} elseif ($e->by_exception instanceof Exception) {
$o .= $e->by_exception->getMessage();
}
}
$o .= '</div></div>';
return $o;
} | Returns HTML representation of the exception.
@return string | entailment |
public function getDocURL($o)
{
if (!is_object($o)) {
return false;
}
if (!$o instanceof AbstractObject) {
return false;
}
/*$refl = new ReflectionClass($o);
$parent = $refl->getParentClass();
if($parent) {
// check to make sure property is overriden in child
$const = $parent->getConstants();
var_Dump($const);
if ($const['DOC'] == $o::DOC) return false;
}
*/
$url = $o::DOC;
if (substr($url, 0, 4) != 'http') {
return 'http://book.agiletoolkit.org/'.$url.'.html';
}
return $url;
} | Classes define a DOC constant which points to a on-line resource
containing documentation for given class. This method will
return full URL for the specified object.
@param AbstractObject $o
@return bool|string | entailment |
public function backtrace($sh = null, $backtrace = null)
{
$output = '<div class="atk-box-small atk-table atk-table-zebra">';
$output .= "<table>\n";
$output .= "<tr><th align='right'>File</th><th>Object Name</th><th>Stack Trace</th><th>Help</th></tr>";
if (!isset($backtrace)) {
$backtrace = debug_backtrace();
}
$sh -= 2;
$n = 0;
foreach ($backtrace as $bt) {
++$n;
$args = '';
if (!isset($bt['args'])) {
continue;
}
foreach ($bt['args'] as $a) {
if (!empty($args)) {
$args .= ', ';
}
switch (gettype($a)) {
case 'integer':
case 'double':
$args .= $a;
break;
case 'string':
$a = htmlspecialchars(substr($a, 0, 128)).((strlen($a) > 128) ? '...' : '');
$args .= "\"$a\"";
break;
case 'array':
$args .= 'Array('.count($a).')';
break;
case 'object':
$args .= 'Object('.get_class($a).')';
break;
case 'resource':
$args .= 'Resource('.strstr((string) $a, '#').')';
break;
case 'boolean':
$args .= $a ? 'True' : 'False';
break;
case 'NULL':
$args .= 'Null';
break;
default:
$args .= 'Unknown';
}
}
if (($sh == null && strpos($bt['file'], '/atk4/lib/') === false)
|| (!is_int($sh) && $bt['function'] == $sh)
) {
$sh = $n;
}
$doc = $this->getDocURL($bt['object']);
if ($doc) {
$doc .= '#'.get_class($bt['object']).'::'.$bt['function'];
}
$output .= '<tr><td valign=top align=right class=atk-effect-'.
($sh == $n ? 'danger' : 'info').'>'.htmlspecialchars(dirname($bt['file'])).'/'.
'<b>'.htmlspecialchars(basename($bt['file'])).'</b>';
$output .= ":{$bt['line']}</font> </td>";
$name = (!isset($bt['object']->name)) ? get_class($bt['object']) : $bt['object']->name;
if ($name) {
$output .= '<td>'.$name.'</td>';
} else {
$output .= '<td></td>';
}
$output .= '<td valign=top class=atk-effect-'.($sh == $n ? 'danger' : 'success').'>'.
get_class($bt['object'])."{$bt['type']}<b>{$bt['function']}</b>($args)</td>";
if ($doc) {
$output .= "<td><a href='".$doc."' target='_blank'><i class='icon-book'></i></a></td>";
} else {
$output .= '<td> </td>';
}
$output .= '</tr>';
}
$output .= "</table></div>\n";
return $output;
} | @param int $sh
@param array $backtrace
@return string | entailment |
public function getText()
{
$more_info = $this->print_r($this->more_info, '[', ']', '', ',', ' ');
$text = get_class($this).': '.$this->getMessage().' ('.$more_info.')'.
' in '.$this->getMyFile().':'.$this->getMyLine();
return $text;
} | Returns Textual representation of the exception.
@return string | entailment |
public function dsql($class = null)
{
$obj = parent::dsql($class);
if (!$obj instanceof DB_dsql_prefixed) {
throw $this->exception('Specified class must be descendant of DB_dsql_prefixed')
->addMoreInfo('class', $class);
}
if ($this->table_prefix) {
$obj->prefix($this->table_prefix);
}
return $obj;
} | Returns Dynamic Query object compatible with this database driver (PDO). Also sets prefix | entailment |
public function init()
{
parent::init();
// sorting support
$this->sortby =
isset($_GET[$this->name.'_sort'])
? $this->memorize('sortby', $_GET[$this->name.'_sort'])
: $this->recall('sortby', '0');
} | Initialization. | entailment |
public function addPaginator($rows = 25, $options = null, $class = null)
{
// add only once
// @todo decide, maybe we should destroy and recreate to keep last one
if ($this->paginator) {
return $this->paginator;
}
$this->paginator = $this->add($class ?: $this->paginator_class, $options);
/** @type Paginator $this->paginator */
$this->paginator->setRowsPerPage($rows);
return $this->paginator;
} | Adds paginator to the grid.
@param int $rows row count per page
@param array $options optional options array
@param string $class optional paginator class name
@return Paginator
@todo decide, maybe we need to add $spot optional template spot like in addQuickSearch() | entailment |
public function addQuickSearch($fields, $options = null, $class = null, $spot = null)
{
// add only once
// @todo decide, maybe we should destroy and recreate to keep last one
if ($this->quick_search) {
return $this->quick_search;
}
$this->quick_search = $this->add($class ?: $this->quick_search_class, $options, $spot ?: 'quick_search');
/** @type QuickSearch $this->quick_search */
$this->quick_search
->useWith($this)
->useFields($fields);
return $this->quick_search;
} | Adds QuickSearch to the grid.
@param array $fields array of fieldnames used in quick search
@param array $options optional options array
@param string $class optional quick search object class
@param string $spot optional template spot
@return QuickSearch | entailment |
public function addSelectable($field)
{
$this->js_widget = null;
$this->js(true)
->_load('ui.atk4_checkboxes')
->atk4_checkboxes(array('dst_field' => $field));
$this->addColumn('checkbox', 'selected');
$this->addOrder()
->useArray($this->columns)
->move('selected', 'first')
->now();
} | Adds column with checkboxes on the basis of Model definition.
@param mixed $field should be Form_Field object or jQuery selector of
1 field. When passing it as jQuery selector don't
forget to use hash sign like "#myfield" | entailment |
public function getIterator()
{
$iter = parent::getIterator();
// sorting support
if ($this->sortby) {
$desc = ($this->sortby_db[0] == '-');
$order = ltrim($this->sortby_db, '-');
$this->applySorting($iter, $order, $desc);
}
return $iter;
} | Returns data source iterator.
@return mixed | entailment |
public function makeSortable($db_field = null)
{
// reverse sorting
$reverse = false;
if ($db_field[0] == '-') {
$reverse = true;
$db_field = substr($db_field, 1);
}
// used db field
if (!$db_field) {
$db_field = $this->last_column;
}
switch ((string) $this->sortby) {
// we are already sorting by this column
case $db_field:
$info = array('1', $reverse ? 0 : ('-'.$db_field));
$this->sortby_db = $db_field;
break;
// We are sorted reverse by this column
case '-'.$db_field:
$info = array('2', $reverse ? $db_field : '0');
$this->sortby_db = '-'.$db_field;
break;
// we are not sorted by this column
default:
$info = array('0', $reverse ? ('-'.$db_field) : $db_field);
}
$this->columns[$db_field]['sortable'] = $info;
return $this;
} | Make sortable.
@param string $db_field
@return $this | entailment |
public function staticSortCompare($str1, $str2)
{
if ($this->sortby[0] == '-') {
return strcmp(
$str2[substr($this->sortby, 1)],
$str1[substr($this->sortby, 1)]
);
}
return strcmp(
$str1[$this->sortby],
$str2[$this->sortby]
);
} | Compare two strings and return:
< 0 if str1 is less than str2;
> 0 if str1 is greater than str2,
and 0 if they are equal.
Note that this comparison is case sensitive
@param string $str1
@param string $str2
@return int | entailment |
public function applySorting($i, $field, $desc)
{
if (!$field) {
return;
}
if ($i instanceof DB_dsql) {
$i->order($field, $desc);
} elseif ($i instanceof \atk4\data\Model) {
$i->setOrder($field, $desc);
} elseif ($i instanceof SQL_Model) {
$i->setOrder($field, $desc);
} elseif ($i instanceof Model) {
$i->setOrder($field, $desc);
}
} | Apply sorting on particular field.
@param Iterator $i
@param string $field
@param string|bool $desc | entailment |
public function formatTotalsRow()
{
// call CompleteLister formatTotalsRow method
parent::formatTotalsRow();
// additional formatting of totals row
$totals_columns = array_keys($this->totals) ?: array();
foreach ($this->columns as $field => $column) {
if (in_array($field, $totals_columns)) {
// process formatters (additional to default formatters)
$this->executeFormatters($field, $column, 'format_totals_', true);
} else {
// show empty cell if totals are not calculated for this column
$this->current_row_html[$field] = '';
}
// totals title displaying
if ($field == $this->totals_title_field) {
$this->setTDParam($field, 'style/font-weight', 'bold');
}
// apply TD parameters to all columns
$this->applyTDParams($field, $this->totals_t);
}
// set title
if ($this->totals_title_field && $this->totals) {
$this->current_row_html[$this->totals_title_field] = sprintf(
$this->totals_title,
$this->current_row['row_count'],
$this->current_row['plural_s']
);
}
} | Additional formatting for Totals row.
Extends CompleteLister formatTotalsRow method.
Note: in this method you should only add *additional* formatting of
totals row because standard row formatting will be already applied by
calling parent::formatTotalsRow(). | entailment |
public function getCurrentIndex($idfield = 'id')
{
// TODO: think more to optimize this method
if (is_array($this->data)) {
return array_search(current($this->data), $this->data);
}
// else it is dsql dataset...
return $this->current_row[$idfield];
} | Returns ID of record.
@param string $idfield ID field name
@return mixed | entailment |
public function setTDParam($field, $path, $value)
{
// if value is null, then do nothing
if ($value === null) {
return;
}
// adds a parameter. nested ones can be specified like 'style/color'
$path = explode('/', $path);
$current_position = &$this->tdparam[$this->getCurrentIndex()][$field];
if (!is_array($current_position)) {
$current_position = array();
}
foreach ($path as $part) {
if (array_key_exists($part, $current_position)) {
$current_position = &$current_position[$part];
} else {
$current_position[$part] = array();
$current_position = &$current_position[$part];
}
}
$current_position = $value;
} | Sets TD params.
@param string $field
@param string $path
@param string $value | entailment |
public function applyTDParams($field, &$row_template = null)
{
// data row template by default
if (!$row_template) {
$row_template = &$this->row_t;
}
// setting cell parameters (tdparam)
$tdparam = $this->tdparam[$this->getCurrentIndex()][$field];
$tdparam_str = '';
if (is_array($tdparam)) {
if (is_array($tdparam['style'])) {
$tdparam_str .= 'style="';
foreach ($tdparam['style'] as $key => $value) {
$tdparam_str .= $key.':'.$value.';';
}
$tdparam_str .= '" ';
unset($tdparam['style']);
}
//walking and combining string
foreach ($tdparam as $id => $value) {
$tdparam_str .= $id.'="'.$value.'" ';
}
// set TD param to appropriate row template
$row_template->set("tdparam_$field", trim($tdparam_str));
}
} | Apply TD parameters to appropriate template.
You can pass row template to use too. That's useful to set up totals rows, for example.
@param string $field Fieldname
@param SQLite $row_template Optional row template | entailment |
public function setTotalsTitle($field, $title = 'Total: %s row%s')
{
$this->totals_title_field = $field;
$this->totals_title = $title;
return $this;
} | Sets totals title field and text.
@param string $field
@param string $title
@return $this | entailment |
public function init_expander($field)
{
// set column style
$this->columns[$field]['thparam'] .= ' style="width:40px; text-align:center"';
// set column refid - referenced model table for example
if (!isset($this->columns[$field]['refid'])) {
if ($this->model) {
$refid = $this->model->table;
} elseif ($this->dq) {
$refid = $this->dq->args['table'];
} else {
$refid = preg_replace('/.*_/', '', $this->app->page);
}
$this->columns[$field]['refid'] = $refid;
}
// initialize button widget on page load
$class = $this->name.'_'.$field.'_expander';
$this->js(true)->find('.'.$class)->button();
// initialize expander
$this->js(true)
->_selector('.'.$class)
->_load('ui.atk4_expander')
->atk4_expander();
} | Initialize expander.
@param string $field field name | entailment |
public function format_expander($field, $column)
{
if (!$this->current_row[$field]) {
$this->current_row[$field] = $column['descr'];
}
// TODO:
// reformat this using Button, once we have more advanced system to
// bypass rendering of sub-elements.
// $this->current_row[$field] = $this->add('Button',null,false)
$key = $this->name.'_'.$field.'_';
$id = $key.$this->app->normalizeName($this->model->id);
$class = $key.'expander';
$this->current_row_html[$field] =
'<input type="checkbox" '.
'class="'.$class.'" '.
'id="'.$id.'" '.
'rel="'.$this->app->url(
$column['page'] ?: './'.$field,
array(
'expander' => $field,
'expanded' => $this->name,
'cut_page' => 1,
// TODO: id is obsolete
//'id' => $this->model->id,
$this->columns[$field]['refid'].'_'.$this->model->id_field => $this->model->id,
)
).'" '.
'/>'.
'<label for="'.$id.'" style="cursor:pointer;"><a class="atk-button-small">'.
$this->current_row[$field].'</a></label>';
} | Format expander.
@param string $field field name
@param array $column column configuration | entailment |
public function format_float($field)
{
$precision = 2;
$m = (float) $this->current_row[$field];
$this->current_row[$field] =
is_null($this->current_row[$field])
? '-'
: number_format($m, $precision);
$this->setTDParam($field, 'align', 'right');
$this->setTDParam($field, 'style/white-space', 'nowrap');
} | Format field as real number with 2 digit precision.
@param string $field | entailment |
public function format_boolean($field)
{
$value = $this->current_row[$field.'_original'];
$label = $this->current_row[$field];
if ($value === true || $value === 1 || $value === 'Y') {
$this->current_row_html[$field] =
'<div align=center>'.
'<i class="icon-check">'.($label!==$value ? $label : $this->app->_('yes')).'</i>'.
'</div>';
} else {
$this->current_row_html[$field] = '';
/*
$this->current_row_html[$field] =
'<div align=center>'.
'<i class="icon-check-empty">'.($label!==$value ? $label : $this->app->_('no')).'</i>'.
'</div>';
*/
}
} | Format field as boolean.
@param string $field | entailment |
public function format_money($field)
{
// use real number formatter
$this->format_real($field);
// negative values show in red color
if ($this->current_row[$field] < 0) {
$this->setTDParam($field, 'style/color', 'red');
} else {
$this->setTDParam($field, 'style/color', false);
}
} | Format field as money with 2 digit precision.
@param string $field | entailment |
public function format_object($field)
{
$this->current_row[$field] = (string) $this->current_row[$field];
return $this->format_shorttext($field);
} | Format field as object.
@param string $field | entailment |
public function format_json($field)
{
if (!is_scalar($this->current_row[$field])) {
$this->current_row[$field] = json_encode($this->current_row[$field]);
}
} | Format field by json encoding it.
@param string $field | entailment |
public function format_date($field)
{
if (!$this->current_row[$field]) {
$this->current_row[$field] = '-';
} else {
if (is_object($this->current_row[$field])) {
$this->current_row[$field] = $this->current_row[$field]->format(
$this->app->getConfig('locale/date', 'd/m/Y')
);
} else {
$this->current_row[$field] = date(
$this->app->getConfig('locale/date', 'd/m/Y'),
strtotime($this->current_row[$field])
);
}
}
} | Format field as date.
@param string $field | entailment |
public function format_time($field)
{
$this->current_row[$field] = date(
$this->app->getConfig('locale/time', 'H:i:s'),
strtotime($this->current_row[$field])
);
} | Format field as time.
@param string $field | entailment |
public function format_datetime($field)
{
$d = $this->current_row[$field];
if (!$d) {
$this->current_row[$field] = '-';
} else {
if ($d instanceof MongoDate) {
$this->current_row[$field] = date(
$this->app->getConfig('locale/datetime', 'd/m/Y H:i:s'),
$d->sec
);
} elseif (is_numeric($d)) {
$this->current_row[$field] = date(
$this->app->getConfig('locale/datetime', 'd/m/Y H:i:s'),
$d
);
} elseif ($d instanceof \DateTime) {
$this->current_row[$field] = $d->format($this->app->getConfig('locale/datetime', 'd/m/Y H:i:s'));
} else {
$d = strtotime($d);
$this->current_row[$field] = $d
? date(
$this->app->getConfig('locale/datetime', 'd/m/Y H:i:s'),
$d
)
: '-';
}
}
} | Format field as datetime.
@param string $field | entailment |
public function format_shorttext($field)
{
$text = $this->current_row[$field];
if (strlen($text) > 60) {
// Not sure about multi-byte support and execution speed of this
$a = explode(PHP_EOL, wordwrap($text, 28, PHP_EOL, true), 2);
$b = explode(PHP_EOL, wordwrap(strrev($text), 28, PHP_EOL, true), 2);
$text = $a[0].' ~~~ '.strrev($b[0]);
}
$this->current_row[$field] = $text;
$this->setTDParam(
$field,
'title',
$this->app->encodeHtmlChars(strip_tags($this->current_row[$field.'_original']), ENT_QUOTES)
);
} | Format shorttext field.
@param string $field | entailment |
public function format_checkbox($field)
{
$this->current_row_html[$field] =
'<input type="checkbox" '.
'id="cb_'.$this->current_id.'" '.
'name="cb_'.$this->current_id.'" '.
'value="'.$this->current_id.'" '.
($this->current_row['selected'] == 'Y'
? 'checked '
: ''
).
'/>';
$this->setTDParam($field, 'width', '10');
$this->setTDParam($field, 'align', 'center');
} | Format field as checkbox.
@param string $field | entailment |
public function init_button($field)
{
$this->on('click', '.do-'.$field)->univ()->ajaxec(array(
$this->app->url(),
$field => $a = $this->js()->_selectorThis()->data('id'),
$this->name.'_'.$field => $a,
));
/*
$this->columns[$field]['thparam'] .= ' style="width: 40px; text-align: center"';
$this->js(true)->find('.button_'.$field)->button();
*/
} | Initialize buttons column.
@param string $field | entailment |
public function format_button($field)
{
$class = $this->columns[$field]['button_class'];
$icon = $this->columns[$field]['icon'];
if ($icon) {
if ($icon[0] != '<') {
$icon = '<span class="icon-'.$icon.'"></span>';
}
$icon .= ' ';
}
$this->current_row_html[$field] =
'<button class="atk-button-small do-'.$field.' '.$class.'" data-id="'.$this->model->id.'">'.
$icon.$this->columns[$field]['descr'].
'</button>';
} | Format field as button.
@param string $field | entailment |
public function format_prompt($field)
{
$class = $this->columns[$field]['button_class'].' button_'.$field;
$icon = isset($this->columns[$field]['icon'])
? $this->columns[$field]['icon']
: '';
$message = 'Enter value: ';
$this->current_row_html[$field] =
'<button type="button" class="'.$class.'" '.
'onclick="value=prompt(\''.$message.'\');$(this).univ().ajaxec(\''.
$this->app->url(null, array(
$field => $this->current_id,
$this->name.'_'.$field => $this->current_id,
)).
'&value=\'+value)"'.
'>'.
$icon.
$this->columns[$field]['descr'].
'</button>';
} | Format field as prompt button.
@param string $field | entailment |
public function init_delete($field)
{
// set special CSS class for delete buttons to add some styling
$this->columns[$field]['button_class'] = 'atk-effect-danger atk-delete-button';
$this->columns[$field]['icon'] = 'trash';
// if this was clicked, then delete record
if ($id = $_GET[$this->name.'_'.$field]) {
// delete record
$this->_performDelete($id);
// show message
$this->js()->univ()
->successMessage('Deleted Successfully')
->reload()
->execute();
}
// move button column at the end (to the right)
$self = $this;
$this->app->addHook('post-init', function () use ($self, $field) {
if ($self->hasColumn($field)) {
$self->addOrder()->move($field, 'last')->now();
}
});
// ask for confirmation
$this->init_confirm($field);
} | Initialize column with delete buttons.
@param string $field | entailment |
public function _performDelete($id)
{
if ($this->model) {
$this->model->delete($id);
} else {
$this->dq->where('id', $id)->delete();
}
} | Delete record from DB.
Formatter init_delete() calls this to delete current record from DB
@param string $id ID of record | entailment |
public function setTemplate($template, $field = null)
{
if ($field === null) {
$field = $this->last_column;
}
/** @type GiTemplate $gi */
$gi = $this->add('GiTemplate');
$this->columns[$field]['template'] = $gi->loadTemplateFromString($template);
return $this;
} | This allows you to use Template.
@param string $template template as a string
@return $this | entailment |
public function format_template($field)
{
if (!($t = $this->columns[$field]['template'])) {
throw new BaseException('use setTemplate() for field '.$field);
}
$this->current_row_html[$field] = $t
->trySet('id', $this->current_id)
->set($this->current_row)
->trySet('_value_', $this->current_row[$field])
->render();
} | Format field using template.
@param string $field | entailment |
public function format_link($field)
{
$page = $this->columns[$field]['page'] ?: './'.$field;
$attr = $this->columns[$field]['id_field'] ?: 'id';
$this->current_row['_link'] =
$this->app->url($page, array($attr => $this->columns[$field]['id_value']
? ($this->model[$this->columns[$field]['id_value']]
?: $this->current_row[$this->columns[$field]['id_value'].'_original'])
: $this->current_id, ));
if (!$this->current_row[$field]) {
$this->current_row[$field] = $this->columns[$field]['descr'];
}
return $this->format_template($field);
} | Format field as link.
@param string $field | entailment |
public function addStickyArguments()
{
$sticky = $this->app->getStickyArguments();
$args = array();
if (is_array($sticky) && !empty($sticky)) {
foreach ($sticky as $key => $val) {
if ($val === true) {
if (isset($_GET[$key])) {
$val = $_GET[$key];
} else {
continue;
}
}
if (!isset($args[$key])) {
$args[$key] = $val;
}
}
}
$this->setArguments($args);
} | [private] add arguments set as sticky through APP | entailment |
public function isCurrent($inc_parent = false, $inc_args = false)
{
// strict match with arguments
if ($inc_args) {
return $this->app->url()->getURL() == $this->getURL();
}
// match current page or parent page without arguments
return $this->_current || ($inc_parent && $this->_current_sub);
} | Detects if the URL matches current page.
If $inc_parent is set to true, then it will also try to match sub-pages.
If $inc_args is set to true then it will also try to match arguments.
@param bool $inc_parent
@param bool $inc_args
@return bool | entailment |
public function setPage($page = null)
{
// The following argument formats are supported:
//
// null = set current page
// '.' = set current page
// 'page' = sets webroot/page.html
// './page' = set page relatively to current page
// '..' = parent page
// '../page' = page besides our own (foo/bar -> foo/page)
// 'index' = properly points to the index page defined in APP
// '/admin/' = will not be converted
/** @type $this->app App_Web */
$destination = '';
if (is_null($page)) {
$page = '.';
}
foreach (explode('/', $page) as $component) {
if ($component == '') {
continue;
}
if ($component == '.' && $destination == '') {
if ($this->app->page == 'index') {
continue;
}
$destination = str_replace('_', '/', $this->app->page);
continue;
}
if ($component == '..') {
if (!$destination) {
$destination = str_replace('_', '/', $this->app->page);
}
$tmp = explode('/', $destination);
array_pop($tmp);
$destination = implode('/', $tmp);
continue;
}
if ($component == 'index' && $destination == '') {
$destination = $this->app->index_page;
continue;
}
$destination = $destination ? $destination.'/'.$component : $component;
}
if ($destination === '') {
$destination = @$this->app->index_page;
}
$this->page = $destination;
// check if it's current page
list($p, $ap) = str_replace('/', '_', array($this->page, $this->app->page));
$this->_current = ($p == $ap); // page exactly match
$this->_current_sub = ($p == substr($ap, 0, strlen($p)) && isset($ap[strlen($p)]) && $ap[strlen($p)] == '_'); // first part of page match followed by separator
return $this;
} | [private] automatically called with 1st argument of $app->url() | entailment |
public function set($argument, $value = null)
{
if (!is_array($argument)) {
$argument = array($argument => $value);
}
return $this->setArguments($argument);
} | Set additional arguments | entailment |
public function setArguments($arguments = array())
{
// add additional arguments
if (!$arguments) {
$arguments = array();
}
if (!is_array($arguments)) {
throw new BaseException('Arguments must be always an array');
}
$this->arguments = $args = array_merge($this->arguments, $arguments);
foreach ($args as $arg => $val) {
if (is_null($val)) {
unset($this->arguments[$arg]);
}
}
return $this;
} | Set arguments to specified array.
@param array $arguments
@return $this | entailment |
public function init()
{
$this->connect();
$this->tmpFile();
$this->open($this->temp, 'wb');
$this->getTables();
$this->lock();
$this->dump();
$this->unlock();
$this->close();
$this->move();
} | {@inheritdoc} | entailment |
protected function escape($value)
{
if ($value === null) {
return 'NULL';
}
if (is_integer($value) || is_float($value)) {
return $value;
}
return $this->pdo->quote($value);
} | Escapes a value for a use in a SQL statement.
@param mixed $value
@return string | entailment |
protected function dump()
{
$this->write('-- '.date('c').' - '.$this->config->dsn, false);
if ($this->config->disableAutoCommit === true) {
$this->write('SET AUTOCOMMIT = 0');
}
if ($this->config->disableForeignKeyChecks === true) {
$this->write('SET FOREIGN_KEY_CHECKS = 0');
}
if ($this->config->disableUniqueKeyChecks === true) {
$this->write('SET UNIQUE_CHECKS = 0');
}
if ($this->config->createDatabase) {
if ($this->config->createDatabase === true) {
$database = $this->database;
} else {
$database = (string) $this->config->createDatabase;
}
$this->write(
'CREATE DATABASE IF NOT EXISTS `'.$database.'` '.
'DEFAULT CHARACTER SET = '.$this->escape($this->config->encoding)
);
$this->write('USE `'.$database.'`');
}
$this->dumpTables();
$this->dumpViews();
$this->dumpTriggers();
$this->dumpEvents();
if ($this->config->disableForeignKeyChecks === true) {
$this->write('SET FOREIGN_KEY_CHECKS = 1');
}
if ($this->config->disableUniqueKeyChecks === true) {
$this->write('SET UNIQUE_CHECKS = 1');
}
if ($this->config->disableAutoCommit === true) {
$this->write('COMMIT');
$this->write('SET AUTOCOMMIT = 1');
}
$this->write("\n-- Completed on: ".date('c'), false);
} | Dumps database contents to a temporary file. | entailment |
protected function dumpTables()
{
$this->tables->execute();
foreach ($this->tables->fetchAll(\PDO::FETCH_ASSOC) as $a) {
$table = current($a);
if (isset($a['Table_type']) && $a['Table_type'] === 'VIEW') {
continue;
}
if (in_array($table, (array) $this->config->ignore, true)) {
continue;
}
if ((string) $this->config->prefix !== '' && strpos($table, $this->config->prefix) !== 0) {
continue;
}
if ($this->config->structure === true) {
$structure = $this->pdo->query('SHOW CREATE TABLE `'.$table.'`')->fetch(\PDO::FETCH_ASSOC);
$this->write("\n-- Table structure for table `{$table}`\n", false);
$this->write('DROP TABLE IF EXISTS `'.$table.'`');
$this->write(end($structure));
}
if ($this->config->data === true) {
$this->write("\n-- Dumping data for table `{$table}`\n", false);
$this->write("LOCK TABLES `{$table}` WRITE");
if (isset($this->config->select[$table])) {
$query = $this->config->select[$table];
} else {
$query = 'SELECT * FROM `'.$table.'`';
}
$rows = $this->pdo->prepare($query);
$rows->execute();
while ($a = $rows->fetch(\PDO::FETCH_ASSOC)) {
$this->write(
"INSERT INTO `{$table}` VALUES (".
implode(',', array_map(array($this, 'escape'), $a)).
")"
);
}
$this->write('UNLOCK TABLES');
}
}
} | Dumps tables.
@since 2.5.0 | entailment |
protected function dumpViews()
{
$this->tables->execute();
foreach ($this->tables->fetchAll(\PDO::FETCH_ASSOC) as $a) {
$view = current($a);
if (!isset($a['Table_type']) || $a['Table_type'] !== 'VIEW') {
continue;
}
if (in_array($view, (array) $this->config->ignore, true)) {
continue;
}
if ((string) $this->config->prefix !== '' && strpos($view, $this->config->prefix) !== 0) {
continue;
}
$structure = $this->pdo->query('SHOW CREATE VIEW `'.$view.'`');
if ($structure = $structure->fetch(\PDO::FETCH_ASSOC)) {
if (isset($structure['Create View'])) {
$this->write("\n-- Structure for view `{$view}`\n", false);
$this->write('DROP VIEW IF EXISTS `'.$view.'`');
$this->write($structure['Create View']);
}
}
}
} | Dumps views.
@since 2.5.0 | entailment |
protected function dumpTriggers()
{
if ($this->config->triggers === true && version_compare($this->version, '5.0.10') >= 0) {
$triggers = $this->pdo->prepare('SHOW TRIGGERS');
$triggers->execute();
while ($a = $triggers->fetch(\PDO::FETCH_ASSOC)) {
if (in_array($a['Table'], (array) $this->config->ignore, true)) {
continue;
}
if ((string) $this->config->prefix !== '' && strpos($a['Table'], $this->config->prefix) !== 0) {
continue;
}
$this->write("\n-- Trigger structure `{$a['Trigger']}`\n", false);
$this->write('DROP TRIGGER IF EXISTS `'.$a['Trigger'].'`');
$query = "CREATE TRIGGER `{$a['Trigger']}`".
" {$a['Timing']} {$a['Event']} ON `{$a['Table']}`".
" FOR EACH ROW\n{$a['Statement']}";
$delimiter = $this->getDelimiter('//', $query);
$this->write("DELIMITER {$delimiter}\n{$query}\n{$delimiter}\nDELIMITER ;", false);
}
}
} | Dumps triggers.
@since 2.5.0 | entailment |
protected function dumpEvents()
{
if ($this->config->events === true && version_compare($this->version, '5.1.12') >= 0) {
$events = $this->pdo->prepare('SHOW EVENTS');
$events->execute();
foreach ($events->fetchAll(\PDO::FETCH_ASSOC) as $a) {
$event = $a['Name'];
if (in_array($event, (array) $this->config->ignore, true)) {
continue;
}
if ((string) $this->config->prefix !== '' && strpos($event, $this->config->prefix) !== 0) {
continue;
}
$structure = $this->pdo->query('SHOW CREATE EVENT `'.$event.'`');
if ($structure = $structure->fetch(\PDO::FETCH_ASSOC)) {
if (isset($structure['Create Event'])) {
$query = $structure['Create Event'];
$delimiter = $this->getDelimiter('//', $query);
$this->write("\n-- Structure for event `{$event}`\n", false);
$this->write('DROP EVENT IF EXISTS `'.$event.'`');
$this->write("DELIMITER {$delimiter}\n{$query}\n{$delimiter}\nDELIMITER ;", false);
}
}
}
}
} | Dumps events.
@since 2.7.0 | entailment |
public function setterGetter($type, $value = UNDEFINED)
{
if ($value === UNDEFINED) {
return isset($this->$type) ? $this->$type : null;
}
$this->$type = $value;
return $this;
} | Implementation of generic setter-getter method which supports "UNDEFINED"
constant. This method is used by all other sette-getters.
@param string $type Corresponds to the name of property of a field
@param mixed $value New value for a property.
@return mixed|$this new or current property (if value is UNDEFINED) | entailment |
public function listData($t = UNDEFINED)
{
if ($this->type() === 'boolean' && $t !== UNDEFINED) {
$this->owner->addHook('afterLoad,afterUpdate,afterInsert', function ($m) use ($t) {
// Normalize boolean data
$val = !array_search($m->data[$this->short_name], $t);
if ($val === false) {
return;
} // do nothing
$m->data[$this->short_name] = (boolean) $val;
});
$this->owner->addHook('beforeUpdate,beforeInsert', function ($m, &$data) use ($t) {
// De-Normalize boolean data
$val = (int) (!$m->get($this->short_name));
if (!isset($t[$val])) {
return;
} // do nothing
$data->set($this->short_name, $t[$val]);
});
}
return $this->setterGetter('listData', $t);
} | Supplies a list data for multi-value fields (selects, radio buttons,
checkbox area, autocomplete). You may also use enum(). This setting
is typically used with a static falues (Male / Female), if your field
values could be described through a different model, use setModel()
or better yet - hasOne().
@param array $t Array( id => val )
@return array|$this current value if $t=UNDEFINED | entailment |
public function from($m = UNDEFINED)
{
if ($m === UNDEFINED) {
return $this->relation;
} elseif (is_object($m)) {
$this->relation = $m;
} else {
$this->relations = $this->owner->relations[$m];
}
return $this;
} | Binds the field to a relation (returned by join() function).
@param mixed $m the result of join() function
@return $this|object or the relation if $m is UNDEFINED | entailment |
public function updateSelectQuery($select)
{
$p = null;
if (!empty($this->owner->relations)) {
$p = $this->owner->table_alias ?: $this->owner->table;
}
if ($this->relation) {
$select->field($this->actual_field ?: $this->short_name, $this->relation->short_name, $this->short_name);
} elseif (!(is_null($this->actual_field)) && $this->actual_field != $this->short_name) {
$select->field($this->actual_field, $p, $this->short_name);
return $this;
} else {
$select->field($this->short_name, $p);
}
return $this;
} | Modifies specified query to include this particular field.
@param DB_dsql $select
@return $this | entailment |
public function updateInsertQuery($insert)
{
if ($this->relation) {
$insert = $this->relation->dsql;
}
$insert->set(
$this->actual_field ?: $this->short_name,
$this->getSQL()
);
return $this;
} | Modify insert query to set value of this field.
@param DB_dsql $insert
@return $this | entailment |
public function updateModifyQuery($modify)
{
if ($this->relation) {
$modify = $this->relation->dsql;
}
$modify->set(
$this->actual_field ?: $this->short_name,
$this->getSQL()
);
return $this;
} | Modify update query to set value of this field.
@param DB_dsql $modify
@return $this | entailment |
public function getSQL()
{
$val = $this->owner->get($this->short_name);
if ($this->type == 'boolean') {
$val = $this->getBooleanValue($val);
}
if ($val == ''
&& !$this->mandatory
&& ($this->listData || $this instanceof Field_Reference)
&& $this->type != 'boolean'
) {
$val = null;
}
return $val;
} | Get value of this field formatted for SQL. Redefine if you need to convert.
@return mixed | entailment |
public function getExpr()
{
$q = $this->owner->_dsql();
return $q->bt($this->relation ? $this->relation->short_name : $q->main_table).'.'.
$q->bt($this->actual_field ?: $this->short_name);
} | Returns field of this model.
@return string | entailment |
public function init()
{
parent::init();
// setup user menu
if ($this->template->hasTag('UserMenu')) {
if (isset($this->app->auth)) {
$this->user_menu = $this->add('Menu_Horizontal', null, 'UserMenu');
/** @type Menu_Horizontal $this->user_menu */
$this->user_menu->addMenu($this->app->auth->model[$this->app->auth->model->title_field]);
$this->user_menu->addItem('Logout', 'logout');
} else {
$this->template->tryDel('UserMenu');
$this->template->tryDel('user_icon');
}
}
} | Initialization. | entailment |
public function addHeader($class = 'Menu_Objective')
{
$this->header_wrap = $this->add('View', null, 'Header', array('layout/fluid', 'Header'));
/** @type View $this->header_wrap */
$this->header = $this->header_wrap->add($class, null, 'Header_Content');
return $this->header;
} | Adds header.
@param string $class
@return View | entailment |
public function loadCurrent($model, &$cursor)
{
$model->data = array_shift($cursor);
$model->id = $model->data[$model->id_field];
} | Load next data row from cursor. | entailment |
public function addField($n, $actual_field = null)
{
$f = $this->owner->addField($n, $actual_field)->from($this);
return $f;
} | Second argument to addField() will specify how the field is really called | entailment |
public function set($foreign_table, $master_field = null, $join_kind = null, $relation = null)
{
// http://dev.mysql.com/doc/refman/5.0/en/join.html
$join_types = array(
'left', 'right', 'inner', 'cross', 'natural',
'left outer', 'right outer', 'natural left',
'natural right', 'natural left outer', 'natural right outer'
);
if ($join_kind && !in_array(strtolower($join_kind), $join_types)) {
throw $this->exception('Specify reasonable SQL join type.')
->addMoreInfo('Specified', $join_kind)
->addMoreInfo('Allowed', implode(', ', $join_types));
}
$this->relation = $relation;
// Split and deduce fields
list($f1, $f2) = explode('.', $foreign_table, 2);
$m1 = $m2 = null;
if (is_object($master_field)) {
$this->expr = $master_field;
} else {
$m1 = $this->relation ?: $this->owner;
$m1 = $m1->table_alias ?: $m1->table;
// Split and deduce primary table
$m2 = $master_field;
// Identify fields we use for joins
if (is_null($f2) && is_null($m2)) {
$m2 = $f1.'_id';
}
if (is_null($m2)) {
$m2 = $this->owner->id_field;
}
$this->f1 = $f1;
$this->m1 = $m1;
$this->m2 = $m2;
}
if (is_null($f2)) {
$f2 = 'id';
}
$this->f2 = $f2;
$this->t = $join_kind ?: 'inner';
$this->fa = $this->short_name;
// Use the real ID field as defined by the model as default
$this->owner->_dsql()->join($foreign_table, $this->expr ?: ($m1.'.'.$m2), $this->t, $this->short_name);
// If our ID field is NOT used, must insert record in OTHER table first and use their primary value in OUR field
if ($this->m2 && $this->m2 != $this->owner->id_field) {
// user.contactinfo_id = contactinfo.id
$this->owner->addHook('beforeInsert', array($this, 'beforeInsert'), array(), -5);
$this->owner->addHook('beforeModify', array($this, 'beforeModify'), array(), -5);
$this->owner->addHook('afterDelete', array($this, 'afterDelete'), array(), -5);
} elseif ($this->m2) {
// author.id = book.author_id
$this->owner->addHook('afterInsert', array($this, 'afterInsert'));
$this->owner->addHook('beforeModify', array($this, 'beforeModify'));
$this->owner->addHook('beforeDelete', array($this, 'beforeDelete'));
}// else $m2 is not set, expression is used, so don't try to do anything unnecessary
$this->owner->addHook('beforeSave', array($this, 'beforeSave'));
$this->owner->addHook('beforeLoad', array($this, 'beforeLoad'));
$this->owner->addHook('afterLoad', array($this, 'afterLoad'));
return $this;
} | TODO: hasMany() | entailment |
public function beforeLoad($m, $q = null)
{
if (is_null($q)) {
return;
} // manual load
if ($this->m2 && $this->m2 != $this->owner->id_field) {
$q->field($this->m2, $this->m1, $this->short_name);
} elseif ($this->m2) {
$q->field($this->f2, $this->fa ?: $this->f1, $this->short_name);
}
} | Add query for the relation's ID, but then remove it from results. Remove ID when unloading. | entailment |
public function setSource($model, $data)
{
$this->app->initializeSession();
if ($data === UNDEFINED || $data === null) {
$data = '-';
}
if (!$_SESSION['ctl_data'][$data]) {
$_SESSION['ctl_data'][$data] = array();
}
if (!$_SESSION['ctl_data'][$data][$model->table]) {
$_SESSION['ctl_data'][$data][$model->table] = array();
}
$model->_table[$this->short_name] = &$_SESSION['ctl_data'][$data][$model->table];
} | }}} | entailment |
public function init()
{
parent::init();
if (!$this->template->hasTag($this->item_tag)) {
if (@$this->app->compat_42 && $this instanceof Menu_Basic) {
// look for MenuItem
$default = $this->item_tag;
$this->item_tag = 'MenuItem';
$this->container_tag = 'Item';
if (!$this->template->hasTag($this->item_tag)) {
throw $this->template->exception('Template must have "'.$default.'" tag')
->addMoreInfo('compat', 'Also tried for compatibility reason "'.$this->item_tag.'" tag');
}
} else {
throw $this->template->exception('Template must have "'.$this->item_tag.'" tag');
}
}
$this->row_t = $this->template->cloneRegion($this->item_tag);
if ($this->template->hasTag('sep')) {
$this->sep_html = $this->template->get('sep');
}
} | Initialization.
@retun void | entailment |
public function addGrandTotals($fields = UNDEFINED)
{
if (!$this->getIterator() instanceof SQL_Model) {
throw $this->exception('Grand Totals can be used only with SQL_Model data source');
}
return $this->_addTotals($fields, 'onRequest');
} | Enable totals calculation for specified array of fields.
If particular fields not specified, then all field totals are calculated.
If you only need to count records, then pass null and no fields will be calculated.
Be aware that this method works ONLY for SQL models set as data source
because this calculates grand totals using DSQL.
@param array $fields optional array of fieldnames
@return $this | entailment |
protected function _addTotals($fields = UNDEFINED, $type = null)
{
// set type
$this->totals_type = $type;
// clone template chunk for totals
if ($this->template->hasTag('totals')) {
$this->totals_t = $this->template->cloneRegion('totals');
}
// if no fields defined then get available fields from model
$iter = $this->getIterator();
if ($fields === UNDEFINED && $iter->hasMethod('getActualFields')) {
$fields = $iter->getActualFields();
}
// reset field totals
if ($this->totals === false) {
$this->totals = array();
}
if (is_array($fields)) {
foreach ($fields as $field) {
$this->totals[$field] = 0;
}
}
return $this;
} | Private method to enable / disable totals calculation for specified array
of fields.
If particular fields not specified, then all field totals are calculated.
If you only need to count records, then pass null and no fields will be calculated.
@param array $fields optional array of fieldnames
@param string $type type of totals calculation (null|onRender|onRequest)
@return $this | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.