sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function render() { $this->params = $this->extra_params; $r = $this->_render(); $this->debug((string) $this->getDebugQuery($r)); return $r; }
Converts query into string format. This will contain parametric references. @return string Resulting query
entailment
public function _render() { /**/$this->app->pr->start('dsql/render'); if (is_null($this->template)) { $this->SQLTemplate('select'); } $self = $this; $res = preg_replace_callback( '/\[([a-z0-9_]*)\]/', function ($matches) use ($self) { /**/$self->app->pr->next('dsql/render/'.$matches[1], true); $fx = 'render_'.$matches[1]; if (isset($self->args['custom'][$matches[1]])) { return $self->consume($self->args['custom'][$matches[1]], false); } elseif ($self->hasMethod($fx)) { return $self->$fx(); } else { return $matches[0]; } }, $this->template ); /**/$this->app->pr->stop(null, true); return $res; }
Helper for render(), which does the actual work. @private @return string Resulting query
entailment
public function register() { $this->app->singleton('sms', function ($app) { $this->registerSender(); $sms = new SMS($app['sms.sender']); $this->setSMSDependencies($sms, $app); //Set the from setting if ($app['config']->has('sms.from')) { $sms->alwaysFrom($app['config']['sms']['from']); } return $sms; }); }
Register the service provider.
entailment
public function destroy($recursive = true) { if ($recursive) { foreach ($this->elements as $el) { if ($el instanceof self) { $el->destroy(); } } } /* if (@$this->model && $this->model instanceof AbstractObject) { $this->model->destroy(); unset($this->model); } if (@$this->controller && $this->controller instanceof AbstractObject) { $this->controller->destroy(); unset($this->controller); } */ $this->owner->_removeElement($this->short_name); }
Removes object from parent and prevents it from rendering \code $view = $this->add('View'); $view -> destroy(); \endcode.
entailment
public function removeElement($short_name) { if (is_object($this->elements[$short_name])) { $this->elements[$short_name]->destroy(); } else { unset($this->elements[$short_name]); } return $this; }
Remove child element if it exists. @param string $short_name short name of the element @return $this
entailment
public function _removeElement($short_name) { unset($this->elements[$short_name]); if ($this->_element_name_counts[$short_name] === 1) { unset($this->_element_name_counts[$short_name]); } return $this; }
Actually removes the element. @param string $short_name short name @return $this @access private
entailment
public function add( $class, $options = null, $template_spot = null, $template_branch = null ) { if (is_array($class)) { if (!$class[0]) { throw $this->exception('When passing class as array, use ["Class", "option"=>123] format') ->addMoreInfo('class', var_export($class, true)); } $o = $class; $class = $o[0]; unset($o[0]); $options = $options ? array_merge($options, $o) : $o; } if (is_string($options)) { $options = array('name' => $options); } if (!is_array($options)) { $options = array(); } if (is_object($class)) { // Object specified, just add the object, do not create anything if (!($class instanceof self) && !(method_exists($class, 'init'))) { throw $this->exception( 'You may only add objects based on AbstractObject' ); } if (!isset($class->short_name)) { $class->short_name = str_replace('\\', '_', strtolower(get_class($class))); } if (!isset($class->app)) { $class->app = $this->app; $class->api = $this->app; // compatibility with ATK 4.2 and lower } $class->short_name = $this->_unique_element($class->short_name); $class->name = $this->_shorten($this->name.'_'.$class->short_name); $this->elements[$class->short_name] = $class; if ($class instanceof AbstractView) { /** @type AbstractView $class */ $class->owner->elements[$class->short_name] = true; } $class->owner = $this; if ($class instanceof AbstractView) { /** @type AbstractView $class */ // Scrutinizer complains that $this->template is not defined and it really is not :) if (!isset($this->template) || !$this->template) { $class->initializeTemplate($template_spot, $template_branch); } } if (!$class->_initialized) { $this->app->hook('beforeObjectInit', array(&$class)); $class->init(); } return $class; } if (!is_string($class) || !$class) { throw $this->exception('Class is not valid') ->addMoreInfo('class', $class); } $class = str_replace('/', '\\', $class); if ($class[0] == '.') { // Relative class name specified, extract current namespace // and make new class name relative to this namespace $ns = get_class($this); $ns = substr($ns, 0, strrpos($ns, '\\')); $class = $ns.'\\'.substr($class, 2); } $short_name = isset($options['name']) ? $options['name'] : str_replace('\\', '_', strtolower($class)); // Adding same controller twice will return existing one if (isset($this->elements[$short_name])) { if ($this->elements[$short_name] instanceof AbstractController) { return $this->elements[$short_name]; } } $short_name = $this->_unique_element($short_name); if (isset($this->elements[$short_name])) { throw $this->exception($class.' with requested name already exists') ->addMoreInfo('class', $class) ->addMoreInfo('new_short_name', $short_name) ->addMoreInfo('object', $this) ->addMoreInfo('counts', json_encode($this->_element_name_counts)) ->addThis($this); } $class_name_nodash = str_replace('-', '', $class); /* * Even though this might break some applications, * your loading must be configured properly instead * of relying on this * if (!class_exists($class_name_nodash, false) && isset($this->app->pathfinder) ) { $this->app->pathfinder->loadClass($class); }*/ $element = new $class_name_nodash($options); if (!($element instanceof self)) { throw $this->exception( 'You can add only classes based on AbstractObject' ); } $element->owner = $this; $element->app = $this->app; $element->api = $this->app; // compatibility with ATK 4.2 and lower $element->name = $this->_shorten($this->name.'_'.$short_name); $element->short_name = $short_name; if (!$element->auto_track_element) { // dont store extra reference to models and controlers // for purposes of better garbage collection $this->elements[$short_name] = true; } else { $this->elements[$short_name] = $element; } // Initialize template before init() starts if ($element instanceof AbstractView) { $element->initializeTemplate($template_spot, $template_branch); } // Avoid using this hook. Agile Toolkit creates LOTS of objects, // so you'll get significantly slower code if you try to use this $this->app->hook('beforeObjectInit', array(&$element)); // Initialize element $element->init(); // Make sure init()'s parent was called. It's a popular coder's mistake. if (!$element->_initialized) { throw $element->exception( 'You should call parent::init() when you override it' ) ->addMoreInfo('object_name', $element->name) ->addMoreInfo('class', get_class($element)); } // Great hook to affect children recursively $this->hook('afterAdd', array($element)); return $element; }
Creates new object and adds it as a child of current object. Returns new object. @param array|string|object $class Name of the new class. Can also be array with 0=>name and rest of array will be considered as $options or object. @param array|string $options Short name or array of properties. 0=>name will be used as a short-name or your object. @param string $template_spot Tag where output will appear @param array|string $template_branch Redefine template @link http://agiletoolkit.org/learn/understand/base/adding @return AbstractObject
entailment
public function getElement($short_name) { if (!isset($this->elements[$short_name])) { throw $this->exception('Child element not found') ->addMoreInfo('element', $short_name); } return $this->elements[$short_name]; }
Find child element by its short name. Use in chaining. Exception if not found. @param string $short_name Short name of the child element @return AbstractObject
entailment
public function rename($short_name) { unset($this->owner->elements[$this->short_name]); $this->name = $this->name.'_'.$short_name; $this->short_name = $short_name; if (!$this->auto_track_element) { $this->owner->elements[$short_name] = true; } else { $this->owner->elements[$short_name] = $this; } return $this; }
Names object accordingly. May not work on some objects. @param string $short_name Short name of the child element @return $this
entailment
public function setController($controller, $name = null) { $controller = $this->app->normalizeClassName($controller, 'Controller'); return $this->add($controller, $name); }
Associate controller with the object. @param string|object $controller Class or instance of controller @param string|array $name Name or property for new controller @return AbstractController Newly added controller
entailment
public function setModel($model) { // in case of Agile Data model - don't add it to object. // Agile Data Model owner is Agile Data Persistance and so be it. if ($model instanceof \atk4\data\Model) { return $this->model = $model; } $model = $this->app->normalizeClassName($model, 'Model'); $this->model = $this->add($model); return $this->model; }
Associate model with object. @param string|object $model Class or instance of model @return AbstractModel Newly added Model
entailment
public function exception($message = 'Undefined Exception', $type = null, $code = null) { if ($type === null) { $type = $this->default_exception; } elseif ($type[0] == '_') { if ($this->default_exception == 'BaseException') { $type = 'Exception_'.substr($type, 1); } else { $type = $this->default_exception.'_'.substr($type, 1); } } elseif ($type != 'BaseException') { $type = $this->app->normalizeClassName($type, 'Exception'); } // Localization support $message = $this->app->_($message); if ($type == 'Exception') { $type = 'BaseException'; } $e = new $type($message, $code); if (!($e instanceof BaseException)) { throw $e; } $e->owner = $this; $e->app = $this->app; $e->api = $this->app; // compatibility with ATK 4.2 and lower $e->init(); return $e; }
Returns relevant exception class. Use this method with "throw". @param string $message Static text of exception. @param string $type Exception class or class postfix @param string $code Optional error code @return BaseException
entailment
public function debug($msg = true, $file = null, $line = null) { 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, $msg, $file/*, $line*/); } }
Turns on debug mode for this object. Using first argument as string is obsolete. @param bool|string $msg "true" to start debugging @param string $file obsolete @param string $line obsolete
entailment
public function upCall($type, $args = array()) { /* * Try to handle something on our own and in case we are not able, * pass to parent. Such as messages, notifications and request for * additional info or descriptions are passed this way. */ if (method_exists($this, $type)) { return call_user_func_array( array( $this, $type, ), $args ); } if (!$this->owner) { return false; } return $this->owner->upCall($type, $args); }
Call specified method for this class and all parents up to app. @param string $type information @param array $args relative offset in backtrace @obsolete
entailment
public function addHook($hook_spot, $callable, $arguments = array(), $priority = 5) { if (!is_array($arguments)) { throw $this->exception('Incorrect arguments'); } if (is_string($hook_spot) && strpos($hook_spot, ',') !== false) { $hook_spot = explode(',', $hook_spot); } if (is_array($hook_spot)) { foreach ($hook_spot as $h) { $this->addHook($h, $callable, $arguments, $priority); } return $this; } if (!is_callable($callable) && ($callable instanceof self && !$callable->hasMethod($hook_spot)) ) { throw $this->exception('Hook does not exist'); } if (is_object($callable) && !is_callable($callable)) { $callable = array($callable, $hook_spot); // short for addHook('test', $this); to call $this->test(); } $this->hooks[$hook_spot][$priority][] = array($callable, $arguments); return $this; }
If priority is negative, then hooks will be executed in reverse order. @param string $hook_spot Hook identifier to bind on @param AbstractObject|callable $callable Will be called on hook() @param array $arguments Arguments are passed to $callable @param int $priority Lower priority is called sooner @return $this
entailment
public function hook($hook_spot, $arg = array()) { if (!is_array($arg)) { throw $this->exception( 'Incorrect arguments, or hook does not exist' ); } $return = array(); if ($arg === UNDEFINED) { $arg = array(); } if (isset($this->hooks[$hook_spot])) { if (is_array($this->hooks[$hook_spot])) { krsort($this->hooks[$hook_spot]); // lower priority is called sooner $hook_backup = $this->hooks[$hook_spot]; try { while ($_data = array_pop($this->hooks[$hook_spot])) { foreach ($_data as $prio => &$data) { // Our extension if (is_string($data[0]) && !preg_match( '/^[a-zA-Z_][a-zA-Z0-9_]*$/', $data[0] ) ) { $result = eval($data[0]); } elseif (is_callable($data[0])) { $result = call_user_func_array( $data[0], array_merge( array($this), $arg, $data[1] ) ); } else { if (!is_array($data[0])) { $data[0] = array( 'STATIC', $data[0], ); } throw $this->exception( 'Cannot call hook. Function might not exist.' ) ->addMoreInfo('hook', $hook_spot) ->addMoreInfo('arg1', $data[0][0]) ->addMoreInfo('arg2', $data[0][1]); } $return[] = $result; } } } catch (Exception_Hook $e) { /** @type Exception_Hook $e */ $this->hooks[$hook_spot] = $hook_backup; return $e->return_value; } $this->hooks[$hook_spot] = $hook_backup; } } return $return; }
Execute all callables assigned to $hook_spot. @param string $hook_spot Hook identifier @param array $arg Additional arguments to callables @return mixed Array of responses or value specified to breakHook
entailment
public function tryCall($method, $arguments) { if ($ret = $this->hook('method-'.$method, $arguments)) { return $ret; } array_unshift($arguments, $this); if (($ret = $this->app->hook('global-method-'.$method, $arguments))) { return $ret; } }
Attempts to call dynamic method. Returns array containing result or false. @param string $method Name of the method @param array $arguments Arguments @return mixed
entailment
public function addMethod($name, $callable) { if (is_string($name) && strpos($name, ',') !== false) { $name = explode(',', $name); } if (is_array($name)) { foreach ($name as $h) { $this->addMethod($h, $callable); } return $this; } if (is_object($callable) && !is_callable($callable)) { $callable = array($callable, $name); } if ($this->hasMethod($name)) { throw $this->exception('Registering method twice'); } $this->addHook('method-'.$name, $callable); return $this; }
Add new method for this object. @param string|array $name Name of new method of $this object @param callable $callable Callback @return $this
entailment
public function hasMethod($name) { return method_exists($this, $name) || isset($this->hooks['method-'.$name]) || isset($this->app->hooks['global-method-'.$name]); }
Return if this object has specified method (either native or dynamic). @param string $name Name of the method @return bool
entailment
public function logError($error, $msg = '') { if (is_object($error)) { // we got exception object obviously $error = $error->getMessage(); } $this->app->getLogger()->logLine($msg.' '.$error."\n", null, 'error'); }
Output string into error file. @param string $error error @param string $msg msg @obsolete
entailment
public function each($callable) { if ($this instanceof Iterator) { if (is_string($callable)) { foreach ($this as $obj) { if ($obj->$callable() === false) { break; } } return $this; } foreach ($this as $obj) { if (call_user_func($callable, $obj) === false) { break; } } } else { throw $this->exception('Calling each() on non-iterative object'); } return $this; }
A handy shortcut for foreach(){ .. } code. Make your callable return "false" if you would like to break the loop. @param string|callable $callable will be executed for each member @return $this
entailment
public function _unique(&$array, $desired = null) { if (!is_array($array)) { throw $this->exception('not array'); } $postfix = count($array); $attempted_key = $desired; while (array_key_exists($attempted_key, $array)) { // already used, move on $attempted_key = ($desired ?: 'undef').'_'.(++$postfix); } return $attempted_key; }
This funcion given the associative $array and desired new key will return the best matching key which is not yet in the array. For example, if you have array('foo'=>x,'bar'=>x) and $desired is 'foo' function will return 'foo_2'. If 'foo_2' key also exists in that array, then 'foo_3' is returned and so on. @param array &$array Reference to array which stores key=>value pairs @param string $desired Desired key for new object @return string unique key for new object
entailment
public function pack($from, $to) { if (($gzip = gzopen($to, 'wb')) === false) { throw new Exception('Unable create compressed file.'); } if (($source = fopen($from, 'rb')) === false) { throw new Exception('Unable open the compression source file.'); } while (!feof($source)) { $content = fread($source, 4096); gzwrite($gzip, $content, strlen($content)); } gzclose($gzip); fclose($source); }
Compresses a file. @param string $from The source @param string $to The target @throws Exception
entailment
public function unpack($from, $to) { if (($gzip = gzopen($from, 'rb')) === false) { throw new Exception('Unable to read compressed file.'); } if (($target = fopen($to, 'w')) === false) { throw new Exception('Unable to open the target.'); } while ($string = gzread($gzip, 4096)) { fwrite($target, $string, strlen($string)); } gzclose($gzip); fclose($target); }
Uncompresses a file. @param string $from The source @param string $to The target @throws Exception
entailment
public function setModel($m) { if (is_string($m)) { $m = 'Model_'.$m; } $this->model = $this->add($m); return $this->model; }
@param string $m @return Model
entailment
public function setEmptyText($text = null) { $this->empty_text = $text === null ? $this->default_empty_text : $text; return $this; }
Sets default text which is displayed on a null-value option. Set to "Select.." or "Pick one.." @param string $text Pass null to use default text, empty string - disable @return $this
entailment
public function validateValidItem() { if (!$this->value) { return; } // load allowed values in values_list // @todo Imants: Actually we don't need to load all values from Model in // array, just to check couple of posted values. // Probably we should do SELECT * FROM t WHERE id IN ($values) or // something like that to limit array size and time spent on // parsing all DB records in Model. $this->getValueList(); $values = explode($this->separator, $this->value); foreach ($values as $v) { if (!isset($this->value_list[$v])) { $this->displayFieldError("Value $v is not one of the offered values"); return $this->validate(); } } }
Validate POSTed field value. @return bool
entailment
public function getValueList() { // add model data rows in value list try { if ($this->model) { $id = $this->model->id_field; $title = $this->model->getElement($this->model->title_field); $this->value_list = array(); foreach ($this->model as $row) { $this->value_list[(string) $row[$id]] = $row[$title]; } } // prepend empty text message at the begining of value list if needed if ($this->empty_text && !isset($this->value_list[$this->empty_value])) { $this->value_list = array($this->empty_value => $this->empty_text) + $this->value_list; } return $this->value_list; } catch (\atk4\core\Exception $e) { $e->addMoreInfo('values_for_field', $this->short_name); throw $e; } }
Return value list. @return array
entailment
public function normalize() { $data = $this->get(); if (is_array($data)) { $data = implode($this->separator, $data); } $data = trim($data, $this->separator); if (!$data) { $data = null; } if (get_magic_quotes_gpc()) { $this->set(stripslashes($data)); } else { $this->set($data); } return parent::normalize(); }
Normalize POSTed data.
entailment
public function send(OutgoingMessage $message) { try { $message = $this->mailer->send(['text' => $message->getView()], $message->getData(), function ($email) use ($message) { $this->generateMessage($email, $message); }); } catch (InvalidArgumentException $e) { $message = $this->sendRaw($message); } return $message; }
Sends a SMS message via the mailer. @param SimpleSoftwareIO\SMS\OutgoingMessage $message @return Illuminate\Mail\Message
entailment
protected function generateMessage($email, $message) { foreach ($message->getToWithCarriers() as $number) { $email->to($this->buildEmail($number, $message)); } if ($message->getAttachImages()) { foreach ($message->getAttachImages() as $image) { $email->attach($image); } } $email->from($message->getFrom()); return $email; }
Generates the Laravel Message Object. @param Illuminate\Mail\Message $email @param SimpleSoftwareIO\SMS\OutgoingMessage $message @return Illuminate\Mail\Message
entailment
protected function sendRaw(OutgoingMessage $message) { $message = $this->mailer->raw($message->getView(), function ($email) use ($message) { $this->generateMessage($email, $message); }); return $message; }
Sends a SMS message via the mailer using the raw method. @param SimpleSoftwareIO\SMS\OutgoingMessage $message @return Illuminate\Mail\Message
entailment
protected function buildEmail($number, OutgoingMessage $message) { if (!$number['carrier']) { throw new \InvalidArgumentException('A carrier must be specified if using the E-Mail Driver.'); } return $number['number'].'@'.$this->lookupGateway($number['carrier'], $message->isMMS()); }
Builds the email address of a number. @param array $number @param SimpleSoftwareIO\SMS\OutgoingMessage $message @return string
entailment
protected function lookupGateway($carrier, $mms) { if ($mms) { switch ($carrier) { case 'att': return 'mms.att.net'; case 'airfiremobile': throw new \InvalidArgumentException('Air Fire Mobile does not support Email Gateway MMS messages.'); case 'alaskacommunicates': return 'msg.acsalaska.com'; case 'ameritech': throw new \InvalidArgumentException('Ameritech does not support Email Gateway MMS messages.'); case 'assurancewireless': return 'vmobl.com'; case 'boostmobile': return 'myboostmobile.com'; case 'cleartalk': throw new \InvalidArgumentException('Clear Talk does not support Email Gateway MMS messages.'); case 'cricket': return 'mms.mycricket.com '; case 'metropcs': return 'mymetropcs.com'; case 'nextech': throw new \InvalidArgumentException('NexTech does not support Email Gateway MMS messages.'); case 'projectfi': return 'msg.fi.google.com'; case 'rogerswireless': return 'mms.rogers.com'; case 'unicel': return 'utext.com'; case 'verizonwireless': return 'vzwpix.com'; case 'virginmobile': return 'vmpix.com'; case 'tmobile': return 'tmomail.net'; case 'sprint': return 'pm.sprint.com'; case 'uscellular': return 'mms.uscc.net'; default: throw new \InvalidArgumentException('Carrier specified is not found.'); } } else { switch ($carrier) { case 'att': return 'txt.att.net'; case 'airfiremobile': return 'sms.airfiremobile.com'; case 'alaskacommunicates': return 'msg.acsalaska.com'; case 'ameritech': return 'paging.acswireless.com'; case 'assurancewireless': return 'vmobl.com'; case 'boostmobile': return 'sms.myboostmobile.com'; case 'cleartalk': return 'sms.cleartalk.us'; case 'cricket': return 'sms.mycricket.com'; case 'metropcs': return 'mymetropcs.com'; case 'nextech': return 'sms.ntwls.net'; case 'projectfi': return 'msg.fi.google.com'; case 'rogerswireless': return 'sms.rogers.com'; case 'unicel': return 'utext.com'; case 'verizonwireless': return 'vtext.com'; case 'virginmobile': return 'vmobl.com'; case 'tmobile': return 'tmomail.net'; case 'sprint': return 'messaging.sprintpcs.com'; case 'uscellular': return 'email.uscc.net'; default: throw new \InvalidArgumentException('Carrier specified is not found.'); } } }
Finds the gateway based on the carrier and MMS. @param string $carrier @param bool $mms @return string
entailment
public function send(OutgoingMessage $message) { $from = $message->getFrom(); $composeMessage = $message->composeMessage(); foreach ($message->getTo() as $to) { $this->twilio->account->messages->create([ 'To' => $to, 'From' => $from, 'Body' => $composeMessage, 'MediaUrl' => $message->getAttachImages(), ]); } }
Sends a SMS message. @param \SimpleSoftwareIO\SMS\OutgoingMessage $message
entailment
protected function processReceive($raw) { $incomingMessage = $this->createIncomingMessage(); $incomingMessage->setRaw($raw); $incomingMessage->setMessage($raw->body); $incomingMessage->setFrom($raw->from); $incomingMessage->setId($raw->sid); $incomingMessage->setTo($raw->to); }
Processing the raw information from a request and inputs it into the IncomingMessage object. @param $raw
entailment
public function checkMessages(array $options = []) { $start = array_key_exists('start', $options) ? $options['start'] : 0; $end = array_key_exists('end', $options) ? $options['end'] : 25; $rawMessages = $this->twilio->account->messages->getIterator($start, $end, $options); $incomingMessages = []; foreach ($rawMessages as $rawMessage) { $incomingMessage = $this->createIncomingMessage(); $this->processReceive($incomingMessage, $rawMessage); $incomingMessages[] = $incomingMessage; } return $incomingMessages; }
Checks the server for messages and returns their results. @param array $options @return array
entailment
public function getMessage($messageId) { $rawMessage = $this->twilio->account->messages->get($messageId); $incomingMessage = $this->createIncomingMessage(); $this->processReceive($incomingMessage, $rawMessage); return $incomingMessage; }
Gets a single message by it's ID. @param string|int $messageId @return \SimpleSoftwareIO\SMS\IncomingMessage
entailment
protected function validateRequest() { //Twilio requires that all POST data be sorted alpha to validate. $data = $_POST; ksort($data); // append the data array to the url string, with no delimiters $url = $this->url; foreach ($data as $key => $value) { $url = $url.$key.$value; } //Encode the request string $hmac = hash_hmac('sha1', $url, $this->authToken, true); //Verify it against the given Twilio key if (base64_encode($hmac) != $_SERVER['HTTP_X_TWILIO_SIGNATURE']) { throw new \InvalidArgumentException('This request was not able to verify it came from Twilio.'); } }
Checks if a message is authentic from Twilio. @throws \InvalidArgumentException
entailment
public function sseMessageLine($text, $id = null) { if (!is_null($id)) { echo "id: $id\n"; } $text = explode("\n", $text); $text = 'data: '.implode("\ndata: ", $text)."\n\n"; echo $text; flush(); }
Sends text through SSE channel. Text may contain newlines which will be transmitted proprely. Optionally you can specify ID also.
entailment
public function sseMessageJSON($text, $id = null) { if (!is_null($id)) { echo "id: $id\n"; } $text = 'data: '.json_encode($text)."\n\n"; $this->_out_encoding = false; echo $text; flush(); $this->_out_encoding = true; }
Sends text or structured data through SSE channel encoded in JSON format. You may supply id argument.
entailment
public function jsEval($str) { if (is_object($str)) { $str = $str->_render(); } $data = ['js' => $str]; $this->sseMessageJSON($data); }
Add ability to send javascript.
entailment
public function out($str, $opt = array()) { $data = array_merge($opt, ['text' => rtrim($str, "\n")]); //if($color)$data['style']='color: '.$color; $this->sseMessageJSON($data); }
Displays output in the console.
entailment
public function rule_regex($a) { $opt = array(); $rule = $this->pullRule(); if ($rule[0] != '/') { $rule = '/^'.$rule.'*$/'; } $opt['regexp'] = $rule; if (!filter_var($a, FILTER_VALIDATE_REGEXP, ['options' => $opt])) { return $this->fail('does not match the pattern'); } }
Requires a regex pattern as the next rule in the chain. Please give your rule a custom error message.
entailment
public function rule_in($a) { $vals = $this->prep_in_vals($a); if (!in_array($a, $vals)) { return $this->fail('has an invalid value'); } }
Checks that value is in the list provided. Syntax: |in|foo,bar,foobar.
entailment
public function rule_not_in($a) { $vals = $this->prep_in_vals($a); if (in_array($a, $vals)) { return $this->fail('has an invalid value'); } }
Checks that value is not in the list provided. Syntax: |not_in|foo,bar,foobar.
entailment
public function rule_between($a) { $min = $this->pullRule(true); $max = $this->pullRule(true); if (is_numeric($a)) { if ($a < $min || $a > $max) { return $this->fail('must be between {{arg1}} and {{arg2}}', $min, $max); } } else { return $this->fail('Must be a numeric value'); } }
Inclusive range check. Overloaded: checks value for numbers, string-length for other values. Next 2 rules must specify the min and max
entailment
public function rule_decimal_places($a) { $places = $this->pullRule(); $pattern = sprintf('/^[0-9]+\.[0-9]{%s}$/', $places); if (!preg_match($pattern, $a)) { return $this->fail('Must have {{arg1}} decimal places', $places); } }
Checks for a specific number of decimal places. Arg: int- number of places
entailment
public function rule_bool($a) { // We don't use PHP inbuilt test - a bit restrictive // Changes PHP true/false to 1, 0 $a = strtolower($a); $vals = array('true', 'false', 't', 'f', 1, 0, 'yes', 'no', 'y', 'n'); if (!in_array($a, $vals)) { return $this->fail('Must be a boolean value'); } }
Validate for true|false|t|f|1|0|yes|no|y|n. Normalizes to lower case
entailment
public function rule_true($a) { // Changes PHP true to 1 $a = strtolower($a); $vals = array('true', 't', 1, 'yes', 'y'); if (!in_array($a, $vals)) { return $this->fail('Must be true'); } }
Validate for true|t|1|yes|y. Normalizes to lower case Useful for 'if' rules
entailment
public function rule_false($a) { // Changes PHP false to 0 $a = strtolower($a); $vals = array('false', 'f', 0, 'no', 'n'); if (!in_array($a, $vals)) { return $this->fail('Must be false'); } }
Validate for false|f|0|no|n. Normalizes to lower case Useful for 'if' rules
entailment
public function validate_iso_date($a) { $date = explode('-', $a); $msg = 'Must be date in format: YYYY-MMM-DD'; if (count($date) != 3) { return $this->fail($msg); } if (strlen($date[0]) !== 4 || strlen($date[1]) !== 2 || strlen($date[2]) !== 2) { return $this->fail($msg); } if (!@checkdate($date[1], $date[2], $date[0])) { return $this->fail($msg); } }
Validate for ISO date in format YYYY-MM-DD. Also checks for valid month and day values
entailment
public function rule_iso_time($a) { $pattern = "/^([0-9]{2}):([0-9]{2})(?::([0-9]{2})(?:(?:\.[0-9]{1,}))?)?$/"; $msg = 'Must be a valid ISO time'; if (preg_match($pattern, $a, $matches)) { if ($matches[1] > 24) { return $this->fail($msg); } if ($matches[2] > 59) { return $this->fail($msg); } if (isset($matches[3]) && $matches[3] > 59) { return $this->fail($msg); } } else { return $this->fail($msg); } }
Validate for ISO time. Requires a complete hour:minute:second time with the optional ':' separators. Checks for hh:mm[[:ss][.**..] where * = microseconds Also checks for valid # of hours, mins, secs
entailment
public function rule_iso_datetime($a) { $parts = explode(' ', $a); $msg = 'Must be a valid ISO datetime'; if (count($parts) != 2) { return $this->fail($msg); } try { $this->rule_iso_date($parts[0]); } catch (Exception $e) { return $this->fail($msg); } try { $this->rule_iso_time($parts[1]); } catch (Exception $e) { return $this->fail($msg); } }
Validate ISO datetime in the format:. YYYY-MM-DD hh:mm:ss with optional microseconds
entailment
public function rule_before($a) { $time = $this->pullRule(); if (strtotime($a) >= strtotime($time)) { return $this->fail('Must be before {{arg1}}', $time); } }
Checks any PHP datetime format: http://www.php.net/manual/en/datetime.formats.date.php.
entailment
public function rule_after($a) { $time = $this->pullRule(); if (strtotime($a) <= strtotime($time)) { return $this->fail('Must be after {{arg1}}', $time); } }
Checks any PHP datetime format: http://www.php.net/manual/en/datetime.formats.date.php.
entailment
public function rule_credit_card($a) { // Card formats keep changing and there is too high a risk // of false negatives if we get clever. So we just check it // with the Luhn Mod 10 formula // Calculate the Luhn check number $msg = 'Not a valid card number'; $sum = 0; $alt = false; for ($i = strlen($a) - 1; $i >= 0; --$i) { $n = substr($a, $i, 1); if ($alt) { //square n $n *= 2; if ($n > 9) { //calculate remainder $n = ($n % 10) + 1; } } $sum += $n; $alt = !$alt; } // If $sum divides exactly by 10 it's valid if (!($sum % 10 == 0)) { return $this->fail($msg); } else { // Luhn check seems to return true for any string of 0s $stripped = str_replace('0', '', $a); if (strlen($stripped) == 0) { return $this->fail($msg); } } }
Validate for credit card number. Uses the Luhn Mod 10 check
entailment
public function rule_to_truncate_custom($a) { $len = $this->pullRule(); $append = $this->pullRule(); return $this->mb_truncate($a, $len, $append); }
Requires parameters: length, custom string to end of string.
entailment
public function rule_to_name($name, $is_capitalise_prefix = false) { /* A name can have up to 5 components, space delimited: Worst case: salutation | forenames | prefix(es) | main name | suffix Ms | Jo-Sue Ellen | de la | Mer-Savarin | III Rules for forenames 1) Capitalise 1st char and after a hyphen. Rules for special case prefixes: von, de etc 1) Set capitalisation at runtime. There seem to be no fixed rules, but lower case is commonly used as part of a whole name: John von Trapp While it is normally capitalised as part of a salutation: Dear Mr Von Trapp By default we store in the lower case form. Set the param $is_capitalise_prefix to true to capitalise. 2) In default mode, St is capitalised, other prefixes lower cased. We retain user's choice of punctuation with St./St Rules for main name: 1) Capitalise after a hyphen in the main name: Smythington-Fenwick 2) Capitalise after Mc at start of name - this is pretty much a universal rule MCDONALD => McDonald 3) Unless user has capitalised after the M, do NOT capitalise after Mac at start of name: - Many Scottish Mac names are not capitalised: Macaulay, Macdonald - Many non-Scottish names start with Mac: eg Macon - we want to avoid "MacOn"; - The Cpan name modules and some style manuals force MacDonald, but this seems to create more problems than it solves. macrae => Macrae 4) Capitalise after O' o'grady => O'Grady */ // If name string is empty, bail out if (empty($name)) { return ''; } // Setup special case prefix lookup list. // These are prefixes that are not capitalised. // Prefixes which are capitalised such as "St" // can be omitted. // We omit prefixes that are also common names, // such as "Della", "Di" and "Ben" $prefixes = array( 'ap' => array('upper' => 'Ap', 'lower' => 'ap'), 'da' => array('upper' => 'Da', 'lower' => 'da'), 'de' => array('upper' => 'De', 'lower' => 'de'), 'del' => array('upper' => 'Del', 'lower' => 'del'), 'der' => array('upper' => 'Der', 'lower' => 'der'), 'du' => array('upper' => 'Du', 'lower' => 'du'), 'la' => array('upper' => 'La', 'lower' => 'la'), 'le' => array('upper' => 'Le', 'lower' => 'le'), 'lo' => array('upper' => 'Lo', 'lower' => 'lo'), 'van' => array('upper' => 'Van', 'lower' => 'van'), 'von' => array('upper' => 'Von', 'lower' => 'von'), ); // Set up suffix lookup list // We preserve user's preferred punctuation: Sr./Sr $suffixes = array( 'i' => 'I', 'ii' => 'II', 'iii' => 'III', 'iv' => 'IV', 'v' => 'V', 'vi' => 'VI', 'vii' => 'VII', 'viii' => 'VIII', 'ix' => 'IX', 'x' => 'X', 'jr.' => 'Jr.', 'jr' => 'Jr', 'jnr.' => 'Jnr.', 'jnr' => 'Jnr', 'sr.' => 'Sr.', 'sr' => 'Sr', 'snr.' => 'Snr.', 'snr' => 'Snr', '1st' => '1st', '2nd' => '2nd', '3rd' => '3rd', '4th' => '4th', '5th' => '5th', '6th' => '6th', '7th' => '7th', '8th' => '8th', '9th' => '9th', '10th' => '10th', '1st.' => '1st.', '2nd.' => '2nd.', '3rd.' => '3rd.', '4th.' => '4th.', '5th.' => '5th.', '6th.' => '6th.', '7th.' => '7th.', '8th.' => '8th.', '9th.' => '9th.', '10th.' => '10th.', ); // Clean out extra whitespace $name = $this->strip_excess_whitespace(trim($name)); // Try to parse into forenames, main name, suffix $parts = explode(' ', $name); if (count($parts) == 1) { // Must be the main name $name_main = array_pop($parts); $name_fname = false; $name_suffix = false; } else { // We have more than one part to parse // Is the last part a suffix? // We assume name can have only one suffix $part = array_pop($parts); $normalised_part = strtolower($part); if (array_key_exists($normalised_part, $suffixes)) { // Last part is a suffix $name_main = array_pop($parts); $name_suffix = $suffixes[$normalised_part]; } else { // Last part is the main name $name_main = $part; $name_suffix = false; } } // Anything left is a salutation, initial or forname if (count($parts) > 0) { $name_fnames = $parts; } else { $name_fnames = false; } // We build the name from first to last: $new_name = array(); // Set case for the forenames if ($name_fnames) { foreach ($name_fnames as $fname) { $parts = array(); $fname = strtolower($fname); // Do hypenated parts separately $exploded_fname = explode('-', $fname); foreach ($exploded_fname as $part) { // If it is one of our special case prefixes // we use the appropriate value // Else, we capitalise if (array_key_exists($part, $prefixes)) { if ($is_capitalise_prefix !== false) { $parts[] = $prefixes[$part]['upper']; } else { $parts[] = $prefixes[$part]['lower']; } } else { // It is a normal forename, salutation or initial // We capitalise it. $parts[] = ucfirst($part); } } $new_name[] = implode('-', $parts); } } // Set case for the main name $name_main_original = $name_main; $name_main = strtolower($name_main); // Do hypenated parts separately $exploded_main_original = explode('-', $name_main_original); $exploded_main = explode('-', $name_main); $parts = array(); foreach ($exploded_main as $key => $part) { $part_original = $exploded_main_original[$key]; if (substr($part, 0, 2) == 'mc') { // Do "Mc" // Uppercase the 3rd character $a = substr($part, 2); $parts[] = 'Mc'.ucfirst($a); } elseif (substr($part, 0, 3) == 'mac') { // Do "Mac" // Lowercase the 3rd character // unless user has submitted // a correct looking name if (preg_match('|^Mac[A-Z][a-z]*$|', $part_original)) { $parts[] = $part_original; } else { $parts[] = ucfirst($part); } } elseif (substr($part, 0, 2) == "o'") { // Do O' // Uppercase the 3rd character $a = substr($part, 2); $parts[] = "O'".ucwords($a); } else { // It is a plain-jane name $parts[] = ucfirst($part); } } $new_name[] = implode('-', $parts); if ($name_suffix !== false) { $new_name[] = $name_suffix; } // Assemble the new name $output = implode(' ', $new_name); return $output; }
Useful for cleaning up input where you don't want to present an error to the user - eg a checkout where ease of use is more important than accuracy. Can save a lot of re-keying. Some libraries don't clean up names if already in mixed case. Experience shows this isn't very useful, as many users will type mAry, JOSepH etc. Can only be a best guess - but much better than nothing: has been in production for years without any negative customer feedback. Set $is_capitalise_prefix if you want prefixes in upper: Von Trapp vs von Trapp. You would do this to format a last name for use in salutations: Dear Mr Von Trapp Can handle full names, 1st only, middle only, last only. Cleans up extra whitespace.
entailment
protected function card_date_parser($a, $type) { // Strip out any slash $date = str_replace('/', '', $a); // Check that we have 4 digits if (!preg_match('|^[0-9]{4}$|', $date)) { return false; } $month = substr($date, 0, 2); $year = substr($date, 2, 2); // Check month is logical if ($month > 12) { return false; } $parts = array(date('Y'), date('m'), 1); $now_datetime = new DateTime(implode('-', $parts)); $parts = array('20'.$year, $month, '1'); $card_datetime = new DateTime(implode('-', $parts)); $interval = $now_datetime->diff($card_datetime); $days = $interval->format('%R%a days'); if ($type == 'from') { // Check from date is older or equal to current month if ($days <= 0 && $days > -3650) { return true; } else { return false; } } elseif ($type == 'to') { // Check to date is newer or equal to current month if ($days >= 0 && $days < 3650) { return true; } else { return false; } } else { $msg = "Bad date type '$type' in card-date validation"; throw new Error($msg); } }
Helper for validating card to and from dates.
entailment
protected function prep_in_vals($a) { $vals = $this->pullRule(); if (is_array($vals)) { return $vals; } $vals = explode(',', $vals); array_walk($vals, function ($val) { return trim($val); }); // create_function('&$val', '$val = trim($val);')); return $vals; }
Explode and trim a comma-delmited list for the in and not_in rules.
entailment
public function setActualFields($fields) { if ($this->owner->model->hasMethod('getActualFields')) { $this->importFields($this->owner->model, $fields); } }
Import model fields in grid. @param array|string|bool $fields
entailment
public function importFields($model, $fields = null) { $this->model = $model; $this->grid = $this->owner; if ($fields === false) { return; } if (!$fields) { $fields = 'visible'; } if (!is_array($fields)) { // note: $fields parameter only useful if model is SQL_Model $fields = $model->getActualFields($fields); } // import fields one by one foreach ($fields as $field) { $this->importField($field); } $model->setActualFields($fields); return $this; }
Import model fields in form. @param Model $model @param array|string|bool $fields @return void|$this
entailment
public function importField($field) { $field = $this->model->hasElement($field); if (!$field) { return; } /** @type Field $field */ $field_name = $field->short_name; if ($field instanceof Field_Reference) { $field_name = $field->getDereferenced(); } $field_type = $this->getFieldType($field); /** @type string $field_caption */ $field_caption = $field->caption(); $this->field_associations[$field_name] = $field; $column = $this->owner->addColumn($field_type, $field_name, $field_caption); if ($field->sortable() && $column->hasMethod('makeSortable')) { $column->makeSortable(); } return $column; }
Import one field from model into grid. @param string $field @return void|Grid|Controller_Grid_Format
entailment
public function _beforeInit() { $this->pm = $this->add($this->pagemanager_class, $this->pagemanager_options); /** @type Controller_PageManager $this->pm */ $this->pm->parseRequestedURL(); parent::_beforeInit(); }
Executed before init, this method will initialize PageManager and pathfinder.
entailment
public function init() { $this->getLogger(); // Verify Licensing //$this->licenseCheck('atk4'); // send headers, no caching $this->sendHeaders(); $this->cleanMagicQuotes(); parent::init(); // in addition to default initialization, set up logger and template $this->initializeTemplate(); if (get_class($this) == 'App_Web') { $this->setConfig(array('url_postfix' => '.php', 'url_prefix' => '')); } }
Redefine this function instead of default constructor.
entailment
public function cleanMagicQuotes() { if (!function_exists('stripslashes_array')) { function stripslashes_array(&$array, $iterations = 0) { if ($iterations < 3) { foreach ($array as $key => $value) { if (is_array($value)) { stripslashes_array($array[$key], $iterations + 1); } else { $array[$key] = stripslashes($array[$key]); } } } } } if (get_magic_quotes_gpc()) { stripslashes_array($_GET); stripslashes_array($_POST); stripslashes_array($_COOKIE); } }
Magic Quotes were a design error. Let's strip them if they are enabled.
entailment
public function destroySession() { if ($this->_is_session_initialized) { $_SESSION = array(); if (isset($_COOKIE[$this->name])) { setcookie($this->name/*session_name()*/, '', time() - 42000, '/'); } session_destroy(); $this->_is_session_initialized = false; } }
Completely destroy existing session.
entailment
public function addStylesheet($file, $ext = '.css', $locate = 'css') { //$file = $this->app->locateURL('css', $file . $ext); if (@$this->included[$locate.'-'.$file.$ext]++) { return; } if (strpos($file, 'http') !== 0 && $file[0] != '/') { $url = $this->locateURL($locate, $file.$ext); } else { $url = $file; } $this->template->appendHTML( 'js_include', '<link type="text/css" href="'.$url.'" rel="stylesheet" />'."\n" ); return $this; }
@todo Description @param string $file @param string $ext @param string $locate @return $this
entailment
public function main() { try { // Initialize page and all elements from here $this->initLayout(); } catch (Exception $e) { if (!($e instanceof Exception_Stop)) { return $this->caughtException($e); } //$this->caughtException($e); } try { $this->hook('post-init'); $this->hook('afterInit'); $this->hook('pre-exec'); $this->hook('beforeExec'); if (isset($_GET['submit']) && $_POST) { $this->hook('submitted'); } $this->hook('post-submit'); $this->hook('afterSubmit'); $this->execute(); } catch (Exception $e) { $this->caughtException($e); } $this->hook('saveDelayedModels'); }
Call this method from your index file. It is the main method of Agile Toolkit.
entailment
public function execute() { $this->rendered['sub-elements'] = array(); try { $this->hook('pre-render'); $this->hook('beforeRender'); $this->recursiveRender(); if (isset($_GET['cut_object'])) { throw new BaseException("Unable to cut object with name='".$_GET['cut_object']."'. ". "It wasn't initialized"); } if (isset($_GET['cut_region'])) { // @todo Imants: This looks something obsolete. At least property cut_region_result is never defined. if (!$this->cut_region_result) { throw new BaseException("Unable to cut region with name='".$_GET['cut_region']."'"); } echo $this->cut_region_result; return; } } catch (Exception $e) { if ($e instanceof Exception_Stop) { $this->hook('cut-output'); if (isset($e->result)) { echo $e->result; } $this->hook('post-render-output'); return; } throw $e; } }
Main execution loop.
entailment
public function render() { $this->hook('pre-js-collection'); if (isset($this->app->jquery) && $this->app->jquery) { $this->app->jquery->getJS($this); } if (!($this->template)) { throw new BaseException('You should specify template for APP object'); } $this->hook('pre-render-output'); if (headers_sent($file, $line)) { echo "<br />Direct output (echo or print) detected on $file:$line. <a target='_blank' " ."href='http://agiletoolkit.org/error/direct_output'>Use \$this->add('Text') instead</a>.<br />"; } echo $this->template->render(); $this->hook('post-render-output'); }
Renders all objects inside applications and echo all output to the browser.
entailment
public function redirect($page = null, $args = array()) { /* * Redirect to specified page. $args are $_GET arguments. * Use this function instead of issuing header("Location") stuff */ $url = $this->url($page, $args); if ($this->app->isAjaxOutput()) { if ($_GET['cut_page']) { echo '<script>'.$this->app->js()->redirect($url).'</script>Redirecting page...'; exit; } else { $this->app->js()->redirect($url)->execute(); } } header('Location: '.$url); exit; }
Perform instant redirect to another page. @param string $page @param array $args
entailment
public function setTags($t) { // Determine Location to atk_public if ($this->app->pathfinder && $this->app->pathfinder->atk_public) { $q = $this->app->pathfinder->atk_public->getURL(); } else { $q = 'http://www.agiletoolkit.org/'; } $t->trySet('atk_path', $q.'/'); $t->trySet('base_path', $q = $this->app->pm->base_path); // We are using new capability of SMlite to process tags individually try { $t->eachTag($tag = 'template', array($this, '_locateTemplate')); $t->eachTag($tag = 'public', array($this, '_locatePublic')); $t->eachTag($tag = 'js', array($this, '_locateJS')); $t->eachTag($tag = 'css', array($this, '_locateCSS')); $t->eachTag($tag = 'page', array($this, 'getBaseURL')); } catch (BaseException $e) { throw $e ->addMoreInfo('processing_tag', $tag) ->addMoreInfo('template', $t->template_file) ; } $this->hook('set-tags', array($t)); }
Called on all templates in the system, populates some system-wide tags. @param Template $t
entailment
public function addLayout($name) { if (!$this->template) { return; } // TODO: change to functionExists() if (method_exists($this, $lfunc = 'layout_'.$name)) { if ($this->template->is_set($name)) { $this->$lfunc(); } } return $this; }
Register new layout, which, if has method and tag in the template, will be rendered. @param string $name @return $this
entailment
public function layout_Content() { $page = str_replace('/', '_', $this->page); if (method_exists($this, $pagefunc = 'page_'.$page)) { $p = $this->add('Page', $this->page, 'Content'); $this->$pagefunc($p); } else { $this->app->locate('page', str_replace('_', '/', $this->page).'.php'); $this->add('page_'.$page, $page, 'Content'); //throw new BaseException("No such page: ".$this->page); } }
Default handling of Content page. To be replaced by App_Frontend This function initializes content. Content is page-dependant.
entailment
public function send(OutgoingMessage $message) { $composeMessage = $message->composeMessage(); $from = $message->getFrom(); foreach ($message->getTo() as $to) { $data = [ 'from' => $from, 'bulkVariant' => $this->getVariantForSender($from), 'message' => $composeMessage, 'to' => $to, ]; $response = $this->sendRequest($data); if ($this->hasError($response)) { $this->handleError($response); } } }
Sends a SMS message. @param \SimpleSoftwareIO\SMS\OutgoingMessage $message
entailment
protected function sendRequest($data) { $curl = curl_init(); $options = [ CURLOPT_URL => "https://justsend.pl/api/rest/message/send/{$this->apiKey}/", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_HTTPHEADER => [ 'content-type: application/json', ], ]; curl_setopt_array($curl, $options); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { $this->throwNotSentException('cURL Error #:'.$err); } return json_decode($response, true); }
@param $data @return mixed
entailment
protected function handleError($response) { $message = $response['responseCode'].' ('.$response['errorId'].'): '.$response['message']; $this->throwNotSentException($message, $response['errorId']); }
Log the error message which ocurred. @param $response
entailment
public function getValue($model, $data) { /** @type Model $model */ $model = $this->add($this->getModel()); $id = $data[$this->foreignName]; try { $this->hook('beforeForeignLoad', array($model, $id)); $model->load($id); $titleField = $model->getTitleField(); return $model->get($titleField) ?: 'Ref#'.$id; } catch (BaseException $e) { // record is no longer there it seems return null; } }
@todo Useless method parameter $model @param Model $model @param array $data @return mixed
entailment
public function init() { $this->connect(); $this->tmpFile(); if (!is_file($this->config->file) || !is_readable($this->config->file)) { throw new Exception('Unable to access the source file.'); } if ($this->compress) { $gzip = new Compress(); $gzip->unpack($this->config->file, $this->temp); } else { copy($this->config->file, $this->temp); } $this->open($this->temp, 'r'); $this->import(); $this->close(); $this->clean(); }
{@inheritdoc}
entailment
protected function import() { $query = ''; while (!feof($this->file)) { $line = fgets($this->file); $trim = trim($line); if ($trim === '' || strpos($trim, '--') === 0 || strpos($trim, '/*') === 0) { continue; } if (strpos($trim, 'DELIMITER ') === 0) { $this->delimiter = substr($trim, 10); continue; } $query .= $line; if (substr($trim, strlen($this->delimiter) * -1) === $this->delimiter) { $this->pdo->exec(substr(trim($query), 0, strlen($this->delimiter) * -1)); $query = ''; } } }
Processes the SQL file. Reads a SQL file by line by line. Expects that individual queries are separated by semicolons, and that quoted values are properly escaped, including newlines. Queries themselves can not contain any comments. All comments are stripped from the file.
entailment
public function init() { parent::init(); $this->days = array(); for ($i = 1; $i <= 31; ++$i) { $this->days[$i] = str_pad($i, 2, '0', STR_PAD_LEFT); } $cur_year = date('Y'); $this->setYearRange($cur_year - 3, $cur_year + 3); $this->c_year = $cur_year; $this->c_month = date('m'); $this->c_day = date('d'); $this->enable(); }
/ }}}
entailment
public function init() { parent::init(); if (!$this->db) { $this->db = $this->app->db; } if ($this->owner instanceof Field_Reference && !empty($this->owner->owner->relations)) { $this->relations = &$this->owner->owner->relations; } }
{@inheritdoc}
entailment
public function addField($name, $actual_field = null) { if ($this->hasElement($name)) { if ($name == $this->id_field) { return $this->getElement($name); } throw $this->exception('Field with this name is already defined') ->addMoreInfo('field', $name); } if ($name == 'deleted' && isset($this->app->compat)) { /** @type Field_Deleted $f */ $f = $this->add('Field_Deleted', $name); return $f->enum(array('Y', 'N')); } // $f=parent::addField($name); /** @type Field $f */ $f = $this->add($this->field_class, $name); // if (!is_null($actual_field)) { $f->actual($actual_field); } return $f; }
Adds field to model @param string $name @param string $actual_field @return Field
entailment
public function initQuery() { if (!$this->table) { throw $this->exception('$table property must be defined'); } $this->dsql = $this->db->dsql(); $this->dsql->debug($this->debug); $this->dsql->table($this->table, $this->table_alias); $this->dsql->default_field = $this->dsql->expr('*,'. $this->dsql->bt($this->table_alias ?: $this->table).'.'. $this->dsql->bt($this->id_field)) ; $this->dsql->id_field = $this->id_field; return $this; }
Initializes base query for this model. @link http://agiletoolkit.org/doc/modeltable/dsql
entailment
public function debug($enabled = true) { if ($enabled === true) { $this->debug = $enabled; if ($this->dsql) { $this->dsql->debug($enabled); } } else { parent::debug($enabled); } return $this; }
Turns debugging mode on|off for this model. All database operations will be outputed. @param bool $enabled @return $this
entailment
public function selectQuery($fields = null) { /**/$this->app->pr->start('selectQuery/getActualF'); $actual_fields = $fields ?: $this->getActualFields(); if ($this->fast && $this->_selectQuery) { return $this->_selectQuery(); } $this->_selectQuery = $select = $this->_dsql()->del('fields'); /**/$this->app->pr->next('selectQuery/addSystemFields'); // add system fields into select foreach ($this->elements as $el) { if ($el instanceof Field) { if ($el->system() && !in_array($el->short_name, $actual_fields)) { $actual_fields[] = $el->short_name; } } } /**/$this->app->pr->next('selectQuery/updateQuery'); // add actual fields foreach ($actual_fields as $field) { /** @type Field $field */ $field = $this->hasElement($field); if (!$field) { continue; } $field->updateSelectQuery($select); } /**/$this->app->pr->stop(); return $select; }
Completes initialization of dsql() by adding fields and expressions. @param array $fields @return DB_dsql
entailment
public function fieldQuery($field) { $query = $this->dsql()->del('fields'); if (is_string($field)) { $field = $this->getElement($field); } $field->updateSelectQuery($query); return $query; }
Return query for a specific field. All other fields are ommitted.
entailment
public function titleQuery() { $query = $this->dsql()->del('fields'); /** @type Field $el */ $el = $this->hasElement($this->title_field); if ($this->title_field && $el) { $el->updateSelectQuery($query); return $query; } return $query->field($query->concat('Record #', $this->getElement($this->id_field))); }
Returns query which selects title field
entailment
public function addExpression($name, $expression = null) { /** @type Field_Expression $f */ $f = $this->add('Field_Expression', $name); return $f->set($expression); }
Adds and returns SQL-calculated expression as a read-only field. See Field_Expression class. @param string $name @param mixed $expression @return DB_dsql
entailment
public function join( $foreign_table, $master_field = null, $join_kind = null, $_foreign_alias = null, $relation = null ) { if (!$_foreign_alias) { $_foreign_alias = '_'.$foreign_table[0]; } $_foreign_alias = $this->_unique($this->relations, $_foreign_alias); /** @type SQL_Relation $rel */ $rel = $this->add('SQL_Relation', $_foreign_alias); return $this->relations[$_foreign_alias] = $rel ->set($foreign_table, $master_field, $join_kind, $relation); }
Constructs model from multiple tables. Queries will join tables, inserts, updates and deletes will be applied on both tables
entailment
public function leftJoin( $foreign_table, $master_field = null, $join_kind = null, $_foreign_alias = null, $relation = null ) { if (!$join_kind) { $join_kind = 'left'; } $res = $this->join($foreign_table, $master_field, $join_kind, $_foreign_alias, $relation); $res->delete_behaviour = 'ignore'; return $res; }
Creates weak join between tables. The foreign table may be absent and will not be automatically deleted.
entailment
public function hasOne($model, $our_field = null, $display_field = null, $as_field = null) { // register reference, but don't create any fields there // parent::hasOne($model,null); // model, our_field $this->_references[null] = $model; if (!$our_field) { if (!is_object($model)) { $tmp = $this->app->normalizeClassName($model, 'Model'); $tmp = new $tmp(); // avoid recursion } else { $tmp = $model; } $our_field = ($tmp->table).'_id'; } /** @type Field_Reference $r */ $r = $this->add('Field_Reference', array('name' => $our_field, 'dereferenced_field' => $as_field)); $r->setModel($model, $display_field); $r->system(true)->editable(true); return $r; }
Defines one to many association
entailment
public function hasMany($model, $their_field = null, $our_field = null, $as_field = null) { if (!$our_field) { $our_field = $this->id_field; } if (!$their_field) { $their_field = ($this->table).'_id'; } /** @type SQL_Many $rel */ $rel = $this->add('SQL_Many', $as_field ?: $model); $rel->set($model, $their_field, $our_field); return $rel; }
Defines many to one association
entailment
public function containsOne($field, $model) { if (is_array($field) && $field[0]) { $field['name'] = $field[0]; unset($field[0]); } if ($e = $this->hasElement(is_string($field) ? $field : $field['name'])) { $e->destroy(); } $this->add('Relation_ContainsOne', $field) ->setModel($model); }
Defines contained model for field
entailment
public function ref($name, $load = null) { if (!$name) { return $this; } /** @type Field $field */ $field = $this->getElement($name); return $field->ref($load); }
Traverses references. Use field name for hasOne() relations. Use model name for hasMany()
entailment
public function refSQL($name, $load = null) { /** @type Field_Reference $ref */ $ref = $this->getElement($name); return $ref->refSQL($load); }
Returns Model with SQL join usable for subqueries.
entailment
public function addCondition($field, $cond = UNDEFINED, $value = UNDEFINED, $dsql = null) { // by default add condition to models DSQL if (!$dsql) { $dsql = $this->_dsql(); } // if array passed, then create multiple conditions joined with OR if (is_array($field)) { $or = $this->dsql()->orExpr(); foreach ($field as $row) { if (!is_array($row)) { $row = array($row); } // add each condition to OR expression (not models DSQL) $f = $row[0]; $c = array_key_exists(1, $row) ? $row[1] : UNDEFINED; $v = array_key_exists(2, $row) ? $row[2] : UNDEFINED; // recursively calls addCondition method, but adds conditions // to OR expression not models DSQL object $this->addCondition($f, $c, $v, $or); } // pass generated DSQL expression as "field" $field = $or; $cond = $value = UNDEFINED; } // You may pass DSQL expression as a first argument if ($field instanceof DB_dsql) { $dsql->where($field, $cond, $value); return $this; } // value should be specified if ($cond === UNDEFINED && $value === UNDEFINED) { throw $this->exception('Incorrect condition. Please specify value'); } // get model field object if (!$field instanceof Field) { $field = $this->getElement($field); } /** @type Field $field */ if ($cond !== UNDEFINED && $value === UNDEFINED) { $value = $cond; $cond = '='; } if ($field->type() == 'boolean') { $value = $field->getBooleanValue($value); } if ($cond === '=' && !is_array($value)) { $field->defaultValue($value)->system(true)->editable(false); } $f = $field->actual_field ?: $field->short_name; if ($field instanceof Field_Expression) { // TODO: should we use expression in where? $dsql->where($field->getExpr(), $cond, $value); //$dsql->having($f, $cond, $value); //$field->updateSelectQuery($this->dsql); } elseif ($field->relation) { $dsql->where($field->relation->short_name.'.'.$f, $cond, $value); } elseif (!empty($this->relations)) { $dsql->where(($this->table_alias ?: $this->table).'.'.$f, $cond, $value); } else { $dsql->where(($this->table_alias ?: $this->table).'.'.$f, $cond, $value); } return $this; }
Adds "WHERE" condition / conditions in underlying DSQL. It tries to be smart about where and how the field is defined. $field can be passed as: - string (field name in this model) - Field object - DSQL expression - array (see note below) $cond can be passed as: - string ('=', '>', '<=', etc.) - value can be passed here, then it's used as $value with condition '=' $value can be passed as: - string, integer, boolean or any other simple data type - Field object - DSQL expreession NOTE: $field can be passed as array of conditions. Then all conditions will be joined with `OR` using DSQLs orExpr method. For example, $model->addCondition(array( array('profit', '=', null), array('profit', '<', 1000), )); will generate "WHERE profit is null OR profit < 1000" EXAMPLES: you can pass [dsql, dsql, dsql ...] and this will be treated as (dsql OR dsql OR dsql) ... you can pass [[field,cond,value], [field,cond,value], ...] and this will be treated as (field=value OR field=value OR ...) BTW, you can mix these too :) [[field,cond,value], dsql, [field,cond,value], ...] will become (field=value OR dsql OR field=value) Value also can be DSQL expression, so following will work nicely: [dsql,'>',dsql] will become (dsql > dsql) [dsql, dsql] will become (dsql = dsql) [field, cond, dsql] will become (field = dsql) @todo Romans: refactor using parent::conditions (through array) @param mixed $field Field for comparing or array of conditions @param mixed $cond Condition @param mixed $value Value for comparing @param DB_dsql $dsql DSQL object to which conditions will be added @return $this
entailment
public function setLimit($count, $offset = null) { $this->_dsql()->limit($count, $offset); return $this; }
Sets limit on query
entailment