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->pullRule())) {
$this->cast = false;
$this->custom_error = null;
if ($rule == 'required') {
$is_required = true;
}
// For debugging
$tmp = null;
$this->consumed = array($rule);
try {
if ((is_object($rule) || is_array($rule)) && is_callable($rule)) {
$tmp = $rule($this, $this->acc, $field);
} else {
// For to_XX rules
if (substr($rule, 0, 3) == 'to_') {
if (!$this->hasMethod('rule_'.$rule)) {
$rule = substr($rule, 3);
}
$this->cast = true;
}
if ($rule === '') {
if ($this->cast) {
$this->set($field, $this->acc);
}
continue;
}
$rule = $this->resolveRuleAlias($rule);
$tmp = $this->{'rule_'.$rule}($this->acc, $field);
}
if ($this->debug) {
echo "<font color=blue>rule_$rule({$this->acc},".
implode(',', $this->consumed).")=$tmp</font><br/>";
}
if (!is_null($tmp)) {
$this->acc = $tmp;
}
if ($this->cast) {
$this->set($field, $tmp);
}
if ($this->bail_out) {
break;
}
} catch (\Exception_ValidityCheck $e) {
if ($this->debug) {
echo "<font color=red>rule_$rule({$this->acc},".
implode(',', $this->consumed).') failed</font><br/>';
}
$this->acc = $acc;
$this->current_ruleset = $crs;
throw $e
->setField($field)
->addMoreInfo('val', $this->acc)
->addMoreInfo('rule', $rule);
}
}
$this->acc = $acc;
$this->current_ruleset = $crs;
} | 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 method is constructor.')
->addMoreInfo('method and class', get_class($this))
;
}
if ($this->app instanceof App_Frontend
&& @$this->app->layout
&& $this->app->layout->template->hasTag('page_title')
) {
$this->app->addHook('afterInit', array($this, 'addBreadCrumb'));
}
if ($this->app instanceof App_Frontend
&& $this->app->template->hasTag('page_metas')
) {
$this->app->addHook('afterInit', array($this, 'addMetas'));
}
if ($this->app instanceof App_Frontend
&& $this->app->template->hasTag('page_title')
) {
$this->app->addHook('afterInit', array($this, 'addTitle'));
}
parent::init();
} | }}} | 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');
} catch (Exception_PathFinder $e) {
return array('page');
}
return array($page_name, '_top');
} | 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 !== ($file = $dd->read())) {
// skip current folder and hidden files
if ($file[0] == '.') {
continue;
}
// skip folders in general
if (is_dir($dir.'/'.$file)) {
continue;
}
// do we strip extensios?
if ($d['strip_extension']) {
// remove any extension
$basefile = pathinfo($file, PATHINFO_FILENAME);
$ext = pathinfo($file, PATHINFO_EXTENSION);
if ($d['strip_extension'] !== true) {
if ($ext !== $d['strip_extension']) {
continue;
}
}
$file = $basefile;
}
$colls[] = array(
'base_path' => $dir.'/'.$file,
'name' => $file,
'id' => $file,
);
}
}
return $colls;
} | 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').' >> '.
date($this->app->getConfig('locale/timestamp', 'Y-m-d H:i:s')."\n"), null, 'error');
}
//if(!isset($this->mime['text'])&&!isset($this->mime['html'])){
$this->setBody(is_object($this->body) ? $this->body->render() : $this->body);
//}
// sign should be added to all parts
if (isset($this->mime['text'])) {
$this->mime['text']['content'] .= $this->getSign();
}
if (isset($this->mime['html'])) {
$this->mime['html']['content'] .= $this->getSign();
// HTML should be converted to base 64
//$this->mime['html']['content']=base64_encode($this->mime['html']['content']);
// no, it should be splitted
//$this->mime['html']['content']=wordwrap($this->mime['html']['content'],76,"\r\n",false);
}
// now as we have all the needed parts set
$result = '';
// first we have to add a simple text for non-Mime readers
if (count($this->mime) == 0) {
$result .= $this->plain_text;
}
// adding mail parts
foreach ($this->mime as $name => $att) {
list($type) = explode(';', $att['type']);
// $name is a file name/part name, $att is a hash with type and content
// depending on the type adding a header
switch ($type) {
case 'text/plain':
if (count($this->mime) > 0) {
$result .= "\n\n--".$this->getBoundary()."\n".
'Content-Type: '.$att['type'].'; ';
}
//$result.="charset=UTF-8";
break;
case 'text/html':
if (count($this->mime) > 0) {
$result .= "\n\n--".$this->getBoundary()."\n".
'Content-Type: '.$att['type'].'; ';
}
$result .=
'Content-Transfer-Encoding: 8bit';
$att['content'] = rtrim(wordwrap($att['content']));
break;
}
if (isset($att['attachment'])) {
$att['content'] = rtrim(chunk_split($att['content']));
$result .= "name=$name\n".
"Content-transfer-encoding: base64\nContent-Disposition: attachment;";
}
$result .= "\n\n";
$result .= $att['content'];
}
// if there were any attachments, trailing boundary should be added
if (count($this->mime) > 0) {
$result .= "\n--".$this->getBoundary()."\n";
}
return ltrim($result);
} | 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->attachHtml($body);
break;
case 'both':
//$this->attachText("Text part is not set");
$this->attachHtml($body);
break;
}
return $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)) {
if ($asstring) {
$name = 'file_'.count($this->mime);
} else {
$name = basename($file);
}
}
// encoding content
$this->mime['"'.$name.'"'] = array(
'type' => $type,
'content' => base64_encode($content),
'attachment' => true,
);
return $this;
} | 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', $this->app->getConfig('mail/from', '[email protected]'));
}
// send an email with defined parameters
$this->headers['X-B64'] = base64_encode($address);
mail(
$address,
$this->get('subject', false),
//($this->is_html?'<html>':'').
$this->getBody(), //.($this->is_html?'</html>':''),
$this->getHeaders(),
'-f '.$this->get('from', false).' '.$add_params
);
} | 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 {
$fields = [];
// get all field-elements
foreach ($model->elements as $field => $f_object) {
if ($f_object instanceof \atk4\data\Field
&& $f_object->isEditable()
&& !$f_object->isHidden()
) {
$fields[] = $field;
}
}
}
}
if (!is_array($fields)) {
$fields = [$fields];
}
// import fields one by one
foreach ($fields as $field) {
$this->importField($field);
}
// set update hook
if (!$this->_hook_set) {
$this->owner->addHook('update', array($this, 'update'));
$model->addHook('afterLoad', array($this, 'setFields'));
$this->_hook_set = true;
}
return $this;
} | 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 = $this->_unique($this->owner->elements, $field->short_name);
}
$this->field_associations[$field_name] = $field;
$field_type = $this->getFieldType($field);
$field_caption = isset($field->ui['caption']) ? $field->ui['caption'] : null;
// add form field
$form_field = $this->owner->addField($field_type, $field_name, $field_caption);
$form_field->set($field->get());
// set model for hasOne field
if ($ref_field = $this->model->hasRef($field->short_name)) {
$form_field->setModel($ref_field->getModel());
}
// set model for enum field
if (isset($field->enum)) {
$list = isset($field->ui['valueList'])
? $field->ui['valueList']
: array_combine($field->enum, $field->enum);
if ($form_field instanceof Form_Field_Checkbox) {
$list = array_reverse($list);
}
$form_field->setValueList($list);
}
// field value is mandatory
if ($field->mandatory) {
$form_field->validateNotNULL($field->mandatory);
}
// form field placeholder
$placeholder = isset($field->ui['placeholder']) ? $field->ui['placeholder'] : /*$field->emptyText() ?:*/ null;
if ($placeholder) {
$form_field->setAttr('placeholder', $placeholder);
}
// form field hint
if (isset($field->ui['hint'])) {
$form_field->setFieldHint($field->ui['hint']);
}
// set empty text option for dropdown type form fields if model field is not mandatory
if ($form_field instanceof Form_Field_ValueList && !$field->mandatory) {
/** @type string $text */
//$text = $field->emptyText();
//$form_field->setEmptyText($text);
$form_field->setEmptyText('- no value -');
}
return $form_field;
} | 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'];
}
if (is_string($tmp) && $tmp) {
return $tmp;
}
}
// associate hasOne (Reference_One) fields with DropDown form field
if ($this->model->hasRef($field->short_name)) {
return 'DropDown';
}
// associate enum fields with DropDown form_field
if (isset($field->enum) && $field->type != 'boolean') {
return 'DropDown';
}
// try to find associated form field type
if (isset($this->type_associations[$field->type])) {
$type = $this->type_associations[$field->type];
}
return $type;
} | 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)) {
$rightField = 'id';
}
$referenceType = ($rightField === 'id') ? 'hasOne' : 'hasMany';
if ($referenceType === 'hasMany') {
throw $this->exception('has many join isn\'t supported');
}
$leftTable = $this->table;
$joinAlias = $this->_unique($this->relations, $joinAlias);
/** @type Field_SQL_Relation $field */
$field = $this->add($this->defaultSQLRelationFieldClass);
$field->setLeftTable($relation ?: $leftTable)
->setLeftField($leftField)
->setRightTable($rightTable)
->setRightField($rightField)
->setJoinKind($joinKind)
->setJoinAlias($joinAlias)
->setModel($this);
$field->referenceType = $referenceType;
$field->setBehaviour($behaviour);
$this->relations[$joinAlias] = $field;
return $field;
} | 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->buildBody($data);
return $provider;
} | 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->buildBody($auth);
return $provider;
} | 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['password'],
];
$provider->buildBody($auth);
return $provider;
} | 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['verify']
);
} | 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 $provider;
} | 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 + 2);
$meta = stream_get_meta_data($this->_connection);
if ($meta['timed_out']) {
$message = 'Connection timed out while reading data from socket.';
throw new RuntimeException($message);
}
$packet = rtrim($data, "\r\n");
} else {
$packet = stream_get_line($this->_connection, 16384, "\r\n");
}
return $packet;
} | 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 'JOB_TOO_BIG':
default:
$this->_error($status);
return false;
}
} | 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 job in the
ready queue. The job will be in the "delayed" state during this time.
@param integer $ttr Time to run - Number of seconds to allow a worker to
run this job. The minimum ttr is 1.
@param string $data The job body.
@return integer|boolean `false` on error otherwise an integer indicating
the job id. | 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 created.
@return string|boolean `false` on error otherwise the name of the tube. | 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, ' ');
}
if (is_numeric($value)) {
$value = (integer) $value == $value ? (integer) $value : (float) $value;
}
$result[$key] = $value;
}
return $result;
} | 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');
}
$this->args[] = escapeshellarg($val);
}
// Command myst be safe
$this->cmd = escapeshellcmd($cmd);
$this->debug('Executing '.$cmd.($this->args ? ' '.implode(' ', $this->args) : ''));
// Now do the execution
$this->executeRaw($this->cmd.' '.implode(' ', $this->args));
return $this;
} | 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->debugStatus();
$this->pipes['in'] = &$pipes[0];
$this->pipes['out'] = &$pipes[1];
$this->pipes['err'] = &$pipes[2];
return $pipes; // in case you need more streams redirected
} | 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");
$this->debugStatus();
return $this;
} | 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") {
$str .= "\n";
}
return $str;
} | 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'])) {
$out = $this->read_all();
}
$out = $this->close('out');
// Read stderr if anything is left there
$this->stderr .= $this->read_stderr();
$this->close('err');
return $out;
} else {
$this->debug('Closing '.$res);
if (is_resource($this->pipes[$res])) {
fclose($this->pipes[$res]);
$this->pipes[$res] = null;
$this->debugStatus();
}
}
//$this->exit_code = proc_close($this->process);
} | 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 = $relation;
$this->our_field = $our_field;
$this->their_field = $their_field;
return $this;
}
$this->their_field = $their_field ?: $this->owner->table.'_id';
$this->our_field = $our_field ?: $this->owner->id_field;
return $this;
} | }}} | 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 ? [] : new \stdClass;
}
// Returns the xml input from a request
$xml = simplexml_load_string($content, null, LIBXML_NOCDATA);
$json = json_encode($xml);
return json_decode($json, $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 == 'dsn') {
$this->app->getConfig($dsn); // throws exception
}
if (is_string($dsn)) {
// Backward-compatible DSN parsing
preg_match(
'|([a-z]+)://([^:]*)(:(.*))?@([A-Za-z0-9\.-]*)'.
'(/([0-9a-zA-Z_/\.-]*))|',
$dsn,
$matches
);
// Common cause of problem is lack of MySQL module for DSN, but
// what if we don't want to use MYSQL?
if (!defined('PDO::MYSQL_ATTR_INIT_COMMAND')) {
throw $this->exception('PDO_MYSQL unavailable');
}
// Reconstruct PDO DSN out of old-style DSN
$dsn = array(
$matches[1].':host='.$matches[5].';dbname='.$matches[7].
';charset=utf8',
$matches[2],
$matches[4],
array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'),
);
}
}
try {
$this->dbh = new PDO(
@$dsn[0],
@$dsn[1],
@$dsn[2],
@$dsn[3] ?: array(PDO::ATTR_PERSISTENT => true)
);
} catch (PDOException $e) {
throw $this->exception('Database Connection Failed')
->addMoreInfo('PDO error', $e->getMessage())
->addMoreInfo('DSN', $dsn[0]);
}
// Configure PDO to play nice
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Based on type, switch dsql class
list($this->type, $junk) = explode(':', $dsn[0]);
$this->type = strtolower($this->type);
$this->dsql_class = isset($dsn['class'])
? $dsn['class']
: 'DB_dsql_'.$this->type;
return $this;
} | 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 $dsn is not specified, it will read it from $config['dsn'].
@param string|array $dsn Connection string in PEAR::DB or PDO format
@return DB $this | 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 $obj;
} | 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 here
if (is_object($query)) {
$query = (string) $query;
}
// For some weird reason SQLite will fail sometimes to execute query
// for the first time. We will try it again before complaining about
// the error, but only if error=17.
$e = null;
for ($i = 0; $i < 2; ++$i) {
try {
$statement = $this->dbh->prepare($query);
foreach ($params as $key => $val) {
if (!$statement->bindValue(
$key,
$val,
is_int($val) ? (PDO::PARAM_INT) : (PDO::PARAM_STR)
)) {
throw $this->exception('Could not bind parameter')
->addMoreInfo('key', $key)
->addMoreInfo('val', $val)
->addMoreInfo('query', $query);
}
}
$statement->execute();
return $statement;
} catch (PDOException $e) {
if ($e->errorInfo[1] === 17 && !$i) {
continue;
}
throw $e;
}
}
} | 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 arguments
@return PDOStatement Newly created statement | 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->commit();
}
return false;
} | 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->dbh->rollBack();
}
return false;
} | 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) {
throw $this->exception('Use setModel() for Models');
} elseif ($source instanceof Controller) {
throw $this->exception('Use setController() for Controllers');
} elseif ($source instanceof Iterator || $source instanceof Closure) {
$this->iter = $source;
return $this;
}
// Cast non-iterable objects into array
$source = (array) $source;
}
// Set Array as a data source
if (is_array($source)) {
$m = $this->setModel('Model', $fields);
$m->setSource('Array', $source);
return $this;
}
// Set manually
$this->dq = $this->app->db->dsql();
$this->dq
->table($source)
->field($fields ?: '*');
return $this;
} | 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
@return $this | 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->current_row = $this->current_row->get();
} elseif (!is_array($this->current_row) && !($this->current_row instanceof ArrayAccess)) {
// Looks like we won't be able to access current_row as array, so we will
// copy it's value inside $this->current instead and produce an empty array
// to be filled out by a custom iterators
$this->current = $this->current_row;
$this->current_row = get_object_vars($this->current);
}
$this->formatRow();
$this->output($this->rowRender($this->template));
}
} | 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-d H:i:s'));
}
$template->trySet($key, $val);
}
$template->setHTML($this->current_row_html);
$template->trySet('id', $this->current_id);
$o = $template->render();
foreach (array_keys($this->current_row) + array_keys($this->current_row_html) as $k) {
$template->tryDel($k);
}
return $o;
} | 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->param_base;
$name = $this->_unique($this->params, $name);
$this->params[$name] = $val;
return $name;
} | 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) || !$dsql instanceof self) {
return $tick ? $this->bt($dsql) : $dsql;
}
$dsql->params = &$this->params;
$ret = $dsql->_render();
if ($dsql->mode === 'select') {
$ret = '('.$ret.')';
}
unset($dsql->params);
$dsql->params = array();
return $ret;
} | 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->debug) && $this->debug)
|| (isset($this->app->debug) && $this->app->debug)
) {
$this->app->outputDebug($this->owner, $msg);
}
} | 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;
if (!empty($tags)) {
$this->setCustom($tags);
}
$this->output_mode = 'render';
return $this;
} | 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->bt($fld)
);
} | 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;
}
$this->table($t, $alias);
}
return $this;
}
// main_table tracking allows us to
if ($this->main_table === null) {
$this->main_table = $alias === UNDEFINED || !$alias ? $table : $alias;
} elseif ($this->main_table) {
$this->main_table = false; // query from multiple tables
}
// if $table is DSQL, then alias is mandatory
if ($table instanceof DB_dsql && ($alias === UNDEFINED || !$alias)) {
throw $this->exception('If table is passed as DSQL, then table alias is mandatory!');
}
$this->args['table'][] = array($table, $alias);
return $this;
} | 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'));
$q->table($q2->table('user')->where('active',1), 'active_users');
If you specify multiple tables, you still need to make sure to add
proper "where" conditions. All the above examples return $q (for chaining)
You can also call table without arguments, which will return current table:
echo $q->table();
If multiple tables are used, "false" is returned. Return is not quoted.
Please avoid using table() without arguments as more tables may be
dynamically added later.
@param string|DB_dsql $table Specify table to use or DSQL to use as derived table
@param string $alias Specify alias for the table, if $table is DSQL, then alias is mandatory
@return $this|string | 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
$table = $this->bt($table);
} elseif ($table instanceof DB_dsql) {
// table passed as DSQL expression
// remove SQL_CALC_FOUND_ROWS from subquery
$i = @array_search('SQL_CALC_FOUND_ROWS', $table->args['options']);
if ($i !== false) {
unset($table->args['options'][$i]);
}
// consume subquery
$table = $this->consume($table);
}
if ($alias !== UNDEFINED && $alias) {
$table .= ' '.$this->bt($alias);
}
$ret[] = $table;
}
return implode(',', $ret);
} | 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)) {
foreach ($field as $alias => $f) {
if (is_numeric($alias)) {
$alias = null;
}
$this->field($f, $table, $alias);
}
return $this;
}
$this->args['fields'][] = array($field, $table, $alias);
return $this;
} | 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->field(array('name','surname'));
Associative array will assume that "key" holds the alias. Value may be object.
$q->field(array('alias'=>'name','alias2'=>surname'));
$q->field(array('alias'=>$q->expr(..), 'alias2'=>$q->dsql()->.. ));
You may use array with aliases together with table specifier.
$q->field(array('alias'=>'name','alias2'=>surname'),'user');
You can specify $q->expr() for calculated fields. Alias is mandatory.
$q->field( $q->expr('2+2'),'alias'); // must always use alias
You can use $q->dsql() for subqueries. Alias is mandatory.
$q->field( $q->dsql()->table('x')... , 'alias'); // must always use alias
@param string|array $field Specifies field to select
@param string $table Specify if not using primary table
@param string $alias Specify alias for this field
@return $this | 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 for this field
@return DB_dsql Clone of $this with only one field | 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->args['fields'] as $row) {
list($field, $table, $alias) = $row;
if ($alias === $field) {
$alias = UNDEFINED;
}
/**/$this->app->pr->start('dsql/render/field/consume');
$field = $this->consume($field);
/**/$this->app->pr->stop();
if (!$field) {
$field = $table;
$table = UNDEFINED;
}
if ($table && $table !== UNDEFINED) {
$field = $this->bt($table).'.'.$field;
}
if ($alias && $alias !== UNDEFINED) {
$field .= ' '.$this->bt($alias);
}
$result[] = $field;
}
return implode(',', $result);
} | 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(
$row[0],
array_key_exists(1, $row) ? $row[1] : UNDEFINED,
array_key_exists(2, $row) ? $row[2] : UNDEFINED
);
} elseif (is_object($row)) {
$or->where($row);
} else {
$or->where($or->expr($row));
}
}
$field = $or;
}
if (is_string($field) && !preg_match('/^[.a-zA-Z0-9_]*$/', $field)) {
// field contains non-alphanumeric values. Look for condition
preg_match(
'/^([^ <>!=]*)([><!=]*|( *(not|is|in|like))*) *$/',
$field,
$matches
);
$value = $cond;
$cond = $matches[2];
if (!$cond) {
// IF COMPAT
$matches[1] = $this->expr($field);
if ($value && $value !== UNDEFINED) {
$cond = '=';
} else {
$cond = UNDEFINED;
}
}
$field = $matches[1];
}
$this->args[$kind][] = array($field, $cond, $value);
return $this;
} | 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 also be used
$q->where('foo',$q->dsql()->table('foo')->field('name'));
To specify OR conditions
$q->where($q->orExpr()->where('a',1)->where('b',1));
you can also use the shortcut:
$q->where(array('a is null','b is null'));
@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
@param string $kind Do not use directly. Use having()
@return $this | 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
$field = $this->consume($field);
} else {
list($table, $field) = explode('.', $field, 2);
if ($field) {
if ($this->mode == 'delete') {
$field = $this->bt($field);
} else {
$field = $this->bt($table).'.'.$this->bt($field);
}
} else {
$field = $this->bt($table);
}
}
// no value or condition passed, so this should be SQL chunk itself
if ($value === UNDEFINED && $cond === UNDEFINED) {
$r = $field;
$ret[] = $r;
continue;
}
// if no condition defined - set default condition
if ($value === UNDEFINED) {
$value = $cond;
if (is_array($value)) {
$cond = 'in';
} elseif (is_object($value) && @$value->mode === 'select') {
$cond = 'in';
} else {
$cond = '=';
}
} else {
$cond = trim(strtolower($cond));
}
// special conditions if value is null
if ($value === null) {
if ($cond === '=') {
$cond = 'is';
} elseif (in_array($cond, array('!=', '<>', 'not'))) {
$cond = 'is not';
}
}
// value should be array for such conditions
if (($cond === 'in' || $cond === 'not in') && is_string($value)) {
$value = explode(',', $value);
}
// if value is array, then use IN or NOT IN as condition
if (is_array($value)) {
$v = array();
foreach ($value as $vv) {
$v[] = $this->escape($vv);
}
$value = '('.implode(',', $v).')';
$cond = in_array($cond, array('!=', '<>', 'not', 'not in')) ? 'not in' : 'in';
$r = $this->consume($field).' '.$cond.' '.$value;
$ret[] = $r;
continue;
}
// if value is object, then it should be DSQL itself
// otherwise just escape value
if (is_object($value)) {
$value = $this->consume($value);
} else {
$value = $this->escape($value);
}
$r = $field.' '.$cond.' '.$value;
$ret[] = $r;
}
return $ret;
} | 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(' ', $foreign_table);
$foreign_table = array($alias => $foreign_table);
}
if (strpos($master_field, '=')) {
$master_field = $this->expr($master_field);
}
}
// If array - add recursively
if (is_array($foreign_table)) {
foreach ($foreign_table as $alias => $foreign) {
if (is_numeric($alias)) {
$alias = null;
}
$this->join($foreign, $master_field, $join_kind, $alias);
}
return $this;
}
$j = array();
// Split and deduce fields
list($f1, $f2) = explode('.', $foreign_table, 2);
if (is_object($master_field)) {
$j['expr'] = $master_field;
} else {
// Split and deduce primary table
if (is_null($master_field)) {
list($m1, $m2) = array(null, null);
} else {
list($m1, $m2) = explode('.', $master_field, 2);
}
if (is_null($m2)) {
$m2 = $m1;
$m1 = null;
}
if (is_null($m1)) {
$m1 = $this->main_table;
}
// Identify fields we use for joins
if (is_null($f2) && is_null($m2)) {
$m2 = $f1.'_id';
}
if (is_null($m2)) {
$m2 = 'id';
}
$j['m1'] = $m1;
$j['m2'] = $m2;
}
$j['f1'] = $f1;
if (is_null($f2)) {
$f2 = 'id';
}
$j['f2'] = $f2;
$j['t'] = $join_kind ?: 'left';
$j['fa'] = $_foreign_alias;
$this->args['join'][] = $j;
return $this;
} | 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->join('address', 'billing_id');
$q->join('address.code', 'code');
$q->join('address.code', 'user.code');
Third argument may specify which kind of join to use.
$q->join('address', null, 'left');
$q->join('address.code', 'user.code', 'inner');
Using array syntax you can join multiple tables too
$q->join(array('a'=>'address', 'p'=>'portfolio'));
You can use expression for more complex joins
$q->join('address',
$q->orExpr()
->where('user.billing_id=address.id')
->where('user.technical_id=address.id')
)
@param string $foreign_table Table to join with
@param mixed $master_field Field in master table
@param string $join_kind 'left' or 'inner', etc
@param string $_foreign_alias Internal, don't use
@return $this | 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'])) {
$jj .= ' as '.$this->bt($j['fa']);
}
$jj .= ' on ';
if ($j['expr']) {
$jj .= $this->consume($j['expr']);
} else {
$jj .=
$this->bt($j['fa'] ?: $j['f1']).'.'.
$this->bt($j['f2']).' = '.
$this->bt($j['m1']).'.'.
$this->bt($j['m2']);
}
$joins[] = $jj;
}
return implode(' ', $joins);
} | 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)) {
if (!is_null($desc)) {
throw $this->exception(
'If first argument is array, second argument must not be used'
);
}
foreach (array_reverse($order) as $o) {
$this->order($o);
}
return $this;
}
// First argument may contain space, to divide field and keyword
if (is_null($desc) && is_string($order) && strpos($order, ' ') !== false) {
list($order, $desc) = array_map('trim', explode(' ', trim($order), 2));
}
if (is_string($order) && strpos($order, '.') !== false) {
$order = implode('.', $this->bt(explode('.', $order)));
}
if (is_bool($desc)) {
$desc = $desc ? 'desc' : '';
} elseif (strtolower($desc) === 'asc') {
$desc = '';
} elseif ($desc && strtolower($desc) != 'desc') {
throw $this->exception('Incorrect ordering keyword')
->addMoreInfo('order by', $desc);
}
// TODO:
/*
if (isset($this->args['order'][0]) and (
$this->args['order'][0] === array($order,$desc))) {
}
*/
$this->args['order'][] = array($order, $desc);
return $this;
} | 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 '.implode(', ', array_reverse($x));
} | 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) {
$this->set($key, $value);
}
return $this;
}
if ($value === UNDEFINED) {
throw $this->exception('Specify value when calling set()');
}
$this->args['set'][$field] = $value;
return $this;
} | 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);
}
if (is_object($value)) {
$value = $this->consume($value);
} else {
if (is_array($value)) {
$value = json_encode($value);
}
$value = $this->escape($value);
}
$x[] = $field.'='.$value;
}
}
return implode(', ', $x);
} | 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($field);
}
$x[] = $field;
}
}
return implode(',', $x);
} | 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)) {
$value = json_encode($value);
}
$value = $this->escape($value);
}
$x[] = $value;
}
}
return implode(',', $x);
} | 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, '.') !== false
|| strpos($s, '(') !== false
|| strpos($s, $this->bt) !== false
) {
return $s;
}
return $this->bt.$s.$this->bt;
} | 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])) {
$this->args[$name] = array();
}
$this->args[$name] = array_merge($this->args[$name], $values);
return $this;
} | 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;
/**/$this->app->pr->stop();
return $this;
} catch (PDOException $e) {
throw $this->exception('Database Query Failed')
->addMoreInfo('pdo_error', $e->getMessage())
->addMoreInfo('mode', $this->mode)
->addMoreInfo('params', $this->params)
->addMoreInfo('query', $q)
->addMoreInfo('template', $this->template)
;
}
} | 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 (is_string($val)) {
$d = preg_replace('/'.$key.'([^_]|$)/', '"<font color="green">'.
htmlspecialchars(addslashes($val)).'</font>"\1', $d);
} elseif (is_null($val)) {
$d = preg_replace(
'/'.$key.'([^_]|$)/',
'<font color="black">NULL</font>\1',
$d
);
} elseif (is_numeric($val)) {
$d = preg_replace(
'/'.$key.'([^_]|$)/',
'<font color="red">'.$val.'</font>\1',
$d
);
} else {
$d = preg_replace('/'.$key.'([^_]|$)/', $val.'\1', $d);
}
$pp[] = $key;
}
return $d." <font color='gray'>[".
implode(', ', $pp).']</font>';
} | 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.