sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function incr($key, $offset = 1) { $value = $this->get($key) + $offset; return $this->set($key, $value) ? $value : false; }
Note: This method is not an atomic operation {@inheritdoc}
entailment
public function applyCoupon($basketId, string $couponCode) // !! DEPRECATED moved to basket { $params = [ "basketId" => $basketId, "couponCode" => $couponCode, ]; $response = $this->handler->handle('POST', $params, 'apply'); //TODO: refactor to make method return $response; // return $this->make($response, false); }
Apply coupon code to basket @param $basketId @param string $couponCode @return \GuzzleHttp\Promise\PromiseInterface|\SphereMall\MS\Lib\Http\Response @throws \Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function cancelCoupon($basketId, string $couponCode, $userId) // !! DEPRECATED moved to basket { $params = [ "basketId" => $basketId, "couponCode" => $couponCode, "userId" => $userId ]; $response = $this->handler->handle('POST', $params, 'discard'); //TODO: refactor to make method return $response; // return $this->make($response, false); }
Discard coupon code for basket @param integer $basketId @param string $couponCode @param integer $userId @return \GuzzleHttp\Promise\PromiseInterface|\SphereMall\MS\Lib\Http\Response @throws \Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function ret($message, $code = 1, $type = 'success') { return $this->ret->__invoke($message, $code, $type); }
Return operation result data @param string|array $message @param int $code @param string $type @return array
entailment
public function err($message, $code = -1, $level = 'info') { return $this->ret->err($message, $code, $level); }
Return operation failed result, and logs with an info level @param string|array $message @param int $code @param string $level @return array
entailment
protected function doCreateObject(array $array) { $productPriceConfiguration = new ProductPriceConfiguration($array); if (isset($array['prices']['affectAttributes'])) { $productPriceConfiguration->affectedAttributes = $array['prices']['affectAttributes']; } if (isset($array['prices']['priceTable'])) { foreach ($array['prices']['priceTable'] as $priceKey => $price) { $productPriceConfiguration->priceTable[$priceKey] = $price; } } // deprecated - work with an old response structure if(isset($array['prices']['priceWithVat'])) { $productPriceConfiguration->priceWithVat = $array['prices']['priceWithVat']; } if(isset($array['prices']['priceWithoutVat'])) { $productPriceConfiguration->priceWithoutVat = $array['prices']['priceWithoutVat']; } //Work with a new response structure if (isset($array['priceWithVat'])) { $productPriceConfiguration->priceWithVat = $array['priceWithVat']; } if (isset($array['priceWithoutVat'])) { $productPriceConfiguration->priceWithoutVat = $array['priceWithoutVat']; } if (isset($array['vatId'])) { $productPriceConfiguration->vatId = $array['vatId']; } if (isset($array['productVatId'])) { $productPriceConfiguration->productVatId = $array['productVatId']; } if (isset($array['vatPercent'])) { $productPriceConfiguration->vatPercent = $array['vatPercent']; } $productPriceConfiguration->removeProperty('prices'); return $productPriceConfiguration; }
@param array $array @return ProductPriceConfiguration
entailment
public function connect() { if ($this->isConnected) { return false; } if (!$this->pdo) { $this->beforeConnect && call_user_func($this->beforeConnect, $this); $dsn = $this->getDsn(); $attrs = $this->attrs + array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_STRINGIFY_FETCHES => true, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ); try { $this->pdo = new PDO($dsn, $this->user, $this->password, $attrs); } catch (\PDOException $e) { $this->connectFails && call_user_func($this->connectFails, $this, $e); throw $e; } $this->afterConnect && call_user_func($this->afterConnect, $this, $this->pdo); } $this->isConnected = true; return true; }
Connect to the database server @throws \PDOException When fails to connect to database server @return boolean
entailment
public function insert($table, array $data) { $table = $this->getTable($table); $field = implode(', ', array_keys($data)); $placeholder = array(); foreach ($data as $key => $value) { if ($value instanceof \stdClass && isset($value->scalar)) { $placeholder[] = $value->scalar; unset($data[$key]); } else { $placeholder[] = '?'; } } $placeholder = implode(', ', $placeholder); $query = "INSERT INTO $table ($field) VALUES ($placeholder)"; return $this->executeUpdate($query, array_values($data)); }
Executes an INSERT query to insert specified data into table @param string $table The name of table @param array $data An associative array containing column-value pairs @return int The number of affected rows
entailment
public function batchInsert($table, array $data, $extra = null) { $table = $this->getTable($table); $field = implode(', ', array_keys($data[0])); $placeholders = array(); $values = array(); switch ($this->driver) { default: case 'mysql': case 'pgsql': foreach ($data as $row) { $placeholders[] = '(' . implode(', ', array_pad(array(), count($row), '?')) . ')'; $values = array_merge($values, array_values($row)); } $placeholder = 'VALUES ' . implode(', ', $placeholders); break; // For SQLite before 3.7.11, http://www.sqlite.org/releaselog/3_7_11.html case 'sqlite': foreach ($data as $row) { $placeholders[] = 'SELECT ' . implode(', ', array_pad(array(), count($row), '?')); $values = array_merge($values, array_values($row)); } $placeholder = implode(' UNION ', $placeholders); break; } $query = "INSERT INTO $table ($field) $placeholder"; $extra && $query .= ' ' . $extra; return $this->executeUpdate($query, $values); }
Insert batch data into table @param string $table The name of table @param array $data A two-dimensional array @param string $extra A extra string concat after sql, like "ON DUPLICATE KEY UPDATE ..." @return int The number of inserted rows
entailment
public function update($table, array $data, array $conditions) { $table = $this->getTable($table); $set = $this->buildSqlObject($data, ', '); $where = $this->buildSqlObject($conditions, ' AND '); $query = "UPDATE $table SET $set WHERE $where"; $params = array_merge(array_values($data), array_values($conditions)); return $this->executeUpdate($query, $params); }
Executes a UPDATE query @param string $table The name of table @param array $data An associative array containing column-value pairs @param array $conditions The conditions to search records @return int The number of affected rows
entailment
public function delete($table, array $conditions) { $table = $this->getTable($table); $where = $this->buildSqlObject($conditions, ' AND '); $query = "DELETE FROM $table WHERE " . $where; return $this->executeUpdate($query, array_values($conditions)); }
Executes a DELETE query @param string $table The name of table @param array $conditions The conditions to search records @return int The number of affected rows
entailment
public function select($table, $conditions, $select = '*') { $data = $this->selectAll($table, $conditions, $select, 1); return $data ? $data[0] : false; }
Executes a SELECT query and return the first result ```php // Find by the "id" key $db->select('user', 1); // Find by specified column $db->select('user', array('username' => 'twin')); // Find in list $db->select('user', array('id' => array(1, 2, 3))); ``` @param string $table The name of table @param string|array $conditions The "id" key value or an associative array containing column-value pairs @param string $select The table columns to select @return array|false An associative array containing column-value pairs
entailment
public function selectAll($table, $conditions = false, $select = '*', $limit = null) { $params = array(); $query = "SELECT $select FROM " . $this->getTable($table) . ' '; if (is_array($conditions)) { if (!empty($conditions)) { $query .= "WHERE " . implode(' = ? AND ', array_keys($conditions)) . ' = ?'; $params = array_values($conditions); } } elseif ($conditions !== false) { $query .= "WHERE id = :id"; $params = array('id' => $conditions); } if ($limit) { $query .= " LIMIT $limit"; } return $this->query($query, $params)->fetchAll(); }
Executes a SELECT query and return all results ```php // Find by the "id" key $db->selectAll('user', 1); // Find by specified column $db->selectAll('user', array('username' => 'twin')); // Find in list $db->selectAll('user', array('id' => array(1, 2, 3))); ``` @param string $table The name of table @param bool $conditions The "id" key value or an associative array containing column-value pairs @param string $select The table columns to select @param int $limit The row number to retrieve @return array
entailment
public function fetch($sql, $params = array(), $types = array()) { return $this->query($sql, $params, $types)->fetch(); }
Executes a query and returns the first array result @param string $sql The SQL query @param mixed $params The query parameters @param array $types The parameter types to bind @return array|false Return an array or false when no result found
entailment
public function fetchAll($sql, $params = array(), $types = array()) { return $this->query($sql, $params, $types)->fetchAll(); }
Executes a query and returns all array results @param string $sql The SQL query @param mixed $params The query parameters @param array $types The parameter types to bind @return array|false Return an array or false when no result found
entailment
public function fetchColumn($sql, $params = array(), $column = 0) { return $this->query($sql, $params)->fetchColumn($column); }
Executes a query and returns a column value of the first row @param string $sql The SQL query @param mixed $params The query parameters @param int $column The index of column @return string
entailment
public function executeUpdate($sql, $params = array(), $types = array()) { return $this->query($sql, $params, $types, true); }
Executes an SQL INSERT/UPDATE/DELETE query with the given parameters and returns the number of affected rows @param string $sql The SQL query @param array $params The query parameters @param array $types The parameter types to bind @return int The number of affected rows
entailment
public function query($sql, $params = array(), $types = array(), $returnRows = false) { // A select query, using slave db if configured if (!$returnRows && $this->slaveDb) { /** @var $slaveDb \Wei\Db */ $slaveDb = $this->wei->get($this->slaveDb); return $slaveDb->query($sql, $params, $types, $returnRows); } $this->connect(); $this->queries[] = $sql; if ($this->beforeQuery) { call_user_func_array($this->beforeQuery, array($sql, $params, $types, $this)); } try { if (!$returnRows) { if ($params) { $stmt = $this->pdo->prepare($sql); if ($types) { $this->bindParameter($stmt, $params, $types); $stmt->execute(); } else { $stmt->execute((array)$params); } } else { $stmt = $this->pdo->query($sql); } $result = $stmt; } else { if ($params) { $stmt = $this->pdo->prepare($sql); $stmt->execute($params); $result = $stmt->rowCount(); } else { $result = $this->pdo->exec($sql); } } } catch (\PDOException $e) { // Builder exception message $msg = sprintf("An exception occurred while executing \"%s\" : \n\n %s", $sql, $e->getMessage()); $params && $msg .= ', with parameters ' . json_encode($params); // Reset exception message $message = new \ReflectionProperty($e, 'message'); $message->setAccessible(true); $message->setValue($e, $msg); throw $e; } if ($this->afterQuery) { call_user_func_array($this->afterQuery, array($sql, $params, $types, $this)); } return $result; }
Executes an SQL statement, returning a PDOStatement object or the number of affected rows @param string $sql The SQL query @param array $params The SQL parameters @param array $types The parameter types to bind @param bool $returnRows Whether returns a PDOStatement object or the number of affected rows @throws \PDOException @return \PDOStatement|int
entailment
public function sum($table, $field, $conditions = false) { return $this->executeAggregate('SUM', $table, $field, $conditions); }
Returns the sum of specified table field and conditions @param string $table @param string $field @param mixed $conditions @return float
entailment
public function max($table, $field, $conditions = false) { return $this->executeAggregate('MAX', $table, $field, $conditions); }
Returns the max value of specified table field and conditions @param string $table @param string $field @param mixed $conditions @return float
entailment
public function min($table, $field, $conditions = false) { return $this->executeAggregate('MIN', $table, $field, $conditions); }
Returns the min value of specified table field and conditions @param string $table @param string $field @param mixed $conditions @return float
entailment
public function avg($table, $field, $conditions = false) { return $this->executeAggregate('AVG', $table, $field, $conditions); }
Returns the avg value of specified table field and conditions @param string $table @param string $field @param mixed $conditions @return float
entailment
public function init($table, $data = array(), $isNew = true) { $class = $this->getRecordClass($table); return new $class(array( 'wei' => $this->wei, 'db' => $this, 'table' => $table, 'isNew' => $isNew, 'data' => $data, )); }
Init a record instance @param string $table The name of database table @param array $data The data for table record @param bool $isNew Whether it's a new record and have not save to database @return Record
entailment
public function find($table, $id) { $data = $this->select($table, $id); return $data ? $this->init($table, $data, false) : false; }
Find a record from specified table and conditions @param string $table The name of table @param string|array $id The primary key value or an associative array containing column-value pairs @return Record|false
entailment
public function findOrInit($table, $id, $data = array()) { return $this->init($table)->findOrInit($id, $data); }
Find a record, if not found, create a new one from specified data @param string $table The name of table @param string $id The primary key value or an associative array containing column-value pairs @param array $data The data to create a new record when record not found @return Record
entailment
public function getRecordClass($table) { if (isset($this->recordClasses[$table])) { return $this->recordClasses[$table]; } if ($this->recordNamespace) { $class = $this->recordNamespace . '\\' . implode('', array_map('ucfirst', explode('_', $table))); if (class_exists($class)) { return $class; } } return $this->recordClass; }
Returns the record class name of table @param string $table The name of table @return string The record class name for table
entailment
public function getDsn() { if ($this->dsn) { return $this->dsn; } $dsn = $this->driver . ':'; switch ($this->driver) { case 'mysql': $this->host && $dsn .= 'host=' . $this->host . ';'; $this->port && $dsn .= 'port=' . $this->port . ';'; $this->dbname && $dsn .= 'dbname=' . $this->dbname . ';'; $this->unixSocket && $dsn .= 'unix_socket=' . $this->unixSocket . ';'; $this->charset && $dsn .= 'charset=' . $this->charset; break; case 'sqlite': $dsn .= $this->path; break; case 'pgsql': $this->host && $dsn .= 'host=' . $this->host . ';'; $this->port && $dsn .= 'port=' . $this->port . ';'; $this->dbname && $dsn .= 'dbname=' . $this->dbname; break; default: throw new \RuntimeException(sprintf('Unsupported database driver: %s', $this->driver)); } return $this->dsn = $dsn; }
Returns the PDO DSN @return string @throws \RuntimeException When database driver is unsupported
entailment
public function getTableFields($table, $withPrefix = false) { $fullTable = $withPrefix ? $table : $this->getTable($table); if (isset($this->tableFields[$fullTable])) { return $this->tableFields[$fullTable]; } else { $fields = array(); switch ($this->driver) { case 'mysql': $tableInfo = $this->fetchAll("SHOW COLUMNS FROM $fullTable"); $fields = $this->filter($tableInfo, 'Field'); break; case 'sqlite': $tableInfo = $this->fetchAll("PRAGMA table_info($fullTable)"); $fields = $this->filter($tableInfo, 'name'); break; case 'pgsql': $tableInfo = $this->fetchAll( "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_catalog = ? AND table_name = ? ORDER BY dtd_identifier ASC", array($this->dbname, $fullTable) ); $fields = $this->filter($tableInfo, 'column_name'); } if (empty($fields)) { // For SQLite and PostgreSQL throw new \PDOException(sprintf('Table or view "%s" not found', $fullTable)); } return $this->tableFields[$table] = $fields; } }
Returns the name of fields of specified table @param string $table @param bool $withPrefix @throws \PDOException @return array
entailment
protected function bindParameter(\PDOStatement $stmt, $params, $types) { !is_array($params) && $params = array($params); !is_array($types) && $types = array($types); $isIndex = is_int(key($params)); $index = 1; foreach ($params as $name => $param) { // Number index parameters if ($isIndex) { if (isset($types[$index - 1])) { $stmt->bindValue($index, $param, $types[$index - 1]); } else { $stmt->bindValue($index, $param); } $index++; // Named parameters } else { if (isset($types[$name])) { $stmt->bindValue($name, $param, $types[$name]); } else { $stmt->bindValue($name, $param); } } } }
Bind parameters to statement object @param \PDOStatement $stmt @param array $params @param array $types
entailment
protected function executeAggregate($fn, $table, $field, $conditions) { $data = $this->selectAll($table, $conditions, $fn . '(' . $field . ')'); return $data ? (float)current($data[0]) : 0.0; }
Execute a query with aggregate function @param string $fn @param string $table @param string $field @param mixed $conditions @return float
entailment
public function useDb($database) { switch ($this->driver) { case 'mysql': $this->query("USE `$database`"); $this->dbname = $database; break; default: throw new \RuntimeException(sprintf('Unsupported switching database for current driver: %s', $this->driver)); } return $this; }
Switch to specified database @param string $database @return $this
entailment
public function transactional(callable $fn) { $pdo = $this->getPdo(); $pdo->beginTransaction(); try { call_user_func($fn); $pdo->commit(); } catch (\Exception $e) { $pdo->rollBack(); throw $e; } }
Execute a function in a transaction @param callable $fn @throws \Exception
entailment
protected function doValidate($input) { if ($this->min > $input || $this->max < $input) { $this->addError('between'); return false; } return true; }
{@inheritdoc}
entailment
protected function doValidate($input) { if (function_exists($fn = 'is_' . $this->type)) { $result = $fn($input); } elseif (function_exists($fn = 'ctype_' . $this->type)) { $result = $fn($input); } else { $result = $input instanceof $this->type; } if (!$result) { $this->addError('type'); } return $result; }
{@inheritdoc}
entailment
public function getMessages($name = null) { $this->loadTranslationMessages(); $this->typeName = $this->t($this->type); return parent::getMessages($name); }
{@inheritdoc}
entailment
public function bind(callable $function) : Monadic { list($result, $output) = $function($this->result)->run(); return self::of($result, flatten(extend($this->output, $output))); }
bind method. @param callable $function @param mixed $output @return object Writer
entailment
public function elements(array $elements) { /** * @var GridFilterElement $element */ foreach ($elements as $element) { $this->elements[$this->level][$element->getName()] = $element->getValues(); } $this->level++; return $this; }
@param GridFilterElement[] $elements @return $this
entailment
public function setFilters($filters = []) { foreach ($filters as $key => $value) { $this->addFilter($key, $value); } return $this; }
@param array $filters @return $this
entailment
public function addFilter($field, $value, $operator = null) { $this->filters[$field] = $value; return $this; }
Adds a filter to the resource request @param string $field the field to filter on @param string $value the value of the attribute to operate on @param $operator @return $this
entailment
public function setValues($values=array()) { $count=$this->count(); if (\is_array($values) === false) { $values=\array_fill(0, $count, $values); } else { if (JArray::isAssociative($values) === true) { $values=\array_values($values); } } $count=\min(\sizeof($values), $count); for($i=0; $i < $count; $i++) { $cell=$this->content[$i]; $cell->setValue($values[$i]); } }
Sets values to the row cols @param mixed $values
entailment
public function setCaption($value) { if (PhalconUtils::startsWith($value, "-")) { $this->class="dropdown-header"; $this->role="presentation"; $this->_template='<li id="%identifier%" class="%class%" role="%role%">%content%</li>'; if ($value==="-") { $this->class="divider"; } $value=substr($value, 1); } $this->content=$value; return $this; }
Set the item caption @param string $value @return $this
entailment
private function getMedia($type, $property) { if(property_exists('InteractsWithMedia', $property)) { throw new PropertyNotFoundException("Property {$property} not found"); } if(!empty($this->{$property})) { return $this->{$property}; } $this->setMediaByType($type, $property); return $this->{$property}; }
#region [Private methods]
entailment
public function map(callable $func) : self { $list = $this->list; foreach ($list as $index => $val) { $list[$index] = $func($val); } return new static($list); }
map method. @method map @param callable $func @return object Collection
entailment
public function flatMap(callable $func) : array { $list = $this->list; $acc = []; foreach ($list as $val) { $acc[] = $func($val); } return $acc; }
flatMap method. @method flatMap @param callable $func @return array $flattened
entailment
public function filter(callable $func) : self { $list = $this->list; $acc = []; foreach ($list as $index => $val) { if ($func($val)) { $acc[] = $val; } } return new static(\SplFixedArray::fromArray($acc)); }
filter method. @method filter @param callable $func @return object Collection
entailment
public function fold(callable $func, $acc) : self { $list = $this->list; foreach ($list as $val) { $acc = $func($acc, $val); } return new static($acc); }
fold method. @method fold @param callable $func @param mixed $acc @return object Collection
entailment
public function slice(int $count) : self { $list = $this->list; $listCount = $list->count(); $new = new \SplFixedArray($listCount - $count); foreach ($new as $index => $val) { $new[$index] = $list[($index + $count)]; } return new static($new); }
slice method. @method slice @param int $count @return object Collection
entailment
public function merge(self $list) : self { $oldSize = $this->getSize(); $combinedSize = $oldSize + $list->getSize(); $old = $this->list; $old->setSize($combinedSize); foreach ($old as $index => $val) { if ($index > $oldSize - 1) { $old[$index] = $list->getList()[($index - $oldSize)]; } } return new static($old); }
merge method. @method merge @param Collection $list @return object Collection
entailment
public function reverse() : self { $list = $this->list; $count = $this->list->getSize(); $newList = new \SplFixedArray($count); foreach ($newList as $index => $val) { $newList[$index] = $list[$count - $index - 1]; } return new static($newList); }
reverse method. @method reverse @return object Collection
entailment
public function fill($value, int $start, int $end) { $list = $this->list; foreach ($list as $index => $val) { $list[$index] = $index >= $start && $index <= $end ? $value : $val; } return new static($list); }
fill method. @method fill @param mixed $value @param int $start @param int $end @return object Collection
entailment
public function fetch($key) : Collection { $extr = []; foreach ($this->list as $list) { if (is_array($list) && key_exists($key, $list)) { $extr[] = $list[$key]; } } return self::from(...$extr); }
fetch method @method fetch @param mixed key
entailment
private static function checkContains(array $list) : bool { $comp = A\compose(A\flatten, function (array $val) { return in_array(true, $val); }); return $comp($list); }
checkContains function checkContains :: [a] -> Bool @param array $list
entailment
public function contains($element) : bool { $acc = []; foreach ($this->list as $item) { $acc[] = is_array($item) ? A\mapDeep(function ($val) use ($element) { return $val == $element; }, $item) : $item == $element; } return self::checkContains($acc); }
contains method @method contains @param mixed element
entailment
public function unique() : Collection { $acc = []; foreach ($this->list as $item) { if (!in_array($item, $acc)) { $acc[] = $item; } } return self::from(...$acc); }
unique method @method unique
entailment
public function tail() : Collection { $acc = []; foreach ($this->list as $index => $item) { if ($index > 0) { $acc[] = $item; } } return self::from(...$acc); }
tail method @method tail
entailment
public function intersects(Collection $list) : bool { $intersect = []; $main = $this->getSize(); $oth = $list->getSize(); if ($main > $oth) { foreach ($list->getList() as $item) { $intersect[] = in_array($item, $this->toArray()); } } elseif ($oth > $main) { foreach ($this->getList() as $item) { $intersect[] = in_array($item, $list->toArray()); } } return in_array(true, $intersect); }
intersects method @method head @param object Collection
entailment
public function implode(string $delimiter) : string { return rtrim($this->fold(function (string $fold, $elem) use ($delimiter) { $fold .= A\concat($delimiter, $elem, ''); return $fold; }, '')->getList(), $delimiter); }
implode function @method implode @param string $delimiter
entailment
public function offsetGet(int $offset) { if (!isset($this->list[$offset])) { throw new \OutOfRangeException('Offset does not exist'); } return $this->list[$offset]; }
offsetGet function @method offsetGet @param int $offset
entailment
public function fullById(int $id) { $all = $this->full($id); return $this->checkAndReturnResult($all); }
@param int $id @return Entity @throws EntityNotFoundException @throws \GuzzleHttp\Exception\GuzzleException @deprecated
entailment
public function fullByCode(string $code) { $all = $this->full($code); return $this->checkAndReturnResult($all); }
@param string $code @return Entity @throws EntityNotFoundException @throws \GuzzleHttp\Exception\GuzzleException @deprecated
entailment
public function full($param = null) { $uriAppend = 'full'; $params = $this->getQueryParams(); if (!is_null($param)) { $uriAppend = is_int($param) ? $uriAppend . "/$param" : "url/$param"; } $response = $this->handler->handle('GET', false, $uriAppend, $params); return $this->make($response); }
Get list of entities @param null|int|string $param @return Entity|Entity[] @throws \GuzzleHttp\Exception\GuzzleException @deprecated
entailment
public function compile(JsUtils $js=NULL,&$view=NULL){ $this->insertItem(new HtmlIcon("", "left chevron")); $this->addItem(new HtmlIcon("", "right chevron")); $this->asPagination(); return parent::compile($js,$view); }
{@inheritDoc} @see \Ajax\common\html\BaseHtml::compile()
entailment
public function valid($options = array()) { $options && $this->setOption($options); // Initialize the validation result to be true $this->result = true; $this->beforeValidate && call_user_func($this->beforeValidate, $this, $this->wei); foreach ($this->rules as $field => $rules) { $data = $this->getFieldData($field); /** * Process simple rule * FROM * 'username' => 'required' * TO * 'username' => array( * 'required' => true * ) */ if (is_string($rules)) { $rules = array($rules => true); } elseif ($rules instanceof BaseValidator) { $rules = array($rules); } elseif (!is_array($rules)) { throw new \InvalidArgumentException(sprintf( 'Expected argument of type array, string or instance of Wei\Validator\BaseValidator, "%s" given', is_object($rules) ? get_class($rules) : gettype($rules) )); } // Make sure the "required" rule at first if (!isset($rules['required'])) { $isRequired = true; } else { $isRequired = (bool) $rules['required']; unset($rules['required']); } $rules = array('required' => $isRequired) + $rules; // Start validation foreach ($rules as $rule => $params) { // Prepare property options for validator $props = $this->prepareProps($field, $rule); // The current rule validation result /* @var $validator Validator\BaseValidator */ $validator = null; $result = $this->validateOne($rule, $data, $params, $validator, $props); if (is_object($params)) { $rule = get_class($params); } // Record the rule validators $this->ruleValidators[$field][$rule] = $validator; // If any rule is invalid, the result would always be false in the whole validation flow if (false === $result) { $this->result = false; } // Record the valid/invalid rule $method = $result ? 'addValidRule' : 'addInvalidRule'; $this->$method($field, $rule); // Trigger the ruleValid/ruleInvalid callback $callback = $result ? 'ruleValid' : 'ruleInvalid'; if ($this->$callback && false === call_user_func($this->$callback, $rule, $field, $this, $this->wei)) { return $this->result; } if ($result) { // The field data is empty and optional, skip the remaining validation rules /** @var $validator Validator\Required */ if ('required' === $rule && $validator->isInvalid($data)) { break; } } else { // Break the validation flow when any field's rule is invalid if ('required' === $rule || $this->breakRule || $this->skip) { break; } } } // Trigger the fieldValid/fieldInvalid callback $callback = $this->isFieldValid($field) ? 'fieldValid' : 'fieldInvalid'; if ($this->$callback && false === call_user_func($this->$callback, $field, $this, $this->wei)) { return $this->result; } if (!$this->result && $this->skip) { continue; } // Break the validation flow when any field is invalid if (!$this->result && ($this->breakRule || $this->breakField)) { break; } } // Trigger the success/failure callback $callback = $this->result ? 'success' : 'failure'; $this->$callback && call_user_func($this->$callback, $this, $this->wei); return $this->result; }
Validate the data by the given options @param array $options The options for validation @return bool Whether pass the validation or not @throws \InvalidArgumentException When validation rule is not array, string or instance of BaseValidator
entailment
protected function prepareProps($field, $rule) { $props = $messages = array(); $props['plugins/app/js/validation'] = $this; // Prepare name for validator if (isset($this->names[$field])) { $props['name'] = $this->names[$field]; } /** * Prepare messages for validator * * The messages array may look like below * array( * // Case 1 * 'field' => 'message', * // Case 2 * 'field2' => array( * 'rule' => 'message' * ), * // Case 2 * 'field3' => array( * 'rule' => array( * 'option' => 'message', * 'option2' => 'message', * ) * ) * ) * * In case 2, checking non-numeric offsets of strings would return true * in PHP 5.3, while return false in PHP 5.4, so we do NOT known * $messages is array or string * @link http://php.net/manual/en/function.isset.php * * In case 1, $messages is string */ // Case 2 if (isset($this->messages[$field][$rule]) && is_array($this->messages[$field])) { $messages = $this->messages[$field][$rule]; // Case 1 } elseif (isset($this->messages[$field]) && is_scalar($this->messages[$field])) { $messages = $this->messages[$field]; } // Convert message to array for validator if (is_scalar($messages)) { $props['message'] = $messages; } elseif (is_array($messages)) { foreach ($messages as $name => $message) { $props[$name . 'Message'] = $message; } } return $props; }
Prepare name and messages property option for rule validator @param string $field @param string $rule @return array
entailment
public function getRuleParams($field, $rule) { return isset($this->rules[$field][$rule]) ? (array) $this->rules[$field][$rule] : array(); }
Get validation rule parameters @param string $field The validation field @param string $rule The validation rule @return array
entailment
public function getInvalidRules($field = null) { return $field ? isset($this->invalidRules[$field]) ? $this->invalidRules[$field] : array() : $this->invalidRules; }
Get invalid rules by field @param string $field @return array
entailment
public function removeRule($field, $rule) { if (isset($this->rules[$field][$rule])) { unset($this->rules[$field][$rule]); return true; } return false; }
Removes the rule in field @param string $field The name of field @param string $rule The name of rule @return bool
entailment
public function removeField($field) { if (isset($this->rules[$field])) { unset($this->rules[$field]); return true; } return false; }
Removes the validate field @param string $field @return bool
entailment
public function setData($data) { if (!is_array($data) && !is_object($data)) { throw new \InvalidArgumentException(sprintf( 'Expected argument of type array or object, "%s" given', is_object($data) ? get_class($data) : gettype($data) )); } $this->data = $data; return $this; }
Sets data for validation @param array|object $data @throws \InvalidArgumentException when argument type is not array or object @return $this
entailment
public function getFieldData($field) { // $this->data could only be array or object, which has been checked by $this->setData if ((is_array($this->data) && array_key_exists($field, $this->data)) || ($this->data instanceof \ArrayAccess && $this->data->offsetExists($field)) ) { return $this->data[$field]; } elseif (isset($this->data->$field)) { return $this->data->$field; } elseif (method_exists($this->data, 'get' . $field)) { return $this->data->{'get' . $field}(); } else { return null; } }
Returns validation field data @param string $field The name of field @return mixed
entailment
public function setFieldData($field, $data) { if (is_array($this->data)) { $this->data[$field] = $data; } else { $this->data->$field = $data; } return $this; }
Sets data for validation field @param string $field The name of field @param mixed $data The data of field @return $this
entailment
public function getDetailMessages() { $messages = array(); foreach ($this->invalidRules as $field => $rules) { foreach ($rules as $rule) { $messages[$field][$rule] = $this->ruleValidators[$field][$rule]->getMessages(); } } return $messages; }
Returns detail invalid messages @return array
entailment
public function getSummaryMessages() { $messages = $this->getDetailMessages(); $summaries = array(); foreach ($messages as $field => $rules) { foreach ($rules as $options) { foreach ($options as $message) { $summaries[$field][] = $message; } } } return $summaries; }
Returns summary invalid messages @return array
entailment
public function getJoinedMessage($separator = "\n") { $messages = $this->getDetailMessages(); $array = array(); foreach ($messages as $rules) { foreach ($rules as $options) { foreach ($options as $message) { $array[] = $message; } } } return implode($separator, array_unique($array)); }
Returns error message string connected by specified separator @param string $separator @return string
entailment
public function getRuleValidator($field, $rule) { return isset($this->ruleValidators[$field][$rule]) ? $this->ruleValidators[$field][$rule] : null; }
Returns the rule validator object @param string $field @param string $rule @return Validator\BaseValidator
entailment
public function createRuleValidator($rule, array $options = array()) { // Starts with "not", such as notDigit, notEqual if (0 === stripos($rule, 'not')) { $options['negative'] = true; $rule = substr($rule, 3); } $object = 'is' . ucfirst($rule); $class = $this->wei->getClass($object); if (!$class || !class_exists($class)) { throw new \InvalidArgumentException(sprintf('Validator "%s" not found', $rule)); } $options = $options + array('wei' => $this->wei) + (array)$this->wei->getConfig('is' . ucfirst($rule)); return new $class($options); }
Create a rule validator instance by specified rule name @param string $rule The name of rule validator @param array $options The property options for rule validator @return Validator\BaseValidator @throws \InvalidArgumentException When validator not found
entailment
public function detectEnvName() { // Detect from local env file if ($this->envFile && is_file($this->envFile)) { $this->name = require $this->envFile; if ($this->name) { return; } } // Return if env name is detected, or, or continue detecting by IP if ($this->detector && $this->name = call_user_func($this->detector)) { return; } // Executes in web server, like Apache, Nginx if (isset($this->server['SERVER_ADDR'])) { $ip = $this->server['SERVER_ADDR']; if (isset($this->ipMap[$ip])) { $this->name = $this->ipMap[$ip]; } else { $this->name = 'prod'; } return; } // Executes in CLI if (php_sapi_name() == 'cli' && $ips = $this->getServerIps()) { foreach ($ips as $ip) { if (isset($this->ipMap[$ip])) { $this->name = $this->ipMap[$ip]; return; } } } $this->name = 'prod'; return; }
Detect environment by server IP
entailment
public function loadConfigFile($file, $env = null) { $file = str_replace('%env%', $env ?: $this->name, $file); $config = $this->getFileConfig($file); if ($config) { $this->wei->setConfig($config); } return $this; }
Loads configs from specified file to service container @param string $file The config file path @param string $env The value to replace the %env% placeholder, default to the env name @return $this
entailment
public function loadConfigDir($dir, $env = null) { !$env && $env = $this->name; $config = $this->getFileConfig($dir . '/config.php'); $envConfig = $this->getFileConfig($dir . '/config-' . $env . '.php'); $config = array_replace_recursive($config, $envConfig); $this->wei->setConfig($config); return $this; }
Loads two config files in specified directory to service container @param string $dir The config directory @param string $env @return $this
entailment
public function _json($url, $method="get", $params="{}", $jsCallback=NULL, $attr="id", $context="document",$immediatly=false) { $jsCallback=isset($jsCallback) ? $jsCallback : ""; $retour=$this->_getAjaxUrl($url, $attr); $retour.="$.{$method}(url,".$params.").done(function( data ) {\n"; $retour.="\tdata=$.parseJSON(data);for(var key in data){" ."if($('#'+key,".$context.").length){ if($('#'+key,".$context.").is('[value]')) { $('#'+key,".$context.").val(data[key]);} else { $('#'+key,".$context.").html(data[key]); }}};\n"; $retour.="\t".$jsCallback."\n". "\t$(document).trigger('jsonReady',[data]);\n". "});\n"; if ($immediatly) $this->jquery_code_for_compile[]=$retour; return $retour; }
Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name @param string $url the request address @param string $params Paramètres passés au format JSON @param string $method Method use @param string $jsCallback javascript code to execute after the request @param boolean $immediatly
entailment
public function _jsonOn($event,$element, $url,$parameters=array()) { $preventDefault=true; $stopPropagation=true; $jsCallback=null; $attr="id"; $method="get"; $context="document"; $params="{}"; $immediatly=true; extract($parameters); return $this->_add_event($element, $this->_json($url,$method, $params,$jsCallback, $attr,$context), $event, $preventDefault, $stopPropagation,$immediatly); }
Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name when $event fired on $element @param string $element @param string $event @param string $url the request address @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get","immediatly"=>true)
entailment
public function _jsonArray($maskSelector, $url, $method="get", $params="{}", $jsCallback=NULL, $attr="id", $context=null,$immediatly=false) { $jsCallback=isset($jsCallback) ? $jsCallback : ""; $retour=$this->_getAjaxUrl($url, $attr); if($context===null){ $appendTo="\t\tnewElm.appendTo($('".$maskSelector."').parent());\n"; $newElm = "$('#'+newId)"; }else{ $appendTo="\t\tnewElm.appendTo(".$context.");\n"; $newElm = $context.".find('#'+newId)"; } $retour.="var self = $(this);\n$.{$method}(url,".$params.").done(function( data ) {\n"; $retour.="\tdata=$.parseJSON(data);$.each(data, function(index, value) {\n"."\tvar created=false;var maskElm=$('".$maskSelector."').first();maskElm.hide();"."\tvar newId=(maskElm.attr('id') || 'mask')+'-'+index;"."\tvar newElm=".$newElm.";\n"."\tif(!newElm.length){\n"."\t\tnewElm=maskElm.clone();newElm.attr('id',newId);\n"; $retour.= $appendTo; $retour.="\t}\n"."\tfor(var key in value){\n"."\t\t\tvar html = $('<div />').append($(newElm).clone()).html();\n"."\t\t\tif(html.indexOf('[['+key+']]')>-1){\n"."\t\t\t\tcontent=$(html.split('[['+key+']]').join(value[key]));\n"."\t\t\t\t$(newElm).replaceWith(content);newElm=content;\n"."\t\t\t}\n"."\t\tvar sel='[data-id=\"'+key+'\"]';if($(sel,newElm).length){\n"."\t\t\tvar selElm=$(sel,newElm);\n"."\t\t\t if(selElm.is('[value]')) { selElm.attr('value',value[key]);selElm.val(value[key]);} else { selElm.html(value[key]); }\n"."\t\t}\n"."}\n"."\t$(newElm).show(true);"."\n"."\t$(newElm).removeClass('hide');"."});\n"; $retour.="\t$(document).trigger('jsonReady',[data]);\n"; $retour.="\t".$jsCallback."\n"."});\n"; if ($immediatly) $this->jquery_code_for_compile[]=$retour; return $retour; }
Makes an ajax request and receives a JSON array data types by copying and assigning them to the DOM elements with the same name @param string $url the request address @param string $params Paramètres passés au format JSON @param string $method Method use @param string $jsCallback javascript code to execute after the request @param string $context jquery DOM element, array container. @param boolean $immediatly
entailment
public function _jsonArrayOn($event,$element, $maskSelector,$url,$parameters=array()) { $preventDefault=true; $stopPropagation=true; $jsCallback=null; $attr="id"; $method="get"; $context = null; $params="{}"; $immediatly=true; extract($parameters); return $this->_add_event($element, $this->_jsonArray($maskSelector,$url,$method, $params,$jsCallback, $attr, $context), $event, $preventDefault, $stopPropagation,$immediatly); }
Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name when $event fired on $element @param string $element @param string $event @param string $url the request address @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get", "context"=>null)
entailment
public function _getOn($event,$element, $url, $params="{}", $responseElement="", $parameters=array()) { $preventDefault=true; $stopPropagation=true; $jsCallback=null; $attr="id"; $hasLoader=true; $immediatly=true; extract($parameters); return $this->_add_event($element, $this->_get($url, $params, $responseElement, $jsCallback, $attr,$hasLoader), $event, $preventDefault, $stopPropagation,$immediatly); }
Effectue un get vers $url sur l'évènement $event de $element en passant les paramètres $params puis affiche le résultat dans $responseElement @param string $element @param string $event @param string $url @param string $params queryString parameters (JSON format). default : {} @param string $responseElement @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true)
entailment
public function _postFormOn($event,$element, $url, $form, $responseElement="", $parameters=array()) { $preventDefault=true; $stopPropagation=true; $validation=false; $jsCallback=null; $attr="id"; $hasLoader=true; $immediatly=true; extract($parameters); return $this->_add_event($element, $this->_postForm($url, $form, $responseElement, $validation, $jsCallback, $attr,$hasLoader), $event, $preventDefault, $stopPropagation,$immediatly); }
Effectue un post vers $url sur l'évènement $event de $element en passant les paramètres du formulaire $form puis affiche le résultat dans $responseElement @param string $element @param string $event @param string $url @param string $form @param string $responseElement @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"validation"=>false,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"immediatly"=>true)
entailment
public function getConfig() { return [ 'cluster' => Config::get('database.redis.cluster'), 'default' => [ 'host' => $this->HAClient->getIpAddress(), 'port' => $this->HAClient->getPort(), 'password' => Config::get('database.redis.password', null), 'database' => Config::get('database.redis.database', 0), ] ]; }
Get the config values for the redis database. @return array
entailment
protected function doValidate($input) { if (!call_user_func($this->fn, $input, $this, $this->wei)) { $this->addError('invalid'); return false; } return true; }
{@inheritdoc}
entailment
protected function getResultFromResponse(Response $response) { $result = []; $included = $this->getIncludedArray($response->getIncluded()); foreach ($response->getData() as $element) { $mapperClass = $this->getMapperClass($element['type']); if (is_null($mapperClass)) { throw new EntityNotFoundException("Entity mapper class for {$element['type']} was not found"); } $result[$element['type']][] = $this->createObject($mapperClass, $element, $included); } return $result; }
@param Response $response @return array @throws EntityNotFoundException
entailment
public function getOneBySourceUriPathAndHost($sourceUriPath, $host = null, $fallback = true) { $redirect = $this->redirectRepository->findOneBySourceUriPathAndHost($sourceUriPath, $host, $fallback); if ($redirect !== null) { return RedirectDto::create($redirect); } }
{@inheritdoc}
entailment
public function getAll($host = null) { foreach ($this->redirectRepository->findAll($host) as $redirect) { yield RedirectDto::create($redirect); } }
{@inheritdoc}
entailment
public function removeOneBySourceUriPathAndHost($sourceUriPath, $host = null) { $redirect = $this->redirectRepository->findOneBySourceUriPathAndHost($sourceUriPath, $host); if ($redirect === null) { return; } $this->redirectRepository->remove($redirect); }
{@inheritdoc}
entailment
public function addRedirect($sourceUriPath, $targetUriPath, $statusCode = null, array $hosts = []) { $statusCode = $statusCode ?: (int) $this->defaultStatusCode['redirect']; $redirects = []; if ($hosts !== []) { array_map(function ($host) use ($sourceUriPath, $targetUriPath, $statusCode, &$redirects) { $redirects[] = $this->addRedirectByHost($sourceUriPath, $targetUriPath, $statusCode, $host); }, $hosts); } else { $redirects[] = $this->addRedirectByHost($sourceUriPath, $targetUriPath, $statusCode); } $this->emitRedirectCreated($redirects); return $redirects; }
{@inheritdoc}
entailment
protected function addRedirectByHost($sourceUriPath, $targetUriPath, $statusCode, $host = null) { $redirect = new Redirect($sourceUriPath, $targetUriPath, $statusCode, $host); $this->updateDependingRedirects($redirect); $this->persistenceManager->persistAll(); $this->redirectRepository->add($redirect); $this->routerCachingService->flushCachesForUriPath($sourceUriPath); return RedirectDto::create($redirect); }
Adds a redirect to the repository and updates related redirects accordingly. @param string $sourceUriPath the relative URI path that should trigger a redirect @param string $targetUriPath the relative URI path the redirect should point to @param int $statusCode the status code of the redirect header @param string $host the host for the current redirect @return Redirect the freshly generated redirect DTO instance @api
entailment
protected function updateDependingRedirects(RedirectInterface $newRedirect) { /** @var $existingRedirectForSourceUriPath Redirect */ $existingRedirectForSourceUriPath = $this->redirectRepository->findOneBySourceUriPathAndHost($newRedirect->getSourceUriPath(), $newRedirect->getHost(), false); if ($existingRedirectForSourceUriPath !== null) { $this->removeAndLog($existingRedirectForSourceUriPath, sprintf('Existing redirect for the source URI path "%s" removed.', $newRedirect->getSourceUriPath())); $this->routerCachingService->flushCachesForUriPath($existingRedirectForSourceUriPath->getSourceUriPath()); } /** @var $existingRedirectForTargetUriPath Redirect */ $existingRedirectForTargetUriPath = $this->redirectRepository->findOneBySourceUriPathAndHost($newRedirect->getTargetUriPath(), $newRedirect->getHost(), false); if ($existingRedirectForTargetUriPath !== null) { $this->removeAndLog($existingRedirectForTargetUriPath, sprintf('Existing redirect for the target URI path "%s" removed.', $newRedirect->getTargetUriPath())); $this->routerCachingService->flushCachesForUriPath($existingRedirectForTargetUriPath->getSourceUriPath()); } $obsoleteRedirectInstances = $this->redirectRepository->findByTargetUriPathAndHost($newRedirect->getSourceUriPath(), $newRedirect->getHost()); /** @var $obsoleteRedirect Redirect */ foreach ($obsoleteRedirectInstances as $obsoleteRedirect) { if ($obsoleteRedirect->getSourceUriPath() === $newRedirect->getTargetUriPath()) { $this->redirectRepository->remove($obsoleteRedirect); } else { $obsoleteRedirect->setTargetUriPath($newRedirect->getTargetUriPath()); $this->redirectRepository->update($obsoleteRedirect); } } }
Updates affected redirects in order to avoid redundant or circular redirections. @param RedirectInterface $newRedirect @throws Exception if creating the redirect would cause conflicts @return void
entailment
public function incrementHitCount(RedirectInterface $redirect) { try { $this->redirectRepository->incrementHitCount($redirect); } catch (\Exception $exception) { $this->_logger->logException($exception); } }
Increment the hit counter for the given redirect. @param RedirectInterface $redirect @return void @api
entailment
public function getFirstValueByAttributeCode(string $code) { $attribute = $this->getAttributeByCode($code); if (is_null($attribute)) { return null; } if (empty($value = reset($attribute->values))) { return null; } return $value; }
@param string $code @return null|AttributeValue
entailment
public function getFirstValueByAttributeCodeAsString(string $code, $asTitle = true) { $attributeValue = $this->getFirstValueByAttributeCode($code); if (!$attributeValue) { return ""; } $field = $asTitle ? 'title' : 'value'; return $attributeValue->$field; }
The method should get rid of addition conditions in templates @param string $code @param bool $asTitle By default we should display always Title field, but it should be also possible to use value @return string|null
entailment
protected function getAttributesByFieldNameAndValues(string $fieldName, $values) { $attributes = []; if (empty($values) || empty($this->attributes)) { return $attributes; } foreach ($this->attributes as $attribute) { if (in_array($attribute->{$fieldName}, $values)) { $attributes[] = $attribute; } } return $attributes; }
@param string $fieldName @param $values @return array|Attribute[]
entailment
protected function doValidate($input) { $flag = 0; if ($this->ipv4) { $flag = $flag | FILTER_FLAG_IPV4; } if ($this->ipv6) { $flag = $flag | FILTER_FLAG_IPV6; } if ($this->noPrivRange) { $flag = $flag | FILTER_FLAG_NO_PRIV_RANGE; } if ($this->noResRange) { $flag = $flag | FILTER_FLAG_NO_RES_RANGE; } if (!filter_var($input, FILTER_VALIDATE_IP, $flag)) { $this->addError('notAllow'); return false; } return true; }
{@inheritdoc}
entailment
public function getById(int $id, string $forClassName) { $params = $this->getQueryParams(); $type = CorrelationTypeHelper::getGraphTypeByClass($forClassName); $uriAppend = "{$type}/{$id}"; unset($params['limit'], $params['offset']); $response = $this->handler->handle('GET', false, $uriAppend, $params)->getData(); if (!$response) { return []; } $functionalNames = []; if ($filter = $this->getFilter()) { $functionalNames = current($filter->getElements())['functionalNames'] ?? null; } return $this->client->elastic() ->search($this->prepareElasticSearchBody($response, ['functionalNameId' => $functionalNames])) ->all(); }
@param int $id @param string $forClassName @return array|Collection @throws \GuzzleHttp\Exception\GuzzleException
entailment