repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
bav-php/bav
classes/dataBackend/update/UpdatePlan.php
UpdatePlan.isOutdated
public function isOutdated(DataBackend $backend) { /* * The following code creates a sorted list with the release months (update month - $relaseThreshold) * and the current month. To build that threshold date simply pick the month before the current month from * that list. * * Note that the second parameter of the date() calls is there on purpose. This allows * to mock time() for testing. */ /* * The current month gets an increment of 0.5 for the case that the current month is a * release month (e.g. the list will look (2, 2.5, 5, 8, 11)). */ $currentMonth = date("n", time()) + 0.5; $monthList = array($currentMonth); foreach (self::$updateMonths as $month) { $releaseMonth = $month - self::$relaseThreshold; $monthList[] = $releaseMonth; } sort($monthList); // You have now something like (2, 2.5, 5, 8, 11). // Now add the cycle between the last and the first month(11, 2, 3.5, 5, 8, 11, 2). $monthList[] = self::$updateMonths[0] - self::$relaseThreshold; // this is acually not needed. array_unshift($monthList, self::$updateMonths[count(self::$updateMonths) - 1] - self::$relaseThreshold); $index = array_search($currentMonth, $monthList); assert($index > 0); $previousIndex = $index - 1; $thresholdMonth = $monthList[$previousIndex]; // flip the year if the threshold was in the last year. $year = $thresholdMonth > $currentMonth ? date("Y", time()) - 1 : date("Y", time()); $threshold = mktime(0, 0, 0, $thresholdMonth, 1, $year); return $backend->getLastUpdate() < $threshold; }
php
public function isOutdated(DataBackend $backend) { /* * The following code creates a sorted list with the release months (update month - $relaseThreshold) * and the current month. To build that threshold date simply pick the month before the current month from * that list. * * Note that the second parameter of the date() calls is there on purpose. This allows * to mock time() for testing. */ /* * The current month gets an increment of 0.5 for the case that the current month is a * release month (e.g. the list will look (2, 2.5, 5, 8, 11)). */ $currentMonth = date("n", time()) + 0.5; $monthList = array($currentMonth); foreach (self::$updateMonths as $month) { $releaseMonth = $month - self::$relaseThreshold; $monthList[] = $releaseMonth; } sort($monthList); // You have now something like (2, 2.5, 5, 8, 11). // Now add the cycle between the last and the first month(11, 2, 3.5, 5, 8, 11, 2). $monthList[] = self::$updateMonths[0] - self::$relaseThreshold; // this is acually not needed. array_unshift($monthList, self::$updateMonths[count(self::$updateMonths) - 1] - self::$relaseThreshold); $index = array_search($currentMonth, $monthList); assert($index > 0); $previousIndex = $index - 1; $thresholdMonth = $monthList[$previousIndex]; // flip the year if the threshold was in the last year. $year = $thresholdMonth > $currentMonth ? date("Y", time()) - 1 : date("Y", time()); $threshold = mktime(0, 0, 0, $thresholdMonth, 1, $year); return $backend->getLastUpdate() < $threshold; }
[ "public", "function", "isOutdated", "(", "DataBackend", "$", "backend", ")", "{", "/*\n * The following code creates a sorted list with the release months (update month - $relaseThreshold)\n * and the current month. To build that threshold date simply pick the month before the curr...
Returns true if the data is to old and needs an update @see DataBackend::getLastUpdate() @return bool
[ "Returns", "true", "if", "the", "data", "is", "to", "old", "and", "needs", "an", "update" ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/dataBackend/update/UpdatePlan.php#L45-L86
train
silverstripe-archive/deploynaut
code/backends/DemoDeploymentBackend.php
DemoDeploymentBackend.deploy
public function deploy(DNEnvironment $environment, $sha, DeploynautLogFile $log, DNProject $project, $leaveMaintenancePage = false) { $this->extend('deployStart', $environment, $sha, $log, $project); $file = sprintf('%s/%s.deploy-history.txt', DEPLOYNAUT_LOG_PATH, $environment->getFullName()); $CLI_file = escapeshellarg($file); $CLI_line = escapeshellarg(date('Y-m-d H:i:s') . " => $sha"); // Put maintenance page up $this->enableMaintenance($environment, $log, $project); // Do the deployment $log->write("Demo deployment: echo $CLI_line >> $CLI_file"); `echo $CLI_line >> $CLI_file`; $log->write("Arbitrary pause for 10s"); sleep(10); $log->write("Well, that was a waste of time"); // Once the deployment has run it's necessary to update the maintenance page status if($leaveMaintenancePage) { $this->enableMaintenance($environment, $log, $project); } else { // Remove maintenance page if we want it to $this->disableMaintenance($environment, $log, $project); } $this->extend('deployEnd', $environment, $sha, $log, $project); }
php
public function deploy(DNEnvironment $environment, $sha, DeploynautLogFile $log, DNProject $project, $leaveMaintenancePage = false) { $this->extend('deployStart', $environment, $sha, $log, $project); $file = sprintf('%s/%s.deploy-history.txt', DEPLOYNAUT_LOG_PATH, $environment->getFullName()); $CLI_file = escapeshellarg($file); $CLI_line = escapeshellarg(date('Y-m-d H:i:s') . " => $sha"); // Put maintenance page up $this->enableMaintenance($environment, $log, $project); // Do the deployment $log->write("Demo deployment: echo $CLI_line >> $CLI_file"); `echo $CLI_line >> $CLI_file`; $log->write("Arbitrary pause for 10s"); sleep(10); $log->write("Well, that was a waste of time"); // Once the deployment has run it's necessary to update the maintenance page status if($leaveMaintenancePage) { $this->enableMaintenance($environment, $log, $project); } else { // Remove maintenance page if we want it to $this->disableMaintenance($environment, $log, $project); } $this->extend('deployEnd', $environment, $sha, $log, $project); }
[ "public", "function", "deploy", "(", "DNEnvironment", "$", "environment", ",", "$", "sha", ",", "DeploynautLogFile", "$", "log", ",", "DNProject", "$", "project", ",", "$", "leaveMaintenancePage", "=", "false", ")", "{", "$", "this", "->", "extend", "(", "...
Deploy the given build to the given environment
[ "Deploy", "the", "given", "build", "to", "the", "given", "environment" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/backends/DemoDeploymentBackend.php#L15-L41
train
dmitriybelyy/yii2-cassandra-cql
phpcassa/AbstractColumnFamily.php
AbstractColumnFamily.get
public function get($key, $column_slice=null, $column_names=null, $consistency_level=null) { $column_parent = $this->create_column_parent(); $predicate = $this->create_slice_predicate($column_names, $column_slice); return $this->_get($key, $column_parent, $predicate, $consistency_level); }
php
public function get($key, $column_slice=null, $column_names=null, $consistency_level=null) { $column_parent = $this->create_column_parent(); $predicate = $this->create_slice_predicate($column_names, $column_slice); return $this->_get($key, $column_parent, $predicate, $consistency_level); }
[ "public", "function", "get", "(", "$", "key", ",", "$", "column_slice", "=", "null", ",", "$", "column_names", "=", "null", ",", "$", "consistency_level", "=", "null", ")", "{", "$", "column_parent", "=", "$", "this", "->", "create_column_parent", "(", "...
Fetch a row from this column family. @param string $key row key to fetch @param \phpcassa\ColumnSlice a slice of columns to fetch, or null @param mixed[] $column_names limit the columns or super columns fetched to this list @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns @return mixed array(column_name => column_value)
[ "Fetch", "a", "row", "from", "this", "column", "family", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/AbstractColumnFamily.php#L289-L297
train
dmitriybelyy/yii2-cassandra-cql
phpcassa/AbstractColumnFamily.php
AbstractColumnFamily.multiget
public function multiget($keys, $column_slice=null, $column_names=null, $consistency_level=null, $buffer_size=16) { $cp = $this->create_column_parent(); $slice = $this->create_slice_predicate($column_names, $column_slice); return $this->_multiget($keys, $cp, $slice, $consistency_level, $buffer_size); }
php
public function multiget($keys, $column_slice=null, $column_names=null, $consistency_level=null, $buffer_size=16) { $cp = $this->create_column_parent(); $slice = $this->create_slice_predicate($column_names, $column_slice); return $this->_multiget($keys, $cp, $slice, $consistency_level, $buffer_size); }
[ "public", "function", "multiget", "(", "$", "keys", ",", "$", "column_slice", "=", "null", ",", "$", "column_names", "=", "null", ",", "$", "consistency_level", "=", "null", ",", "$", "buffer_size", "=", "16", ")", "{", "$", "cp", "=", "$", "this", "...
Fetch a set of rows from this column family. @param string[] $keys row keys to fetch @param \phpcassa\ColumnSlice a slice of columns to fetch, or null @param mixed[] $column_names limit the columns or super columns fetched to this list @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns @param int $buffer_size the number of keys to multiget at a single time. If your rows are large, having a high buffer size gives poor performance; if your rows are small, consider increasing this value. @return mixed array(key => array(column_name => column_value))
[ "Fetch", "a", "set", "of", "rows", "from", "this", "column", "family", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/AbstractColumnFamily.php#L324-L334
train
dmitriybelyy/yii2-cassandra-cql
phpcassa/AbstractColumnFamily.php
AbstractColumnFamily.get_count
public function get_count($key, $column_slice=null, $column_names=null, $consistency_level=null) { $cp = $this->create_column_parent(); $slice = $this->create_slice_predicate( $column_names, $column_slice, null, ColumnSlice::MAX_COUNT); return $this->_get_count($key, $cp, $slice, $consistency_level); }
php
public function get_count($key, $column_slice=null, $column_names=null, $consistency_level=null) { $cp = $this->create_column_parent(); $slice = $this->create_slice_predicate( $column_names, $column_slice, null, ColumnSlice::MAX_COUNT); return $this->_get_count($key, $cp, $slice, $consistency_level); }
[ "public", "function", "get_count", "(", "$", "key", ",", "$", "column_slice", "=", "null", ",", "$", "column_names", "=", "null", ",", "$", "consistency_level", "=", "null", ")", "{", "$", "cp", "=", "$", "this", "->", "create_column_parent", "(", ")", ...
Count the number of columns in a row. @param string $key row to be counted @param \phpcassa\ColumnSlice a slice of columns to count, or null @param mixed[] $column_names limit the possible columns or super columns counted to this list @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns @return int
[ "Count", "the", "number", "of", "columns", "in", "a", "row", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/AbstractColumnFamily.php#L426-L435
train
dmitriybelyy/yii2-cassandra-cql
phpcassa/AbstractColumnFamily.php
AbstractColumnFamily.multiget_count
public function multiget_count($keys, $column_slice=null, $column_names=null, $consistency_level=null) { $cp = $this->create_column_parent(); $slice = $this->create_slice_predicate( $column_names, $column_slice, null, ColumnSlice::MAX_COUNT); return $this->_multiget_count($keys, $cp, $slice, $consistency_level); }
php
public function multiget_count($keys, $column_slice=null, $column_names=null, $consistency_level=null) { $cp = $this->create_column_parent(); $slice = $this->create_slice_predicate( $column_names, $column_slice, null, ColumnSlice::MAX_COUNT); return $this->_multiget_count($keys, $cp, $slice, $consistency_level); }
[ "public", "function", "multiget_count", "(", "$", "keys", ",", "$", "column_slice", "=", "null", ",", "$", "column_names", "=", "null", ",", "$", "consistency_level", "=", "null", ")", "{", "$", "cp", "=", "$", "this", "->", "create_column_parent", "(", ...
Count the number of columns in a set of rows. @param string[] $keys rows to be counted @param \phpcassa\ColumnSlice a slice of columns to count, or null @param mixed[] $column_names limit the possible columns or super columns counted to this list @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns @return mixed array(row_key => row_count)
[ "Count", "the", "number", "of", "columns", "in", "a", "set", "of", "rows", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/AbstractColumnFamily.php#L453-L463
train
dmitriybelyy/yii2-cassandra-cql
phpcassa/AbstractColumnFamily.php
AbstractColumnFamily.get_range_by_token
public function get_range_by_token($token_start="", $token_finish="", $row_count=self::DEFAULT_ROW_COUNT, $column_slice=null, $column_names=null, $consistency_level=null, $buffer_size=null) { $cp = $this->create_column_parent(); $slice = $this->create_slice_predicate($column_names, $column_slice); return $this->_get_range_by_token($token_start, $token_finish, $row_count, $cp, $slice, $consistency_level, $buffer_size); }
php
public function get_range_by_token($token_start="", $token_finish="", $row_count=self::DEFAULT_ROW_COUNT, $column_slice=null, $column_names=null, $consistency_level=null, $buffer_size=null) { $cp = $this->create_column_parent(); $slice = $this->create_slice_predicate($column_names, $column_slice); return $this->_get_range_by_token($token_start, $token_finish, $row_count, $cp, $slice, $consistency_level, $buffer_size); }
[ "public", "function", "get_range_by_token", "(", "$", "token_start", "=", "\"\"", ",", "$", "token_finish", "=", "\"\"", ",", "$", "row_count", "=", "self", "::", "DEFAULT_ROW_COUNT", ",", "$", "column_slice", "=", "null", ",", "$", "column_names", "=", "nul...
Get an iterator over a token range. Example usages of get_range_by_token() : 1. You can iterate part of the ring. This helps to start several processes, that scans the ring in parallel in fashion similar to Hadoop. Then full ring scan will take only 1 / <number of processes> 2. You can iterate "local" token range for each Cassandra node. You can start one process on each cassandra node, that iterates only on token range for this node. In this case you minimize the network traffic between nodes. 3. Combinations of the above. @param string $token_start fetch rows with a token >= this @param string $token_finish fetch rows with a token <= this @param int $row_count limit the number of rows returned to this amount @param \phpcassa\ColumnSlice a slice of columns to fetch, or null @param mixed[] $column_names limit the columns or super columns fetched to this list @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns @param int $buffer_size When calling `get_range`, the intermediate results need to be buffered if we are fetching many rows, otherwise the Cassandra server will overallocate memory and fail. This is the size of that buffer in number of rows. @return phpcassa\Iterator\RangeColumnFamilyIterator
[ "Get", "an", "iterator", "over", "a", "token", "range", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/AbstractColumnFamily.php#L581-L594
train
dmitriybelyy/yii2-cassandra-cql
phpcassa/AbstractColumnFamily.php
AbstractColumnFamily.get_indexed_slices
public function get_indexed_slices($index_clause, $column_slice=null, $column_names=null, $consistency_level=null, $buffer_size=null) { if ($buffer_size == null) $buffer_size = $this->buffer_size; if ($buffer_size < 2) { $ire = new InvalidRequestException(); $ire->message = 'buffer_size cannot be less than 2'; throw $ire; } $new_clause = new IndexClause(); foreach($index_clause->expressions as $expr) { $new_expr = new IndexExpression(); $new_expr->column_name = $this->pack_name($expr->column_name); $new_expr->value = $this->pack_value($expr->value, $new_expr->column_name); $new_expr->op = $expr->op; $new_clause->expressions[] = $new_expr; } $new_clause->start_key = $index_clause->start_key; $new_clause->count = $index_clause->count; $column_parent = $this->create_column_parent(); $predicate = $this->create_slice_predicate($column_names, $column_slice); return new IndexedColumnFamilyIterator($this, $new_clause, $buffer_size, $column_parent, $predicate, $this->rcl($consistency_level)); }
php
public function get_indexed_slices($index_clause, $column_slice=null, $column_names=null, $consistency_level=null, $buffer_size=null) { if ($buffer_size == null) $buffer_size = $this->buffer_size; if ($buffer_size < 2) { $ire = new InvalidRequestException(); $ire->message = 'buffer_size cannot be less than 2'; throw $ire; } $new_clause = new IndexClause(); foreach($index_clause->expressions as $expr) { $new_expr = new IndexExpression(); $new_expr->column_name = $this->pack_name($expr->column_name); $new_expr->value = $this->pack_value($expr->value, $new_expr->column_name); $new_expr->op = $expr->op; $new_clause->expressions[] = $new_expr; } $new_clause->start_key = $index_clause->start_key; $new_clause->count = $index_clause->count; $column_parent = $this->create_column_parent(); $predicate = $this->create_slice_predicate($column_names, $column_slice); return new IndexedColumnFamilyIterator($this, $new_clause, $buffer_size, $column_parent, $predicate, $this->rcl($consistency_level)); }
[ "public", "function", "get_indexed_slices", "(", "$", "index_clause", ",", "$", "column_slice", "=", "null", ",", "$", "column_names", "=", "null", ",", "$", "consistency_level", "=", "null", ",", "$", "buffer_size", "=", "null", ")", "{", "if", "(", "$", ...
Fetch a set of rows from this column family based on an index clause. @param phpcassa\Index\IndexClause $index_clause limits the keys that are returned based on expressions that compare the value of a column to a given value. At least one of the expressions in the IndexClause must be on an indexed column. @param phpcassa\ColumnSlice a slice of columns to fetch, or null @param mixed[] $column_names limit the columns or super columns fetched to this list number of nodes that must respond before the operation returns @return phpcassa\Iterator\IndexedColumnFamilyIterator
[ "Fetch", "a", "set", "of", "rows", "from", "this", "column", "family", "based", "on", "an", "index", "clause", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/AbstractColumnFamily.php#L626-L657
train
dmitriybelyy/yii2-cassandra-cql
phpcassa/AbstractColumnFamily.php
AbstractColumnFamily.insert
public function insert($key, $columns, $timestamp=null, $ttl=null, $consistency_level=null) { if ($timestamp === null) $timestamp = Clock::get_time(); $cfmap = array(); $packed_key = $this->pack_key($key); $cfmap[$packed_key][$this->column_family] = $this->make_mutation($columns, $timestamp, $ttl); return $this->pool->call("batch_mutate", $cfmap, $this->wcl($consistency_level)); }
php
public function insert($key, $columns, $timestamp=null, $ttl=null, $consistency_level=null) { if ($timestamp === null) $timestamp = Clock::get_time(); $cfmap = array(); $packed_key = $this->pack_key($key); $cfmap[$packed_key][$this->column_family] = $this->make_mutation($columns, $timestamp, $ttl); return $this->pool->call("batch_mutate", $cfmap, $this->wcl($consistency_level)); }
[ "public", "function", "insert", "(", "$", "key", ",", "$", "columns", ",", "$", "timestamp", "=", "null", ",", "$", "ttl", "=", "null", ",", "$", "consistency_level", "=", "null", ")", "{", "if", "(", "$", "timestamp", "===", "null", ")", "$", "tim...
Insert or update columns in a row. @param string $key the row to insert or update the columns in @param mixed[] $columns array(column_name => column_value) the columns to insert or update @param int $timestamp the timestamp to use for this insertion. Leaving this as null will result in a timestamp being generated for you @param int $ttl time to live for the columns; after ttl seconds they will be deleted @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns @return int the timestamp for the operation
[ "Insert", "or", "update", "columns", "in", "a", "row", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/AbstractColumnFamily.php#L672-L687
train
dmitriybelyy/yii2-cassandra-cql
phpcassa/AbstractColumnFamily.php
AbstractColumnFamily.batch_insert
public function batch_insert($rows, $timestamp=null, $ttl=null, $consistency_level=null) { if ($timestamp === null) $timestamp = Clock::get_time(); $cfmap = array(); if ($this->insert_format == self::DICTIONARY_FORMAT) { foreach($rows as $key => $columns) { $packed_key = $this->pack_key($key, $handle_serialize=true); $ttlRow = $this->get_ttl($ttl, $packed_key); $cfmap[$packed_key][$this->column_family] = $this->make_mutation($columns, $timestamp, $ttlRow); } } else if ($this->insert_format == self::ARRAY_FORMAT) { foreach($rows as $row) { list($key, $columns) = $row; $packed_key = $this->pack_key($key); $ttlRow = $this->get_ttl($ttl, $packed_key); $cfmap[$packed_key][$this->column_family] = $this->make_mutation($columns, $timestamp, $ttlRow); } } else { throw new UnexpectedValueException("Bad insert_format selected"); } return $this->pool->call("batch_mutate", $cfmap, $this->wcl($consistency_level)); }
php
public function batch_insert($rows, $timestamp=null, $ttl=null, $consistency_level=null) { if ($timestamp === null) $timestamp = Clock::get_time(); $cfmap = array(); if ($this->insert_format == self::DICTIONARY_FORMAT) { foreach($rows as $key => $columns) { $packed_key = $this->pack_key($key, $handle_serialize=true); $ttlRow = $this->get_ttl($ttl, $packed_key); $cfmap[$packed_key][$this->column_family] = $this->make_mutation($columns, $timestamp, $ttlRow); } } else if ($this->insert_format == self::ARRAY_FORMAT) { foreach($rows as $row) { list($key, $columns) = $row; $packed_key = $this->pack_key($key); $ttlRow = $this->get_ttl($ttl, $packed_key); $cfmap[$packed_key][$this->column_family] = $this->make_mutation($columns, $timestamp, $ttlRow); } } else { throw new UnexpectedValueException("Bad insert_format selected"); } return $this->pool->call("batch_mutate", $cfmap, $this->wcl($consistency_level)); }
[ "public", "function", "batch_insert", "(", "$", "rows", ",", "$", "timestamp", "=", "null", ",", "$", "ttl", "=", "null", ",", "$", "consistency_level", "=", "null", ")", "{", "if", "(", "$", "timestamp", "===", "null", ")", "$", "timestamp", "=", "C...
Insert or update columns in multiple rows. Note that this operation is only atomic per row. @param array $rows an array of keys, each of which maps to an array of columns. This looks like array(key => array(column_name => column_value)) @param int $timestamp the timestamp to use for these insertions. Leaving this as null will result in a timestamp being generated for you @param int $ttl time to live for the columns; after ttl seconds they will be deleted @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns @return int the timestamp for the operation
[ "Insert", "or", "update", "columns", "in", "multiple", "rows", ".", "Note", "that", "this", "operation", "is", "only", "atomic", "per", "row", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/AbstractColumnFamily.php#L703-L728
train
dmitriybelyy/yii2-cassandra-cql
phpcassa/AbstractColumnFamily.php
AbstractColumnFamily.remove
public function remove($key, $column_names=null, $consistency_level=null) { if (($column_names === null || count($column_names) == 1) && ! $this->has_counters) { $cp = new ColumnPath(); $cp->column_family = $this->column_family; if ($column_names !== null) { if ($this->is_super) $cp->super_column = $this->pack_name($column_names[0], true); else $cp->column = $this->pack_name($column_names[0], false); } return $this->_remove_single($key, $cp, $consistency_level); } else { $deletion = new Deletion(); if ($column_names !== null) $deletion->predicate = $this->create_slice_predicate($column_names, null); return $this->_remove_multi($key, $deletion, $consistency_level); } }
php
public function remove($key, $column_names=null, $consistency_level=null) { if (($column_names === null || count($column_names) == 1) && ! $this->has_counters) { $cp = new ColumnPath(); $cp->column_family = $this->column_family; if ($column_names !== null) { if ($this->is_super) $cp->super_column = $this->pack_name($column_names[0], true); else $cp->column = $this->pack_name($column_names[0], false); } return $this->_remove_single($key, $cp, $consistency_level); } else { $deletion = new Deletion(); if ($column_names !== null) $deletion->predicate = $this->create_slice_predicate($column_names, null); return $this->_remove_multi($key, $deletion, $consistency_level); } }
[ "public", "function", "remove", "(", "$", "key", ",", "$", "column_names", "=", "null", ",", "$", "consistency_level", "=", "null", ")", "{", "if", "(", "(", "$", "column_names", "===", "null", "||", "count", "(", "$", "column_names", ")", "==", "1", ...
Delete a row or a set of columns or supercolumns from a row. @param string $key the row to remove columns from @param mixed[] $column_names the columns or supercolumns to remove. If null, the entire row will be removed. @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns @return int the timestamp for the operation
[ "Delete", "a", "row", "or", "a", "set", "of", "columns", "or", "supercolumns", "from", "a", "row", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/AbstractColumnFamily.php#L754-L776
train
webfactorybulgaria/laravel-shop
src/Models/ShopItemModel.php
ShopItemModel.getReadableAttributesAttribute
public function getReadableAttributesAttribute() { $attributes = []; foreach($this->itemAttributes as $attribute) { if($attribute->attribute_reference_id) { $attr = Attribute::where('attributes.id', $attribute->attribute_reference_id)->with('attributeGroup')->first(); $attributes[$attr->attributeGroup->value] = $attr->value; } else { $attributes[$attribute->group_value] = $attribute->attribute_value; } } return $attributes; }
php
public function getReadableAttributesAttribute() { $attributes = []; foreach($this->itemAttributes as $attribute) { if($attribute->attribute_reference_id) { $attr = Attribute::where('attributes.id', $attribute->attribute_reference_id)->with('attributeGroup')->first(); $attributes[$attr->attributeGroup->value] = $attr->value; } else { $attributes[$attribute->group_value] = $attribute->attribute_value; } } return $attributes; }
[ "public", "function", "getReadableAttributesAttribute", "(", ")", "{", "$", "attributes", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "itemAttributes", "as", "$", "attribute", ")", "{", "if", "(", "$", "attribute", "->", "attribute_reference_id", ...
Returns all selected attributes for the item. @return array
[ "Returns", "all", "selected", "attributes", "for", "the", "item", "." ]
9d191b7d17395bd875505bfbc0b1077dc6c87869
https://github.com/webfactorybulgaria/laravel-shop/blob/9d191b7d17395bd875505bfbc0b1077dc6c87869/src/Models/ShopItemModel.php#L117-L129
train
webfactorybulgaria/laravel-shop
src/Traits/ShoppableTrait.php
ShoppableTrait.getDisplayNameAttribute
public function getDisplayNameAttribute() { // if(isset($this->itemName) && $this->itemName == 'title') $this->attributes['title'] = 'Title'; // if ($this->hasObject) return $this->object->displayName; return isset($this->itemName) ? $this->attributes[$this->itemName] : $this->title; }
php
public function getDisplayNameAttribute() { // if(isset($this->itemName) && $this->itemName == 'title') $this->attributes['title'] = 'Title'; // if ($this->hasObject) return $this->object->displayName; return isset($this->itemName) ? $this->attributes[$this->itemName] : $this->title; }
[ "public", "function", "getDisplayNameAttribute", "(", ")", "{", "// if(isset($this->itemName) && $this->itemName == 'title') $this->attributes['title'] = 'Title';", "// if ($this->hasObject) return $this->object->displayName;", "return", "isset", "(", "$", "this", "->", "itemName", ")"...
Returns item name. @return string
[ "Returns", "item", "name", "." ]
9d191b7d17395bd875505bfbc0b1077dc6c87869
https://github.com/webfactorybulgaria/laravel-shop/blob/9d191b7d17395bd875505bfbc0b1077dc6c87869/src/Traits/ShoppableTrait.php#L63-L70
train
mcustiel/php-simple-request
src/Validator/Properties.php
Properties.setAdditionalProperties
private function setAdditionalProperties($specification) { if (is_bool($specification)) { $this->additionalProperties = $specification; } else { $this->additionalProperties = $this->checkIfAnnotationAndReturnObject($specification); } }
php
private function setAdditionalProperties($specification) { if (is_bool($specification)) { $this->additionalProperties = $specification; } else { $this->additionalProperties = $this->checkIfAnnotationAndReturnObject($specification); } }
[ "private", "function", "setAdditionalProperties", "(", "$", "specification", ")", "{", "if", "(", "is_bool", "(", "$", "specification", ")", ")", "{", "$", "this", "->", "additionalProperties", "=", "$", "specification", ";", "}", "else", "{", "$", "this", ...
Checks and sets items specification. @param bool|\Mcustiel\SimpleRequest\Interfaces\ValidatorInterface $specification @throws \Mcustiel\SimpleRequest\Exception\UnspecifiedValidatorException
[ "Checks", "and", "sets", "items", "specification", "." ]
4d0fc06092ccdff3ea488c67b394225c7243428f
https://github.com/mcustiel/php-simple-request/blob/4d0fc06092ccdff3ea488c67b394225c7243428f/src/Validator/Properties.php#L249-L256
train
bav-php/bav
classes/dataBackend/file/validator/FileValidator.php
FileValidator.validate
public function validate($file) { $parser = new FileParser($file); // file size is normally around 3 MB. Less than 1.5 is not valid $size = filesize($file); if ($size < self::FILESIZE) { throw new InvalidFilesizeException( "Get updated BAV version:" . " file size should not be less than " . self::FILESIZE . " but was $size." ); } // check line length $minLength = FileParser::SUCCESSOR_OFFSET + FileParser::SUCCESSOR_LENGTH; if ($parser->getLineLength() < $minLength) { throw new InvalidLineLengthException( "Get updated BAV version:" . " Line length shouldn't be less than $minLength but was {$parser->getLineLength()}." ); } // rough check that line length is constant. if ($size % $parser->getLineLength() != 0) { throw new InvalidLineLengthException("Get updated BAV version: Line length is not constant."); } $firstLine = $parser->readLine(0); if (! preg_match("/^100000001Bundesbank/", $firstLine)) { throw new FieldException("Get updated BAV version: first line has unexpected content: $firstLine"); } }
php
public function validate($file) { $parser = new FileParser($file); // file size is normally around 3 MB. Less than 1.5 is not valid $size = filesize($file); if ($size < self::FILESIZE) { throw new InvalidFilesizeException( "Get updated BAV version:" . " file size should not be less than " . self::FILESIZE . " but was $size." ); } // check line length $minLength = FileParser::SUCCESSOR_OFFSET + FileParser::SUCCESSOR_LENGTH; if ($parser->getLineLength() < $minLength) { throw new InvalidLineLengthException( "Get updated BAV version:" . " Line length shouldn't be less than $minLength but was {$parser->getLineLength()}." ); } // rough check that line length is constant. if ($size % $parser->getLineLength() != 0) { throw new InvalidLineLengthException("Get updated BAV version: Line length is not constant."); } $firstLine = $parser->readLine(0); if (! preg_match("/^100000001Bundesbank/", $firstLine)) { throw new FieldException("Get updated BAV version: first line has unexpected content: $firstLine"); } }
[ "public", "function", "validate", "(", "$", "file", ")", "{", "$", "parser", "=", "new", "FileParser", "(", "$", "file", ")", ";", "// file size is normally around 3 MB. Less than 1.5 is not valid", "$", "size", "=", "filesize", "(", "$", "file", ")", ";", "if...
Validates a bundesbank file. @param string $file bundesbank file. @throws FileValidatorException
[ "Validates", "a", "bundesbank", "file", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/dataBackend/file/validator/FileValidator.php#L23-L58
train
dmyers/laravel-storage
src/Dmyers/Storage/Adapter/Base.php
Base.remoteUpload
public function remoteUpload($url, $target) { $tmp_name = md5($url); $tmp_path = Storage::config('tmp_path').'/'.$tmp_name; if (!$this->remoteDownload($url, $tmp_path)) { return false; } return $this->upload($tmp_path, $target); }
php
public function remoteUpload($url, $target) { $tmp_name = md5($url); $tmp_path = Storage::config('tmp_path').'/'.$tmp_name; if (!$this->remoteDownload($url, $tmp_path)) { return false; } return $this->upload($tmp_path, $target); }
[ "public", "function", "remoteUpload", "(", "$", "url", ",", "$", "target", ")", "{", "$", "tmp_name", "=", "md5", "(", "$", "url", ")", ";", "$", "tmp_path", "=", "Storage", "::", "config", "(", "'tmp_path'", ")", ".", "'/'", ".", "$", "tmp_name", ...
Upload a remote file into storage. @param string $url The url to the remote file to upload. @param string $target The path to the file to store. @return bool
[ "Upload", "a", "remote", "file", "into", "storage", "." ]
2c4d3b22ecb3e76b5124eb671b06da1e33b65ac7
https://github.com/dmyers/laravel-storage/blob/2c4d3b22ecb3e76b5124eb671b06da1e33b65ac7/src/Dmyers/Storage/Adapter/Base.php#L60-L70
train
dmyers/laravel-storage
src/Dmyers/Storage/Adapter/Base.php
Base.remoteDownload
public function remoteDownload($url, $target) { $client = new \GuzzleHttp\Client(); try { $client->get($url, array('save_to' => $target)); } catch (\GuzzleHttp\Exception\RequestException $e) { return false; } return true; }
php
public function remoteDownload($url, $target) { $client = new \GuzzleHttp\Client(); try { $client->get($url, array('save_to' => $target)); } catch (\GuzzleHttp\Exception\RequestException $e) { return false; } return true; }
[ "public", "function", "remoteDownload", "(", "$", "url", ",", "$", "target", ")", "{", "$", "client", "=", "new", "\\", "GuzzleHttp", "\\", "Client", "(", ")", ";", "try", "{", "$", "client", "->", "get", "(", "$", "url", ",", "array", "(", "'save_...
Download a remote file locally. @param string $url The url to the remote file to download. @param string $target The path to the local file to store. @return bool
[ "Download", "a", "remote", "file", "locally", "." ]
2c4d3b22ecb3e76b5124eb671b06da1e33b65ac7
https://github.com/dmyers/laravel-storage/blob/2c4d3b22ecb3e76b5124eb671b06da1e33b65ac7/src/Dmyers/Storage/Adapter/Base.php#L90-L102
train
dmyers/laravel-storage
src/Dmyers/Storage/Adapter/Base.php
Base.render
public function render($path) { $file = static::get($path); $mime = static::mime($path); return \Response::make($file, 200, array( 'Content-Type' => $mime, )); }
php
public function render($path) { $file = static::get($path); $mime = static::mime($path); return \Response::make($file, 200, array( 'Content-Type' => $mime, )); }
[ "public", "function", "render", "(", "$", "path", ")", "{", "$", "file", "=", "static", "::", "get", "(", "$", "path", ")", ";", "$", "mime", "=", "static", "::", "mime", "(", "$", "path", ")", ";", "return", "\\", "Response", "::", "make", "(", ...
Render a file from storage to the browser. @param string $path The path to the file to render. @return Response
[ "Render", "a", "file", "from", "storage", "to", "the", "browser", "." ]
2c4d3b22ecb3e76b5124eb671b06da1e33b65ac7
https://github.com/dmyers/laravel-storage/blob/2c4d3b22ecb3e76b5124eb671b06da1e33b65ac7/src/Dmyers/Storage/Adapter/Base.php#L203-L212
train
tedslittlerobot/html-table-builder
src/Elements/Traits/Attributable.php
Attributable.renderAttributes
public function renderAttributes() : string { $pairs = array_map(function(string $value, string $key) { return sprintf('%s="%s"', helpers\e($key), helpers\e($value)); }, $this->attributes, array_keys($this->attributes)); return implode(' ', $pairs); }
php
public function renderAttributes() : string { $pairs = array_map(function(string $value, string $key) { return sprintf('%s="%s"', helpers\e($key), helpers\e($value)); }, $this->attributes, array_keys($this->attributes)); return implode(' ', $pairs); }
[ "public", "function", "renderAttributes", "(", ")", ":", "string", "{", "$", "pairs", "=", "array_map", "(", "function", "(", "string", "$", "value", ",", "string", "$", "key", ")", "{", "return", "sprintf", "(", "'%s=\"%s\"'", ",", "helpers", "\\", "e",...
Render the attributes as a string @return string
[ "Render", "the", "attributes", "as", "a", "string" ]
12597f8c44dde9f002c74b0aeadefec2bdb2eafa
https://github.com/tedslittlerobot/html-table-builder/blob/12597f8c44dde9f002c74b0aeadefec2bdb2eafa/src/Elements/Traits/Attributable.php#L61-L68
train
asinfotrack/yii2-toolbox
helpers/Geocoding.php
Geocoding.geocode
public static function geocode($address, $fullResults=false, $timeout=5, $apiKey=null, $url=null) { //prepare the url by replacing the placeholders $preparedUrl = static::getForwardUrl($address, $apiKey, $url); //perform api call $response = static::callApi($preparedUrl, $timeout); if ($response === false) return false; //parse result and act according to status $data = Json::decode($response); if (strcasecmp($data['status'], 'ok') === 0 && count($data['results']) > 0) { if ($fullResults) { return $data['results']; } else { return [ 'latitude'=>$data['results'][0]['geometry']['location']['lat'], 'longitude'=>$data['results'][0]['geometry']['location']['lng'], ]; } } else { return false; } }
php
public static function geocode($address, $fullResults=false, $timeout=5, $apiKey=null, $url=null) { //prepare the url by replacing the placeholders $preparedUrl = static::getForwardUrl($address, $apiKey, $url); //perform api call $response = static::callApi($preparedUrl, $timeout); if ($response === false) return false; //parse result and act according to status $data = Json::decode($response); if (strcasecmp($data['status'], 'ok') === 0 && count($data['results']) > 0) { if ($fullResults) { return $data['results']; } else { return [ 'latitude'=>$data['results'][0]['geometry']['location']['lat'], 'longitude'=>$data['results'][0]['geometry']['location']['lng'], ]; } } else { return false; } }
[ "public", "static", "function", "geocode", "(", "$", "address", ",", "$", "fullResults", "=", "false", ",", "$", "timeout", "=", "5", ",", "$", "apiKey", "=", "null", ",", "$", "url", "=", "null", ")", "{", "//prepare the url by replacing the placeholders", ...
Tries to geocode an address into WGS84 latitude and longitude coordinates. If successful the method will return an array in the following format: ```php [ 'latitude'=>46.2213, 'longitude'=>26.1654, ] ``` If the request failed, the method will return false. The full documentation of the google api can be found here: @see https://developers.google.com/maps/documentation/geocoding/intro @param string $address the address to geocode @param int $timeout optional timeout (defaults to 5s) @param string $apiKey optional specific api key @param string $url optional custom url, make sure you use the placeholders `{address}` and `{apikey}` @return array|bool either an array containing lat and long or false upon failure @throws \Exception when not properly configured or upon problem during the api call
[ "Tries", "to", "geocode", "an", "address", "into", "WGS84", "latitude", "and", "longitude", "coordinates", "." ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/Geocoding.php#L59-L82
train
asinfotrack/yii2-toolbox
helpers/Geocoding.php
Geocoding.callApi
protected static function callApi($url, $timeout) { try { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); $response = curl_exec($ch); } catch (\Exception $e) { curl_close($ch); Yii::error($e->getMessage()); throw $e; } curl_close($ch); return $response; }
php
protected static function callApi($url, $timeout) { try { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); $response = curl_exec($ch); } catch (\Exception $e) { curl_close($ch); Yii::error($e->getMessage()); throw $e; } curl_close($ch); return $response; }
[ "protected", "static", "function", "callApi", "(", "$", "url", ",", "$", "timeout", ")", "{", "try", "{", "$", "ch", "=", "curl_init", "(", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "$", "url", ")", ";", "curl_setopt", "(", ...
Does an actual api call via curl @param string $url the url to call @param integer $timeout the timeout @return mixed the raw result @throws \Exception when something goes wrong during the curl call
[ "Does", "an", "actual", "api", "call", "via", "curl" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/Geocoding.php#L132-L151
train
asinfotrack/yii2-toolbox
helpers/Geocoding.php
Geocoding.getApiKey
protected static function getApiKey($customApiKey=null) { //check if key was provided if ($customApiKey !== null) return $customApiKey; //otherwise lookup the key in the params or throw exception if (!isset(Yii::$app->params['api.google.key'])) { $msg = Yii::t('app', 'You need to set the google api key into your params (index: `api.google.key`)'); throw new InvalidConfigException($msg); } return Yii::$app->params['api.google.key']; }
php
protected static function getApiKey($customApiKey=null) { //check if key was provided if ($customApiKey !== null) return $customApiKey; //otherwise lookup the key in the params or throw exception if (!isset(Yii::$app->params['api.google.key'])) { $msg = Yii::t('app', 'You need to set the google api key into your params (index: `api.google.key`)'); throw new InvalidConfigException($msg); } return Yii::$app->params['api.google.key']; }
[ "protected", "static", "function", "getApiKey", "(", "$", "customApiKey", "=", "null", ")", "{", "//check if key was provided", "if", "(", "$", "customApiKey", "!==", "null", ")", "return", "$", "customApiKey", ";", "//otherwise lookup the key in the params or throw exc...
Configures the class for further usage @param string $customApiKey api key data or null to lookup in params @return null if no api key is set in the params @throws \yii\base\InvalidConfigException if no api key is set in the params
[ "Configures", "the", "class", "for", "further", "usage" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/Geocoding.php#L210-L222
train
laravel-notification-channels/hipchat
src/CardAttribute.php
CardAttribute.icon
public function icon($icon, $icon2 = null) { $this->icon = trim($icon); if (! str_empty($icon2)) { $this->icon2 = trim($icon2); } return $this; }
php
public function icon($icon, $icon2 = null) { $this->icon = trim($icon); if (! str_empty($icon2)) { $this->icon2 = trim($icon2); } return $this; }
[ "public", "function", "icon", "(", "$", "icon", ",", "$", "icon2", "=", "null", ")", "{", "$", "this", "->", "icon", "=", "trim", "(", "$", "icon", ")", ";", "if", "(", "!", "str_empty", "(", "$", "icon2", ")", ")", "{", "$", "this", "->", "i...
Sets the icon for the attribute. @param string $icon @param string|null $icon2 @return $this
[ "Sets", "the", "icon", "for", "the", "attribute", "." ]
c24bca85f7cf9f6804635aa206c961783e22e888
https://github.com/laravel-notification-channels/hipchat/blob/c24bca85f7cf9f6804635aa206c961783e22e888/src/CardAttribute.php#L94-L103
train
silverstripe-archive/deploynaut
code/model/jobs/DNDataTransfer.php
DNDataTransfer.start
public function start() { $env = $this->Environment(); $log = $this->log(); $args = array( 'dataTransferID' => $this->ID, 'logfile' => $this->logfile(), 'backupBeforePush' => $this->backupBeforePush ); if(!$this->AuthorID) { $this->AuthorID = Member::currentUserID(); } if($this->AuthorID) { $author = $this->Author(); $message = sprintf( 'Data transfer on %s (%s, %s) initiated by %s (%s), with IP address %s', $env->getFullName(), $this->Direction, $this->Mode, $author->getName(), $author->Email, Controller::curr()->getRequest()->getIP() ); $log->write($message); } $token = Resque::enqueue('git', 'DataTransferJob', $args, true); $this->ResqueToken = $token; $this->write(); $message = sprintf('Data transfer queued as job %s', $token); $log->write($message); }
php
public function start() { $env = $this->Environment(); $log = $this->log(); $args = array( 'dataTransferID' => $this->ID, 'logfile' => $this->logfile(), 'backupBeforePush' => $this->backupBeforePush ); if(!$this->AuthorID) { $this->AuthorID = Member::currentUserID(); } if($this->AuthorID) { $author = $this->Author(); $message = sprintf( 'Data transfer on %s (%s, %s) initiated by %s (%s), with IP address %s', $env->getFullName(), $this->Direction, $this->Mode, $author->getName(), $author->Email, Controller::curr()->getRequest()->getIP() ); $log->write($message); } $token = Resque::enqueue('git', 'DataTransferJob', $args, true); $this->ResqueToken = $token; $this->write(); $message = sprintf('Data transfer queued as job %s', $token); $log->write($message); }
[ "public", "function", "start", "(", ")", "{", "$", "env", "=", "$", "this", "->", "Environment", "(", ")", ";", "$", "log", "=", "$", "this", "->", "log", "(", ")", ";", "$", "args", "=", "array", "(", "'dataTransferID'", "=>", "$", "this", "->",...
Queue a transfer job
[ "Queue", "a", "transfer", "job" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/jobs/DNDataTransfer.php#L132-L166
train
mcustiel/php-simple-request
src/AllErrorsRequestParser.php
AllErrorsRequestParser.parse
public function parse($request) { $object = clone $this->requestObject; $invalidValues = []; foreach ($this->propertyParsers as $propertyParser) { try { $this->setProperty($request, $object, $propertyParser); } catch (InvalidValueException $e) { $invalidValues[$propertyParser->getName()] = $e->getMessage(); } } $this->checkIfRequestIsValidOrThrowException($invalidValues); return $object; }
php
public function parse($request) { $object = clone $this->requestObject; $invalidValues = []; foreach ($this->propertyParsers as $propertyParser) { try { $this->setProperty($request, $object, $propertyParser); } catch (InvalidValueException $e) { $invalidValues[$propertyParser->getName()] = $e->getMessage(); } } $this->checkIfRequestIsValidOrThrowException($invalidValues); return $object; }
[ "public", "function", "parse", "(", "$", "request", ")", "{", "$", "object", "=", "clone", "$", "this", "->", "requestObject", ";", "$", "invalidValues", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "propertyParsers", "as", "$", "propertyParser...
Parses a request and returns a response object containing the converted object and the list of errors. @param array|\stdClass $request @return ParserResponse
[ "Parses", "a", "request", "and", "returns", "a", "response", "object", "containing", "the", "converted", "object", "and", "the", "list", "of", "errors", "." ]
4d0fc06092ccdff3ea488c67b394225c7243428f
https://github.com/mcustiel/php-simple-request/blob/4d0fc06092ccdff3ea488c67b394225c7243428f/src/AllErrorsRequestParser.php#L39-L54
train
mcustiel/php-simple-request
src/AllErrorsRequestParser.php
AllErrorsRequestParser.checkIfRequestIsValidOrThrowException
private function checkIfRequestIsValidOrThrowException($invalidValues) { if (!empty($invalidValues)) { $exception = new InvalidRequestException('Errors occurred while parsing the request'); $exception->setErrors($invalidValues); throw $exception; } }
php
private function checkIfRequestIsValidOrThrowException($invalidValues) { if (!empty($invalidValues)) { $exception = new InvalidRequestException('Errors occurred while parsing the request'); $exception->setErrors($invalidValues); throw $exception; } }
[ "private", "function", "checkIfRequestIsValidOrThrowException", "(", "$", "invalidValues", ")", "{", "if", "(", "!", "empty", "(", "$", "invalidValues", ")", ")", "{", "$", "exception", "=", "new", "InvalidRequestException", "(", "'Errors occurred while parsing the re...
Checks if there are invalid values in the request, in that case it throws an exception. @param array $invalidValues @throws \Mcustiel\SimpleRequest\Exception\InvalidRequestException
[ "Checks", "if", "there", "are", "invalid", "values", "in", "the", "request", "in", "that", "case", "it", "throws", "an", "exception", "." ]
4d0fc06092ccdff3ea488c67b394225c7243428f
https://github.com/mcustiel/php-simple-request/blob/4d0fc06092ccdff3ea488c67b394225c7243428f/src/AllErrorsRequestParser.php#L64-L71
train
silverstripe-archive/deploynaut
code/model/jobs/DNGitFetch.php
DNGitFetch.start
public function start() { $project = $this->Project(); $log = $this->log(); $args = array( 'projectName' => $project->Name, 'logfile' => $this->logfile(), 'env' => $project->getProcessEnv() ); if(!$this->DeployerID) { $this->DeployerID = Member::currentUserID(); } if($this->DeployerID) { $deployer = $this->Deployer(); $message = sprintf( 'Update repository job for %s initiated by %s (%s)', $project->Name, $deployer->getName(), $deployer->Email ); $log->write($message); } $token = Resque::enqueue('git', 'FetchJob', $args, true); $this->ResqueToken = $token; $this->write(); $message = sprintf('Fetch queued as job %s', $token); $log->write($message); }
php
public function start() { $project = $this->Project(); $log = $this->log(); $args = array( 'projectName' => $project->Name, 'logfile' => $this->logfile(), 'env' => $project->getProcessEnv() ); if(!$this->DeployerID) { $this->DeployerID = Member::currentUserID(); } if($this->DeployerID) { $deployer = $this->Deployer(); $message = sprintf( 'Update repository job for %s initiated by %s (%s)', $project->Name, $deployer->getName(), $deployer->Email ); $log->write($message); } $token = Resque::enqueue('git', 'FetchJob', $args, true); $this->ResqueToken = $token; $this->write(); $message = sprintf('Fetch queued as job %s', $token); $log->write($message); }
[ "public", "function", "start", "(", ")", "{", "$", "project", "=", "$", "this", "->", "Project", "(", ")", ";", "$", "log", "=", "$", "this", "->", "log", "(", ")", ";", "$", "args", "=", "array", "(", "'projectName'", "=>", "$", "project", "->",...
Queue a fetch job
[ "Queue", "a", "fetch", "job" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/jobs/DNGitFetch.php#L25-L56
train
tedslittlerobot/html-table-builder
src/Elements/Section.php
Section.nextRow
public function nextRow(Row $current) : RowInterface { $index = array_search($current, $this->rows, true); if ($index === false) { throw new InvalidArgumentException('The given row is not in the rows array'); } return $this->rows[$index + 1] ?? $this->row(); }
php
public function nextRow(Row $current) : RowInterface { $index = array_search($current, $this->rows, true); if ($index === false) { throw new InvalidArgumentException('The given row is not in the rows array'); } return $this->rows[$index + 1] ?? $this->row(); }
[ "public", "function", "nextRow", "(", "Row", "$", "current", ")", ":", "RowInterface", "{", "$", "index", "=", "array_search", "(", "$", "current", ",", "$", "this", "->", "rows", ",", "true", ")", ";", "if", "(", "$", "index", "===", "false", ")", ...
Get the next row from the one given. Creates a new row if it's the last row @return \Tlr\Tables\Elements\Interfaces\RowInterface
[ "Get", "the", "next", "row", "from", "the", "one", "given", ".", "Creates", "a", "new", "row", "if", "it", "s", "the", "last", "row" ]
12597f8c44dde9f002c74b0aeadefec2bdb2eafa
https://github.com/tedslittlerobot/html-table-builder/blob/12597f8c44dde9f002c74b0aeadefec2bdb2eafa/src/Elements/Section.php#L29-L38
train
mcustiel/php-simple-request
src/Util/FilterBuilder.php
FilterBuilder.getClassForType
final protected function getClassForType($type) { if (!class_exists($type)) { throw new FilterDoesNotExistException("Filter class {$type} does not exist"); } $filter = new $type; if (! ($filter instanceof FilterInterface)) { throw new FilterDoesNotExistException( "Filter class {$type} must implement " . FilterInterface::class ); } return $filter; }
php
final protected function getClassForType($type) { if (!class_exists($type)) { throw new FilterDoesNotExistException("Filter class {$type} does not exist"); } $filter = new $type; if (! ($filter instanceof FilterInterface)) { throw new FilterDoesNotExistException( "Filter class {$type} must implement " . FilterInterface::class ); } return $filter; }
[ "final", "protected", "function", "getClassForType", "(", "$", "type", ")", "{", "if", "(", "!", "class_exists", "(", "$", "type", ")", ")", "{", "throw", "new", "FilterDoesNotExistException", "(", "\"Filter class {$type} does not exist\"", ")", ";", "}", "$", ...
This method is used from AnnotationToImplementationBuilder trait. It checks the existence of the Filter class and then checks it's of type FilterInterface. @param string $type The type to instantiate. @return \Mcustiel\SimpleRequest\Interfaces\FilterInterface The instance created @throws \Mcustiel\SimpleRequest\Exception\FilterDoesNotExistException If class does not exist or does not implement FilterInterface
[ "This", "method", "is", "used", "from", "AnnotationToImplementationBuilder", "trait", ".", "It", "checks", "the", "existence", "of", "the", "Filter", "class", "and", "then", "checks", "it", "s", "of", "type", "FilterInterface", "." ]
4d0fc06092ccdff3ea488c67b394225c7243428f
https://github.com/mcustiel/php-simple-request/blob/4d0fc06092ccdff3ea488c67b394225c7243428f/src/Util/FilterBuilder.php#L41-L54
train
asinfotrack/yii2-toolbox
widgets/grid/AdvancedActionColumn.php
AdvancedActionColumn.createIcon
protected function createIcon($iconName) { if (is_callable($this->createIconCallback)) { return call_user_func($this->createIconCallback, $iconName); } else { return Icon::create($iconName); } }
php
protected function createIcon($iconName) { if (is_callable($this->createIconCallback)) { return call_user_func($this->createIconCallback, $iconName); } else { return Icon::create($iconName); } }
[ "protected", "function", "createIcon", "(", "$", "iconName", ")", "{", "if", "(", "is_callable", "(", "$", "this", "->", "createIconCallback", ")", ")", "{", "return", "call_user_func", "(", "$", "this", "->", "createIconCallback", ",", "$", "iconName", ")",...
Creates the icons as used by the buttons @param string $iconName the name of the icon to use @return string the final html code of the icon
[ "Creates", "the", "icons", "as", "used", "by", "the", "buttons" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/widgets/grid/AdvancedActionColumn.php#L138-L145
train
asinfotrack/yii2-toolbox
widgets/StatsBoxes.php
StatsBoxes.renderBox
protected function renderBox($boxData, $colSize) { $options = $boxData['options']; Html::addCssClass($options, 'col-md-' . $colSize); Html::addCssClass($options, 'col-sm-' . ($colSize * 2)); Html::addCssClass($options, 'stats-box'); echo Html::beginTag('div', $options); echo Html::beginTag('div', ['class'=>'stats-box-content-wrapper']); //header echo Html::beginTag('div', ['class'=>'stats-box-header']); if (isset($boxData['headerIcon'])) { echo $this->createIcon($boxData['headerIcon']); } echo Html::tag($this->headerTagName, $boxData['header']); echo Html::endTag('div'); //content echo Html::beginTag('div', ['class'=>'stats-box-content']); if (isset($boxData['valuePrefix'])) echo Html::tag('span', $boxData['valuePrefix'], ['class'=>'stats-box-content-prefix']); $value = $boxData['value'] instanceof \Closure ? call_user_func($boxData['value']) : $boxData['value']; echo Html::tag('span', $value, ['class'=>'stats-box-value']); if (isset($boxData['valueSuffix'])) echo Html::tag('span', $boxData['valueSuffix'], ['class'=>'stats-box-content-suffix']); echo Html::endTag('div'); echo Html::endTag('div'); echo Html::endTag('div'); }
php
protected function renderBox($boxData, $colSize) { $options = $boxData['options']; Html::addCssClass($options, 'col-md-' . $colSize); Html::addCssClass($options, 'col-sm-' . ($colSize * 2)); Html::addCssClass($options, 'stats-box'); echo Html::beginTag('div', $options); echo Html::beginTag('div', ['class'=>'stats-box-content-wrapper']); //header echo Html::beginTag('div', ['class'=>'stats-box-header']); if (isset($boxData['headerIcon'])) { echo $this->createIcon($boxData['headerIcon']); } echo Html::tag($this->headerTagName, $boxData['header']); echo Html::endTag('div'); //content echo Html::beginTag('div', ['class'=>'stats-box-content']); if (isset($boxData['valuePrefix'])) echo Html::tag('span', $boxData['valuePrefix'], ['class'=>'stats-box-content-prefix']); $value = $boxData['value'] instanceof \Closure ? call_user_func($boxData['value']) : $boxData['value']; echo Html::tag('span', $value, ['class'=>'stats-box-value']); if (isset($boxData['valueSuffix'])) echo Html::tag('span', $boxData['valueSuffix'], ['class'=>'stats-box-content-suffix']); echo Html::endTag('div'); echo Html::endTag('div'); echo Html::endTag('div'); }
[ "protected", "function", "renderBox", "(", "$", "boxData", ",", "$", "colSize", ")", "{", "$", "options", "=", "$", "boxData", "[", "'options'", "]", ";", "Html", "::", "addCssClass", "(", "$", "options", ",", "'col-md-'", ".", "$", "colSize", ")", ";"...
Does the actual rendering of a single box @param array $boxData the box configuration data @param int $colSize the column size
[ "Does", "the", "actual", "rendering", "of", "a", "single", "box" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/widgets/StatsBoxes.php#L129-L157
train
webfactorybulgaria/laravel-shop
src/Http/Controllers/Shop/CallbackController.php
CallbackController.process
protected function process(Request $request, $status, $id, $shoptoken) { $validator = Validator::make( [ 'id' => $id, 'status' => $status, 'shoptoken' => $shoptoken, ], [ 'id' => 'required|exists:' . config('shop.order_table') . ',id', 'status' => 'required|in:success,fail', 'shoptoken' => 'required|exists:' . config('shop.transaction_table') . ',token,order_id,' . $id, ] ); if ($validator->fails()) { abort(404); } $order = call_user_func(config('shop.order') . '::find', $id); $transaction = $order->transactions()->where('token', $shoptoken)->first(); Shop::callback($order, $transaction, $status, $request->all()); $transaction->token = null; $transaction->save(); return redirect()->route(config('shop.callback_redirect_route'), ['order' => $order->id]); }
php
protected function process(Request $request, $status, $id, $shoptoken) { $validator = Validator::make( [ 'id' => $id, 'status' => $status, 'shoptoken' => $shoptoken, ], [ 'id' => 'required|exists:' . config('shop.order_table') . ',id', 'status' => 'required|in:success,fail', 'shoptoken' => 'required|exists:' . config('shop.transaction_table') . ',token,order_id,' . $id, ] ); if ($validator->fails()) { abort(404); } $order = call_user_func(config('shop.order') . '::find', $id); $transaction = $order->transactions()->where('token', $shoptoken)->first(); Shop::callback($order, $transaction, $status, $request->all()); $transaction->token = null; $transaction->save(); return redirect()->route(config('shop.callback_redirect_route'), ['order' => $order->id]); }
[ "protected", "function", "process", "(", "Request", "$", "request", ",", "$", "status", ",", "$", "id", ",", "$", "shoptoken", ")", "{", "$", "validator", "=", "Validator", "::", "make", "(", "[", "'id'", "=>", "$", "id", ",", "'status'", "=>", "$", ...
Process payment callback. @param Request $request Request. @param string $status Callback status. @param int $id Order ID. @param string $shoptoken Transaction token for security. @return redirect
[ "Process", "payment", "callback", "." ]
9d191b7d17395bd875505bfbc0b1077dc6c87869
https://github.com/webfactorybulgaria/laravel-shop/blob/9d191b7d17395bd875505bfbc0b1077dc6c87869/src/Http/Controllers/Shop/CallbackController.php#L22-L52
train
swoft-cloud/swoft-http-message
src/Uri/Uri.php
Uri.validateState
private function validateState() { if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { $this->host = self::DEFAULT_HTTP_HOST; } if ($this->getAuthority() === '') { if (0 === strpos($this->path, '//')) { throw new \InvalidArgumentException('The path of a URI without an authority must not start with two slashes "//"'); } if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) { throw new \InvalidArgumentException('A relative URI must not have a path beginning with a segment containing a colon'); } } elseif (isset($this->path[0]) && $this->path[0] !== '/') { $this->path = '/' . $this->path; } }
php
private function validateState() { if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { $this->host = self::DEFAULT_HTTP_HOST; } if ($this->getAuthority() === '') { if (0 === strpos($this->path, '//')) { throw new \InvalidArgumentException('The path of a URI without an authority must not start with two slashes "//"'); } if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) { throw new \InvalidArgumentException('A relative URI must not have a path beginning with a segment containing a colon'); } } elseif (isset($this->path[0]) && $this->path[0] !== '/') { $this->path = '/' . $this->path; } }
[ "private", "function", "validateState", "(", ")", "{", "if", "(", "$", "this", "->", "host", "===", "''", "&&", "(", "$", "this", "->", "scheme", "===", "'http'", "||", "$", "this", "->", "scheme", "===", "'https'", ")", ")", "{", "$", "this", "->"...
Common state validate method
[ "Common", "state", "validate", "method" ]
5cc36c68b24d8ff9bc75cd0f6c8492bcc452f73a
https://github.com/swoft-cloud/swoft-http-message/blob/5cc36c68b24d8ff9bc75cd0f6c8492bcc452f73a/src/Uri/Uri.php#L545-L560
train
bav-php/bav
classes/BAV.php
BAV.isValidBankAccount
public function isValidBankAccount($bankID, $account) { try { $bank = $this->getBank($bankID); return $bank->isValid($account); } catch (BankNotFoundException $e) { return false; } }
php
public function isValidBankAccount($bankID, $account) { try { $bank = $this->getBank($bankID); return $bank->isValid($account); } catch (BankNotFoundException $e) { return false; } }
[ "public", "function", "isValidBankAccount", "(", "$", "bankID", ",", "$", "account", ")", "{", "try", "{", "$", "bank", "=", "$", "this", "->", "getBank", "(", "$", "bankID", ")", ";", "return", "$", "bank", "->", "isValid", "(", "$", "account", ")",...
Returns true if both the bank exists and the account is valid. @throws DataBackendException for some reason the validator might not be implemented @param string $bankID @param string $account @see isValidBank() @see getBank() @see Bank::isValid() @return bool
[ "Returns", "true", "if", "both", "the", "bank", "exists", "and", "the", "account", "is", "valid", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/BAV.php#L95-L105
train
silverstripe-archive/deploynaut
code/backends/CapistranoDeploymentBackend.php
CapistranoDeploymentBackend.deploy
public function deploy(DNEnvironment $environment, $sha, DeploynautLogFile $log, DNProject $project, $leaveMaintenancePage = false) { $name = $environment->getFullName(); $repository = $project->LocalCVSPath; $args = array( 'branch' => $sha, 'repository' => $repository, ); $this->extend('deployStart', $environment, $sha, $log, $project); $log->write(sprintf('Deploying "%s" to "%s"', $sha, $name)); $this->enableMaintenance($environment, $log, $project); // Use a package generator if specified, otherwise run a direct deploy, which is the default behaviour // if build_filename isn't specified if($this->packageGenerator) { $args['build_filename'] = $this->packageGenerator->getPackageFilename($project->Name, $sha, $repository, $log); if(empty($args['build_filename'])) { throw new RuntimeException('Failed to generate package.'); } } $command = $this->getCommand('deploy', 'web', $environment, $args, $log); $command->run(function($type, $buffer) use($log) { $log->write($buffer); }); // Deployment cleanup. We assume it is always safe to run this at the end, regardless of the outcome. $self = $this; $cleanupFn = function() use($self, $environment, $args, $log, $sha, $project) { $command = $self->getCommand('deploy:cleanup', 'web', $environment, $args, $log); $command->run(function($type, $buffer) use($log) { $log->write($buffer); }); if(!$command->isSuccessful()) { $self->extend('cleanupFailure', $environment, $sha, $log, $project); $log->write('Warning: Cleanup failed, but fine to continue. Needs manual cleanup sometime.'); } }; // Once the deployment has run it's necessary to update the maintenance page status if($leaveMaintenancePage) { $this->enableMaintenance($environment, $log, $project); } if(!$command->isSuccessful()) { $cleanupFn(); $this->extend('deployFailure', $environment, $sha, $log, $project); throw new RuntimeException($command->getErrorOutput()); } // Check if maintenance page should be removed if(!$leaveMaintenancePage) { $this->disableMaintenance($environment, $log, $project); } $cleanupFn(); $log->write(sprintf('Deploy of "%s" to "%s" finished', $sha, $name)); $this->extend('deployEnd', $environment, $sha, $log, $project); }
php
public function deploy(DNEnvironment $environment, $sha, DeploynautLogFile $log, DNProject $project, $leaveMaintenancePage = false) { $name = $environment->getFullName(); $repository = $project->LocalCVSPath; $args = array( 'branch' => $sha, 'repository' => $repository, ); $this->extend('deployStart', $environment, $sha, $log, $project); $log->write(sprintf('Deploying "%s" to "%s"', $sha, $name)); $this->enableMaintenance($environment, $log, $project); // Use a package generator if specified, otherwise run a direct deploy, which is the default behaviour // if build_filename isn't specified if($this->packageGenerator) { $args['build_filename'] = $this->packageGenerator->getPackageFilename($project->Name, $sha, $repository, $log); if(empty($args['build_filename'])) { throw new RuntimeException('Failed to generate package.'); } } $command = $this->getCommand('deploy', 'web', $environment, $args, $log); $command->run(function($type, $buffer) use($log) { $log->write($buffer); }); // Deployment cleanup. We assume it is always safe to run this at the end, regardless of the outcome. $self = $this; $cleanupFn = function() use($self, $environment, $args, $log, $sha, $project) { $command = $self->getCommand('deploy:cleanup', 'web', $environment, $args, $log); $command->run(function($type, $buffer) use($log) { $log->write($buffer); }); if(!$command->isSuccessful()) { $self->extend('cleanupFailure', $environment, $sha, $log, $project); $log->write('Warning: Cleanup failed, but fine to continue. Needs manual cleanup sometime.'); } }; // Once the deployment has run it's necessary to update the maintenance page status if($leaveMaintenancePage) { $this->enableMaintenance($environment, $log, $project); } if(!$command->isSuccessful()) { $cleanupFn(); $this->extend('deployFailure', $environment, $sha, $log, $project); throw new RuntimeException($command->getErrorOutput()); } // Check if maintenance page should be removed if(!$leaveMaintenancePage) { $this->disableMaintenance($environment, $log, $project); } $cleanupFn(); $log->write(sprintf('Deploy of "%s" to "%s" finished', $sha, $name)); $this->extend('deployEnd', $environment, $sha, $log, $project); }
[ "public", "function", "deploy", "(", "DNEnvironment", "$", "environment", ",", "$", "sha", ",", "DeploynautLogFile", "$", "log", ",", "DNProject", "$", "project", ",", "$", "leaveMaintenancePage", "=", "false", ")", "{", "$", "name", "=", "$", "environment",...
Deploy the given build to the given environment.
[ "Deploy", "the", "given", "build", "to", "the", "given", "environment", "." ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/backends/CapistranoDeploymentBackend.php#L19-L83
train
silverstripe-archive/deploynaut
code/backends/CapistranoDeploymentBackend.php
CapistranoDeploymentBackend.rebuild
public function rebuild(DNEnvironment $environment, $log) { $name = $environment->getFullName(); $command = $this->getCommand('deploy:migrate', 'web', $environment, null, $log); $command->run(function($type, $buffer) use($log) { $log->write($buffer); }); if(!$command->isSuccessful()) { $log->write(sprintf('Rebuild of "%s" failed: %s', $name, $command->getErrorOutput())); throw new RuntimeException($command->getErrorOutput()); } $log->write(sprintf('Rebuild of "%s" done', $name)); }
php
public function rebuild(DNEnvironment $environment, $log) { $name = $environment->getFullName(); $command = $this->getCommand('deploy:migrate', 'web', $environment, null, $log); $command->run(function($type, $buffer) use($log) { $log->write($buffer); }); if(!$command->isSuccessful()) { $log->write(sprintf('Rebuild of "%s" failed: %s', $name, $command->getErrorOutput())); throw new RuntimeException($command->getErrorOutput()); } $log->write(sprintf('Rebuild of "%s" done', $name)); }
[ "public", "function", "rebuild", "(", "DNEnvironment", "$", "environment", ",", "$", "log", ")", "{", "$", "name", "=", "$", "environment", "->", "getFullName", "(", ")", ";", "$", "command", "=", "$", "this", "->", "getCommand", "(", "'deploy:migrate'", ...
Utility function for triggering the db rebuild and flush. Also cleans up and generates new error pages.
[ "Utility", "function", "for", "triggering", "the", "db", "rebuild", "and", "flush", ".", "Also", "cleans", "up", "and", "generates", "new", "error", "pages", "." ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/backends/CapistranoDeploymentBackend.php#L314-L325
train
bav-php/bav
classes/dataBackend/orm/doctrine/DoctrineBackendContainer.php
DoctrineBackendContainer.buildByConnection
public static function buildByConnection($connection, $isDevMode = false) { $mappings = self::getXMLMappings(); $config = Setup::createXMLMetadataConfiguration($mappings, $isDevMode); $entityManager = EntityManager::create($connection, $config); return new self($entityManager); }
php
public static function buildByConnection($connection, $isDevMode = false) { $mappings = self::getXMLMappings(); $config = Setup::createXMLMetadataConfiguration($mappings, $isDevMode); $entityManager = EntityManager::create($connection, $config); return new self($entityManager); }
[ "public", "static", "function", "buildByConnection", "(", "$", "connection", ",", "$", "isDevMode", "=", "false", ")", "{", "$", "mappings", "=", "self", "::", "getXMLMappings", "(", ")", ";", "$", "config", "=", "Setup", "::", "createXMLMetadataConfiguration"...
Builds a container for a connection. @param mixed $connection Doctrine::DBAL connection @return DoctrineBackendContainer
[ "Builds", "a", "container", "for", "a", "connection", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/dataBackend/orm/doctrine/DoctrineBackendContainer.php#L44-L51
train
dmitriybelyy/yii2-cassandra-cql
Connection.php
Connection.getRaw
private function getRaw() { if ($this->pool === null) { $this->pool = new ConnectionPool($this->keyspace, $this->servers); } return $this->pool->get(); }
php
private function getRaw() { if ($this->pool === null) { $this->pool = new ConnectionPool($this->keyspace, $this->servers); } return $this->pool->get(); }
[ "private", "function", "getRaw", "(", ")", "{", "if", "(", "$", "this", "->", "pool", "===", "null", ")", "{", "$", "this", "->", "pool", "=", "new", "ConnectionPool", "(", "$", "this", "->", "keyspace", ",", "$", "this", "->", "servers", ")", ";",...
Establish connection to cassandra cluster @return \phpcassa\Connection\ConnectionWrapper
[ "Establish", "connection", "to", "cassandra", "cluster" ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/Connection.php#L29-L35
train
dmitriybelyy/yii2-cassandra-cql
Connection.php
Connection.cql3Query
public function cql3Query($query, $compression=Compression::NONE, $consistency=ConsistencyLevel::ONE) { $raw = $this->getRaw(); $cqlResult = $raw->client->execute_cql3_query($query, $compression, $consistency); $this->pool->return_connection($raw); return $cqlResult; }
php
public function cql3Query($query, $compression=Compression::NONE, $consistency=ConsistencyLevel::ONE) { $raw = $this->getRaw(); $cqlResult = $raw->client->execute_cql3_query($query, $compression, $consistency); $this->pool->return_connection($raw); return $cqlResult; }
[ "public", "function", "cql3Query", "(", "$", "query", ",", "$", "compression", "=", "Compression", "::", "NONE", ",", "$", "consistency", "=", "ConsistencyLevel", "::", "ONE", ")", "{", "$", "raw", "=", "$", "this", "->", "getRaw", "(", ")", ";", "$", ...
Execute cql3 query. @param $query @param int $compression @param int $consistency @return object
[ "Execute", "cql3", "query", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/Connection.php#L44-L51
train
dmitriybelyy/yii2-cassandra-cql
Connection.php
Connection.cqlGetRows
public function cqlGetRows($cqlResult) { if ($cqlResult->type == 1) { $rows = array(); foreach ($cqlResult->rows as $rowIndex => $cqlRow) { $cols = array(); foreach ($cqlRow->columns as $colIndex => $column) { $type = DataType::get_type_for($cqlResult->schema->value_types[$column->name]); $cols[$column->name] = $type->unpack($column->value); } $rows[] = $cols; } return $rows; } else { return null; } }
php
public function cqlGetRows($cqlResult) { if ($cqlResult->type == 1) { $rows = array(); foreach ($cqlResult->rows as $rowIndex => $cqlRow) { $cols = array(); foreach ($cqlRow->columns as $colIndex => $column) { $type = DataType::get_type_for($cqlResult->schema->value_types[$column->name]); $cols[$column->name] = $type->unpack($column->value); } $rows[] = $cols; } return $rows; } else { return null; } }
[ "public", "function", "cqlGetRows", "(", "$", "cqlResult", ")", "{", "if", "(", "$", "cqlResult", "->", "type", "==", "1", ")", "{", "$", "rows", "=", "array", "(", ")", ";", "foreach", "(", "$", "cqlResult", "->", "rows", "as", "$", "rowIndex", "=...
Retrieving the correct integer value. Eliminates the problem of incorrect binary to different data types in cassandra including integer types. @param $cqlResult @return array|null @link http://stackoverflow.com/questions/16139362/cassandra-is-not-retrieving-the-correct-integer-value
[ "Retrieving", "the", "correct", "integer", "value", ".", "Eliminates", "the", "problem", "of", "incorrect", "binary", "to", "different", "data", "types", "in", "cassandra", "including", "integer", "types", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/Connection.php#L60-L76
train
fondbot/drivers-vk
src/VkCommunityCommandHandler.php
VkCommunityCommandHandler.handleSendMessage
protected function handleSendMessage(SendMessage $command): void { $payload = [ 'access_token' => $this->driver->getParameter('access_token'), 'v' => VkCommunityDriver::API_VERSION, 'user_id' => $command->getRecipient()->getId(), 'message' => $command->getText(), ]; $this->driver->getHttp() ->get(VkCommunityDriver::API_URL.'messages.send', [ 'query' => $payload, ]); }
php
protected function handleSendMessage(SendMessage $command): void { $payload = [ 'access_token' => $this->driver->getParameter('access_token'), 'v' => VkCommunityDriver::API_VERSION, 'user_id' => $command->getRecipient()->getId(), 'message' => $command->getText(), ]; $this->driver->getHttp() ->get(VkCommunityDriver::API_URL.'messages.send', [ 'query' => $payload, ]); }
[ "protected", "function", "handleSendMessage", "(", "SendMessage", "$", "command", ")", ":", "void", "{", "$", "payload", "=", "[", "'access_token'", "=>", "$", "this", "->", "driver", "->", "getParameter", "(", "'access_token'", ")", ",", "'v'", "=>", "VkCom...
Handle send message command. @param SendMessage $command
[ "Handle", "send", "message", "command", "." ]
b4da296d19f0c58dacb7bae486b43d59b82da4c3
https://github.com/fondbot/drivers-vk/blob/b4da296d19f0c58dacb7bae486b43d59b82da4c3/src/VkCommunityCommandHandler.php#L19-L32
train
bav-php/bav
classes/dataBackend/file/FileDataBackend.php
FileDataBackend.update
public function update() { $downloader = new Downloader(); $content = $downloader->downloadContent(self::DOWNLOAD_URI); $uriPicker = new FallbackURIPicker(); $path = $uriPicker->pickURI($content); if (strlen($path) > 0 && $path{0} != "/") { $path = sprintf("/%s/%s", dirname(self::DOWNLOAD_URI), $path); } $pathParts = explode('/', $path); foreach ($pathParts as $i => $part) { switch ($part) { case '..': unset($pathParts[$i-1]); // fall-through as the current part ("..") should be removed as well. case '.': unset($pathParts[$i]); break; } } $path = implode('/', $pathParts); $urlParts = parse_url(self::DOWNLOAD_URI); $url = sprintf("%s://%s%s", $urlParts["scheme"], $urlParts["host"], $path); // download file $file = $downloader->downloadFile($url); // Validate file format. $validator = new FileValidator(); $validator->validate($file); // blz_20100308.txt is not sorted. $parser = new FileParser($file); $lastBankID = $parser->getBankID($parser->getLines()); if ($lastBankID < 80000000) { $this->sortFile($file); } $this->fileUtil->safeRename($file, $this->parser->getFile()); chmod($this->parser->getFile(), 0644); }
php
public function update() { $downloader = new Downloader(); $content = $downloader->downloadContent(self::DOWNLOAD_URI); $uriPicker = new FallbackURIPicker(); $path = $uriPicker->pickURI($content); if (strlen($path) > 0 && $path{0} != "/") { $path = sprintf("/%s/%s", dirname(self::DOWNLOAD_URI), $path); } $pathParts = explode('/', $path); foreach ($pathParts as $i => $part) { switch ($part) { case '..': unset($pathParts[$i-1]); // fall-through as the current part ("..") should be removed as well. case '.': unset($pathParts[$i]); break; } } $path = implode('/', $pathParts); $urlParts = parse_url(self::DOWNLOAD_URI); $url = sprintf("%s://%s%s", $urlParts["scheme"], $urlParts["host"], $path); // download file $file = $downloader->downloadFile($url); // Validate file format. $validator = new FileValidator(); $validator->validate($file); // blz_20100308.txt is not sorted. $parser = new FileParser($file); $lastBankID = $parser->getBankID($parser->getLines()); if ($lastBankID < 80000000) { $this->sortFile($file); } $this->fileUtil->safeRename($file, $this->parser->getFile()); chmod($this->parser->getFile(), 0644); }
[ "public", "function", "update", "(", ")", "{", "$", "downloader", "=", "new", "Downloader", "(", ")", ";", "$", "content", "=", "$", "downloader", "->", "downloadContent", "(", "self", "::", "DOWNLOAD_URI", ")", ";", "$", "uriPicker", "=", "new", "Fallba...
This method works only if your PHP is compiled with cURL. @see DataBackend::update() @throws DataBackendIOException @throws FileException @throws DownloaderException
[ "This", "method", "works", "only", "if", "your", "PHP", "is", "compiled", "with", "cURL", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/dataBackend/file/FileDataBackend.php#L159-L205
train
bigpaulie/yii2-social-share
src/Widget.php
Widget.parseTemplate
protected function parseTemplate($network) { $button = ''; if (!in_array($network, $this->exclude)) { $url = $this->networks[$network]; switch ($this->type) { case self::TYPE_EXTRA_SMALL: $button = str_replace( '{button}', '<a href="#" class="btn btn-sm btn-social-icon btn-{network}" onClick="sharePopup(\'' . $url . '\');">' . '<i class="fa fa-{network}"></i></a>', $this->template ); break; case self::TYPE_SMALL: $button = str_replace( '{button}', '<a href="#" class="btn btn-social-icon btn-{network}" onClick="return sharePopup(\'' . $url . '\');">' . '<i class="fa fa-{network}"></i></a>', $this->template ); break; case self::TYPE_LARGE: $button = str_replace( '{button}', '<a href="#" class="btn btn-block btn-social btn-{network}" onClick="return sharePopup(\'' . $url . '\');">' . '<i class="fa fa-{network}"></i> {text}</a>', $this->template ); break; default: break; } } if ($button) { $url = $this->url; if ($this->addUtm) { $delimitBy = '?'; if (strpos($this->url, '?')) { $delimitBy = '&'; } $url .= ($delimitBy . $this->buildUtm($network)); } $button = str_replace( [ '{text}', '{network}', '{url}', '{title}', '{description}', '{image}' ], [ $this->text, $network, urlencode($url), urlencode($this->title), urlencode($this->description), urlencode($this->image) ], $button ); } return $button; }
php
protected function parseTemplate($network) { $button = ''; if (!in_array($network, $this->exclude)) { $url = $this->networks[$network]; switch ($this->type) { case self::TYPE_EXTRA_SMALL: $button = str_replace( '{button}', '<a href="#" class="btn btn-sm btn-social-icon btn-{network}" onClick="sharePopup(\'' . $url . '\');">' . '<i class="fa fa-{network}"></i></a>', $this->template ); break; case self::TYPE_SMALL: $button = str_replace( '{button}', '<a href="#" class="btn btn-social-icon btn-{network}" onClick="return sharePopup(\'' . $url . '\');">' . '<i class="fa fa-{network}"></i></a>', $this->template ); break; case self::TYPE_LARGE: $button = str_replace( '{button}', '<a href="#" class="btn btn-block btn-social btn-{network}" onClick="return sharePopup(\'' . $url . '\');">' . '<i class="fa fa-{network}"></i> {text}</a>', $this->template ); break; default: break; } } if ($button) { $url = $this->url; if ($this->addUtm) { $delimitBy = '?'; if (strpos($this->url, '?')) { $delimitBy = '&'; } $url .= ($delimitBy . $this->buildUtm($network)); } $button = str_replace( [ '{text}', '{network}', '{url}', '{title}', '{description}', '{image}' ], [ $this->text, $network, urlencode($url), urlencode($this->title), urlencode($this->description), urlencode($this->image) ], $button ); } return $button; }
[ "protected", "function", "parseTemplate", "(", "$", "network", ")", "{", "$", "button", "=", "''", ";", "if", "(", "!", "in_array", "(", "$", "network", ",", "$", "this", "->", "exclude", ")", ")", "{", "$", "url", "=", "$", "this", "->", "networks...
Parse the template and create the specific button for the selected network @param string $network @return mixed
[ "Parse", "the", "template", "and", "create", "the", "specific", "button", "for", "the", "selected", "network" ]
49a0855616a52387997af5ce123040d762724bec
https://github.com/bigpaulie/yii2-social-share/blob/49a0855616a52387997af5ce123040d762724bec/src/Widget.php#L180-L241
train
asinfotrack/yii2-toolbox
helpers/Url.php
Url.cacheReqData
protected static function cacheReqData() { //fetch relevant vars $host = rtrim(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'], '/'); $pathInfo = !empty($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : (!empty($_SERVER['ORIG_PATH_INFO']) ? $_SERVER['ORIG_PATH_INFO'] : ''); $hostParts = array_reverse(explode('.', $host)); $pathParts = explode('/', $pathInfo); static::$RCACHE = [ 'protocol'=>!empty($_SERVER['HTTPS']) ? 'https' : 'http', 'host'=>$host, 'uri'=>$_SERVER['REQUEST_URI'], 'queryString'=>$_SERVER['QUERY_STRING'], 'hostParts'=>$hostParts, 'numParts'=>count($hostParts), 'pathParts'=>$pathParts, 'numPathParts'=>count($pathParts), ]; }
php
protected static function cacheReqData() { //fetch relevant vars $host = rtrim(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'], '/'); $pathInfo = !empty($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : (!empty($_SERVER['ORIG_PATH_INFO']) ? $_SERVER['ORIG_PATH_INFO'] : ''); $hostParts = array_reverse(explode('.', $host)); $pathParts = explode('/', $pathInfo); static::$RCACHE = [ 'protocol'=>!empty($_SERVER['HTTPS']) ? 'https' : 'http', 'host'=>$host, 'uri'=>$_SERVER['REQUEST_URI'], 'queryString'=>$_SERVER['QUERY_STRING'], 'hostParts'=>$hostParts, 'numParts'=>count($hostParts), 'pathParts'=>$pathParts, 'numPathParts'=>count($pathParts), ]; }
[ "protected", "static", "function", "cacheReqData", "(", ")", "{", "//fetch relevant vars", "$", "host", "=", "rtrim", "(", "isset", "(", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ")", "?", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ":", "$", "_SERVER", "[", ...
Caches the data for faster access in subsequent calls
[ "Caches", "the", "data", "for", "faster", "access", "in", "subsequent", "calls" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/Url.php#L24-L43
train
asinfotrack/yii2-toolbox
helpers/Url.php
Url.isInIpRange
public static function isInIpRange($range) { //get from and to addresses and translate them into numeric format if (!is_array($range)) { $from = ip2long(str_replace('*', '1', $range)); $to = ip2long(str_replace('*', '255', $range)); } else { $from = ip2long($range[0]); $to = ip2long($range[1]); } //get request ip $ipReq = ip2long(static::$RCACHE['host']); return $ipReq >= $from && $ipReq <= $to; }
php
public static function isInIpRange($range) { //get from and to addresses and translate them into numeric format if (!is_array($range)) { $from = ip2long(str_replace('*', '1', $range)); $to = ip2long(str_replace('*', '255', $range)); } else { $from = ip2long($range[0]); $to = ip2long($range[1]); } //get request ip $ipReq = ip2long(static::$RCACHE['host']); return $ipReq >= $from && $ipReq <= $to; }
[ "public", "static", "function", "isInIpRange", "(", "$", "range", ")", "{", "//get from and to addresses and translate them into numeric format", "if", "(", "!", "is_array", "(", "$", "range", ")", ")", "{", "$", "from", "=", "ip2long", "(", "str_replace", "(", ...
This method checks whether or not the request comes from a certain ip range @param string|array $range either a range specified as a single string with asterisks (`192.168.1.*`) as placeholders, or an array containing a from and a to address (`['192.168.1.1', '192.168.1.10']`). @return bool true if in range
[ "This", "method", "checks", "whether", "or", "not", "the", "request", "comes", "from", "a", "certain", "ip", "range" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/Url.php#L64-L79
train
silverstripe-archive/deploynaut
code/model/steps/LongRunningPipelineStep.php
LongRunningPipelineStep.isTimedOut
public function isTimedOut() { $age = $this->getAge(); $timeout = $this->getMaxDuration(); return $age && $timeout && ($age > $timeout); }
php
public function isTimedOut() { $age = $this->getAge(); $timeout = $this->getMaxDuration(); return $age && $timeout && ($age > $timeout); }
[ "public", "function", "isTimedOut", "(", ")", "{", "$", "age", "=", "$", "this", "->", "getAge", "(", ")", ";", "$", "timeout", "=", "$", "this", "->", "getMaxDuration", "(", ")", ";", "return", "$", "age", "&&", "$", "timeout", "&&", "(", "$", "...
Return true if this has timed out @return boolean
[ "Return", "true", "if", "this", "has", "timed", "out" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/LongRunningPipelineStep.php#L29-L33
train
silverstripe-archive/deploynaut
code/model/steps/LongRunningPipelineStep.php
LongRunningPipelineStep.getAge
public function getAge() { if($this->Started) { $started = intval($this->dbObject('Started')->Format('U')); $now = intval(SS_Datetime::now()->Format('U')); if($started && $now) return $now - $started; } return 0; }
php
public function getAge() { if($this->Started) { $started = intval($this->dbObject('Started')->Format('U')); $now = intval(SS_Datetime::now()->Format('U')); if($started && $now) return $now - $started; } return 0; }
[ "public", "function", "getAge", "(", ")", "{", "if", "(", "$", "this", "->", "Started", ")", "{", "$", "started", "=", "intval", "(", "$", "this", "->", "dbObject", "(", "'Started'", ")", "->", "Format", "(", "'U'", ")", ")", ";", "$", "now", "="...
Gets the age of this job in seconds, or 0 if not started @return int Age in seconds
[ "Gets", "the", "age", "of", "this", "job", "in", "seconds", "or", "0", "if", "not", "started" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/LongRunningPipelineStep.php#L40-L47
train
dmitriybelyy/yii2-cassandra-cql
phpcassa/Util/Clock.php
Clock.get_time
static public function get_time() { // By David Maciel (jdmaciel@gmail.com) list($microsecond, $second) = explode(" ", \microtime()); // remove '0.' from the beginning and trailing zeros(2) from the end $microsecond = substr($microsecond, 2, -2); return (int) $second . $microsecond; }
php
static public function get_time() { // By David Maciel (jdmaciel@gmail.com) list($microsecond, $second) = explode(" ", \microtime()); // remove '0.' from the beginning and trailing zeros(2) from the end $microsecond = substr($microsecond, 2, -2); return (int) $second . $microsecond; }
[ "static", "public", "function", "get_time", "(", ")", "{", "// By David Maciel (jdmaciel@gmail.com)", "list", "(", "$", "microsecond", ",", "$", "second", ")", "=", "explode", "(", "\" \"", ",", "\\", "microtime", "(", ")", ")", ";", "// remove '0.' from the beg...
Get a timestamp with microsecond precision
[ "Get", "a", "timestamp", "with", "microsecond", "precision" ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/Util/Clock.php#L14-L20
train
laravel-notification-channels/hipchat
src/HipChatChannel.php
HipChatChannel.sendMessage
protected function sendMessage($to, $message) { if ($message instanceof HipChatMessage) { return $this->hipChat->sendMessage($to, $message->toArray()); } if ($message instanceof HipChatFile) { return $this->hipChat->shareFile($to, $message->toArray()); } }
php
protected function sendMessage($to, $message) { if ($message instanceof HipChatMessage) { return $this->hipChat->sendMessage($to, $message->toArray()); } if ($message instanceof HipChatFile) { return $this->hipChat->shareFile($to, $message->toArray()); } }
[ "protected", "function", "sendMessage", "(", "$", "to", ",", "$", "message", ")", "{", "if", "(", "$", "message", "instanceof", "HipChatMessage", ")", "{", "return", "$", "this", "->", "hipChat", "->", "sendMessage", "(", "$", "to", ",", "$", "message", ...
Send the HipChat notification message. @param $to @param mixed $message @return \Psr\Http\Message\ResponseInterface
[ "Send", "the", "HipChat", "notification", "message", "." ]
c24bca85f7cf9f6804635aa206c961783e22e888
https://github.com/laravel-notification-channels/hipchat/blob/c24bca85f7cf9f6804635aa206c961783e22e888/src/HipChatChannel.php#L70-L79
train
laraplug/product-module
Services/CategoryRenderer.php
CategoryRenderer.generateHtmlFor
private function generateHtmlFor($items) { $this->category .= '<ol class="dd-list">'; foreach ($items as $item) { $this->category .= "<li class=\"dd-item\" data-id=\"{$item->id}\">"; $editLink = route('admin.product.category.edit', [$item->id]); $this->category .= <<<HTML <div class="btn-group" role="group" aria-label="Action buttons" style="display: inline"> <a class="btn btn-sm btn-info" style="float:left;" href="{$editLink}"> <i class="fa fa-pencil"></i> </a> <a class="btn btn-sm btn-danger jsDeleteCategoryItem" style="float:left; margin-right: 15px;" data-item-id="{$item->id}"> <i class="fa fa-times"></i> </a> </div> HTML; $this->category .= "<div class=\"dd-handle\">{$item->name}</div>"; if ($this->hasChildren($item)) { $this->generateHtmlFor($item->items); } $this->category .= '</li>'; } $this->category .= '</ol>'; }
php
private function generateHtmlFor($items) { $this->category .= '<ol class="dd-list">'; foreach ($items as $item) { $this->category .= "<li class=\"dd-item\" data-id=\"{$item->id}\">"; $editLink = route('admin.product.category.edit', [$item->id]); $this->category .= <<<HTML <div class="btn-group" role="group" aria-label="Action buttons" style="display: inline"> <a class="btn btn-sm btn-info" style="float:left;" href="{$editLink}"> <i class="fa fa-pencil"></i> </a> <a class="btn btn-sm btn-danger jsDeleteCategoryItem" style="float:left; margin-right: 15px;" data-item-id="{$item->id}"> <i class="fa fa-times"></i> </a> </div> HTML; $this->category .= "<div class=\"dd-handle\">{$item->name}</div>"; if ($this->hasChildren($item)) { $this->generateHtmlFor($item->items); } $this->category .= '</li>'; } $this->category .= '</ol>'; }
[ "private", "function", "generateHtmlFor", "(", "$", "items", ")", "{", "$", "this", "->", "category", ".=", "'<ol class=\"dd-list\">'", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "$", "this", "->", "category", ".=", "\"<li class=\\\"dd-i...
Generate the html for the given items @param $items
[ "Generate", "the", "html", "for", "the", "given", "items" ]
0a835482d2888a05bfe145e1b453926832185ae0
https://github.com/laraplug/product-module/blob/0a835482d2888a05bfe145e1b453926832185ae0/Services/CategoryRenderer.php#L37-L62
train
mcustiel/php-simple-request
src/FirstErrorRequestParser.php
FirstErrorRequestParser.parse
public function parse($request) { $object = clone $this->requestObject; foreach ($this->propertyParsers as $propertyParser) { try { $this->setProperty($request, $object, $propertyParser); } catch (InvalidValueException $e) { $propertyName = $propertyParser->getName(); $exception = new InvalidRequestException($propertyName . ': ' . $e->getMessage()); $exception->setErrors([$propertyName => $e->getMessage()]); throw $exception; } } return clone $object; }
php
public function parse($request) { $object = clone $this->requestObject; foreach ($this->propertyParsers as $propertyParser) { try { $this->setProperty($request, $object, $propertyParser); } catch (InvalidValueException $e) { $propertyName = $propertyParser->getName(); $exception = new InvalidRequestException($propertyName . ': ' . $e->getMessage()); $exception->setErrors([$propertyName => $e->getMessage()]); throw $exception; } } return clone $object; }
[ "public", "function", "parse", "(", "$", "request", ")", "{", "$", "object", "=", "clone", "$", "this", "->", "requestObject", ";", "foreach", "(", "$", "this", "->", "propertyParsers", "as", "$", "propertyParser", ")", "{", "try", "{", "$", "this", "-...
Parses a request and returns the object obtained. @param array|\stdClass $request @return object
[ "Parses", "a", "request", "and", "returns", "the", "object", "obtained", "." ]
4d0fc06092ccdff3ea488c67b394225c7243428f
https://github.com/mcustiel/php-simple-request/blob/4d0fc06092ccdff3ea488c67b394225c7243428f/src/FirstErrorRequestParser.php#L37-L52
train
asinfotrack/yii2-toolbox
widgets/Button.php
Button.createLabel
protected function createLabel() { $icon = empty($this->icon) ? '' : $this->createIcon($this->icon); if (empty($this->label) || strcmp($this->label, 'Button') === 0) { $label = ''; } else { $label = Html::tag('span', $this->encodeLabel ? Html::encode($this->label) : $this->label); } return $icon . $label; }
php
protected function createLabel() { $icon = empty($this->icon) ? '' : $this->createIcon($this->icon); if (empty($this->label) || strcmp($this->label, 'Button') === 0) { $label = ''; } else { $label = Html::tag('span', $this->encodeLabel ? Html::encode($this->label) : $this->label); } return $icon . $label; }
[ "protected", "function", "createLabel", "(", ")", "{", "$", "icon", "=", "empty", "(", "$", "this", "->", "icon", ")", "?", "''", ":", "$", "this", "->", "createIcon", "(", "$", "this", "->", "icon", ")", ";", "if", "(", "empty", "(", "$", "this"...
Creates the label for a button @return string the label
[ "Creates", "the", "label", "for", "a", "button" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/widgets/Button.php#L47-L57
train
asinfotrack/yii2-toolbox
components/Icon.php
Icon.create
public static function create($iconName, $options=[]) { if (isset(Yii::$app->{static::$COMPONENT_NAME}) && Yii::$app->{static::$COMPONENT_NAME} instanceof Icon) { $instance = Yii::$app->{static::$COMPONENT_NAME}; } else { $instance = new Icon(); } return $instance->createIcon($iconName, $options); }
php
public static function create($iconName, $options=[]) { if (isset(Yii::$app->{static::$COMPONENT_NAME}) && Yii::$app->{static::$COMPONENT_NAME} instanceof Icon) { $instance = Yii::$app->{static::$COMPONENT_NAME}; } else { $instance = new Icon(); } return $instance->createIcon($iconName, $options); }
[ "public", "static", "function", "create", "(", "$", "iconName", ",", "$", "options", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "Yii", "::", "$", "app", "->", "{", "static", "::", "$", "COMPONENT_NAME", "}", ")", "&&", "Yii", "::", "$", "a...
Shorthand method to create an icon. The method will use the singleton component instance if defined under `Yii::$app->icon` or a one time instance if not defined. @param string $iconName the desired icon name @param array $options options array for the icon @return string the icon code
[ "Shorthand", "method", "to", "create", "an", "icon", "." ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/components/Icon.php#L78-L87
train
asinfotrack/yii2-toolbox
components/Icon.php
Icon.replaceIconName
protected function replaceIconName($iconName) { return isset($this->replaceMap[$iconName]) ? $this->replaceMap[$iconName] : $iconName; }
php
protected function replaceIconName($iconName) { return isset($this->replaceMap[$iconName]) ? $this->replaceMap[$iconName] : $iconName; }
[ "protected", "function", "replaceIconName", "(", "$", "iconName", ")", "{", "return", "isset", "(", "$", "this", "->", "replaceMap", "[", "$", "iconName", "]", ")", "?", "$", "this", "->", "replaceMap", "[", "$", "iconName", "]", ":", "$", "iconName", ...
Replaces an old icon name with an alternative provided in the replaceMap of the class @param string $iconName the icon name to replace if necessary @return string the final icon name
[ "Replaces", "an", "old", "icon", "name", "with", "an", "alternative", "provided", "in", "the", "replaceMap", "of", "the", "class" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/components/Icon.php#L147-L150
train
johannes/JSMysqlndBundle
DataCollector/MysqlndDataCollector.php
MysqlndDataCollector.getMysqlInfo
public function getMysqlInfo() { if (!extension_loaded("mysqli")) { return "The mysqli extension is not available at all."; } ob_start(); $re = new \ReflectionExtension("mysqli"); $re->info(); $info = ob_get_contents(); ob_end_clean(); return str_replace('<h2><a name="module_mysqli">mysqli</a></h2>', '', $info); }
php
public function getMysqlInfo() { if (!extension_loaded("mysqli")) { return "The mysqli extension is not available at all."; } ob_start(); $re = new \ReflectionExtension("mysqli"); $re->info(); $info = ob_get_contents(); ob_end_clean(); return str_replace('<h2><a name="module_mysqli">mysqli</a></h2>', '', $info); }
[ "public", "function", "getMysqlInfo", "(", ")", "{", "if", "(", "!", "extension_loaded", "(", "\"mysqli\"", ")", ")", "{", "return", "\"The mysqli extension is not available at all.\"", ";", "}", "ob_start", "(", ")", ";", "$", "re", "=", "new", "\\", "Reflect...
Dump information about mysqli. This is used by the view in case no statistics were collected to ease the debugging @return string
[ "Dump", "information", "about", "mysqli", "." ]
f658cfdfa42b362fc709f6deba0667838dc3c290
https://github.com/johannes/JSMysqlndBundle/blob/f658cfdfa42b362fc709f6deba0667838dc3c290/DataCollector/MysqlndDataCollector.php#L93-L106
train
silverstripe-archive/deploynaut
code/api/nouns/APINoun.php
APINoun.message
protected function message($message, $statusCode) { $response = $this->getAPIResponse(array( 'message' => $message, 'statusCode' => $statusCode )); $response->setStatusCode($statusCode); return $response; }
php
protected function message($message, $statusCode) { $response = $this->getAPIResponse(array( 'message' => $message, 'statusCode' => $statusCode )); $response->setStatusCode($statusCode); return $response; }
[ "protected", "function", "message", "(", "$", "message", ",", "$", "statusCode", ")", "{", "$", "response", "=", "$", "this", "->", "getAPIResponse", "(", "array", "(", "'message'", "=>", "$", "message", ",", "'statusCode'", "=>", "$", "statusCode", ")", ...
Return a simple response with a message @param string $message @param int $statusCode @return SS_HTTPResponse
[ "Return", "a", "simple", "response", "with", "a", "message" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/api/nouns/APINoun.php#L121-L128
train
asinfotrack/yii2-toolbox
widgets/TabsWithMemory.php
TabsWithMemory.registerJs
protected function registerJs() { if (static::$JS_REGISTERED) return; JqueryAsset::register($this->getView()); BootstrapAsset::register($this->getView()); $js = new JsExpression(<<<JS var widgetClass = 'widget-memory-tabs'; var storageName = 'widget-memory-tabs'; var hasStorage = function() { var test = 'test'; try { {$this->storageType}.setItem(test, test); {$this->storageType}.removeItem(test); return true; } catch(e) { return false; } }; if (hasStorage) { var loadData = function() { var dataStr = {$this->storageType}.getItem(storageName); if (dataStr == null) return {}; return JSON.parse(dataStr); }; var saveData = function(dataObj) { dataStr = JSON.stringify(dataObj); {$this->storageType}.setItem(storageName, dataStr); }; var activateIndex = function(tabId, index) { var tab = $('#' + tabId); var items = tab.children('li'); if (items.length <= index) return; $('#' + tabId + ' li:eq(' + index + ') a').tab('show'); }; var getBaseUrlByAnchor = function(url) { var hashTagIndex = url.indexOf('#',0); if (hashTagIndex === -1) return null; return url.substring(0, hashTagIndex); }; var initIndexes = function() { var data = loadData(); var curUrl = window.location.href; if (data[curUrl] == null) { var baseUrl = getBaseUrlByAnchor(curUrl); if (baseUrl === null) { return; } else if (data[baseUrl] == null) { return; } curUrl = baseUrl; } var tabs = $('.' + widgetClass); tabs.each(function(i, el) { var tabId = $(this).attr('id'); if (tabId != null) { var index = data[curUrl][tabId]; activateIndex(tabId, index); } }); }; var setIndex = function(tabId, index) { var curUrl = window.location.href; var baseUrl = getBaseUrlByAnchor(curUrl); var data = loadData(); if(data[curUrl] == null) { if (baseUrl !== null && data[baseUrl] == null) { data[baseUrl] = {}; } else if (baseUrl === null) { data[curUrl] = {}; } else { curUrl = baseUrl; } } data[curUrl][tabId] = index; saveData(data); }; $('.widget-memory-tabs > li > a').mouseup(function(event) { var tabs = $(this).closest('.' + widgetClass); var selectedIndex = $(this).parent().prevAll().length; setIndex(tabs.attr('id'), selectedIndex); }); initIndexes(); } JS ); $this->view->registerJs($js); static::$JS_REGISTERED = true; }
php
protected function registerJs() { if (static::$JS_REGISTERED) return; JqueryAsset::register($this->getView()); BootstrapAsset::register($this->getView()); $js = new JsExpression(<<<JS var widgetClass = 'widget-memory-tabs'; var storageName = 'widget-memory-tabs'; var hasStorage = function() { var test = 'test'; try { {$this->storageType}.setItem(test, test); {$this->storageType}.removeItem(test); return true; } catch(e) { return false; } }; if (hasStorage) { var loadData = function() { var dataStr = {$this->storageType}.getItem(storageName); if (dataStr == null) return {}; return JSON.parse(dataStr); }; var saveData = function(dataObj) { dataStr = JSON.stringify(dataObj); {$this->storageType}.setItem(storageName, dataStr); }; var activateIndex = function(tabId, index) { var tab = $('#' + tabId); var items = tab.children('li'); if (items.length <= index) return; $('#' + tabId + ' li:eq(' + index + ') a').tab('show'); }; var getBaseUrlByAnchor = function(url) { var hashTagIndex = url.indexOf('#',0); if (hashTagIndex === -1) return null; return url.substring(0, hashTagIndex); }; var initIndexes = function() { var data = loadData(); var curUrl = window.location.href; if (data[curUrl] == null) { var baseUrl = getBaseUrlByAnchor(curUrl); if (baseUrl === null) { return; } else if (data[baseUrl] == null) { return; } curUrl = baseUrl; } var tabs = $('.' + widgetClass); tabs.each(function(i, el) { var tabId = $(this).attr('id'); if (tabId != null) { var index = data[curUrl][tabId]; activateIndex(tabId, index); } }); }; var setIndex = function(tabId, index) { var curUrl = window.location.href; var baseUrl = getBaseUrlByAnchor(curUrl); var data = loadData(); if(data[curUrl] == null) { if (baseUrl !== null && data[baseUrl] == null) { data[baseUrl] = {}; } else if (baseUrl === null) { data[curUrl] = {}; } else { curUrl = baseUrl; } } data[curUrl][tabId] = index; saveData(data); }; $('.widget-memory-tabs > li > a').mouseup(function(event) { var tabs = $(this).closest('.' + widgetClass); var selectedIndex = $(this).parent().prevAll().length; setIndex(tabs.attr('id'), selectedIndex); }); initIndexes(); } JS ); $this->view->registerJs($js); static::$JS_REGISTERED = true; }
[ "protected", "function", "registerJs", "(", ")", "{", "if", "(", "static", "::", "$", "JS_REGISTERED", ")", "return", ";", "JqueryAsset", "::", "register", "(", "$", "this", "->", "getView", "(", ")", ")", ";", "BootstrapAsset", "::", "register", "(", "$...
Registers the js code if necessary
[ "Registers", "the", "js", "code", "if", "necessary" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/widgets/TabsWithMemory.php#L46-L152
train
bav-php/bav
classes/dataBackend/pdo/StatementContainer.php
StatementContainer.prepare
public function prepare($sql) { if (! array_key_exists($sql, $this->statements)) { $this->statements[$sql] = $this->pdo->prepare($sql); } return $this->statements[$sql]; }
php
public function prepare($sql) { if (! array_key_exists($sql, $this->statements)) { $this->statements[$sql] = $this->pdo->prepare($sql); } return $this->statements[$sql]; }
[ "public", "function", "prepare", "(", "$", "sql", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "sql", ",", "$", "this", "->", "statements", ")", ")", "{", "$", "this", "->", "statements", "[", "$", "sql", "]", "=", "$", "this", "->", "...
Returns a PDOStatement This method will return the same object for equal queries. @param string $sql @return \PDOStatement @throws \PDOException
[ "Returns", "a", "PDOStatement" ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/dataBackend/pdo/StatementContainer.php#L42-L49
train
marcoazn89/booboo
src/BooBoo.php
BooBoo.setUp
final public static function setUp(\Psr\Log\LoggerInterface $logger = null, $traceAlwaysOn = false, \Closure $lastAction = null, $ignore = []) { ini_set('display_errors', 0); error_reporting(E_ALL - array_sum($ignore)); self::$ignore = $ignore; self::$defaultErrorPath = [ 'text' => __DIR__ . '/templates/text.php', 'html' => __DIR__ . '/templates/html.php', 'json' => __DIR__ . '/templates/json.php', 'xml' => __DIR__ . '/templates/xml.php' ]; self::$httpHandler = (new Response())->withTypeNegotiation()->withStatus(500); self::$logger = $logger; self::$trace = $traceAlwaysOn; self::$lastAction = $lastAction; set_exception_handler(['Exception\BooBoo','exceptionHandler']); set_error_handler(['Exception\BooBoo','errorHandler']); register_shutdown_function(['Exception\BooBoo','shutdownFunction']); }
php
final public static function setUp(\Psr\Log\LoggerInterface $logger = null, $traceAlwaysOn = false, \Closure $lastAction = null, $ignore = []) { ini_set('display_errors', 0); error_reporting(E_ALL - array_sum($ignore)); self::$ignore = $ignore; self::$defaultErrorPath = [ 'text' => __DIR__ . '/templates/text.php', 'html' => __DIR__ . '/templates/html.php', 'json' => __DIR__ . '/templates/json.php', 'xml' => __DIR__ . '/templates/xml.php' ]; self::$httpHandler = (new Response())->withTypeNegotiation()->withStatus(500); self::$logger = $logger; self::$trace = $traceAlwaysOn; self::$lastAction = $lastAction; set_exception_handler(['Exception\BooBoo','exceptionHandler']); set_error_handler(['Exception\BooBoo','errorHandler']); register_shutdown_function(['Exception\BooBoo','shutdownFunction']); }
[ "final", "public", "static", "function", "setUp", "(", "\\", "Psr", "\\", "Log", "\\", "LoggerInterface", "$", "logger", "=", "null", ",", "$", "traceAlwaysOn", "=", "false", ",", "\\", "Closure", "$", "lastAction", "=", "null", ",", "$", "ignore", "=", ...
Set up BooBoo. @param \Psr\Log\LoggerInterface|null $logger A psr3 compatible logger @param \Closure $lastAction Last action to run before script ends @param int $reportLevel Level of reporting. One can pass a bitmask here
[ "Set", "up", "BooBoo", "." ]
fdbd5b4bca2c2e3233ab716a4de11dbef7380528
https://github.com/marcoazn89/booboo/blob/fdbd5b4bca2c2e3233ab716a4de11dbef7380528/src/BooBoo.php#L110-L134
train
marcoazn89/booboo
src/BooBoo.php
BooBoo.getContents
public static function getContents($content, $response, $message, $data) { ob_start(); if (is_file($content)) { include($content); } else { echo $content; } $buffer = ob_get_contents(); ob_end_clean(); return $buffer; }
php
public static function getContents($content, $response, $message, $data) { ob_start(); if (is_file($content)) { include($content); } else { echo $content; } $buffer = ob_get_contents(); ob_end_clean(); return $buffer; }
[ "public", "static", "function", "getContents", "(", "$", "content", ",", "$", "response", ",", "$", "message", ",", "$", "data", ")", "{", "ob_start", "(", ")", ";", "if", "(", "is_file", "(", "$", "content", ")", ")", "{", "include", "(", "$", "co...
Get the contents of an error template @param String $file [Path of the file] @param mixed $data [Data to be used in the file. This may get deprecated] @return file
[ "Get", "the", "contents", "of", "an", "error", "template" ]
fdbd5b4bca2c2e3233ab716a4de11dbef7380528
https://github.com/marcoazn89/booboo/blob/fdbd5b4bca2c2e3233ab716a4de11dbef7380528/src/BooBoo.php#L227-L241
train
marcoazn89/booboo
src/BooBoo.php
BooBoo.exceptionHandler
final public static function exceptionHandler($exception) { $response = null; if (!$exception instanceof \Exception\BooBoo) { $class = get_class($exception); $msg = preg_replace("~[\r\n]~", ' ', $exception->getMessage()); $context = self::getContext(self::EXCEPTION, $class, $msg, $exception->getFile(), $exception->getLine(), $exception->getCode()); if (!empty(self::$logger)) { self::$logger->critical($class.": {$msg} in {$exception->getFile()} in line {$exception->getLine()}.", $context); } else { error_log(self::getExceptionMsg($class, $exception, self::$trace)); } if (!is_null(self::$lastAction)) { $fn = self::$lastAction; $fn(); } $response = self::$httpHandler->overwrite( self::getErrorTemplate(self::$httpHandler, self::$defaultErrorPath) ); } else { if (self::$booboo->alwaysLog || self::$alwaysLog) { $context = self::getContext(self::BOOBOO, self::$booboo->tag, $exception->getMessage(), $exception->getFile(), $exception->getLine()); $logMsg = self::getExceptionMsg(self::$booboo->tag, $exception, self::$booboo->trace); if (self::$booboo->httpHandler->getStatusCode() >= 500) { if (!empty(self::$logger)) { self::$logger->critical($logMsg, $context); } else { error_log($logMsg); } } else { if (!empty(self::$logger)) { self::$logger->warning($logMsg, $context); } else { error_log($logMsg); } } } if (!is_null(self::$lastAction)) { $fn = self::$lastAction; $fn(); } /*self::$booboo->httpHandler->overwrite( self::getErrorTemplate( self::$booboo->httpHandler, self::$booboo->templates, self::$booboo->displayMessage, self::$booboo->templateData ) )->send();*/ $response = self::$booboo->httpHandler->overwrite( self::getErrorTemplate( self::$booboo->httpHandler, self::$booboo->templates, self::$booboo->displayMessage, self::$booboo->templateData ) ); } if (self::$exit) { $response->send(); } else { return $response; } }
php
final public static function exceptionHandler($exception) { $response = null; if (!$exception instanceof \Exception\BooBoo) { $class = get_class($exception); $msg = preg_replace("~[\r\n]~", ' ', $exception->getMessage()); $context = self::getContext(self::EXCEPTION, $class, $msg, $exception->getFile(), $exception->getLine(), $exception->getCode()); if (!empty(self::$logger)) { self::$logger->critical($class.": {$msg} in {$exception->getFile()} in line {$exception->getLine()}.", $context); } else { error_log(self::getExceptionMsg($class, $exception, self::$trace)); } if (!is_null(self::$lastAction)) { $fn = self::$lastAction; $fn(); } $response = self::$httpHandler->overwrite( self::getErrorTemplate(self::$httpHandler, self::$defaultErrorPath) ); } else { if (self::$booboo->alwaysLog || self::$alwaysLog) { $context = self::getContext(self::BOOBOO, self::$booboo->tag, $exception->getMessage(), $exception->getFile(), $exception->getLine()); $logMsg = self::getExceptionMsg(self::$booboo->tag, $exception, self::$booboo->trace); if (self::$booboo->httpHandler->getStatusCode() >= 500) { if (!empty(self::$logger)) { self::$logger->critical($logMsg, $context); } else { error_log($logMsg); } } else { if (!empty(self::$logger)) { self::$logger->warning($logMsg, $context); } else { error_log($logMsg); } } } if (!is_null(self::$lastAction)) { $fn = self::$lastAction; $fn(); } /*self::$booboo->httpHandler->overwrite( self::getErrorTemplate( self::$booboo->httpHandler, self::$booboo->templates, self::$booboo->displayMessage, self::$booboo->templateData ) )->send();*/ $response = self::$booboo->httpHandler->overwrite( self::getErrorTemplate( self::$booboo->httpHandler, self::$booboo->templates, self::$booboo->displayMessage, self::$booboo->templateData ) ); } if (self::$exit) { $response->send(); } else { return $response; } }
[ "final", "public", "static", "function", "exceptionHandler", "(", "$", "exception", ")", "{", "$", "response", "=", "null", ";", "if", "(", "!", "$", "exception", "instanceof", "\\", "Exception", "\\", "BooBoo", ")", "{", "$", "class", "=", "get_class", ...
Override the exception handler
[ "Override", "the", "exception", "handler" ]
fdbd5b4bca2c2e3233ab716a4de11dbef7380528
https://github.com/marcoazn89/booboo/blob/fdbd5b4bca2c2e3233ab716a4de11dbef7380528/src/BooBoo.php#L335-L414
train
marcoazn89/booboo
src/BooBoo.php
BooBoo.shutdownFunction
final public static function shutdownFunction() { $last_error = error_get_last(); if (isset($last_error) && ($last_error['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING | E_RECOVERABLE_ERROR))) { self::errorHandler($last_error['type'], $last_error['message'], $last_error['file'], $last_error['line']); } }
php
final public static function shutdownFunction() { $last_error = error_get_last(); if (isset($last_error) && ($last_error['type'] & (E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING | E_RECOVERABLE_ERROR))) { self::errorHandler($last_error['type'], $last_error['message'], $last_error['file'], $last_error['line']); } }
[ "final", "public", "static", "function", "shutdownFunction", "(", ")", "{", "$", "last_error", "=", "error_get_last", "(", ")", ";", "if", "(", "isset", "(", "$", "last_error", ")", "&&", "(", "$", "last_error", "[", "'type'", "]", "&", "(", "E_ERROR", ...
Override the shut down function
[ "Override", "the", "shut", "down", "function" ]
fdbd5b4bca2c2e3233ab716a4de11dbef7380528
https://github.com/marcoazn89/booboo/blob/fdbd5b4bca2c2e3233ab716a4de11dbef7380528/src/BooBoo.php#L419-L427
train
marcoazn89/booboo
src/BooBoo.php
BooBoo.errorHandler
final public static function errorHandler($severity, $message, $filepath, $line) { $is_error = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR) & $severity) === $severity); $level = self::$levels[$severity]; $context = self::getContext(self::ERROR, $level, $message, $filepath, $line); if (!in_array($severity, array_merge([E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR], self::$ignore), true)) { error_log("{$level}: {$message} in {$filepath} in line {$line}"); if (!empty(self::$logger)) { self::$logger->error("{$level}: {$message} in {$filepath} in line {$line}", $context); } } if ($is_error) { if (!empty(self::$logger)) { self::$logger->critical("{$level}: {$message} in {$filepath} in line {$line}", $context); } if (!is_null(self::$lastAction)) { $fn = self::$lastAction; $fn(); } self::$httpHandler->overwrite(self::getErrorTemplate(self::$httpHandler, self::$defaultErrorPath))->withStatus(500)->send(); } }
php
final public static function errorHandler($severity, $message, $filepath, $line) { $is_error = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR) & $severity) === $severity); $level = self::$levels[$severity]; $context = self::getContext(self::ERROR, $level, $message, $filepath, $line); if (!in_array($severity, array_merge([E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR], self::$ignore), true)) { error_log("{$level}: {$message} in {$filepath} in line {$line}"); if (!empty(self::$logger)) { self::$logger->error("{$level}: {$message} in {$filepath} in line {$line}", $context); } } if ($is_error) { if (!empty(self::$logger)) { self::$logger->critical("{$level}: {$message} in {$filepath} in line {$line}", $context); } if (!is_null(self::$lastAction)) { $fn = self::$lastAction; $fn(); } self::$httpHandler->overwrite(self::getErrorTemplate(self::$httpHandler, self::$defaultErrorPath))->withStatus(500)->send(); } }
[ "final", "public", "static", "function", "errorHandler", "(", "$", "severity", ",", "$", "message", ",", "$", "filepath", ",", "$", "line", ")", "{", "$", "is_error", "=", "(", "(", "(", "E_ERROR", "|", "E_COMPILE_ERROR", "|", "E_CORE_ERROR", "|", "E_USE...
Override the errorHandler
[ "Override", "the", "errorHandler" ]
fdbd5b4bca2c2e3233ab716a4de11dbef7380528
https://github.com/marcoazn89/booboo/blob/fdbd5b4bca2c2e3233ab716a4de11dbef7380528/src/BooBoo.php#L432-L461
train
silverstripe-archive/deploynaut
code/control/EmailMessagingService.php
EmailMessagingService.sendIndividualMessages
protected function sendIndividualMessages($source, $message, $recipients, $from, $subject) { // Split recipients that are comma separated if(is_string($recipients) && stripos($recipients, ',')) { $recipients = explode(',', $recipients); return $this->sendIndividualMessages($source, $message, $recipients, $from, $subject); } // Iterate through arrays if(is_array($recipients) || $recipients instanceof SS_List) { foreach($recipients as $recipient) { $this->sendIndividualMessages($source, $message, $recipient, $from, $subject); } return true; } if($recipients) { $this->sendMessageTo($source, $from, $recipients, $subject, $message); return true; } // Can't send to empty recipient return false; }
php
protected function sendIndividualMessages($source, $message, $recipients, $from, $subject) { // Split recipients that are comma separated if(is_string($recipients) && stripos($recipients, ',')) { $recipients = explode(',', $recipients); return $this->sendIndividualMessages($source, $message, $recipients, $from, $subject); } // Iterate through arrays if(is_array($recipients) || $recipients instanceof SS_List) { foreach($recipients as $recipient) { $this->sendIndividualMessages($source, $message, $recipient, $from, $subject); } return true; } if($recipients) { $this->sendMessageTo($source, $from, $recipients, $subject, $message); return true; } // Can't send to empty recipient return false; }
[ "protected", "function", "sendIndividualMessages", "(", "$", "source", ",", "$", "message", ",", "$", "recipients", ",", "$", "from", ",", "$", "subject", ")", "{", "// Split recipients that are comma separated", "if", "(", "is_string", "(", "$", "recipients", "...
Separates recipients into individual users @param PipelineStep $source Source client step @param string $message Plain text message @param mixed $recipients Either a Member object, string, or array of strings or Member objects @param string $from @param string $subject @return boolean True if success
[ "Separates", "recipients", "into", "individual", "users" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/control/EmailMessagingService.php#L43-L65
train
silverstripe-archive/deploynaut
code/control/EmailMessagingService.php
EmailMessagingService.sendMessageTo
protected function sendMessageTo($source, $from, $to, $subject, $body) { if($to instanceof Member) $to = $to->Email; $this->sendViaEmail($source, $from, $to, $subject, $body); }
php
protected function sendMessageTo($source, $from, $to, $subject, $body) { if($to instanceof Member) $to = $to->Email; $this->sendViaEmail($source, $from, $to, $subject, $body); }
[ "protected", "function", "sendMessageTo", "(", "$", "source", ",", "$", "from", ",", "$", "to", ",", "$", "subject", ",", "$", "body", ")", "{", "if", "(", "$", "to", "instanceof", "Member", ")", "$", "to", "=", "$", "to", "->", "Email", ";", "$"...
Send an message to a single recipient @param PipelineStep $source Client step @param string $from @param string|Member $to @param string $subject @param string $body
[ "Send", "an", "message", "to", "a", "single", "recipient" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/control/EmailMessagingService.php#L77-L80
train
silverstripe-archive/deploynaut
code/control/EmailMessagingService.php
EmailMessagingService.sendViaEmail
protected function sendViaEmail($source, $from, $to, $subject, $body) { $email = new Email($from, $to, $subject, $body); if($source->getDryRun()) { $source->log("[Skipped] Sent message to $to (subject: $subject)"); } else { $email->sendPlain(); $source->log("Sent message to $to (subject: $subject)"); } }
php
protected function sendViaEmail($source, $from, $to, $subject, $body) { $email = new Email($from, $to, $subject, $body); if($source->getDryRun()) { $source->log("[Skipped] Sent message to $to (subject: $subject)"); } else { $email->sendPlain(); $source->log("Sent message to $to (subject: $subject)"); } }
[ "protected", "function", "sendViaEmail", "(", "$", "source", ",", "$", "from", ",", "$", "to", ",", "$", "subject", ",", "$", "body", ")", "{", "$", "email", "=", "new", "Email", "(", "$", "from", ",", "$", "to", ",", "$", "subject", ",", "$", ...
Send an email to a single recipient @param PipelineStep $source Client step @param string $from @param string|Member $to @param string $subject @param string $body
[ "Send", "an", "email", "to", "a", "single", "recipient" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/control/EmailMessagingService.php#L91-L99
train
bangerkuwranger/google-cloud-storage-php-wrapper
GoogleCloudStorage.php
GoogleCloudStorage.bucket_object_concatenate
public function bucket_object_concatenate( $obj1, $obj2, $final_name ) { $result = null; $sources = array( $obj1, $obj2 ); try { $this->object = $this->bucket->compose( $sources, $final_name ); if( null != $this->object ) { $this->get_object_acl(); } $result = $this->object; } catch( \Exception $e ) { $result = $e; $this->errors[$this->error_count] = $e->getServiceException()->getMessage(); $this->error_count++; } return $result; }
php
public function bucket_object_concatenate( $obj1, $obj2, $final_name ) { $result = null; $sources = array( $obj1, $obj2 ); try { $this->object = $this->bucket->compose( $sources, $final_name ); if( null != $this->object ) { $this->get_object_acl(); } $result = $this->object; } catch( \Exception $e ) { $result = $e; $this->errors[$this->error_count] = $e->getServiceException()->getMessage(); $this->error_count++; } return $result; }
[ "public", "function", "bucket_object_concatenate", "(", "$", "obj1", ",", "$", "obj2", ",", "$", "final_name", ")", "{", "$", "result", "=", "null", ";", "$", "sources", "=", "array", "(", "$", "obj1", ",", "$", "obj2", ")", ";", "try", "{", "$", "...
Bucket Object operations Operations are: Get all objects (filterable), concatenate 2 objects, upload data (simple), upload large data (resumable)
[ "Bucket", "Object", "operations" ]
167059243c1643db64aed8d0602c2790a3f19d41
https://github.com/bangerkuwranger/google-cloud-storage-php-wrapper/blob/167059243c1643db64aed8d0602c2790a3f19d41/GoogleCloudStorage.php#L81-L108
train
bangerkuwranger/google-cloud-storage-php-wrapper
GoogleCloudStorage.php
GoogleCloudStorage.bucket_acl_entity_add
public function bucket_acl_entity_add( $entity, $role ) { $result = null; try { $result = $this->bucket_acl->add( $entity, $role); } catch( \Exception $e ) { $result = $e; $this->errors[$this->error_count] = $e->getServiceException()->getMessage(); $this->error_count++; } return $result; }
php
public function bucket_acl_entity_add( $entity, $role ) { $result = null; try { $result = $this->bucket_acl->add( $entity, $role); } catch( \Exception $e ) { $result = $e; $this->errors[$this->error_count] = $e->getServiceException()->getMessage(); $this->error_count++; } return $result; }
[ "public", "function", "bucket_acl_entity_add", "(", "$", "entity", ",", "$", "role", ")", "{", "$", "result", "=", "null", ";", "try", "{", "$", "result", "=", "$", "this", "->", "bucket_acl", "->", "add", "(", "$", "entity", ",", "$", "role", ")", ...
Bucket ACL operations Operations to query and modify access to the bucket itself. Operations are: Query entity's role, update entity's role, add entity and role, remove entity and role
[ "Bucket", "ACL", "operations" ]
167059243c1643db64aed8d0602c2790a3f19d41
https://github.com/bangerkuwranger/google-cloud-storage-php-wrapper/blob/167059243c1643db64aed8d0602c2790a3f19d41/GoogleCloudStorage.php#L289-L306
train
silverstripe-archive/deploynaut
code/control/PipelineController.php
PipelineController.log
public function log() { $log = $this->pipeline->getLogger(); if($log->exists()) { $content = $log->content(); } else { $content = 'Waiting for action to start'; } $sendJSON = (strpos($this->request->getHeader('Accept'), 'application/json') !== false) || $this->request->getExtension() == 'json'; $content = preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\n", $content); if($sendJSON) { $this->response->addHeader("Content-type", "application/json"); return json_encode(array( 'status' => $this->pipeline->Status, 'content' => $content, )); } else { $this->response->addHeader("Content-type", "text/plain"); return $content; } }
php
public function log() { $log = $this->pipeline->getLogger(); if($log->exists()) { $content = $log->content(); } else { $content = 'Waiting for action to start'; } $sendJSON = (strpos($this->request->getHeader('Accept'), 'application/json') !== false) || $this->request->getExtension() == 'json'; $content = preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\n", $content); if($sendJSON) { $this->response->addHeader("Content-type", "application/json"); return json_encode(array( 'status' => $this->pipeline->Status, 'content' => $content, )); } else { $this->response->addHeader("Content-type", "text/plain"); return $content; } }
[ "public", "function", "log", "(", ")", "{", "$", "log", "=", "$", "this", "->", "pipeline", "->", "getLogger", "(", ")", ";", "if", "(", "$", "log", "->", "exists", "(", ")", ")", "{", "$", "content", "=", "$", "log", "->", "content", "(", ")",...
Get log for this pipeline
[ "Get", "log", "for", "this", "pipeline" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/control/PipelineController.php#L33-L56
train
silverstripe-archive/deploynaut
code/control/PipelineController.php
PipelineController.abort
public function abort() { if($this->pipeline->canAbort()) { $this->pipeline->markAborted(); } return $this->redirect($this->pipeline->Environment()->Link()); }
php
public function abort() { if($this->pipeline->canAbort()) { $this->pipeline->markAborted(); } return $this->redirect($this->pipeline->Environment()->Link()); }
[ "public", "function", "abort", "(", ")", "{", "if", "(", "$", "this", "->", "pipeline", "->", "canAbort", "(", ")", ")", "{", "$", "this", "->", "pipeline", "->", "markAborted", "(", ")", ";", "}", "return", "$", "this", "->", "redirect", "(", "$",...
Aborts the current pipeline
[ "Aborts", "the", "current", "pipeline" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/control/PipelineController.php#L61-L66
train
silverstripe-archive/deploynaut
code/control/PipelineController.php
PipelineController.step
public function step() { $action = $this->request->param('ID'); $step = $this->pipeline->CurrentStep(); // Check if the action is available on this step if($step && ($actions = $step->allowedActions()) && isset($actions[$action])) { // Execute this action, allowing it to override the httpresponse given $step->$action(); } return $this->redirect($this->pipeline->Environment()->Link()); }
php
public function step() { $action = $this->request->param('ID'); $step = $this->pipeline->CurrentStep(); // Check if the action is available on this step if($step && ($actions = $step->allowedActions()) && isset($actions[$action])) { // Execute this action, allowing it to override the httpresponse given $step->$action(); } return $this->redirect($this->pipeline->Environment()->Link()); }
[ "public", "function", "step", "(", ")", "{", "$", "action", "=", "$", "this", "->", "request", "->", "param", "(", "'ID'", ")", ";", "$", "step", "=", "$", "this", "->", "pipeline", "->", "CurrentStep", "(", ")", ";", "// Check if the action is available...
Perform an action on the current pipeline step
[ "Perform", "an", "action", "on", "the", "current", "pipeline", "step" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/control/PipelineController.php#L71-L81
train
stevenmaguire/laravel-cache
src/Services/EloquentCacheTrait.php
EloquentCacheTrait.cache
protected function cache($key, Builder $query, $verb = 'get') { $actualKey = $this->indexKey($key); $fetchData = function () use ($actualKey, $query, $verb) { $this->log('refreshing cache for '.get_class($this).' ('.$actualKey.')'); return $this->callQueryVerb($query, $verb); }; if ($this->enableCaching) { if ($this->cacheForMinutes > 0) { return CacheFacade::remember($actualKey, $this->cacheForMinutes, $fetchData); } return CacheFacade::rememberForever($actualKey, $fetchData); } return $fetchData(); }
php
protected function cache($key, Builder $query, $verb = 'get') { $actualKey = $this->indexKey($key); $fetchData = function () use ($actualKey, $query, $verb) { $this->log('refreshing cache for '.get_class($this).' ('.$actualKey.')'); return $this->callQueryVerb($query, $verb); }; if ($this->enableCaching) { if ($this->cacheForMinutes > 0) { return CacheFacade::remember($actualKey, $this->cacheForMinutes, $fetchData); } return CacheFacade::rememberForever($actualKey, $fetchData); } return $fetchData(); }
[ "protected", "function", "cache", "(", "$", "key", ",", "Builder", "$", "query", ",", "$", "verb", "=", "'get'", ")", "{", "$", "actualKey", "=", "$", "this", "->", "indexKey", "(", "$", "key", ")", ";", "$", "fetchData", "=", "function", "(", ")",...
Retrieve from cache if not empty, otherwise store results of query in cache @param string $key @param Builder $query @param string $verb Optional Builder verb to execute query @return Collection|Model|array|null
[ "Retrieve", "from", "cache", "if", "not", "empty", "otherwise", "store", "results", "of", "query", "in", "cache" ]
0bc4d52512e12246e805afa1653e4bbd512b9d50
https://github.com/stevenmaguire/laravel-cache/blob/0bc4d52512e12246e805afa1653e4bbd512b9d50/src/Services/EloquentCacheTrait.php#L48-L67
train
stevenmaguire/laravel-cache
src/Services/EloquentCacheTrait.php
EloquentCacheTrait.callQueryVerb
protected function callQueryVerb(Builder $query, $verbKey) { $verb = static::getVerbParts($verbKey); return call_user_func_array([$query, $verb[0]], $verb[1]); }
php
protected function callQueryVerb(Builder $query, $verbKey) { $verb = static::getVerbParts($verbKey); return call_user_func_array([$query, $verb[0]], $verb[1]); }
[ "protected", "function", "callQueryVerb", "(", "Builder", "$", "query", ",", "$", "verbKey", ")", "{", "$", "verb", "=", "static", "::", "getVerbParts", "(", "$", "verbKey", ")", ";", "return", "call_user_func_array", "(", "[", "$", "query", ",", "$", "v...
Attempts to deconstruct verb into method name and parameters to call on query builder object. @param Builder $query @param string $verbKey @return Collection|Model|array|null
[ "Attempts", "to", "deconstruct", "verb", "into", "method", "name", "and", "parameters", "to", "call", "on", "query", "builder", "object", "." ]
0bc4d52512e12246e805afa1653e4bbd512b9d50
https://github.com/stevenmaguire/laravel-cache/blob/0bc4d52512e12246e805afa1653e4bbd512b9d50/src/Services/EloquentCacheTrait.php#L78-L83
train
stevenmaguire/laravel-cache
src/Services/EloquentCacheTrait.php
EloquentCacheTrait.filterArrayValuesWithPattern
public static function filterArrayValuesWithPattern(array $values, $pattern) { return array_values( array_filter( array_map(function ($key) use ($pattern) { if ((bool) preg_match('/'.$pattern.'/', $key)) { return $key; } }, $values) ) ); }
php
public static function filterArrayValuesWithPattern(array $values, $pattern) { return array_values( array_filter( array_map(function ($key) use ($pattern) { if ((bool) preg_match('/'.$pattern.'/', $key)) { return $key; } }, $values) ) ); }
[ "public", "static", "function", "filterArrayValuesWithPattern", "(", "array", "$", "values", ",", "$", "pattern", ")", "{", "return", "array_values", "(", "array_filter", "(", "array_map", "(", "function", "(", "$", "key", ")", "use", "(", "$", "pattern", ")...
Iterates over given array to remove values that don't match a given regular expression pattern. @param array $values @param string $pattern @return array
[ "Iterates", "over", "given", "array", "to", "remove", "values", "that", "don", "t", "match", "a", "given", "regular", "expression", "pattern", "." ]
0bc4d52512e12246e805afa1653e4bbd512b9d50
https://github.com/stevenmaguire/laravel-cache/blob/0bc4d52512e12246e805afa1653e4bbd512b9d50/src/Services/EloquentCacheTrait.php#L94-L105
train
stevenmaguire/laravel-cache
src/Services/EloquentCacheTrait.php
EloquentCacheTrait.getByAttributeFromCollection
protected function getByAttributeFromCollection(Collection $collection, $attribute, $value = null) { return $collection->filter(function ($item) use ($attribute, $value) { if (isset($item->$attribute) && $value) { return $item->$attribute == $value; } return false; }); }
php
protected function getByAttributeFromCollection(Collection $collection, $attribute, $value = null) { return $collection->filter(function ($item) use ($attribute, $value) { if (isset($item->$attribute) && $value) { return $item->$attribute == $value; } return false; }); }
[ "protected", "function", "getByAttributeFromCollection", "(", "Collection", "$", "collection", ",", "$", "attribute", ",", "$", "value", "=", "null", ")", "{", "return", "$", "collection", "->", "filter", "(", "function", "(", "$", "item", ")", "use", "(", ...
Get items from collection whose properties match a given attribute and value @param Collection $collection @param string $attribute @param mixed $value @return Collection
[ "Get", "items", "from", "collection", "whose", "properties", "match", "a", "given", "attribute", "and", "value" ]
0bc4d52512e12246e805afa1653e4bbd512b9d50
https://github.com/stevenmaguire/laravel-cache/blob/0bc4d52512e12246e805afa1653e4bbd512b9d50/src/Services/EloquentCacheTrait.php#L116-L125
train
stevenmaguire/laravel-cache
src/Services/EloquentCacheTrait.php
EloquentCacheTrait.getServiceKeys
protected function getServiceKeys($pattern = null) { $keys = $this->getKeys(); $serviceKey = $this->getCacheKey(); $serviceKeys = isset($keys[$serviceKey]) ? $keys[$serviceKey] : []; if (!is_null($pattern)) { $serviceKeys = $this->filterArrayValuesWithPattern( $serviceKeys, $pattern ); } return $serviceKeys; }
php
protected function getServiceKeys($pattern = null) { $keys = $this->getKeys(); $serviceKey = $this->getCacheKey(); $serviceKeys = isset($keys[$serviceKey]) ? $keys[$serviceKey] : []; if (!is_null($pattern)) { $serviceKeys = $this->filterArrayValuesWithPattern( $serviceKeys, $pattern ); } return $serviceKeys; }
[ "protected", "function", "getServiceKeys", "(", "$", "pattern", "=", "null", ")", "{", "$", "keys", "=", "$", "this", "->", "getKeys", "(", ")", ";", "$", "serviceKey", "=", "$", "this", "->", "getCacheKey", "(", ")", ";", "$", "serviceKeys", "=", "i...
Get keys for concrete service @param string $pattern @return array
[ "Get", "keys", "for", "concrete", "service" ]
0bc4d52512e12246e805afa1653e4bbd512b9d50
https://github.com/stevenmaguire/laravel-cache/blob/0bc4d52512e12246e805afa1653e4bbd512b9d50/src/Services/EloquentCacheTrait.php#L166-L180
train
stevenmaguire/laravel-cache
src/Services/EloquentCacheTrait.php
EloquentCacheTrait.getVerbParts
public static function getVerbParts($verbKey) { $verbParts = explode(':', $verbKey); $verb = array_shift($verbParts); $params = []; if (!empty($verbParts)) { $params = array_map(function ($param) { $subParams = explode('|', $param); return count($subParams) > 1 ? $subParams : $subParams[0]; }, explode(',', array_shift($verbParts))); } return [$verb, $params]; }
php
public static function getVerbParts($verbKey) { $verbParts = explode(':', $verbKey); $verb = array_shift($verbParts); $params = []; if (!empty($verbParts)) { $params = array_map(function ($param) { $subParams = explode('|', $param); return count($subParams) > 1 ? $subParams : $subParams[0]; }, explode(',', array_shift($verbParts))); } return [$verb, $params]; }
[ "public", "static", "function", "getVerbParts", "(", "$", "verbKey", ")", "{", "$", "verbParts", "=", "explode", "(", "':'", ",", "$", "verbKey", ")", ";", "$", "verb", "=", "array_shift", "(", "$", "verbParts", ")", ";", "$", "params", "=", "[", "]"...
Attempts to deconstruct verb into method name and parameters. @param string $verbKey @return array
[ "Attempts", "to", "deconstruct", "verb", "into", "method", "name", "and", "parameters", "." ]
0bc4d52512e12246e805afa1653e4bbd512b9d50
https://github.com/stevenmaguire/laravel-cache/blob/0bc4d52512e12246e805afa1653e4bbd512b9d50/src/Services/EloquentCacheTrait.php#L189-L204
train
stevenmaguire/laravel-cache
src/Services/EloquentCacheTrait.php
EloquentCacheTrait.indexKey
protected function indexKey($key) { $keys = $this->getServiceKeys(); array_push($keys, $key); $keys = array_unique($keys); $this->setServiceKeys($keys); return $this->getFullKey($key); }
php
protected function indexKey($key) { $keys = $this->getServiceKeys(); array_push($keys, $key); $keys = array_unique($keys); $this->setServiceKeys($keys); return $this->getFullKey($key); }
[ "protected", "function", "indexKey", "(", "$", "key", ")", "{", "$", "keys", "=", "$", "this", "->", "getServiceKeys", "(", ")", ";", "array_push", "(", "$", "keys", ",", "$", "key", ")", ";", "$", "keys", "=", "array_unique", "(", "$", "keys", ")"...
Index a given key in the service key inventory @param string $key @return string
[ "Index", "a", "given", "key", "in", "the", "service", "key", "inventory" ]
0bc4d52512e12246e805afa1653e4bbd512b9d50
https://github.com/stevenmaguire/laravel-cache/blob/0bc4d52512e12246e805afa1653e4bbd512b9d50/src/Services/EloquentCacheTrait.php#L213-L224
train
stevenmaguire/laravel-cache
src/Services/EloquentCacheTrait.php
EloquentCacheTrait.setServiceKeys
protected function setServiceKeys($keys = []) { $allkeys = $this->getKeys(); $serviceKey = $this->getCacheKey(); $allkeys[$serviceKey] = $keys; CacheFacade::forever($this->cacheIndexKey, $allkeys); }
php
protected function setServiceKeys($keys = []) { $allkeys = $this->getKeys(); $serviceKey = $this->getCacheKey(); $allkeys[$serviceKey] = $keys; CacheFacade::forever($this->cacheIndexKey, $allkeys); }
[ "protected", "function", "setServiceKeys", "(", "$", "keys", "=", "[", "]", ")", "{", "$", "allkeys", "=", "$", "this", "->", "getKeys", "(", ")", ";", "$", "serviceKey", "=", "$", "this", "->", "getCacheKey", "(", ")", ";", "$", "allkeys", "[", "$...
Set keys for concrete service @param array $keys
[ "Set", "keys", "for", "concrete", "service" ]
0bc4d52512e12246e805afa1653e4bbd512b9d50
https://github.com/stevenmaguire/laravel-cache/blob/0bc4d52512e12246e805afa1653e4bbd512b9d50/src/Services/EloquentCacheTrait.php#L245-L253
train
stevenmaguire/laravel-cache
src/Services/EloquentCacheTrait.php
EloquentCacheTrait.flushCache
public function flushCache($pattern = null) { $keys = $this->getServiceKeys($pattern); array_map(function ($key) { $actualKey = $this->getFullKey($key); $this->log('flushing cache for '.get_class($this).' ('.$actualKey.')'); CacheFacade::forget($actualKey); }, $keys); }
php
public function flushCache($pattern = null) { $keys = $this->getServiceKeys($pattern); array_map(function ($key) { $actualKey = $this->getFullKey($key); $this->log('flushing cache for '.get_class($this).' ('.$actualKey.')'); CacheFacade::forget($actualKey); }, $keys); }
[ "public", "function", "flushCache", "(", "$", "pattern", "=", "null", ")", "{", "$", "keys", "=", "$", "this", "->", "getServiceKeys", "(", "$", "pattern", ")", ";", "array_map", "(", "function", "(", "$", "key", ")", "{", "$", "actualKey", "=", "$",...
Flush the cache for the concrete service @param string $pattern @return void
[ "Flush", "the", "cache", "for", "the", "concrete", "service" ]
0bc4d52512e12246e805afa1653e4bbd512b9d50
https://github.com/stevenmaguire/laravel-cache/blob/0bc4d52512e12246e805afa1653e4bbd512b9d50/src/Services/EloquentCacheTrait.php#L262-L272
train
swoft-cloud/swoft-http-message
src/Base/MessageTrait.php
MessageTrait.withoutHeader
public function withoutHeader($name) { $normalized = strtolower($name); if (!isset($this->headerNames[$normalized])) { return $this; } $name = $this->headerNames[$normalized]; $new = clone $this; unset($new->headers[$name], $new->headerNames[$normalized]); return $new; }
php
public function withoutHeader($name) { $normalized = strtolower($name); if (!isset($this->headerNames[$normalized])) { return $this; } $name = $this->headerNames[$normalized]; $new = clone $this; unset($new->headers[$name], $new->headerNames[$normalized]); return $new; }
[ "public", "function", "withoutHeader", "(", "$", "name", ")", "{", "$", "normalized", "=", "strtolower", "(", "$", "name", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "headerNames", "[", "$", "normalized", "]", ")", ")", "{", "return",...
Return an instance without the specified header. Header resolution MUST be done without case-sensitivity. This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that removes the named header. @param string $name Case-insensitive header field name to remove. @return static
[ "Return", "an", "instance", "without", "the", "specified", "header", ".", "Header", "resolution", "MUST", "be", "done", "without", "case", "-", "sensitivity", ".", "This", "method", "MUST", "be", "implemented", "in", "such", "a", "way", "as", "to", "retain",...
5cc36c68b24d8ff9bc75cd0f6c8492bcc452f73a
https://github.com/swoft-cloud/swoft-http-message/blob/5cc36c68b24d8ff9bc75cd0f6c8492bcc452f73a/src/Base/MessageTrait.php#L243-L257
train
asinfotrack/yii2-toolbox
widgets/grid/LinkColumn.php
LinkColumn.parseUrl
protected function parseUrl($model, $key, $index) { //catch no link if (!$this->hasLink()) return null; //prepare link if (is_array($this->link)) { return Url::to($this->link); } else if ($this->link instanceof \Closure) { return call_user_func($this->link, $model, $key, $index, $this); } else { return $this->link; } }
php
protected function parseUrl($model, $key, $index) { //catch no link if (!$this->hasLink()) return null; //prepare link if (is_array($this->link)) { return Url::to($this->link); } else if ($this->link instanceof \Closure) { return call_user_func($this->link, $model, $key, $index, $this); } else { return $this->link; } }
[ "protected", "function", "parseUrl", "(", "$", "model", ",", "$", "key", ",", "$", "index", ")", "{", "//catch no link", "if", "(", "!", "$", "this", "->", "hasLink", "(", ")", ")", "return", "null", ";", "//prepare link", "if", "(", "is_array", "(", ...
Parses the provided link-value into the final url for the link @param mixed $model the data model @param mixed $key the key associated with the data model @param integer $index the zero-based index of the data model among the models array returned by [[GridView::dataProvider]]. @return string|null final url string or null
[ "Parses", "the", "provided", "link", "-", "value", "into", "the", "final", "url", "for", "the", "link" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/widgets/grid/LinkColumn.php#L61-L74
train
webfactorybulgaria/laravel-shop
src/Traits/ShopCalculationsTrait.php
ShopCalculationsTrait.setCoupon
public function setCoupon($coupon) { if ($coupon->value > 0) { $this->coupon['value'] = $coupon->value; } elseif ($coupon->discount > 0) { $this->coupon['percent'] = $coupon->discount; } session(['coupon' => $coupon]); }
php
public function setCoupon($coupon) { if ($coupon->value > 0) { $this->coupon['value'] = $coupon->value; } elseif ($coupon->discount > 0) { $this->coupon['percent'] = $coupon->discount; } session(['coupon' => $coupon]); }
[ "public", "function", "setCoupon", "(", "$", "coupon", ")", "{", "if", "(", "$", "coupon", "->", "value", ">", "0", ")", "{", "$", "this", "->", "coupon", "[", "'value'", "]", "=", "$", "coupon", "->", "value", ";", "}", "elseif", "(", "$", "coup...
Used to set the discount coupon @return float
[ "Used", "to", "set", "the", "discount", "coupon" ]
9d191b7d17395bd875505bfbc0b1077dc6c87869
https://github.com/webfactorybulgaria/laravel-shop/blob/9d191b7d17395bd875505bfbc0b1077dc6c87869/src/Traits/ShopCalculationsTrait.php#L87-L96
train
webfactorybulgaria/laravel-shop
src/Traits/ShopCalculationsTrait.php
ShopCalculationsTrait.getTotalDiscountAttribute
public function getTotalDiscountAttribute() { if (empty($this->shopCalculations)) $this->runCalculations(); return round($this->shopCalculations->totalDiscount, 2); }
php
public function getTotalDiscountAttribute() { if (empty($this->shopCalculations)) $this->runCalculations(); return round($this->shopCalculations->totalDiscount, 2); }
[ "public", "function", "getTotalDiscountAttribute", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "shopCalculations", ")", ")", "$", "this", "->", "runCalculations", "(", ")", ";", "return", "round", "(", "$", "this", "->", "shopCalculations", ...
Returns total discount amount based on all coupons applied. @return float
[ "Returns", "total", "discount", "amount", "based", "on", "all", "coupons", "applied", "." ]
9d191b7d17395bd875505bfbc0b1077dc6c87869
https://github.com/webfactorybulgaria/laravel-shop/blob/9d191b7d17395bd875505bfbc0b1077dc6c87869/src/Traits/ShopCalculationsTrait.php#L103-L106
train
silverstripe-archive/deploynaut
code/model/steps/EmergencyRollbackStep.php
EmergencyRollbackStep.canTriggerRollback
public function canTriggerRollback($member = null) { return $this->Pipeline()->Environment()->canDeploy($member) || $this->Pipeline()->canAbort($member); }
php
public function canTriggerRollback($member = null) { return $this->Pipeline()->Environment()->canDeploy($member) || $this->Pipeline()->canAbort($member); }
[ "public", "function", "canTriggerRollback", "(", "$", "member", "=", "null", ")", "{", "return", "$", "this", "->", "Pipeline", "(", ")", "->", "Environment", "(", ")", "->", "canDeploy", "(", "$", "member", ")", "||", "$", "this", "->", "Pipeline", "(...
The user can do an emergency rollback if he could have deployed the code, or if he can abort pipelines. @param type $member @return boolean
[ "The", "user", "can", "do", "an", "emergency", "rollback", "if", "he", "could", "have", "deployed", "the", "code", "or", "if", "he", "can", "abort", "pipelines", "." ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/EmergencyRollbackStep.php#L69-L71
train
silverstripe-archive/deploynaut
code/model/steps/EmergencyRollbackStep.php
EmergencyRollbackStep.rollback
public function rollback() { // Check permission if(!$this->canTriggerRollback()) { return Security::permissionFailure( null, _t("EmergencyRollbackStep.DENYROLLBACKED", "You do not have permission to rollback this pipeline") ); } if ($this->Status == 'Queued') { $this->start(); } // Write down some metadata. $this->RolledBack = SS_Datetime::now()->Rfc2822(); $this->log(_t('EmergencyRollbackStep.BEINGROLLEDBACK', "{$this->Title} is being rolled back")); $this->ResponderID = Member::currentUserID(); $this->write(); // Rollback itself is handled by the Pipeline object. This step will be marked as failed. if ($this->Pipeline()->isRunning()) { $this->Pipeline()->markFailed(); return true; } else { return false; } }
php
public function rollback() { // Check permission if(!$this->canTriggerRollback()) { return Security::permissionFailure( null, _t("EmergencyRollbackStep.DENYROLLBACKED", "You do not have permission to rollback this pipeline") ); } if ($this->Status == 'Queued') { $this->start(); } // Write down some metadata. $this->RolledBack = SS_Datetime::now()->Rfc2822(); $this->log(_t('EmergencyRollbackStep.BEINGROLLEDBACK', "{$this->Title} is being rolled back")); $this->ResponderID = Member::currentUserID(); $this->write(); // Rollback itself is handled by the Pipeline object. This step will be marked as failed. if ($this->Pipeline()->isRunning()) { $this->Pipeline()->markFailed(); return true; } else { return false; } }
[ "public", "function", "rollback", "(", ")", "{", "// Check permission", "if", "(", "!", "$", "this", "->", "canTriggerRollback", "(", ")", ")", "{", "return", "Security", "::", "permissionFailure", "(", "null", ",", "_t", "(", "\"EmergencyRollbackStep.DENYROLLBA...
When a member wishes to rollback this pipeline @return boolean True if successful
[ "When", "a", "member", "wishes", "to", "rollback", "this", "pipeline" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/EmergencyRollbackStep.php#L78-L105
train
silverstripe-archive/deploynaut
code/model/steps/EmergencyRollbackStep.php
EmergencyRollbackStep.dismiss
public function dismiss() { // Check permission if(!$this->canTriggerRollback()) { return Security::permissionFailure( null, _t("EmergencyRollbackStep.DENYROLLBACKED", "You do not have permission to rollback this pipeline") ); } $this->log("Dismissing rollback window."); $this->finish(); return true; }
php
public function dismiss() { // Check permission if(!$this->canTriggerRollback()) { return Security::permissionFailure( null, _t("EmergencyRollbackStep.DENYROLLBACKED", "You do not have permission to rollback this pipeline") ); } $this->log("Dismissing rollback window."); $this->finish(); return true; }
[ "public", "function", "dismiss", "(", ")", "{", "// Check permission", "if", "(", "!", "$", "this", "->", "canTriggerRollback", "(", ")", ")", "{", "return", "Security", "::", "permissionFailure", "(", "null", ",", "_t", "(", "\"EmergencyRollbackStep.DENYROLLBAC...
Dismiss the rollback window
[ "Dismiss", "the", "rollback", "window" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/EmergencyRollbackStep.php#L110-L123
train
silverstripe-archive/deploynaut
code/model/steps/EmergencyRollbackStep.php
EmergencyRollbackStep.beginRollbackWindow
public function beginRollbackWindow() { $this->Status = 'Started'; if (!$this->Started) $this->Started = SS_Datetime::now()->Rfc2822(); $this->log(_t('EmergencyRollbackStep.BEGINROLLBACKWINDOW', "{$this->Title} is beginning a rollback window...")); $this->write(); // Message author that the deployment is complete $this->Pipeline()->sendMessage(Pipeline::ALERT_SUCCESS); return true; }
php
public function beginRollbackWindow() { $this->Status = 'Started'; if (!$this->Started) $this->Started = SS_Datetime::now()->Rfc2822(); $this->log(_t('EmergencyRollbackStep.BEGINROLLBACKWINDOW', "{$this->Title} is beginning a rollback window...")); $this->write(); // Message author that the deployment is complete $this->Pipeline()->sendMessage(Pipeline::ALERT_SUCCESS); return true; }
[ "public", "function", "beginRollbackWindow", "(", ")", "{", "$", "this", "->", "Status", "=", "'Started'", ";", "if", "(", "!", "$", "this", "->", "Started", ")", "$", "this", "->", "Started", "=", "SS_Datetime", "::", "now", "(", ")", "->", "Rfc2822",...
Initiate the a rollback window
[ "Initiate", "the", "a", "rollback", "window" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/EmergencyRollbackStep.php#L128-L137
train
mcustiel/php-simple-request
src/Util/ValidatorBuilder.php
ValidatorBuilder.getClassForType
final protected function getClassForType($type) { if (!class_exists($type)) { throw new ValidatorDoesNotExistException("Validator class {$type} does not exist"); } $validator = new $type; if (! ($validator instanceof ValidatorInterface)) { throw new ValidatorDoesNotExistException( "Validator class {$type} must implement " . ValidatorInterface::class ); } return $validator; }
php
final protected function getClassForType($type) { if (!class_exists($type)) { throw new ValidatorDoesNotExistException("Validator class {$type} does not exist"); } $validator = new $type; if (! ($validator instanceof ValidatorInterface)) { throw new ValidatorDoesNotExistException( "Validator class {$type} must implement " . ValidatorInterface::class ); } return $validator; }
[ "final", "protected", "function", "getClassForType", "(", "$", "type", ")", "{", "if", "(", "!", "class_exists", "(", "$", "type", ")", ")", "{", "throw", "new", "ValidatorDoesNotExistException", "(", "\"Validator class {$type} does not exist\"", ")", ";", "}", ...
This method is used from AnnotationToImplementationBuilder trait. It checks the existence of the Validator class and then checks it's of type ValidatorInterface. @param string $type Name of the class to instantiate. @throws \Mcustiel\SimpleRequest\Exception\ValidatorDoesNotExistException If class does not exist or is not of type ValidatorInterface. @return \Mcustiel\SimpleRequest\Interfaces\ValidatorInterface The created object.
[ "This", "method", "is", "used", "from", "AnnotationToImplementationBuilder", "trait", ".", "It", "checks", "the", "existence", "of", "the", "Validator", "class", "and", "then", "checks", "it", "s", "of", "type", "ValidatorInterface", "." ]
4d0fc06092ccdff3ea488c67b394225c7243428f
https://github.com/mcustiel/php-simple-request/blob/4d0fc06092ccdff3ea488c67b394225c7243428f/src/Util/ValidatorBuilder.php#L41-L54
train
tylercd100/monolog-sms
src/Handler/SMSHandler.php
SMSHandler.buildHeader
private function buildHeader($content) { $auth = $this->authToken; if ($this->authId) { $auth = "Basic " . base64_encode($this->authId.":".$this->authToken); } $header = $this->buildRequestUrl(); $header .= "Host: {$this->host}\r\n"; $header .= "Authorization: ".$auth."\r\n"; $header .= "Content-Type: application/json\r\n"; $header .= "Content-Length: " . strlen($content) . "\r\n"; $header .= "\r\n"; return $header; }
php
private function buildHeader($content) { $auth = $this->authToken; if ($this->authId) { $auth = "Basic " . base64_encode($this->authId.":".$this->authToken); } $header = $this->buildRequestUrl(); $header .= "Host: {$this->host}\r\n"; $header .= "Authorization: ".$auth."\r\n"; $header .= "Content-Type: application/json\r\n"; $header .= "Content-Length: " . strlen($content) . "\r\n"; $header .= "\r\n"; return $header; }
[ "private", "function", "buildHeader", "(", "$", "content", ")", "{", "$", "auth", "=", "$", "this", "->", "authToken", ";", "if", "(", "$", "this", "->", "authId", ")", "{", "$", "auth", "=", "\"Basic \"", ".", "base64_encode", "(", "$", "this", "->"...
Builds the header of the API call @param string $content @return string
[ "Builds", "the", "header", "of", "the", "API", "call" ]
66d2592b1ab795a7fe938ebe004c90fcfd31343a
https://github.com/tylercd100/monolog-sms/blob/66d2592b1ab795a7fe938ebe004c90fcfd31343a/src/Handler/SMSHandler.php#L111-L127
train
bav-php/bav
classes/dataBackend/update/AutomaticUpdatePlan.php
AutomaticUpdatePlan.perform
public function perform(DataBackend $backend) { $isNotice = $this->notice; $lock = new Lock(self::UPDATE_LOCK); $lock->nonblockingExecuteOnce( function () use ($backend, $isNotice) { $backend->update(); if ($isNotice) { trigger_error("bav's bank data was updated sucessfully.", E_USER_NOTICE); } } ); }
php
public function perform(DataBackend $backend) { $isNotice = $this->notice; $lock = new Lock(self::UPDATE_LOCK); $lock->nonblockingExecuteOnce( function () use ($backend, $isNotice) { $backend->update(); if ($isNotice) { trigger_error("bav's bank data was updated sucessfully.", E_USER_NOTICE); } } ); }
[ "public", "function", "perform", "(", "DataBackend", "$", "backend", ")", "{", "$", "isNotice", "=", "$", "this", "->", "notice", ";", "$", "lock", "=", "new", "Lock", "(", "self", "::", "UPDATE_LOCK", ")", ";", "$", "lock", "->", "nonblockingExecuteOnce...
Perform an update. If enabled (default) this method will send a E_USER_NOTICE about the update. @see setNotice()
[ "Perform", "an", "update", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/dataBackend/update/AutomaticUpdatePlan.php#L43-L56
train
OzanKurt/google-analytics
src/Traits/Filters/GoogleCommonFilters.php
GoogleCommonFilters.getUsersAndPageviewsOverTime
public function getUsersAndPageviewsOverTime($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions,ga:pageviews', ]); return $this->execute($parameters, $parseResult); }
php
public function getUsersAndPageviewsOverTime($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions,ga:pageviews', ]); return $this->execute($parameters, $parseResult); }
[ "public", "function", "getUsersAndPageviewsOverTime", "(", "$", "parameters", "=", "[", "]", ",", "$", "parseResult", "=", "true", ")", "{", "$", "this", "->", "setParams", "(", "[", "'metrics'", "=>", "'ga:sessions,ga:pageviews'", ",", "]", ")", ";", "retur...
Users and Pageviews Over Time. This query returns the total users and pageviews for the specified time period. Note that this query doesn't require any dimensions. @param array $parameters Parameters you may want to overwrite. @return array
[ "Users", "and", "Pageviews", "Over", "Time", "." ]
da5fecb6d9267f2fc5015a918c3aebda2c2f70a5
https://github.com/OzanKurt/google-analytics/blob/da5fecb6d9267f2fc5015a918c3aebda2c2f70a5/src/Traits/Filters/GoogleCommonFilters.php#L29-L36
train
OzanKurt/google-analytics
src/Traits/Filters/GoogleCommonFilters.php
GoogleCommonFilters.getMobileTraffic
public function getMobileTraffic($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions,ga:pageviews,ga:sessionDuration', 'dimensions' => 'ga:mobileDeviceInfo,ga:source', 'segment' => 'gaid::-14', ]); return $this->execute($parameters, $parseResult); }
php
public function getMobileTraffic($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions,ga:pageviews,ga:sessionDuration', 'dimensions' => 'ga:mobileDeviceInfo,ga:source', 'segment' => 'gaid::-14', ]); return $this->execute($parameters, $parseResult); }
[ "public", "function", "getMobileTraffic", "(", "$", "parameters", "=", "[", "]", ",", "$", "parseResult", "=", "true", ")", "{", "$", "this", "->", "setParams", "(", "[", "'metrics'", "=>", "'ga:sessions,ga:pageviews,ga:sessionDuration'", ",", "'dimensions'", "=...
Mobile Traffic. This query returns some information about sessions which occurred from mobile devices. Note that "Mobile Traffic" is defined using the default segment ID -14. @param array $parameters Parameters you may want to overwrite. @return array
[ "Mobile", "Traffic", "." ]
da5fecb6d9267f2fc5015a918c3aebda2c2f70a5
https://github.com/OzanKurt/google-analytics/blob/da5fecb6d9267f2fc5015a918c3aebda2c2f70a5/src/Traits/Filters/GoogleCommonFilters.php#L48-L57
train
OzanKurt/google-analytics
src/Traits/Filters/GoogleCommonFilters.php
GoogleCommonFilters.getRevenueGeneratingCampaigns
public function getRevenueGeneratingCampaigns($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions,ga:pageviews,ga:sessionDuration,ga:bounces', 'dimensions' => 'ga:source,ga:medium', 'segment' => 'dynamic::ga:transactions>1', ]); return $this->execute($parameters, $parseResult); }
php
public function getRevenueGeneratingCampaigns($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions,ga:pageviews,ga:sessionDuration,ga:bounces', 'dimensions' => 'ga:source,ga:medium', 'segment' => 'dynamic::ga:transactions>1', ]); return $this->execute($parameters, $parseResult); }
[ "public", "function", "getRevenueGeneratingCampaigns", "(", "$", "parameters", "=", "[", "]", ",", "$", "parseResult", "=", "true", ")", "{", "$", "this", "->", "setParams", "(", "[", "'metrics'", "=>", "'ga:sessions,ga:pageviews,ga:sessionDuration,ga:bounces'", ","...
Revenue Generating Campaigns. This query returns campaign and site usage data for campaigns that led to more than one purchase through your site. @param array $parameters Parameters you may want to overwrite. @return array
[ "Revenue", "Generating", "Campaigns", "." ]
da5fecb6d9267f2fc5015a918c3aebda2c2f70a5
https://github.com/OzanKurt/google-analytics/blob/da5fecb6d9267f2fc5015a918c3aebda2c2f70a5/src/Traits/Filters/GoogleCommonFilters.php#L69-L78
train
OzanKurt/google-analytics
src/Traits/Filters/GoogleCommonFilters.php
GoogleCommonFilters.getNewVsReturningSessions
public function getNewVsReturningSessions($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions', 'dimensions' => 'ga:userType', ]); return $this->execute($parameters, $parseResult); }
php
public function getNewVsReturningSessions($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions', 'dimensions' => 'ga:userType', ]); return $this->execute($parameters, $parseResult); }
[ "public", "function", "getNewVsReturningSessions", "(", "$", "parameters", "=", "[", "]", ",", "$", "parseResult", "=", "true", ")", "{", "$", "this", "->", "setParams", "(", "[", "'metrics'", "=>", "'ga:sessions'", ",", "'dimensions'", "=>", "'ga:userType'", ...
New vs Returning Sessions. This query returns the number of new sessions vs returning sessions. @param array $parameters Parameters you may want to overwrite. @return array
[ "New", "vs", "Returning", "Sessions", "." ]
da5fecb6d9267f2fc5015a918c3aebda2c2f70a5
https://github.com/OzanKurt/google-analytics/blob/da5fecb6d9267f2fc5015a918c3aebda2c2f70a5/src/Traits/Filters/GoogleCommonFilters.php#L95-L103
train
OzanKurt/google-analytics
src/Traits/Filters/GoogleCommonFilters.php
GoogleCommonFilters.getSessionsByCountry
public function getSessionsByCountry($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions', 'dimensions' => 'ga:country', 'sort' => '-ga:sessions', ]); return $this->execute($parameters, $parseResult); }
php
public function getSessionsByCountry($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions', 'dimensions' => 'ga:country', 'sort' => '-ga:sessions', ]); return $this->execute($parameters, $parseResult); }
[ "public", "function", "getSessionsByCountry", "(", "$", "parameters", "=", "[", "]", ",", "$", "parseResult", "=", "true", ")", "{", "$", "this", "->", "setParams", "(", "[", "'metrics'", "=>", "'ga:sessions'", ",", "'dimensions'", "=>", "'ga:country'", ",",...
Sessions by Country. This query returns a breakdown of your sessions by country, sorted by number of sessions. @param array $parameters Parameters you may want to overwrite. @return array
[ "Sessions", "by", "Country", "." ]
da5fecb6d9267f2fc5015a918c3aebda2c2f70a5
https://github.com/OzanKurt/google-analytics/blob/da5fecb6d9267f2fc5015a918c3aebda2c2f70a5/src/Traits/Filters/GoogleCommonFilters.php#L114-L123
train
OzanKurt/google-analytics
src/Traits/Filters/GoogleCommonFilters.php
GoogleCommonFilters.getBrowserAndOperatingSystem
public function getBrowserAndOperatingSystem($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions', 'dimensions' => 'ga:operatingSystem,ga:operatingSystemVersion,ga:browser,ga:browserVersion', ]); return $this->execute($parameters, $parseResult); }
php
public function getBrowserAndOperatingSystem($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions', 'dimensions' => 'ga:operatingSystem,ga:operatingSystemVersion,ga:browser,ga:browserVersion', ]); return $this->execute($parameters, $parseResult); }
[ "public", "function", "getBrowserAndOperatingSystem", "(", "$", "parameters", "=", "[", "]", ",", "$", "parseResult", "=", "true", ")", "{", "$", "this", "->", "setParams", "(", "[", "'metrics'", "=>", "'ga:sessions'", ",", "'dimensions'", "=>", "'ga:operating...
Browser and Operating System. This query returns a breakdown of sessions by the Operating System, web browser, and browser version used. @param array $parameters Parameters you may want to overwrite. @return array
[ "Browser", "and", "Operating", "System", "." ]
da5fecb6d9267f2fc5015a918c3aebda2c2f70a5
https://github.com/OzanKurt/google-analytics/blob/da5fecb6d9267f2fc5015a918c3aebda2c2f70a5/src/Traits/Filters/GoogleCommonFilters.php#L134-L142
train
OzanKurt/google-analytics
src/Traits/Filters/GoogleCommonFilters.php
GoogleCommonFilters.getTimeOnSite
public function getTimeOnSite($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions', 'dimensions' => 'ga:operatingSystem,ga:operatingSystemVersion,ga:browser,ga:browserVersion', ]); return $this->execute($parameters, $parseResult); }
php
public function getTimeOnSite($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions', 'dimensions' => 'ga:operatingSystem,ga:operatingSystemVersion,ga:browser,ga:browserVersion', ]); return $this->execute($parameters, $parseResult); }
[ "public", "function", "getTimeOnSite", "(", "$", "parameters", "=", "[", "]", ",", "$", "parseResult", "=", "true", ")", "{", "$", "this", "->", "setParams", "(", "[", "'metrics'", "=>", "'ga:sessions'", ",", "'dimensions'", "=>", "'ga:operatingSystem,ga:opera...
Time on Site. This query returns the number of sessions and total time on site, which can be used to calculate average time on site. @param array $parameters Parameters you may want to overwrite. @return array
[ "Time", "on", "Site", "." ]
da5fecb6d9267f2fc5015a918c3aebda2c2f70a5
https://github.com/OzanKurt/google-analytics/blob/da5fecb6d9267f2fc5015a918c3aebda2c2f70a5/src/Traits/Filters/GoogleCommonFilters.php#L153-L161
train
OzanKurt/google-analytics
src/Traits/Filters/GoogleCommonFilters.php
GoogleCommonFilters.getAllTrafficSources_Usage
public function getAllTrafficSources_Usage($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions,ga:pageviews,ga:sessionDuration,ga:exits', 'dimensions' => 'ga:source,ga:medium', 'sort' => '-ga:sessions', ]); return $this->execute($parameters, $parseResult); }
php
public function getAllTrafficSources_Usage($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions,ga:pageviews,ga:sessionDuration,ga:exits', 'dimensions' => 'ga:source,ga:medium', 'sort' => '-ga:sessions', ]); return $this->execute($parameters, $parseResult); }
[ "public", "function", "getAllTrafficSources_Usage", "(", "$", "parameters", "=", "[", "]", ",", "$", "parseResult", "=", "true", ")", "{", "$", "this", "->", "setParams", "(", "[", "'metrics'", "=>", "'ga:sessions,ga:pageviews,ga:sessionDuration,ga:exits'", ",", "...
All Traffic Sources - Usage. This query returns the site usage data broken down by source and medium, sorted by sessions in descending order. @param array $parameters Parameters you may want to overwrite. @return array
[ "All", "Traffic", "Sources", "-", "Usage", "." ]
da5fecb6d9267f2fc5015a918c3aebda2c2f70a5
https://github.com/OzanKurt/google-analytics/blob/da5fecb6d9267f2fc5015a918c3aebda2c2f70a5/src/Traits/Filters/GoogleCommonFilters.php#L178-L187
train
OzanKurt/google-analytics
src/Traits/Filters/GoogleCommonFilters.php
GoogleCommonFilters.getAllTrafficSources_Goals
public function getAllTrafficSources_Goals($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions,ga:goal1Starts,ga:goal1Completions,ga:goal1Value,ga:goalStartsAll,ga:goalCompletionsAll,ga:goalValueAll', 'dimensions' => 'ga:source,ga:medium', 'sort' => '-ga:goalCompletionsAll', ]); return $this->execute($parameters, $parseResult); }
php
public function getAllTrafficSources_Goals($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:sessions,ga:goal1Starts,ga:goal1Completions,ga:goal1Value,ga:goalStartsAll,ga:goalCompletionsAll,ga:goalValueAll', 'dimensions' => 'ga:source,ga:medium', 'sort' => '-ga:goalCompletionsAll', ]); return $this->execute($parameters, $parseResult); }
[ "public", "function", "getAllTrafficSources_Goals", "(", "$", "parameters", "=", "[", "]", ",", "$", "parseResult", "=", "true", ")", "{", "$", "this", "->", "setParams", "(", "[", "'metrics'", "=>", "'ga:sessions,ga:goal1Starts,ga:goal1Completions,ga:goal1Value,ga:go...
All Traffic Sources - Goals. This query returns data for the first and all goals defined, sorted by total goal completions in descending order. @param array $parameters Parameters you may want to overwrite. @return array
[ "All", "Traffic", "Sources", "-", "Goals", "." ]
da5fecb6d9267f2fc5015a918c3aebda2c2f70a5
https://github.com/OzanKurt/google-analytics/blob/da5fecb6d9267f2fc5015a918c3aebda2c2f70a5/src/Traits/Filters/GoogleCommonFilters.php#L198-L207
train