sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
public function applyRules($field, $ruleset)
{
// Save previous values, just in case
$acc = $this->acc;
$crs = $this->current_ruleset;
$this->bail_out = false;
$this->acc = $this->get($field);
$this->current_ruleset = $ruleset;
while (!is_null($rule = $this-... | This is the main body for rule processing. | entailment |
public function init()
{
$this->app->page_object = $this;
$this->template->trySet('_page', $this->short_name);
if (method_exists($this, get_class($this))) {
throw $this->exception('Your sub-page name matches your page class name. '.
'PHP will assume that your met... | }}} | entailment |
public function defaultTemplate()
{
if (isset($_GET['cut_page'])) {
return array('page');
}
$page_name = 'page/'.strtolower($this->short_name);
// See if we can locate the page
try {
$p = $this->app->locate('template', $page_name.'.html');
} c... | Set default template
@return array|string | entailment |
public function prefetchAll($model)
{
$d = $this->d($model);
$dirs = $this->app->pathfinder->search($d[0], $d['path_prefix'], 'path');
$colls = array();
foreach ($dirs as $dir) {
// folder will contain collections
$dd = dir($dir);
while (false !=... | TODO: testing | entailment |
public function setBodyType($type)
{
if ($type == 'html' || $type == 'text' || $type = 'both') {
$this->body_type = $type;
} else {
throw new Exception_TMail("Unsupported body type: $type");
}
return $this;
} | Sets the body type. Possible values:
- text: plain text
- html: HTML only
- both: text and HTML. | entailment |
public function getBody()
{
// first we should render the body if it was not rendered before
if (is_null($this->body)) {
$this->set('body', '');
// this is unnormal situation, notifying developer
$this->app->logger->logLine('Email body is null: '.$this->get('from'... | Returns the rendered mail body, sign included. | entailment |
public function setBody($body)
{
if (is_object($body)) {
throw new Exception_TMail('Body cannot be an object');
}
switch ($this->body_type) {
case 'text':
$this->plain_text = $body;
break;
case 'html':
$this-... | Sets the body of the message.
Behaviour of this method depends on the body type specified with setBodyType():
- text: plain text mime part is set
- html: html mime part only is set
- both: html mime part only is set, text part should be added separately.
This method does NOT accept SMlite object as a parameter. | entailment |
public function attachFile($file, $type, $name = null, $asstring = false)
{
$content = $asstring ? $file : file_get_contents($file);
if (!$content) {
throw new Exception_TMail('Error reading attachment: '.($asstring ? $name : $file));
}
if (is_null($name)) {
i... | Attaches a saved file.
@param $file any valid path to a file
@param $type valid mime type. e.g.:
audio/mpeg
image/jpeg
application/zip
audio/wav
etc.
@param $name optional, sets the filename for message
@param $asstring if set to true, $file contains contents, not filename | entailment |
public function send($address, $add_params = null)
{
if (is_array($address)) {
foreach ($address as $a) {
$this->send($a, $add_params);
}
return;
}
// checking if from is set
if (!$this->get('from')) {
$this->set('from'... | Does the actual send by calling mail() function. | entailment |
public function init()
{
parent::init();
if (! $this->owner->model instanceof \atk4\data\Model) {
throw $this->exception('Controller_ADForm can only be used with Agile Data \atk4\data\Model models');
}
} | Initialization. | entailment |
public function importFields($model, $fields = null)
{
$this->model = $model;
$this->form = $this->owner;
if ($fields === false) {
return;
}
if (!$fields) {
if ($model->only_fields) {
$fields = $model->only_fields;
} else ... | Import model fields in form.
Use $fields === false if you want to associate form with model, but don't create form fields.
@param \atk4\data\Model $model
@param array|string|bool $fields
@return void|$this | entailment |
public function importField($field, $field_name = null)
{
$field = $this->model->hasElement($field);
/** @type \atk4\data\Field $field */
if (!$field || !$field->isEditable() || $field->isHidden()) {
return;
}
if ($field_name === null) {
$field_name ... | Import one field from model into form.
@param string $field
@param string $field_name
@return void|Form_Field | entailment |
public function setFields()
{
foreach ($this->field_associations as $form_field => $model_field) {
$this->form->set($form_field, $model_field->get());
}
} | Copies model field values into form. | entailment |
public function getFieldType($field)
{
$type = 'Line';
// if form field type explicitly set in models UI properties
if (isset($field->ui['display'])) {
$tmp = $field->ui['display'];
if (isset($tmp['form'])) {
$tmp = $tmp['form'];
}
... | Returns form field 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 update($form)
{
$models = $this->getFields();
foreach ($models as $model) {
$model->save();
}
} | Update form model
@param Form $form | entailment |
public function render()
{
if (!isset($this->options['icons']['secondary'])) {
$this->options['icons']['secondary'] = $this->js_triangle_class;
}
parent::render();
} | Render button. | entailment |
public function join(
$foreignTable,
$leftField = null,
$joinKind = null,
$joinAlias = null,
$relation = null,
$behaviour = 'cascade'
) {
list($rightTable, $rightField) = explode('.', $foreignTable, 2);
if (is_null($rightField)) {
$rightFie... | See Field_SQL_Relation. | entailment |
protected function createCallfireDriver()
{
$config = $this->app['config']->get('sms.callfire', []);
$provider = new CallFireSMS(
new Client(),
$config['app_login'],
$config['app_password']
);
return $provider;
} | Create an instance of the CallFire driver.
@return CallFireSMS | entailment |
protected function createEztextingDriver()
{
$config = $this->app['config']->get('sms.eztexting', []);
$provider = new EZTextingSMS(new Client());
$data = [
'User' => $config['username'],
'Password' => $config['password'],
];
$provider->buildBod... | Create an instance of the EZTexting driver.
@return EZTextingSMS | entailment |
protected function createLabsMobileDriver()
{
$config = $this->app['config']->get('sms.labsmobile', []);
$provider = new LabsMobileSMS(new Client());
$auth = [
'username' => $config['username'],
'password' => $config['password'],
];
$provider->build... | Create an instance of the LabsMobile driver.
@return LabsMobileSMS | entailment |
protected function createMozeoDriver()
{
$config = $this->app['config']->get('sms.mozeo', []);
$provider = new MozeoSMS(new Client());
$auth = [
'companykey' => $config['company_key'],
'username' => $config['username'],
'password' => $config['passwor... | Create an instance of the Mozeo driver.
@return MozeoSMS | entailment |
protected function createNexmoDriver()
{
$config = $this->app['config']->get('sms.nexmo', []);
$provider = new NexmoSMS(
new Client(),
$config['api_key'],
$config['api_secret']
);
return $provider;
} | Create an instance of the nexmo driver.
@return NexmoSMS | entailment |
protected function createTwilioDriver()
{
$config = $this->app['config']->get('sms.twilio', []);
return new TwilioSMS(
new \Services_Twilio($config['account_sid'], $config['auth_token']),
$config['auth_token'],
$this->app['request']->url(),
$config['v... | Create an instance of the Twillo driver.
@return TwilioSMS | entailment |
protected function createZenviaDriver()
{
$config = $this->app['config']->get('sms.zenvia', []);
$provider = new ZenviaSMS(
new Client(),
$config['account_key'],
$config['passcode'],
$config['callbackOption']
);
return $provi... | Create an instance of the Zenvia driver.
@return ZenviaSMS | entailment |
protected function createPlivoDriver()
{
$config = $this->app['config']->get('sms.plivo', []);
$provider = new PlivoSMS(
$config['auth_id'],
$config['auth_token']
);
return $provider;
} | Create an instance of the Plivo driver.
@return PlivoSMS | entailment |
protected function createFlowrouteDriver()
{
$config = $this->app['config']->get('sms.flowroute', []);
$provider = new FlowrouteSMS(
new Client(),
$config['access_key'],
$config['secret_key']
);
return $provider;
} | Create an instance of the flowroute driver.
@return FlowrouteSMS | entailment |
protected function createSms77Driver()
{
$config = $this->app['config']->get('sms.sms77', []);
$provider = new SMS77(
new Client(),
$config['user'],
$config['api_key'],
$config['debug']
);
return $provider;
} | Create an instance of the SMS77 driver.
@return SMS77 | entailment |
protected function _write($data) {
if (!$this->connected) {
$message = 'No connecting found while writing data to socket.';
throw new RuntimeException($message);
}
$data .= "\r\n";
return fwrite($this->_connection, $data, strlen($data));
} | Writes a packet to the socket. Prior to writing to the socket will
check for availability of the connection.
@param string $data
@return integer|boolean number of written bytes or `false` on error. | entailment |
protected function _read($length = null) {
if (!$this->connected) {
$message = 'No connection found while reading data from socket.';
throw new RuntimeException($message);
}
if ($length) {
if (feof($this->_connection)) {
return false;
}
$data = stream_get_contents($this->_connection, $length + ... | Reads a packet from the socket. Prior to reading from the socket
will check for availability of the connection.
@param integer $length Number of bytes to read.
@return string|boolean Data or `false` on error. | entailment |
public function put($pri, $delay, $ttr, $data) {
$this->_write(sprintf("put %d %d %d %d\r\n%s", $pri, $delay, $ttr, strlen($data), $data));
$status = strtok($this->_read(), ' ');
switch ($status) {
case 'INSERTED':
case 'BURIED':
return (integer) strtok(' '); // job id
case 'EXPECTED_CRLF':
case ... | The `put` command is for any process that wants to insert a job into the queue.
@param integer $pri Jobs with smaller priority values will be scheduled
before jobs with larger priorities. The most urgent priority is
0; the least urgent priority is 4294967295.
@param integer $delay Seconds to wait before putting the jo... | entailment |
public function useTube($tube) {
$this->_write(sprintf('use %s', $tube));
$status = strtok($this->_read(), ' ');
switch ($status) {
case 'USING':
return strtok(' ');
default:
$this->_error($status);
return false;
}
} | The `use` command is for producers. Subsequent put commands will put
jobs into the tube specified by this command. If no use command has
been issued, jobs will be put into the tube named `default`.
@param string $tube A name at most 200 bytes. It specifies the tube to
use. If the tube does not exist, it will be create... | entailment |
public function pauseTube($tube, $delay) {
$this->_write(sprintf('pause-tube %s %d', $tube, $delay));
$status = strtok($this->_read(), ' ');
switch ($status) {
case 'PAUSED':
return true;
case 'NOT_FOUND':
default:
$this->_error($status);
return false;
}
} | Pause a tube delaying any new job in it being reserved for a given time.
@param string $tube The name of the tube to pause.
@param integer $delay Number of seconds to wait before reserving any more
jobs from the queue.
@return boolean `false` on error otherwise `true`. | entailment |
public function bury($id, $pri) {
$this->_write(sprintf('bury %d %d', $id, $pri));
$status = $this->_read();
switch ($status) {
case 'BURIED':
return true;
case 'NOT_FOUND':
default:
$this->_error($status);
return false;
}
} | Puts a job into the `buried` state Buried jobs are put into a FIFO
linked list and will not be touched until a client kicks them.
@param integer $id The id of the job.
@param integer $pri *New* priority to assign to the job.
@return boolean `false` on error, `true` on success. | entailment |
public function watch($tube) {
$this->_write(sprintf('watch %s', $tube));
$status = strtok($this->_read(), ' ');
switch ($status) {
case 'WATCHING':
return (integer) strtok(' ');
default:
$this->_error($status);
return false;
}
} | Adds the named tube to the watch list for the current connection.
@param string $tube Name of tube to watch.
@return integer|boolean `false` on error otherwise number of tubes in watch list. | entailment |
protected function _peekRead() {
$status = strtok($this->_read(), ' ');
switch ($status) {
case 'FOUND':
return [
'id' => (integer) strtok(' '),
'body' => $this->_read((integer) strtok(' '))
];
case 'NOT_FOUND':
default:
$this->_error($status);
return false;
}
} | Handles response for all peek methods.
@return string|boolean `false` on error otherwise the body of the job. | entailment |
public function kick($bound) {
$this->_write(sprintf('kick %d', $bound));
$status = strtok($this->_read(), ' ');
switch ($status) {
case 'KICKED':
return (integer) strtok(' ');
default:
$this->_error($status);
return false;
}
} | Moves jobs into the ready queue (applies to the current tube).
If there are buried jobs those get kicked only otherwise delayed
jobs get kicked.
@param integer $bound Upper bound on the number of jobs to kick.
@return integer|boolean False on error otherwise number of jobs kicked. | entailment |
public function listTubeUsed() {
$this->_write('list-tube-used');
$status = strtok($this->_read(), ' ');
switch ($status) {
case 'USING':
return strtok(' ');
default:
$this->_error($status);
return false;
}
} | Returns the tube currently being used by the producer.
@return string|boolean `false` on error otherwise a string with the name of the tube. | entailment |
protected function _statsRead($decode = true) {
$status = strtok($this->_read(), ' ');
switch ($status) {
case 'OK':
$data = $this->_read((integer) strtok(' '));
return $decode ? $this->_decode($data) : $data;
default:
$this->_error($status);
return false;
}
} | Handles responses for all stat methods.
@param boolean $decode Whether to decode data before returning it or not. Default is `true`.
@return array|string|boolean `false` on error otherwise statistical data. | entailment |
protected function _decode($data) {
$data = array_slice(explode("\n", $data), 1);
$result = [];
foreach ($data as $key => $value) {
if ($value[0] === '-') {
$value = ltrim($value, '- ');
} elseif (strpos($value, ':') !== false) {
list($key, $value) = explode(':', $value);
$value = ltrim($value,... | Decodes YAML data. This is a super naive decoder which just works on
a subset of YAML which is commonly returned by beanstalk.
@param string $data The data in YAML format, can be either a list or a dictionary.
@return array An (associative) array of the converted data. | entailment |
public function exec($cmd, $args = array())
{
// Arguments must be safe
if (!is_array($args)) {
$args = array($args);
}
foreach ($args as $val) {
if (!is_string($val)) {
throw new BaseException('You must specify arguments as strings');
... | Execute the process and associate with this object.
@param string $cmd Command to be executed
@param array|string $args Arguments (strings)
@return self | entailment |
protected function executeRaw($command)
{
$pipes = null;
$this->process = proc_open($command, $this->descriptorspec, $pipes);
if (!is_resource($this->process)) {
throw new Exception_SystemProcessIO('Failed to execute');
}
$this->debug('Execute successful');
... | This function just executes command and returns hash of descriptors.
Hash will have keys 'in', 'out' and 'err'.
This is a handy function to override if you are piping input and
output through sockets (such as SSH connection)
@param string $command raw and proprely escaped command
@return array of pipes | entailment |
public function write($str)
{
if (!is_resource($this->pipes['in'])) {
throw new Exception_SystemProcessIO("stdin is closed or haven't been opened. Cannot write to process");
}
$this->debug('writing '.$str.'+newline into stdin');
fwrite($this->pipes['in'], $str."\n");
... | Sends string to process, but process will wait for more input. Always
adds newline at the end.
@param string $str any input data.
@return self | entailment |
public function writeAll($str)
{
if (substr($str, -1) == "\n") {
$str = substr($str, 0, -1);
}
$this->write($str);
$this->close('in');
$this->debugStatus();
return $this;
} | Similar to write but will send EOF after sending text.
Also makes sure your list do not end with endline (because write
adds it).
@param string $str any input data.
@return self | entailment |
public function readLine($res = 'out')
{
$str = fgets($this->pipes[$res]);
if (substr($str, -1) == "\n") {
$str = substr($str, 0, -1);
}
return $str;
} | Reads one line of output. Careful - if no output is provided it
this function will be waiting.
@param string $res optional descriptor (either out or err)
@return self | entailment |
public function readAll($res = 'out')
{
$str = '';
$this->debugStatus();
$this->debug('reading all output');
//stream_set_blocking($this->pipes[$res],0);
$str = stream_get_contents($this->pipes[$res]);
$this->close($res);
if (substr($str, -1) != "\n") {
... | Reads all output and returns. Closes stdout when EOF reached.
@param string $res optional descriptor (out or err)
@return self | entailment |
public function terminate($sig = null)
{
// Terminates application without reading anything more.
foreach ($this->pipes as $key => $res) {
$this->close($key);
}
$this->debug('process terminated');
proc_terminate($this->process, $sig);
} | Closing IO and terminating.
@param int $sig Unix signal | entailment |
public function close($res = null)
{
if (is_null($res)) {
$this->debug('closing ALL streams, starting with IN');
$this->close('in');
$this->debug('Reading all data from OUT');
// Read remaining of stdout if not read
if (!feof($this->pipes['out']))... | This function will finish reading from in/err streams
and will close all streams. If you are doing your
own reading line-by-line or you want to terminate
application without reading all of it's output -
use terminate() instead;. | entailment |
public function set($model, $their_field = null, $our_field = null, $relation = null)
{
$this->model_name = is_string($model) ? $model : get_class($model);
$this->model_name = $this->app->normalizeClassName($this->model_name, 'Model');
if ($relation) {
$this->relation = $relatio... | }}} | entailment |
public function register()
{
Request::macro('isXml', function () {
return strtolower($this->getContentType()) === 'xml';
});
Request::macro('xml', function ($assoc = true) {
if (!$this->isXml() || !$content = $this->getContent()) {
return $assoc ? [] ... | Register the application services.
@return void | entailment |
public function init()
{
parent::init();
$this->addClass('atk-effect-danger');
$this->template->set('label', $this->app->_('Error').': ');
$this->addIcon('attention');
} | Initialization | entailment |
public function connect($dsn = null)
{
if ($dsn === null) {
$dsn = 'dsn';
}
if (is_string($dsn)) {
$new_dsn = $this->app->getConfig($dsn, 'no_config');
if ($new_dsn != 'no_config') {
$dsn = $new_dsn;
}
if ($dsn == 'd... | Connect will parse supplied DSN and connect to the database. Please be
aware that DSN may contain plaintext password and if you record backtrace
it may expose it. To avoid, put your DSN inside a config file under a
custom key and use a string e'g:.
$config['my_dsn'] = 'secret';
$db->connect('my_dsn');
If the argument... | entailment |
public function dsql($class = null)
{
$class = $class ?: $this->dsql_class;
$obj = $this->add($class);
if (!$obj instanceof DB_dsql) {
throw $this->exception('Specified class must be descendant of DB_dsql')
->addMoreInfo('class', $class);
}
return... | Returns Dynamic Query object which would be compatible with current
database connection. If you are connected to MySQL, DB_dsql_mysql will
be returned.
@param string $class Override class (e.g. DB_dsql_my)
@return DB_dsql empty dsql object | entailment |
public function query($query, $params = array())
{
// If user forgot to explicitly connect to database, let's do it for him
if (!$this->dbh) {
$this->connect();
}
// There are all sorts of objects used by Agile Toolkit, let's make
// sure we operate with strings ... | Sometimes for whatever reason DSQL is not what you want to do. I really
don't understand your circumstances in which you would want to use
query() directly, but if you really know what you are doing, then this
method executes query with specified params.
@param string $query SQL query
@param array $params Parametric... | entailment |
public function getOne($query, $params = array())
{
$res = $this->query($query, $params)->fetch();
return $res[0];
} | Executes query and returns first column of first row. This is quick and
speedy way to get the results of simple queries.
Consider using DSQL:
echo $this->app->db->dsql()->expr('select now()')->getOne();
@param string $query SQL Query
@param arary $params PDO-params
@return string first column of first row | entailment |
public function commit()
{
--$this->transaction_depth;
// This means we rolled something back and now we lost track of commits
if ($this->transaction_depth < 0) {
$this->transaction_depth = 0;
}
if ($this->transaction_depth == 0) {
return $this->dbh-... | Each occurance of beginTransaction() must be matched with commit().
Only when same amount of commits are executed, the ACTUAL commit will be
issued to the database.
@see beginTransaction()
@return mixed Don't rely on any meaningful return | entailment |
public function rollBack()
{
--$this->transaction_depth;
// This means we rolled something back and now we lost track of commits
if ($this->transaction_depth < 0) {
$this->transaction_depth = 0;
}
if ($this->transaction_depth == 0) {
return $this->db... | Rollbacks queries since beginTransaction and resets transaction depth.
@see beginTransaction()
@return mixed Don't rely on any meaningful return | entailment |
public function setSource($source, $fields = null)
{
// Set DSQL
if ($source instanceof DB_dsql) {
$this->dq = $source;
return $this;
}
// SimpleXML and other objects
if (is_object($source)) {
if ($source instanceof Model) {
... | Similar to setModel, however you specify array of data here. setSource is
actually implemented around :php:class:`Controller_Data_Array`. actually
you can pass anything iterateable to setSource() as long as elements of
iterating produce either a string or array.
@param mixed $source
@param array|string|null $fields
@... | entailment |
public function getIterator()
{
if (is_null($i = $this->model ?: $this->dq ?: $this->iter)) {
throw $this->exception('Please specify data source with setSource or setModel');
}
if ($i instanceof Closure) {
$i = call_user_func($i);
}
return $i;
} | Returns data source iterator.
@return mixed | entailment |
public function render()
{
$iter = $this->getIterator();
foreach ($iter as $this->current_id => $this->current_row) {
if ($this->current_row instanceof Model || $this->current_row instanceof \atk4\data\Model) {
/** @type Model $this->current_row */
$this->... | Renders everything. | entailment |
public function rowRender($template)
{
foreach ($this->current_row as $key => $val) {
if (isset($this->current_row_html[$key])) {
continue;
}
if ($val instanceof DateTime) {
$val = $val->format($this->app->getConfig('locale/datetime', 'Y-m... | Renders single row.
If you use for formatting then interact with template->set() directly
prior to calling parent
@param Template $template template to use for row rendering
@return string HTML of rendered template | entailment |
public function _unique(&$array, $desired = null)
{
$desired = preg_replace('/[^a-zA-Z0-9:]/', '_', $desired);
$desired = parent::_unique($array, $desired);
return $desired;
} | {{{ Generic routines | entailment |
public function escape($val)
{
if ($val === UNDEFINED) {
return '';
}
if (is_array($val)) {
$out = array();
foreach ($val as $v) {
$out[] = $this->escape($v);
}
return $out;
}
$name = ':'.$this->para... | Converts value into parameter and returns reference. Use only during
query rendering. Consider using `consume()` instead.
@param string $val String literal containing input data
@return string Safe and escapeed string | entailment |
public function consume($dsql, $tick = true)
{
if ($dsql === UNDEFINED) {
return '';
}
if ($dsql === null) {
return '';
}
if (is_object($dsql) && $dsql instanceof Field) {
$dsql = $dsql->getExpr();
}
if (!is_object($dsql) ||... | Recursively renders sub-query or expression, combining parameters.
If the argument is more likely to be a field, use tick=true.
@param string|Field|DB_dsql $dsql Expression
@param bool $tick Preferred quoted style
@return string Quoted expression | entailment |
public function setCustom($tag, $value = null)
{
if (is_array($tag)) {
foreach ($tag as $key => $val) {
$this->setCustom($key, $val);
}
return $this;
}
$this->args['custom'][$tag] = $value;
return $this;
} | Defines a custom tag variable. WARNING: always backtick / escaped
argument if it's unsafe.
@param string|array $tag Corresponds to [tag] inside template
@param string|object $value Value for the template tag
@return $this | entailment |
public function debug($msg = true)
{
if (is_bool($msg)) {
$this->debug = $msg;
return $this;
}
if (is_object($msg)) {
throw $this->exception('Do not debug objects');
}
// The rest of this method is obsolete
if ((isset($this->debu... | This is identical to AbstractObject::debug(), but as an object
will refer to the $owner. This is to avoid string-casting and
messing up with the DSQL string.
@param bool|string $msg "true" to start debugging | entailment |
public function useExpr($expr, $tags = array())
{
foreach ($tags as $key => $value) {
if ($key[0] == ':') {
$this->extra_params[$key] = $value;
continue;
}
$this->args['custom'][$key] = $value;
}
$this->template = $expr;
... | Change template of existing query instead of creating new one. If unsure
use expr().
@param string $expr SQL Expression. Don't pass unverified input
@param array $tags Obsolete, use templates / setCustom()
@return $this | entailment |
public function getField($fld)
{
if ($this->main_table === false) {
throw $this->exception(
'Cannot use getField() when multiple tables are queried'
);
}
return $this->expr(
$this->bt($this->main_table).
'.'.
$this-... | Return expression containing a properly escaped field. Use make
subquery condition reference parent query.
@param string $fld Field in SQL table
@return DB_dsql Expression pointing to specified field | entailment |
public function table($table = UNDEFINED, $alias = UNDEFINED)
{
if ($table === UNDEFINED) {
return $this->main_table;
}
if (is_array($table)) {
foreach ($table as $alias => $t) {
if (is_numeric($alias)) {
$alias = UNDEFINED;
... | Specifies which table to use in this dynamic query. You may specify
array to perform operation on multiple tables.
Examples:
$q->table('user');
$q->table('user','u');
$q->table('user')->table('salary')
$q->table(array('user','salary'));
$q->table(array('user','salary'),'user');
$q->table(array('u'=>'user','s'=>'salary... | entailment |
public function render_table()
{
$ret = array();
if (!is_array($this->args['table'])) {
return;
}
foreach ($this->args['table'] as $row) {
list($table, $alias) = $row;
if (is_string($table)) {
// table name passed as string
... | Renders part of the template: [table]
Do not call directly.
@return string Parsed template chunk | entailment |
public function render_table_noalias()
{
$ret = array();
foreach ($this->args['table'] as $row) {
list($table, $alias) = $row;
$table = $this->bt($table);
$ret[] = $table;
}
return implode(', ', $ret);
} | Returns template component [table_noalias].
@return string Parsed template chunk | entailment |
public function field($field, $table = null, $alias = null)
{
if (is_string($field) && strpos($field, ',') !== false) {
$field = explode(',', $field);
} elseif (is_object($field)) {
$alias = $table;
$table = null;
}
if (is_array($field)) {
... | Adds new column to resulting select by querying $field.
Examples:
$q->field('name');
Second argument specifies table for regular fields
$q->field('name','user');
$q->field('name','user')->field('line1','address');
Array as a first argument will specify mulitple fields, same as calling field() multiple times
$q->fiel... | entailment |
public function fieldQuery($field, $table = null, $alias = null)
{
$q = clone $this;
return $q->del('fields')->field($field, $table, $alias);
} | Removes all field definitions and returns only field you specify
as parameter to this method. Original query is not affected ($this)
Same as for field() syntax.
@param string|array $field Specifies field to select
@param string $table Specify if not using primary table
@param string $alias Specify alias fo... | entailment |
public function render_field()
{
$result = array();
if (!$this->args['fields']) {
if ($this->default_field instanceof self) {
return $this->consume($this->default_field);
}
return (string) $this->default_field;
}
foreach ($this->ar... | Returns template component [field].
@return string Parsed template chunk | entailment |
public function where($field, $cond = UNDEFINED, $value = UNDEFINED, $kind = 'where')
{
if (is_array($field)) {
// or conditions
$or = $this->orExpr();
foreach ($field as $row) {
if (is_array($row)) {
$or->where(
... | Adds condition to your query.
Examples:
$q->where('id',1);
Second argument specifies table for regular fields
$q->where('id>','1');
$q->where('id','>',1);
You may use expressions
$q->where($q->expr('a=b'));
$q->where('date>',$q->expr('now()'));
$q->where($q->expr('length(password)'),'>',5);
Finally, subqueries can ... | entailment |
public function having($field, $cond = UNDEFINED, $value = UNDEFINED)
{
return $this->where($field, $cond, $value, 'having');
} | Same syntax as where().
@param mixed $field Field, array for OR or Expression
@param string $cond Condition such as '=', '>' or 'is not'
@param string $value Value. Will be quoted unless you pass expression
@return $this | entailment |
public function _render_where($kind)
{
$ret = array();
foreach ($this->args[$kind] as $row) {
list($field, $cond, $value) = $row;
if (is_object($field)) {
// if first argument is object, condition must be explicitly
// specified
... | Subroutine which renders either [where] or [having].
@param string $kind 'where' or 'having'
@return array Parsed chunks of query | entailment |
public function join(
$foreign_table,
$master_field = null,
$join_kind = null,
$_foreign_alias = null
) {
// Compatibility mode
if (isset($this->app->compat)) {
if (strpos($foreign_table, ' ')) {
list($foreign_table, $alias) = explode(' ', ... | Joins your query with another table.
Examples:
$q->join('address'); // on user.address_id=address.id
$q->join('address.user_id'); // on address.user_id=user.id
$q->join('address a'); // With alias
$q->join(array('a'=>'address')); // Also alias
Second argument may specify the field of the master table
$q... | entailment |
public function render_join()
{
if (!$this->args['join']) {
return '';
}
$joins = array();
foreach ($this->args['join'] as $j) {
$jj = '';
$jj .= $j['t'].' join ';
$jj .= $this->bt($j['f1']);
if (!is_null($j['fa'])) {
... | Renders [join].
@return string rendered SQL chunk | entailment |
public function render_group()
{
if (!$this->args['group']) {
return'';
}
$x = array();
foreach ($this->args['group'] as $arg) {
$x[] = $this->consume($arg);
}
return 'group by '.implode(', ', $x);
} | Renders [group].
@return string rendered SQL chunk | entailment |
public function order($order, $desc = null)
{
// Case with comma-separated fields or first argument being an array
if (is_string($order) && strpos($order, ',') !== false) {
// Check for multiple
$order = explode(',', $order);
}
if (is_array($order)) {
... | Orders results by field or Expression. See documentation for full
list of possible arguments.
$q->order('name');
$q->order('name desc');
$q->order('name desc, id asc')
$q->order('name',true);
@param mixed $order Order by
@param string|bool $desc true to sort descending
@return $this | entailment |
public function render_order()
{
if (!$this->args['order']) {
return'';
}
$x = array();
foreach ($this->args['order'] as $tmp) {
list($arg, $desc) = $tmp;
$x[] = $this->consume($arg).($desc ? (' '.$desc) : '');
}
return 'order by '... | Renders [order].
@return string rendered SQL chunk | entailment |
public function call($fx, $args = null)
{
$this->mode = 'call';
$this->args['fx'] = $fx;
if (!is_null($args)) {
$this->args($args);
}
$this->template = 'call [fx]([args])';
return $this;
} | Sets a template for a user-defined method call with specified arguments.
@param string $fx Name of the user defined method
@param array $args Arguments in mixed form
@return $this | entailment |
public function render_args()
{
$x = array();
foreach ($this->args['args'] as $arg) {
$x[] = is_object($arg) ?
$this->consume($arg) :
$this->escape($arg);
}
return implode(', ', $x);
} | Renders [args].
@return string rendered SQL chunk | entailment |
public function set($field, $value = UNDEFINED)
{
if ($value === false) {
throw $this->exception('Value "false" is not supported by SQL')
->addMoreInfo('field', $field);
}
if (is_array($field)) {
foreach ($field as $key => $value) {
$th... | Sets field value for INSERT or UPDATE statements.
@param string $field Name of the field
@param mixed $value Value of the field
@return $this | entailment |
public function render_set()
{
$x = array();
if ($this->args['set']) {
foreach ($this->args['set'] as $field => $value) {
if (is_object($field)) {
$field = $this->consume($field);
} else {
$field = $this->bt($field);... | Renders [set] for UPDATE query.
@return string rendered SQL chunk | entailment |
public function render_set_fields()
{
$x = array();
if ($this->args['set']) {
foreach ($this->args['set'] as $field => $value) {
if (is_object($field)) {
$field = $this->consume($field);
} else {
$field = $this->bt($... | Renders [set_fields] for INSERT.
@return string rendered SQL chunk | entailment |
public function render_set_values()
{
$x = array();
if ($this->args['set']) {
foreach ($this->args['set'] as $field => $value) {
if (is_object($value)) {
$value = $this->consume($value);
} else {
if (is_array($value)... | Renders [set_values] for INSERT.
@return string rendered SQL chunk | entailment |
public function bt($s)
{
if (is_array($s)) {
$out = array();
foreach ($s as $ss) {
$out[] = $this->bt($ss);
}
return $out;
}
if (!$this->bt
|| is_object($s)
|| $s === '*'
|| strpos($s, '.') !... | Adds backtics around argument. This will allow you to use reserved
SQL words as table or field names such as "table".
@param mixed $s Any string or array of strings
@return string Quoted string | entailment |
public function _setArray($values, $name, $parse_commas = true)
{
if (is_string($values) && $parse_commas && strpos($values, ',')) {
$values = explode(',', $values);
}
if (!is_array($values)) {
$values = array($values);
}
if (!isset($this->args[$name])... | Internal method which can be used by simple param-giving methods such
as option(), group(), etc.
@param mixed $values
@param string $name
@param bool $parse_commas
@private
@return $this | entailment |
public function SQLTemplate($mode)
{
$this->mode = $mode;
$this->template = $this->sql_templates[$mode];
return $this;
} | Switch template for this query. Determines what would be done
on execute.
By default it is in SELECT mode
@param string $mode A key for $this->sql_templates
@return $this | entailment |
public function describe($table = null)
{
$q = clone $this;
if ($table !== null) {
$q->table($table);
}
return $q->SQLTemplate('describe');
} | Creates a query for listing tables in databse-specific form
Agile Toolkit DSQL does not pretend to know anything about model
structure, so result parsing is up to you.
@param string $table Table
@return DB_dsql clone of $this | entailment |
public function count($arg = null)
{
if (is_null($arg)) {
$arg = '*';
}
return $this->expr('count([count])')->setCustom('count', $this->bt($arg));
} | Creates expression for COUNT().
@param string|object $arg Typically fieldname or expression of a sub-query
@return DB_dsql clone of $this | entailment |
public function execute()
{
try {
/**/$this->app->pr->start('dsql/execute/render');
$q = $this->render();
/**/$this->app->pr->next('dsql/execute/query');
$this->stmt = $this->owner->query($q, $this->params);
$this->template = $this->mode = null;
... | Executes current query.
@return $this | entailment |
public function insert()
{
$this->SQLTemplate('insert')->execute();
return
$this->hasInsertOption('ignore') ? null :
$this->owner->lastID();
} | Executes insert query. Returns ID of new record.
@return int new record ID (from last_id) | entailment |
public function insertAll($array)
{
$ids = array();
foreach ($array as $hash) {
$ids[] = $this->del('set')->set($hash)->insert();
}
return $ids;
} | Inserts multiple rows of data. Uses ignore option
AVOID using this, might not be implemented correctly.
@param array $array Insert multiple rows into table with one query
@return array List of IDs | entailment |
public function get()
{
if (!$this->stmt) {
$this->execute();
}
$res = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
$this->rewind();
$this->stmt = null;
return $res;
} | Will execute DSQL query and return all results inside array of hashes.
@return array Array of associative arrays | entailment |
public function getOne()
{
$res = $this->getRow();
$this->rewind();
$this->stmt = null;
return $res[0];
} | Will execute DSQL query and return first column of a first row.
You can also simply cast your DSQL into string to get this value
echo $dsql;
@return string Value of first column in first row | entailment |
public function fetch($mode = PDO::FETCH_ASSOC)
{
if (!$this->stmt) {
$this->execute();
}
return $this->stmt->fetch($mode);
} | Will execute the query (if it's not executed already) and return
first row.
@param int $mode PDO fetch mode
@return mixed return result of PDO::fetch | entailment |
public function foundRows()
{
if ($this->hasOption('SQL_CALC_FOUND_ROWS')) {
return (int) $this->owner->getOne('select found_rows()');
}
/* db-compatible way: */
$c = clone $this;
$c->del('limit');
return (int) $c->fieldQuery('count(*)')->getOne();
} | After fetching data, call this to find out how many rows there were in
total. Call calcFoundRows() for better performance.
@return int number of results | entailment |
public function getDebugQuery($r = null)
{
if ($r === null) {
$r = $this->_render();
}
$d = $r;
$pp = array();
$d = preg_replace('/`([^`]*)`/', '`<font color="black">\1</font>`', $d);
foreach (array_reverse($this->params) as $key => $val) {
if... | Return formatted debug output.
@param string $r Rendered material
@return string SQL syntax of query | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.