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
ua1-labs/firesql
Fire/Sql/Collection.php
Collection.delete
public function delete($id) { $delete = Statement::get( 'DELETE_OBJECT_INDEX', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($id) ] ); $delete .= Statement::get( 'DELETE_OBJECT', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($id) ] ); $this->_connector->exec($delete); }
php
public function delete($id) { $delete = Statement::get( 'DELETE_OBJECT_INDEX', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($id) ] ); $delete .= Statement::get( 'DELETE_OBJECT', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($id) ] ); $this->_connector->exec($delete); }
[ "public", "function", "delete", "(", "$", "id", ")", "{", "$", "delete", "=", "Statement", "::", "get", "(", "'DELETE_OBJECT_INDEX'", ",", "[", "'@collection'", "=>", "$", "this", "->", "_name", ",", "'@id'", "=>", "$", "this", "->", "_connector", "->", ...
Deletes an object from the database. @param string $id The ID of the object you want to delete @return void
[ "Deletes", "an", "object", "from", "the", "database", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L129-L147
train
ua1-labs/firesql
Fire/Sql/Collection.php
Collection.count
public function count($filter = null) { if (is_null($filter)) { return $this->_countObjectsInCollection(); } else if (is_string($filter)) { json_decode($filter); $isJson = (json_last_error() === JSON_ERROR_NONE) ? true :false; if ($isJson) { $filter = new Filter($filter); return $this->_countObjectsInCollectionByFilter($filter); } } else if (is_object($filter) && $filter instanceof Filter) { return $this->_countObjectsInCollectionByFilter($filter); } return 0; }
php
public function count($filter = null) { if (is_null($filter)) { return $this->_countObjectsInCollection(); } else if (is_string($filter)) { json_decode($filter); $isJson = (json_last_error() === JSON_ERROR_NONE) ? true :false; if ($isJson) { $filter = new Filter($filter); return $this->_countObjectsInCollectionByFilter($filter); } } else if (is_object($filter) && $filter instanceof Filter) { return $this->_countObjectsInCollectionByFilter($filter); } return 0; }
[ "public", "function", "count", "(", "$", "filter", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "filter", ")", ")", "{", "return", "$", "this", "->", "_countObjectsInCollection", "(", ")", ";", "}", "else", "if", "(", "is_string", "(", "$",...
Returns the total number of objects in a collection. @param string|null|Fire\Sql\Filter $filter @return int
[ "Returns", "the", "total", "number", "of", "objects", "in", "a", "collection", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L154-L169
train
ua1-labs/firesql
Fire/Sql/Collection.php
Collection._commitObject
private function _commitObject($id, $revision) { $update = ''; //if version tracking is disabled, delete previous revisions of the object if (!$this->_options->versionTracking) { $update .= Statement::get( 'DELETE_OBJECT_EXCEPT_REVISION', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($id), '@revision' => $this->_connector->quote($revision) ] ); } $update .= Statement::get( 'UPDATE_OBJECT_TO_COMMITTED', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($id), '@revision' => $this->_connector->quote($revision) ] ); $this->_connector->exec($update); }
php
private function _commitObject($id, $revision) { $update = ''; //if version tracking is disabled, delete previous revisions of the object if (!$this->_options->versionTracking) { $update .= Statement::get( 'DELETE_OBJECT_EXCEPT_REVISION', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($id), '@revision' => $this->_connector->quote($revision) ] ); } $update .= Statement::get( 'UPDATE_OBJECT_TO_COMMITTED', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($id), '@revision' => $this->_connector->quote($revision) ] ); $this->_connector->exec($update); }
[ "private", "function", "_commitObject", "(", "$", "id", ",", "$", "revision", ")", "{", "$", "update", "=", "''", ";", "//if version tracking is disabled, delete previous revisions of the object", "if", "(", "!", "$", "this", "->", "_options", "->", "versionTracking...
After an object has been fully indexed, the object needs to be updated to indicated it is ready to be used within the collection. @param string $id @param int $revision @return void
[ "After", "an", "object", "has", "been", "fully", "indexed", "the", "object", "needs", "to", "be", "updated", "to", "indicated", "it", "is", "ready", "to", "be", "used", "within", "the", "collection", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L178-L202
train
ua1-labs/firesql
Fire/Sql/Collection.php
Collection._generateAlphaToken
private function _generateAlphaToken() { $timestamp = strtotime($this->_generateTimestamp()); $characters = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'); shuffle($characters); $randomString = ''; foreach (str_split((string) $timestamp) as $num) { $randomString .= $characters[$num]; } return $randomString; }
php
private function _generateAlphaToken() { $timestamp = strtotime($this->_generateTimestamp()); $characters = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'); shuffle($characters); $randomString = ''; foreach (str_split((string) $timestamp) as $num) { $randomString .= $characters[$num]; } return $randomString; }
[ "private", "function", "_generateAlphaToken", "(", ")", "{", "$", "timestamp", "=", "strtotime", "(", "$", "this", "->", "_generateTimestamp", "(", ")", ")", ";", "$", "characters", "=", "str_split", "(", "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'", ")"...
This method is used to dynamically create tokens to help manage temporary tables within SQL queries. @return string A randomly genereated token
[ "This", "method", "is", "used", "to", "dynamically", "create", "tokens", "to", "help", "manage", "temporary", "tables", "within", "SQL", "queries", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L209-L219
train
ua1-labs/firesql
Fire/Sql/Collection.php
Collection._generateTimestamp
private function _generateTimestamp() { $time = microtime(true); $micro = sprintf('%06d', ($time - floor($time)) * 1000000); $date = new DateTime(date('Y-m-d H:i:s.' . $micro, $time)); return $date->format("Y-m-d H:i:s.u"); }
php
private function _generateTimestamp() { $time = microtime(true); $micro = sprintf('%06d', ($time - floor($time)) * 1000000); $date = new DateTime(date('Y-m-d H:i:s.' . $micro, $time)); return $date->format("Y-m-d H:i:s.u"); }
[ "private", "function", "_generateTimestamp", "(", ")", "{", "$", "time", "=", "microtime", "(", "true", ")", ";", "$", "micro", "=", "sprintf", "(", "'%06d'", ",", "(", "$", "time", "-", "floor", "(", "$", "time", ")", ")", "*", "1000000", ")", ";"...
Generates a timestamp with micro seconds. @return string
[ "Generates", "a", "timestamp", "with", "micro", "seconds", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L234-L240
train
ua1-labs/firesql
Fire/Sql/Collection.php
Collection._generateUniqueId
private function _generateUniqueId() { $rand = uniqid(rand(10, 99)); $time = microtime(true); $micro = sprintf('%06d', ($time - floor($time)) * 1000000); $date = new DateTime(date('Y-m-d H:i:s.' . $micro, $time)); return sha1($date->format('YmdHisu')); }
php
private function _generateUniqueId() { $rand = uniqid(rand(10, 99)); $time = microtime(true); $micro = sprintf('%06d', ($time - floor($time)) * 1000000); $date = new DateTime(date('Y-m-d H:i:s.' . $micro, $time)); return sha1($date->format('YmdHisu')); }
[ "private", "function", "_generateUniqueId", "(", ")", "{", "$", "rand", "=", "uniqid", "(", "rand", "(", "10", ",", "99", ")", ")", ";", "$", "time", "=", "microtime", "(", "true", ")", ";", "$", "micro", "=", "sprintf", "(", "'%06d'", ",", "(", ...
Generates a unique id based on a timestamp so that it is truely unique. @return string
[ "Generates", "a", "unique", "id", "based", "on", "a", "timestamp", "so", "that", "it", "is", "truely", "unique", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L246-L253
train
ua1-labs/firesql
Fire/Sql/Collection.php
Collection._getObject
private function _getObject($id, $revision = null) { if ($revision === null) { $select = Statement::get( 'GET_CURRENT_OBJECT', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($id) ] ); $record = $this->_connector->query($select)->fetch(); if ($record) { return json_decode($record['obj']); } } return null; }
php
private function _getObject($id, $revision = null) { if ($revision === null) { $select = Statement::get( 'GET_CURRENT_OBJECT', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($id) ] ); $record = $this->_connector->query($select)->fetch(); if ($record) { return json_decode($record['obj']); } } return null; }
[ "private", "function", "_getObject", "(", "$", "id", ",", "$", "revision", "=", "null", ")", "{", "if", "(", "$", "revision", "===", "null", ")", "{", "$", "select", "=", "Statement", "::", "get", "(", "'GET_CURRENT_OBJECT'", ",", "[", "'@collection'", ...
Returns an object in the collection. If the revision isn't provided, the latest revision of the object will be returned. @param string $id @param int $revision @return object|null
[ "Returns", "an", "object", "in", "the", "collection", ".", "If", "the", "revision", "isn", "t", "provided", "the", "latest", "revision", "of", "the", "object", "will", "be", "returned", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L262-L278
train
ua1-labs/firesql
Fire/Sql/Collection.php
Collection._getObjectOrigin
private function _getObjectOrigin($id) { $select = Statement::get( 'GET_OBJECT_ORIGIN_DATE', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($id) ] ); $record = $this->_connector->query($select)->fetch(); return ($record) ? $record['updated'] : null; }
php
private function _getObjectOrigin($id) { $select = Statement::get( 'GET_OBJECT_ORIGIN_DATE', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($id) ] ); $record = $this->_connector->query($select)->fetch(); return ($record) ? $record['updated'] : null; }
[ "private", "function", "_getObjectOrigin", "(", "$", "id", ")", "{", "$", "select", "=", "Statement", "::", "get", "(", "'GET_OBJECT_ORIGIN_DATE'", ",", "[", "'@collection'", "=>", "$", "this", "->", "_name", ",", "'@id'", "=>", "$", "this", "->", "_connec...
Returns an object's origin timestamp date. @param string $id @return string|null
[ "Returns", "an", "object", "s", "origin", "timestamp", "date", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L285-L296
train
ua1-labs/firesql
Fire/Sql/Collection.php
Collection._getObjectsByFilter
private function _getObjectsByFilter(Filter $filterQuery) { $records = []; $props = []; $filters = []; foreach ($filterQuery->getComparisons() as $comparison) { $props[] = $comparison->prop; if ($comparison->expression && $comparison->comparison && $comparison->prop) { $expression = ($comparison->expression !== 'WHERE') ? $comparison->expression . ' ' : ''; $prop = is_int($comparison->val) ? 'CAST(' . $comparison->prop . ' AS INT)' : $comparison->prop; $compare = $comparison->comparison; $value = (!isset($comparison->val) || is_null($comparison->val)) ? 'NULL' : $comparison->val; $filters[] = $expression . $prop . ' ' . $compare . ' \'' . $value . '\''; } } $props = array_unique($props); $joins = []; foreach ($props as $prop) { $standardFields = [ '__id', '__type', '__collection', '__origin' ]; if (!in_array($prop, $standardFields)) { $asTbl = $this->_generateAlphaToken(); $joins[] = 'JOIN(' . 'SELECT id, val AS ' . $prop . ' ' . 'FROM ' . $this->_name . '__index ' . 'WHERE prop = \'' . $prop . '\'' . ') AS ' . $asTbl . ' ' . 'ON A.id = ' . $asTbl . '.id'; } } $select = Statement::get( 'GET_OBJECTS_BY_FILTER', [ '@collection' => $this->_name, '@columns' => (count($props) > 0) ? ', ' . implode($props, ', ') : '', '@joinColumns' => (count($joins) > 0) ? implode($joins, ' ') . ' ' : '', '@type' => $this->_connector->quote($filterQuery->getIndexType()), '@filters' => ($filters) ? 'AND (' . implode($filters, ' ') . ') ' : '', '@order' => $filterQuery->getOrderBy(), '@reverse' => ($filterQuery->getReverse()) ? 'DESC' : 'ASC', '@limit' => $filterQuery->getLength(), '@offset' => $filterQuery->getOffset() ] ); $result = $this->_connector->query($select); if ($result) { $records = $result->fetchAll(); } return ($records) ? array_map([$this, '_mapObjectIds'], $records) : []; }
php
private function _getObjectsByFilter(Filter $filterQuery) { $records = []; $props = []; $filters = []; foreach ($filterQuery->getComparisons() as $comparison) { $props[] = $comparison->prop; if ($comparison->expression && $comparison->comparison && $comparison->prop) { $expression = ($comparison->expression !== 'WHERE') ? $comparison->expression . ' ' : ''; $prop = is_int($comparison->val) ? 'CAST(' . $comparison->prop . ' AS INT)' : $comparison->prop; $compare = $comparison->comparison; $value = (!isset($comparison->val) || is_null($comparison->val)) ? 'NULL' : $comparison->val; $filters[] = $expression . $prop . ' ' . $compare . ' \'' . $value . '\''; } } $props = array_unique($props); $joins = []; foreach ($props as $prop) { $standardFields = [ '__id', '__type', '__collection', '__origin' ]; if (!in_array($prop, $standardFields)) { $asTbl = $this->_generateAlphaToken(); $joins[] = 'JOIN(' . 'SELECT id, val AS ' . $prop . ' ' . 'FROM ' . $this->_name . '__index ' . 'WHERE prop = \'' . $prop . '\'' . ') AS ' . $asTbl . ' ' . 'ON A.id = ' . $asTbl . '.id'; } } $select = Statement::get( 'GET_OBJECTS_BY_FILTER', [ '@collection' => $this->_name, '@columns' => (count($props) > 0) ? ', ' . implode($props, ', ') : '', '@joinColumns' => (count($joins) > 0) ? implode($joins, ' ') . ' ' : '', '@type' => $this->_connector->quote($filterQuery->getIndexType()), '@filters' => ($filters) ? 'AND (' . implode($filters, ' ') . ') ' : '', '@order' => $filterQuery->getOrderBy(), '@reverse' => ($filterQuery->getReverse()) ? 'DESC' : 'ASC', '@limit' => $filterQuery->getLength(), '@offset' => $filterQuery->getOffset() ] ); $result = $this->_connector->query($select); if ($result) { $records = $result->fetchAll(); } return ($records) ? array_map([$this, '_mapObjectIds'], $records) : []; }
[ "private", "function", "_getObjectsByFilter", "(", "Filter", "$", "filterQuery", ")", "{", "$", "records", "=", "[", "]", ";", "$", "props", "=", "[", "]", ";", "$", "filters", "=", "[", "]", ";", "foreach", "(", "$", "filterQuery", "->", "getCompariso...
Returns a collection of objects that matches a filter. @param Filter $filterQuery @return array
[ "Returns", "a", "collection", "of", "objects", "that", "matches", "a", "filter", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L303-L361
train
ua1-labs/firesql
Fire/Sql/Collection.php
Collection._isValueIndexable
public function _isValueIndexable($value) { return ( is_string($value) || is_null($value) || is_bool($value) || is_integer($value) ); }
php
public function _isValueIndexable($value) { return ( is_string($value) || is_null($value) || is_bool($value) || is_integer($value) ); }
[ "public", "function", "_isValueIndexable", "(", "$", "value", ")", "{", "return", "(", "is_string", "(", "$", "value", ")", "||", "is_null", "(", "$", "value", ")", "||", "is_bool", "(", "$", "value", ")", "||", "is_integer", "(", "$", "value", ")", ...
Determines if a value is indexable. @param mixed $value @return boolean
[ "Determines", "if", "a", "value", "is", "indexable", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L379-L387
train
ua1-labs/firesql
Fire/Sql/Collection.php
Collection._updateObjectIndexes
private function _updateObjectIndexes($object) { //delete all indexed references to this object $update = Statement::get( 'DELETE_OBJECT_INDEX', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($object->__id) ] ); //parse each property of the object an attempt to index each value foreach (get_object_vars($object) as $property => $value) { if ( $this->_isPropertyIndexable($property) && $this->_isValueIndexable($value) ) { $insert = Statement::get( 'INSERT_OBJECT_INDEX', [ '@collection' => $this->_name, '@type' => $this->_connector->quote('value'), '@prop' => $this->_connector->quote($property), '@val' => $this->_connector->quote($value), '@id' => $this->_connector->quote($object->__id), '@origin' => $this->_connector->quote($object->__origin) ] ); $update .= $insert; } } //add the object registry index $insert = Statement::get( 'INSERT_OBJECT_INDEX', [ '@collection' => $this->_name, '@type' => $this->_connector->quote('registry'), '@prop' => $this->_connector->quote(''), '@val' => $this->_connector->quote(''), '@id' => $this->_connector->quote($object->__id), '@origin' => $this->_connector->quote($object->__origin) ] ); $update .= $insert; //execute all the sql to update indexes. $this->_connector->exec($update); }
php
private function _updateObjectIndexes($object) { //delete all indexed references to this object $update = Statement::get( 'DELETE_OBJECT_INDEX', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($object->__id) ] ); //parse each property of the object an attempt to index each value foreach (get_object_vars($object) as $property => $value) { if ( $this->_isPropertyIndexable($property) && $this->_isValueIndexable($value) ) { $insert = Statement::get( 'INSERT_OBJECT_INDEX', [ '@collection' => $this->_name, '@type' => $this->_connector->quote('value'), '@prop' => $this->_connector->quote($property), '@val' => $this->_connector->quote($value), '@id' => $this->_connector->quote($object->__id), '@origin' => $this->_connector->quote($object->__origin) ] ); $update .= $insert; } } //add the object registry index $insert = Statement::get( 'INSERT_OBJECT_INDEX', [ '@collection' => $this->_name, '@type' => $this->_connector->quote('registry'), '@prop' => $this->_connector->quote(''), '@val' => $this->_connector->quote(''), '@id' => $this->_connector->quote($object->__id), '@origin' => $this->_connector->quote($object->__origin) ] ); $update .= $insert; //execute all the sql to update indexes. $this->_connector->exec($update); }
[ "private", "function", "_updateObjectIndexes", "(", "$", "object", ")", "{", "//delete all indexed references to this object", "$", "update", "=", "Statement", "::", "get", "(", "'DELETE_OBJECT_INDEX'", ",", "[", "'@collection'", "=>", "$", "this", "->", "_name", ",...
Updates an object's "value" index. @param object $object @return void
[ "Updates", "an", "object", "s", "value", "index", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L405-L450
train
ua1-labs/firesql
Fire/Sql/Collection.php
Collection._upsert
private function _upsert($object, $id = null) { $object = $this->_writeObjectToDb($object, $id); $this->_updateObjectIndexes($object); $this->_commitObject($object->__id, $object->__revision); return $object; }
php
private function _upsert($object, $id = null) { $object = $this->_writeObjectToDb($object, $id); $this->_updateObjectIndexes($object); $this->_commitObject($object->__id, $object->__revision); return $object; }
[ "private", "function", "_upsert", "(", "$", "object", ",", "$", "id", "=", "null", ")", "{", "$", "object", "=", "$", "this", "->", "_writeObjectToDb", "(", "$", "object", ",", "$", "id", ")", ";", "$", "this", "->", "_updateObjectIndexes", "(", "$",...
Upserts an object into the collection. Since update and inserts are the same logic, this method handles both. @param object $object @param string $id @return void
[ "Upserts", "an", "object", "into", "the", "collection", ".", "Since", "update", "and", "inserts", "are", "the", "same", "logic", "this", "method", "handles", "both", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L459-L465
train
ua1-labs/firesql
Fire/Sql/Collection.php
Collection._writeObjectToDb
private function _writeObjectToDb($object, $id) { $objectId = (!is_null($id)) ? $id : $this->_generateUniqueId(); $origin = $this->_getObjectOrigin($objectId); $object = json_decode(json_encode($object)); $object->__id = $objectId; $object->__revision = $this->_generateRevisionNumber(); $object->__updated = $this->_generateTimestamp(); $object->__origin = ($origin) ? $origin : $object->__updated; //insert into database $insert = Statement::get( 'INSERT_OBJECT', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($object->__id), '@revision' => $this->_connector->quote($object->__revision), '@committed' => $this->_connector->quote(0), '@updated' => $this->_connector->quote($object->__updated), '@origin' => $this->_connector->quote($object->__origin), '@obj' => $this->_connector->quote(json_encode($object)) ] ); $this->_connector->exec($insert); return $object; }
php
private function _writeObjectToDb($object, $id) { $objectId = (!is_null($id)) ? $id : $this->_generateUniqueId(); $origin = $this->_getObjectOrigin($objectId); $object = json_decode(json_encode($object)); $object->__id = $objectId; $object->__revision = $this->_generateRevisionNumber(); $object->__updated = $this->_generateTimestamp(); $object->__origin = ($origin) ? $origin : $object->__updated; //insert into database $insert = Statement::get( 'INSERT_OBJECT', [ '@collection' => $this->_name, '@id' => $this->_connector->quote($object->__id), '@revision' => $this->_connector->quote($object->__revision), '@committed' => $this->_connector->quote(0), '@updated' => $this->_connector->quote($object->__updated), '@origin' => $this->_connector->quote($object->__origin), '@obj' => $this->_connector->quote(json_encode($object)) ] ); $this->_connector->exec($insert); return $object; }
[ "private", "function", "_writeObjectToDb", "(", "$", "object", ",", "$", "id", ")", "{", "$", "objectId", "=", "(", "!", "is_null", "(", "$", "id", ")", ")", "?", "$", "id", ":", "$", "this", "->", "_generateUniqueId", "(", ")", ";", "$", "origin",...
Part of the upsert process, this method contains logic to write an object to the database. This method will also add the appropriate meta data to the object and return it. @param object $object @param string $id @return object
[ "Part", "of", "the", "upsert", "process", "this", "method", "contains", "logic", "to", "write", "an", "object", "to", "the", "database", ".", "This", "method", "will", "also", "add", "the", "appropriate", "meta", "data", "to", "the", "object", "and", "retu...
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L475-L500
train
ua1-labs/firesql
Fire/Sql/Collection.php
Collection._countObjectsInCollection
private function _countObjectsInCollection() { $select = Statement::get( 'GET_COLLECTION_OBJECT_COUNT', [ '@collection' => $this->_name ] ); $count = $this->_connector->query($select)->fetch(); if ($count) { return (int) $count[0]; } else { return 0; } }
php
private function _countObjectsInCollection() { $select = Statement::get( 'GET_COLLECTION_OBJECT_COUNT', [ '@collection' => $this->_name ] ); $count = $this->_connector->query($select)->fetch(); if ($count) { return (int) $count[0]; } else { return 0; } }
[ "private", "function", "_countObjectsInCollection", "(", ")", "{", "$", "select", "=", "Statement", "::", "get", "(", "'GET_COLLECTION_OBJECT_COUNT'", ",", "[", "'@collection'", "=>", "$", "this", "->", "_name", "]", ")", ";", "$", "count", "=", "$", "this",...
This method is used will return the count of objects contained with the collection. @return int
[ "This", "method", "is", "used", "will", "return", "the", "count", "of", "objects", "contained", "with", "the", "collection", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L507-L521
train
ua1-labs/firesql
Fire/Sql/Collection.php
Collection._countObjectsInCollectionByFilter
private function _countObjectsInCollectionByFilter(Filter $filterQuery) { $records = []; $props = []; $filters = []; foreach ($filterQuery->getComparisons() as $comparison) { $props[] = $comparison->prop; if ($comparison->expression && $comparison->comparison && $comparison->prop) { $expression = ($comparison->expression !== 'WHERE') ? $comparison->expression . ' ' : ''; $prop = is_int($comparison->val) ? 'CAST(' . $comparison->prop . ' AS INT)' : $comparison->prop; $compare = $comparison->comparison; $value = (!isset($comparison->val) || is_null($comparison->val)) ? 'NULL' : $comparison->val; $filters[] = $expression . $prop . ' ' . $compare . ' \'' . $value . '\''; } } $props = array_unique($props); $joins = []; foreach ($props as $prop) { $standardFields = [ '__id', '__type', '__collection', '__origin' ]; if (!in_array($prop, $standardFields)) { $asTbl = $this->_generateAlphaToken(); $joins[] = 'JOIN(' . 'SELECT id, val AS ' . $prop . ' ' . 'FROM ' . $this->_name . '__index ' . 'WHERE prop = \'' . $prop . '\'' . ') AS ' . $asTbl . ' ' . 'ON A.id = ' . $asTbl . '.id'; } } $select = Statement::get( 'GET_OBJECTS_COUNT_BY_FILTER', [ '@collection' => $this->_name, '@columns' => (count($props) > 0) ? ', ' . implode($props, ', ') : '', '@joinColumns' => (count($joins) > 0) ? implode($joins, ' ') . ' ' : '', '@type' => $this->_connector->quote($filterQuery->getIndexType()), '@filters' => ($filters) ? 'AND (' . implode($filters, ' ') . ') ' : '' ] ); $count = $this->_connector->query($select)->fetch(); if ($count) { return (int) $count[0]; } else { return 0; } }
php
private function _countObjectsInCollectionByFilter(Filter $filterQuery) { $records = []; $props = []; $filters = []; foreach ($filterQuery->getComparisons() as $comparison) { $props[] = $comparison->prop; if ($comparison->expression && $comparison->comparison && $comparison->prop) { $expression = ($comparison->expression !== 'WHERE') ? $comparison->expression . ' ' : ''; $prop = is_int($comparison->val) ? 'CAST(' . $comparison->prop . ' AS INT)' : $comparison->prop; $compare = $comparison->comparison; $value = (!isset($comparison->val) || is_null($comparison->val)) ? 'NULL' : $comparison->val; $filters[] = $expression . $prop . ' ' . $compare . ' \'' . $value . '\''; } } $props = array_unique($props); $joins = []; foreach ($props as $prop) { $standardFields = [ '__id', '__type', '__collection', '__origin' ]; if (!in_array($prop, $standardFields)) { $asTbl = $this->_generateAlphaToken(); $joins[] = 'JOIN(' . 'SELECT id, val AS ' . $prop . ' ' . 'FROM ' . $this->_name . '__index ' . 'WHERE prop = \'' . $prop . '\'' . ') AS ' . $asTbl . ' ' . 'ON A.id = ' . $asTbl . '.id'; } } $select = Statement::get( 'GET_OBJECTS_COUNT_BY_FILTER', [ '@collection' => $this->_name, '@columns' => (count($props) > 0) ? ', ' . implode($props, ', ') : '', '@joinColumns' => (count($joins) > 0) ? implode($joins, ' ') . ' ' : '', '@type' => $this->_connector->quote($filterQuery->getIndexType()), '@filters' => ($filters) ? 'AND (' . implode($filters, ' ') . ') ' : '' ] ); $count = $this->_connector->query($select)->fetch(); if ($count) { return (int) $count[0]; } else { return 0; } }
[ "private", "function", "_countObjectsInCollectionByFilter", "(", "Filter", "$", "filterQuery", ")", "{", "$", "records", "=", "[", "]", ";", "$", "props", "=", "[", "]", ";", "$", "filters", "=", "[", "]", ";", "foreach", "(", "$", "filterQuery", "->", ...
This method is used to return an object count by the filter that is passed in. @param Filter $filterQuery @return int
[ "This", "method", "is", "used", "to", "return", "an", "object", "count", "by", "the", "filter", "that", "is", "passed", "in", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Collection.php#L528-L583
train
yuan1994/ZCrawler
src/Grade/Cet.php
Cet.grade
public function grade() { $url = Config::get('url.grade_class_exam'); $response = $this->request('get', [$url]); $body = $this->checkAndThrow($response); return Parser::table($body, '#DataGrid1', [ 'year', 'term', 'name', 'number', 'date', 'grade_all', 'grade_listening', 'grade_reading', 'grade_writing', 'grade_synthesizing', ], 10); }
php
public function grade() { $url = Config::get('url.grade_class_exam'); $response = $this->request('get', [$url]); $body = $this->checkAndThrow($response); return Parser::table($body, '#DataGrid1', [ 'year', 'term', 'name', 'number', 'date', 'grade_all', 'grade_listening', 'grade_reading', 'grade_writing', 'grade_synthesizing', ], 10); }
[ "public", "function", "grade", "(", ")", "{", "$", "url", "=", "Config", "::", "get", "(", "'url.grade_class_exam'", ")", ";", "$", "response", "=", "$", "this", "->", "request", "(", "'get'", ",", "[", "$", "url", "]", ")", ";", "$", "body", "=", ...
Query student CET4 and CET6 grade @return array
[ "Query", "student", "CET4", "and", "CET6", "grade" ]
46c48a7c1837e404c324811776fc60f7b2a80df6
https://github.com/yuan1994/ZCrawler/blob/46c48a7c1837e404c324811776fc60f7b2a80df6/src/Grade/Cet.php#L28-L40
train
yuan1994/ZCrawler
src/Support/Parser.php
Parser.schedule
public static function schedule($body, $selector = '#Table1') { $array = []; $crawler = $body instanceof Crawler ? $body : new Crawler((string)$body); // to array $crawler->filter($selector)->children()->each(function (Crawler $node, $i) use (&$array) { // 删除前两行 if ($i < 2) { return false; } $array[] = $node->children()->each(function (Crawler $node, $j) { $span = (int)$node->attr('rowspan') ?: 0; return [$node->html(), $span]; }); }); // If there are some classes in the table is in two or more lines, // insert it into the next lines in $array. $lineCount = count($array); $schedule = []; for ($i = 0; $i < $lineCount; $i++) { // lines for ($j = 0; $j < 9; $j++) { // rows if (isset($array[$i][$j])) { $k = $array[$i][$j][1]; while (--$k > 0) { // insert element to next line // Set the span 0 $array[$i][$j][1] = 0; $array[$i + $k] = array_merge( array_slice($array[$i + $k], 0, $j), [$array[$i][$j]], array_splice($array[$i + $k], $j) ); } } $schedule[$i][$j] = isset($array[$i][$j][0]) ? $array[$i][$j][0] : ''; } } return $schedule; }
php
public static function schedule($body, $selector = '#Table1') { $array = []; $crawler = $body instanceof Crawler ? $body : new Crawler((string)$body); // to array $crawler->filter($selector)->children()->each(function (Crawler $node, $i) use (&$array) { // 删除前两行 if ($i < 2) { return false; } $array[] = $node->children()->each(function (Crawler $node, $j) { $span = (int)$node->attr('rowspan') ?: 0; return [$node->html(), $span]; }); }); // If there are some classes in the table is in two or more lines, // insert it into the next lines in $array. $lineCount = count($array); $schedule = []; for ($i = 0; $i < $lineCount; $i++) { // lines for ($j = 0; $j < 9; $j++) { // rows if (isset($array[$i][$j])) { $k = $array[$i][$j][1]; while (--$k > 0) { // insert element to next line // Set the span 0 $array[$i][$j][1] = 0; $array[$i + $k] = array_merge( array_slice($array[$i + $k], 0, $j), [$array[$i][$j]], array_splice($array[$i + $k], $j) ); } } $schedule[$i][$j] = isset($array[$i][$j][0]) ? $array[$i][$j][0] : ''; } } return $schedule; }
[ "public", "static", "function", "schedule", "(", "$", "body", ",", "$", "selector", "=", "'#Table1'", ")", "{", "$", "array", "=", "[", "]", ";", "$", "crawler", "=", "$", "body", "instanceof", "Crawler", "?", "$", "body", ":", "new", "Crawler", "(",...
Parser the schedule data. @param string|Crawler $body @param string $selector @return array
[ "Parser", "the", "schedule", "data", "." ]
46c48a7c1837e404c324811776fc60f7b2a80df6
https://github.com/yuan1994/ZCrawler/blob/46c48a7c1837e404c324811776fc60f7b2a80df6/src/Support/Parser.php#L26-L67
train
yuan1994/ZCrawler
src/Support/Parser.php
Parser.fieldName
public static function fieldName($body, $fieldName, $attr = 'value') { $crawler = $body instanceof Crawler ? $body : new Crawler((string)$body); return $crawler->filterXPath('//input[@name="' . $fieldName . '"]')->attr($attr); }
php
public static function fieldName($body, $fieldName, $attr = 'value') { $crawler = $body instanceof Crawler ? $body : new Crawler((string)$body); return $crawler->filterXPath('//input[@name="' . $fieldName . '"]')->attr($attr); }
[ "public", "static", "function", "fieldName", "(", "$", "body", ",", "$", "fieldName", ",", "$", "attr", "=", "'value'", ")", "{", "$", "crawler", "=", "$", "body", "instanceof", "Crawler", "?", "$", "body", ":", "new", "Crawler", "(", "(", "string", ...
Parser the form control name`s attribute @param string|object|Crawler $body @param string $fieldName @param string $attr @return string
[ "Parser", "the", "form", "control", "name", "s", "attribute" ]
46c48a7c1837e404c324811776fc60f7b2a80df6
https://github.com/yuan1994/ZCrawler/blob/46c48a7c1837e404c324811776fc60f7b2a80df6/src/Support/Parser.php#L123-L128
train
yuan1994/ZCrawler
src/Exam/Exam.php
Exam.current
public function current() { $url = Config::get('url.exam_basic'); $response = $this->request('get', [$url]); return $this->parseExam($response); }
php
public function current() { $url = Config::get('url.exam_basic'); $response = $this->request('get', [$url]); return $this->parseExam($response); }
[ "public", "function", "current", "(", ")", "{", "$", "url", "=", "Config", "::", "get", "(", "'url.exam_basic'", ")", ";", "$", "response", "=", "$", "this", "->", "request", "(", "'get'", ",", "[", "$", "url", "]", ")", ";", "return", "$", "this",...
Query current exam @return array
[ "Query", "current", "exam" ]
46c48a7c1837e404c324811776fc60f7b2a80df6
https://github.com/yuan1994/ZCrawler/blob/46c48a7c1837e404c324811776fc60f7b2a80df6/src/Exam/Exam.php#L26-L33
train
yuan1994/ZCrawler
src/Exam/Exam.php
Exam.getByTerm
public function getByTerm($year, $term) { $url = Config::get('url.exam_basic'); $param['__VIEWSTATE'] = true; $param['__EVENTTARGET'] = "xnd"; $param['__EVENTARGUMENT'] = ""; $param['xnd'] = $year; $param['xqd'] = $term; $response = $this->request('post', [$url, $param]); return $this->parseExam($response); }
php
public function getByTerm($year, $term) { $url = Config::get('url.exam_basic'); $param['__VIEWSTATE'] = true; $param['__EVENTTARGET'] = "xnd"; $param['__EVENTARGUMENT'] = ""; $param['xnd'] = $year; $param['xqd'] = $term; $response = $this->request('post', [$url, $param]); return $this->parseExam($response); }
[ "public", "function", "getByTerm", "(", "$", "year", ",", "$", "term", ")", "{", "$", "url", "=", "Config", "::", "get", "(", "'url.exam_basic'", ")", ";", "$", "param", "[", "'__VIEWSTATE'", "]", "=", "true", ";", "$", "param", "[", "'__EVENTTARGET'",...
Get exam by the year and term @param string $year @param string|int $term @return array
[ "Get", "exam", "by", "the", "year", "and", "term" ]
46c48a7c1837e404c324811776fc60f7b2a80df6
https://github.com/yuan1994/ZCrawler/blob/46c48a7c1837e404c324811776fc60f7b2a80df6/src/Exam/Exam.php#L43-L56
train
yuan1994/ZCrawler
src/Exam/Exam.php
Exam.currentMakeUp
public function currentMakeUp() { $url = Config::get('url.exam_make_up'); $response = $this->request('get', [$url]); return $this->parseMakeUpExam($response); }
php
public function currentMakeUp() { $url = Config::get('url.exam_make_up'); $response = $this->request('get', [$url]); return $this->parseMakeUpExam($response); }
[ "public", "function", "currentMakeUp", "(", ")", "{", "$", "url", "=", "Config", "::", "get", "(", "'url.exam_make_up'", ")", ";", "$", "response", "=", "$", "this", "->", "request", "(", "'get'", ",", "[", "$", "url", "]", ")", ";", "return", "$", ...
Query current make-up exam @return array
[ "Query", "current", "make", "-", "up", "exam" ]
46c48a7c1837e404c324811776fc60f7b2a80df6
https://github.com/yuan1994/ZCrawler/blob/46c48a7c1837e404c324811776fc60f7b2a80df6/src/Exam/Exam.php#L78-L85
train
yuan1994/ZCrawler
src/Exam/Exam.php
Exam.getMakeUpByTerm
public function getMakeUpByTerm($year, $term) { $url = Config::get('url.exam_make_up'); $param['__VIEWSTATE'] = true; $param['__EVENTTARGET'] = "xqd"; $param['__EVENTARGUMENT'] = ""; $param['__VIEWSTATEGENERATOR'] = "3F4872EB"; $param['xnd'] = $year; $param['xqd'] = $term; $response = $this->request('post', [$url, $param]); return $this->parseMakeUpExam($response); }
php
public function getMakeUpByTerm($year, $term) { $url = Config::get('url.exam_make_up'); $param['__VIEWSTATE'] = true; $param['__EVENTTARGET'] = "xqd"; $param['__EVENTARGUMENT'] = ""; $param['__VIEWSTATEGENERATOR'] = "3F4872EB"; $param['xnd'] = $year; $param['xqd'] = $term; $response = $this->request('post', [$url, $param]); return $this->parseMakeUpExam($response); }
[ "public", "function", "getMakeUpByTerm", "(", "$", "year", ",", "$", "term", ")", "{", "$", "url", "=", "Config", "::", "get", "(", "'url.exam_make_up'", ")", ";", "$", "param", "[", "'__VIEWSTATE'", "]", "=", "true", ";", "$", "param", "[", "'__EVENTT...
Get make-up exam by the year and term @param string $year @param string|int $term @return array
[ "Get", "make", "-", "up", "exam", "by", "the", "year", "and", "term" ]
46c48a7c1837e404c324811776fc60f7b2a80df6
https://github.com/yuan1994/ZCrawler/blob/46c48a7c1837e404c324811776fc60f7b2a80df6/src/Exam/Exam.php#L95-L109
train
yuan1994/ZCrawler
src/Schedule/Schedule.php
Schedule.current
public function current() { $url = $this->requestUrl; $response = $this->request('get', [$url]); return $this->parseSchedule($response); }
php
public function current() { $url = $this->requestUrl; $response = $this->request('get', [$url]); return $this->parseSchedule($response); }
[ "public", "function", "current", "(", ")", "{", "$", "url", "=", "$", "this", "->", "requestUrl", ";", "$", "response", "=", "$", "this", "->", "request", "(", "'get'", ",", "[", "$", "url", "]", ")", ";", "return", "$", "this", "->", "parseSchedul...
Get the current term`s schedule @return array
[ "Get", "the", "current", "term", "s", "schedule" ]
46c48a7c1837e404c324811776fc60f7b2a80df6
https://github.com/yuan1994/ZCrawler/blob/46c48a7c1837e404c324811776fc60f7b2a80df6/src/Schedule/Schedule.php#L47-L54
train
yuan1994/ZCrawler
src/Schedule/Schedule.php
Schedule.getByTerm
public function getByTerm($year, $term) { $url = $this->requestUrl; $param['__VIEWSTATE'] = true; $param['__EVENTTARGET'] = "xnd"; $param['__EVENTARGUMENT'] = ""; $param['xnd'] = $year; $param['xqd'] = $term; $response = $this->request('post', [$url, $param]); return $this->parseSchedule($response); }
php
public function getByTerm($year, $term) { $url = $this->requestUrl; $param['__VIEWSTATE'] = true; $param['__EVENTTARGET'] = "xnd"; $param['__EVENTARGUMENT'] = ""; $param['xnd'] = $year; $param['xqd'] = $term; $response = $this->request('post', [$url, $param]); return $this->parseSchedule($response); }
[ "public", "function", "getByTerm", "(", "$", "year", ",", "$", "term", ")", "{", "$", "url", "=", "$", "this", "->", "requestUrl", ";", "$", "param", "[", "'__VIEWSTATE'", "]", "=", "true", ";", "$", "param", "[", "'__EVENTTARGET'", "]", "=", "\"xnd\...
Get schedule by the year and term @param string $year @param string|int $term @return array
[ "Get", "schedule", "by", "the", "year", "and", "term" ]
46c48a7c1837e404c324811776fc60f7b2a80df6
https://github.com/yuan1994/ZCrawler/blob/46c48a7c1837e404c324811776fc60f7b2a80df6/src/Schedule/Schedule.php#L64-L77
train
yuan1994/ZCrawler
src/Login/Login.php
Login.getCookie
public function getCookie($forceRefresh = false, $method = 'noCode') { $cacheKey = $this->getCacheKey(); $cookie = $this->getCache()->fetch($cacheKey); if ($forceRefresh || empty($cookie)) { if (is_array($method)) { $cookie = call_user_func_array([$this, $method['method']], $method['param']); } else { $cookie = call_user_func([$this, $method]); } $this->setCookie($cookie); } return $cookie; }
php
public function getCookie($forceRefresh = false, $method = 'noCode') { $cacheKey = $this->getCacheKey(); $cookie = $this->getCache()->fetch($cacheKey); if ($forceRefresh || empty($cookie)) { if (is_array($method)) { $cookie = call_user_func_array([$this, $method['method']], $method['param']); } else { $cookie = call_user_func([$this, $method]); } $this->setCookie($cookie); } return $cookie; }
[ "public", "function", "getCookie", "(", "$", "forceRefresh", "=", "false", ",", "$", "method", "=", "'noCode'", ")", "{", "$", "cacheKey", "=", "$", "this", "->", "getCacheKey", "(", ")", ";", "$", "cookie", "=", "$", "this", "->", "getCache", "(", "...
Get the cookies for login. @param bool $forceRefresh @param string|array $method @return mixed
[ "Get", "the", "cookies", "for", "login", "." ]
46c48a7c1837e404c324811776fc60f7b2a80df6
https://github.com/yuan1994/ZCrawler/blob/46c48a7c1837e404c324811776fc60f7b2a80df6/src/Login/Login.php#L61-L77
train
yuan1994/ZCrawler
src/Login/Login.php
Login.setCookie
public function setCookie(CookieJar $cookie) { return $this->getCache()->save($this->getCacheKey(), $cookie, Config::get('cache.expire', 100)); }
php
public function setCookie(CookieJar $cookie) { return $this->getCache()->save($this->getCacheKey(), $cookie, Config::get('cache.expire', 100)); }
[ "public", "function", "setCookie", "(", "CookieJar", "$", "cookie", ")", "{", "return", "$", "this", "->", "getCache", "(", ")", "->", "save", "(", "$", "this", "->", "getCacheKey", "(", ")", ",", "$", "cookie", ",", "Config", "::", "get", "(", "'cac...
Set new cookies @param CookieJar $cookie @return bool
[ "Set", "new", "cookies" ]
46c48a7c1837e404c324811776fc60f7b2a80df6
https://github.com/yuan1994/ZCrawler/blob/46c48a7c1837e404c324811776fc60f7b2a80df6/src/Login/Login.php#L86-L89
train
yuan1994/ZCrawler
src/Login/Login.php
Login.getCaptcha
public function getCaptcha($path) { $url = Config::get('url.login_captcha'); $cookie = new CookieJar(); $codePath = $path . sha1($this->getUsername() . '-' . microtime(true)) . '.gif'; $options = ['cookies' => $cookie, 'save_to' => $codePath]; $response = $this->request('get', [$url, [], $options]); // Check the StatusCode if ($response->getStatusCode() == 200) { throw new HttpException('get the captcha failed!', 10005); } return $codePath; }
php
public function getCaptcha($path) { $url = Config::get('url.login_captcha'); $cookie = new CookieJar(); $codePath = $path . sha1($this->getUsername() . '-' . microtime(true)) . '.gif'; $options = ['cookies' => $cookie, 'save_to' => $codePath]; $response = $this->request('get', [$url, [], $options]); // Check the StatusCode if ($response->getStatusCode() == 200) { throw new HttpException('get the captcha failed!', 10005); } return $codePath; }
[ "public", "function", "getCaptcha", "(", "$", "path", ")", "{", "$", "url", "=", "Config", "::", "get", "(", "'url.login_captcha'", ")", ";", "$", "cookie", "=", "new", "CookieJar", "(", ")", ";", "$", "codePath", "=", "$", "path", ".", "sha1", "(", ...
Get the login captcha. @param string $codePath @return string
[ "Get", "the", "login", "captcha", "." ]
46c48a7c1837e404c324811776fc60f7b2a80df6
https://github.com/yuan1994/ZCrawler/blob/46c48a7c1837e404c324811776fc60f7b2a80df6/src/Login/Login.php#L160-L175
train
ua1-labs/firesql
Fire/Sql/Statement.php
Statement.get
static public function get($sqlStatement, $variables = []) { if (!is_array(self::$_statements)) { self::init(); } $sql = self::$_statements[$sqlStatement]; if ($variables) { foreach ($variables as $variable => $value) { $sql = str_replace($variable, $value, $sql); } } return $sql; }
php
static public function get($sqlStatement, $variables = []) { if (!is_array(self::$_statements)) { self::init(); } $sql = self::$_statements[$sqlStatement]; if ($variables) { foreach ($variables as $variable => $value) { $sql = str_replace($variable, $value, $sql); } } return $sql; }
[ "static", "public", "function", "get", "(", "$", "sqlStatement", ",", "$", "variables", "=", "[", "]", ")", "{", "if", "(", "!", "is_array", "(", "self", "::", "$", "_statements", ")", ")", "{", "self", "::", "init", "(", ")", ";", "}", "$", "sql...
This method is responsible for returning the associated SQL statement that has been prepared with the proper variables. @param string $sqlStatement The key associated with the SQL statement you want to return @param array $variables An array of variables @return string
[ "This", "method", "is", "responsible", "for", "returning", "the", "associated", "SQL", "statement", "that", "has", "been", "prepared", "with", "the", "proper", "variables", "." ]
9c2a480ad16429e659ba9f476c27b73c9b5c9a06
https://github.com/ua1-labs/firesql/blob/9c2a480ad16429e659ba9f476c27b73c9b5c9a06/Fire/Sql/Statement.php#L117-L129
train
obsh/sse-client
src/Client.php
Client.getEvents
public function getEvents() { $buffer = ''; $body = $this->response->getBody(); while (true) { // if server close connection - try to reconnect if ($body->eof()) { // wait retry period before reconnection sleep($this->retry / 1000); $this->connect(); // clear buffer since there is no sense in partial message $buffer = ''; } $buffer .= $body->read(1); if (preg_match(self::END_OF_MESSAGE, $buffer)) { $parts = preg_split(self::END_OF_MESSAGE, $buffer, 2); $rawMessage = $parts[0]; $remaining = $parts[1]; $buffer = $remaining; $event = Event::parse($rawMessage); // if message contains id set it to last received message id if ($event->getId()) { $this->lastId = $event->getId(); } // take into account server request for reconnection delay if ($event->getRetry()) { $this->retry = $event->getRetry(); } yield $event; } } }
php
public function getEvents() { $buffer = ''; $body = $this->response->getBody(); while (true) { // if server close connection - try to reconnect if ($body->eof()) { // wait retry period before reconnection sleep($this->retry / 1000); $this->connect(); // clear buffer since there is no sense in partial message $buffer = ''; } $buffer .= $body->read(1); if (preg_match(self::END_OF_MESSAGE, $buffer)) { $parts = preg_split(self::END_OF_MESSAGE, $buffer, 2); $rawMessage = $parts[0]; $remaining = $parts[1]; $buffer = $remaining; $event = Event::parse($rawMessage); // if message contains id set it to last received message id if ($event->getId()) { $this->lastId = $event->getId(); } // take into account server request for reconnection delay if ($event->getRetry()) { $this->retry = $event->getRetry(); } yield $event; } } }
[ "public", "function", "getEvents", "(", ")", "{", "$", "buffer", "=", "''", ";", "$", "body", "=", "$", "this", "->", "response", "->", "getBody", "(", ")", ";", "while", "(", "true", ")", "{", "// if server close connection - try to reconnect", "if", "(",...
Returns generator that yields new event when it's available on stream. @return Event[]
[ "Returns", "generator", "that", "yields", "new", "event", "when", "it", "s", "available", "on", "stream", "." ]
4f459f735917e84723bfd80eb1461e3f791e33ce
https://github.com/obsh/sse-client/blob/4f459f735917e84723bfd80eb1461e3f791e33ce/src/Client.php#L65-L103
train
Snowfire/Laravel-Postmark-Driver
src/Snowfire/Mail/PostmarkServiceProvider.php
PostmarkServiceProvider.registerPostmarkMailer
protected function registerPostmarkMailer() { $postmark = $this->app['config']->get('services.postmark', []); $this->app->singleton('swift.mailer', function ($app) use ($postmark) { return new Swift_Mailer( new Swift_PostmarkTransport($postmark['api_key']) ); }); }
php
protected function registerPostmarkMailer() { $postmark = $this->app['config']->get('services.postmark', []); $this->app->singleton('swift.mailer', function ($app) use ($postmark) { return new Swift_Mailer( new Swift_PostmarkTransport($postmark['api_key']) ); }); }
[ "protected", "function", "registerPostmarkMailer", "(", ")", "{", "$", "postmark", "=", "$", "this", "->", "app", "[", "'config'", "]", "->", "get", "(", "'services.postmark'", ",", "[", "]", ")", ";", "$", "this", "->", "app", "->", "singleton", "(", ...
Register the Postmark Swift Mailer. @return void
[ "Register", "the", "Postmark", "Swift", "Mailer", "." ]
f073dfe0d8e5d61bcb9a63719f51f8caec8aa9f6
https://github.com/Snowfire/Laravel-Postmark-Driver/blob/f073dfe0d8e5d61bcb9a63719f51f8caec8aa9f6/src/Snowfire/Mail/PostmarkServiceProvider.php#L33-L42
train
andegna/calender
src/Operations/Formatter.php
Formatter.getValueOfFormatCharacter
protected function getValueOfFormatCharacter(string $name, bool &$skip = false): string { if (($r = $this->shouldWeSkip($name, $skip)) !== false) { return ''.$r; } if ($this->isOverrideFormatCharacter($name)) { return ''.$this->{Constants::FORMAT_MAPPER[$name]}(); }
php
protected function getValueOfFormatCharacter(string $name, bool &$skip = false): string { if (($r = $this->shouldWeSkip($name, $skip)) !== false) { return ''.$r; } if ($this->isOverrideFormatCharacter($name)) { return ''.$this->{Constants::FORMAT_MAPPER[$name]}(); }
[ "protected", "function", "getValueOfFormatCharacter", "(", "string", "$", "name", ",", "bool", "&", "$", "skip", "=", "false", ")", ":", "string", "{", "if", "(", "(", "$", "r", "=", "$", "this", "->", "shouldWeSkip", "(", "$", "name", ",", "$", "ski...
Return the value of the format character. @param string $name of the field @param bool $skip @return string
[ "Return", "the", "value", "of", "the", "format", "character", "." ]
66e868422d1ac771c5063021638d022a0dc571be
https://github.com/andegna/calender/blob/66e868422d1ac771c5063021638d022a0dc571be/src/Operations/Formatter.php#L50-L58
train
andegna/calender
src/Holiday/Easter.php
Easter.get
public function get(int $year) { // convert the Ethiopian year to a Julian year // ሚያዝያ 1 is just a random day after the Gregorian new year $julian_year = (int) DateTimeFactory::of($year, 8, 1) ->toGregorian()->format('Y'); // get the number of days from vernal equinox to the Easter in the given Julian year $days_after = easter_days($julian_year, CAL_EASTER_ALWAYS_JULIAN); // get the JDN of vernal equinox (March 21) in the given Julian year $jdn = juliantojd(3, 21, $julian_year); // add the number of days to Easter $jdn += $days_after; // create a Ethiopian Date to JDN converter $con = new FromJdnConverter($jdn); // create an Ethiopian date from the converter return DateTimeFactory::of($con->getYear(), $con->getMonth(), $con->getDay(), 0, 0, 0, $this->dateTimeZone); }
php
public function get(int $year) { // convert the Ethiopian year to a Julian year // ሚያዝያ 1 is just a random day after the Gregorian new year $julian_year = (int) DateTimeFactory::of($year, 8, 1) ->toGregorian()->format('Y'); // get the number of days from vernal equinox to the Easter in the given Julian year $days_after = easter_days($julian_year, CAL_EASTER_ALWAYS_JULIAN); // get the JDN of vernal equinox (March 21) in the given Julian year $jdn = juliantojd(3, 21, $julian_year); // add the number of days to Easter $jdn += $days_after; // create a Ethiopian Date to JDN converter $con = new FromJdnConverter($jdn); // create an Ethiopian date from the converter return DateTimeFactory::of($con->getYear(), $con->getMonth(), $con->getDay(), 0, 0, 0, $this->dateTimeZone); }
[ "public", "function", "get", "(", "int", "$", "year", ")", "{", "// convert the Ethiopian year to a Julian year", "// ሚያዝያ 1 is just a random day after the Gregorian new year", "$", "julian_year", "=", "(", "int", ")", "DateTimeFactory", "::", "of", "(", "$", "year", ",...
Get the easter date of a given Ethiopian year. @param $year int Ethiopian year @return \Andegna\DateTime
[ "Get", "the", "easter", "date", "of", "a", "given", "Ethiopian", "year", "." ]
66e868422d1ac771c5063021638d022a0dc571be
https://github.com/andegna/calender/blob/66e868422d1ac771c5063021638d022a0dc571be/src/Holiday/Easter.php#L34-L56
train
andegna/calender
src/Converter/ToJdnConverter.php
ToJdnConverter.set
public function set(int $day, int $month, int $year) { $validator = new DateValidator($day, $month, $year); if (!$validator->isValid()) { throw new InvalidDateException(); } $this->day = $day; $this->month = $month; $this->year = $year; $this->jdn = (int) static::process($day, $month, $year); return $this; }
php
public function set(int $day, int $month, int $year) { $validator = new DateValidator($day, $month, $year); if (!$validator->isValid()) { throw new InvalidDateException(); } $this->day = $day; $this->month = $month; $this->year = $year; $this->jdn = (int) static::process($day, $month, $year); return $this; }
[ "public", "function", "set", "(", "int", "$", "day", ",", "int", "$", "month", ",", "int", "$", "year", ")", "{", "$", "validator", "=", "new", "DateValidator", "(", "$", "day", ",", "$", "month", ",", "$", "year", ")", ";", "if", "(", "!", "$"...
Set the date for processing. @param $day @param $month @param $year @throws \Andegna\Exception\InvalidDateException @return $this
[ "Set", "the", "date", "for", "processing", "." ]
66e868422d1ac771c5063021638d022a0dc571be
https://github.com/andegna/calender/blob/66e868422d1ac771c5063021638d022a0dc571be/src/Converter/ToJdnConverter.php#L38-L53
train
andegna/calender
src/Validator/DateValidator.php
DateValidator.isValid
public function isValid() { $validators = [ 'isDateValuesIntegers', 'isValidDayRange', 'isValidMonthRange', 'isValidPagumeDayRange', 'isValidLeapDay', ]; return array_reduce($validators, function ($result, $validator) { return $result && $this->{$validator}(); }, true); }
php
public function isValid() { $validators = [ 'isDateValuesIntegers', 'isValidDayRange', 'isValidMonthRange', 'isValidPagumeDayRange', 'isValidLeapDay', ]; return array_reduce($validators, function ($result, $validator) { return $result && $this->{$validator}(); }, true); }
[ "public", "function", "isValid", "(", ")", "{", "$", "validators", "=", "[", "'isDateValuesIntegers'", ",", "'isValidDayRange'", ",", "'isValidMonthRange'", ",", "'isValidPagumeDayRange'", ",", "'isValidLeapDay'", ",", "]", ";", "return", "array_reduce", "(", "$", ...
validate the ethiopian date. @return bool true if valid
[ "validate", "the", "ethiopian", "date", "." ]
66e868422d1ac771c5063021638d022a0dc571be
https://github.com/andegna/calender/blob/66e868422d1ac771c5063021638d022a0dc571be/src/Validator/DateValidator.php#L52-L65
train
andegna/calender
src/Converter/FromJdnConverter.php
FromJdnConverter.set
public function set(int $jdn) { if (!$this->isValidInteger($jdn)) { throw new InvalidDateException(); } $this->jdn = $jdn; $date = static::process($jdn); return $this->setDate($date); }
php
public function set(int $jdn) { if (!$this->isValidInteger($jdn)) { throw new InvalidDateException(); } $this->jdn = $jdn; $date = static::process($jdn); return $this->setDate($date); }
[ "public", "function", "set", "(", "int", "$", "jdn", ")", "{", "if", "(", "!", "$", "this", "->", "isValidInteger", "(", "$", "jdn", ")", ")", "{", "throw", "new", "InvalidDateException", "(", ")", ";", "}", "$", "this", "->", "jdn", "=", "$", "j...
Set the JDN for processing. @param $jdn @throws \Andegna\Exception\InvalidDateException @return $this
[ "Set", "the", "JDN", "for", "processing", "." ]
66e868422d1ac771c5063021638d022a0dc571be
https://github.com/andegna/calender/blob/66e868422d1ac771c5063021638d022a0dc571be/src/Converter/FromJdnConverter.php#L33-L44
train
andegna/calender
src/Operations/Initiator.php
Initiator.updateComputedFields
protected function updateComputedFields() { // Julian Date Number of the available datetime $jdn = $this->getJdnFromBase($this->dateTime); $converter = new FromJdnConverter($jdn); $this->setDateFromConverter($converter); $this->cacheTimestamp(); $this->computeFields(); }
php
protected function updateComputedFields() { // Julian Date Number of the available datetime $jdn = $this->getJdnFromBase($this->dateTime); $converter = new FromJdnConverter($jdn); $this->setDateFromConverter($converter); $this->cacheTimestamp(); $this->computeFields(); }
[ "protected", "function", "updateComputedFields", "(", ")", "{", "// Julian Date Number of the available datetime", "$", "jdn", "=", "$", "this", "->", "getJdnFromBase", "(", "$", "this", "->", "dateTime", ")", ";", "$", "converter", "=", "new", "FromJdnConverter", ...
This fields are just for catching. @return void
[ "This", "fields", "are", "just", "for", "catching", "." ]
66e868422d1ac771c5063021638d022a0dc571be
https://github.com/andegna/calender/blob/66e868422d1ac771c5063021638d022a0dc571be/src/Operations/Initiator.php#L20-L30
train
andegna/calender
src/Operations/Initiator.php
Initiator.getJdnFromBase
protected function getJdnFromBase(GregorianDateTime $dateTime): int { $year = $dateTime->format('Y'); $month = $dateTime->format('m'); $day = $dateTime->format('d'); return gregoriantojd($month, $day, $year); }
php
protected function getJdnFromBase(GregorianDateTime $dateTime): int { $year = $dateTime->format('Y'); $month = $dateTime->format('m'); $day = $dateTime->format('d'); return gregoriantojd($month, $day, $year); }
[ "protected", "function", "getJdnFromBase", "(", "GregorianDateTime", "$", "dateTime", ")", ":", "int", "{", "$", "year", "=", "$", "dateTime", "->", "format", "(", "'Y'", ")", ";", "$", "month", "=", "$", "dateTime", "->", "format", "(", "'m'", ")", ";...
Return the JDN of the given gregorian date time. @param GregorianDateTime $dateTime @return int
[ "Return", "the", "JDN", "of", "the", "given", "gregorian", "date", "time", "." ]
66e868422d1ac771c5063021638d022a0dc571be
https://github.com/andegna/calender/blob/66e868422d1ac771c5063021638d022a0dc571be/src/Operations/Initiator.php#L39-L46
train
andegna/calender
src/Operations/Initiator.php
Initiator.setDateFromConverter
protected function setDateFromConverter(Converter $converter) { $this->year = $converter->getYear(); $this->month = $converter->getMonth(); $this->day = $converter->getDay(); }
php
protected function setDateFromConverter(Converter $converter) { $this->year = $converter->getYear(); $this->month = $converter->getMonth(); $this->day = $converter->getDay(); }
[ "protected", "function", "setDateFromConverter", "(", "Converter", "$", "converter", ")", "{", "$", "this", "->", "year", "=", "$", "converter", "->", "getYear", "(", ")", ";", "$", "this", "->", "month", "=", "$", "converter", "->", "getMonth", "(", ")"...
Set the converted year, month and day from the given converter. @param Converter $converter @return void
[ "Set", "the", "converted", "year", "month", "and", "day", "from", "the", "given", "converter", "." ]
66e868422d1ac771c5063021638d022a0dc571be
https://github.com/andegna/calender/blob/66e868422d1ac771c5063021638d022a0dc571be/src/Operations/Initiator.php#L55-L60
train
andegna/calender
src/DateTimeFactory.php
DateTimeFactory.fromConverter
public static function fromConverter(Converter $con, DateTimeZone $dateTimeZone = null) { return static::of( $con->getYear(), $con->getMonth(), $con->getDay(), 0, 0, 0, $dateTimeZone ); }
php
public static function fromConverter(Converter $con, DateTimeZone $dateTimeZone = null) { return static::of( $con->getYear(), $con->getMonth(), $con->getDay(), 0, 0, 0, $dateTimeZone ); }
[ "public", "static", "function", "fromConverter", "(", "Converter", "$", "con", ",", "DateTimeZone", "$", "dateTimeZone", "=", "null", ")", "{", "return", "static", "::", "of", "(", "$", "con", "->", "getYear", "(", ")", ",", "$", "con", "->", "getMonth",...
Just for convenience. @param Converter $con @param DateTimeZone|null $dateTimeZone @return DateTime the datetime u wanted
[ "Just", "for", "convenience", "." ]
66e868422d1ac771c5063021638d022a0dc571be
https://github.com/andegna/calender/blob/66e868422d1ac771c5063021638d022a0dc571be/src/DateTimeFactory.php#L118-L124
train
xfra35/f3-multilang
lib/multilang.php
Multilang.isLocalized
function isLocalized($name,$lang=NULL) { if (!isset($lang)) $lang=$this->current; return !$this->isGlobal($name) && array_key_exists($name,$this->_aliases) && (!isset($this->rules[$lang][$name]) || $this->rules[$lang][$name]!==FALSE); }
php
function isLocalized($name,$lang=NULL) { if (!isset($lang)) $lang=$this->current; return !$this->isGlobal($name) && array_key_exists($name,$this->_aliases) && (!isset($this->rules[$lang][$name]) || $this->rules[$lang][$name]!==FALSE); }
[ "function", "isLocalized", "(", "$", "name", ",", "$", "lang", "=", "NULL", ")", "{", "if", "(", "!", "isset", "(", "$", "lang", ")", ")", "$", "lang", "=", "$", "this", "->", "current", ";", "return", "!", "$", "this", "->", "isGlobal", "(", "...
Check if a route is localized in a given language @param string $name @param string $lang @return bool
[ "Check", "if", "a", "route", "is", "localized", "in", "a", "given", "language" ]
ffaf7eb49af12fdd61e89fb6c740a994c960975c
https://github.com/xfra35/f3-multilang/blob/ffaf7eb49af12fdd61e89fb6c740a994c960975c/lib/multilang.php#L88-L93
train
xfra35/f3-multilang
lib/multilang.php
Multilang.detect
protected function detect($uri=NULL) { $this->current=$this->primary; if (preg_match('/^'.preg_quote($this->f3->get('BASE'),'/').'\/([^\/?]+)([\/?]|$)/',$uri?:$_SERVER['REQUEST_URI'],$m) && array_key_exists($m[1],$this->languages)) $this->current=$m[1]; else {//auto-detect language $this->auto=TRUE; $detected=array_intersect(explode(',',$this->f3->get('LANGUAGE')),explode(',',implode(',',$this->languages))); if ($detected=reset($detected)) foreach($this->languages as $lang=>$locales) if (in_array($detected,explode(',',$locales))) { $this->current=$lang; break; } } $this->f3->set('LANGUAGE',$this->languages[$this->current]); }
php
protected function detect($uri=NULL) { $this->current=$this->primary; if (preg_match('/^'.preg_quote($this->f3->get('BASE'),'/').'\/([^\/?]+)([\/?]|$)/',$uri?:$_SERVER['REQUEST_URI'],$m) && array_key_exists($m[1],$this->languages)) $this->current=$m[1]; else {//auto-detect language $this->auto=TRUE; $detected=array_intersect(explode(',',$this->f3->get('LANGUAGE')),explode(',',implode(',',$this->languages))); if ($detected=reset($detected)) foreach($this->languages as $lang=>$locales) if (in_array($detected,explode(',',$locales))) { $this->current=$lang; break; } } $this->f3->set('LANGUAGE',$this->languages[$this->current]); }
[ "protected", "function", "detect", "(", "$", "uri", "=", "NULL", ")", "{", "$", "this", "->", "current", "=", "$", "this", "->", "primary", ";", "if", "(", "preg_match", "(", "'/^'", ".", "preg_quote", "(", "$", "this", "->", "f3", "->", "get", "("...
! Detects the current language
[ "!", "Detects", "the", "current", "language" ]
ffaf7eb49af12fdd61e89fb6c740a994c960975c
https://github.com/xfra35/f3-multilang/blob/ffaf7eb49af12fdd61e89fb6c740a994c960975c/lib/multilang.php#L173-L189
train
xfra35/f3-multilang
lib/multilang.php
Multilang.rewrite
protected function rewrite() { $routes=array(); $aliases=&$this->f3->ref('ALIASES'); $redirects=array(); foreach($this->f3->get('ROUTES') as $old=>$data) { $route=current(current($data));//let's pick up any route just to get the URL name $name=@$route[3];//PHP 5.3 compatibility $new=$old; if (!($name && in_array($name,$this->global_aliases) || isset($this->global_regex) && preg_match($this->global_regex,$old))) { if (isset($this->rules[$this->current][$name])) { $new=$this->rules[$this->current][$name]; if ($new===FALSE) { if (isset($aliases[$name])) unset($aliases[$name]); continue; } } $new=rtrim('/'.$this->current.($new),'/'); if ($this->migrate && $this->auto) { $redir=$old; if (isset($this->rules[$this->primary][$name])) $redir=$this->rules[$this->primary][$name]; if ($redir!==FALSE) $redirects[$old]=rtrim('/'.$this->primary.($redir),'/'); } } if (isset($routes[$new]) && $this->strict) user_error(sprintf(self::E_Duplicate,$new),E_USER_ERROR); $routes[$new]=$data; if (isset($aliases[$name])) $aliases[$name]=$new; } $this->f3->set('ROUTES',$routes); foreach($redirects as $old=>$new) $this->f3->route('GET '.$old,function($f3)use($new){$f3->reroute($new,TRUE);}); }
php
protected function rewrite() { $routes=array(); $aliases=&$this->f3->ref('ALIASES'); $redirects=array(); foreach($this->f3->get('ROUTES') as $old=>$data) { $route=current(current($data));//let's pick up any route just to get the URL name $name=@$route[3];//PHP 5.3 compatibility $new=$old; if (!($name && in_array($name,$this->global_aliases) || isset($this->global_regex) && preg_match($this->global_regex,$old))) { if (isset($this->rules[$this->current][$name])) { $new=$this->rules[$this->current][$name]; if ($new===FALSE) { if (isset($aliases[$name])) unset($aliases[$name]); continue; } } $new=rtrim('/'.$this->current.($new),'/'); if ($this->migrate && $this->auto) { $redir=$old; if (isset($this->rules[$this->primary][$name])) $redir=$this->rules[$this->primary][$name]; if ($redir!==FALSE) $redirects[$old]=rtrim('/'.$this->primary.($redir),'/'); } } if (isset($routes[$new]) && $this->strict) user_error(sprintf(self::E_Duplicate,$new),E_USER_ERROR); $routes[$new]=$data; if (isset($aliases[$name])) $aliases[$name]=$new; } $this->f3->set('ROUTES',$routes); foreach($redirects as $old=>$new) $this->f3->route('GET '.$old,function($f3)use($new){$f3->reroute($new,TRUE);}); }
[ "protected", "function", "rewrite", "(", ")", "{", "$", "routes", "=", "array", "(", ")", ";", "$", "aliases", "=", "&", "$", "this", "->", "f3", "->", "ref", "(", "'ALIASES'", ")", ";", "$", "redirects", "=", "array", "(", ")", ";", "foreach", "...
! Rewrite ROUTES and ALIASES
[ "!", "Rewrite", "ROUTES", "and", "ALIASES" ]
ffaf7eb49af12fdd61e89fb6c740a994c960975c
https://github.com/xfra35/f3-multilang/blob/ffaf7eb49af12fdd61e89fb6c740a994c960975c/lib/multilang.php#L192-L228
train
hassansin/dbcart
src/Hassansin/DBCart/Models/Cart.php
Cart.current
public static function current($instance_name = 'default', $save_on_demand = null){ $save_on_demand = is_null($save_on_demand)? config('cart.save_on_demand', false): $save_on_demand; return static::init($instance_name, $save_on_demand); }
php
public static function current($instance_name = 'default', $save_on_demand = null){ $save_on_demand = is_null($save_on_demand)? config('cart.save_on_demand', false): $save_on_demand; return static::init($instance_name, $save_on_demand); }
[ "public", "static", "function", "current", "(", "$", "instance_name", "=", "'default'", ",", "$", "save_on_demand", "=", "null", ")", "{", "$", "save_on_demand", "=", "is_null", "(", "$", "save_on_demand", ")", "?", "config", "(", "'cart.save_on_demand'", ",",...
Get the current cart instance @param string $instance_name @return mixed
[ "Get", "the", "current", "cart", "instance" ]
eb44d6adc3819151fee2e8bea64c76dbdef3e01c
https://github.com/hassansin/dbcart/blob/eb44d6adc3819151fee2e8bea64c76dbdef3e01c/src/Hassansin/DBCart/Models/Cart.php#L106-L109
train
hassansin/dbcart
src/Hassansin/DBCart/Models/Cart.php
Cart.init
public static function init($instance_name, $save_on_demand){ $request = app('request'); $session_id = $request->session()->getId(); $user_id = config('cart.user_id'); $app = Application::getInstance(); $carts = $app->offsetGet("cart_instances"); if ($user_id instanceof \Closure) $user_id = $user_id(); //if user logged in if( $user_id ){ $user_cart = static::active()->user()->where('name', $instance_name)->first(); $session_cart_id = $request->session()->get('cart_'.$instance_name); $session_cart = is_null($session_cart_id)? null: static::active()->session($session_cart_id)->where('name', $instance_name)->first(); switch (true) { case is_null($user_cart) && is_null($session_cart): //no user cart or session cart $attributes = array( 'user_id' => $user_id, 'name' => $instance_name, 'status' => STATUS_ACTIVE ); if($save_on_demand) $cart = new static($attributes); else $cart = static::create($attributes); break; case !is_null($user_cart) && is_null($session_cart): //only user cart $cart = $user_cart; break; case is_null($user_cart) && !is_null($session_cart): //only session cart $cart = $session_cart; $cart->user_id = $user_id; $cart->session = null; $cart->save(); break; case !is_null($user_cart) && !is_null($session_cart): //both user cart and session cart exists $session_cart->moveItemsTo($user_cart); //move items from session cart to user cart $session_cart->delete(); //delete session cart $cart = $user_cart; break; } $request->session()->forget('cart_'.$instance_name); //no longer need it. $carts[$instance_name] = $cart; } //guest user, create cart with session id else{ $attributes = array( 'session' => $session_id, 'name' => $instance_name, 'status' => STATUS_ACTIVE ); $cart = static::firstOrNew($attributes); if(!$save_on_demand) $cart->save(); //save current session id, since upon login session id will be regenerated //we will use this id to get back the cart before login $request->session()->put('cart_'.$instance_name, $session_id); $carts[$instance_name] = $cart; } $app->offsetSet("cart_instances", $carts); return $carts[$instance_name]; }
php
public static function init($instance_name, $save_on_demand){ $request = app('request'); $session_id = $request->session()->getId(); $user_id = config('cart.user_id'); $app = Application::getInstance(); $carts = $app->offsetGet("cart_instances"); if ($user_id instanceof \Closure) $user_id = $user_id(); //if user logged in if( $user_id ){ $user_cart = static::active()->user()->where('name', $instance_name)->first(); $session_cart_id = $request->session()->get('cart_'.$instance_name); $session_cart = is_null($session_cart_id)? null: static::active()->session($session_cart_id)->where('name', $instance_name)->first(); switch (true) { case is_null($user_cart) && is_null($session_cart): //no user cart or session cart $attributes = array( 'user_id' => $user_id, 'name' => $instance_name, 'status' => STATUS_ACTIVE ); if($save_on_demand) $cart = new static($attributes); else $cart = static::create($attributes); break; case !is_null($user_cart) && is_null($session_cart): //only user cart $cart = $user_cart; break; case is_null($user_cart) && !is_null($session_cart): //only session cart $cart = $session_cart; $cart->user_id = $user_id; $cart->session = null; $cart->save(); break; case !is_null($user_cart) && !is_null($session_cart): //both user cart and session cart exists $session_cart->moveItemsTo($user_cart); //move items from session cart to user cart $session_cart->delete(); //delete session cart $cart = $user_cart; break; } $request->session()->forget('cart_'.$instance_name); //no longer need it. $carts[$instance_name] = $cart; } //guest user, create cart with session id else{ $attributes = array( 'session' => $session_id, 'name' => $instance_name, 'status' => STATUS_ACTIVE ); $cart = static::firstOrNew($attributes); if(!$save_on_demand) $cart->save(); //save current session id, since upon login session id will be regenerated //we will use this id to get back the cart before login $request->session()->put('cart_'.$instance_name, $session_id); $carts[$instance_name] = $cart; } $app->offsetSet("cart_instances", $carts); return $carts[$instance_name]; }
[ "public", "static", "function", "init", "(", "$", "instance_name", ",", "$", "save_on_demand", ")", "{", "$", "request", "=", "app", "(", "'request'", ")", ";", "$", "session_id", "=", "$", "request", "->", "session", "(", ")", "->", "getId", "(", ")",...
Initialize the cart @param string $instance_name @return mixed
[ "Initialize", "the", "cart" ]
eb44d6adc3819151fee2e8bea64c76dbdef3e01c
https://github.com/hassansin/dbcart/blob/eb44d6adc3819151fee2e8bea64c76dbdef3e01c/src/Hassansin/DBCart/Models/Cart.php#L117-L190
train
hassansin/dbcart
src/Hassansin/DBCart/Models/Cart.php
Cart.addItem
public function addItem(array $attributes = []){ if($item = $this->getItem(collect($attributes)->except(['quantity']))){ $item->quantity += $attributes['quantity']; $item->save(); return $item; } return $this->items()->create($attributes); }
php
public function addItem(array $attributes = []){ if($item = $this->getItem(collect($attributes)->except(['quantity']))){ $item->quantity += $attributes['quantity']; $item->save(); return $item; } return $this->items()->create($attributes); }
[ "public", "function", "addItem", "(", "array", "$", "attributes", "=", "[", "]", ")", "{", "if", "(", "$", "item", "=", "$", "this", "->", "getItem", "(", "collect", "(", "$", "attributes", ")", "->", "except", "(", "[", "'quantity'", "]", ")", ")"...
Add item to a cart. Increases quantity if the item already exists. @param array $attributes
[ "Add", "item", "to", "a", "cart", ".", "Increases", "quantity", "if", "the", "item", "already", "exists", "." ]
eb44d6adc3819151fee2e8bea64c76dbdef3e01c
https://github.com/hassansin/dbcart/blob/eb44d6adc3819151fee2e8bea64c76dbdef3e01c/src/Hassansin/DBCart/Models/Cart.php#L211-L218
train
hassansin/dbcart
src/Hassansin/DBCart/Models/Cart.php
Cart.updateItem
public function updateItem(array $where, array $values){ return $this->items()->where($where)->first()->update($values); }
php
public function updateItem(array $where, array $values){ return $this->items()->where($where)->first()->update($values); }
[ "public", "function", "updateItem", "(", "array", "$", "where", ",", "array", "$", "values", ")", "{", "return", "$", "this", "->", "items", "(", ")", "->", "where", "(", "$", "where", ")", "->", "first", "(", ")", "->", "update", "(", "$", "values...
update item in a cart @param array $attributes
[ "update", "item", "in", "a", "cart" ]
eb44d6adc3819151fee2e8bea64c76dbdef3e01c
https://github.com/hassansin/dbcart/blob/eb44d6adc3819151fee2e8bea64c76dbdef3e01c/src/Hassansin/DBCart/Models/Cart.php#L234-L236
train
hassansin/dbcart
src/Hassansin/DBCart/Models/Cart.php
Cart.clear
public function clear(){ $this->items()->delete(); $this->updateTimestamps(); $this->total_price = 0; $this->item_count = 0; $this->relations = []; return $this->save(); }
php
public function clear(){ $this->items()->delete(); $this->updateTimestamps(); $this->total_price = 0; $this->item_count = 0; $this->relations = []; return $this->save(); }
[ "public", "function", "clear", "(", ")", "{", "$", "this", "->", "items", "(", ")", "->", "delete", "(", ")", ";", "$", "this", "->", "updateTimestamps", "(", ")", ";", "$", "this", "->", "total_price", "=", "0", ";", "$", "this", "->", "item_count...
Empties a cart
[ "Empties", "a", "cart" ]
eb44d6adc3819151fee2e8bea64c76dbdef3e01c
https://github.com/hassansin/dbcart/blob/eb44d6adc3819151fee2e8bea64c76dbdef3e01c/src/Hassansin/DBCart/Models/Cart.php#L286-L293
train
hassansin/dbcart
src/Hassansin/DBCart/Models/Cart.php
Cart.moveItemsTo
public function moveItemsTo(Cart $cart){ \DB::transaction(function () use(&$cart){ $current_items = $cart->items()->pluck('product_id'); $items_to_move = $this->items()->whereNotIn('product_id', $current_items->toArray())->get(); if($items_to_move->count() === 0){ return; } $this->items()->whereNotIn('product_id', $current_items->toArray())->update([ 'cart_id' => $cart->id ]); foreach($items_to_move as $item) { $this->item_count -= $item->quantity; $this->total_price -= $item->getPrice(); $cart->item_count += $item->quantity; $cart->total_price += $item->getPrice(); } $this->relations = []; $cart->relations = []; $this->save(); $cart->save(); }); return $cart; }
php
public function moveItemsTo(Cart $cart){ \DB::transaction(function () use(&$cart){ $current_items = $cart->items()->pluck('product_id'); $items_to_move = $this->items()->whereNotIn('product_id', $current_items->toArray())->get(); if($items_to_move->count() === 0){ return; } $this->items()->whereNotIn('product_id', $current_items->toArray())->update([ 'cart_id' => $cart->id ]); foreach($items_to_move as $item) { $this->item_count -= $item->quantity; $this->total_price -= $item->getPrice(); $cart->item_count += $item->quantity; $cart->total_price += $item->getPrice(); } $this->relations = []; $cart->relations = []; $this->save(); $cart->save(); }); return $cart; }
[ "public", "function", "moveItemsTo", "(", "Cart", "$", "cart", ")", "{", "\\", "DB", "::", "transaction", "(", "function", "(", ")", "use", "(", "&", "$", "cart", ")", "{", "$", "current_items", "=", "$", "cart", "->", "items", "(", ")", "->", "plu...
Move Items to another cart instance @param Cart $cart
[ "Move", "Items", "to", "another", "cart", "instance" ]
eb44d6adc3819151fee2e8bea64c76dbdef3e01c
https://github.com/hassansin/dbcart/blob/eb44d6adc3819151fee2e8bea64c76dbdef3e01c/src/Hassansin/DBCart/Models/Cart.php#L300-L323
train
antonioribeiro/random
src/Faker.php
Faker.getFaker
public function getFaker() { if (is_null($this->faker) && class_exists($this->fakerClass)) { $this->faker = call_user_func("$this->fakerClass::create"); } return $this->faker; }
php
public function getFaker() { if (is_null($this->faker) && class_exists($this->fakerClass)) { $this->faker = call_user_func("$this->fakerClass::create"); } return $this->faker; }
[ "public", "function", "getFaker", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "faker", ")", "&&", "class_exists", "(", "$", "this", "->", "fakerClass", ")", ")", "{", "$", "this", "->", "faker", "=", "call_user_func", "(", "\"$this->fa...
Instantiate and get Faker. @return \Faker\Generator|null
[ "Instantiate", "and", "get", "Faker", "." ]
ae85276f4e83dc4e25dd05c3d9116dd0261c2deb
https://github.com/antonioribeiro/random/blob/ae85276f4e83dc4e25dd05c3d9116dd0261c2deb/src/Faker.php#L37-L44
train
antonioribeiro/random
src/CharCase.php
CharCase.changeCase
protected function changeCase($string) { if ($this->isLowercase()) { return strtolower($string); } if ($this->isUppercase()) { return strtoupper($string); } return $string; }
php
protected function changeCase($string) { if ($this->isLowercase()) { return strtolower($string); } if ($this->isUppercase()) { return strtoupper($string); } return $string; }
[ "protected", "function", "changeCase", "(", "$", "string", ")", "{", "if", "(", "$", "this", "->", "isLowercase", "(", ")", ")", "{", "return", "strtolower", "(", "$", "string", ")", ";", "}", "if", "(", "$", "this", "->", "isUppercase", "(", ")", ...
Return a string in the proper case. @param $string @return string
[ "Return", "a", "string", "in", "the", "proper", "case", "." ]
ae85276f4e83dc4e25dd05c3d9116dd0261c2deb
https://github.com/antonioribeiro/random/blob/ae85276f4e83dc4e25dd05c3d9116dd0261c2deb/src/CharCase.php#L37-L48
train
antonioribeiro/random
src/Generators/AlphaGenerator.php
AlphaGenerator.generateNumeric
protected function generateNumeric() { if (is_null($this->size) && $this->pattern == static::DEFAULT_PATTERN) { return $this->generateInteger(); } return $this->generateString($this->getNumericGenerator()); }
php
protected function generateNumeric() { if (is_null($this->size) && $this->pattern == static::DEFAULT_PATTERN) { return $this->generateInteger(); } return $this->generateString($this->getNumericGenerator()); }
[ "protected", "function", "generateNumeric", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "size", ")", "&&", "$", "this", "->", "pattern", "==", "static", "::", "DEFAULT_PATTERN", ")", "{", "return", "$", "this", "->", "generateInteger", "...
Generate a numeric random value. @return int|string
[ "Generate", "a", "numeric", "random", "value", "." ]
ae85276f4e83dc4e25dd05c3d9116dd0261c2deb
https://github.com/antonioribeiro/random/blob/ae85276f4e83dc4e25dd05c3d9116dd0261c2deb/src/Generators/AlphaGenerator.php#L34-L41
train
antonioribeiro/random
src/Trivia.php
Trivia.trivia
public function trivia() { $this->array = true; $this->count = 1; $this->items = (new TriviaService())->all(); return $this; }
php
public function trivia() { $this->array = true; $this->count = 1; $this->items = (new TriviaService())->all(); return $this; }
[ "public", "function", "trivia", "(", ")", "{", "$", "this", "->", "array", "=", "true", ";", "$", "this", "->", "count", "=", "1", ";", "$", "this", "->", "items", "=", "(", "new", "TriviaService", "(", ")", ")", "->", "all", "(", ")", ";", "re...
Generate trivia lines. @return static
[ "Generate", "trivia", "lines", "." ]
ae85276f4e83dc4e25dd05c3d9116dd0261c2deb
https://github.com/antonioribeiro/random/blob/ae85276f4e83dc4e25dd05c3d9116dd0261c2deb/src/Trivia.php#L17-L26
train
antonioribeiro/random
src/Generators/ArrayGenerator.php
ArrayGenerator.generateArray
protected function generateArray() { $result = []; $last = count($this->items)-1; for ($counter = 1; $counter <= $this->count; $counter++) { $result[] = $this->items[$this->generateRandomInt(0, $last)]; } if ($this->count == 1) { return $result[0]; } return $result; }
php
protected function generateArray() { $result = []; $last = count($this->items)-1; for ($counter = 1; $counter <= $this->count; $counter++) { $result[] = $this->items[$this->generateRandomInt(0, $last)]; } if ($this->count == 1) { return $result[0]; } return $result; }
[ "protected", "function", "generateArray", "(", ")", "{", "$", "result", "=", "[", "]", ";", "$", "last", "=", "count", "(", "$", "this", "->", "items", ")", "-", "1", ";", "for", "(", "$", "counter", "=", "1", ";", "$", "counter", "<=", "$", "t...
Generate random array elements. @return array
[ "Generate", "random", "array", "elements", "." ]
ae85276f4e83dc4e25dd05c3d9116dd0261c2deb
https://github.com/antonioribeiro/random/blob/ae85276f4e83dc4e25dd05c3d9116dd0261c2deb/src/Generators/ArrayGenerator.php#L31-L46
train
antonioribeiro/random
src/Random.php
Random.extractPattern
protected function extractPattern($string) { if (is_null($pattern = $this->getPattern())) { return $string; } preg_match_all("/$pattern/", $string, $matches); return implode('', $matches[0]); }
php
protected function extractPattern($string) { if (is_null($pattern = $this->getPattern())) { return $string; } preg_match_all("/$pattern/", $string, $matches); return implode('', $matches[0]); }
[ "protected", "function", "extractPattern", "(", "$", "string", ")", "{", "if", "(", "is_null", "(", "$", "pattern", "=", "$", "this", "->", "getPattern", "(", ")", ")", ")", "{", "return", "$", "string", ";", "}", "preg_match_all", "(", "\"/$pattern/\"",...
Extract a string pattern from a string. @param $string @return string
[ "Extract", "a", "string", "pattern", "from", "a", "string", "." ]
ae85276f4e83dc4e25dd05c3d9116dd0261c2deb
https://github.com/antonioribeiro/random/blob/ae85276f4e83dc4e25dd05c3d9116dd0261c2deb/src/Random.php#L87-L96
train
antonioribeiro/random
src/Random.php
Random.resetOneTimeValues
public function resetOneTimeValues() { $this->prefix = null; $this->suffix = null; $this->fakerString = null; return $this; }
php
public function resetOneTimeValues() { $this->prefix = null; $this->suffix = null; $this->fakerString = null; return $this; }
[ "public", "function", "resetOneTimeValues", "(", ")", "{", "$", "this", "->", "prefix", "=", "null", ";", "$", "this", "->", "suffix", "=", "null", ";", "$", "this", "->", "fakerString", "=", "null", ";", "return", "$", "this", ";", "}" ]
Reset one-time values. @return $this
[ "Reset", "one", "-", "time", "values", "." ]
ae85276f4e83dc4e25dd05c3d9116dd0261c2deb
https://github.com/antonioribeiro/random/blob/ae85276f4e83dc4e25dd05c3d9116dd0261c2deb/src/Random.php#L189-L198
train
php-ddd/domain-driven-design
src/Domain/CommandEventDispatcher.php
CommandEventDispatcher.handle
public function handle(AbstractCommand $command) { $this->commandDispatcher->handle($command); // Now that the command is handled, let's found if there is some events to publish $events = $this->extractEventsFromCommand($command); foreach ($events as $event) { // we will only publish event to synchronous listeners $this->publish($event); } return $command; }
php
public function handle(AbstractCommand $command) { $this->commandDispatcher->handle($command); // Now that the command is handled, let's found if there is some events to publish $events = $this->extractEventsFromCommand($command); foreach ($events as $event) { // we will only publish event to synchronous listeners $this->publish($event); } return $command; }
[ "public", "function", "handle", "(", "AbstractCommand", "$", "command", ")", "{", "$", "this", "->", "commandDispatcher", "->", "handle", "(", "$", "command", ")", ";", "// Now that the command is handled, let's found if there is some events to publish", "$", "events", ...
Try to handle the command given in argument. It will look over every handlers registered and find the one that knows how handle it. @param AbstractCommand $command @return AbstractCommand
[ "Try", "to", "handle", "the", "command", "given", "in", "argument", ".", "It", "will", "look", "over", "every", "handlers", "registered", "and", "find", "the", "one", "that", "knows", "how", "handle", "it", "." ]
764f48657f8c3a0ad0e4eea1df6b6dacb89b8c49
https://github.com/php-ddd/domain-driven-design/blob/764f48657f8c3a0ad0e4eea1df6b6dacb89b8c49/src/Domain/CommandEventDispatcher.php#L46-L57
train
mmoreram/symfony-bundle-dependencies
BundleDependenciesResolver.php
BundleDependenciesResolver.getBundleInstances
protected function getBundleInstances( KernelInterface $kernel, array $bundles ): array { $bundleStack = $this ->resolveAndReturnBundleDependencies( $kernel, $bundles ); $builtBundles = []; foreach ($bundleStack as $bundle) { $builtBundles[] = $this ->getBundleDefinitionInstance($bundle); } return $builtBundles; }
php
protected function getBundleInstances( KernelInterface $kernel, array $bundles ): array { $bundleStack = $this ->resolveAndReturnBundleDependencies( $kernel, $bundles ); $builtBundles = []; foreach ($bundleStack as $bundle) { $builtBundles[] = $this ->getBundleDefinitionInstance($bundle); } return $builtBundles; }
[ "protected", "function", "getBundleInstances", "(", "KernelInterface", "$", "kernel", ",", "array", "$", "bundles", ")", ":", "array", "{", "$", "bundleStack", "=", "$", "this", "->", "resolveAndReturnBundleDependencies", "(", "$", "kernel", ",", "$", "bundles",...
Get bundle instances given the namespace stack. @param KernelInterface $kernel @param array $bundles @return BundleInterface[]
[ "Get", "bundle", "instances", "given", "the", "namespace", "stack", "." ]
aed90cc4b91e08ce6b01506d5b36830041ceb18e
https://github.com/mmoreram/symfony-bundle-dependencies/blob/aed90cc4b91e08ce6b01506d5b36830041ceb18e/BundleDependenciesResolver.php#L36-L53
train
mmoreram/symfony-bundle-dependencies
BundleDependenciesResolver.php
BundleDependenciesResolver.resolveBundleDependencies
private function resolveBundleDependencies( KernelInterface $kernel, array &$bundleStack, array &$visitedBundles, array $bundles ) { $bundles = array_reverse($bundles); foreach ($bundles as $bundle) { /* * Each visited node is prioritized and placed at the beginning. */ $this ->prioritizeBundle( $bundleStack, $bundle ); } foreach ($bundles as $bundle) { $bundleNamespace = $this->getBundleDefinitionNamespace($bundle); /* * If have already visited this bundle, continue. One bundle can be * processed once. */ if (isset($visitedBundles[$bundleNamespace])) { continue; } $visitedBundles[$bundleNamespace] = true; $bundleNamespaceObj = new \ReflectionClass($bundleNamespace); if ($bundleNamespaceObj->implementsInterface(DependentBundleInterface::class)) { /** * @var DependentBundleInterface */ $bundleDependencies = $bundleNamespace::getBundleDependencies($kernel); $this->resolveBundleDependencies( $kernel, $bundleStack, $visitedBundles, $bundleDependencies ); } } }
php
private function resolveBundleDependencies( KernelInterface $kernel, array &$bundleStack, array &$visitedBundles, array $bundles ) { $bundles = array_reverse($bundles); foreach ($bundles as $bundle) { /* * Each visited node is prioritized and placed at the beginning. */ $this ->prioritizeBundle( $bundleStack, $bundle ); } foreach ($bundles as $bundle) { $bundleNamespace = $this->getBundleDefinitionNamespace($bundle); /* * If have already visited this bundle, continue. One bundle can be * processed once. */ if (isset($visitedBundles[$bundleNamespace])) { continue; } $visitedBundles[$bundleNamespace] = true; $bundleNamespaceObj = new \ReflectionClass($bundleNamespace); if ($bundleNamespaceObj->implementsInterface(DependentBundleInterface::class)) { /** * @var DependentBundleInterface */ $bundleDependencies = $bundleNamespace::getBundleDependencies($kernel); $this->resolveBundleDependencies( $kernel, $bundleStack, $visitedBundles, $bundleDependencies ); } } }
[ "private", "function", "resolveBundleDependencies", "(", "KernelInterface", "$", "kernel", ",", "array", "&", "$", "bundleStack", ",", "array", "&", "$", "visitedBundles", ",", "array", "$", "bundles", ")", "{", "$", "bundles", "=", "array_reverse", "(", "$", ...
Resolve bundle dependencies. Given a set of already loaded bundles and a set of new needed bundles, build new dependencies and fill given array of loaded bundles. @param KernelInterface $kernel @param array $bundleStack @param array $visitedBundles @param array $bundles
[ "Resolve", "bundle", "dependencies", "." ]
aed90cc4b91e08ce6b01506d5b36830041ceb18e
https://github.com/mmoreram/symfony-bundle-dependencies/blob/aed90cc4b91e08ce6b01506d5b36830041ceb18e/BundleDependenciesResolver.php#L91-L136
train
mmoreram/symfony-bundle-dependencies
BundleDependenciesResolver.php
BundleDependenciesResolver.prioritizeBundle
private function prioritizeBundle( array &$bundleStack, $elementToPrioritize ) { $elementNamespace = $this->getBundleDefinitionNamespace($elementToPrioritize); foreach ($bundleStack as $bundlePosition => $bundle) { $bundleNamespace = $this->getBundleDefinitionNamespace($bundle); if ($elementNamespace == $bundleNamespace) { unset($bundleStack[$bundlePosition]); } } array_unshift($bundleStack, $elementToPrioritize); }
php
private function prioritizeBundle( array &$bundleStack, $elementToPrioritize ) { $elementNamespace = $this->getBundleDefinitionNamespace($elementToPrioritize); foreach ($bundleStack as $bundlePosition => $bundle) { $bundleNamespace = $this->getBundleDefinitionNamespace($bundle); if ($elementNamespace == $bundleNamespace) { unset($bundleStack[$bundlePosition]); } } array_unshift($bundleStack, $elementToPrioritize); }
[ "private", "function", "prioritizeBundle", "(", "array", "&", "$", "bundleStack", ",", "$", "elementToPrioritize", ")", "{", "$", "elementNamespace", "=", "$", "this", "->", "getBundleDefinitionNamespace", "(", "$", "elementToPrioritize", ")", ";", "foreach", "(",...
Given the global bundle stack and a bundle definition, considering this bundle definition as an instance or a namespace, prioritize this bundle inside this stack. To prioritize a bundle means that must be placed in the beginning of the stack. If already exists, then remove the old entry just before adding it again. @param array $bundleStack @param BundleInterface|string $elementToPrioritize
[ "Given", "the", "global", "bundle", "stack", "and", "a", "bundle", "definition", "considering", "this", "bundle", "definition", "as", "an", "instance", "or", "a", "namespace", "prioritize", "this", "bundle", "inside", "this", "stack", "." ]
aed90cc4b91e08ce6b01506d5b36830041ceb18e
https://github.com/mmoreram/symfony-bundle-dependencies/blob/aed90cc4b91e08ce6b01506d5b36830041ceb18e/BundleDependenciesResolver.php#L150-L163
train
mmoreram/symfony-bundle-dependencies
BundleDependenciesResolver.php
BundleDependenciesResolver.getBundleDefinitionInstance
private function getBundleDefinitionInstance($bundle): BundleInterface { if (!is_object($bundle)) { $bundle = new $bundle($this); } if (!$bundle instanceof BundleInterface) { throw new BundleDependencyException(get_class($bundle)); } return $bundle; }
php
private function getBundleDefinitionInstance($bundle): BundleInterface { if (!is_object($bundle)) { $bundle = new $bundle($this); } if (!$bundle instanceof BundleInterface) { throw new BundleDependencyException(get_class($bundle)); } return $bundle; }
[ "private", "function", "getBundleDefinitionInstance", "(", "$", "bundle", ")", ":", "BundleInterface", "{", "if", "(", "!", "is_object", "(", "$", "bundle", ")", ")", "{", "$", "bundle", "=", "new", "$", "bundle", "(", "$", "this", ")", ";", "}", "if",...
Given a bundle instance or a namespace, return the instance. Each bundle is instanced with the Kernel as the first element of the construction, by default. @param BundleInterface|string $bundle @return BundleInterface @throws BundleDependencyException Is not a BundleInterface implementation
[ "Given", "a", "bundle", "instance", "or", "a", "namespace", "return", "the", "instance", ".", "Each", "bundle", "is", "instanced", "with", "the", "Kernel", "as", "the", "first", "element", "of", "the", "construction", "by", "default", "." ]
aed90cc4b91e08ce6b01506d5b36830041ceb18e
https://github.com/mmoreram/symfony-bundle-dependencies/blob/aed90cc4b91e08ce6b01506d5b36830041ceb18e/BundleDependenciesResolver.php#L190-L201
train
mmoreram/symfony-bundle-dependencies
CachedBundleDependenciesResolver.php
CachedBundleDependenciesResolver.cacheBuiltBundleStack
protected function cacheBuiltBundleStack( array $bundleStack, string $cacheFile ) { foreach ($bundleStack as $bundle) { if (is_object($bundle)) { $kernelNamespace = get_class($this); $bundleNamespace = get_class($bundle); throw new BundleStackNotCacheableException( $kernelNamespace, $bundleNamespace ); } } file_put_contents( $cacheFile, '<?php return ' . var_export($bundleStack, true) . ';' ); }
php
protected function cacheBuiltBundleStack( array $bundleStack, string $cacheFile ) { foreach ($bundleStack as $bundle) { if (is_object($bundle)) { $kernelNamespace = get_class($this); $bundleNamespace = get_class($bundle); throw new BundleStackNotCacheableException( $kernelNamespace, $bundleNamespace ); } } file_put_contents( $cacheFile, '<?php return ' . var_export($bundleStack, true) . ';' ); }
[ "protected", "function", "cacheBuiltBundleStack", "(", "array", "$", "bundleStack", ",", "string", "$", "cacheFile", ")", "{", "foreach", "(", "$", "bundleStack", "as", "$", "bundle", ")", "{", "if", "(", "is_object", "(", "$", "bundle", ")", ")", "{", "...
Cache the built bundles stack. Only bundles stack with string definitions are allowed to be cached. Otherwise, will throw an exception. @param Bundle[]|string[] $bundleStack @param string $cacheFile @throws BundleStackNotCacheableException Bundles not cacheable
[ "Cache", "the", "built", "bundles", "stack", ".", "Only", "bundles", "stack", "with", "string", "definitions", "are", "allowed", "to", "be", "cached", ".", "Otherwise", "will", "throw", "an", "exception", "." ]
aed90cc4b91e08ce6b01506d5b36830041ceb18e
https://github.com/mmoreram/symfony-bundle-dependencies/blob/aed90cc4b91e08ce6b01506d5b36830041ceb18e/CachedBundleDependenciesResolver.php#L95-L114
train
nilportugues/php-sql-query-formatter
src/Helper/NewLine.php
NewLine.addNewLineBreak
public function addNewLineBreak($tab) { $addedNewline = false; if (true === $this->newline) { $this->formatter->appendToFormattedSql("\n".str_repeat($tab, $this->indentation->getIndentLvl())); $this->newline = false; $addedNewline = true; } return $addedNewline; }
php
public function addNewLineBreak($tab) { $addedNewline = false; if (true === $this->newline) { $this->formatter->appendToFormattedSql("\n".str_repeat($tab, $this->indentation->getIndentLvl())); $this->newline = false; $addedNewline = true; } return $addedNewline; }
[ "public", "function", "addNewLineBreak", "(", "$", "tab", ")", "{", "$", "addedNewline", "=", "false", ";", "if", "(", "true", "===", "$", "this", "->", "newline", ")", "{", "$", "this", "->", "formatter", "->", "appendToFormattedSql", "(", "\"\\n\"", "....
Adds a new line break if needed. @param string $tab @return bool
[ "Adds", "a", "new", "line", "break", "if", "needed", "." ]
865e9c13ff78be6af03b2b259e28c6677f3d79aa
https://github.com/nilportugues/php-sql-query-formatter/blob/865e9c13ff78be6af03b2b259e28c6677f3d79aa/src/Helper/NewLine.php#L60-L71
train
nilportugues/php-sql-query-formatter
src/Helper/NewLine.php
NewLine.addNewLineAfterOpeningParentheses
public function addNewLineAfterOpeningParentheses() { if (false === $this->parentheses->getInlineParentheses()) { $this->indentation->setIncreaseBlockIndent(true); $this->newline = true; } }
php
public function addNewLineAfterOpeningParentheses() { if (false === $this->parentheses->getInlineParentheses()) { $this->indentation->setIncreaseBlockIndent(true); $this->newline = true; } }
[ "public", "function", "addNewLineAfterOpeningParentheses", "(", ")", "{", "if", "(", "false", "===", "$", "this", "->", "parentheses", "->", "getInlineParentheses", "(", ")", ")", "{", "$", "this", "->", "indentation", "->", "setIncreaseBlockIndent", "(", "true"...
Adds a new line break for an opening parentheses for a non-inline expression.
[ "Adds", "a", "new", "line", "break", "for", "an", "opening", "parentheses", "for", "a", "non", "-", "inline", "expression", "." ]
865e9c13ff78be6af03b2b259e28c6677f3d79aa
https://github.com/nilportugues/php-sql-query-formatter/blob/865e9c13ff78be6af03b2b259e28c6677f3d79aa/src/Helper/NewLine.php#L101-L107
train
nilportugues/php-sql-query-formatter
src/Helper/NewLine.php
NewLine.writeNewLineBecauseOfTopLevelReservedWord
public function writeNewLineBecauseOfTopLevelReservedWord($addedNewline, $tab) { if (false === $addedNewline) { $this->formatter->appendToFormattedSql("\n"); } else { $this->formatter->setFormattedSql(\rtrim($this->formatter->getFormattedSql(), $tab)); } $this->formatter->appendToFormattedSql(\str_repeat($tab, $this->indentation->getIndentLvl())); $this->newline = true; }
php
public function writeNewLineBecauseOfTopLevelReservedWord($addedNewline, $tab) { if (false === $addedNewline) { $this->formatter->appendToFormattedSql("\n"); } else { $this->formatter->setFormattedSql(\rtrim($this->formatter->getFormattedSql(), $tab)); } $this->formatter->appendToFormattedSql(\str_repeat($tab, $this->indentation->getIndentLvl())); $this->newline = true; }
[ "public", "function", "writeNewLineBecauseOfTopLevelReservedWord", "(", "$", "addedNewline", ",", "$", "tab", ")", "{", "if", "(", "false", "===", "$", "addedNewline", ")", "{", "$", "this", "->", "formatter", "->", "appendToFormattedSql", "(", "\"\\n\"", ")", ...
Add a newline before the top level reserved word if necessary and indent. @param bool $addedNewline @param string $tab
[ "Add", "a", "newline", "before", "the", "top", "level", "reserved", "word", "if", "necessary", "and", "indent", "." ]
865e9c13ff78be6af03b2b259e28c6677f3d79aa
https://github.com/nilportugues/php-sql-query-formatter/blob/865e9c13ff78be6af03b2b259e28c6677f3d79aa/src/Helper/NewLine.php#L128-L138
train
nilportugues/php-sql-query-formatter
src/Helper/NewLine.php
NewLine.writeNewLineBecauseOfComma
public function writeNewLineBecauseOfComma() { $this->newline = true; if (true === $this->formatter->getClauseLimit()) { $this->newline = false; $this->formatter->setClauseLimit(false); } }
php
public function writeNewLineBecauseOfComma() { $this->newline = true; if (true === $this->formatter->getClauseLimit()) { $this->newline = false; $this->formatter->setClauseLimit(false); } }
[ "public", "function", "writeNewLineBecauseOfComma", "(", ")", "{", "$", "this", "->", "newline", "=", "true", ";", "if", "(", "true", "===", "$", "this", "->", "formatter", "->", "getClauseLimit", "(", ")", ")", "{", "$", "this", "->", "newline", "=", ...
Commas start a new line unless they are found within inline parentheses or SQL 'LIMIT' clause. If the previous TOKEN_VALUE is 'LIMIT', undo new line.
[ "Commas", "start", "a", "new", "line", "unless", "they", "are", "found", "within", "inline", "parentheses", "or", "SQL", "LIMIT", "clause", ".", "If", "the", "previous", "TOKEN_VALUE", "is", "LIMIT", "undo", "new", "line", "." ]
865e9c13ff78be6af03b2b259e28c6677f3d79aa
https://github.com/nilportugues/php-sql-query-formatter/blob/865e9c13ff78be6af03b2b259e28c6677f3d79aa/src/Helper/NewLine.php#L144-L152
train
nilportugues/php-sql-query-formatter
src/Formatter.php
Formatter.format
public function format($sql) { $this->reset(); $tab = "\t"; $originalTokens = $this->tokenizer->tokenize((string) $sql); $tokens = WhiteSpace::removeTokenWhitespace($originalTokens); foreach ($tokens as $i => $token) { $queryValue = $token[Tokenizer::TOKEN_VALUE]; $this->indentation->increaseSpecialIndent()->increaseBlockIndent(); $addedNewline = $this->newLine->addNewLineBreak($tab); if ($this->comment->stringHasCommentToken($token)) { $this->formattedSql = $this->comment->writeCommentBlock($token, $tab, $queryValue); continue; } if ($this->parentheses->getInlineParentheses()) { if ($this->parentheses->stringIsClosingParentheses($token)) { $this->parentheses->writeInlineParenthesesBlock($tab, $queryValue); continue; } $this->newLine->writeNewLineForLongCommaInlineValues($token); $this->inlineCount += \strlen($token[Tokenizer::TOKEN_VALUE]); } switch ($token) { case $this->parentheses->stringIsOpeningParentheses($token): $tokens = $this->formatOpeningParenthesis($token, $i, $tokens, $originalTokens); break; case $this->parentheses->stringIsClosingParentheses($token): $this->indentation->decreaseIndentLevelUntilIndentTypeIsSpecial($this); $this->newLine->addNewLineBeforeToken($addedNewline, $tab); break; case $this->stringIsEndOfLimitClause($token): $this->clauseLimit = false; break; case $token[Tokenizer::TOKEN_VALUE] === ',' && false === $this->parentheses->getInlineParentheses(): $this->newLine->writeNewLineBecauseOfComma(); break; case Token::isTokenTypeReservedTopLevel($token): $queryValue = $this->formatTokenTypeReservedTopLevel($addedNewline, $tab, $token, $queryValue); break; case $this->newLine->isTokenTypeReservedNewLine($token): $this->newLine->addNewLineBeforeToken($addedNewline, $tab); if (WhiteSpace::tokenHasExtraWhiteSpaces($token)) { $queryValue = \preg_replace('/\s+/', ' ', $queryValue); } break; } $this->formatBoundaryCharacterToken($token, $i, $tokens, $originalTokens); $this->formatWhiteSpaceToken($token, $queryValue); $this->formatDashToken($token, $i, $tokens); } return \trim(\str_replace(["\t", " \n"], [$this->tab, "\n"], $this->formattedSql))."\n"; }
php
public function format($sql) { $this->reset(); $tab = "\t"; $originalTokens = $this->tokenizer->tokenize((string) $sql); $tokens = WhiteSpace::removeTokenWhitespace($originalTokens); foreach ($tokens as $i => $token) { $queryValue = $token[Tokenizer::TOKEN_VALUE]; $this->indentation->increaseSpecialIndent()->increaseBlockIndent(); $addedNewline = $this->newLine->addNewLineBreak($tab); if ($this->comment->stringHasCommentToken($token)) { $this->formattedSql = $this->comment->writeCommentBlock($token, $tab, $queryValue); continue; } if ($this->parentheses->getInlineParentheses()) { if ($this->parentheses->stringIsClosingParentheses($token)) { $this->parentheses->writeInlineParenthesesBlock($tab, $queryValue); continue; } $this->newLine->writeNewLineForLongCommaInlineValues($token); $this->inlineCount += \strlen($token[Tokenizer::TOKEN_VALUE]); } switch ($token) { case $this->parentheses->stringIsOpeningParentheses($token): $tokens = $this->formatOpeningParenthesis($token, $i, $tokens, $originalTokens); break; case $this->parentheses->stringIsClosingParentheses($token): $this->indentation->decreaseIndentLevelUntilIndentTypeIsSpecial($this); $this->newLine->addNewLineBeforeToken($addedNewline, $tab); break; case $this->stringIsEndOfLimitClause($token): $this->clauseLimit = false; break; case $token[Tokenizer::TOKEN_VALUE] === ',' && false === $this->parentheses->getInlineParentheses(): $this->newLine->writeNewLineBecauseOfComma(); break; case Token::isTokenTypeReservedTopLevel($token): $queryValue = $this->formatTokenTypeReservedTopLevel($addedNewline, $tab, $token, $queryValue); break; case $this->newLine->isTokenTypeReservedNewLine($token): $this->newLine->addNewLineBeforeToken($addedNewline, $tab); if (WhiteSpace::tokenHasExtraWhiteSpaces($token)) { $queryValue = \preg_replace('/\s+/', ' ', $queryValue); } break; } $this->formatBoundaryCharacterToken($token, $i, $tokens, $originalTokens); $this->formatWhiteSpaceToken($token, $queryValue); $this->formatDashToken($token, $i, $tokens); } return \trim(\str_replace(["\t", " \n"], [$this->tab, "\n"], $this->formattedSql))."\n"; }
[ "public", "function", "format", "(", "$", "sql", ")", "{", "$", "this", "->", "reset", "(", ")", ";", "$", "tab", "=", "\"\\t\"", ";", "$", "originalTokens", "=", "$", "this", "->", "tokenizer", "->", "tokenize", "(", "(", "string", ")", "$", "sql"...
Returns a SQL string in a readable human-friendly format. @param string $sql @return string
[ "Returns", "a", "SQL", "string", "in", "a", "readable", "human", "-", "friendly", "format", "." ]
865e9c13ff78be6af03b2b259e28c6677f3d79aa
https://github.com/nilportugues/php-sql-query-formatter/blob/865e9c13ff78be6af03b2b259e28c6677f3d79aa/src/Formatter.php#L77-L141
train
nilportugues/php-sql-query-formatter
src/Helper/Indent.php
Indent.increaseSpecialIndent
public function increaseSpecialIndent() { if ($this->increaseSpecialIndent) { ++$this->indentLvl; $this->increaseSpecialIndent = false; \array_unshift($this->indentTypes, 'special'); } return $this; }
php
public function increaseSpecialIndent() { if ($this->increaseSpecialIndent) { ++$this->indentLvl; $this->increaseSpecialIndent = false; \array_unshift($this->indentTypes, 'special'); } return $this; }
[ "public", "function", "increaseSpecialIndent", "(", ")", "{", "if", "(", "$", "this", "->", "increaseSpecialIndent", ")", "{", "++", "$", "this", "->", "indentLvl", ";", "$", "this", "->", "increaseSpecialIndent", "=", "false", ";", "\\", "array_unshift", "(...
Increase the Special Indent if increaseSpecialIndent is true after the current iteration. @return $this
[ "Increase", "the", "Special", "Indent", "if", "increaseSpecialIndent", "is", "true", "after", "the", "current", "iteration", "." ]
865e9c13ff78be6af03b2b259e28c6677f3d79aa
https://github.com/nilportugues/php-sql-query-formatter/blob/865e9c13ff78be6af03b2b259e28c6677f3d79aa/src/Helper/Indent.php#L50-L59
train
nilportugues/php-sql-query-formatter
src/Helper/Indent.php
Indent.increaseBlockIndent
public function increaseBlockIndent() { if ($this->increaseBlockIndent) { ++$this->indentLvl; $this->increaseBlockIndent = false; \array_unshift($this->indentTypes, 'block'); } return $this; }
php
public function increaseBlockIndent() { if ($this->increaseBlockIndent) { ++$this->indentLvl; $this->increaseBlockIndent = false; \array_unshift($this->indentTypes, 'block'); } return $this; }
[ "public", "function", "increaseBlockIndent", "(", ")", "{", "if", "(", "$", "this", "->", "increaseBlockIndent", ")", "{", "++", "$", "this", "->", "indentLvl", ";", "$", "this", "->", "increaseBlockIndent", "=", "false", ";", "\\", "array_unshift", "(", "...
Increase the Block Indent if increaseBlockIndent is true after the current iteration. @return $this
[ "Increase", "the", "Block", "Indent", "if", "increaseBlockIndent", "is", "true", "after", "the", "current", "iteration", "." ]
865e9c13ff78be6af03b2b259e28c6677f3d79aa
https://github.com/nilportugues/php-sql-query-formatter/blob/865e9c13ff78be6af03b2b259e28c6677f3d79aa/src/Helper/Indent.php#L66-L75
train
nilportugues/php-sql-query-formatter
src/Helper/Indent.php
Indent.decreaseIndentLevelUntilIndentTypeIsSpecial
public function decreaseIndentLevelUntilIndentTypeIsSpecial(Formatter $formatter) { $formatter->setFormattedSql(\rtrim($formatter->getFormattedSql(), ' ')); --$this->indentLvl; while ($j = \array_shift($this->indentTypes)) { if ('special' !== $j) { break; } --$this->indentLvl; } return $this; }
php
public function decreaseIndentLevelUntilIndentTypeIsSpecial(Formatter $formatter) { $formatter->setFormattedSql(\rtrim($formatter->getFormattedSql(), ' ')); --$this->indentLvl; while ($j = \array_shift($this->indentTypes)) { if ('special' !== $j) { break; } --$this->indentLvl; } return $this; }
[ "public", "function", "decreaseIndentLevelUntilIndentTypeIsSpecial", "(", "Formatter", "$", "formatter", ")", "{", "$", "formatter", "->", "setFormattedSql", "(", "\\", "rtrim", "(", "$", "formatter", "->", "getFormattedSql", "(", ")", ",", "' '", ")", ")", ";",...
Closing parentheses decrease the block indent level. @param Formatter $formatter @return $this
[ "Closing", "parentheses", "decrease", "the", "block", "indent", "level", "." ]
865e9c13ff78be6af03b2b259e28c6677f3d79aa
https://github.com/nilportugues/php-sql-query-formatter/blob/865e9c13ff78be6af03b2b259e28c6677f3d79aa/src/Helper/Indent.php#L84-L97
train
nilportugues/php-sql-query-formatter
src/Tokenizer/Parser/Reserved.php
Reserved.isReservedPrecededByDotCharacter
protected static function isReservedPrecededByDotCharacter($previous) { return !$previous || !isset($previous[Tokenizer::TOKEN_VALUE]) || $previous[Tokenizer::TOKEN_VALUE] !== '.'; }
php
protected static function isReservedPrecededByDotCharacter($previous) { return !$previous || !isset($previous[Tokenizer::TOKEN_VALUE]) || $previous[Tokenizer::TOKEN_VALUE] !== '.'; }
[ "protected", "static", "function", "isReservedPrecededByDotCharacter", "(", "$", "previous", ")", "{", "return", "!", "$", "previous", "||", "!", "isset", "(", "$", "previous", "[", "Tokenizer", "::", "TOKEN_VALUE", "]", ")", "||", "$", "previous", "[", "Tok...
A reserved word cannot be preceded by a "." in order to differentiate "mytable.from" from the token "from". @param $previous @return bool
[ "A", "reserved", "word", "cannot", "be", "preceded", "by", "a", ".", "in", "order", "to", "differentiate", "mytable", ".", "from", "from", "the", "token", "from", "." ]
865e9c13ff78be6af03b2b259e28c6677f3d79aa
https://github.com/nilportugues/php-sql-query-formatter/blob/865e9c13ff78be6af03b2b259e28c6677f3d79aa/src/Tokenizer/Parser/Reserved.php#L58-L61
train
nilportugues/php-sql-query-formatter
src/Tokenizer/Parser/UserDefined.php
UserDefined.getUserDefinedVariableString
protected static function getUserDefinedVariableString(&$string) { $returnData = [ Tokenizer::TOKEN_VALUE => null, Tokenizer::TOKEN_TYPE => Tokenizer::TOKEN_TYPE_VARIABLE, ]; self::setTokenValueStartingWithAtSymbolAndWrapped($returnData, $string); self::setTokenValueStartingWithAtSymbol($returnData, $string); return $returnData; }
php
protected static function getUserDefinedVariableString(&$string) { $returnData = [ Tokenizer::TOKEN_VALUE => null, Tokenizer::TOKEN_TYPE => Tokenizer::TOKEN_TYPE_VARIABLE, ]; self::setTokenValueStartingWithAtSymbolAndWrapped($returnData, $string); self::setTokenValueStartingWithAtSymbol($returnData, $string); return $returnData; }
[ "protected", "static", "function", "getUserDefinedVariableString", "(", "&", "$", "string", ")", "{", "$", "returnData", "=", "[", "Tokenizer", "::", "TOKEN_VALUE", "=>", "null", ",", "Tokenizer", "::", "TOKEN_TYPE", "=>", "Tokenizer", "::", "TOKEN_TYPE_VARIABLE",...
Gets the user defined variables for in quoted or non-quoted fashion. @param string $string @return array
[ "Gets", "the", "user", "defined", "variables", "for", "in", "quoted", "or", "non", "-", "quoted", "fashion", "." ]
865e9c13ff78be6af03b2b259e28c6677f3d79aa
https://github.com/nilportugues/php-sql-query-formatter/blob/865e9c13ff78be6af03b2b259e28c6677f3d79aa/src/Tokenizer/Parser/UserDefined.php#L50-L61
train
nilportugues/php-sql-query-formatter
src/Tokenizer/Tokenizer.php
Tokenizer.getNextTokenFromString
protected function getNextTokenFromString($string, $token, $cacheKey) { $token = $this->parseNextToken($string, $token); if ($cacheKey && \strlen($token[self::TOKEN_VALUE]) < $this->maxCacheKeySize) { $this->tokenCache[$cacheKey] = $token; } return $token; }
php
protected function getNextTokenFromString($string, $token, $cacheKey) { $token = $this->parseNextToken($string, $token); if ($cacheKey && \strlen($token[self::TOKEN_VALUE]) < $this->maxCacheKeySize) { $this->tokenCache[$cacheKey] = $token; } return $token; }
[ "protected", "function", "getNextTokenFromString", "(", "$", "string", ",", "$", "token", ",", "$", "cacheKey", ")", "{", "$", "token", "=", "$", "this", "->", "parseNextToken", "(", "$", "string", ",", "$", "token", ")", ";", "if", "(", "$", "cacheKey...
Get the next token and the token type and store it in cache. @param string $string @param string $token @param string $cacheKey @return array
[ "Get", "the", "next", "token", "and", "the", "token", "type", "and", "store", "it", "in", "cache", "." ]
865e9c13ff78be6af03b2b259e28c6677f3d79aa
https://github.com/nilportugues/php-sql-query-formatter/blob/865e9c13ff78be6af03b2b259e28c6677f3d79aa/src/Tokenizer/Tokenizer.php#L241-L250
train
megahertz/guzzle-tor
src/Middleware.php
Middleware.tor
public static function tor($proxy = '127.0.0.1:9050', $torControl = '127.0.0.1:9051') { return function (callable $handler) use ($proxy, $torControl) { return function ( RequestInterface $request, array $options ) use ($handler, $proxy, $torControl) { $options = array_replace_recursive([ 'proxy' => $proxy, 'curl' => [ CURLOPT_PROXYTYPE => CURLPROXY_SOCKS5_HOSTNAME ] ], $options); if (array_key_exists('tor_new_identity', $options) && $options['tor_new_identity']) { try { self::requireNewTorIdentity($torControl, $options); } catch (GuzzleException $e) { if (@$options['tor_new_identity_exception']) { throw $e; } } } return $handler($request, $options); }; }; }
php
public static function tor($proxy = '127.0.0.1:9050', $torControl = '127.0.0.1:9051') { return function (callable $handler) use ($proxy, $torControl) { return function ( RequestInterface $request, array $options ) use ($handler, $proxy, $torControl) { $options = array_replace_recursive([ 'proxy' => $proxy, 'curl' => [ CURLOPT_PROXYTYPE => CURLPROXY_SOCKS5_HOSTNAME ] ], $options); if (array_key_exists('tor_new_identity', $options) && $options['tor_new_identity']) { try { self::requireNewTorIdentity($torControl, $options); } catch (GuzzleException $e) { if (@$options['tor_new_identity_exception']) { throw $e; } } } return $handler($request, $options); }; }; }
[ "public", "static", "function", "tor", "(", "$", "proxy", "=", "'127.0.0.1:9050'", ",", "$", "torControl", "=", "'127.0.0.1:9051'", ")", "{", "return", "function", "(", "callable", "$", "handler", ")", "use", "(", "$", "proxy", ",", "$", "torControl", ")",...
This middleware allows to use Tor client as a proxy @param string $proxy Tor socks5 proxy host:port @param string $torControl Tor control host:port @return callable
[ "This", "middleware", "allows", "to", "use", "Tor", "client", "as", "a", "proxy" ]
ce58a86b912d4aaf7ccd126e12ef1d9966a82367
https://github.com/megahertz/guzzle-tor/blob/ce58a86b912d4aaf7ccd126e12ef1d9966a82367/src/Middleware.php#L20-L47
train
stekycz/Cronner
src/Cronner/TimestampStorage/FileStorage.php
FileStorage.setTaskName
public function setTaskName(string $taskName = NULL) { if ($taskName !== NULL && Strings::length($taskName) <= 0) { throw new InvalidTaskNameException('Given task name is not valid.'); } $this->taskName = $taskName; }
php
public function setTaskName(string $taskName = NULL) { if ($taskName !== NULL && Strings::length($taskName) <= 0) { throw new InvalidTaskNameException('Given task name is not valid.'); } $this->taskName = $taskName; }
[ "public", "function", "setTaskName", "(", "string", "$", "taskName", "=", "NULL", ")", "{", "if", "(", "$", "taskName", "!==", "NULL", "&&", "Strings", "::", "length", "(", "$", "taskName", ")", "<=", "0", ")", "{", "throw", "new", "InvalidTaskNameExcept...
Sets name of current task. @param string|null $taskName
[ "Sets", "name", "of", "current", "task", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/TimestampStorage/FileStorage.php#L48-L54
train
stekycz/Cronner
src/Cronner/TimestampStorage/FileStorage.php
FileStorage.saveRunTime
public function saveRunTime(DateTimeInterface $now) { $filepath = $this->buildFilePath(); file_put_contents($filepath, $now->format(self::DATETIME_FORMAT)); }
php
public function saveRunTime(DateTimeInterface $now) { $filepath = $this->buildFilePath(); file_put_contents($filepath, $now->format(self::DATETIME_FORMAT)); }
[ "public", "function", "saveRunTime", "(", "DateTimeInterface", "$", "now", ")", "{", "$", "filepath", "=", "$", "this", "->", "buildFilePath", "(", ")", ";", "file_put_contents", "(", "$", "filepath", ",", "$", "now", "->", "format", "(", "self", "::", "...
Saves current date and time as last invocation time. @param DateTimeInterface $now
[ "Saves", "current", "date", "and", "time", "as", "last", "invocation", "time", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/TimestampStorage/FileStorage.php#L61-L65
train
stekycz/Cronner
src/Cronner/TimestampStorage/FileStorage.php
FileStorage.loadLastRunTime
public function loadLastRunTime() { $date = NULL; $filepath = $this->buildFilePath(); if (file_exists($filepath)) { $date = file_get_contents($filepath); $date = DateTime::createFromFormat(self::DATETIME_FORMAT, $date); } return $date ? $date : NULL; }
php
public function loadLastRunTime() { $date = NULL; $filepath = $this->buildFilePath(); if (file_exists($filepath)) { $date = file_get_contents($filepath); $date = DateTime::createFromFormat(self::DATETIME_FORMAT, $date); } return $date ? $date : NULL; }
[ "public", "function", "loadLastRunTime", "(", ")", "{", "$", "date", "=", "NULL", ";", "$", "filepath", "=", "$", "this", "->", "buildFilePath", "(", ")", ";", "if", "(", "file_exists", "(", "$", "filepath", ")", ")", "{", "$", "date", "=", "file_get...
Returns date and time of last cron task invocation. @return DateTimeInterface|null
[ "Returns", "date", "and", "time", "of", "last", "cron", "task", "invocation", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/TimestampStorage/FileStorage.php#L72-L82
train
stekycz/Cronner
src/Cronner/TimestampStorage/FileStorage.php
FileStorage.buildFilePath
private function buildFilePath() : string { if ($this->taskName === NULL) { throw new EmptyTaskNameException('Task name was not set.'); } return SafeStream::PROTOCOL . '://' . $this->directory . '/' . sha1($this->taskName); }
php
private function buildFilePath() : string { if ($this->taskName === NULL) { throw new EmptyTaskNameException('Task name was not set.'); } return SafeStream::PROTOCOL . '://' . $this->directory . '/' . sha1($this->taskName); }
[ "private", "function", "buildFilePath", "(", ")", ":", "string", "{", "if", "(", "$", "this", "->", "taskName", "===", "NULL", ")", "{", "throw", "new", "EmptyTaskNameException", "(", "'Task name was not set.'", ")", ";", "}", "return", "SafeStream", "::", "...
Builds file path from directory and task name.
[ "Builds", "file", "path", "from", "directory", "and", "task", "name", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/TimestampStorage/FileStorage.php#L87-L94
train
stekycz/Cronner
src/Cronner/Tasks/Task.php
Task.shouldBeRun
public function shouldBeRun(DateTimeInterface $now = NULL) : bool { if ($now === NULL) { $now = new DateTime(); } $parameters = $this->getParameters(); if (!$parameters->isTask()) { return FALSE; } $this->timestampStorage->setTaskName($parameters->getName()); return $parameters->isInDay($now) && $parameters->isInTime($now) && $parameters->isNextPeriod($now, $this->timestampStorage->loadLastRunTime()); }
php
public function shouldBeRun(DateTimeInterface $now = NULL) : bool { if ($now === NULL) { $now = new DateTime(); } $parameters = $this->getParameters(); if (!$parameters->isTask()) { return FALSE; } $this->timestampStorage->setTaskName($parameters->getName()); return $parameters->isInDay($now) && $parameters->isInTime($now) && $parameters->isNextPeriod($now, $this->timestampStorage->loadLastRunTime()); }
[ "public", "function", "shouldBeRun", "(", "DateTimeInterface", "$", "now", "=", "NULL", ")", ":", "bool", "{", "if", "(", "$", "now", "===", "NULL", ")", "{", "$", "now", "=", "new", "DateTime", "(", ")", ";", "}", "$", "parameters", "=", "$", "thi...
Returns True if given parameters should be run.
[ "Returns", "True", "if", "given", "parameters", "should", "be", "run", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Tasks/Task.php#L71-L86
train
stekycz/Cronner
src/Cronner/Tasks/Task.php
Task.getParameters
private function getParameters() : Parameters { if ($this->parameters === NULL) { $this->parameters = new Parameters(Parameters::parseParameters($this->method)); } return $this->parameters; }
php
private function getParameters() : Parameters { if ($this->parameters === NULL) { $this->parameters = new Parameters(Parameters::parseParameters($this->method)); } return $this->parameters; }
[ "private", "function", "getParameters", "(", ")", ":", "Parameters", "{", "if", "(", "$", "this", "->", "parameters", "===", "NULL", ")", "{", "$", "this", "->", "parameters", "=", "new", "Parameters", "(", "Parameters", "::", "parseParameters", "(", "$", ...
Returns instance of parsed parameters.
[ "Returns", "instance", "of", "parsed", "parameters", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Tasks/Task.php#L104-L111
train
stekycz/Cronner
src/Cronner/Cronner.php
Cronner.setMaxExecutionTime
public function setMaxExecutionTime(int $maxExecutionTime = NULL) : self { if ($maxExecutionTime !== NULL && $maxExecutionTime <= 0) { throw new InvalidArgumentException("Max execution time must be NULL or non negative number."); } $this->maxExecutionTime = $maxExecutionTime; return $this; }
php
public function setMaxExecutionTime(int $maxExecutionTime = NULL) : self { if ($maxExecutionTime !== NULL && $maxExecutionTime <= 0) { throw new InvalidArgumentException("Max execution time must be NULL or non negative number."); } $this->maxExecutionTime = $maxExecutionTime; return $this; }
[ "public", "function", "setMaxExecutionTime", "(", "int", "$", "maxExecutionTime", "=", "NULL", ")", ":", "self", "{", "if", "(", "$", "maxExecutionTime", "!==", "NULL", "&&", "$", "maxExecutionTime", "<=", "0", ")", "{", "throw", "new", "InvalidArgumentExcepti...
Sets max execution time for Cronner. It is used only when Cronner runs. @param int|null $maxExecutionTime @return Cronner @throws InvalidArgumentException
[ "Sets", "max", "execution", "time", "for", "Cronner", ".", "It", "is", "used", "only", "when", "Cronner", "runs", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Cronner.php#L119-L127
train
stekycz/Cronner
src/Cronner/Cronner.php
Cronner.addTasks
public function addTasks($tasks) : self { $tasksId = $this->createIdFromObject($tasks); if (in_array($tasksId, $this->registeredTaskObjects)) { throw new InvalidArgumentException("Tasks with ID '" . $tasksId . "' have been already added."); } $reflection = new ClassType($tasks); $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { if (!Strings::startsWith($method->getName(), '__') && $method->hasAnnotation(Parameters::TASK)) { $task = new Task($tasks, $method, $this->timestampStorage); if (array_key_exists($task->getName(), $this->tasks)) { throw new DuplicateTaskNameException('Cannot use more tasks with the same name "' . $task->getName() . '".'); } $this->tasks[$task->getName()] = $task; } } $this->registeredTaskObjects[] = $tasksId; return $this; }
php
public function addTasks($tasks) : self { $tasksId = $this->createIdFromObject($tasks); if (in_array($tasksId, $this->registeredTaskObjects)) { throw new InvalidArgumentException("Tasks with ID '" . $tasksId . "' have been already added."); } $reflection = new ClassType($tasks); $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { if (!Strings::startsWith($method->getName(), '__') && $method->hasAnnotation(Parameters::TASK)) { $task = new Task($tasks, $method, $this->timestampStorage); if (array_key_exists($task->getName(), $this->tasks)) { throw new DuplicateTaskNameException('Cannot use more tasks with the same name "' . $task->getName() . '".'); } $this->tasks[$task->getName()] = $task; } } $this->registeredTaskObjects[] = $tasksId; return $this; }
[ "public", "function", "addTasks", "(", "$", "tasks", ")", ":", "self", "{", "$", "tasksId", "=", "$", "this", "->", "createIdFromObject", "(", "$", "tasks", ")", ";", "if", "(", "in_array", "(", "$", "tasksId", ",", "$", "this", "->", "registeredTaskOb...
Adds task case to be processed when cronner runs. If tasks with name which is already added are given then throws an exception. @param object $tasks @return Cronner @throws InvalidArgumentException
[ "Adds", "task", "case", "to", "be", "processed", "when", "cronner", "runs", ".", "If", "tasks", "with", "name", "which", "is", "already", "added", "are", "given", "then", "throws", "an", "exception", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Cronner.php#L158-L179
train
stekycz/Cronner
src/Cronner/Cronner.php
Cronner.run
public function run(DateTimeInterface $now = NULL) { if ($now === NULL) { $now = new DateTime(); } if ($this->maxExecutionTime !== NULL) { set_time_limit($this->maxExecutionTime); } foreach ($this->tasks as $task) { try { $name = $task->getName(); if ($task->shouldBeRun($now)) { if ($this->criticalSection->enter($name)) { $this->onTaskBegin($this, $task); $task($now); $this->onTaskFinished($this, $task); $this->criticalSection->leave($name); } } } catch (Exception $e) { $this->onTaskError($this, $e, $task); $name = $task->getName(); if ($this->criticalSection->isEntered($name)) { $this->criticalSection->leave($name); } if ($e instanceof RuntimeException) { throw $e; // Throw exception if it is Cronner Runtime exception } elseif ($this->skipFailedTask === FALSE) { throw $e; // Throw exception if failed task should not be skipped } } } }
php
public function run(DateTimeInterface $now = NULL) { if ($now === NULL) { $now = new DateTime(); } if ($this->maxExecutionTime !== NULL) { set_time_limit($this->maxExecutionTime); } foreach ($this->tasks as $task) { try { $name = $task->getName(); if ($task->shouldBeRun($now)) { if ($this->criticalSection->enter($name)) { $this->onTaskBegin($this, $task); $task($now); $this->onTaskFinished($this, $task); $this->criticalSection->leave($name); } } } catch (Exception $e) { $this->onTaskError($this, $e, $task); $name = $task->getName(); if ($this->criticalSection->isEntered($name)) { $this->criticalSection->leave($name); } if ($e instanceof RuntimeException) { throw $e; // Throw exception if it is Cronner Runtime exception } elseif ($this->skipFailedTask === FALSE) { throw $e; // Throw exception if failed task should not be skipped } } } }
[ "public", "function", "run", "(", "DateTimeInterface", "$", "now", "=", "NULL", ")", "{", "if", "(", "$", "now", "===", "NULL", ")", "{", "$", "now", "=", "new", "DateTime", "(", ")", ";", "}", "if", "(", "$", "this", "->", "maxExecutionTime", "!==...
Runs all cron tasks.
[ "Runs", "all", "cron", "tasks", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Cronner.php#L184-L217
train
stekycz/Cronner
src/Cronner/Tasks/Parameters.php
Parameters.isInDay
public function isInDay(DateTimeInterface $now) : bool { if (($days = $this->values[static::DAYS]) !== NULL) { return in_array($now->format('D'), $days); } return TRUE; }
php
public function isInDay(DateTimeInterface $now) : bool { if (($days = $this->values[static::DAYS]) !== NULL) { return in_array($now->format('D'), $days); } return TRUE; }
[ "public", "function", "isInDay", "(", "DateTimeInterface", "$", "now", ")", ":", "bool", "{", "if", "(", "(", "$", "days", "=", "$", "this", "->", "values", "[", "static", "::", "DAYS", "]", ")", "!==", "NULL", ")", "{", "return", "in_array", "(", ...
Returns true if today is allowed day of week.
[ "Returns", "true", "if", "today", "is", "allowed", "day", "of", "week", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Tasks/Parameters.php#L51-L58
train
stekycz/Cronner
src/Cronner/Tasks/Parameters.php
Parameters.isInTime
public function isInTime(DateTimeInterface $now) : bool { if ($times = $this->values[static::TIME]) { foreach ($times as $time) { if ($time['to'] && $time['to'] >= $now->format('H:i') && $time['from'] <= $now->format('H:i')) { // Is in range with precision to minutes return TRUE; } elseif ($time['from'] == $now->format('H:i')) { // Is in specific minute return TRUE; } } return FALSE; } return TRUE; }
php
public function isInTime(DateTimeInterface $now) : bool { if ($times = $this->values[static::TIME]) { foreach ($times as $time) { if ($time['to'] && $time['to'] >= $now->format('H:i') && $time['from'] <= $now->format('H:i')) { // Is in range with precision to minutes return TRUE; } elseif ($time['from'] == $now->format('H:i')) { // Is in specific minute return TRUE; } } return FALSE; } return TRUE; }
[ "public", "function", "isInTime", "(", "DateTimeInterface", "$", "now", ")", ":", "bool", "{", "if", "(", "$", "times", "=", "$", "this", "->", "values", "[", "static", "::", "TIME", "]", ")", "{", "foreach", "(", "$", "times", "as", "$", "time", "...
Returns true if current time is in allowed range.
[ "Returns", "true", "if", "current", "time", "is", "in", "allowed", "range", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Tasks/Parameters.php#L63-L80
train
stekycz/Cronner
src/Cronner/Tasks/Parameters.php
Parameters.isNextPeriod
public function isNextPeriod(DateTimeInterface $now, DateTimeInterface $lastRunTime = NULL) : bool { if ( $lastRunTime !== NULL && !$lastRunTime instanceof \DateTimeImmutable && !$lastRunTime instanceof \DateTime ) { throw new InvalidArgumentException; } if (isset($this->values[static::PERIOD]) && $this->values[static::PERIOD]) { // Prevent run task on next cronner run because of a few seconds shift $now = Nette\Utils\DateTime::from($now)->modifyClone('+5 seconds'); return $lastRunTime === NULL || $lastRunTime->modify('+ ' . $this->values[static::PERIOD]) <= $now; } return TRUE; }
php
public function isNextPeriod(DateTimeInterface $now, DateTimeInterface $lastRunTime = NULL) : bool { if ( $lastRunTime !== NULL && !$lastRunTime instanceof \DateTimeImmutable && !$lastRunTime instanceof \DateTime ) { throw new InvalidArgumentException; } if (isset($this->values[static::PERIOD]) && $this->values[static::PERIOD]) { // Prevent run task on next cronner run because of a few seconds shift $now = Nette\Utils\DateTime::from($now)->modifyClone('+5 seconds'); return $lastRunTime === NULL || $lastRunTime->modify('+ ' . $this->values[static::PERIOD]) <= $now; } return TRUE; }
[ "public", "function", "isNextPeriod", "(", "DateTimeInterface", "$", "now", ",", "DateTimeInterface", "$", "lastRunTime", "=", "NULL", ")", ":", "bool", "{", "if", "(", "$", "lastRunTime", "!==", "NULL", "&&", "!", "$", "lastRunTime", "instanceof", "\\", "Da...
Returns true if current time is next period of invocation.
[ "Returns", "true", "if", "current", "time", "is", "next", "period", "of", "invocation", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Tasks/Parameters.php#L85-L103
train
stekycz/Cronner
src/Cronner/Tasks/Parameters.php
Parameters.parseParameters
public static function parseParameters(Method $method) : array { $taskName = NULL; if ($method->hasAnnotation(Parameters::TASK)) { $className = $method->getDeclaringClass()->getName(); $methodName = $method->getName(); $taskName = $className . ' - ' . $methodName; } $taskAnnotation = $method->getAnnotation(Parameters::TASK); $parameters = [ static::TASK => is_string($taskAnnotation) ? Parser::parseName($taskAnnotation) : $taskName, static::PERIOD => $method->hasAnnotation(Parameters::PERIOD) ? Parser::parsePeriod((string) $method->getAnnotation(Parameters::PERIOD)) : NULL, static::DAYS => $method->hasAnnotation(Parameters::DAYS) ? Parser::parseDays((string) $method->getAnnotation(Parameters::DAYS)) : NULL, static::TIME => $method->hasAnnotation(Parameters::TIME) ? Parser::parseTimes((string) $method->getAnnotation(Parameters::TIME)) : NULL, ]; return $parameters; }
php
public static function parseParameters(Method $method) : array { $taskName = NULL; if ($method->hasAnnotation(Parameters::TASK)) { $className = $method->getDeclaringClass()->getName(); $methodName = $method->getName(); $taskName = $className . ' - ' . $methodName; } $taskAnnotation = $method->getAnnotation(Parameters::TASK); $parameters = [ static::TASK => is_string($taskAnnotation) ? Parser::parseName($taskAnnotation) : $taskName, static::PERIOD => $method->hasAnnotation(Parameters::PERIOD) ? Parser::parsePeriod((string) $method->getAnnotation(Parameters::PERIOD)) : NULL, static::DAYS => $method->hasAnnotation(Parameters::DAYS) ? Parser::parseDays((string) $method->getAnnotation(Parameters::DAYS)) : NULL, static::TIME => $method->hasAnnotation(Parameters::TIME) ? Parser::parseTimes((string) $method->getAnnotation(Parameters::TIME)) : NULL, ]; return $parameters; }
[ "public", "static", "function", "parseParameters", "(", "Method", "$", "method", ")", ":", "array", "{", "$", "taskName", "=", "NULL", ";", "if", "(", "$", "method", "->", "hasAnnotation", "(", "Parameters", "::", "TASK", ")", ")", "{", "$", "className",...
Parse cronner values from annotations.
[ "Parse", "cronner", "values", "from", "annotations", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Tasks/Parameters.php#L108-L135
train
stekycz/Cronner
src/Cronner/Tasks/Parser.php
Parser.parseName
public static function parseName(string $annotation) { $name = Strings::trim($annotation); $name = Strings::length($name) > 0 ? $name : NULL; return $name; }
php
public static function parseName(string $annotation) { $name = Strings::trim($annotation); $name = Strings::length($name) > 0 ? $name : NULL; return $name; }
[ "public", "static", "function", "parseName", "(", "string", "$", "annotation", ")", "{", "$", "name", "=", "Strings", "::", "trim", "(", "$", "annotation", ")", ";", "$", "name", "=", "Strings", "::", "length", "(", "$", "name", ")", ">", "0", "?", ...
Parses name of cron task. @param string $annotation @return string|null
[ "Parses", "name", "of", "cron", "task", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Tasks/Parser.php#L20-L26
train
stekycz/Cronner
src/Cronner/Tasks/Parser.php
Parser.parsePeriod
public static function parsePeriod(string $annotation) { $period = NULL; $annotation = Strings::trim($annotation); if (Strings::length($annotation)) { if (strtotime('+ ' . $annotation) === FALSE) { throw new InvalidParameterException( "Given period parameter '" . $annotation . "' must be valid for strtotime() with '+' sign as its prefix (added by Cronner automatically)." ); } $period = $annotation; } return $period ?: NULL; }
php
public static function parsePeriod(string $annotation) { $period = NULL; $annotation = Strings::trim($annotation); if (Strings::length($annotation)) { if (strtotime('+ ' . $annotation) === FALSE) { throw new InvalidParameterException( "Given period parameter '" . $annotation . "' must be valid for strtotime() with '+' sign as its prefix (added by Cronner automatically)." ); } $period = $annotation; } return $period ?: NULL; }
[ "public", "static", "function", "parsePeriod", "(", "string", "$", "annotation", ")", "{", "$", "period", "=", "NULL", ";", "$", "annotation", "=", "Strings", "::", "trim", "(", "$", "annotation", ")", ";", "if", "(", "Strings", "::", "length", "(", "$...
Parses period of cron task. If annotation is invalid throws exception. @param string $annotation @return string|null @throws InvalidParameterException
[ "Parses", "period", "of", "cron", "task", ".", "If", "annotation", "is", "invalid", "throws", "exception", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Tasks/Parser.php#L35-L49
train
stekycz/Cronner
src/Cronner/Tasks/Parser.php
Parser.parseDays
public static function parseDays(string $annotation) { static $validValues = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun',]; $days = NULL; $annotation = Strings::trim($annotation); if (Strings::length($annotation)) { $days = static::translateToDayNames($annotation); $days = static::expandDaysRange($days); foreach ($days as $day) { if (!in_array($day, $validValues)) { throw new InvalidParameterException( "Given day parameter '" . $day . "' must be one from " . implode(', ', $validValues) . "." ); } } $days = array_values(array_intersect($validValues, $days)); } return $days ?: NULL; }
php
public static function parseDays(string $annotation) { static $validValues = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun',]; $days = NULL; $annotation = Strings::trim($annotation); if (Strings::length($annotation)) { $days = static::translateToDayNames($annotation); $days = static::expandDaysRange($days); foreach ($days as $day) { if (!in_array($day, $validValues)) { throw new InvalidParameterException( "Given day parameter '" . $day . "' must be one from " . implode(', ', $validValues) . "." ); } } $days = array_values(array_intersect($validValues, $days)); } return $days ?: NULL; }
[ "public", "static", "function", "parseDays", "(", "string", "$", "annotation", ")", "{", "static", "$", "validValues", "=", "[", "'Mon'", ",", "'Tue'", ",", "'Wed'", ",", "'Thu'", ",", "'Fri'", ",", "'Sat'", ",", "'Sun'", ",", "]", ";", "$", "days", ...
Parses allowed days for cron task. If annotation is invalid throws exception. @param string $annotation @return string[]|null @throws InvalidParameterException
[ "Parses", "allowed", "days", "for", "cron", "task", ".", "If", "annotation", "is", "invalid", "throws", "exception", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Tasks/Parser.php#L59-L79
train
stekycz/Cronner
src/Cronner/Tasks/Parser.php
Parser.parseTimes
public static function parseTimes(string $annotation) { $times = NULL; $annotation = Strings::trim($annotation); if (Strings::length($annotation)) { if ($values = static::splitMultipleValues($annotation)) { $times = []; foreach ($values as $time) { $times = array_merge($times, static::parseOneTime($time)); } usort($times, function ($a, $b) { return $a < $b ? -1 : ($a > $b ? 1 : 0); }); } } return $times ?: NULL; }
php
public static function parseTimes(string $annotation) { $times = NULL; $annotation = Strings::trim($annotation); if (Strings::length($annotation)) { if ($values = static::splitMultipleValues($annotation)) { $times = []; foreach ($values as $time) { $times = array_merge($times, static::parseOneTime($time)); } usort($times, function ($a, $b) { return $a < $b ? -1 : ($a > $b ? 1 : 0); }); } } return $times ?: NULL; }
[ "public", "static", "function", "parseTimes", "(", "string", "$", "annotation", ")", "{", "$", "times", "=", "NULL", ";", "$", "annotation", "=", "Strings", "::", "trim", "(", "$", "annotation", ")", ";", "if", "(", "Strings", "::", "length", "(", "$",...
Parses allowed time ranges for cron task. If annotation is invalid throws exception. @param string $annotation @return string[][]|null @throws InvalidParameterException
[ "Parses", "allowed", "time", "ranges", "for", "cron", "task", ".", "If", "annotation", "is", "invalid", "throws", "exception", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Tasks/Parser.php#L89-L106
train
stekycz/Cronner
src/Cronner/Tasks/Parser.php
Parser.expandDaysRange
private static function expandDaysRange(array $days) : array { static $dayNames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun',]; $expandedValues = []; foreach ($days as $day) { if (Strings::match($day, '~^\w{3}\s*-\s*\w{3}$~u')) { list($begin, $end) = Strings::split($day, '~\s*-\s*~'); $started = FALSE; foreach ($dayNames as $dayName) { if ($dayName === $begin) { $started = TRUE; } if ($started) { $expandedValues[] = $dayName; } if ($dayName === $end) { $started = FALSE; } } } else { $expandedValues[] = $day; } } return array_unique($expandedValues); }
php
private static function expandDaysRange(array $days) : array { static $dayNames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun',]; $expandedValues = []; foreach ($days as $day) { if (Strings::match($day, '~^\w{3}\s*-\s*\w{3}$~u')) { list($begin, $end) = Strings::split($day, '~\s*-\s*~'); $started = FALSE; foreach ($dayNames as $dayName) { if ($dayName === $begin) { $started = TRUE; } if ($started) { $expandedValues[] = $dayName; } if ($dayName === $end) { $started = FALSE; } } } else { $expandedValues[] = $day; } } return array_unique($expandedValues); }
[ "private", "static", "function", "expandDaysRange", "(", "array", "$", "days", ")", ":", "array", "{", "static", "$", "dayNames", "=", "[", "'Mon'", ",", "'Tue'", ",", "'Wed'", ",", "'Thu'", ",", "'Fri'", ",", "'Sat'", ",", "'Sun'", ",", "]", ";", "$...
Expands given day names and day ranges to day names only. The day range must be in "Mon-Fri" format. @param string[] $days @return string[]
[ "Expands", "given", "day", "names", "and", "day", "ranges", "to", "day", "names", "only", ".", "The", "day", "range", "must", "be", "in", "Mon", "-", "Fri", "format", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Tasks/Parser.php#L144-L170
train
stekycz/Cronner
src/Cronner/Tasks/Parser.php
Parser.parseOneTime
private static function parseOneTime(string $time) : array { $time = static::translateToTimes($time); $parts = Strings::split($time, '/\s*-\s*/'); if (!static::isValidTime($parts[0]) || (isset($parts[1]) && !static::isValidTime($parts[1]))) { throw new InvalidParameterException( "Times annotation is not in valid format. It must looks like 'hh:mm[ - hh:mm]' but '" . $time . "' was given." ); } $times = []; if (static::isTimeOverMidnight($parts[0], isset($parts[1]) ? $parts[1] : NULL)) { $times[] = static::timePartsToArray('00:00', $parts[1]); $times[] = static::timePartsToArray($parts[0], '23:59'); } else { $times[] = static::timePartsToArray($parts[0], isset($parts[1]) ? $parts[1] : NULL); } return $times; }
php
private static function parseOneTime(string $time) : array { $time = static::translateToTimes($time); $parts = Strings::split($time, '/\s*-\s*/'); if (!static::isValidTime($parts[0]) || (isset($parts[1]) && !static::isValidTime($parts[1]))) { throw new InvalidParameterException( "Times annotation is not in valid format. It must looks like 'hh:mm[ - hh:mm]' but '" . $time . "' was given." ); } $times = []; if (static::isTimeOverMidnight($parts[0], isset($parts[1]) ? $parts[1] : NULL)) { $times[] = static::timePartsToArray('00:00', $parts[1]); $times[] = static::timePartsToArray($parts[0], '23:59'); } else { $times[] = static::timePartsToArray($parts[0], isset($parts[1]) ? $parts[1] : NULL); } return $times; }
[ "private", "static", "function", "parseOneTime", "(", "string", "$", "time", ")", ":", "array", "{", "$", "time", "=", "static", "::", "translateToTimes", "(", "$", "time", ")", ";", "$", "parts", "=", "Strings", "::", "split", "(", "$", "time", ",", ...
Parses one time annotation. If it is invalid throws exception. @param string $time @return string[][] @throws InvalidParameterException
[ "Parses", "one", "time", "annotation", ".", "If", "it", "is", "invalid", "throws", "exception", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Tasks/Parser.php#L198-L216
train
stekycz/Cronner
src/Cronner/Tasks/Parser.php
Parser.isTimeOverMidnight
private static function isTimeOverMidnight(string $from, string $to = NULL) : bool { return $to !== NULL && $to < $from; }
php
private static function isTimeOverMidnight(string $from, string $to = NULL) : bool { return $to !== NULL && $to < $from; }
[ "private", "static", "function", "isTimeOverMidnight", "(", "string", "$", "from", ",", "string", "$", "to", "=", "NULL", ")", ":", "bool", "{", "return", "$", "to", "!==", "NULL", "&&", "$", "to", "<", "$", "from", ";", "}" ]
Returns True if given times includes midnight, False otherwise.
[ "Returns", "True", "if", "given", "times", "includes", "midnight", "False", "otherwise", "." ]
86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c
https://github.com/stekycz/Cronner/blob/86c0d54fd88f7f8ffe7a47e60b17d604cc25cd3c/src/Cronner/Tasks/Parser.php#L238-L241
train
cartalyst/converter
src/Converter.php
Converter.format
public function format($measurement = null) { // Get the value $value = $this->getValue(); // Do we have a negative value? $negative = $value < 0; // Switch to negative format $format = $negative ? 'negative' : 'format'; // Get the measurement format $measurement = $measurement ?: $this->getMeasurement("{$this->to}.{$format}"); // Value Regex $valRegex = '/([0-9].*|)[0-9]/'; // Match decimal and thousand separators preg_match_all('/[,.!]/', $measurement, $separators); if ($thousand = array_get($separators, '0.0', null)) { if ($thousand == '!') { $thousand = ''; } } $decimal = array_get($separators, '0.1', null); // Match format for decimals count preg_match($valRegex, $measurement, $valFormat); $valFormat = array_get($valFormat, 0, 0); // Count decimals length $decimals = $decimal ? strlen(substr(strrchr($valFormat, $decimal), 1)) : 0; // Strip negative sign if ($negative) { $value *= -1; } // Format the value $value = number_format($value, $decimals, $decimal, $thousand); // Return the formatted measurement return preg_replace($valRegex, $value, $measurement); }
php
public function format($measurement = null) { // Get the value $value = $this->getValue(); // Do we have a negative value? $negative = $value < 0; // Switch to negative format $format = $negative ? 'negative' : 'format'; // Get the measurement format $measurement = $measurement ?: $this->getMeasurement("{$this->to}.{$format}"); // Value Regex $valRegex = '/([0-9].*|)[0-9]/'; // Match decimal and thousand separators preg_match_all('/[,.!]/', $measurement, $separators); if ($thousand = array_get($separators, '0.0', null)) { if ($thousand == '!') { $thousand = ''; } } $decimal = array_get($separators, '0.1', null); // Match format for decimals count preg_match($valRegex, $measurement, $valFormat); $valFormat = array_get($valFormat, 0, 0); // Count decimals length $decimals = $decimal ? strlen(substr(strrchr($valFormat, $decimal), 1)) : 0; // Strip negative sign if ($negative) { $value *= -1; } // Format the value $value = number_format($value, $decimals, $decimal, $thousand); // Return the formatted measurement return preg_replace($valRegex, $value, $measurement); }
[ "public", "function", "format", "(", "$", "measurement", "=", "null", ")", "{", "// Get the value", "$", "value", "=", "$", "this", "->", "getValue", "(", ")", ";", "// Do we have a negative value?", "$", "negative", "=", "$", "value", "<", "0", ";", "// S...
Format the value into the desired measurement. @param string $measurement @return string
[ "Format", "the", "value", "into", "the", "desired", "measurement", "." ]
fc4d047bf4f17a63470e0703a0f2ae8ef3f6345c
https://github.com/cartalyst/converter/blob/fc4d047bf4f17a63470e0703a0f2ae8ef3f6345c/src/Converter.php#L174-L220
train
cartalyst/converter
src/Converter.php
Converter.getMeasurement
public function getMeasurement($measurement, $default = null) { $measurements = $this->getMeasurements(); $measure = array_get($measurements, $measurement, $default); if (is_null($measure)) { if (str_contains($measurement, 'negative')) { return '-' . $this->getMeasurement(str_replace('negative', 'format', $measurement)); } if (str_contains($measurement, 'currency')) { $currency = explode('.', $measurement); return $this->exchanger->get($currency[1]); } throw new Exception("Measurement [{$measurement}] was not found."); } return $measure; }
php
public function getMeasurement($measurement, $default = null) { $measurements = $this->getMeasurements(); $measure = array_get($measurements, $measurement, $default); if (is_null($measure)) { if (str_contains($measurement, 'negative')) { return '-' . $this->getMeasurement(str_replace('negative', 'format', $measurement)); } if (str_contains($measurement, 'currency')) { $currency = explode('.', $measurement); return $this->exchanger->get($currency[1]); } throw new Exception("Measurement [{$measurement}] was not found."); } return $measure; }
[ "public", "function", "getMeasurement", "(", "$", "measurement", ",", "$", "default", "=", "null", ")", "{", "$", "measurements", "=", "$", "this", "->", "getMeasurements", "(", ")", ";", "$", "measure", "=", "array_get", "(", "$", "measurements", ",", "...
Returns information about the given measurement. @param string $measurement @param mixed $default @return mixed @throws \Exception
[ "Returns", "information", "about", "the", "given", "measurement", "." ]
fc4d047bf4f17a63470e0703a0f2ae8ef3f6345c
https://github.com/cartalyst/converter/blob/fc4d047bf4f17a63470e0703a0f2ae8ef3f6345c/src/Converter.php#L253-L274
train
steos/php-quickcheck
src/QCheck/Random.php
Random.int_add
public static function int_add($x, $y) { if ($y == 0) { return $x; } else { return self::int_add($x ^ $y, ($x & $y) << 1); } }
php
public static function int_add($x, $y) { if ($y == 0) { return $x; } else { return self::int_add($x ^ $y, ($x & $y) << 1); } }
[ "public", "static", "function", "int_add", "(", "$", "x", ",", "$", "y", ")", "{", "if", "(", "$", "y", "==", "0", ")", "{", "return", "$", "x", ";", "}", "else", "{", "return", "self", "::", "int_add", "(", "$", "x", "^", "$", "y", ",", "(...
addition with only shifts and ands
[ "addition", "with", "only", "shifts", "and", "ands" ]
11f6f8e33f6d04452bca2ab510dc457fe8267773
https://github.com/steos/php-quickcheck/blob/11f6f8e33f6d04452bca2ab510dc457fe8267773/src/QCheck/Random.php#L80-L87
train
steos/php-quickcheck
src/QCheck/Generator.php
Generator.sequence
private static function sequence($ms) { return FP::reduce( function (Generator $acc, Generator $elem) { return $acc->bindGen(function ($xs) use ($elem) { return $elem->bindGen(function ($y) use ($xs) { return self::pureGen(FP::push($xs, $y)); }); }); }, $ms, self::pureGen([]) ); }
php
private static function sequence($ms) { return FP::reduce( function (Generator $acc, Generator $elem) { return $acc->bindGen(function ($xs) use ($elem) { return $elem->bindGen(function ($y) use ($xs) { return self::pureGen(FP::push($xs, $y)); }); }); }, $ms, self::pureGen([]) ); }
[ "private", "static", "function", "sequence", "(", "$", "ms", ")", "{", "return", "FP", "::", "reduce", "(", "function", "(", "Generator", "$", "acc", ",", "Generator", "$", "elem", ")", "{", "return", "$", "acc", "->", "bindGen", "(", "function", "(", ...
turns a list of generators into a generator of a list @param Generator[]|\Iterator $ms @return Generator
[ "turns", "a", "list", "of", "generators", "into", "a", "generator", "of", "a", "list" ]
11f6f8e33f6d04452bca2ab510dc457fe8267773
https://github.com/steos/php-quickcheck/blob/11f6f8e33f6d04452bca2ab510dc457fe8267773/src/QCheck/Generator.php#L60-L73
train
steos/php-quickcheck
src/QCheck/Generator.php
Generator.fmap
public function fmap(callable $f) { return $this->fmapGen(function (RoseTree $rose) use ($f) { return $rose->fmap($f); }); }
php
public function fmap(callable $f) { return $this->fmapGen(function (RoseTree $rose) use ($f) { return $rose->fmap($f); }); }
[ "public", "function", "fmap", "(", "callable", "$", "f", ")", "{", "return", "$", "this", "->", "fmapGen", "(", "function", "(", "RoseTree", "$", "rose", ")", "use", "(", "$", "f", ")", "{", "return", "$", "rose", "->", "fmap", "(", "$", "f", ")"...
maps function f over the values produced by this generator @param callable $f @return Generator
[ "maps", "function", "f", "over", "the", "values", "produced", "by", "this", "generator" ]
11f6f8e33f6d04452bca2ab510dc457fe8267773
https://github.com/steos/php-quickcheck/blob/11f6f8e33f6d04452bca2ab510dc457fe8267773/src/QCheck/Generator.php#L81-L86
train
steos/php-quickcheck
src/QCheck/Generator.php
Generator.tuples
public static function tuples() { $seq = self::sequence(self::getArgs(func_get_args())); return $seq->bindGen(function ($roses) { return self::pureGen(RoseTree::zip(FP::args(), $roses)); }); }
php
public static function tuples() { $seq = self::sequence(self::getArgs(func_get_args())); return $seq->bindGen(function ($roses) { return self::pureGen(RoseTree::zip(FP::args(), $roses)); }); }
[ "public", "static", "function", "tuples", "(", ")", "{", "$", "seq", "=", "self", "::", "sequence", "(", "self", "::", "getArgs", "(", "func_get_args", "(", ")", ")", ")", ";", "return", "$", "seq", "->", "bindGen", "(", "function", "(", "$", "roses"...
creates a new generator that returns an array whose elements are chosen from the list of given generators. Individual elements shrink according to their generator but the array will never shrink in count. Accepts either a variadic number of args or a single array of generators. Example: Gen::tuples(Gen::booleans(), Gen::ints()) Gen::tuples([Gen::booleans(), Gen::ints()]) @return Generator
[ "creates", "a", "new", "generator", "that", "returns", "an", "array", "whose", "elements", "are", "chosen", "from", "the", "list", "of", "given", "generators", ".", "Individual", "elements", "shrink", "according", "to", "their", "generator", "but", "the", "arr...
11f6f8e33f6d04452bca2ab510dc457fe8267773
https://github.com/steos/php-quickcheck/blob/11f6f8e33f6d04452bca2ab510dc457fe8267773/src/QCheck/Generator.php#L254-L260
train
steos/php-quickcheck
src/QCheck/Generator.php
Generator.alphaNumChars
public static function alphaNumChars() { return self::oneOf( self::choose(48, 57), self::choose(65, 90), self::choose(97, 122) )->fmap('chr'); }
php
public static function alphaNumChars() { return self::oneOf( self::choose(48, 57), self::choose(65, 90), self::choose(97, 122) )->fmap('chr'); }
[ "public", "static", "function", "alphaNumChars", "(", ")", "{", "return", "self", "::", "oneOf", "(", "self", "::", "choose", "(", "48", ",", "57", ")", ",", "self", "::", "choose", "(", "65", ",", "90", ")", ",", "self", "::", "choose", "(", "97",...
creates a generator that produces alphanumeric characters @return Generator
[ "creates", "a", "generator", "that", "produces", "alphanumeric", "characters" ]
11f6f8e33f6d04452bca2ab510dc457fe8267773
https://github.com/steos/php-quickcheck/blob/11f6f8e33f6d04452bca2ab510dc457fe8267773/src/QCheck/Generator.php#L331-L338
train