repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
shabbyrobe/amiss
src/Sql/Manager.php
Manager.updateTable
public function updateTable($meta, ...$args) { $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta; if (!$meta->canUpdate) { throw new Exception("Meta {$meta->id} prohibits update"); } $query = Query\Update::fromParamArgs($args); if (!$query->set) { throw new \InvalidArgumentException("Query missing 'set' values"); } list ($sql, $params, $setProps, $whereProps) = $query->buildQuery($meta); if ($setProps) { $params = $this->mapper->formatParams($meta, $setProps, $params); } if ($whereProps) { $params = $this->mapper->formatParams($meta, $whereProps, $params); } return $this->getConnector()->exec($sql, $params); }
php
public function updateTable($meta, ...$args) { $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta; if (!$meta->canUpdate) { throw new Exception("Meta {$meta->id} prohibits update"); } $query = Query\Update::fromParamArgs($args); if (!$query->set) { throw new \InvalidArgumentException("Query missing 'set' values"); } list ($sql, $params, $setProps, $whereProps) = $query->buildQuery($meta); if ($setProps) { $params = $this->mapper->formatParams($meta, $setProps, $params); } if ($whereProps) { $params = $this->mapper->formatParams($meta, $whereProps, $params); } return $this->getConnector()->exec($sql, $params); }
[ "public", "function", "updateTable", "(", "$", "meta", ",", "...", "$", "args", ")", "{", "$", "meta", "=", "!", "$", "meta", "instanceof", "Meta", "?", "$", "this", "->", "mapper", "->", "getMeta", "(", "$", "meta", ")", ":", "$", "meta", ";", "if", "(", "!", "$", "meta", "->", "canUpdate", ")", "{", "throw", "new", "Exception", "(", "\"Meta {$meta->id} prohibits update\"", ")", ";", "}", "$", "query", "=", "Query", "\\", "Update", "::", "fromParamArgs", "(", "$", "args", ")", ";", "if", "(", "!", "$", "query", "->", "set", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Query missing 'set' values\"", ")", ";", "}", "list", "(", "$", "sql", ",", "$", "params", ",", "$", "setProps", ",", "$", "whereProps", ")", "=", "$", "query", "->", "buildQuery", "(", "$", "meta", ")", ";", "if", "(", "$", "setProps", ")", "{", "$", "params", "=", "$", "this", "->", "mapper", "->", "formatParams", "(", "$", "meta", ",", "$", "setProps", ",", "$", "params", ")", ";", "}", "if", "(", "$", "whereProps", ")", "{", "$", "params", "=", "$", "this", "->", "mapper", "->", "formatParams", "(", "$", "meta", ",", "$", "whereProps", ",", "$", "params", ")", ";", "}", "return", "$", "this", "->", "getConnector", "(", ")", "->", "exec", "(", "$", "sql", ",", "$", "params", ")", ";", "}" ]
Update a table by criteria. updateTable ( $meta , array $values , $criteria... ) updateTable ( $meta , Query\Update $query , $criteria... ) @return void
[ "Update", "a", "table", "by", "criteria", "." ]
train
https://github.com/shabbyrobe/amiss/blob/ba261f0d1f985ed36e9fd2903ac0df86c5b9498d/src/Sql/Manager.php#L644-L665
shabbyrobe/amiss
src/Sql/Manager.php
Manager.update
public function update($object, $meta=null) { $query = new Query\Update(); if (!is_object($object)) { throw new \BadMethodCallException("Please use updateTable()"); } if ($meta) { $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta; } else { $meta = $this->mapper->getMeta(get_class($object)); } if (!$meta->primary) { throw new Exception("Cannot update: meta {$meta->id} has no primary key"); } if (!$meta->canUpdate) { throw new Exception("Meta {$meta->id} prohibits update"); } event_before: { if (isset($meta->on['beforeUpdate'])) { foreach ($meta->on['beforeUpdate'] as $cb) { $cb = [$object, $cb]; $cb(); } } if (isset($this->on['beforeUpdate'])) { foreach ($this->on['beforeUpdate'] as $cb) { $cb($object, $meta); } } } query: { $query->set = $this->mapper->mapObjectToRow($object, $meta, 'update'); $query->where = $meta->getIndexValue($object); list ($sql, $params, $props) = $query->buildQuery($meta); // don't need to do formatParams - it's already covered by the mapPropertiesToRow call in // table update mode $return = $this->getConnector()->exec($sql, $params); } event_after: { if (isset($meta->on['afterUpdate'])) { foreach ($meta->on['afterUpdate'] as $cb) { $cb = [$object, $cb]; $cb(); } } if (isset($this->on['afterUpdate'])) { foreach ($this->on['afterUpdate'] as $cb) { $cb($object, $meta); } } } return $return; }
php
public function update($object, $meta=null) { $query = new Query\Update(); if (!is_object($object)) { throw new \BadMethodCallException("Please use updateTable()"); } if ($meta) { $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta; } else { $meta = $this->mapper->getMeta(get_class($object)); } if (!$meta->primary) { throw new Exception("Cannot update: meta {$meta->id} has no primary key"); } if (!$meta->canUpdate) { throw new Exception("Meta {$meta->id} prohibits update"); } event_before: { if (isset($meta->on['beforeUpdate'])) { foreach ($meta->on['beforeUpdate'] as $cb) { $cb = [$object, $cb]; $cb(); } } if (isset($this->on['beforeUpdate'])) { foreach ($this->on['beforeUpdate'] as $cb) { $cb($object, $meta); } } } query: { $query->set = $this->mapper->mapObjectToRow($object, $meta, 'update'); $query->where = $meta->getIndexValue($object); list ($sql, $params, $props) = $query->buildQuery($meta); // don't need to do formatParams - it's already covered by the mapPropertiesToRow call in // table update mode $return = $this->getConnector()->exec($sql, $params); } event_after: { if (isset($meta->on['afterUpdate'])) { foreach ($meta->on['afterUpdate'] as $cb) { $cb = [$object, $cb]; $cb(); } } if (isset($this->on['afterUpdate'])) { foreach ($this->on['afterUpdate'] as $cb) { $cb($object, $meta); } } } return $return; }
[ "public", "function", "update", "(", "$", "object", ",", "$", "meta", "=", "null", ")", "{", "$", "query", "=", "new", "Query", "\\", "Update", "(", ")", ";", "if", "(", "!", "is_object", "(", "$", "object", ")", ")", "{", "throw", "new", "\\", "BadMethodCallException", "(", "\"Please use updateTable()\"", ")", ";", "}", "if", "(", "$", "meta", ")", "{", "$", "meta", "=", "!", "$", "meta", "instanceof", "Meta", "?", "$", "this", "->", "mapper", "->", "getMeta", "(", "$", "meta", ")", ":", "$", "meta", ";", "}", "else", "{", "$", "meta", "=", "$", "this", "->", "mapper", "->", "getMeta", "(", "get_class", "(", "$", "object", ")", ")", ";", "}", "if", "(", "!", "$", "meta", "->", "primary", ")", "{", "throw", "new", "Exception", "(", "\"Cannot update: meta {$meta->id} has no primary key\"", ")", ";", "}", "if", "(", "!", "$", "meta", "->", "canUpdate", ")", "{", "throw", "new", "Exception", "(", "\"Meta {$meta->id} prohibits update\"", ")", ";", "}", "event_before", ":", "{", "if", "(", "isset", "(", "$", "meta", "->", "on", "[", "'beforeUpdate'", "]", ")", ")", "{", "foreach", "(", "$", "meta", "->", "on", "[", "'beforeUpdate'", "]", "as", "$", "cb", ")", "{", "$", "cb", "=", "[", "$", "object", ",", "$", "cb", "]", ";", "$", "cb", "(", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "this", "->", "on", "[", "'beforeUpdate'", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "on", "[", "'beforeUpdate'", "]", "as", "$", "cb", ")", "{", "$", "cb", "(", "$", "object", ",", "$", "meta", ")", ";", "}", "}", "}", "query", ":", "{", "$", "query", "->", "set", "=", "$", "this", "->", "mapper", "->", "mapObjectToRow", "(", "$", "object", ",", "$", "meta", ",", "'update'", ")", ";", "$", "query", "->", "where", "=", "$", "meta", "->", "getIndexValue", "(", "$", "object", ")", ";", "list", "(", "$", "sql", ",", "$", "params", ",", "$", "props", ")", "=", "$", "query", "->", "buildQuery", "(", "$", "meta", ")", ";", "// don't need to do formatParams - it's already covered by the mapPropertiesToRow call in", "// table update mode", "$", "return", "=", "$", "this", "->", "getConnector", "(", ")", "->", "exec", "(", "$", "sql", ",", "$", "params", ")", ";", "}", "event_after", ":", "{", "if", "(", "isset", "(", "$", "meta", "->", "on", "[", "'afterUpdate'", "]", ")", ")", "{", "foreach", "(", "$", "meta", "->", "on", "[", "'afterUpdate'", "]", "as", "$", "cb", ")", "{", "$", "cb", "=", "[", "$", "object", ",", "$", "cb", "]", ";", "$", "cb", "(", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "this", "->", "on", "[", "'afterUpdate'", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "on", "[", "'afterUpdate'", "]", "as", "$", "cb", ")", "{", "$", "cb", "(", "$", "object", ",", "$", "meta", ")", ";", "}", "}", "}", "return", "$", "return", ";", "}" ]
Update an object in the database, or update a table by criteria. update ( $object ) update ( $object , $meta ) @return void
[ "Update", "an", "object", "in", "the", "database", "or", "update", "a", "table", "by", "criteria", "." ]
train
https://github.com/shabbyrobe/amiss/blob/ba261f0d1f985ed36e9fd2903ac0df86c5b9498d/src/Sql/Manager.php#L675-L724
shabbyrobe/amiss
src/Sql/Manager.php
Manager.deleteTable
public function deleteTable($meta, ...$args) { if (!isset($args[0])) { throw new \InvalidArgumentException("Cannot delete from table without a condition (pass the string '1=1' if you really meant to do this)"); } $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta; if (!$meta->canDelete) { throw new Exception("Meta {$meta->id} prohibits update"); } $query = Query\Criteria::fromParamArgs($args); return $this->executeDelete($meta, $query); }
php
public function deleteTable($meta, ...$args) { if (!isset($args[0])) { throw new \InvalidArgumentException("Cannot delete from table without a condition (pass the string '1=1' if you really meant to do this)"); } $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta; if (!$meta->canDelete) { throw new Exception("Meta {$meta->id} prohibits update"); } $query = Query\Criteria::fromParamArgs($args); return $this->executeDelete($meta, $query); }
[ "public", "function", "deleteTable", "(", "$", "meta", ",", "...", "$", "args", ")", "{", "if", "(", "!", "isset", "(", "$", "args", "[", "0", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Cannot delete from table without a condition (pass the string '1=1' if you really meant to do this)\"", ")", ";", "}", "$", "meta", "=", "!", "$", "meta", "instanceof", "Meta", "?", "$", "this", "->", "mapper", "->", "getMeta", "(", "$", "meta", ")", ":", "$", "meta", ";", "if", "(", "!", "$", "meta", "->", "canDelete", ")", "{", "throw", "new", "Exception", "(", "\"Meta {$meta->id} prohibits update\"", ")", ";", "}", "$", "query", "=", "Query", "\\", "Criteria", "::", "fromParamArgs", "(", "$", "args", ")", ";", "return", "$", "this", "->", "executeDelete", "(", "$", "meta", ",", "$", "query", ")", ";", "}" ]
Delete from a table by criteria deleteTable ( $meta , $criteria... ); @return void
[ "Delete", "from", "a", "table", "by", "criteria" ]
train
https://github.com/shabbyrobe/amiss/blob/ba261f0d1f985ed36e9fd2903ac0df86c5b9498d/src/Sql/Manager.php#L733-L744
shabbyrobe/amiss
src/Sql/Manager.php
Manager.delete
public function delete($object, $meta=null) { $query = new Query\Criteria(); if (!is_object($object)) { throw new \BadMethodCallException("Please use deleteTable()"); } if ($meta) { $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta; } else { $meta = $this->mapper->getMeta(get_class($object)); } if (!$meta->canDelete) { throw new Exception("Meta {$meta->id} prohibits delete"); } event_before: { if (isset($meta->on['beforeDelete'])) { foreach ($meta->on['beforeDelete'] as $cb) { $cb = [$object, $cb]; $cb(); } } if (isset($this->on['beforeDelete'])) { foreach ($this->on['beforeDelete'] as $cb) { $cb($object, $meta); } } } $query->where = $meta->getIndexValue($object); $return = $this->executeDelete($meta, $query); event_after: { if (isset($meta->on['afterDelete'])) { foreach ($meta->on['afterDelete'] as $cb) { $cb = [$object, $cb]; $cb(); } } if (isset($this->on['afterDelete'])) { foreach ($this->on['afterDelete'] as $cb) { $cb($object, $meta); } } } return $return; }
php
public function delete($object, $meta=null) { $query = new Query\Criteria(); if (!is_object($object)) { throw new \BadMethodCallException("Please use deleteTable()"); } if ($meta) { $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta; } else { $meta = $this->mapper->getMeta(get_class($object)); } if (!$meta->canDelete) { throw new Exception("Meta {$meta->id} prohibits delete"); } event_before: { if (isset($meta->on['beforeDelete'])) { foreach ($meta->on['beforeDelete'] as $cb) { $cb = [$object, $cb]; $cb(); } } if (isset($this->on['beforeDelete'])) { foreach ($this->on['beforeDelete'] as $cb) { $cb($object, $meta); } } } $query->where = $meta->getIndexValue($object); $return = $this->executeDelete($meta, $query); event_after: { if (isset($meta->on['afterDelete'])) { foreach ($meta->on['afterDelete'] as $cb) { $cb = [$object, $cb]; $cb(); } } if (isset($this->on['afterDelete'])) { foreach ($this->on['afterDelete'] as $cb) { $cb($object, $meta); } } } return $return; }
[ "public", "function", "delete", "(", "$", "object", ",", "$", "meta", "=", "null", ")", "{", "$", "query", "=", "new", "Query", "\\", "Criteria", "(", ")", ";", "if", "(", "!", "is_object", "(", "$", "object", ")", ")", "{", "throw", "new", "\\", "BadMethodCallException", "(", "\"Please use deleteTable()\"", ")", ";", "}", "if", "(", "$", "meta", ")", "{", "$", "meta", "=", "!", "$", "meta", "instanceof", "Meta", "?", "$", "this", "->", "mapper", "->", "getMeta", "(", "$", "meta", ")", ":", "$", "meta", ";", "}", "else", "{", "$", "meta", "=", "$", "this", "->", "mapper", "->", "getMeta", "(", "get_class", "(", "$", "object", ")", ")", ";", "}", "if", "(", "!", "$", "meta", "->", "canDelete", ")", "{", "throw", "new", "Exception", "(", "\"Meta {$meta->id} prohibits delete\"", ")", ";", "}", "event_before", ":", "{", "if", "(", "isset", "(", "$", "meta", "->", "on", "[", "'beforeDelete'", "]", ")", ")", "{", "foreach", "(", "$", "meta", "->", "on", "[", "'beforeDelete'", "]", "as", "$", "cb", ")", "{", "$", "cb", "=", "[", "$", "object", ",", "$", "cb", "]", ";", "$", "cb", "(", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "this", "->", "on", "[", "'beforeDelete'", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "on", "[", "'beforeDelete'", "]", "as", "$", "cb", ")", "{", "$", "cb", "(", "$", "object", ",", "$", "meta", ")", ";", "}", "}", "}", "$", "query", "->", "where", "=", "$", "meta", "->", "getIndexValue", "(", "$", "object", ")", ";", "$", "return", "=", "$", "this", "->", "executeDelete", "(", "$", "meta", ",", "$", "query", ")", ";", "event_after", ":", "{", "if", "(", "isset", "(", "$", "meta", "->", "on", "[", "'afterDelete'", "]", ")", ")", "{", "foreach", "(", "$", "meta", "->", "on", "[", "'afterDelete'", "]", "as", "$", "cb", ")", "{", "$", "cb", "=", "[", "$", "object", ",", "$", "cb", "]", ";", "$", "cb", "(", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "this", "->", "on", "[", "'afterDelete'", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "on", "[", "'afterDelete'", "]", "as", "$", "cb", ")", "{", "$", "cb", "(", "$", "object", ",", "$", "meta", ")", ";", "}", "}", "}", "return", "$", "return", ";", "}" ]
Delete an object from the database delete ( $object ) delete ( $object, $meta ) @return void
[ "Delete", "an", "object", "from", "the", "database" ]
train
https://github.com/shabbyrobe/amiss/blob/ba261f0d1f985ed36e9fd2903ac0df86c5b9498d/src/Sql/Manager.php#L754-L794
shabbyrobe/amiss
src/Sql/Manager.php
Manager.save
public function save($object, $meta=null) { if ($meta) { $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta; } else { $meta = $this->mapper->getMeta(get_class($object)); } if (!$meta->primary) { throw new Exception("No primary key for {$meta->id}"); } $shouldInsert = null; $prival = null; if ($meta->autoinc) { $prival = $meta->getValue($object, $meta->autoinc); $shouldInsert = !$prival; } else { $prival = $meta->getIndexValue($object); } event_before: { if (isset($meta->on['beforeSave'])) { foreach ($meta->on['beforeSave'] as $cb) { $cb = [$object, $cb]; $cb(); } } if (isset($this->on['beforeSave'])) { foreach ($this->on['beforeSave'] as $cb) { $cb($object, $meta); } } } if ($shouldInsert === null) { $newpri = $meta->getIndexValue($object); $shouldInsert = $newpri != $prival; } if ($shouldInsert) { $this->insert($object, $meta); } else { $this->update($object, $meta); } event_after: { if (isset($meta->on['afterSave'])) { foreach ($meta->on['afterSave'] as $cb) { $cb = [$object, $cb]; $cb(); } } if (isset($this->on['afterSave'])) { foreach ($this->on['afterSave'] as $cb) { $cb($object, $meta); } } } }
php
public function save($object, $meta=null) { if ($meta) { $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta; } else { $meta = $this->mapper->getMeta(get_class($object)); } if (!$meta->primary) { throw new Exception("No primary key for {$meta->id}"); } $shouldInsert = null; $prival = null; if ($meta->autoinc) { $prival = $meta->getValue($object, $meta->autoinc); $shouldInsert = !$prival; } else { $prival = $meta->getIndexValue($object); } event_before: { if (isset($meta->on['beforeSave'])) { foreach ($meta->on['beforeSave'] as $cb) { $cb = [$object, $cb]; $cb(); } } if (isset($this->on['beforeSave'])) { foreach ($this->on['beforeSave'] as $cb) { $cb($object, $meta); } } } if ($shouldInsert === null) { $newpri = $meta->getIndexValue($object); $shouldInsert = $newpri != $prival; } if ($shouldInsert) { $this->insert($object, $meta); } else { $this->update($object, $meta); } event_after: { if (isset($meta->on['afterSave'])) { foreach ($meta->on['afterSave'] as $cb) { $cb = [$object, $cb]; $cb(); } } if (isset($this->on['afterSave'])) { foreach ($this->on['afterSave'] as $cb) { $cb($object, $meta); } } } }
[ "public", "function", "save", "(", "$", "object", ",", "$", "meta", "=", "null", ")", "{", "if", "(", "$", "meta", ")", "{", "$", "meta", "=", "!", "$", "meta", "instanceof", "Meta", "?", "$", "this", "->", "mapper", "->", "getMeta", "(", "$", "meta", ")", ":", "$", "meta", ";", "}", "else", "{", "$", "meta", "=", "$", "this", "->", "mapper", "->", "getMeta", "(", "get_class", "(", "$", "object", ")", ")", ";", "}", "if", "(", "!", "$", "meta", "->", "primary", ")", "{", "throw", "new", "Exception", "(", "\"No primary key for {$meta->id}\"", ")", ";", "}", "$", "shouldInsert", "=", "null", ";", "$", "prival", "=", "null", ";", "if", "(", "$", "meta", "->", "autoinc", ")", "{", "$", "prival", "=", "$", "meta", "->", "getValue", "(", "$", "object", ",", "$", "meta", "->", "autoinc", ")", ";", "$", "shouldInsert", "=", "!", "$", "prival", ";", "}", "else", "{", "$", "prival", "=", "$", "meta", "->", "getIndexValue", "(", "$", "object", ")", ";", "}", "event_before", ":", "{", "if", "(", "isset", "(", "$", "meta", "->", "on", "[", "'beforeSave'", "]", ")", ")", "{", "foreach", "(", "$", "meta", "->", "on", "[", "'beforeSave'", "]", "as", "$", "cb", ")", "{", "$", "cb", "=", "[", "$", "object", ",", "$", "cb", "]", ";", "$", "cb", "(", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "this", "->", "on", "[", "'beforeSave'", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "on", "[", "'beforeSave'", "]", "as", "$", "cb", ")", "{", "$", "cb", "(", "$", "object", ",", "$", "meta", ")", ";", "}", "}", "}", "if", "(", "$", "shouldInsert", "===", "null", ")", "{", "$", "newpri", "=", "$", "meta", "->", "getIndexValue", "(", "$", "object", ")", ";", "$", "shouldInsert", "=", "$", "newpri", "!=", "$", "prival", ";", "}", "if", "(", "$", "shouldInsert", ")", "{", "$", "this", "->", "insert", "(", "$", "object", ",", "$", "meta", ")", ";", "}", "else", "{", "$", "this", "->", "update", "(", "$", "object", ",", "$", "meta", ")", ";", "}", "event_after", ":", "{", "if", "(", "isset", "(", "$", "meta", "->", "on", "[", "'afterSave'", "]", ")", ")", "{", "foreach", "(", "$", "meta", "->", "on", "[", "'afterSave'", "]", "as", "$", "cb", ")", "{", "$", "cb", "=", "[", "$", "object", ",", "$", "cb", "]", ";", "$", "cb", "(", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "this", "->", "on", "[", "'afterSave'", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "on", "[", "'afterSave'", "]", "as", "$", "cb", ")", "{", "$", "cb", "(", "$", "object", ",", "$", "meta", ")", ";", "}", "}", "}", "}" ]
If an object has an autoincrement primary key, insert or update as necessary. @return void
[ "If", "an", "object", "has", "an", "autoincrement", "primary", "key", "insert", "or", "update", "as", "necessary", "." ]
train
https://github.com/shabbyrobe/amiss/blob/ba261f0d1f985ed36e9fd2903ac0df86c5b9498d/src/Sql/Manager.php#L809-L858
shabbyrobe/amiss
src/Sql/Manager.php
Manager.createKeyCriteria
public function createKeyCriteria($meta, $id, $indexId=null) { if ($indexId == null) { $indexId = 'primary'; } $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta; if (!isset($meta->indexes[$indexId])) { throw new Exception("Index $indexId does not exist on meta {$meta->id}"); } $index = $meta->indexes[$indexId]; if (!$index['key']) { throw new Exception("Index $indexId is not a key index for meta {$meta->id}"); } if (!is_array($id)) { $id = array($id); } $where = array(); foreach ($index['fields'] as $idx=>$p) { $idVal = isset($id[$p]) ? $id[$p] : (isset($id[$idx]) ? $id[$idx] : null); if (!$idVal) { throw new \InvalidArgumentException("Couldn't get ID value when getting {$meta->id} by index '{$indexId}'"); } $where[$p] = $idVal; } return array('where'=>$where); }
php
public function createKeyCriteria($meta, $id, $indexId=null) { if ($indexId == null) { $indexId = 'primary'; } $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta; if (!isset($meta->indexes[$indexId])) { throw new Exception("Index $indexId does not exist on meta {$meta->id}"); } $index = $meta->indexes[$indexId]; if (!$index['key']) { throw new Exception("Index $indexId is not a key index for meta {$meta->id}"); } if (!is_array($id)) { $id = array($id); } $where = array(); foreach ($index['fields'] as $idx=>$p) { $idVal = isset($id[$p]) ? $id[$p] : (isset($id[$idx]) ? $id[$idx] : null); if (!$idVal) { throw new \InvalidArgumentException("Couldn't get ID value when getting {$meta->id} by index '{$indexId}'"); } $where[$p] = $idVal; } return array('where'=>$where); }
[ "public", "function", "createKeyCriteria", "(", "$", "meta", ",", "$", "id", ",", "$", "indexId", "=", "null", ")", "{", "if", "(", "$", "indexId", "==", "null", ")", "{", "$", "indexId", "=", "'primary'", ";", "}", "$", "meta", "=", "!", "$", "meta", "instanceof", "Meta", "?", "$", "this", "->", "mapper", "->", "getMeta", "(", "$", "meta", ")", ":", "$", "meta", ";", "if", "(", "!", "isset", "(", "$", "meta", "->", "indexes", "[", "$", "indexId", "]", ")", ")", "{", "throw", "new", "Exception", "(", "\"Index $indexId does not exist on meta {$meta->id}\"", ")", ";", "}", "$", "index", "=", "$", "meta", "->", "indexes", "[", "$", "indexId", "]", ";", "if", "(", "!", "$", "index", "[", "'key'", "]", ")", "{", "throw", "new", "Exception", "(", "\"Index $indexId is not a key index for meta {$meta->id}\"", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "id", ")", ")", "{", "$", "id", "=", "array", "(", "$", "id", ")", ";", "}", "$", "where", "=", "array", "(", ")", ";", "foreach", "(", "$", "index", "[", "'fields'", "]", "as", "$", "idx", "=>", "$", "p", ")", "{", "$", "idVal", "=", "isset", "(", "$", "id", "[", "$", "p", "]", ")", "?", "$", "id", "[", "$", "p", "]", ":", "(", "isset", "(", "$", "id", "[", "$", "idx", "]", ")", "?", "$", "id", "[", "$", "idx", "]", ":", "null", ")", ";", "if", "(", "!", "$", "idVal", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Couldn't get ID value when getting {$meta->id} by index '{$indexId}'\"", ")", ";", "}", "$", "where", "[", "$", "p", "]", "=", "$", "idVal", ";", "}", "return", "array", "(", "'where'", "=>", "$", "where", ")", ";", "}" ]
Creates an array criteria for a key index @param mixed $meta Meta or class name @return array Criteria
[ "Creates", "an", "array", "criteria", "for", "a", "key", "index" ]
train
https://github.com/shabbyrobe/amiss/blob/ba261f0d1f985ed36e9fd2903ac0df86c5b9498d/src/Sql/Manager.php#L865-L892
shabbyrobe/amiss
src/Sql/Manager.php
Manager.getChildren
public function getChildren(...$args) { if (!$this->filter) { $this->filter = new \Amiss\Filter($this->mapper); } return $this->filter->getChildren(...$args); }
php
public function getChildren(...$args) { if (!$this->filter) { $this->filter = new \Amiss\Filter($this->mapper); } return $this->filter->getChildren(...$args); }
[ "public", "function", "getChildren", "(", "...", "$", "args", ")", "{", "if", "(", "!", "$", "this", "->", "filter", ")", "{", "$", "this", "->", "filter", "=", "new", "\\", "Amiss", "\\", "Filter", "(", "$", "this", "->", "mapper", ")", ";", "}", "return", "$", "this", "->", "filter", "->", "getChildren", "(", "...", "$", "args", ")", ";", "}" ]
/*{{{ Amiss\Filter methods
[ "/", "*", "{{{", "Amiss", "\\", "Filter", "methods" ]
train
https://github.com/shabbyrobe/amiss/blob/ba261f0d1f985ed36e9fd2903ac0df86c5b9498d/src/Sql/Manager.php#L913-L919
spiral-modules/listing
source/Listing/Sorters/UnarySorter.php
UnarySorter.apply
public function apply($selector) { $this->validateSelector($selector); if ($selector instanceof RecordSelector) { $selector = $this->loadDependencies($selector); foreach ($this->sortBy as $expression => $direction) { $selector = $selector->orderBy( $expression, $direction == self::ASC ? SelectQuery::SORT_ASC : SelectQuery::SORT_DESC ); } return $selector; } return $selector->sortBy($this->sortBy); }
php
public function apply($selector) { $this->validateSelector($selector); if ($selector instanceof RecordSelector) { $selector = $this->loadDependencies($selector); foreach ($this->sortBy as $expression => $direction) { $selector = $selector->orderBy( $expression, $direction == self::ASC ? SelectQuery::SORT_ASC : SelectQuery::SORT_DESC ); } return $selector; } return $selector->sortBy($this->sortBy); }
[ "public", "function", "apply", "(", "$", "selector", ")", "{", "$", "this", "->", "validateSelector", "(", "$", "selector", ")", ";", "if", "(", "$", "selector", "instanceof", "RecordSelector", ")", "{", "$", "selector", "=", "$", "this", "->", "loadDependencies", "(", "$", "selector", ")", ";", "foreach", "(", "$", "this", "->", "sortBy", "as", "$", "expression", "=>", "$", "direction", ")", "{", "$", "selector", "=", "$", "selector", "->", "orderBy", "(", "$", "expression", ",", "$", "direction", "==", "self", "::", "ASC", "?", "SelectQuery", "::", "SORT_ASC", ":", "SelectQuery", "::", "SORT_DESC", ")", ";", "}", "return", "$", "selector", ";", "}", "return", "$", "selector", "->", "sortBy", "(", "$", "this", "->", "sortBy", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/spiral-modules/listing/blob/89abe8939ce91cbf61b51b99e93ce1e57c8af83c/source/Listing/Sorters/UnarySorter.php#L45-L63
FriendsOfApi/phraseapp
src/Model/Locale/Uploaded.php
Uploaded.createFromArray
public static function createFromArray(array $data) { $self = new self(); if (isset($data['id'])) { $self->setId($data['id']); } if (isset($data['filename'])) { $self->setFilename($data['filename']); } if (isset($data['format'])) { $self->setFormat($data['format']); } if (isset($data['state'])) { $self->setState($data['state']); } if (isset($data['created_at'])) { $self->setCreatedAt($data['created_at']); } return $self; }
php
public static function createFromArray(array $data) { $self = new self(); if (isset($data['id'])) { $self->setId($data['id']); } if (isset($data['filename'])) { $self->setFilename($data['filename']); } if (isset($data['format'])) { $self->setFormat($data['format']); } if (isset($data['state'])) { $self->setState($data['state']); } if (isset($data['created_at'])) { $self->setCreatedAt($data['created_at']); } return $self; }
[ "public", "static", "function", "createFromArray", "(", "array", "$", "data", ")", "{", "$", "self", "=", "new", "self", "(", ")", ";", "if", "(", "isset", "(", "$", "data", "[", "'id'", "]", ")", ")", "{", "$", "self", "->", "setId", "(", "$", "data", "[", "'id'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'filename'", "]", ")", ")", "{", "$", "self", "->", "setFilename", "(", "$", "data", "[", "'filename'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'format'", "]", ")", ")", "{", "$", "self", "->", "setFormat", "(", "$", "data", "[", "'format'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'state'", "]", ")", ")", "{", "$", "self", "->", "setState", "(", "$", "data", "[", "'state'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "'created_at'", "]", ")", ")", "{", "$", "self", "->", "setCreatedAt", "(", "$", "data", "[", "'created_at'", "]", ")", ";", "}", "return", "$", "self", ";", "}" ]
@param array $data @return Uploaded
[ "@param", "array", "$data" ]
train
https://github.com/FriendsOfApi/phraseapp/blob/1553bf857eb0858f9a7eb905b085864d24f80886/src/Model/Locale/Uploaded.php#L48-L69
getuisdk/getui-php-sdk
src/PBInputStringReader.php
PBInputStringReader.next
public function next($is_string = false) { $package = ''; while (true) { if ($this->pointer >= $this->length) { return false; } $string = $this->string[$this->pointer]; $this->pointer++; if ($is_string === true) { return ord($string); } $value = decbin(ord($string)); if ($value >= 10000000 && $is_string === false) { // now fill to eight with 00 $package .= $value; } else { // now fill to length of eight with 0 $value = substr('00000000', 0, 8 - strlen($value) % 8) . $value; return $this->base128->getValue($package . $value); } } return $package; }
php
public function next($is_string = false) { $package = ''; while (true) { if ($this->pointer >= $this->length) { return false; } $string = $this->string[$this->pointer]; $this->pointer++; if ($is_string === true) { return ord($string); } $value = decbin(ord($string)); if ($value >= 10000000 && $is_string === false) { // now fill to eight with 00 $package .= $value; } else { // now fill to length of eight with 0 $value = substr('00000000', 0, 8 - strlen($value) % 8) . $value; return $this->base128->getValue($package . $value); } } return $package; }
[ "public", "function", "next", "(", "$", "is_string", "=", "false", ")", "{", "$", "package", "=", "''", ";", "while", "(", "true", ")", "{", "if", "(", "$", "this", "->", "pointer", ">=", "$", "this", "->", "length", ")", "{", "return", "false", ";", "}", "$", "string", "=", "$", "this", "->", "string", "[", "$", "this", "->", "pointer", "]", ";", "$", "this", "->", "pointer", "++", ";", "if", "(", "$", "is_string", "===", "true", ")", "{", "return", "ord", "(", "$", "string", ")", ";", "}", "$", "value", "=", "decbin", "(", "ord", "(", "$", "string", ")", ")", ";", "if", "(", "$", "value", ">=", "10000000", "&&", "$", "is_string", "===", "false", ")", "{", "// now fill to eight with 00\r", "$", "package", ".=", "$", "value", ";", "}", "else", "{", "// now fill to length of eight with 0\r", "$", "value", "=", "substr", "(", "'00000000'", ",", "0", ",", "8", "-", "strlen", "(", "$", "value", ")", "%", "8", ")", ".", "$", "value", ";", "return", "$", "this", "->", "base128", "->", "getValue", "(", "$", "package", ".", "$", "value", ")", ";", "}", "}", "return", "$", "package", ";", "}" ]
get the next @param boolean $is_string - if set to true only one byte is read @return mixed
[ "get", "the", "next" ]
train
https://github.com/getuisdk/getui-php-sdk/blob/e91773b099bcbfd7492a44086b373d1c9fee37e2/src/PBInputStringReader.php#L30-L57
sinri/Ark-Core
src/ArkHelper.php
ArkHelper.registerAutoload
public static function registerAutoload($base_namespace, $base_path, $extension = '.php') { spl_autoload_register(function ($class_name) use ($base_namespace, $base_path, $extension) { $file_path = self::getFilePathForClassName( $class_name, $base_namespace, $base_path, $extension ); if ($file_path) { /** @noinspection PhpIncludeInspection */ require_once $file_path; } }); }
php
public static function registerAutoload($base_namespace, $base_path, $extension = '.php') { spl_autoload_register(function ($class_name) use ($base_namespace, $base_path, $extension) { $file_path = self::getFilePathForClassName( $class_name, $base_namespace, $base_path, $extension ); if ($file_path) { /** @noinspection PhpIncludeInspection */ require_once $file_path; } }); }
[ "public", "static", "function", "registerAutoload", "(", "$", "base_namespace", ",", "$", "base_path", ",", "$", "extension", "=", "'.php'", ")", "{", "spl_autoload_register", "(", "function", "(", "$", "class_name", ")", "use", "(", "$", "base_namespace", ",", "$", "base_path", ",", "$", "extension", ")", "{", "$", "file_path", "=", "self", "::", "getFilePathForClassName", "(", "$", "class_name", ",", "$", "base_namespace", ",", "$", "base_path", ",", "$", "extension", ")", ";", "if", "(", "$", "file_path", ")", "{", "/** @noinspection PhpIncludeInspection */", "require_once", "$", "file_path", ";", "}", "}", ")", ";", "}" ]
For Autoload File @param string $base_namespace such as sinri\enoch @param string $base_path /code/sinri/enoch @param string $extension
[ "For", "Autoload", "File" ]
train
https://github.com/sinri/Ark-Core/blob/fb5715e72b500ddc08dd52d9701d713fe49f48c6/src/ArkHelper.php#L39-L53
sinri/Ark-Core
src/ArkHelper.php
ArkHelper.removeFromArray
public static function removeFromArray(&$array, $keychain) { if (!is_array($array)) { $array = []; } if (!is_array($keychain)) { $keychain = [$keychain]; } $headKey = array_shift($keychain); if (empty($keychain)) { //last unset($array[$headKey]); } else { //not last if (isset($array[$headKey])) { self::removeFromArray($array[$headKey], $keychain); } } }
php
public static function removeFromArray(&$array, $keychain) { if (!is_array($array)) { $array = []; } if (!is_array($keychain)) { $keychain = [$keychain]; } $headKey = array_shift($keychain); if (empty($keychain)) { //last unset($array[$headKey]); } else { //not last if (isset($array[$headKey])) { self::removeFromArray($array[$headKey], $keychain); } } }
[ "public", "static", "function", "removeFromArray", "(", "&", "$", "array", ",", "$", "keychain", ")", "{", "if", "(", "!", "is_array", "(", "$", "array", ")", ")", "{", "$", "array", "=", "[", "]", ";", "}", "if", "(", "!", "is_array", "(", "$", "keychain", ")", ")", "{", "$", "keychain", "=", "[", "$", "keychain", "]", ";", "}", "$", "headKey", "=", "array_shift", "(", "$", "keychain", ")", ";", "if", "(", "empty", "(", "$", "keychain", ")", ")", "{", "//last", "unset", "(", "$", "array", "[", "$", "headKey", "]", ")", ";", "}", "else", "{", "//not last", "if", "(", "isset", "(", "$", "array", "[", "$", "headKey", "]", ")", ")", "{", "self", "::", "removeFromArray", "(", "$", "array", "[", "$", "headKey", "]", ",", "$", "keychain", ")", ";", "}", "}", "}" ]
Unset item and nested item in array @since 1.2 @param array $array @param array|string|int $keychain
[ "Unset", "item", "and", "nested", "item", "in", "array" ]
train
https://github.com/sinri/Ark-Core/blob/fb5715e72b500ddc08dd52d9701d713fe49f48c6/src/ArkHelper.php#L154-L173
frdl/webfan
.ApplicationComposer/lib/frdl/ApplicationComposer/ApplicationComposerBootstrap.php
ApplicationComposerBootstrap.wd
public function wd($dir = null, $code = E_USER_WARNING){ if(null !== $dir && is_dir($dir)){ $this->wd = $dir; if(chdir($dir) === false){ throw new \Exception('Cannot change to directory '.$dir.' in '.__METHOD__, $code); return $this; } }else{ $dir = $this->wd; } return $this; }
php
public function wd($dir = null, $code = E_USER_WARNING){ if(null !== $dir && is_dir($dir)){ $this->wd = $dir; if(chdir($dir) === false){ throw new \Exception('Cannot change to directory '.$dir.' in '.__METHOD__, $code); return $this; } }else{ $dir = $this->wd; } return $this; }
[ "public", "function", "wd", "(", "$", "dir", "=", "null", ",", "$", "code", "=", "E_USER_WARNING", ")", "{", "if", "(", "null", "!==", "$", "dir", "&&", "is_dir", "(", "$", "dir", ")", ")", "{", "$", "this", "->", "wd", "=", "$", "dir", ";", "if", "(", "chdir", "(", "$", "dir", ")", "===", "false", ")", "{", "throw", "new", "\\", "Exception", "(", "'Cannot change to directory '", ".", "$", "dir", ".", "' in '", ".", "__METHOD__", ",", "$", "code", ")", ";", "return", "$", "this", ";", "}", "}", "else", "{", "$", "dir", "=", "$", "this", "->", "wd", ";", "}", "return", "$", "this", ";", "}" ]
set working directory
[ "set", "working", "directory" ]
train
https://github.com/frdl/webfan/blob/84d270377685224e891cd9d571b103b36f05b845/.ApplicationComposer/lib/frdl/ApplicationComposer/ApplicationComposerBootstrap.php#L67-L78
unclecheese/silverstripe-bootstrap-tagfield
code/BootstrapTagField.php
BootstrapTagField.formatJSON
protected function formatJSON(SS_List $list) { $ret = array (); foreach($list as $item) { $ret[] = array( 'id' => $item->{$this->idField}, 'label' => $item->{$this->labelField} ); } return Convert::array2json($ret); }
php
protected function formatJSON(SS_List $list) { $ret = array (); foreach($list as $item) { $ret[] = array( 'id' => $item->{$this->idField}, 'label' => $item->{$this->labelField} ); } return Convert::array2json($ret); }
[ "protected", "function", "formatJSON", "(", "SS_List", "$", "list", ")", "{", "$", "ret", "=", "array", "(", ")", ";", "foreach", "(", "$", "list", "as", "$", "item", ")", "{", "$", "ret", "[", "]", "=", "array", "(", "'id'", "=>", "$", "item", "->", "{", "$", "this", "->", "idField", "}", ",", "'label'", "=>", "$", "item", "->", "{", "$", "this", "->", "labelField", "}", ")", ";", "}", "return", "Convert", "::", "array2json", "(", "$", "ret", ")", ";", "}" ]
Formats JSON so that it is usable by the JS component @param SS_List $list The list to format @return string JSON
[ "Formats", "JSON", "so", "that", "it", "is", "usable", "by", "the", "JS", "component" ]
train
https://github.com/unclecheese/silverstripe-bootstrap-tagfield/blob/ada0c647f90ccb753d26a5d01889b2b4fbe2af76/code/BootstrapTagField.php#L80-L90
unclecheese/silverstripe-bootstrap-tagfield
code/BootstrapTagField.php
BootstrapTagField.query
public function query(SS_HTTPRequest $r) { return $this->formatJSON($this->source->filter(array( $this->labelField.':PartialMatch' => $r->getVar('q') )) ->limit(10)); }
php
public function query(SS_HTTPRequest $r) { return $this->formatJSON($this->source->filter(array( $this->labelField.':PartialMatch' => $r->getVar('q') )) ->limit(10)); }
[ "public", "function", "query", "(", "SS_HTTPRequest", "$", "r", ")", "{", "return", "$", "this", "->", "formatJSON", "(", "$", "this", "->", "source", "->", "filter", "(", "array", "(", "$", "this", "->", "labelField", ".", "':PartialMatch'", "=>", "$", "r", "->", "getVar", "(", "'q'", ")", ")", ")", "->", "limit", "(", "10", ")", ")", ";", "}" ]
An AJAX endpoint for querying the typeahead @param SS_HTTPRequest $r The request @return string JSON
[ "An", "AJAX", "endpoint", "for", "querying", "the", "typeahead" ]
train
https://github.com/unclecheese/silverstripe-bootstrap-tagfield/blob/ada0c647f90ccb753d26a5d01889b2b4fbe2af76/code/BootstrapTagField.php#L98-L103
unclecheese/silverstripe-bootstrap-tagfield
code/BootstrapTagField.php
BootstrapTagField.getValuesJSON
protected function getValuesJSON() { $value = $this->value; if($value instanceof SS_List) { $values = $value->column($this->idField); } else if(is_array($value)) { $values = array_keys($value); } else if(is_string($value)) { $values = explode(',', $value); $values = str_replace('{comma}', ',', $values); } return $this->formatJSON($this->source->filter(array( $this->idField => $values ))); }
php
protected function getValuesJSON() { $value = $this->value; if($value instanceof SS_List) { $values = $value->column($this->idField); } else if(is_array($value)) { $values = array_keys($value); } else if(is_string($value)) { $values = explode(',', $value); $values = str_replace('{comma}', ',', $values); } return $this->formatJSON($this->source->filter(array( $this->idField => $values ))); }
[ "protected", "function", "getValuesJSON", "(", ")", "{", "$", "value", "=", "$", "this", "->", "value", ";", "if", "(", "$", "value", "instanceof", "SS_List", ")", "{", "$", "values", "=", "$", "value", "->", "column", "(", "$", "this", "->", "idField", ")", ";", "}", "else", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "values", "=", "array_keys", "(", "$", "value", ")", ";", "}", "else", "if", "(", "is_string", "(", "$", "value", ")", ")", "{", "$", "values", "=", "explode", "(", "','", ",", "$", "value", ")", ";", "$", "values", "=", "str_replace", "(", "'{comma}'", ",", "','", ",", "$", "values", ")", ";", "}", "return", "$", "this", "->", "formatJSON", "(", "$", "this", "->", "source", "->", "filter", "(", "array", "(", "$", "this", "->", "idField", "=>", "$", "values", ")", ")", ")", ";", "}" ]
Gets the current values assigned to the field, formatted as a JSON array @return string JSON
[ "Gets", "the", "current", "values", "assigned", "to", "the", "field", "formatted", "as", "a", "JSON", "array" ]
train
https://github.com/unclecheese/silverstripe-bootstrap-tagfield/blob/ada0c647f90ccb753d26a5d01889b2b4fbe2af76/code/BootstrapTagField.php#L122-L138
unclecheese/silverstripe-bootstrap-tagfield
code/BootstrapTagField.php
BootstrapTagField.setPrefetch
public function setPrefetch(SS_List $list) { if(!$list instanceof SS_List) { throw new Exception('Prefetch list must be an instance of SS_List'); } $this->prefetch = $list; return $this; }
php
public function setPrefetch(SS_List $list) { if(!$list instanceof SS_List) { throw new Exception('Prefetch list must be an instance of SS_List'); } $this->prefetch = $list; return $this; }
[ "public", "function", "setPrefetch", "(", "SS_List", "$", "list", ")", "{", "if", "(", "!", "$", "list", "instanceof", "SS_List", ")", "{", "throw", "new", "Exception", "(", "'Prefetch list must be an instance of SS_List'", ")", ";", "}", "$", "this", "->", "prefetch", "=", "$", "list", ";", "return", "$", "this", ";", "}" ]
Sets the prefetch records list @param SS_List $list @return BootstrapTagField
[ "Sets", "the", "prefetch", "records", "list" ]
train
https://github.com/unclecheese/silverstripe-bootstrap-tagfield/blob/ada0c647f90ccb753d26a5d01889b2b4fbe2af76/code/BootstrapTagField.php#L146-L154
unclecheese/silverstripe-bootstrap-tagfield
code/BootstrapTagField.php
BootstrapTagField.saveInto
public function saveInto(DataObjectInterface $record) { $fieldname = $this->name; $relation = ($fieldname && $record && $record->hasMethod($fieldname)) ? $record->$fieldname() : null; if($fieldname && $record && $relation && ($relation instanceof RelationList || $relation instanceof UnsavedRelationList)) { $idList = array(); if($this->value) foreach($this->value as $id => $text) { if(preg_match('/^__new__/', $id)) { $id = $this->source->newObject(array( $this->labelField => $text ))->write(); } $idList[] = $id; } $relation->setByIDList($idList); } elseif($fieldname && $record) { if($this->value) { $this->value = str_replace(',', '{comma}', $this->value); $record->$fieldname = implode(',', (array) $this->value); } else { $record->$fieldname = ''; } } }
php
public function saveInto(DataObjectInterface $record) { $fieldname = $this->name; $relation = ($fieldname && $record && $record->hasMethod($fieldname)) ? $record->$fieldname() : null; if($fieldname && $record && $relation && ($relation instanceof RelationList || $relation instanceof UnsavedRelationList)) { $idList = array(); if($this->value) foreach($this->value as $id => $text) { if(preg_match('/^__new__/', $id)) { $id = $this->source->newObject(array( $this->labelField => $text ))->write(); } $idList[] = $id; } $relation->setByIDList($idList); } elseif($fieldname && $record) { if($this->value) { $this->value = str_replace(',', '{comma}', $this->value); $record->$fieldname = implode(',', (array) $this->value); } else { $record->$fieldname = ''; } } }
[ "public", "function", "saveInto", "(", "DataObjectInterface", "$", "record", ")", "{", "$", "fieldname", "=", "$", "this", "->", "name", ";", "$", "relation", "=", "(", "$", "fieldname", "&&", "$", "record", "&&", "$", "record", "->", "hasMethod", "(", "$", "fieldname", ")", ")", "?", "$", "record", "->", "$", "fieldname", "(", ")", ":", "null", ";", "if", "(", "$", "fieldname", "&&", "$", "record", "&&", "$", "relation", "&&", "(", "$", "relation", "instanceof", "RelationList", "||", "$", "relation", "instanceof", "UnsavedRelationList", ")", ")", "{", "$", "idList", "=", "array", "(", ")", ";", "if", "(", "$", "this", "->", "value", ")", "foreach", "(", "$", "this", "->", "value", "as", "$", "id", "=>", "$", "text", ")", "{", "if", "(", "preg_match", "(", "'/^__new__/'", ",", "$", "id", ")", ")", "{", "$", "id", "=", "$", "this", "->", "source", "->", "newObject", "(", "array", "(", "$", "this", "->", "labelField", "=>", "$", "text", ")", ")", "->", "write", "(", ")", ";", "}", "$", "idList", "[", "]", "=", "$", "id", ";", "}", "$", "relation", "->", "setByIDList", "(", "$", "idList", ")", ";", "}", "elseif", "(", "$", "fieldname", "&&", "$", "record", ")", "{", "if", "(", "$", "this", "->", "value", ")", "{", "$", "this", "->", "value", "=", "str_replace", "(", "','", ",", "'{comma}'", ",", "$", "this", "->", "value", ")", ";", "$", "record", "->", "$", "fieldname", "=", "implode", "(", "','", ",", "(", "array", ")", "$", "this", "->", "value", ")", ";", "}", "else", "{", "$", "record", "->", "$", "fieldname", "=", "''", ";", "}", "}", "}" ]
Save the current value into a DataObject. If the field it is saving to is a has_many or many_many relationship, it is saved by setByIDList(), otherwise it creates a comma separated list for a standard DB text/varchar field. @param DataObject $record The record to save into
[ "Save", "the", "current", "value", "into", "a", "DataObject", ".", "If", "the", "field", "it", "is", "saving", "to", "is", "a", "has_many", "or", "many_many", "relationship", "it", "is", "saved", "by", "setByIDList", "()", "otherwise", "it", "creates", "a", "comma", "separated", "list", "for", "a", "standard", "DB", "text", "/", "varchar", "field", "." ]
train
https://github.com/unclecheese/silverstripe-bootstrap-tagfield/blob/ada0c647f90ccb753d26a5d01889b2b4fbe2af76/code/BootstrapTagField.php#L220-L244
unclecheese/silverstripe-bootstrap-tagfield
code/BootstrapTagField.php
BootstrapTagField.Field
public function Field($properties = array()) { Requirements::javascript(BOOTSTRAP_TAGFIELD_DIR.'/javascript/typeahead.js'); Requirements::javascript(BOOTSTRAP_TAGFIELD_DIR.'/javascript/bootstrap-tagfield.js'); Requirements::javascript(BOOTSTRAP_TAGFIELD_DIR.'/javascript/bootstrap-tagfield-init.js'); Requirements::css(BOOTSTRAP_TAGFIELD_DIR.'/css/bootstrap-tagfield.css'); $this->setAttribute('data-value', $this->getValuesJSON()) ->setAttribute('data-bootstrap-tags', true) ->setAttribute('data-query-url', $this->Link('query')) ->setAttribute('data-prefetch-url', $this->Link('prefetch')) ->setAttribute('data-freeinput', $this->freeInput) ->setAttribute('class', 'text'); return $this->renderWith( $this->getTemplates() ); }
php
public function Field($properties = array()) { Requirements::javascript(BOOTSTRAP_TAGFIELD_DIR.'/javascript/typeahead.js'); Requirements::javascript(BOOTSTRAP_TAGFIELD_DIR.'/javascript/bootstrap-tagfield.js'); Requirements::javascript(BOOTSTRAP_TAGFIELD_DIR.'/javascript/bootstrap-tagfield-init.js'); Requirements::css(BOOTSTRAP_TAGFIELD_DIR.'/css/bootstrap-tagfield.css'); $this->setAttribute('data-value', $this->getValuesJSON()) ->setAttribute('data-bootstrap-tags', true) ->setAttribute('data-query-url', $this->Link('query')) ->setAttribute('data-prefetch-url', $this->Link('prefetch')) ->setAttribute('data-freeinput', $this->freeInput) ->setAttribute('class', 'text'); return $this->renderWith( $this->getTemplates() ); }
[ "public", "function", "Field", "(", "$", "properties", "=", "array", "(", ")", ")", "{", "Requirements", "::", "javascript", "(", "BOOTSTRAP_TAGFIELD_DIR", ".", "'/javascript/typeahead.js'", ")", ";", "Requirements", "::", "javascript", "(", "BOOTSTRAP_TAGFIELD_DIR", ".", "'/javascript/bootstrap-tagfield.js'", ")", ";", "Requirements", "::", "javascript", "(", "BOOTSTRAP_TAGFIELD_DIR", ".", "'/javascript/bootstrap-tagfield-init.js'", ")", ";", "Requirements", "::", "css", "(", "BOOTSTRAP_TAGFIELD_DIR", ".", "'/css/bootstrap-tagfield.css'", ")", ";", "$", "this", "->", "setAttribute", "(", "'data-value'", ",", "$", "this", "->", "getValuesJSON", "(", ")", ")", "->", "setAttribute", "(", "'data-bootstrap-tags'", ",", "true", ")", "->", "setAttribute", "(", "'data-query-url'", ",", "$", "this", "->", "Link", "(", "'query'", ")", ")", "->", "setAttribute", "(", "'data-prefetch-url'", ",", "$", "this", "->", "Link", "(", "'prefetch'", ")", ")", "->", "setAttribute", "(", "'data-freeinput'", ",", "$", "this", "->", "freeInput", ")", "->", "setAttribute", "(", "'class'", ",", "'text'", ")", ";", "return", "$", "this", "->", "renderWith", "(", "$", "this", "->", "getTemplates", "(", ")", ")", ";", "}" ]
Renders the field @param array $properties @return SSViewer
[ "Renders", "the", "field" ]
train
https://github.com/unclecheese/silverstripe-bootstrap-tagfield/blob/ada0c647f90ccb753d26a5d01889b2b4fbe2af76/code/BootstrapTagField.php#L252-L268
DesignPond/newsletter
src/Newsletter/Worker/MailjetService.php
MailjetService.getListRecipient
public function getListRecipient($email) { $this->hasList(); $ContactID = $this->getContactByEmail($email); $response = $this->mailjet->get(Resources::$Listrecipient, ['filters' => ['Contact' => $ContactID, "ContactsList" => $this->list]]); if($response->success()){ $contact = $response->getData(); return isset($contact[0]) ? $contact[0]['ID'] : false; // returns ID directly } return false; }
php
public function getListRecipient($email) { $this->hasList(); $ContactID = $this->getContactByEmail($email); $response = $this->mailjet->get(Resources::$Listrecipient, ['filters' => ['Contact' => $ContactID, "ContactsList" => $this->list]]); if($response->success()){ $contact = $response->getData(); return isset($contact[0]) ? $contact[0]['ID'] : false; // returns ID directly } return false; }
[ "public", "function", "getListRecipient", "(", "$", "email", ")", "{", "$", "this", "->", "hasList", "(", ")", ";", "$", "ContactID", "=", "$", "this", "->", "getContactByEmail", "(", "$", "email", ")", ";", "$", "response", "=", "$", "this", "->", "mailjet", "->", "get", "(", "Resources", "::", "$", "Listrecipient", ",", "[", "'filters'", "=>", "[", "'Contact'", "=>", "$", "ContactID", ",", "\"ContactsList\"", "=>", "$", "this", "->", "list", "]", "]", ")", ";", "if", "(", "$", "response", "->", "success", "(", ")", ")", "{", "$", "contact", "=", "$", "response", "->", "getData", "(", ")", ";", "return", "isset", "(", "$", "contact", "[", "0", "]", ")", "?", "$", "contact", "[", "0", "]", "[", "'ID'", "]", ":", "false", ";", "// returns ID directly", "}", "return", "false", ";", "}" ]
Lists
[ "Lists" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Worker/MailjetService.php#L140-L154
DesignPond/newsletter
src/Newsletter/Worker/MailjetService.php
MailjetService.getCampagne
public function getCampagne($CampaignID) { $response = $this->mailjet->get(Resources::$Newsletter, ['ID' => $CampaignID]); if($response->success()) return $response->getData(); else return false; }
php
public function getCampagne($CampaignID) { $response = $this->mailjet->get(Resources::$Newsletter, ['ID' => $CampaignID]); if($response->success()) return $response->getData(); else return false; }
[ "public", "function", "getCampagne", "(", "$", "CampaignID", ")", "{", "$", "response", "=", "$", "this", "->", "mailjet", "->", "get", "(", "Resources", "::", "$", "Newsletter", ",", "[", "'ID'", "=>", "$", "CampaignID", "]", ")", ";", "if", "(", "$", "response", "->", "success", "(", ")", ")", "return", "$", "response", "->", "getData", "(", ")", ";", "else", "return", "false", ";", "}" ]
Campagnes
[ "Campagnes" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Worker/MailjetService.php#L159-L167
DesignPond/newsletter
src/Newsletter/Worker/MailjetService.php
MailjetService.statsCampagne
public function statsCampagne($id) { $response = $this->mailjet->get(Resources::$Campaignstatistics, ['ID' => 'mj.nl='.$id]); if($response->success()){ $stats = $response->getData(); return $stats[0]; // returns ID directly } return false; }
php
public function statsCampagne($id) { $response = $this->mailjet->get(Resources::$Campaignstatistics, ['ID' => 'mj.nl='.$id]); if($response->success()){ $stats = $response->getData(); return $stats[0]; // returns ID directly } return false; }
[ "public", "function", "statsCampagne", "(", "$", "id", ")", "{", "$", "response", "=", "$", "this", "->", "mailjet", "->", "get", "(", "Resources", "::", "$", "Campaignstatistics", ",", "[", "'ID'", "=>", "'mj.nl='", ".", "$", "id", "]", ")", ";", "if", "(", "$", "response", "->", "success", "(", ")", ")", "{", "$", "stats", "=", "$", "response", "->", "getData", "(", ")", ";", "return", "$", "stats", "[", "0", "]", ";", "// returns ID directly", "}", "return", "false", ";", "}" ]
Statistiques
[ "Statistiques" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Worker/MailjetService.php#L277-L287
DesignPond/newsletter
src/Newsletter/Worker/MailjetService.php
MailjetService.uploadCSVContactslistData
public function uploadCSVContactslistData($CSVContent) { $this->hasList(); $response = $this->mailjet->post(Resources::$ContactslistCsvdata, ['body' => $CSVContent, 'id' => $this->list]); if($response->success()){ $import = $response->getData(); return $import['ID']; // returns ID directly } return false; }
php
public function uploadCSVContactslistData($CSVContent) { $this->hasList(); $response = $this->mailjet->post(Resources::$ContactslistCsvdata, ['body' => $CSVContent, 'id' => $this->list]); if($response->success()){ $import = $response->getData(); return $import['ID']; // returns ID directly } return false; }
[ "public", "function", "uploadCSVContactslistData", "(", "$", "CSVContent", ")", "{", "$", "this", "->", "hasList", "(", ")", ";", "$", "response", "=", "$", "this", "->", "mailjet", "->", "post", "(", "Resources", "::", "$", "ContactslistCsvdata", ",", "[", "'body'", "=>", "$", "CSVContent", ",", "'id'", "=>", "$", "this", "->", "list", "]", ")", ";", "if", "(", "$", "response", "->", "success", "(", ")", ")", "{", "$", "import", "=", "$", "response", "->", "getData", "(", ")", ";", "return", "$", "import", "[", "'ID'", "]", ";", "// returns ID directly", "}", "return", "false", ";", "}" ]
import listes
[ "import", "listes" ]
train
https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Newsletter/Worker/MailjetService.php#L304-L316
alevilar/ristorantino-vendor
Printers/Utility/AfipWsv1.php
AfipWsv1.__createTRA
static function __createTRA($SERVICE = 'wsfe') { $TRA = new SimpleXMLElement( '<?xml version="1.0" encoding="UTF-8"?>' . '<loginTicketRequest version="1.0">'. '</loginTicketRequest>'); $TRA->addChild('header'); $TRA->header->addChild('uniqueId',date('U')); $TRA->header->addChild('generationTime',date('c',date('U')-60)); $TRA->header->addChild('expirationTime',date('c',date('U')+60)); $TRA->addChild('service',$SERVICE); $TRA->asXML(TMP . 'TRA.xml'); }
php
static function __createTRA($SERVICE = 'wsfe') { $TRA = new SimpleXMLElement( '<?xml version="1.0" encoding="UTF-8"?>' . '<loginTicketRequest version="1.0">'. '</loginTicketRequest>'); $TRA->addChild('header'); $TRA->header->addChild('uniqueId',date('U')); $TRA->header->addChild('generationTime',date('c',date('U')-60)); $TRA->header->addChild('expirationTime',date('c',date('U')+60)); $TRA->addChild('service',$SERVICE); $TRA->asXML(TMP . 'TRA.xml'); }
[ "static", "function", "__createTRA", "(", "$", "SERVICE", "=", "'wsfe'", ")", "{", "$", "TRA", "=", "new", "SimpleXMLElement", "(", "'<?xml version=\"1.0\" encoding=\"UTF-8\"?>'", ".", "'<loginTicketRequest version=\"1.0\">'", ".", "'</loginTicketRequest>'", ")", ";", "$", "TRA", "->", "addChild", "(", "'header'", ")", ";", "$", "TRA", "->", "header", "->", "addChild", "(", "'uniqueId'", ",", "date", "(", "'U'", ")", ")", ";", "$", "TRA", "->", "header", "->", "addChild", "(", "'generationTime'", ",", "date", "(", "'c'", ",", "date", "(", "'U'", ")", "-", "60", ")", ")", ";", "$", "TRA", "->", "header", "->", "addChild", "(", "'expirationTime'", ",", "date", "(", "'c'", ",", "date", "(", "'U'", ")", "+", "60", ")", ")", ";", "$", "TRA", "->", "addChild", "(", "'service'", ",", "$", "SERVICE", ")", ";", "$", "TRA", "->", "asXML", "(", "TMP", ".", "'TRA.xml'", ")", ";", "}" ]
#==============================================================================
[ "#", "==============================================================================" ]
train
https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Printers/Utility/AfipWsv1.php#L454-L466
alevilar/ristorantino-vendor
Printers/Utility/AfipWsv1.php
AfipWsv1.__signTRA
static function __signTRA() { $STATUS=openssl_pkcs7_sign(TMP . "TRA.xml", TMP . "TRA.tmp", "file://".CERT, array("file://".PRIVATEKEY, PASSPHRASE), array(), !PKCS7_DETACHED ); if (!$STATUS) { throw new AfipWsException("ERROR generating PKCS#7 signature"); } $inf=fopen(TMP . "TRA.tmp", "r"); $i=0; $CMS=""; while (!feof($inf)) { $buffer=fgets($inf); if ( $i++ >= 4 ) {$CMS.=$buffer;} } fclose($inf); # unlink("TRA.xml"); unlink(TMP . "TRA.tmp"); return $CMS; }
php
static function __signTRA() { $STATUS=openssl_pkcs7_sign(TMP . "TRA.xml", TMP . "TRA.tmp", "file://".CERT, array("file://".PRIVATEKEY, PASSPHRASE), array(), !PKCS7_DETACHED ); if (!$STATUS) { throw new AfipWsException("ERROR generating PKCS#7 signature"); } $inf=fopen(TMP . "TRA.tmp", "r"); $i=0; $CMS=""; while (!feof($inf)) { $buffer=fgets($inf); if ( $i++ >= 4 ) {$CMS.=$buffer;} } fclose($inf); # unlink("TRA.xml"); unlink(TMP . "TRA.tmp"); return $CMS; }
[ "static", "function", "__signTRA", "(", ")", "{", "$", "STATUS", "=", "openssl_pkcs7_sign", "(", "TMP", ".", "\"TRA.xml\"", ",", "TMP", ".", "\"TRA.tmp\"", ",", "\"file://\"", ".", "CERT", ",", "array", "(", "\"file://\"", ".", "PRIVATEKEY", ",", "PASSPHRASE", ")", ",", "array", "(", ")", ",", "!", "PKCS7_DETACHED", ")", ";", "if", "(", "!", "$", "STATUS", ")", "{", "throw", "new", "AfipWsException", "(", "\"ERROR generating PKCS#7 signature\"", ")", ";", "}", "$", "inf", "=", "fopen", "(", "TMP", ".", "\"TRA.tmp\"", ",", "\"r\"", ")", ";", "$", "i", "=", "0", ";", "$", "CMS", "=", "\"\"", ";", "while", "(", "!", "feof", "(", "$", "inf", ")", ")", "{", "$", "buffer", "=", "fgets", "(", "$", "inf", ")", ";", "if", "(", "$", "i", "++", ">=", "4", ")", "{", "$", "CMS", ".=", "$", "buffer", ";", "}", "}", "fclose", "(", "$", "inf", ")", ";", "# unlink(\"TRA.xml\");", "unlink", "(", "TMP", ".", "\"TRA.tmp\"", ")", ";", "return", "$", "CMS", ";", "}" ]
# MIME heading leaving the final CMS required by WSAA.
[ "#", "MIME", "heading", "leaving", "the", "final", "CMS", "required", "by", "WSAA", "." ]
train
https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Printers/Utility/AfipWsv1.php#L471-L494
alevilar/ristorantino-vendor
Printers/Utility/AfipWsv1.php
AfipWsv1.FEParamGetTiposTributos
static function FEParamGetTiposTributos () { $res = self::$client->FEParamGetTiposTributos( array('Auth'=> self::$authVars)); self::__throwErrorIfExists($res, 'FEParamGetTiposTributosResult'); return $res; }
php
static function FEParamGetTiposTributos () { $res = self::$client->FEParamGetTiposTributos( array('Auth'=> self::$authVars)); self::__throwErrorIfExists($res, 'FEParamGetTiposTributosResult'); return $res; }
[ "static", "function", "FEParamGetTiposTributos", "(", ")", "{", "$", "res", "=", "self", "::", "$", "client", "->", "FEParamGetTiposTributos", "(", "array", "(", "'Auth'", "=>", "self", "::", "$", "authVars", ")", ")", ";", "self", "::", "__throwErrorIfExists", "(", "$", "res", ",", "'FEParamGetTiposTributosResult'", ")", ";", "return", "$", "res", ";", "}" ]
Indica los Tipos de Tributos Nacionales, Provinciales, Municipales, Internos, etc etc EJ: array( (int) 0 => object(stdClass) { Id => (int) 1 Desc => 'Impuestos nacionales' FchDesde => '20100917' FchHasta => 'NULL' },
[ "Indica", "los", "Tipos", "de", "Tributos", "Nacionales", "Provinciales", "Municipales", "Internos", "etc", "etc", "EJ", ":", "array", "(", "(", "int", ")", "0", "=", ">", "object", "(", "stdClass", ")", "{", "Id", "=", ">", "(", "int", ")", "1", "Desc", "=", ">", "Impuestos", "nacionales", "FchDesde", "=", ">", "20100917", "FchHasta", "=", ">", "NULL", "}" ]
train
https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Printers/Utility/AfipWsv1.php#L596-L602
kbond/ControllerUtil
src/FlashRedirect.php
FlashRedirect.create
public static function create($route, array $parameters, $message, $type = self::DEFAULT_FLASH_KEY, $statusCode = self::DEFAULT_STATUS_CODE) { return new static($route, $parameters, array($type => array($message)), $statusCode); }
php
public static function create($route, array $parameters, $message, $type = self::DEFAULT_FLASH_KEY, $statusCode = self::DEFAULT_STATUS_CODE) { return new static($route, $parameters, array($type => array($message)), $statusCode); }
[ "public", "static", "function", "create", "(", "$", "route", ",", "array", "$", "parameters", ",", "$", "message", ",", "$", "type", "=", "self", "::", "DEFAULT_FLASH_KEY", ",", "$", "statusCode", "=", "self", "::", "DEFAULT_STATUS_CODE", ")", "{", "return", "new", "static", "(", "$", "route", ",", "$", "parameters", ",", "array", "(", "$", "type", "=>", "array", "(", "$", "message", ")", ")", ",", "$", "statusCode", ")", ";", "}" ]
@param string $route @param array $parameters @param string $message @param string $type @param int $statusCode @return static
[ "@param", "string", "$route", "@param", "array", "$parameters", "@param", "string", "$message", "@param", "string", "$type", "@param", "int", "$statusCode" ]
train
https://github.com/kbond/ControllerUtil/blob/67375d43c73d6a3f16356f3d683f62b176766e91/src/FlashRedirect.php#L21-L24
kbond/ControllerUtil
src/FlashRedirect.php
FlashRedirect.createSimple
public static function createSimple($route, $message, $type = self::DEFAULT_FLASH_KEY, $statusCode = self::DEFAULT_STATUS_CODE) { return new static($route, array(), array($type => array($message)), $statusCode); }
php
public static function createSimple($route, $message, $type = self::DEFAULT_FLASH_KEY, $statusCode = self::DEFAULT_STATUS_CODE) { return new static($route, array(), array($type => array($message)), $statusCode); }
[ "public", "static", "function", "createSimple", "(", "$", "route", ",", "$", "message", ",", "$", "type", "=", "self", "::", "DEFAULT_FLASH_KEY", ",", "$", "statusCode", "=", "self", "::", "DEFAULT_STATUS_CODE", ")", "{", "return", "new", "static", "(", "$", "route", ",", "array", "(", ")", ",", "array", "(", "$", "type", "=>", "array", "(", "$", "message", ")", ")", ",", "$", "statusCode", ")", ";", "}" ]
@param string $route @param string $message @param string $type @param int $statusCode @return static
[ "@param", "string", "$route", "@param", "string", "$message", "@param", "string", "$type", "@param", "int", "$statusCode" ]
train
https://github.com/kbond/ControllerUtil/blob/67375d43c73d6a3f16356f3d683f62b176766e91/src/FlashRedirect.php#L34-L37
zicht/z
src/Zicht/Tool/Script/Compiler.php
Compiler.parse
public function parse($input) { if (strlen($input) == 0) { return null; } return $this->parser->parse(new TokenStream($this->tokenizer->getTokens($input))); }
php
public function parse($input) { if (strlen($input) == 0) { return null; } return $this->parser->parse(new TokenStream($this->tokenizer->getTokens($input))); }
[ "public", "function", "parse", "(", "$", "input", ")", "{", "if", "(", "strlen", "(", "$", "input", ")", "==", "0", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "parser", "->", "parse", "(", "new", "TokenStream", "(", "$", "this", "->", "tokenizer", "->", "getTokens", "(", "$", "input", ")", ")", ")", ";", "}" ]
Parses the raw string input and returns the resulting root node. @param string $input @return Node
[ "Parses", "the", "raw", "string", "input", "and", "returns", "the", "resulting", "root", "node", "." ]
train
https://github.com/zicht/z/blob/6a1731dad20b018555a96b726a61d4bf8ec8c886/src/Zicht/Tool/Script/Compiler.php#L36-L42
zicht/z
src/Zicht/Tool/Script/Compiler.php
Compiler.compile
public function compile($input) { if (strlen($input) == 0) { return null; } try { $buffer = new Buffer(); $this->parse($input)->compile($buffer); $code = $buffer->getResult(); return $code; } catch (\UnexpectedValueException $e) { throw new \UnexpectedValueException('Error while compiling input: ' . Util::toPhp($input), 0, $e); } }
php
public function compile($input) { if (strlen($input) == 0) { return null; } try { $buffer = new Buffer(); $this->parse($input)->compile($buffer); $code = $buffer->getResult(); return $code; } catch (\UnexpectedValueException $e) { throw new \UnexpectedValueException('Error while compiling input: ' . Util::toPhp($input), 0, $e); } }
[ "public", "function", "compile", "(", "$", "input", ")", "{", "if", "(", "strlen", "(", "$", "input", ")", "==", "0", ")", "{", "return", "null", ";", "}", "try", "{", "$", "buffer", "=", "new", "Buffer", "(", ")", ";", "$", "this", "->", "parse", "(", "$", "input", ")", "->", "compile", "(", "$", "buffer", ")", ";", "$", "code", "=", "$", "buffer", "->", "getResult", "(", ")", ";", "return", "$", "code", ";", "}", "catch", "(", "\\", "UnexpectedValueException", "$", "e", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "'Error while compiling input: '", ".", "Util", "::", "toPhp", "(", "$", "input", ")", ",", "0", ",", "$", "e", ")", ";", "}", "}" ]
Compile an input string to PHP code @param string $input @return string
[ "Compile", "an", "input", "string", "to", "PHP", "code" ]
train
https://github.com/zicht/z/blob/6a1731dad20b018555a96b726a61d4bf8ec8c886/src/Zicht/Tool/Script/Compiler.php#L50-L63
zhouyl/mellivora
Mellivora/Cache/PdoConnector.php
PdoConnector.getCacheAdapter
public function getCacheAdapter() { return $this->autoCreateTable(new PdoAdapter( $this->config['connection'], $this->config['namespace'], $this->config['lifetime'], $this->config['options'] )); }
php
public function getCacheAdapter() { return $this->autoCreateTable(new PdoAdapter( $this->config['connection'], $this->config['namespace'], $this->config['lifetime'], $this->config['options'] )); }
[ "public", "function", "getCacheAdapter", "(", ")", "{", "return", "$", "this", "->", "autoCreateTable", "(", "new", "PdoAdapter", "(", "$", "this", "->", "config", "[", "'connection'", "]", ",", "$", "this", "->", "config", "[", "'namespace'", "]", ",", "$", "this", "->", "config", "[", "'lifetime'", "]", ",", "$", "this", "->", "config", "[", "'options'", "]", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Cache/PdoConnector.php#L40-L48
zhouyl/mellivora
Mellivora/Cache/PdoConnector.php
PdoConnector.getSimpleCacheAdapter
public function getSimpleCacheAdapter() { return $this->autoCreateTable(new PdoCache( $this->config['connection'], $this->config['namespace'], $this->config['lifetime'], $this->config['options'] )); }
php
public function getSimpleCacheAdapter() { return $this->autoCreateTable(new PdoCache( $this->config['connection'], $this->config['namespace'], $this->config['lifetime'], $this->config['options'] )); }
[ "public", "function", "getSimpleCacheAdapter", "(", ")", "{", "return", "$", "this", "->", "autoCreateTable", "(", "new", "PdoCache", "(", "$", "this", "->", "config", "[", "'connection'", "]", ",", "$", "this", "->", "config", "[", "'namespace'", "]", ",", "$", "this", "->", "config", "[", "'lifetime'", "]", ",", "$", "this", "->", "config", "[", "'options'", "]", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Cache/PdoConnector.php#L53-L61
zhouyl/mellivora
Mellivora/Cache/PdoConnector.php
PdoConnector.autoCreateTable
protected function autoCreateTable($cache) { $lockfile = sys_get_temp_dir() . '/mellivora-cache-pdo.lock'; if (!is_file($lockfile)) { try { $cache->createTable(); } catch (\PDOException $e) { } finally { @file_put_contents($lockfile, time()); } } return $cache; }
php
protected function autoCreateTable($cache) { $lockfile = sys_get_temp_dir() . '/mellivora-cache-pdo.lock'; if (!is_file($lockfile)) { try { $cache->createTable(); } catch (\PDOException $e) { } finally { @file_put_contents($lockfile, time()); } } return $cache; }
[ "protected", "function", "autoCreateTable", "(", "$", "cache", ")", "{", "$", "lockfile", "=", "sys_get_temp_dir", "(", ")", ".", "'/mellivora-cache-pdo.lock'", ";", "if", "(", "!", "is_file", "(", "$", "lockfile", ")", ")", "{", "try", "{", "$", "cache", "->", "createTable", "(", ")", ";", "}", "catch", "(", "\\", "PDOException", "$", "e", ")", "{", "}", "finally", "{", "@", "file_put_contents", "(", "$", "lockfile", ",", "time", "(", ")", ")", ";", "}", "}", "return", "$", "cache", ";", "}" ]
自动创建数据表 @param object $cache @return object
[ "自动创建数据表" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Cache/PdoConnector.php#L70-L84
FrenzelGmbH/cm-address
models/CountrySearch.php
CountrySearch.search
public function search($params) { $query = Country::find()->active(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id, 'is_active' => $this->is_active, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, 'country_id' => $this->country_id, ]); $query->andFilterWhere(['like', 'iso2', $this->iso2]) ->andFilterWhere(['like', 'iso3', $this->iso3]) ->andFilterWhere(['like', 'name', $this->name]); return $dataProvider; }
php
public function search($params) { $query = Country::find()->active(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id, 'is_active' => $this->is_active, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, 'country_id' => $this->country_id, ]); $query->andFilterWhere(['like', 'iso2', $this->iso2]) ->andFilterWhere(['like', 'iso3', $this->iso3]) ->andFilterWhere(['like', 'name', $this->name]); return $dataProvider; }
[ "public", "function", "search", "(", "$", "params", ")", "{", "$", "query", "=", "Country", "::", "find", "(", ")", "->", "active", "(", ")", ";", "$", "dataProvider", "=", "new", "ActiveDataProvider", "(", "[", "'query'", "=>", "$", "query", ",", "]", ")", ";", "if", "(", "!", "(", "$", "this", "->", "load", "(", "$", "params", ")", "&&", "$", "this", "->", "validate", "(", ")", ")", ")", "{", "return", "$", "dataProvider", ";", "}", "$", "query", "->", "andFilterWhere", "(", "[", "'id'", "=>", "$", "this", "->", "id", ",", "'is_active'", "=>", "$", "this", "->", "is_active", ",", "'created_at'", "=>", "$", "this", "->", "created_at", ",", "'updated_at'", "=>", "$", "this", "->", "updated_at", ",", "'country_id'", "=>", "$", "this", "->", "country_id", ",", "]", ")", ";", "$", "query", "->", "andFilterWhere", "(", "[", "'like'", ",", "'iso2'", ",", "$", "this", "->", "iso2", "]", ")", "->", "andFilterWhere", "(", "[", "'like'", ",", "'iso3'", ",", "$", "this", "->", "iso3", "]", ")", "->", "andFilterWhere", "(", "[", "'like'", ",", "'name'", ",", "$", "this", "->", "name", "]", ")", ";", "return", "$", "dataProvider", ";", "}" ]
[search description] @param array $params [description] @param string $module [description] @param integer $id [description] @return [type] [description]
[ "[", "search", "description", "]" ]
train
https://github.com/FrenzelGmbH/cm-address/blob/4295671dc603beed4bea6c5a7f77dac9846127f3/models/CountrySearch.php#L45-L70
icicleio/cache
src/MemoryCache.php
MemoryCache.exists
public function exists(string $key): \Generator { yield from $this->wait($key); return array_key_exists($key, $this->data); }
php
public function exists(string $key): \Generator { yield from $this->wait($key); return array_key_exists($key, $this->data); }
[ "public", "function", "exists", "(", "string", "$", "key", ")", ":", "\\", "Generator", "{", "yield", "from", "$", "this", "->", "wait", "(", "$", "key", ")", ";", "return", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "data", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/icicleio/cache/blob/d4edeed7c36dc261f051f880d389db80bb3672cf/src/MemoryCache.php#L50-L55
icicleio/cache
src/MemoryCache.php
MemoryCache.get
public function get(string $key): \Generator { yield from $this->wait($key); return $this->fetch($key); }
php
public function get(string $key): \Generator { yield from $this->wait($key); return $this->fetch($key); }
[ "public", "function", "get", "(", "string", "$", "key", ")", ":", "\\", "Generator", "{", "yield", "from", "$", "this", "->", "wait", "(", "$", "key", ")", ";", "return", "$", "this", "->", "fetch", "(", "$", "key", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/icicleio/cache/blob/d4edeed7c36dc261f051f880d389db80bb3672cf/src/MemoryCache.php#L60-L65
icicleio/cache
src/MemoryCache.php
MemoryCache.set
public function set(string $key, $value, int $expiration = 0): \Generator { yield from $this->wait($key); $this->put($key, $value, $expiration); return true; }
php
public function set(string $key, $value, int $expiration = 0): \Generator { yield from $this->wait($key); $this->put($key, $value, $expiration); return true; }
[ "public", "function", "set", "(", "string", "$", "key", ",", "$", "value", ",", "int", "$", "expiration", "=", "0", ")", ":", "\\", "Generator", "{", "yield", "from", "$", "this", "->", "wait", "(", "$", "key", ")", ";", "$", "this", "->", "put", "(", "$", "key", ",", "$", "value", ",", "$", "expiration", ")", ";", "return", "true", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/icicleio/cache/blob/d4edeed7c36dc261f051f880d389db80bb3672cf/src/MemoryCache.php#L70-L77
icicleio/cache
src/MemoryCache.php
MemoryCache.add
public function add(string $key, $value, int $expiration = 0): \Generator { yield from $this->wait($key); if (isset($this->data[$key])) { return false; } $this->put($key, $value, $expiration); return true; }
php
public function add(string $key, $value, int $expiration = 0): \Generator { yield from $this->wait($key); if (isset($this->data[$key])) { return false; } $this->put($key, $value, $expiration); return true; }
[ "public", "function", "add", "(", "string", "$", "key", ",", "$", "value", ",", "int", "$", "expiration", "=", "0", ")", ":", "\\", "Generator", "{", "yield", "from", "$", "this", "->", "wait", "(", "$", "key", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "data", "[", "$", "key", "]", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "put", "(", "$", "key", ",", "$", "value", ",", "$", "expiration", ")", ";", "return", "true", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/icicleio/cache/blob/d4edeed7c36dc261f051f880d389db80bb3672cf/src/MemoryCache.php#L82-L93
icicleio/cache
src/MemoryCache.php
MemoryCache.fetch
protected function fetch(string $key) { if (!isset($this->data[$key])) { return; } // Reset timer if there was an expiration. if (isset($this->timers[$key])) { $this->timers[$key]->again(); } return $this->data[$key]; }
php
protected function fetch(string $key) { if (!isset($this->data[$key])) { return; } // Reset timer if there was an expiration. if (isset($this->timers[$key])) { $this->timers[$key]->again(); } return $this->data[$key]; }
[ "protected", "function", "fetch", "(", "string", "$", "key", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "data", "[", "$", "key", "]", ")", ")", "{", "return", ";", "}", "// Reset timer if there was an expiration.", "if", "(", "isset", "(", "$", "this", "->", "timers", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "timers", "[", "$", "key", "]", "->", "again", "(", ")", ";", "}", "return", "$", "this", "->", "data", "[", "$", "key", "]", ";", "}" ]
@param string $key @return mixed
[ "@param", "string", "$key" ]
train
https://github.com/icicleio/cache/blob/d4edeed7c36dc261f051f880d389db80bb3672cf/src/MemoryCache.php#L116-L128
icicleio/cache
src/MemoryCache.php
MemoryCache.delete
public function delete(string $key): \Generator { yield from $this->wait($key); unset($this->data[$key]); if (isset($this->timers[$key])) { $this->timers[$key]->stop(); unset($this->timers[$key]); } return true; }
php
public function delete(string $key): \Generator { yield from $this->wait($key); unset($this->data[$key]); if (isset($this->timers[$key])) { $this->timers[$key]->stop(); unset($this->timers[$key]); } return true; }
[ "public", "function", "delete", "(", "string", "$", "key", ")", ":", "\\", "Generator", "{", "yield", "from", "$", "this", "->", "wait", "(", "$", "key", ")", ";", "unset", "(", "$", "this", "->", "data", "[", "$", "key", "]", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "timers", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "timers", "[", "$", "key", "]", "->", "stop", "(", ")", ";", "unset", "(", "$", "this", "->", "timers", "[", "$", "key", "]", ")", ";", "}", "return", "true", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/icicleio/cache/blob/d4edeed7c36dc261f051f880d389db80bb3672cf/src/MemoryCache.php#L153-L165
icicleio/cache
src/MemoryCache.php
MemoryCache.update
public function update(string $key, callable $callback, int $expiration = 0): \Generator { yield from $this->wait($key); $this->lock($key); try { $result = $callback(isset($this->data[$key]) ? $this->data[$key] : null); if ($result instanceof \Generator) { $result = yield from $result; } elseif ($result instanceof Awaitable) { $result = yield $result; } $this->put($key, $result, $expiration); } finally { $this->unlock($key); } return $result; }
php
public function update(string $key, callable $callback, int $expiration = 0): \Generator { yield from $this->wait($key); $this->lock($key); try { $result = $callback(isset($this->data[$key]) ? $this->data[$key] : null); if ($result instanceof \Generator) { $result = yield from $result; } elseif ($result instanceof Awaitable) { $result = yield $result; } $this->put($key, $result, $expiration); } finally { $this->unlock($key); } return $result; }
[ "public", "function", "update", "(", "string", "$", "key", ",", "callable", "$", "callback", ",", "int", "$", "expiration", "=", "0", ")", ":", "\\", "Generator", "{", "yield", "from", "$", "this", "->", "wait", "(", "$", "key", ")", ";", "$", "this", "->", "lock", "(", "$", "key", ")", ";", "try", "{", "$", "result", "=", "$", "callback", "(", "isset", "(", "$", "this", "->", "data", "[", "$", "key", "]", ")", "?", "$", "this", "->", "data", "[", "$", "key", "]", ":", "null", ")", ";", "if", "(", "$", "result", "instanceof", "\\", "Generator", ")", "{", "$", "result", "=", "yield", "from", "$", "result", ";", "}", "elseif", "(", "$", "result", "instanceof", "Awaitable", ")", "{", "$", "result", "=", "yield", "$", "result", ";", "}", "$", "this", "->", "put", "(", "$", "key", ",", "$", "result", ",", "$", "expiration", ")", ";", "}", "finally", "{", "$", "this", "->", "unlock", "(", "$", "key", ")", ";", "}", "return", "$", "result", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/icicleio/cache/blob/d4edeed7c36dc261f051f880d389db80bb3672cf/src/MemoryCache.php#L170-L191
icicleio/cache
src/MemoryCache.php
MemoryCache.lock
protected function lock(string $key) { if (isset($this->locks[$key])) { throw new InvalidArgumentError('Key was already locked.'); } $this->locks[$key] = new Delayed(); }
php
protected function lock(string $key) { if (isset($this->locks[$key])) { throw new InvalidArgumentError('Key was already locked.'); } $this->locks[$key] = new Delayed(); }
[ "protected", "function", "lock", "(", "string", "$", "key", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "locks", "[", "$", "key", "]", ")", ")", "{", "throw", "new", "InvalidArgumentError", "(", "'Key was already locked.'", ")", ";", "}", "$", "this", "->", "locks", "[", "$", "key", "]", "=", "new", "Delayed", "(", ")", ";", "}" ]
Locks the given key until unlock() is called. @param string $key @throws \Icicle\Exception\InvalidArgumentError
[ "Locks", "the", "given", "key", "until", "unlock", "()", "is", "called", "." ]
train
https://github.com/icicleio/cache/blob/d4edeed7c36dc261f051f880d389db80bb3672cf/src/MemoryCache.php#L200-L207
icicleio/cache
src/MemoryCache.php
MemoryCache.unlock
protected function unlock(string $key) { if (!isset($this->locks[$key])) { throw new InvalidArgumentError('No lock was set on the given key.'); } $awaitable = $this->locks[$key]; unset($this->locks[$key]); $awaitable->resolve(); }
php
protected function unlock(string $key) { if (!isset($this->locks[$key])) { throw new InvalidArgumentError('No lock was set on the given key.'); } $awaitable = $this->locks[$key]; unset($this->locks[$key]); $awaitable->resolve(); }
[ "protected", "function", "unlock", "(", "string", "$", "key", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "locks", "[", "$", "key", "]", ")", ")", "{", "throw", "new", "InvalidArgumentError", "(", "'No lock was set on the given key.'", ")", ";", "}", "$", "awaitable", "=", "$", "this", "->", "locks", "[", "$", "key", "]", ";", "unset", "(", "$", "this", "->", "locks", "[", "$", "key", "]", ")", ";", "$", "awaitable", "->", "resolve", "(", ")", ";", "}" ]
Unlocks the given key. Throws if the key was not locked. @param string $key @throws \Icicle\Exception\InvalidArgumentError
[ "Unlocks", "the", "given", "key", ".", "Throws", "if", "the", "key", "was", "not", "locked", "." ]
train
https://github.com/icicleio/cache/blob/d4edeed7c36dc261f051f880d389db80bb3672cf/src/MemoryCache.php#L216-L225
icicleio/cache
src/MemoryCache.php
MemoryCache.wait
protected function wait(string $key): \Generator { if (isset($this->locks[$key])) { do { yield $this->locks[$key]; } while (isset($this->locks[$key])); return true; } return false; }
php
protected function wait(string $key): \Generator { if (isset($this->locks[$key])) { do { yield $this->locks[$key]; } while (isset($this->locks[$key])); return true; } return false; }
[ "protected", "function", "wait", "(", "string", "$", "key", ")", ":", "\\", "Generator", "{", "if", "(", "isset", "(", "$", "this", "->", "locks", "[", "$", "key", "]", ")", ")", "{", "do", "{", "yield", "$", "this", "->", "locks", "[", "$", "key", "]", ";", "}", "while", "(", "isset", "(", "$", "this", "->", "locks", "[", "$", "key", "]", ")", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
@coroutine @param string $key @return \Generator @resolve bool
[ "@coroutine" ]
train
https://github.com/icicleio/cache/blob/d4edeed7c36dc261f051f880d389db80bb3672cf/src/MemoryCache.php#L236-L247
JBZoo/Profiler
src/Benchmark.php
Benchmark.add
public function add($name, \Closure $closure) { $test = new Test($name, $closure); $this->addTest($test); return $test; }
php
public function add($name, \Closure $closure) { $test = new Test($name, $closure); $this->addTest($test); return $test; }
[ "public", "function", "add", "(", "$", "name", ",", "\\", "Closure", "$", "closure", ")", "{", "$", "test", "=", "new", "Test", "(", "$", "name", ",", "$", "closure", ")", ";", "$", "this", "->", "addTest", "(", "$", "test", ")", ";", "return", "$", "test", ";", "}" ]
Utility method to create tests on the fly. You may chain the test: @param string $name @param \Closure $closure function to execute @return Test
[ "Utility", "method", "to", "create", "tests", "on", "the", "fly", ".", "You", "may", "chain", "the", "test", ":" ]
train
https://github.com/JBZoo/Profiler/blob/a4af3d2feb558ab9cd78012e0ca5c8dc7872fc69/src/Benchmark.php#L66-L72
JBZoo/Profiler
src/Benchmark.php
Benchmark._warmup
private function _warmup() { $warmup = new Test('warmup', function () { }); $this->_overhead = $warmup->runTest($this->_count); // One call each method for init (warmup) /** @var Test $test */ foreach ($this->_tests as $test) { $test->runTest(1); } $this->out( 'PHP Overhead: ' . 'time=' . Timer::formatMS($this->_overhead['time']) . '; ' . 'memory=' . FS::format($this->_overhead['memory'], 2) . ';' . PHP_EOL ); }
php
private function _warmup() { $warmup = new Test('warmup', function () { }); $this->_overhead = $warmup->runTest($this->_count); // One call each method for init (warmup) /** @var Test $test */ foreach ($this->_tests as $test) { $test->runTest(1); } $this->out( 'PHP Overhead: ' . 'time=' . Timer::formatMS($this->_overhead['time']) . '; ' . 'memory=' . FS::format($this->_overhead['memory'], 2) . ';' . PHP_EOL ); }
[ "private", "function", "_warmup", "(", ")", "{", "$", "warmup", "=", "new", "Test", "(", "'warmup'", ",", "function", "(", ")", "{", "}", ")", ";", "$", "this", "->", "_overhead", "=", "$", "warmup", "->", "runTest", "(", "$", "this", "->", "_count", ")", ";", "// One call each method for init (warmup)", "/** @var Test $test */", "foreach", "(", "$", "this", "->", "_tests", "as", "$", "test", ")", "{", "$", "test", "->", "runTest", "(", "1", ")", ";", "}", "$", "this", "->", "out", "(", "'PHP Overhead: '", ".", "'time='", ".", "Timer", "::", "formatMS", "(", "$", "this", "->", "_overhead", "[", "'time'", "]", ")", ".", "'; '", ".", "'memory='", ".", "FS", "::", "format", "(", "$", "this", "->", "_overhead", "[", "'memory'", "]", ",", "2", ")", ".", "';'", ".", "PHP_EOL", ")", ";", "}" ]
Runs an empty test to determine the benchmark overhead and run each test once
[ "Runs", "an", "empty", "test", "to", "determine", "the", "benchmark", "overhead", "and", "run", "each", "test", "once" ]
train
https://github.com/JBZoo/Profiler/blob/a4af3d2feb558ab9cd78012e0ca5c8dc7872fc69/src/Benchmark.php#L77-L97
JBZoo/Profiler
src/Benchmark.php
Benchmark.outputTable
public function outputTable(array $lines, $padding = 4) { $pad = function ($string, $width) use ($padding) { if ($width > 0) { return str_pad($string, $width, ' ') . str_repeat(' ', $padding); } else { return str_pad($string, -$width, ' ', STR_PAD_LEFT) . str_repeat(' ', $padding); } }; // init width with keys' length $cols = array_combine( array_keys($lines[0]), array_map('strlen', array_keys($lines[0])) ); foreach ($cols as $col => $width) { foreach ($lines as $line) { $width = max($width, strlen($line[$col])); } if ($col !== self::COL_NAME) { $width = -$width; } $this->out($pad($col, $width), false); $cols[$col] = $width; } $this->out(''); foreach ($lines as $line) { foreach ($cols as $col => $width) { $this->out($pad($line[$col], $width), false); } $this->out(''); } }
php
public function outputTable(array $lines, $padding = 4) { $pad = function ($string, $width) use ($padding) { if ($width > 0) { return str_pad($string, $width, ' ') . str_repeat(' ', $padding); } else { return str_pad($string, -$width, ' ', STR_PAD_LEFT) . str_repeat(' ', $padding); } }; // init width with keys' length $cols = array_combine( array_keys($lines[0]), array_map('strlen', array_keys($lines[0])) ); foreach ($cols as $col => $width) { foreach ($lines as $line) { $width = max($width, strlen($line[$col])); } if ($col !== self::COL_NAME) { $width = -$width; } $this->out($pad($col, $width), false); $cols[$col] = $width; } $this->out(''); foreach ($lines as $line) { foreach ($cols as $col => $width) { $this->out($pad($line[$col], $width), false); } $this->out(''); } }
[ "public", "function", "outputTable", "(", "array", "$", "lines", ",", "$", "padding", "=", "4", ")", "{", "$", "pad", "=", "function", "(", "$", "string", ",", "$", "width", ")", "use", "(", "$", "padding", ")", "{", "if", "(", "$", "width", ">", "0", ")", "{", "return", "str_pad", "(", "$", "string", ",", "$", "width", ",", "' '", ")", ".", "str_repeat", "(", "' '", ",", "$", "padding", ")", ";", "}", "else", "{", "return", "str_pad", "(", "$", "string", ",", "-", "$", "width", ",", "' '", ",", "STR_PAD_LEFT", ")", ".", "str_repeat", "(", "' '", ",", "$", "padding", ")", ";", "}", "}", ";", "// init width with keys' length", "$", "cols", "=", "array_combine", "(", "array_keys", "(", "$", "lines", "[", "0", "]", ")", ",", "array_map", "(", "'strlen'", ",", "array_keys", "(", "$", "lines", "[", "0", "]", ")", ")", ")", ";", "foreach", "(", "$", "cols", "as", "$", "col", "=>", "$", "width", ")", "{", "foreach", "(", "$", "lines", "as", "$", "line", ")", "{", "$", "width", "=", "max", "(", "$", "width", ",", "strlen", "(", "$", "line", "[", "$", "col", "]", ")", ")", ";", "}", "if", "(", "$", "col", "!==", "self", "::", "COL_NAME", ")", "{", "$", "width", "=", "-", "$", "width", ";", "}", "$", "this", "->", "out", "(", "$", "pad", "(", "$", "col", ",", "$", "width", ")", ",", "false", ")", ";", "$", "cols", "[", "$", "col", "]", "=", "$", "width", ";", "}", "$", "this", "->", "out", "(", "''", ")", ";", "foreach", "(", "$", "lines", "as", "$", "line", ")", "{", "foreach", "(", "$", "cols", "as", "$", "col", "=>", "$", "width", ")", "{", "$", "this", "->", "out", "(", "$", "pad", "(", "$", "line", "[", "$", "col", "]", ",", "$", "width", ")", ",", "false", ")", ";", "}", "$", "this", "->", "out", "(", "''", ")", ";", "}", "}" ]
Output results in columns, padding right if values are string, left if numeric @param array $lines array(array('Name' => 'Value')); @param integer $padding space between columns
[ "Output", "results", "in", "columns", "padding", "right", "if", "values", "are", "string", "left", "if", "numeric" ]
train
https://github.com/JBZoo/Profiler/blob/a4af3d2feb558ab9cd78012e0ca5c8dc7872fc69/src/Benchmark.php#L156-L194
JBZoo/Profiler
src/Benchmark.php
Benchmark.formatResults
public function formatResults(array $results) { uasort($results['list'], function ($testOne, $testTwo) { if ($testOne['time'] === $testTwo['time']) { return 0; } else { return ($testOne['time'] < $testTwo['time']) ? -1 : 1; } }); $minTime = INF; $minMemory = INF; foreach ($results['list'] as $name => $result) { // time $time = $result['time']; //$time -= $this->_overhead['time']; // Substract base_time $results['list'][$name]['time'] = $time; $minTime = min($minTime, $time); // memory $memory = $results['list'][$name]['memory']; $memory -= $this->_overhead['memory']; $results['list'][$name]['memory'] = $memory; $minMemory = min($minMemory, $memory); } $output = array(); $isOne = count($results['list']) === 1; foreach ($results['list'] as $name => $result) { if ($isOne) { $output[] = array( self::COL_NAME => $name, self::COL_TIME => $this->_timeFormat($result['time'], 0), self::COL_TIME_ONE => $this->_timeFormat($result['time'] / $this->_count), self::COL_MEMORY => FS::format($result['memory'], 2), ); } else { $output[] = array( self::COL_NAME => $name, self::COL_TIME => $this->_timeFormat($result['time'], 0), self::COL_TIME_ONE => $this->_timeFormat($result['time'] / $this->_count), self::COL_TIME_REL => Vars::relativePercent($minTime, $result['time']), self::COL_MEMORY => FS::format($result['memory'], 2), self::COL_MEMORY_REL => Vars::relativePercent($minMemory, $result['memory']), ); } } return $output; }
php
public function formatResults(array $results) { uasort($results['list'], function ($testOne, $testTwo) { if ($testOne['time'] === $testTwo['time']) { return 0; } else { return ($testOne['time'] < $testTwo['time']) ? -1 : 1; } }); $minTime = INF; $minMemory = INF; foreach ($results['list'] as $name => $result) { // time $time = $result['time']; //$time -= $this->_overhead['time']; // Substract base_time $results['list'][$name]['time'] = $time; $minTime = min($minTime, $time); // memory $memory = $results['list'][$name]['memory']; $memory -= $this->_overhead['memory']; $results['list'][$name]['memory'] = $memory; $minMemory = min($minMemory, $memory); } $output = array(); $isOne = count($results['list']) === 1; foreach ($results['list'] as $name => $result) { if ($isOne) { $output[] = array( self::COL_NAME => $name, self::COL_TIME => $this->_timeFormat($result['time'], 0), self::COL_TIME_ONE => $this->_timeFormat($result['time'] / $this->_count), self::COL_MEMORY => FS::format($result['memory'], 2), ); } else { $output[] = array( self::COL_NAME => $name, self::COL_TIME => $this->_timeFormat($result['time'], 0), self::COL_TIME_ONE => $this->_timeFormat($result['time'] / $this->_count), self::COL_TIME_REL => Vars::relativePercent($minTime, $result['time']), self::COL_MEMORY => FS::format($result['memory'], 2), self::COL_MEMORY_REL => Vars::relativePercent($minMemory, $result['memory']), ); } } return $output; }
[ "public", "function", "formatResults", "(", "array", "$", "results", ")", "{", "uasort", "(", "$", "results", "[", "'list'", "]", ",", "function", "(", "$", "testOne", ",", "$", "testTwo", ")", "{", "if", "(", "$", "testOne", "[", "'time'", "]", "===", "$", "testTwo", "[", "'time'", "]", ")", "{", "return", "0", ";", "}", "else", "{", "return", "(", "$", "testOne", "[", "'time'", "]", "<", "$", "testTwo", "[", "'time'", "]", ")", "?", "-", "1", ":", "1", ";", "}", "}", ")", ";", "$", "minTime", "=", "INF", ";", "$", "minMemory", "=", "INF", ";", "foreach", "(", "$", "results", "[", "'list'", "]", "as", "$", "name", "=>", "$", "result", ")", "{", "// time", "$", "time", "=", "$", "result", "[", "'time'", "]", ";", "//$time -= $this->_overhead['time']; // Substract base_time", "$", "results", "[", "'list'", "]", "[", "$", "name", "]", "[", "'time'", "]", "=", "$", "time", ";", "$", "minTime", "=", "min", "(", "$", "minTime", ",", "$", "time", ")", ";", "// memory", "$", "memory", "=", "$", "results", "[", "'list'", "]", "[", "$", "name", "]", "[", "'memory'", "]", ";", "$", "memory", "-=", "$", "this", "->", "_overhead", "[", "'memory'", "]", ";", "$", "results", "[", "'list'", "]", "[", "$", "name", "]", "[", "'memory'", "]", "=", "$", "memory", ";", "$", "minMemory", "=", "min", "(", "$", "minMemory", ",", "$", "memory", ")", ";", "}", "$", "output", "=", "array", "(", ")", ";", "$", "isOne", "=", "count", "(", "$", "results", "[", "'list'", "]", ")", "===", "1", ";", "foreach", "(", "$", "results", "[", "'list'", "]", "as", "$", "name", "=>", "$", "result", ")", "{", "if", "(", "$", "isOne", ")", "{", "$", "output", "[", "]", "=", "array", "(", "self", "::", "COL_NAME", "=>", "$", "name", ",", "self", "::", "COL_TIME", "=>", "$", "this", "->", "_timeFormat", "(", "$", "result", "[", "'time'", "]", ",", "0", ")", ",", "self", "::", "COL_TIME_ONE", "=>", "$", "this", "->", "_timeFormat", "(", "$", "result", "[", "'time'", "]", "/", "$", "this", "->", "_count", ")", ",", "self", "::", "COL_MEMORY", "=>", "FS", "::", "format", "(", "$", "result", "[", "'memory'", "]", ",", "2", ")", ",", ")", ";", "}", "else", "{", "$", "output", "[", "]", "=", "array", "(", "self", "::", "COL_NAME", "=>", "$", "name", ",", "self", "::", "COL_TIME", "=>", "$", "this", "->", "_timeFormat", "(", "$", "result", "[", "'time'", "]", ",", "0", ")", ",", "self", "::", "COL_TIME_ONE", "=>", "$", "this", "->", "_timeFormat", "(", "$", "result", "[", "'time'", "]", "/", "$", "this", "->", "_count", ")", ",", "self", "::", "COL_TIME_REL", "=>", "Vars", "::", "relativePercent", "(", "$", "minTime", ",", "$", "result", "[", "'time'", "]", ")", ",", "self", "::", "COL_MEMORY", "=>", "FS", "::", "format", "(", "$", "result", "[", "'memory'", "]", ",", "2", ")", ",", "self", "::", "COL_MEMORY_REL", "=>", "Vars", "::", "relativePercent", "(", "$", "minMemory", ",", "$", "result", "[", "'memory'", "]", ")", ",", ")", ";", "}", "}", "return", "$", "output", ";", "}" ]
Format the results, rounding numbers, showing difference percentages and removing a flat time based on the benchmark overhead @param array $results array($name => array('time' => 1.0)) @return array array(array('Test' => $name, 'Time' => '1000 ms', 'Perc' => '100 %'))
[ "Format", "the", "results", "rounding", "numbers", "showing", "difference", "percentages", "and", "removing", "a", "flat", "time", "based", "on", "the", "benchmark", "overhead" ]
train
https://github.com/JBZoo/Profiler/blob/a4af3d2feb558ab9cd78012e0ca5c8dc7872fc69/src/Benchmark.php#L203-L256
Avatar4eg/flarum-ext-geotags
src/Api/Controller/ListGeotagsController.php
ListGeotagsController.data
protected function data(ServerRequestInterface $request, Document $document) { $filter = $this->extractFilter($request); $include = $this->extractInclude($request); $where = []; $sort = $this->extractSort($request); $limit = $this->extractLimit($request); $offset = $this->extractOffset($request); if ($postIds = array_get($filter, 'id')) { $geotags = $this->geotags->findByIds(explode(',', $postIds)); } else { if ($countryIso = array_get($filter, 'country')) { $where['country'] = $countryIso; } $geotags = $this->geotags->findWhere($where, $sort, $limit, $offset); } $total = $this->geotags->query()->count(); $document->addPaginationLinks( $this->url->toRoute('avatar4eg.geotags.index'), $request->getQueryParams(), $offset, $limit, $total ); return $geotags->load($include); }
php
protected function data(ServerRequestInterface $request, Document $document) { $filter = $this->extractFilter($request); $include = $this->extractInclude($request); $where = []; $sort = $this->extractSort($request); $limit = $this->extractLimit($request); $offset = $this->extractOffset($request); if ($postIds = array_get($filter, 'id')) { $geotags = $this->geotags->findByIds(explode(',', $postIds)); } else { if ($countryIso = array_get($filter, 'country')) { $where['country'] = $countryIso; } $geotags = $this->geotags->findWhere($where, $sort, $limit, $offset); } $total = $this->geotags->query()->count(); $document->addPaginationLinks( $this->url->toRoute('avatar4eg.geotags.index'), $request->getQueryParams(), $offset, $limit, $total ); return $geotags->load($include); }
[ "protected", "function", "data", "(", "ServerRequestInterface", "$", "request", ",", "Document", "$", "document", ")", "{", "$", "filter", "=", "$", "this", "->", "extractFilter", "(", "$", "request", ")", ";", "$", "include", "=", "$", "this", "->", "extractInclude", "(", "$", "request", ")", ";", "$", "where", "=", "[", "]", ";", "$", "sort", "=", "$", "this", "->", "extractSort", "(", "$", "request", ")", ";", "$", "limit", "=", "$", "this", "->", "extractLimit", "(", "$", "request", ")", ";", "$", "offset", "=", "$", "this", "->", "extractOffset", "(", "$", "request", ")", ";", "if", "(", "$", "postIds", "=", "array_get", "(", "$", "filter", ",", "'id'", ")", ")", "{", "$", "geotags", "=", "$", "this", "->", "geotags", "->", "findByIds", "(", "explode", "(", "','", ",", "$", "postIds", ")", ")", ";", "}", "else", "{", "if", "(", "$", "countryIso", "=", "array_get", "(", "$", "filter", ",", "'country'", ")", ")", "{", "$", "where", "[", "'country'", "]", "=", "$", "countryIso", ";", "}", "$", "geotags", "=", "$", "this", "->", "geotags", "->", "findWhere", "(", "$", "where", ",", "$", "sort", ",", "$", "limit", ",", "$", "offset", ")", ";", "}", "$", "total", "=", "$", "this", "->", "geotags", "->", "query", "(", ")", "->", "count", "(", ")", ";", "$", "document", "->", "addPaginationLinks", "(", "$", "this", "->", "url", "->", "toRoute", "(", "'avatar4eg.geotags.index'", ")", ",", "$", "request", "->", "getQueryParams", "(", ")", ",", "$", "offset", ",", "$", "limit", ",", "$", "total", ")", ";", "return", "$", "geotags", "->", "load", "(", "$", "include", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/Avatar4eg/flarum-ext-geotags/blob/a54216a02a3e0abc908f9ba3aec69431f906fb92/src/Api/Controller/ListGeotagsController.php#L40-L70
zhouyl/mellivora
Mellivora/Database/Eloquent/Relations/BelongsToMany.php
BelongsToMany.get
public function get($columns = ['*']) { // First we'll add the proper select columns onto the query so it is run with // the proper columns. Then, we will get the results and hydrate out pivot // models with the result of those columns as a separate model relation. $columns = $this->query->getQuery()->columns ? [] : $columns; $builder = $this->query->applyScopes(); $models = $builder->addSelect( $this->shouldSelect($columns) )->getModels(); $this->hydratePivotRelation($models); // If we actually found models we will also eager load any relationships that // have been specified as needing to be eager loaded. This will solve the // n + 1 query problem for the developer and also increase performance. if (count($models) > 0) { $models = $builder->eagerLoadRelations($models); } return $this->related->newCollection($models); }
php
public function get($columns = ['*']) { // First we'll add the proper select columns onto the query so it is run with // the proper columns. Then, we will get the results and hydrate out pivot // models with the result of those columns as a separate model relation. $columns = $this->query->getQuery()->columns ? [] : $columns; $builder = $this->query->applyScopes(); $models = $builder->addSelect( $this->shouldSelect($columns) )->getModels(); $this->hydratePivotRelation($models); // If we actually found models we will also eager load any relationships that // have been specified as needing to be eager loaded. This will solve the // n + 1 query problem for the developer and also increase performance. if (count($models) > 0) { $models = $builder->eagerLoadRelations($models); } return $this->related->newCollection($models); }
[ "public", "function", "get", "(", "$", "columns", "=", "[", "'*'", "]", ")", "{", "// First we'll add the proper select columns onto the query so it is run with", "// the proper columns. Then, we will get the results and hydrate out pivot", "// models with the result of those columns as a separate model relation.", "$", "columns", "=", "$", "this", "->", "query", "->", "getQuery", "(", ")", "->", "columns", "?", "[", "]", ":", "$", "columns", ";", "$", "builder", "=", "$", "this", "->", "query", "->", "applyScopes", "(", ")", ";", "$", "models", "=", "$", "builder", "->", "addSelect", "(", "$", "this", "->", "shouldSelect", "(", "$", "columns", ")", ")", "->", "getModels", "(", ")", ";", "$", "this", "->", "hydratePivotRelation", "(", "$", "models", ")", ";", "// If we actually found models we will also eager load any relationships that", "// have been specified as needing to be eager loaded. This will solve the", "// n + 1 query problem for the developer and also increase performance.", "if", "(", "count", "(", "$", "models", ")", ">", "0", ")", "{", "$", "models", "=", "$", "builder", "->", "eagerLoadRelations", "(", "$", "models", ")", ";", "}", "return", "$", "this", "->", "related", "->", "newCollection", "(", "$", "models", ")", ";", "}" ]
Execute the query as a "select" statement. @param array $columns @return \Mellivora\Database\Eloquent\Collection
[ "Execute", "the", "query", "as", "a", "select", "statement", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Eloquent/Relations/BelongsToMany.php#L502-L525
zhouyl/mellivora
Mellivora/Database/Eloquent/Relations/BelongsToMany.php
BelongsToMany.shouldSelect
protected function shouldSelect(array $columns = ['*']) { if ($columns === ['*']) { $columns = [$this->related->getTable() . '.*']; } return array_merge($columns, $this->aliasedPivotColumns()); }
php
protected function shouldSelect(array $columns = ['*']) { if ($columns === ['*']) { $columns = [$this->related->getTable() . '.*']; } return array_merge($columns, $this->aliasedPivotColumns()); }
[ "protected", "function", "shouldSelect", "(", "array", "$", "columns", "=", "[", "'*'", "]", ")", "{", "if", "(", "$", "columns", "===", "[", "'*'", "]", ")", "{", "$", "columns", "=", "[", "$", "this", "->", "related", "->", "getTable", "(", ")", ".", "'.*'", "]", ";", "}", "return", "array_merge", "(", "$", "columns", ",", "$", "this", "->", "aliasedPivotColumns", "(", ")", ")", ";", "}" ]
Get the select columns for the relation query. @param array $columns @return \Mellivora\Database\Eloquent\Relations\BelongsToMany
[ "Get", "the", "select", "columns", "for", "the", "relation", "query", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Eloquent/Relations/BelongsToMany.php#L534-L541
zhouyl/mellivora
Mellivora/Database/Eloquent/Relations/BelongsToMany.php
BelongsToMany.aliasedPivotColumns
protected function aliasedPivotColumns() { $defaults = [$this->foreignKey, $this->relatedKey]; return collect(array_merge($defaults, $this->pivotColumns))->map(function ($column) { return $this->table . '.' . $column . ' as pivot_' . $column; })->unique()->all(); }
php
protected function aliasedPivotColumns() { $defaults = [$this->foreignKey, $this->relatedKey]; return collect(array_merge($defaults, $this->pivotColumns))->map(function ($column) { return $this->table . '.' . $column . ' as pivot_' . $column; })->unique()->all(); }
[ "protected", "function", "aliasedPivotColumns", "(", ")", "{", "$", "defaults", "=", "[", "$", "this", "->", "foreignKey", ",", "$", "this", "->", "relatedKey", "]", ";", "return", "collect", "(", "array_merge", "(", "$", "defaults", ",", "$", "this", "->", "pivotColumns", ")", ")", "->", "map", "(", "function", "(", "$", "column", ")", "{", "return", "$", "this", "->", "table", ".", "'.'", ".", "$", "column", ".", "' as pivot_'", ".", "$", "column", ";", "}", ")", "->", "unique", "(", ")", "->", "all", "(", ")", ";", "}" ]
Get the pivot columns for the relation. "pivot_" is prefixed ot each column for easy removal later. @return array
[ "Get", "the", "pivot", "columns", "for", "the", "relation", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Eloquent/Relations/BelongsToMany.php#L550-L557
zhouyl/mellivora
Mellivora/Database/Eloquent/Relations/BelongsToMany.php
BelongsToMany.migratePivotAttributes
protected function migratePivotAttributes(Model $model) { $values = []; foreach ($model->getAttributes() as $key => $value) { // To get the pivots attributes we will just take any of the attributes which // begin with "pivot_" and add those to this arrays, as well as unsetting // them from the parent's models since they exist in a different table. if (strpos($key, 'pivot_') === 0) { $values[substr($key, 6)] = $value; $model->{$key} = null; } } return $values; }
php
protected function migratePivotAttributes(Model $model) { $values = []; foreach ($model->getAttributes() as $key => $value) { // To get the pivots attributes we will just take any of the attributes which // begin with "pivot_" and add those to this arrays, as well as unsetting // them from the parent's models since they exist in a different table. if (strpos($key, 'pivot_') === 0) { $values[substr($key, 6)] = $value; $model->{$key} = null; } } return $values; }
[ "protected", "function", "migratePivotAttributes", "(", "Model", "$", "model", ")", "{", "$", "values", "=", "[", "]", ";", "foreach", "(", "$", "model", "->", "getAttributes", "(", ")", "as", "$", "key", "=>", "$", "value", ")", "{", "// To get the pivots attributes we will just take any of the attributes which", "// begin with \"pivot_\" and add those to this arrays, as well as unsetting", "// them from the parent's models since they exist in a different table.", "if", "(", "strpos", "(", "$", "key", ",", "'pivot_'", ")", "===", "0", ")", "{", "$", "values", "[", "substr", "(", "$", "key", ",", "6", ")", "]", "=", "$", "value", ";", "$", "model", "->", "{", "$", "key", "}", "=", "null", ";", "}", "}", "return", "$", "values", ";", "}" ]
Get the pivot attributes from a model. @param \Mellivora\Database\Eloquent\Model $model @return array
[ "Get", "the", "pivot", "attributes", "from", "a", "model", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Eloquent/Relations/BelongsToMany.php#L642-L658
zhouyl/mellivora
Mellivora/Database/Eloquent/Relations/BelongsToMany.php
BelongsToMany.getRelationExistenceQuery
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { if ($parentQuery->getQuery()->from === $query->getQuery()->from) { return $this->getRelationExistenceQueryForSelfJoin($query, $parentQuery, $columns); } $this->performJoin($query); return parent::getRelationExistenceQuery($query, $parentQuery, $columns); }
php
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { if ($parentQuery->getQuery()->from === $query->getQuery()->from) { return $this->getRelationExistenceQueryForSelfJoin($query, $parentQuery, $columns); } $this->performJoin($query); return parent::getRelationExistenceQuery($query, $parentQuery, $columns); }
[ "public", "function", "getRelationExistenceQuery", "(", "Builder", "$", "query", ",", "Builder", "$", "parentQuery", ",", "$", "columns", "=", "[", "'*'", "]", ")", "{", "if", "(", "$", "parentQuery", "->", "getQuery", "(", ")", "->", "from", "===", "$", "query", "->", "getQuery", "(", ")", "->", "from", ")", "{", "return", "$", "this", "->", "getRelationExistenceQueryForSelfJoin", "(", "$", "query", ",", "$", "parentQuery", ",", "$", "columns", ")", ";", "}", "$", "this", "->", "performJoin", "(", "$", "query", ")", ";", "return", "parent", "::", "getRelationExistenceQuery", "(", "$", "query", ",", "$", "parentQuery", ",", "$", "columns", ")", ";", "}" ]
Add the constraints for a relationship query. @param \Mellivora\Database\Eloquent\Builder $query @param \Mellivora\Database\Eloquent\Builder $parentQuery @param array|mixed $columns @return \Mellivora\Database\Eloquent\Builder
[ "Add", "the", "constraints", "for", "a", "relationship", "query", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Eloquent/Relations/BelongsToMany.php#L823-L832
yuncms/yii2-authentication
frontend/models/Authentication.php
Authentication.beforeValidate
public function beforeValidate() { $this->id_file = UploadedFile::getInstance($this, 'id_file'); $this->id_file1 = UploadedFile::getInstance($this, 'id_file1'); $this->id_file2 = UploadedFile::getInstance($this, 'id_file2'); return parent::beforeValidate(); }
php
public function beforeValidate() { $this->id_file = UploadedFile::getInstance($this, 'id_file'); $this->id_file1 = UploadedFile::getInstance($this, 'id_file1'); $this->id_file2 = UploadedFile::getInstance($this, 'id_file2'); return parent::beforeValidate(); }
[ "public", "function", "beforeValidate", "(", ")", "{", "$", "this", "->", "id_file", "=", "UploadedFile", "::", "getInstance", "(", "$", "this", ",", "'id_file'", ")", ";", "$", "this", "->", "id_file1", "=", "UploadedFile", "::", "getInstance", "(", "$", "this", ",", "'id_file1'", ")", ";", "$", "this", "->", "id_file2", "=", "UploadedFile", "::", "getInstance", "(", "$", "this", ",", "'id_file2'", ")", ";", "return", "parent", "::", "beforeValidate", "(", ")", ";", "}" ]
加载上传文件 @return bool
[ "加载上传文件" ]
train
https://github.com/yuncms/yii2-authentication/blob/02b70f7d2587480edb6dcc18ce256db662f1ed0d/frontend/models/Authentication.php#L110-L116
kbond/ControllerUtil
src/EventListener/TemplatingViewListener.php
TemplatingViewListener.getContent
protected function getContent(View $view, $format) { $template = $view->getTemplate(); if (is_array($template)) { foreach ($template as $t) { if ($this->templating->exists($t)) { $template = $t; break; } } } return $this->templating->render($template, $view->getDataAsArray()); }
php
protected function getContent(View $view, $format) { $template = $view->getTemplate(); if (is_array($template)) { foreach ($template as $t) { if ($this->templating->exists($t)) { $template = $t; break; } } } return $this->templating->render($template, $view->getDataAsArray()); }
[ "protected", "function", "getContent", "(", "View", "$", "view", ",", "$", "format", ")", "{", "$", "template", "=", "$", "view", "->", "getTemplate", "(", ")", ";", "if", "(", "is_array", "(", "$", "template", ")", ")", "{", "foreach", "(", "$", "template", "as", "$", "t", ")", "{", "if", "(", "$", "this", "->", "templating", "->", "exists", "(", "$", "t", ")", ")", "{", "$", "template", "=", "$", "t", ";", "break", ";", "}", "}", "}", "return", "$", "this", "->", "templating", "->", "render", "(", "$", "template", ",", "$", "view", "->", "getDataAsArray", "(", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/kbond/ControllerUtil/blob/67375d43c73d6a3f16356f3d683f62b176766e91/src/EventListener/TemplatingViewListener.php#L23-L37
simbiosis-group/yii2-helper
actions/UpdateAction.php
UpdateAction.run
public function run() { $model = $this->model; if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && isset($_POST['ajax'])) { Yii::$app->response->format = Response::FORMAT_JSON; return \yii\widgets\ActiveForm::validate($model); } if ($model->load(Yii::$app->request->post())) { if ($model->save()) { if ($this->isSaveAndNew) { Yii::$app->response->format = Response::FORMAT_JSON; return [ 'message' => 'saveAndNew', 'saveAndNewUrl' => $this->saveAndNewUrl, ]; } Yii::$app->getSession()->setFlash('success', $this->successMsg); Yii::$app->response->format = Response::FORMAT_JSON; return [ 'message' => 'success', 'success' => true, ]; } Yii::$app->getSession()->setFlash('error', $this->errorMsg); Yii::$app->response->format = Response::FORMAT_JSON; return [ 'message' => 'error', 'success' => false, 'error' => Json::encode($model->getErrors()), ]; } return $this->controller->renderAjax($this->view, array_merge([ 'model' => $model, ], $this->params)); }
php
public function run() { $model = $this->model; if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && isset($_POST['ajax'])) { Yii::$app->response->format = Response::FORMAT_JSON; return \yii\widgets\ActiveForm::validate($model); } if ($model->load(Yii::$app->request->post())) { if ($model->save()) { if ($this->isSaveAndNew) { Yii::$app->response->format = Response::FORMAT_JSON; return [ 'message' => 'saveAndNew', 'saveAndNewUrl' => $this->saveAndNewUrl, ]; } Yii::$app->getSession()->setFlash('success', $this->successMsg); Yii::$app->response->format = Response::FORMAT_JSON; return [ 'message' => 'success', 'success' => true, ]; } Yii::$app->getSession()->setFlash('error', $this->errorMsg); Yii::$app->response->format = Response::FORMAT_JSON; return [ 'message' => 'error', 'success' => false, 'error' => Json::encode($model->getErrors()), ]; } return $this->controller->renderAjax($this->view, array_merge([ 'model' => $model, ], $this->params)); }
[ "public", "function", "run", "(", ")", "{", "$", "model", "=", "$", "this", "->", "model", ";", "if", "(", "Yii", "::", "$", "app", "->", "request", "->", "isAjax", "&&", "$", "model", "->", "load", "(", "Yii", "::", "$", "app", "->", "request", "->", "post", "(", ")", ")", "&&", "isset", "(", "$", "_POST", "[", "'ajax'", "]", ")", ")", "{", "Yii", "::", "$", "app", "->", "response", "->", "format", "=", "Response", "::", "FORMAT_JSON", ";", "return", "\\", "yii", "\\", "widgets", "\\", "ActiveForm", "::", "validate", "(", "$", "model", ")", ";", "}", "if", "(", "$", "model", "->", "load", "(", "Yii", "::", "$", "app", "->", "request", "->", "post", "(", ")", ")", ")", "{", "if", "(", "$", "model", "->", "save", "(", ")", ")", "{", "if", "(", "$", "this", "->", "isSaveAndNew", ")", "{", "Yii", "::", "$", "app", "->", "response", "->", "format", "=", "Response", "::", "FORMAT_JSON", ";", "return", "[", "'message'", "=>", "'saveAndNew'", ",", "'saveAndNewUrl'", "=>", "$", "this", "->", "saveAndNewUrl", ",", "]", ";", "}", "Yii", "::", "$", "app", "->", "getSession", "(", ")", "->", "setFlash", "(", "'success'", ",", "$", "this", "->", "successMsg", ")", ";", "Yii", "::", "$", "app", "->", "response", "->", "format", "=", "Response", "::", "FORMAT_JSON", ";", "return", "[", "'message'", "=>", "'success'", ",", "'success'", "=>", "true", ",", "]", ";", "}", "Yii", "::", "$", "app", "->", "getSession", "(", ")", "->", "setFlash", "(", "'error'", ",", "$", "this", "->", "errorMsg", ")", ";", "Yii", "::", "$", "app", "->", "response", "->", "format", "=", "Response", "::", "FORMAT_JSON", ";", "return", "[", "'message'", "=>", "'error'", ",", "'success'", "=>", "false", ",", "'error'", "=>", "Json", "::", "encode", "(", "$", "model", "->", "getErrors", "(", ")", ")", ",", "]", ";", "}", "return", "$", "this", "->", "controller", "->", "renderAjax", "(", "$", "this", "->", "view", ",", "array_merge", "(", "[", "'model'", "=>", "$", "model", ",", "]", ",", "$", "this", "->", "params", ")", ")", ";", "}" ]
Runs the action @return string result content
[ "Runs", "the", "action" ]
train
https://github.com/simbiosis-group/yii2-helper/blob/c85c4204dd06b16e54210e75fe6deb51869d1dd9/actions/UpdateAction.php#L72-L113
inhere/php-librarys
src/Components/ErrorHandler.php
ErrorHandler.register
public function register(array $errorLevelMap = [], $exceptionLevel = null, $fatalLevel = null) { //Forces the autoloader to run for LogLevel. Fixes an autoload issue at compile-time on PHP5.3. See https://github.com/Seldaek/monolog/pull/929 class_exists(LogLevel::class); if ($errorLevelMap !== false) { $this->registerErrorHandler($errorLevelMap); } if ($exceptionLevel !== false) { $this->registerExceptionHandler($exceptionLevel); } if ($fatalLevel !== false) { $this->registerFatalHandler($fatalLevel); } return $this; }
php
public function register(array $errorLevelMap = [], $exceptionLevel = null, $fatalLevel = null) { //Forces the autoloader to run for LogLevel. Fixes an autoload issue at compile-time on PHP5.3. See https://github.com/Seldaek/monolog/pull/929 class_exists(LogLevel::class); if ($errorLevelMap !== false) { $this->registerErrorHandler($errorLevelMap); } if ($exceptionLevel !== false) { $this->registerExceptionHandler($exceptionLevel); } if ($fatalLevel !== false) { $this->registerFatalHandler($fatalLevel); } return $this; }
[ "public", "function", "register", "(", "array", "$", "errorLevelMap", "=", "[", "]", ",", "$", "exceptionLevel", "=", "null", ",", "$", "fatalLevel", "=", "null", ")", "{", "//Forces the autoloader to run for LogLevel. Fixes an autoload issue at compile-time on PHP5.3. See https://github.com/Seldaek/monolog/pull/929", "class_exists", "(", "LogLevel", "::", "class", ")", ";", "if", "(", "$", "errorLevelMap", "!==", "false", ")", "{", "$", "this", "->", "registerErrorHandler", "(", "$", "errorLevelMap", ")", ";", "}", "if", "(", "$", "exceptionLevel", "!==", "false", ")", "{", "$", "this", "->", "registerExceptionHandler", "(", "$", "exceptionLevel", ")", ";", "}", "if", "(", "$", "fatalLevel", "!==", "false", ")", "{", "$", "this", "->", "registerFatalHandler", "(", "$", "fatalLevel", ")", ";", "}", "return", "$", "this", ";", "}" ]
Registers a new ErrorHandler for a given Logger By default it will handle errors, exceptions and fatal errors @param array|false $errorLevelMap an array of E_* constant to LogLevel::* constant mapping, or false to disable error handling @param int|false $exceptionLevel a LogLevel::* constant, or false to disable exception handling @param int|false $fatalLevel a LogLevel::* constant, or false to disable fatal error handling @return ErrorHandler
[ "Registers", "a", "new", "ErrorHandler", "for", "a", "given", "Logger" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/ErrorHandler.php#L70-L86
inhere/php-librarys
src/Components/ErrorHandler.php
ErrorHandler.handleFatalError
public function handleFatalError() { $this->reservedMemory = null; $lastError = error_get_last(); if ($lastError && \in_array($lastError['type'], self::$fatalErrors, true)) { $this->logger->log( $this->fatalLevel ?? LogLevel::ALERT, 'Fatal Error (' . self::codeToString($lastError['type']) . '): ' . $lastError['message'], [ 'code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], 'line' => $lastError['line'] ] ); if (method_exists($this->logger, 'flush')) { $this->logger->flush(); } if ($this->logger instanceof Logger) { foreach ($this->logger->getHandlers() as $handler) { if ($handler instanceof AbstractHandler) { $handler->close(); } } } } }
php
public function handleFatalError() { $this->reservedMemory = null; $lastError = error_get_last(); if ($lastError && \in_array($lastError['type'], self::$fatalErrors, true)) { $this->logger->log( $this->fatalLevel ?? LogLevel::ALERT, 'Fatal Error (' . self::codeToString($lastError['type']) . '): ' . $lastError['message'], [ 'code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], 'line' => $lastError['line'] ] ); if (method_exists($this->logger, 'flush')) { $this->logger->flush(); } if ($this->logger instanceof Logger) { foreach ($this->logger->getHandlers() as $handler) { if ($handler instanceof AbstractHandler) { $handler->close(); } } } } }
[ "public", "function", "handleFatalError", "(", ")", "{", "$", "this", "->", "reservedMemory", "=", "null", ";", "$", "lastError", "=", "error_get_last", "(", ")", ";", "if", "(", "$", "lastError", "&&", "\\", "in_array", "(", "$", "lastError", "[", "'type'", "]", ",", "self", "::", "$", "fatalErrors", ",", "true", ")", ")", "{", "$", "this", "->", "logger", "->", "log", "(", "$", "this", "->", "fatalLevel", "??", "LogLevel", "::", "ALERT", ",", "'Fatal Error ('", ".", "self", "::", "codeToString", "(", "$", "lastError", "[", "'type'", "]", ")", ".", "'): '", ".", "$", "lastError", "[", "'message'", "]", ",", "[", "'code'", "=>", "$", "lastError", "[", "'type'", "]", ",", "'message'", "=>", "$", "lastError", "[", "'message'", "]", ",", "'file'", "=>", "$", "lastError", "[", "'file'", "]", ",", "'line'", "=>", "$", "lastError", "[", "'line'", "]", "]", ")", ";", "if", "(", "method_exists", "(", "$", "this", "->", "logger", ",", "'flush'", ")", ")", "{", "$", "this", "->", "logger", "->", "flush", "(", ")", ";", "}", "if", "(", "$", "this", "->", "logger", "instanceof", "Logger", ")", "{", "foreach", "(", "$", "this", "->", "logger", "->", "getHandlers", "(", ")", "as", "$", "handler", ")", "{", "if", "(", "$", "handler", "instanceof", "AbstractHandler", ")", "{", "$", "handler", "->", "close", "(", ")", ";", "}", "}", "}", "}", "}" ]
handleFatalError @private
[ "handleFatalError" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Components/ErrorHandler.php#L221-L251
nabab/bbn
src/bbn/mvc/environment.php
environment.set_mode
public function set_mode($mode){ if ( router::is_mode($mode) ){ $this->mode = $mode; } return $this->mode; }
php
public function set_mode($mode){ if ( router::is_mode($mode) ){ $this->mode = $mode; } return $this->mode; }
[ "public", "function", "set_mode", "(", "$", "mode", ")", "{", "if", "(", "router", "::", "is_mode", "(", "$", "mode", ")", ")", "{", "$", "this", "->", "mode", "=", "$", "mode", ";", "}", "return", "$", "this", "->", "mode", ";", "}" ]
Change the output mode (content-type) @param $mode @return string $this->mode
[ "Change", "the", "output", "mode", "(", "content", "-", "type", ")" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/mvc/environment.php#L87-L92
nabab/bbn
src/bbn/mvc/environment.php
environment.is_cli
public function is_cli(){ if ( !isset($this->cli) ){ $this->cli = (php_sapi_name() === 'cli'); if ( $this->cli ){ $opt = getopt('', ['cli']); if ( isset($opt['cli']) ){ $this->cli = 'direct'; } } } return $this->cli; }
php
public function is_cli(){ if ( !isset($this->cli) ){ $this->cli = (php_sapi_name() === 'cli'); if ( $this->cli ){ $opt = getopt('', ['cli']); if ( isset($opt['cli']) ){ $this->cli = 'direct'; } } } return $this->cli; }
[ "public", "function", "is_cli", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "cli", ")", ")", "{", "$", "this", "->", "cli", "=", "(", "php_sapi_name", "(", ")", "===", "'cli'", ")", ";", "if", "(", "$", "this", "->", "cli", ")", "{", "$", "opt", "=", "getopt", "(", "''", ",", "[", "'cli'", "]", ")", ";", "if", "(", "isset", "(", "$", "opt", "[", "'cli'", "]", ")", ")", "{", "$", "this", "->", "cli", "=", "'direct'", ";", "}", "}", "}", "return", "$", "this", "->", "cli", ";", "}" ]
Returns true if called from CLI/Cron, false otherwise @return boolean
[ "Returns", "true", "if", "called", "from", "CLI", "/", "Cron", "false", "otherwise" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/mvc/environment.php#L179-L190
stk2k/net-driver
src/Http/HttpProxyGetRequest.php
HttpProxyGetRequest.getProxyServer
public function getProxyServer() { $proxy_options = $this->getOption(EnumRequestOption::PROXY_OPTIONS, []); return isset($proxy_options[EnumProxyOption::PROXY_SERVER]) ? $proxy_options[EnumProxyOption::PROXY_SERVER] : ''; }
php
public function getProxyServer() { $proxy_options = $this->getOption(EnumRequestOption::PROXY_OPTIONS, []); return isset($proxy_options[EnumProxyOption::PROXY_SERVER]) ? $proxy_options[EnumProxyOption::PROXY_SERVER] : ''; }
[ "public", "function", "getProxyServer", "(", ")", "{", "$", "proxy_options", "=", "$", "this", "->", "getOption", "(", "EnumRequestOption", "::", "PROXY_OPTIONS", ",", "[", "]", ")", ";", "return", "isset", "(", "$", "proxy_options", "[", "EnumProxyOption", "::", "PROXY_SERVER", "]", ")", "?", "$", "proxy_options", "[", "EnumProxyOption", "::", "PROXY_SERVER", "]", ":", "''", ";", "}" ]
Returns proxy server @return string
[ "Returns", "proxy", "server" ]
train
https://github.com/stk2k/net-driver/blob/75e0bc1a95ba430dd9ed9e69f6a0a5dd8f2e7b1c/src/Http/HttpProxyGetRequest.php#L28-L32
stk2k/net-driver
src/Http/HttpProxyGetRequest.php
HttpProxyGetRequest.getProxyPort
public function getProxyPort() { $proxy_options = $this->getOption(EnumRequestOption::PROXY_OPTIONS, []); return isset($proxy_options[EnumProxyOption::PROXY_PORT]) ? $proxy_options[EnumProxyOption::PROXY_PORT] : ''; }
php
public function getProxyPort() { $proxy_options = $this->getOption(EnumRequestOption::PROXY_OPTIONS, []); return isset($proxy_options[EnumProxyOption::PROXY_PORT]) ? $proxy_options[EnumProxyOption::PROXY_PORT] : ''; }
[ "public", "function", "getProxyPort", "(", ")", "{", "$", "proxy_options", "=", "$", "this", "->", "getOption", "(", "EnumRequestOption", "::", "PROXY_OPTIONS", ",", "[", "]", ")", ";", "return", "isset", "(", "$", "proxy_options", "[", "EnumProxyOption", "::", "PROXY_PORT", "]", ")", "?", "$", "proxy_options", "[", "EnumProxyOption", "::", "PROXY_PORT", "]", ":", "''", ";", "}" ]
Returns proxy port @return mixed
[ "Returns", "proxy", "port" ]
train
https://github.com/stk2k/net-driver/blob/75e0bc1a95ba430dd9ed9e69f6a0a5dd8f2e7b1c/src/Http/HttpProxyGetRequest.php#L39-L43
stk2k/net-driver
src/Http/HttpProxyGetRequest.php
HttpProxyGetRequest.getProxyType
public function getProxyType() { $proxy_options = $this->getOption(EnumRequestOption::PROXY_OPTIONS, []); return isset($proxy_options[EnumProxyOption::PROXY_TYPE]) ? $proxy_options[EnumProxyOption::PROXY_TYPE] : 'http'; }
php
public function getProxyType() { $proxy_options = $this->getOption(EnumRequestOption::PROXY_OPTIONS, []); return isset($proxy_options[EnumProxyOption::PROXY_TYPE]) ? $proxy_options[EnumProxyOption::PROXY_TYPE] : 'http'; }
[ "public", "function", "getProxyType", "(", ")", "{", "$", "proxy_options", "=", "$", "this", "->", "getOption", "(", "EnumRequestOption", "::", "PROXY_OPTIONS", ",", "[", "]", ")", ";", "return", "isset", "(", "$", "proxy_options", "[", "EnumProxyOption", "::", "PROXY_TYPE", "]", ")", "?", "$", "proxy_options", "[", "EnumProxyOption", "::", "PROXY_TYPE", "]", ":", "'http'", ";", "}" ]
Returns proxy type available values: 'http' for HTTP proxy 'https' for HTTPS proxy @return string
[ "Returns", "proxy", "type" ]
train
https://github.com/stk2k/net-driver/blob/75e0bc1a95ba430dd9ed9e69f6a0a5dd8f2e7b1c/src/Http/HttpProxyGetRequest.php#L55-L59
stk2k/net-driver
src/Http/HttpProxyGetRequest.php
HttpProxyGetRequest.getProxyAuth
public function getProxyAuth() { $proxy_options = $this->getOption(EnumRequestOption::PROXY_OPTIONS, []); return isset($proxy_options[EnumProxyOption::PROXY_AUTH]) ? $proxy_options[EnumProxyOption::PROXY_AUTH] : null; }
php
public function getProxyAuth() { $proxy_options = $this->getOption(EnumRequestOption::PROXY_OPTIONS, []); return isset($proxy_options[EnumProxyOption::PROXY_AUTH]) ? $proxy_options[EnumProxyOption::PROXY_AUTH] : null; }
[ "public", "function", "getProxyAuth", "(", ")", "{", "$", "proxy_options", "=", "$", "this", "->", "getOption", "(", "EnumRequestOption", "::", "PROXY_OPTIONS", ",", "[", "]", ")", ";", "return", "isset", "(", "$", "proxy_options", "[", "EnumProxyOption", "::", "PROXY_AUTH", "]", ")", "?", "$", "proxy_options", "[", "EnumProxyOption", "::", "PROXY_AUTH", "]", ":", "null", ";", "}" ]
Returns proxy auth available values: 'basic' for BASIC auth null or empty('') for no auth @return string
[ "Returns", "proxy", "auth" ]
train
https://github.com/stk2k/net-driver/blob/75e0bc1a95ba430dd9ed9e69f6a0a5dd8f2e7b1c/src/Http/HttpProxyGetRequest.php#L71-L75
stk2k/net-driver
src/Http/HttpProxyGetRequest.php
HttpProxyGetRequest.getProxyUserPassword
public function getProxyUserPassword() { $proxy_options = $this->getOption(EnumRequestOption::PROXY_OPTIONS, []); return isset($proxy_options[EnumProxyOption::USER_PASSWD]) ? $proxy_options[EnumProxyOption::USER_PASSWD] : ''; }
php
public function getProxyUserPassword() { $proxy_options = $this->getOption(EnumRequestOption::PROXY_OPTIONS, []); return isset($proxy_options[EnumProxyOption::USER_PASSWD]) ? $proxy_options[EnumProxyOption::USER_PASSWD] : ''; }
[ "public", "function", "getProxyUserPassword", "(", ")", "{", "$", "proxy_options", "=", "$", "this", "->", "getOption", "(", "EnumRequestOption", "::", "PROXY_OPTIONS", ",", "[", "]", ")", ";", "return", "isset", "(", "$", "proxy_options", "[", "EnumProxyOption", "::", "USER_PASSWD", "]", ")", "?", "$", "proxy_options", "[", "EnumProxyOption", "::", "USER_PASSWD", "]", ":", "''", ";", "}" ]
Returns proxy user/password(FORMAT: "user:password") @return mixed
[ "Returns", "proxy", "user", "/", "password", "(", "FORMAT", ":", "user", ":", "password", ")" ]
train
https://github.com/stk2k/net-driver/blob/75e0bc1a95ba430dd9ed9e69f6a0a5dd8f2e7b1c/src/Http/HttpProxyGetRequest.php#L82-L86
hametuha/wpametu
src/WPametu/UI/Field/Textarea.php
TextArea.build_input
protected function build_input($data, array $fields = []){ $fields = implode(' ', $fields); return sprintf('<textarea id="%1$s" name="%1$s" %2$s>%3$s</textarea>%4$s', $this->name, $fields, esc_textarea($data), $this->length_helper($data)); }
php
protected function build_input($data, array $fields = []){ $fields = implode(' ', $fields); return sprintf('<textarea id="%1$s" name="%1$s" %2$s>%3$s</textarea>%4$s', $this->name, $fields, esc_textarea($data), $this->length_helper($data)); }
[ "protected", "function", "build_input", "(", "$", "data", ",", "array", "$", "fields", "=", "[", "]", ")", "{", "$", "fields", "=", "implode", "(", "' '", ",", "$", "fields", ")", ";", "return", "sprintf", "(", "'<textarea id=\"%1$s\" name=\"%1$s\" %2$s>%3$s</textarea>%4$s'", ",", "$", "this", "->", "name", ",", "$", "fields", ",", "esc_textarea", "(", "$", "data", ")", ",", "$", "this", "->", "length_helper", "(", "$", "data", ")", ")", ";", "}" ]
Make input field @param mixed $data @param array $fields @return string
[ "Make", "input", "field" ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/UI/Field/Textarea.php#L36-L40
php-lug/lug
src/Bundle/ResourceBundle/Form/FormFactory.php
FormFactory.create
public function create($type = null, $data = null, array $options = []) { if ($type instanceof ResourceInterface) { $type = $this->parameterResolver->resolveForm($type); } $validationGroups = $this->parameterResolver->resolveValidationGroups(); $translationDomain = $this->parameterResolver->resolveTranslationDomain(); if (!empty($validationGroups)) { $options['validation_groups'] = $validationGroups; } if (!empty($translationDomain)) { $options['translation_domain'] = $translationDomain; } if ($this->parameterResolver->resolveApi()) { $options['csrf_protection'] = false; } return $this->factory->create($type, $data, $options); }
php
public function create($type = null, $data = null, array $options = []) { if ($type instanceof ResourceInterface) { $type = $this->parameterResolver->resolveForm($type); } $validationGroups = $this->parameterResolver->resolveValidationGroups(); $translationDomain = $this->parameterResolver->resolveTranslationDomain(); if (!empty($validationGroups)) { $options['validation_groups'] = $validationGroups; } if (!empty($translationDomain)) { $options['translation_domain'] = $translationDomain; } if ($this->parameterResolver->resolveApi()) { $options['csrf_protection'] = false; } return $this->factory->create($type, $data, $options); }
[ "public", "function", "create", "(", "$", "type", "=", "null", ",", "$", "data", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "$", "type", "instanceof", "ResourceInterface", ")", "{", "$", "type", "=", "$", "this", "->", "parameterResolver", "->", "resolveForm", "(", "$", "type", ")", ";", "}", "$", "validationGroups", "=", "$", "this", "->", "parameterResolver", "->", "resolveValidationGroups", "(", ")", ";", "$", "translationDomain", "=", "$", "this", "->", "parameterResolver", "->", "resolveTranslationDomain", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "validationGroups", ")", ")", "{", "$", "options", "[", "'validation_groups'", "]", "=", "$", "validationGroups", ";", "}", "if", "(", "!", "empty", "(", "$", "translationDomain", ")", ")", "{", "$", "options", "[", "'translation_domain'", "]", "=", "$", "translationDomain", ";", "}", "if", "(", "$", "this", "->", "parameterResolver", "->", "resolveApi", "(", ")", ")", "{", "$", "options", "[", "'csrf_protection'", "]", "=", "false", ";", "}", "return", "$", "this", "->", "factory", "->", "create", "(", "$", "type", ",", "$", "data", ",", "$", "options", ")", ";", "}" ]
@param string|FormTypeInterface|ResourceInterface $type @param mixed $data @param mixed[] $options @return FormInterface
[ "@param", "string|FormTypeInterface|ResourceInterface", "$type", "@param", "mixed", "$data", "@param", "mixed", "[]", "$options" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/ResourceBundle/Form/FormFactory.php#L52-L74
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.__item
public function __item($item = null) { $result['name'] = $this->getName(); $result['content'] = '0'; $result['active'] = is_null($item) ? true : $item['active']; $result['settings'] = Eresus_CMS::getLegacyKernel()->db-> escape(is_null($item) ? encodeOptions($this->settings) : $item['settings']); $result['title'] = $this->title; $result['version'] = $this->version; $result['description'] = $this->description; return $result; }
php
public function __item($item = null) { $result['name'] = $this->getName(); $result['content'] = '0'; $result['active'] = is_null($item) ? true : $item['active']; $result['settings'] = Eresus_CMS::getLegacyKernel()->db-> escape(is_null($item) ? encodeOptions($this->settings) : $item['settings']); $result['title'] = $this->title; $result['version'] = $this->version; $result['description'] = $this->description; return $result; }
[ "public", "function", "__item", "(", "$", "item", "=", "null", ")", "{", "$", "result", "[", "'name'", "]", "=", "$", "this", "->", "getName", "(", ")", ";", "$", "result", "[", "'content'", "]", "=", "'0'", ";", "$", "result", "[", "'active'", "]", "=", "is_null", "(", "$", "item", ")", "?", "true", ":", "$", "item", "[", "'active'", "]", ";", "$", "result", "[", "'settings'", "]", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "escape", "(", "is_null", "(", "$", "item", ")", "?", "encodeOptions", "(", "$", "this", "->", "settings", ")", ":", "$", "item", "[", "'settings'", "]", ")", ";", "$", "result", "[", "'title'", "]", "=", "$", "this", "->", "title", ";", "$", "result", "[", "'version'", "]", "=", "$", "this", "->", "version", ";", "$", "result", "[", "'description'", "]", "=", "$", "this", "->", "description", ";", "return", "$", "result", ";", "}" ]
Возвращает информацию о плагине @param array $item Предыдущая версия информации (по умолчанию null) @return array Массив информации, пригодный для записи в БД
[ "Возвращает", "информацию", "о", "плагине" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L196-L207
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.getName
public function getName() { if (null === $this->name) { $this->name = strtolower(get_class($this)); } return $this->name; }
php
public function getName() { if (null === $this->name) { $this->name = strtolower(get_class($this)); } return $this->name; }
[ "public", "function", "getName", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "name", ")", "{", "$", "this", "->", "name", "=", "strtolower", "(", "get_class", "(", "$", "this", ")", ")", ";", "}", "return", "$", "this", "->", "name", ";", "}" ]
Возвращает имя плагина @return string @since 3.01
[ "Возвращает", "имя", "плагина" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L229-L236
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.updateSettings
public function updateSettings() { foreach ($this->settings as $key => &$value) { if (!is_null(arg($key))) { $value = arg($key); } } $this->onSettingsUpdate(); $this->saveSettings(); }
php
public function updateSettings() { foreach ($this->settings as $key => &$value) { if (!is_null(arg($key))) { $value = arg($key); } } $this->onSettingsUpdate(); $this->saveSettings(); }
[ "public", "function", "updateSettings", "(", ")", "{", "foreach", "(", "$", "this", "->", "settings", "as", "$", "key", "=>", "&", "$", "value", ")", "{", "if", "(", "!", "is_null", "(", "arg", "(", "$", "key", ")", ")", ")", "{", "$", "value", "=", "arg", "(", "$", "key", ")", ";", "}", "}", "$", "this", "->", "onSettingsUpdate", "(", ")", ";", "$", "this", "->", "saveSettings", "(", ")", ";", "}" ]
Сохраняет в БД изменения настроек плагина
[ "Сохраняет", "в", "БД", "изменения", "настроек", "плагина" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L340-L351
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.dbSelect
public function dbSelect($table = '', $condition = '', $order = '', $fields = '', $limit = 0, $offset = 0, $group = '', $distinct = false) { $result = Eresus_CMS::getLegacyKernel()->db->select($this->__table($table), $condition, $order, $fields, $limit, $offset, $group, $distinct); return $result; }
php
public function dbSelect($table = '', $condition = '', $order = '', $fields = '', $limit = 0, $offset = 0, $group = '', $distinct = false) { $result = Eresus_CMS::getLegacyKernel()->db->select($this->__table($table), $condition, $order, $fields, $limit, $offset, $group, $distinct); return $result; }
[ "public", "function", "dbSelect", "(", "$", "table", "=", "''", ",", "$", "condition", "=", "''", ",", "$", "order", "=", "''", ",", "$", "fields", "=", "''", ",", "$", "limit", "=", "0", ",", "$", "offset", "=", "0", ",", "$", "group", "=", "''", ",", "$", "distinct", "=", "false", ")", "{", "$", "result", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "select", "(", "$", "this", "->", "__table", "(", "$", "table", ")", ",", "$", "condition", ",", "$", "order", ",", "$", "fields", ",", "$", "limit", ",", "$", "offset", ",", "$", "group", ",", "$", "distinct", ")", ";", "return", "$", "result", ";", "}" ]
Производит выборку из таблицы БД @param string $table Имя таблицы (пустое значение - таблица по умолчанию) @param string $condition Условие выборки @param string $order Порядок выборки @param string $fields Список полей @param int $limit Вернуть не больше полей чем limit @param int $offset Смещение выборки @param bool $distinct Только уникальные результаты @return array|bool Выбранные элементы в виде массива или FALSE в случае ошибки
[ "Производит", "выборку", "из", "таблицы", "БД" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L366-L373
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.dbItem
public function dbItem($table, $id, $key = 'id') { $result = Eresus_CMS::getLegacyKernel()->db->selectItem($this->__table($table), "`$key` = '$id'"); return $result; }
php
public function dbItem($table, $id, $key = 'id') { $result = Eresus_CMS::getLegacyKernel()->db->selectItem($this->__table($table), "`$key` = '$id'"); return $result; }
[ "public", "function", "dbItem", "(", "$", "table", ",", "$", "id", ",", "$", "key", "=", "'id'", ")", "{", "$", "result", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "selectItem", "(", "$", "this", "->", "__table", "(", "$", "table", ")", ",", "\"`$key` = '$id'\"", ")", ";", "return", "$", "result", ";", "}" ]
Получение записи из БД @param string $table Имя таблицы @param mixed $id Идентификатор элемента @param string $key Имя ключевого поля @return array Элемент
[ "Получение", "записи", "из", "БД" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L385-L391
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.dbInsert
public function dbInsert($table, $item, $key = 'id') { Eresus_CMS::getLegacyKernel()->db->insert($this->__table($table), $item); $result = $this->dbItem($table, Eresus_CMS::getLegacyKernel()->db->getInsertedId(), $key); return $result; }
php
public function dbInsert($table, $item, $key = 'id') { Eresus_CMS::getLegacyKernel()->db->insert($this->__table($table), $item); $result = $this->dbItem($table, Eresus_CMS::getLegacyKernel()->db->getInsertedId(), $key); return $result; }
[ "public", "function", "dbInsert", "(", "$", "table", ",", "$", "item", ",", "$", "key", "=", "'id'", ")", "{", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "insert", "(", "$", "this", "->", "__table", "(", "$", "table", ")", ",", "$", "item", ")", ";", "$", "result", "=", "$", "this", "->", "dbItem", "(", "$", "table", ",", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "getInsertedId", "(", ")", ",", "$", "key", ")", ";", "return", "$", "result", ";", "}" ]
Вставка в таблицу БД @param string $table Имя таблицы @param array $item Вставляемый элемент @param string $key[optional] Имя ключевого поля. По умолчанию "id"
[ "Вставка", "в", "таблицу", "БД" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L401-L407
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.dbUpdate
public function dbUpdate($table, $data, $condition = '') { if (is_array($data)) { if (empty($condition)) $condition = 'id'; $result = Eresus_CMS::getLegacyKernel()->db-> updateItem($this->__table($table), $data, "`$condition` = '{$data[$condition]}'"); } elseif (is_string($data)) { $result = Eresus_CMS::getLegacyKernel()->db-> update($this->__table($table), $data, $condition); } else { $result = false; } return $result; }
php
public function dbUpdate($table, $data, $condition = '') { if (is_array($data)) { if (empty($condition)) $condition = 'id'; $result = Eresus_CMS::getLegacyKernel()->db-> updateItem($this->__table($table), $data, "`$condition` = '{$data[$condition]}'"); } elseif (is_string($data)) { $result = Eresus_CMS::getLegacyKernel()->db-> update($this->__table($table), $data, $condition); } else { $result = false; } return $result; }
[ "public", "function", "dbUpdate", "(", "$", "table", ",", "$", "data", ",", "$", "condition", "=", "''", ")", "{", "if", "(", "is_array", "(", "$", "data", ")", ")", "{", "if", "(", "empty", "(", "$", "condition", ")", ")", "$", "condition", "=", "'id'", ";", "$", "result", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "updateItem", "(", "$", "this", "->", "__table", "(", "$", "table", ")", ",", "$", "data", ",", "\"`$condition` = '{$data[$condition]}'\"", ")", ";", "}", "elseif", "(", "is_string", "(", "$", "data", ")", ")", "{", "$", "result", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "update", "(", "$", "this", "->", "__table", "(", "$", "table", ")", ",", "$", "data", ",", "$", "condition", ")", ";", "}", "else", "{", "$", "result", "=", "false", ";", "}", "return", "$", "result", ";", "}" ]
Изменение данных в БД @param string $table Имя таблицы @param mixed $data Изменяемый эелемент / Изменения @param string $condition Ключевое поле / Условие для замены @return bool Результат
[ "Изменение", "данных", "в", "БД" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L419-L438
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.dbDelete
public function dbDelete($table, $item, $key = 'id') { $result = Eresus_CMS::getLegacyKernel()->db-> delete($this->__table($table), "`$key` = '".(is_array($item)? $item[$key] : $item)."'"); return $result; }
php
public function dbDelete($table, $item, $key = 'id') { $result = Eresus_CMS::getLegacyKernel()->db-> delete($this->__table($table), "`$key` = '".(is_array($item)? $item[$key] : $item)."'"); return $result; }
[ "public", "function", "dbDelete", "(", "$", "table", ",", "$", "item", ",", "$", "key", "=", "'id'", ")", "{", "$", "result", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "delete", "(", "$", "this", "->", "__table", "(", "$", "table", ")", ",", "\"`$key` = '\"", ".", "(", "is_array", "(", "$", "item", ")", "?", "$", "item", "[", "$", "key", "]", ":", "$", "item", ")", ".", "\"'\"", ")", ";", "return", "$", "result", ";", "}" ]
Удаление элемента из БД @param string $table Имя таблицы @param mixed $item Удаляемый элемент / Идентификатор @param string $key Ключевое поле @return bool Результат
[ "Удаление", "элемента", "из", "БД" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L450-L456
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.dbCount
public function dbCount($table, $condition = '') { $result = Eresus_CMS::getLegacyKernel()->db->count($this->__table($table), $condition); return $result; }
php
public function dbCount($table, $condition = '') { $result = Eresus_CMS::getLegacyKernel()->db->count($this->__table($table), $condition); return $result; }
[ "public", "function", "dbCount", "(", "$", "table", ",", "$", "condition", "=", "''", ")", "{", "$", "result", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "count", "(", "$", "this", "->", "__table", "(", "$", "table", ")", ",", "$", "condition", ")", ";", "return", "$", "result", ";", "}" ]
Подсчёт количества записей в БД @param string $table Имя таблицы @param string $condition Условие для включения в подсчёт @return int Количество записей, удовлетворяющих условию
[ "Подсчёт", "количества", "записей", "в", "БД" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L467-L472
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.dbTable
public function dbTable($table, $param = '') { $result = Eresus_CMS::getLegacyKernel()->db->tableStatus($this->__table($table), $param); return $result; }
php
public function dbTable($table, $param = '') { $result = Eresus_CMS::getLegacyKernel()->db->tableStatus($this->__table($table), $param); return $result; }
[ "public", "function", "dbTable", "(", "$", "table", ",", "$", "param", "=", "''", ")", "{", "$", "result", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "tableStatus", "(", "$", "this", "->", "__table", "(", "$", "table", ")", ",", "$", "param", ")", ";", "return", "$", "result", ";", "}" ]
Получение информации о таблицах @param string $table Маска имени таблицы @param string $param Вернуть только указанный параметр @return mixed
[ "Получение", "информации", "о", "таблицах" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L483-L488
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.templates
public function templates() { if (null === $this->templates) { $this->templates = new Eresus_Plugin_Templates($this); } return $this->templates; }
php
public function templates() { if (null === $this->templates) { $this->templates = new Eresus_Plugin_Templates($this); } return $this->templates; }
[ "public", "function", "templates", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "templates", ")", "{", "$", "this", "->", "templates", "=", "new", "Eresus_Plugin_Templates", "(", "$", "this", ")", ";", "}", "return", "$", "this", "->", "templates", ";", "}" ]
Возвращает объект для работы с шаблонами плагина @return Eresus_Plugin_Templates|null @since 3.01
[ "Возвращает", "объект", "для", "работы", "с", "шаблонами", "плагина" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L496-L503
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.loadSettings
protected function loadSettings() { $result = Eresus_CMS::getLegacyKernel()->db ->selectItem('plugins', "`name`='" . $this->getName() . "'"); if ($result) { $this->settings = decodeOptions($result['settings'], $this->settings); } return (bool) $result; }
php
protected function loadSettings() { $result = Eresus_CMS::getLegacyKernel()->db ->selectItem('plugins', "`name`='" . $this->getName() . "'"); if ($result) { $this->settings = decodeOptions($result['settings'], $this->settings); } return (bool) $result; }
[ "protected", "function", "loadSettings", "(", ")", "{", "$", "result", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "selectItem", "(", "'plugins'", ",", "\"`name`='\"", ".", "$", "this", "->", "getName", "(", ")", ".", "\"'\"", ")", ";", "if", "(", "$", "result", ")", "{", "$", "this", "->", "settings", "=", "decodeOptions", "(", "$", "result", "[", "'settings'", "]", ",", "$", "this", "->", "settings", ")", ";", "}", "return", "(", "bool", ")", "$", "result", ";", "}" ]
Чтение настроек плагина из БД @return bool Результат выполнения
[ "Чтение", "настроек", "плагина", "из", "БД" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L510-L519
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.saveSettings
protected function saveSettings() { $result = Eresus_CMS::getLegacyKernel()->db ->selectItem('plugins', "`name`='{$this->getName()}'"); $result = $this->__item($result); $result['settings'] = Eresus_CMS::getLegacyKernel()->db ->escape(encodeOptions($this->settings)); $result = Eresus_CMS::getLegacyKernel()->db-> updateItem('plugins', $result, "`name`='".$this->getName()."'"); return $result; }
php
protected function saveSettings() { $result = Eresus_CMS::getLegacyKernel()->db ->selectItem('plugins', "`name`='{$this->getName()}'"); $result = $this->__item($result); $result['settings'] = Eresus_CMS::getLegacyKernel()->db ->escape(encodeOptions($this->settings)); $result = Eresus_CMS::getLegacyKernel()->db-> updateItem('plugins', $result, "`name`='".$this->getName()."'"); return $result; }
[ "protected", "function", "saveSettings", "(", ")", "{", "$", "result", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "selectItem", "(", "'plugins'", ",", "\"`name`='{$this->getName()}'\"", ")", ";", "$", "result", "=", "$", "this", "->", "__item", "(", "$", "result", ")", ";", "$", "result", "[", "'settings'", "]", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "escape", "(", "encodeOptions", "(", "$", "this", "->", "settings", ")", ")", ";", "$", "result", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "updateItem", "(", "'plugins'", ",", "$", "result", ",", "\"`name`='\"", ".", "$", "this", "->", "getName", "(", ")", ".", "\"'\"", ")", ";", "return", "$", "result", ";", "}" ]
Сохранение настроек плагина в БД @return bool Результат выполнения
[ "Сохранение", "настроек", "плагина", "в", "БД" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L526-L537
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.listenEvents
protected function listenEvents() { $registry = Eresus_Plugin_Registry::getInstance(); for ($i=0; $i < func_num_args(); $i++) { $event = func_get_arg($i); if (!array_key_exists($event, $registry->events)) { $registry->events[$event] = array(); } $registry->events[$event] []= $this->getName(); } }
php
protected function listenEvents() { $registry = Eresus_Plugin_Registry::getInstance(); for ($i=0; $i < func_num_args(); $i++) { $event = func_get_arg($i); if (!array_key_exists($event, $registry->events)) { $registry->events[$event] = array(); } $registry->events[$event] []= $this->getName(); } }
[ "protected", "function", "listenEvents", "(", ")", "{", "$", "registry", "=", "Eresus_Plugin_Registry", "::", "getInstance", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "func_num_args", "(", ")", ";", "$", "i", "++", ")", "{", "$", "event", "=", "func_get_arg", "(", "$", "i", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "event", ",", "$", "registry", "->", "events", ")", ")", "{", "$", "registry", "->", "events", "[", "$", "event", "]", "=", "array", "(", ")", ";", "}", "$", "registry", "->", "events", "[", "$", "event", "]", "[", "]", "=", "$", "this", "->", "getName", "(", ")", ";", "}", "}" ]
Регистрация обработчиков событий @param string ... имена событий @deprecated с 3.01 используйте {@link Eresus_Event_Dispatcher::addEventListener()}
[ "Регистрация", "обработчиков", "событий" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L554-L566
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.installTemplates
protected function installTemplates() { $path = $this->getCodeDir() . '/client/templates'; if (file_exists($path)) { $ts = Eresus_Template_Service::getInstance(); $it = new DirectoryIterator($path); foreach ($it as $fileInfo) { /** @var DirectoryIterator $fileInfo */ if (!$fileInfo->isDot()) { $ts->install($fileInfo->getPathname(), $this->getName()); } } } }
php
protected function installTemplates() { $path = $this->getCodeDir() . '/client/templates'; if (file_exists($path)) { $ts = Eresus_Template_Service::getInstance(); $it = new DirectoryIterator($path); foreach ($it as $fileInfo) { /** @var DirectoryIterator $fileInfo */ if (!$fileInfo->isDot()) { $ts->install($fileInfo->getPathname(), $this->getName()); } } } }
[ "protected", "function", "installTemplates", "(", ")", "{", "$", "path", "=", "$", "this", "->", "getCodeDir", "(", ")", ".", "'/client/templates'", ";", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "$", "ts", "=", "Eresus_Template_Service", "::", "getInstance", "(", ")", ";", "$", "it", "=", "new", "DirectoryIterator", "(", "$", "path", ")", ";", "foreach", "(", "$", "it", "as", "$", "fileInfo", ")", "{", "/** @var DirectoryIterator $fileInfo */", "if", "(", "!", "$", "fileInfo", "->", "isDot", "(", ")", ")", "{", "$", "ts", "->", "install", "(", "$", "fileInfo", "->", "getPathname", "(", ")", ",", "$", "this", "->", "getName", "(", ")", ")", ";", "}", "}", "}", "}" ]
Устанавливает шаблоны КИ в общую папку шаблонов
[ "Устанавливает", "шаблоны", "КИ", "в", "общую", "папку", "шаблонов" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L571-L587
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.uninstallTemplates
protected function uninstallTemplates() { $path = $this->getCodeDir() . '/client/templates'; if (file_exists($path)) { $ts = Eresus_Template_Service::getInstance(); $ts->remove($this->getName()); } }
php
protected function uninstallTemplates() { $path = $this->getCodeDir() . '/client/templates'; if (file_exists($path)) { $ts = Eresus_Template_Service::getInstance(); $ts->remove($this->getName()); } }
[ "protected", "function", "uninstallTemplates", "(", ")", "{", "$", "path", "=", "$", "this", "->", "getCodeDir", "(", ")", ".", "'/client/templates'", ";", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "$", "ts", "=", "Eresus_Template_Service", "::", "getInstance", "(", ")", ";", "$", "ts", "->", "remove", "(", "$", "this", "->", "getName", "(", ")", ")", ";", "}", "}" ]
Удаляет шаблоны КИ из общей папки шаблонов
[ "Удаляет", "шаблоны", "КИ", "из", "общей", "папки", "шаблонов" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L592-L600
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.cleanupDB
protected function cleanupDB() { $eresus = Eresus_CMS::getLegacyKernel(); $tables = $eresus->db ->query_array("SHOW TABLES LIKE '{$eresus->db->prefix}{$this->getName()}_%'"); $tables = array_merge($tables, $eresus->db-> query_array("SHOW TABLES LIKE '{$eresus->db->prefix}{$this->getName()}'")); for ($i = 0; $i < count($tables); $i++) { $this->dbDropTable(substr(current($tables[$i]), strlen($this->getName()) + 1)); } }
php
protected function cleanupDB() { $eresus = Eresus_CMS::getLegacyKernel(); $tables = $eresus->db ->query_array("SHOW TABLES LIKE '{$eresus->db->prefix}{$this->getName()}_%'"); $tables = array_merge($tables, $eresus->db-> query_array("SHOW TABLES LIKE '{$eresus->db->prefix}{$this->getName()}'")); for ($i = 0; $i < count($tables); $i++) { $this->dbDropTable(substr(current($tables[$i]), strlen($this->getName()) + 1)); } }
[ "protected", "function", "cleanupDB", "(", ")", "{", "$", "eresus", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", ";", "$", "tables", "=", "$", "eresus", "->", "db", "->", "query_array", "(", "\"SHOW TABLES LIKE '{$eresus->db->prefix}{$this->getName()}_%'\"", ")", ";", "$", "tables", "=", "array_merge", "(", "$", "tables", ",", "$", "eresus", "->", "db", "->", "query_array", "(", "\"SHOW TABLES LIKE '{$eresus->db->prefix}{$this->getName()}'\"", ")", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "tables", ")", ";", "$", "i", "++", ")", "{", "$", "this", "->", "dbDropTable", "(", "substr", "(", "current", "(", "$", "tables", "[", "$", "i", "]", ")", ",", "strlen", "(", "$", "this", "->", "getName", "(", ")", ")", "+", "1", ")", ")", ";", "}", "}" ]
Удаляет таблицы БД при удалении плагина @since 3.01
[ "Удаляет", "таблицы", "БД", "при", "удалении", "плагина" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L607-L618
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.mkdir
protected function mkdir($name = '') { $result = true; $umask = umask(0000); # Проверка и создание корневой директории данных if (!is_dir($this->dirData)) $result = mkdir($this->dirData); if ($result) { # Удаляем директории вида "." и "..", а также финальный и лидирующий слэши $name = preg_replace(array('!\.{1,2}/!', '!^/!', '!/$!'), '', $name); if ($name) { $name = explode('/', $name); $root = substr($this->dirData, 0, -1); for($i=0; $i<count($name); $i++) if ($name[$i]) { $root .= '/'.$name[$i]; if (!is_dir($root)) $result = mkdir($root); if (!$result) break; } } } umask($umask); return $result; }
php
protected function mkdir($name = '') { $result = true; $umask = umask(0000); # Проверка и создание корневой директории данных if (!is_dir($this->dirData)) $result = mkdir($this->dirData); if ($result) { # Удаляем директории вида "." и "..", а также финальный и лидирующий слэши $name = preg_replace(array('!\.{1,2}/!', '!^/!', '!/$!'), '', $name); if ($name) { $name = explode('/', $name); $root = substr($this->dirData, 0, -1); for($i=0; $i<count($name); $i++) if ($name[$i]) { $root .= '/'.$name[$i]; if (!is_dir($root)) $result = mkdir($root); if (!$result) break; } } } umask($umask); return $result; }
[ "protected", "function", "mkdir", "(", "$", "name", "=", "''", ")", "{", "$", "result", "=", "true", ";", "$", "umask", "=", "umask", "(", "0000", ")", ";", "# Проверка и создание корневой директории данных", "if", "(", "!", "is_dir", "(", "$", "this", "->", "dirData", ")", ")", "$", "result", "=", "mkdir", "(", "$", "this", "->", "dirData", ")", ";", "if", "(", "$", "result", ")", "{", "# Удаляем директории вида \".\" и \"..\", а также финальный и лидирующий слэши", "$", "name", "=", "preg_replace", "(", "array", "(", "'!\\.{1,2}/!'", ",", "'!^/!'", ",", "'!/$!'", ")", ",", "''", ",", "$", "name", ")", ";", "if", "(", "$", "name", ")", "{", "$", "name", "=", "explode", "(", "'/'", ",", "$", "name", ")", ";", "$", "root", "=", "substr", "(", "$", "this", "->", "dirData", ",", "0", ",", "-", "1", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "name", ")", ";", "$", "i", "++", ")", "if", "(", "$", "name", "[", "$", "i", "]", ")", "{", "$", "root", ".=", "'/'", ".", "$", "name", "[", "$", "i", "]", ";", "if", "(", "!", "is_dir", "(", "$", "root", ")", ")", "$", "result", "=", "mkdir", "(", "$", "root", ")", ";", "if", "(", "!", "$", "result", ")", "break", ";", "}", "}", "}", "umask", "(", "$", "umask", ")", ";", "return", "$", "result", ";", "}" ]
Создание новой директории @param string $name Имя директории @return bool Результат
[ "Создание", "новой", "директории" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L640-L663
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.rmdir
protected function rmdir($name = '') { $result = true; $name = preg_replace(array('!\.{1,2}/!', '!^/!', '!/$!'), '', $name); $name = $this->dirData.$name; if (is_dir($name)) { $files = glob($name.'/{.*,*}', GLOB_BRACE); for ($i = 0; $i < count($files); $i++) { if (substr($files[$i], -2) == '/.' || substr($files[$i], -3) == '/..') continue; if (is_dir($files[$i])) $result = $this->rmdir(substr($files[$i], strlen($this->dirData))); elseif (is_file($files[$i])) $result = filedelete($files[$i]); if (!$result) break; } if ($result) $result = rmdir($name); } return $result; }
php
protected function rmdir($name = '') { $result = true; $name = preg_replace(array('!\.{1,2}/!', '!^/!', '!/$!'), '', $name); $name = $this->dirData.$name; if (is_dir($name)) { $files = glob($name.'/{.*,*}', GLOB_BRACE); for ($i = 0; $i < count($files); $i++) { if (substr($files[$i], -2) == '/.' || substr($files[$i], -3) == '/..') continue; if (is_dir($files[$i])) $result = $this->rmdir(substr($files[$i], strlen($this->dirData))); elseif (is_file($files[$i])) $result = filedelete($files[$i]); if (!$result) break; } if ($result) $result = rmdir($name); } return $result; }
[ "protected", "function", "rmdir", "(", "$", "name", "=", "''", ")", "{", "$", "result", "=", "true", ";", "$", "name", "=", "preg_replace", "(", "array", "(", "'!\\.{1,2}/!'", ",", "'!^/!'", ",", "'!/$!'", ")", ",", "''", ",", "$", "name", ")", ";", "$", "name", "=", "$", "this", "->", "dirData", ".", "$", "name", ";", "if", "(", "is_dir", "(", "$", "name", ")", ")", "{", "$", "files", "=", "glob", "(", "$", "name", ".", "'/{.*,*}'", ",", "GLOB_BRACE", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "files", ")", ";", "$", "i", "++", ")", "{", "if", "(", "substr", "(", "$", "files", "[", "$", "i", "]", ",", "-", "2", ")", "==", "'/.'", "||", "substr", "(", "$", "files", "[", "$", "i", "]", ",", "-", "3", ")", "==", "'/..'", ")", "continue", ";", "if", "(", "is_dir", "(", "$", "files", "[", "$", "i", "]", ")", ")", "$", "result", "=", "$", "this", "->", "rmdir", "(", "substr", "(", "$", "files", "[", "$", "i", "]", ",", "strlen", "(", "$", "this", "->", "dirData", ")", ")", ")", ";", "elseif", "(", "is_file", "(", "$", "files", "[", "$", "i", "]", ")", ")", "$", "result", "=", "filedelete", "(", "$", "files", "[", "$", "i", "]", ")", ";", "if", "(", "!", "$", "result", ")", "break", ";", "}", "if", "(", "$", "result", ")", "$", "result", "=", "rmdir", "(", "$", "name", ")", ";", "}", "return", "$", "result", ";", "}" ]
Удаление директории и файлов @param string $name Имя директории @return bool Результат
[ "Удаление", "директории", "и", "файлов" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L671-L689
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.dbCreateTable
protected function dbCreateTable($SQL, $name = '') { $result = Eresus_CMS::getLegacyKernel()->db->create($this->__table($name), $SQL); return $result; }
php
protected function dbCreateTable($SQL, $name = '') { $result = Eresus_CMS::getLegacyKernel()->db->create($this->__table($name), $SQL); return $result; }
[ "protected", "function", "dbCreateTable", "(", "$", "SQL", ",", "$", "name", "=", "''", ")", "{", "$", "result", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "create", "(", "$", "this", "->", "__table", "(", "$", "name", ")", ",", "$", "SQL", ")", ";", "return", "$", "result", ";", "}" ]
Создание таблицы в БД @param string $SQL Описание таблицы @param string $name Имя таблицы @return bool Результат выполнения
[ "Создание", "таблицы", "в", "БД" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L710-L714
Eresus/EresusCMS
src/core/Plugin.php
Eresus_Plugin.dbDropTable
protected function dbDropTable($name = '') { $result = Eresus_CMS::getLegacyKernel()->db->drop($this->__table($name)); return $result; }
php
protected function dbDropTable($name = '') { $result = Eresus_CMS::getLegacyKernel()->db->drop($this->__table($name)); return $result; }
[ "protected", "function", "dbDropTable", "(", "$", "name", "=", "''", ")", "{", "$", "result", "=", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "db", "->", "drop", "(", "$", "this", "->", "__table", "(", "$", "name", ")", ")", ";", "return", "$", "result", ";", "}" ]
Удаление таблицы БД @param string $name Имя таблицы @return bool Результат выполнения
[ "Удаление", "таблицы", "БД" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin.php#L723-L727
Eresus/EresusCMS
src/core/Client/Controller/Content/Default.php
Eresus_Client_Controller_Content_Default.getHtml
public function getHtml(Eresus_CMS_Request $request, TClientUI $page) { $plugin = new ContentPlugin; return $plugin->clientRenderContent($request, $page); }
php
public function getHtml(Eresus_CMS_Request $request, TClientUI $page) { $plugin = new ContentPlugin; return $plugin->clientRenderContent($request, $page); }
[ "public", "function", "getHtml", "(", "Eresus_CMS_Request", "$", "request", ",", "TClientUI", "$", "page", ")", "{", "$", "plugin", "=", "new", "ContentPlugin", ";", "return", "$", "plugin", "->", "clientRenderContent", "(", "$", "request", ",", "$", "page", ")", ";", "}" ]
Возвращает разметку области контента @param Eresus_CMS_Request $request @param TClientUI $page @return Eresus_HTTP_Response|string @since 3.01
[ "Возвращает", "разметку", "области", "контента" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Client/Controller/Content/Default.php#L45-L49
infusephp/infuse
src/RouteResolver.php
RouteResolver.resolve
public function resolve($route, $req, $res, array $args) { $result = false; if (is_array($route) || is_string($route)) { // method name and controller supplied if (is_string($route) && $req->params('controller')) { $route = [$req->params('controller'), $route]; // method name supplied } elseif (is_string($route)) { $route = [$this->defaultController, $route]; // no method name? fallback to the index() method } elseif (count($route) == 1) { $route[] = $this->defaultAction; } list($controller, $method) = $route; $controller = $this->namespace.'\\'.$controller; if (!class_exists($controller)) { throw new \Exception("Controller does not exist: $controller"); } $controllerObj = new $controller(); // give the controller access to the DI container if (method_exists($controllerObj, 'setApp')) { $controllerObj->setApp($this->app); } // collect any preset route parameters if (isset($route[2])) { $params = $route[2]; $req->setParams($params); } $result = $controllerObj->$method($req, $res, $args); } elseif (is_callable($route)) { $result = call_user_func($route, $req, $res, $args); } if ($result instanceof View) { $res->render($result); } return $res; }
php
public function resolve($route, $req, $res, array $args) { $result = false; if (is_array($route) || is_string($route)) { // method name and controller supplied if (is_string($route) && $req->params('controller')) { $route = [$req->params('controller'), $route]; // method name supplied } elseif (is_string($route)) { $route = [$this->defaultController, $route]; // no method name? fallback to the index() method } elseif (count($route) == 1) { $route[] = $this->defaultAction; } list($controller, $method) = $route; $controller = $this->namespace.'\\'.$controller; if (!class_exists($controller)) { throw new \Exception("Controller does not exist: $controller"); } $controllerObj = new $controller(); // give the controller access to the DI container if (method_exists($controllerObj, 'setApp')) { $controllerObj->setApp($this->app); } // collect any preset route parameters if (isset($route[2])) { $params = $route[2]; $req->setParams($params); } $result = $controllerObj->$method($req, $res, $args); } elseif (is_callable($route)) { $result = call_user_func($route, $req, $res, $args); } if ($result instanceof View) { $res->render($result); } return $res; }
[ "public", "function", "resolve", "(", "$", "route", ",", "$", "req", ",", "$", "res", ",", "array", "$", "args", ")", "{", "$", "result", "=", "false", ";", "if", "(", "is_array", "(", "$", "route", ")", "||", "is_string", "(", "$", "route", ")", ")", "{", "// method name and controller supplied", "if", "(", "is_string", "(", "$", "route", ")", "&&", "$", "req", "->", "params", "(", "'controller'", ")", ")", "{", "$", "route", "=", "[", "$", "req", "->", "params", "(", "'controller'", ")", ",", "$", "route", "]", ";", "// method name supplied", "}", "elseif", "(", "is_string", "(", "$", "route", ")", ")", "{", "$", "route", "=", "[", "$", "this", "->", "defaultController", ",", "$", "route", "]", ";", "// no method name? fallback to the index() method", "}", "elseif", "(", "count", "(", "$", "route", ")", "==", "1", ")", "{", "$", "route", "[", "]", "=", "$", "this", "->", "defaultAction", ";", "}", "list", "(", "$", "controller", ",", "$", "method", ")", "=", "$", "route", ";", "$", "controller", "=", "$", "this", "->", "namespace", ".", "'\\\\'", ".", "$", "controller", ";", "if", "(", "!", "class_exists", "(", "$", "controller", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Controller does not exist: $controller\"", ")", ";", "}", "$", "controllerObj", "=", "new", "$", "controller", "(", ")", ";", "// give the controller access to the DI container", "if", "(", "method_exists", "(", "$", "controllerObj", ",", "'setApp'", ")", ")", "{", "$", "controllerObj", "->", "setApp", "(", "$", "this", "->", "app", ")", ";", "}", "// collect any preset route parameters", "if", "(", "isset", "(", "$", "route", "[", "2", "]", ")", ")", "{", "$", "params", "=", "$", "route", "[", "2", "]", ";", "$", "req", "->", "setParams", "(", "$", "params", ")", ";", "}", "$", "result", "=", "$", "controllerObj", "->", "$", "method", "(", "$", "req", ",", "$", "res", ",", "$", "args", ")", ";", "}", "elseif", "(", "is_callable", "(", "$", "route", ")", ")", "{", "$", "result", "=", "call_user_func", "(", "$", "route", ",", "$", "req", ",", "$", "res", ",", "$", "args", ")", ";", "}", "if", "(", "$", "result", "instanceof", "View", ")", "{", "$", "res", "->", "render", "(", "$", "result", ")", ";", "}", "return", "$", "res", ";", "}" ]
Executes a route handler. @param array|string $route array('controller','method') or array('controller') or 'method' @param Request $req @param Response $res @param array $args @throws Exception when the route cannot be resolved. @return Response
[ "Executes", "a", "route", "handler", "." ]
train
https://github.com/infusephp/infuse/blob/7520b237c69f3d8a07d95d7481b26027ced2ed83/src/RouteResolver.php#L117-L163
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/internal/header_folder.php
ezcMailHeaderFolder.foldAny
static public function foldAny( $text ) { // Don't fold unless we have to. if ( strlen( $text ) <= self::$limit ) { return $text; } // go to 998'th char. // search back to whitespace // fold $length = strlen( $text ); $folded = ""; // find first occurence of whitespace searching backwards $search = 0; $previousFold = 0; while ( ( $search + self::$limit ) < $length ) { // search from the max possible length of the substring $search += self::$limit; while ( $text[$search] != " " && $text[$search] != "\t" && $search > $previousFold ) { $search--; } if ( $search == $previousFold ) { // continuous string of more than limit chars. // We will just have to continue searching forwards to the next whitespace instead // This is not confirming to standard.. but what can we do? $search += self::$limit; // back to where we started while ( $search < $length && $text[$search] != " " && $text[$search] != "\t" ) { $search++; } } // lets fold if ( $folded === "" ) { $folded = substr( $text, $previousFold, $search - $previousFold ); } else { $folded .= ezcMailTools::lineBreak() . substr( $text, $previousFold, $search - $previousFold ); } $previousFold = $search; } // we need to append the rest if there is any if ( $search < $length ) { $folded .= ezcMailTools::lineBreak() . substr( $text, $search ); } return $folded; }
php
static public function foldAny( $text ) { // Don't fold unless we have to. if ( strlen( $text ) <= self::$limit ) { return $text; } // go to 998'th char. // search back to whitespace // fold $length = strlen( $text ); $folded = ""; // find first occurence of whitespace searching backwards $search = 0; $previousFold = 0; while ( ( $search + self::$limit ) < $length ) { // search from the max possible length of the substring $search += self::$limit; while ( $text[$search] != " " && $text[$search] != "\t" && $search > $previousFold ) { $search--; } if ( $search == $previousFold ) { // continuous string of more than limit chars. // We will just have to continue searching forwards to the next whitespace instead // This is not confirming to standard.. but what can we do? $search += self::$limit; // back to where we started while ( $search < $length && $text[$search] != " " && $text[$search] != "\t" ) { $search++; } } // lets fold if ( $folded === "" ) { $folded = substr( $text, $previousFold, $search - $previousFold ); } else { $folded .= ezcMailTools::lineBreak() . substr( $text, $previousFold, $search - $previousFold ); } $previousFold = $search; } // we need to append the rest if there is any if ( $search < $length ) { $folded .= ezcMailTools::lineBreak() . substr( $text, $search ); } return $folded; }
[ "static", "public", "function", "foldAny", "(", "$", "text", ")", "{", "// Don't fold unless we have to.", "if", "(", "strlen", "(", "$", "text", ")", "<=", "self", "::", "$", "limit", ")", "{", "return", "$", "text", ";", "}", "// go to 998'th char.", "// search back to whitespace", "// fold", "$", "length", "=", "strlen", "(", "$", "text", ")", ";", "$", "folded", "=", "\"\"", ";", "// find first occurence of whitespace searching backwards", "$", "search", "=", "0", ";", "$", "previousFold", "=", "0", ";", "while", "(", "(", "$", "search", "+", "self", "::", "$", "limit", ")", "<", "$", "length", ")", "{", "// search from the max possible length of the substring", "$", "search", "+=", "self", "::", "$", "limit", ";", "while", "(", "$", "text", "[", "$", "search", "]", "!=", "\" \"", "&&", "$", "text", "[", "$", "search", "]", "!=", "\"\\t\"", "&&", "$", "search", ">", "$", "previousFold", ")", "{", "$", "search", "--", ";", "}", "if", "(", "$", "search", "==", "$", "previousFold", ")", "{", "// continuous string of more than limit chars.", "// We will just have to continue searching forwards to the next whitespace instead", "// This is not confirming to standard.. but what can we do?", "$", "search", "+=", "self", "::", "$", "limit", ";", "// back to where we started", "while", "(", "$", "search", "<", "$", "length", "&&", "$", "text", "[", "$", "search", "]", "!=", "\" \"", "&&", "$", "text", "[", "$", "search", "]", "!=", "\"\\t\"", ")", "{", "$", "search", "++", ";", "}", "}", "// lets fold", "if", "(", "$", "folded", "===", "\"\"", ")", "{", "$", "folded", "=", "substr", "(", "$", "text", ",", "$", "previousFold", ",", "$", "search", "-", "$", "previousFold", ")", ";", "}", "else", "{", "$", "folded", ".=", "ezcMailTools", "::", "lineBreak", "(", ")", ".", "substr", "(", "$", "text", ",", "$", "previousFold", ",", "$", "search", "-", "$", "previousFold", ")", ";", "}", "$", "previousFold", "=", "$", "search", ";", "}", "// we need to append the rest if there is any", "if", "(", "$", "search", "<", "$", "length", ")", "{", "$", "folded", ".=", "ezcMailTools", "::", "lineBreak", "(", ")", ".", "substr", "(", "$", "text", ",", "$", "search", ")", ";", "}", "return", "$", "folded", ";", "}" ]
Returns $text folded to the 998 character limit on any whitespace. The algorithm tries to minimize the number of comparisons by searching backwards from the maximum number of allowed characters on a line. @param string $text @return string
[ "Returns", "$text", "folded", "to", "the", "998", "character", "limit", "on", "any", "whitespace", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/internal/header_folder.php#L87-L144
thecodingmachine/mvc.splash-common
src/Mouf/Mvc/Splash/Services/SplashCreateControllerService.php
SplashCreateControllerService.generate
public function generate(MoufManager $moufManager, $controllerName, $instanceName, $namespace, $injectLogger = false, $injectTemplate = false, $actions = array()) { $namespace = rtrim($namespace, '\\').'\\'; $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json'); $possibleFileNames = $classNameMapper->getPossibleFileNames($namespace.$controllerName); if (!isset($possibleFileNames[0])) { throw new SplashException("The class '".$namespace.$controllerName."' cannot be loaded using rules defined in composer autoload section"); } $fileName = $possibleFileNames[0]; $controllerPhpDirectory = dirname($fileName); $errors = array(); if (!preg_match('/^[a-z_]\w*$/i', $controllerName)) { $errors['controllerNameError'] = 'This is not a valid PHP class name.'; } if (!preg_match('/^[a-z_][\w\\\\]*$/i', $namespace)) { $errors['namespaceError'] = 'This is not a valid PHP namespace.'; } $namespace = trim($namespace, '\\'); // Check that instance does not already exists if ($moufManager->has($instanceName)) { $errors['instanceError'] = 'This instance already exists.'; } $injectTwig = false; $importJsonResponse = false; $importHtmlResponse = false; $importRedirectResponse = false; foreach ($actions as $key => $action) { // Check if the view file exists if ($injectTemplate && $action['view'] == 'twig') { $injectTwig = true; $importHtmlResponse = true; $twigFile = ltrim($action['twigFile'], '/\\'); $viewDirName = ROOT_PATH.'../../../'.dirname($twigFile); $result = $this->createDirectory($viewDirName); if (!$result) { $errors['actions'][$key]['twigTemplateFileError'] = 'Unable to create directory "'.$viewDirName.'"'; } } if ($injectTemplate && $action['view'] == 'php') { $importHtmlResponse = true; $phpFile = ltrim($action['phpFile'], '/\\'); $viewDirName = ROOT_PATH.'../../../'.dirname($phpFile); $result = $this->createDirectory($viewDirName); if (!$result) { $errors['actions'][$key]['phpTemplateFileError'] = 'Unable to create directory "'.$viewDirName.'"'; } } if ($action['view'] == 'redirect') { if (!isset($action['redirect']) || empty($action['redirect'])) { $errors['actions'][$key]['redirectError'] = 'Redirection URL cannot be empty.'; } $importRedirectResponse = true; } if ($action['view'] == 'json') { $importJsonResponse = true; } } // TODO: check that URLs are not in error. if (!$errors) { $result = $this->createDirectory(ROOT_PATH.'../../../'.$controllerPhpDirectory); if (!$result) { $errors['namespaceError'] = 'Unable to create directory: "'.$controllerPhpDirectory.'"'; } elseif (file_exists(ROOT_PATH.'../../../'.$controllerPhpDirectory.$controllerName.'.php')) { $errors['namespaceError'] = 'The file "'.$controllerPhpDirectory.$controllerName.'.php already exists."'; } elseif (!is_writable(ROOT_PATH.'../../../'.$controllerPhpDirectory)) { $errors['namespaceError'] = 'Unable to write file in directory: "'.$controllerPhpDirectory.'"'; } if (!$errors) { ob_start(); echo '<?php '; ?> namespace <?= $namespace ?>; use TheCodingMachine\Splash\Annotations\Get; use TheCodingMachine\Splash\Annotations\Post; use TheCodingMachine\Splash\Annotations\Put; use TheCodingMachine\Splash\Annotations\Delete; use TheCodingMachine\Splash\Annotations\URL; <?php if ($injectTemplate) { ?> use Mouf\Html\Template\TemplateInterface; use Mouf\Html\HtmlElement\HtmlBlock; <?php } ?> <?php if ($injectLogger) { ?> use Psr\Log\LoggerInterface; <?php } ?> use Psr\Http\Message\ResponseInterface; <?php if ($injectTwig) { ?> use \Twig_Environment; use Mouf\Html\Renderer\Twig\TwigTemplate; <?php } ?> <?php if ($importJsonResponse) { ?> use Zend\Diactoros\Response\JsonResponse; <?php } ?> <?php if ($importRedirectResponse) { ?> use Zend\Diactoros\Response\RedirectResponse; <?php } ?> <?php if ($importHtmlResponse) { ?> use Mouf\Mvc\Splash\HtmlResponse; <?php } ?> /** * TODO: write controller comment */ class <?= $controllerName ?> { <?php if ($injectLogger) { ?> /** * The logger used by this controller. * @var LoggerInterface */ private $logger; <?php } ?> <?php if ($injectTemplate) { ?> /** * The template used by this controller. * @var TemplateInterface */ private $template; /** * The main content block of the page. * @var HtmlBlock */ private $content; <?php } ?> <?php if ($injectTwig) { ?> /** * The Twig environment (used to render Twig templates). * @var Twig_Environment */ private $twig; <?php } ?> /** * Controller's constructor. <?php if ($injectLogger) { echo " * @param LoggerInterface \$logger The logger\n"; } if ($injectTemplate) { echo " * @param TemplateInterface \$template The template used by this controller\n"; echo " * @param HtmlBlock \$content The main content block of the page\n"; } if ($injectTwig) { echo " * @param Twig_Environment \$twig The Twig environment (used to render Twig templates)\n"; } ?> */ public function __construct(<?php $parameters = array(); if ($injectLogger) { $parameters[] = 'LoggerInterface $logger'; } if ($injectTemplate) { $parameters[] = 'TemplateInterface $template'; $parameters[] = 'HtmlBlock $content'; } if ($injectTwig) { $parameters[] = 'Twig_Environment $twig'; } echo implode(', ', $parameters); ?>) { <?php if ($injectLogger) { ?> $this->logger = $logger; <?php } if ($injectTemplate) { ?> $this->template = $template; $this->content = $content; <?php } if ($injectTwig) { ?> $this->twig = $twig; <?php } ?> } <?php foreach ($actions as $action): ?> /** * @URL("<?= addslashes($action['url']) ?>") <?php if ($action['anyMethod'] == 'false') { if ($action['getMethod'] == 'true') { echo " * @Get\n"; } if ($action['postMethod'] == 'true') { echo " * @Post\n"; } if ($action['putMethod'] == 'true') { echo " * @Put\n"; } if ($action['deleteMethod'] == 'true') { echo " * @Delete\n"; } } // let's detect the {parameters} in the URL and add them if necessary if (isset($action['parameters'])) { $parameters = $action['parameters']; foreach ($parameters as $parameter) { echo ' * @param '.$parameter['type'].' $'.$parameter['name']."\n"; } } else { $parameters = array(); } ?> */ public function <?= $action['method'] ?>(<?php $parametersCode = array(); foreach ($parameters as $parameter) { $parameterCode = '$'.$parameter['name']; if ($parameter['optionnal'] == 'true') { if ($parameter['type'] == 'int') { $defaultValue = (int) $parameter['defaultValue']; } elseif ($parameter['type'] == 'number') { $defaultValue = (float) $parameter['defaultValue']; } else { $defaultValue = $parameter['defaultValue']; } $parameterCode .= ' = '.var_export($defaultValue, true); } $parametersCode[] = $parameterCode; } echo implode(', ', $parametersCode); ?>): ResponseInterface { // TODO: write content of action here <?php if ($injectTemplate && $action['view'] == 'twig'): ?> // Let's add the twig file to the template. $this->content->addHtmlElement(new TwigTemplate($this->twig, <?php var_export($action['twigFile']); ?>, array("message"=>"world"))); return new HtmlResponse($this->template); <?php elseif ($injectTemplate && $action['view'] == 'php'): ?> // Let's add the view to the content. // Note: $this is passed as the scope, so in the view file, you can refer to protected // and public variables and methods of this constructor using "$this". $this->content->addFile(ROOT_PATH.<?php var_export($action['phpFile']) ?>, $this); return new HtmlResponse($this->template); <?php elseif ($action['view'] == 'json'): ?> return new JsonResponse([ "status"=>"ok" ]); <?php elseif ($action['view'] == 'redirect'): ?> return new RedirectResponse(<?php var_export($action['redirect']); ?>); <?php endif; ?> } <?php endforeach; ?> } <?php $file = ob_get_clean(); file_put_contents(ROOT_PATH.'../../../'.$fileName, $file); chmod(ROOT_PATH.'../../../'.$fileName, 0664); // Now, let's create the views files foreach ($actions as $action) { if ($injectTemplate && $action['view'] == 'twig') { $twigFile = ltrim($action['twigFile'], '/\\'); if(!file_exists(ROOT_PATH.'../../../'.$twigFile)) { $twigTemplateFile = $this->generateTwigView(); file_put_contents(ROOT_PATH.'../../../'.$twigFile, $twigTemplateFile); chmod(ROOT_PATH.'../../../'.$twigFile, 0664); } } elseif ($injectTemplate && $action['view'] == 'php') { $phpFile = ltrim($action['phpFile'], '/\\'); if(!file_exists(ROOT_PATH.'../../../'.$phpFile)) { $phpTemplateFile = $this->generatePhpView($namespace.'\\'.$controllerName); file_put_contents(ROOT_PATH.'../../../'.$phpFile, $phpTemplateFile); chmod(ROOT_PATH.'../../../'.$phpFile, 0664); } } } // Now, let's create the instance $controllerInstance = $moufManager->createInstance($namespace.'\\'.$controllerName); $controllerInstance->setName($instanceName); if ($injectLogger) { if ($moufManager->has('psr.errorLogLogger')) { $controllerInstance->getProperty('logger')->setValue($moufManager->getInstanceDescriptor('psr.errorLogLogger')); } } if ($injectTemplate) { if ($moufManager->has('bootstrapTemplate')) { $controllerInstance->getProperty('template')->setValue($moufManager->getInstanceDescriptor('bootstrapTemplate')); } if ($moufManager->has('block.content')) { $controllerInstance->getProperty('content')->setValue($moufManager->getInstanceDescriptor('block.content')); } } if ($injectTwig) { if ($moufManager->has('twigEnvironment')) { $controllerInstance->getProperty('twig')->setValue($moufManager->getInstanceDescriptor('twigEnvironment')); } } $moufManager->rewriteMouf(); // There is a new class, let's purge the cache $moufCache = new MoufCache(); $moufCache->purgeAll(); // TODO: purge cache } } if ($errors) { $exception = new SplashCreateControllerServiceException('Errors detected : '.var_export($errors, true)); $exception->setErrors($errors); throw $exception; } }
php
public function generate(MoufManager $moufManager, $controllerName, $instanceName, $namespace, $injectLogger = false, $injectTemplate = false, $actions = array()) { $namespace = rtrim($namespace, '\\').'\\'; $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json'); $possibleFileNames = $classNameMapper->getPossibleFileNames($namespace.$controllerName); if (!isset($possibleFileNames[0])) { throw new SplashException("The class '".$namespace.$controllerName."' cannot be loaded using rules defined in composer autoload section"); } $fileName = $possibleFileNames[0]; $controllerPhpDirectory = dirname($fileName); $errors = array(); if (!preg_match('/^[a-z_]\w*$/i', $controllerName)) { $errors['controllerNameError'] = 'This is not a valid PHP class name.'; } if (!preg_match('/^[a-z_][\w\\\\]*$/i', $namespace)) { $errors['namespaceError'] = 'This is not a valid PHP namespace.'; } $namespace = trim($namespace, '\\'); // Check that instance does not already exists if ($moufManager->has($instanceName)) { $errors['instanceError'] = 'This instance already exists.'; } $injectTwig = false; $importJsonResponse = false; $importHtmlResponse = false; $importRedirectResponse = false; foreach ($actions as $key => $action) { // Check if the view file exists if ($injectTemplate && $action['view'] == 'twig') { $injectTwig = true; $importHtmlResponse = true; $twigFile = ltrim($action['twigFile'], '/\\'); $viewDirName = ROOT_PATH.'../../../'.dirname($twigFile); $result = $this->createDirectory($viewDirName); if (!$result) { $errors['actions'][$key]['twigTemplateFileError'] = 'Unable to create directory "'.$viewDirName.'"'; } } if ($injectTemplate && $action['view'] == 'php') { $importHtmlResponse = true; $phpFile = ltrim($action['phpFile'], '/\\'); $viewDirName = ROOT_PATH.'../../../'.dirname($phpFile); $result = $this->createDirectory($viewDirName); if (!$result) { $errors['actions'][$key]['phpTemplateFileError'] = 'Unable to create directory "'.$viewDirName.'"'; } } if ($action['view'] == 'redirect') { if (!isset($action['redirect']) || empty($action['redirect'])) { $errors['actions'][$key]['redirectError'] = 'Redirection URL cannot be empty.'; } $importRedirectResponse = true; } if ($action['view'] == 'json') { $importJsonResponse = true; } } // TODO: check that URLs are not in error. if (!$errors) { $result = $this->createDirectory(ROOT_PATH.'../../../'.$controllerPhpDirectory); if (!$result) { $errors['namespaceError'] = 'Unable to create directory: "'.$controllerPhpDirectory.'"'; } elseif (file_exists(ROOT_PATH.'../../../'.$controllerPhpDirectory.$controllerName.'.php')) { $errors['namespaceError'] = 'The file "'.$controllerPhpDirectory.$controllerName.'.php already exists."'; } elseif (!is_writable(ROOT_PATH.'../../../'.$controllerPhpDirectory)) { $errors['namespaceError'] = 'Unable to write file in directory: "'.$controllerPhpDirectory.'"'; } if (!$errors) { ob_start(); echo '<?php '; ?> namespace <?= $namespace ?>; use TheCodingMachine\Splash\Annotations\Get; use TheCodingMachine\Splash\Annotations\Post; use TheCodingMachine\Splash\Annotations\Put; use TheCodingMachine\Splash\Annotations\Delete; use TheCodingMachine\Splash\Annotations\URL; <?php if ($injectTemplate) { ?> use Mouf\Html\Template\TemplateInterface; use Mouf\Html\HtmlElement\HtmlBlock; <?php } ?> <?php if ($injectLogger) { ?> use Psr\Log\LoggerInterface; <?php } ?> use Psr\Http\Message\ResponseInterface; <?php if ($injectTwig) { ?> use \Twig_Environment; use Mouf\Html\Renderer\Twig\TwigTemplate; <?php } ?> <?php if ($importJsonResponse) { ?> use Zend\Diactoros\Response\JsonResponse; <?php } ?> <?php if ($importRedirectResponse) { ?> use Zend\Diactoros\Response\RedirectResponse; <?php } ?> <?php if ($importHtmlResponse) { ?> use Mouf\Mvc\Splash\HtmlResponse; <?php } ?> /** * TODO: write controller comment */ class <?= $controllerName ?> { <?php if ($injectLogger) { ?> /** * The logger used by this controller. * @var LoggerInterface */ private $logger; <?php } ?> <?php if ($injectTemplate) { ?> /** * The template used by this controller. * @var TemplateInterface */ private $template; /** * The main content block of the page. * @var HtmlBlock */ private $content; <?php } ?> <?php if ($injectTwig) { ?> /** * The Twig environment (used to render Twig templates). * @var Twig_Environment */ private $twig; <?php } ?> /** * Controller's constructor. <?php if ($injectLogger) { echo " * @param LoggerInterface \$logger The logger\n"; } if ($injectTemplate) { echo " * @param TemplateInterface \$template The template used by this controller\n"; echo " * @param HtmlBlock \$content The main content block of the page\n"; } if ($injectTwig) { echo " * @param Twig_Environment \$twig The Twig environment (used to render Twig templates)\n"; } ?> */ public function __construct(<?php $parameters = array(); if ($injectLogger) { $parameters[] = 'LoggerInterface $logger'; } if ($injectTemplate) { $parameters[] = 'TemplateInterface $template'; $parameters[] = 'HtmlBlock $content'; } if ($injectTwig) { $parameters[] = 'Twig_Environment $twig'; } echo implode(', ', $parameters); ?>) { <?php if ($injectLogger) { ?> $this->logger = $logger; <?php } if ($injectTemplate) { ?> $this->template = $template; $this->content = $content; <?php } if ($injectTwig) { ?> $this->twig = $twig; <?php } ?> } <?php foreach ($actions as $action): ?> /** * @URL("<?= addslashes($action['url']) ?>") <?php if ($action['anyMethod'] == 'false') { if ($action['getMethod'] == 'true') { echo " * @Get\n"; } if ($action['postMethod'] == 'true') { echo " * @Post\n"; } if ($action['putMethod'] == 'true') { echo " * @Put\n"; } if ($action['deleteMethod'] == 'true') { echo " * @Delete\n"; } } // let's detect the {parameters} in the URL and add them if necessary if (isset($action['parameters'])) { $parameters = $action['parameters']; foreach ($parameters as $parameter) { echo ' * @param '.$parameter['type'].' $'.$parameter['name']."\n"; } } else { $parameters = array(); } ?> */ public function <?= $action['method'] ?>(<?php $parametersCode = array(); foreach ($parameters as $parameter) { $parameterCode = '$'.$parameter['name']; if ($parameter['optionnal'] == 'true') { if ($parameter['type'] == 'int') { $defaultValue = (int) $parameter['defaultValue']; } elseif ($parameter['type'] == 'number') { $defaultValue = (float) $parameter['defaultValue']; } else { $defaultValue = $parameter['defaultValue']; } $parameterCode .= ' = '.var_export($defaultValue, true); } $parametersCode[] = $parameterCode; } echo implode(', ', $parametersCode); ?>): ResponseInterface { // TODO: write content of action here <?php if ($injectTemplate && $action['view'] == 'twig'): ?> // Let's add the twig file to the template. $this->content->addHtmlElement(new TwigTemplate($this->twig, <?php var_export($action['twigFile']); ?>, array("message"=>"world"))); return new HtmlResponse($this->template); <?php elseif ($injectTemplate && $action['view'] == 'php'): ?> // Let's add the view to the content. // Note: $this is passed as the scope, so in the view file, you can refer to protected // and public variables and methods of this constructor using "$this". $this->content->addFile(ROOT_PATH.<?php var_export($action['phpFile']) ?>, $this); return new HtmlResponse($this->template); <?php elseif ($action['view'] == 'json'): ?> return new JsonResponse([ "status"=>"ok" ]); <?php elseif ($action['view'] == 'redirect'): ?> return new RedirectResponse(<?php var_export($action['redirect']); ?>); <?php endif; ?> } <?php endforeach; ?> } <?php $file = ob_get_clean(); file_put_contents(ROOT_PATH.'../../../'.$fileName, $file); chmod(ROOT_PATH.'../../../'.$fileName, 0664); // Now, let's create the views files foreach ($actions as $action) { if ($injectTemplate && $action['view'] == 'twig') { $twigFile = ltrim($action['twigFile'], '/\\'); if(!file_exists(ROOT_PATH.'../../../'.$twigFile)) { $twigTemplateFile = $this->generateTwigView(); file_put_contents(ROOT_PATH.'../../../'.$twigFile, $twigTemplateFile); chmod(ROOT_PATH.'../../../'.$twigFile, 0664); } } elseif ($injectTemplate && $action['view'] == 'php') { $phpFile = ltrim($action['phpFile'], '/\\'); if(!file_exists(ROOT_PATH.'../../../'.$phpFile)) { $phpTemplateFile = $this->generatePhpView($namespace.'\\'.$controllerName); file_put_contents(ROOT_PATH.'../../../'.$phpFile, $phpTemplateFile); chmod(ROOT_PATH.'../../../'.$phpFile, 0664); } } } // Now, let's create the instance $controllerInstance = $moufManager->createInstance($namespace.'\\'.$controllerName); $controllerInstance->setName($instanceName); if ($injectLogger) { if ($moufManager->has('psr.errorLogLogger')) { $controllerInstance->getProperty('logger')->setValue($moufManager->getInstanceDescriptor('psr.errorLogLogger')); } } if ($injectTemplate) { if ($moufManager->has('bootstrapTemplate')) { $controllerInstance->getProperty('template')->setValue($moufManager->getInstanceDescriptor('bootstrapTemplate')); } if ($moufManager->has('block.content')) { $controllerInstance->getProperty('content')->setValue($moufManager->getInstanceDescriptor('block.content')); } } if ($injectTwig) { if ($moufManager->has('twigEnvironment')) { $controllerInstance->getProperty('twig')->setValue($moufManager->getInstanceDescriptor('twigEnvironment')); } } $moufManager->rewriteMouf(); // There is a new class, let's purge the cache $moufCache = new MoufCache(); $moufCache->purgeAll(); // TODO: purge cache } } if ($errors) { $exception = new SplashCreateControllerServiceException('Errors detected : '.var_export($errors, true)); $exception->setErrors($errors); throw $exception; } }
[ "public", "function", "generate", "(", "MoufManager", "$", "moufManager", ",", "$", "controllerName", ",", "$", "instanceName", ",", "$", "namespace", ",", "$", "injectLogger", "=", "false", ",", "$", "injectTemplate", "=", "false", ",", "$", "actions", "=", "array", "(", ")", ")", "{", "$", "namespace", "=", "rtrim", "(", "$", "namespace", ",", "'\\\\'", ")", ".", "'\\\\'", ";", "$", "classNameMapper", "=", "ClassNameMapper", "::", "createFromComposerFile", "(", "__DIR__", ".", "'/../../../../../../../../composer.json'", ")", ";", "$", "possibleFileNames", "=", "$", "classNameMapper", "->", "getPossibleFileNames", "(", "$", "namespace", ".", "$", "controllerName", ")", ";", "if", "(", "!", "isset", "(", "$", "possibleFileNames", "[", "0", "]", ")", ")", "{", "throw", "new", "SplashException", "(", "\"The class '\"", ".", "$", "namespace", ".", "$", "controllerName", ".", "\"' cannot be loaded using rules defined in composer autoload section\"", ")", ";", "}", "$", "fileName", "=", "$", "possibleFileNames", "[", "0", "]", ";", "$", "controllerPhpDirectory", "=", "dirname", "(", "$", "fileName", ")", ";", "$", "errors", "=", "array", "(", ")", ";", "if", "(", "!", "preg_match", "(", "'/^[a-z_]\\w*$/i'", ",", "$", "controllerName", ")", ")", "{", "$", "errors", "[", "'controllerNameError'", "]", "=", "'This is not a valid PHP class name.'", ";", "}", "if", "(", "!", "preg_match", "(", "'/^[a-z_][\\w\\\\\\\\]*$/i'", ",", "$", "namespace", ")", ")", "{", "$", "errors", "[", "'namespaceError'", "]", "=", "'This is not a valid PHP namespace.'", ";", "}", "$", "namespace", "=", "trim", "(", "$", "namespace", ",", "'\\\\'", ")", ";", "// Check that instance does not already exists", "if", "(", "$", "moufManager", "->", "has", "(", "$", "instanceName", ")", ")", "{", "$", "errors", "[", "'instanceError'", "]", "=", "'This instance already exists.'", ";", "}", "$", "injectTwig", "=", "false", ";", "$", "importJsonResponse", "=", "false", ";", "$", "importHtmlResponse", "=", "false", ";", "$", "importRedirectResponse", "=", "false", ";", "foreach", "(", "$", "actions", "as", "$", "key", "=>", "$", "action", ")", "{", "// Check if the view file exists", "if", "(", "$", "injectTemplate", "&&", "$", "action", "[", "'view'", "]", "==", "'twig'", ")", "{", "$", "injectTwig", "=", "true", ";", "$", "importHtmlResponse", "=", "true", ";", "$", "twigFile", "=", "ltrim", "(", "$", "action", "[", "'twigFile'", "]", ",", "'/\\\\'", ")", ";", "$", "viewDirName", "=", "ROOT_PATH", ".", "'../../../'", ".", "dirname", "(", "$", "twigFile", ")", ";", "$", "result", "=", "$", "this", "->", "createDirectory", "(", "$", "viewDirName", ")", ";", "if", "(", "!", "$", "result", ")", "{", "$", "errors", "[", "'actions'", "]", "[", "$", "key", "]", "[", "'twigTemplateFileError'", "]", "=", "'Unable to create directory \"'", ".", "$", "viewDirName", ".", "'\"'", ";", "}", "}", "if", "(", "$", "injectTemplate", "&&", "$", "action", "[", "'view'", "]", "==", "'php'", ")", "{", "$", "importHtmlResponse", "=", "true", ";", "$", "phpFile", "=", "ltrim", "(", "$", "action", "[", "'phpFile'", "]", ",", "'/\\\\'", ")", ";", "$", "viewDirName", "=", "ROOT_PATH", ".", "'../../../'", ".", "dirname", "(", "$", "phpFile", ")", ";", "$", "result", "=", "$", "this", "->", "createDirectory", "(", "$", "viewDirName", ")", ";", "if", "(", "!", "$", "result", ")", "{", "$", "errors", "[", "'actions'", "]", "[", "$", "key", "]", "[", "'phpTemplateFileError'", "]", "=", "'Unable to create directory \"'", ".", "$", "viewDirName", ".", "'\"'", ";", "}", "}", "if", "(", "$", "action", "[", "'view'", "]", "==", "'redirect'", ")", "{", "if", "(", "!", "isset", "(", "$", "action", "[", "'redirect'", "]", ")", "||", "empty", "(", "$", "action", "[", "'redirect'", "]", ")", ")", "{", "$", "errors", "[", "'actions'", "]", "[", "$", "key", "]", "[", "'redirectError'", "]", "=", "'Redirection URL cannot be empty.'", ";", "}", "$", "importRedirectResponse", "=", "true", ";", "}", "if", "(", "$", "action", "[", "'view'", "]", "==", "'json'", ")", "{", "$", "importJsonResponse", "=", "true", ";", "}", "}", "// TODO: check that URLs are not in error.", "if", "(", "!", "$", "errors", ")", "{", "$", "result", "=", "$", "this", "->", "createDirectory", "(", "ROOT_PATH", ".", "'../../../'", ".", "$", "controllerPhpDirectory", ")", ";", "if", "(", "!", "$", "result", ")", "{", "$", "errors", "[", "'namespaceError'", "]", "=", "'Unable to create directory: \"'", ".", "$", "controllerPhpDirectory", ".", "'\"'", ";", "}", "elseif", "(", "file_exists", "(", "ROOT_PATH", ".", "'../../../'", ".", "$", "controllerPhpDirectory", ".", "$", "controllerName", ".", "'.php'", ")", ")", "{", "$", "errors", "[", "'namespaceError'", "]", "=", "'The file \"'", ".", "$", "controllerPhpDirectory", ".", "$", "controllerName", ".", "'.php already exists.\"'", ";", "}", "elseif", "(", "!", "is_writable", "(", "ROOT_PATH", ".", "'../../../'", ".", "$", "controllerPhpDirectory", ")", ")", "{", "$", "errors", "[", "'namespaceError'", "]", "=", "'Unable to write file in directory: \"'", ".", "$", "controllerPhpDirectory", ".", "'\"'", ";", "}", "if", "(", "!", "$", "errors", ")", "{", "ob_start", "(", ")", ";", "echo", "'<?php\n'", ";", "?>\nnamespace <?=", "$", "namespace", "?>;\n\nuse TheCodingMachine\\Splash\\Annotations\\Get;\nuse TheCodingMachine\\Splash\\Annotations\\Post;\nuse TheCodingMachine\\Splash\\Annotations\\Put;\nuse TheCodingMachine\\Splash\\Annotations\\Delete;\nuse TheCodingMachine\\Splash\\Annotations\\URL;\n<?php", "if", "(", "$", "injectTemplate", ")", "{", "?>\nuse Mouf\\Html\\Template\\TemplateInterface;\nuse Mouf\\Html\\HtmlElement\\HtmlBlock;\n<?php", "}", "?>\n<?php", "if", "(", "$", "injectLogger", ")", "{", "?>\nuse Psr\\Log\\LoggerInterface;\n<?php", "}", "?>\nuse Psr\\Http\\Message\\ResponseInterface;\n<?php", "if", "(", "$", "injectTwig", ")", "{", "?>\nuse \\Twig_Environment;\nuse Mouf\\Html\\Renderer\\Twig\\TwigTemplate;\n<?php", "}", "?>\n<?php", "if", "(", "$", "importJsonResponse", ")", "{", "?>\nuse Zend\\Diactoros\\Response\\JsonResponse;\n<?php", "}", "?>\n<?php", "if", "(", "$", "importRedirectResponse", ")", "{", "?>\nuse Zend\\Diactoros\\Response\\RedirectResponse;\n<?php", "}", "?>\n<?php", "if", "(", "$", "importHtmlResponse", ")", "{", "?>\nuse Mouf\\Mvc\\Splash\\HtmlResponse;\n<?php", "}", "?>\n\n/**\n * TODO: write controller comment\n */\nclass <?=", "$", "controllerName", "?> {\n\n<?php", "if", "(", "$", "injectLogger", ")", "{", "?>\n /**\n * The logger used by this controller.\n * @var LoggerInterface\n */\n private $logger;\n\n<?php", "}", "?>\n<?php", "if", "(", "$", "injectTemplate", ")", "{", "?>\n /**\n * The template used by this controller.\n * @var TemplateInterface\n */\n private $template;\n\n /**\n * The main content block of the page.\n * @var HtmlBlock\n */\n private $content;\n\n<?php", "}", "?>\n<?php", "if", "(", "$", "injectTwig", ")", "{", "?>\n /**\n * The Twig environment (used to render Twig templates).\n * @var Twig_Environment\n */\n private $twig;\n\n<?php", "}", "?>\n\n /**\n * Controller's constructor.\n<?php", "if", "(", "$", "injectLogger", ")", "{", "echo", "\" * @param LoggerInterface \\$logger The logger\\n\"", ";", "}", "if", "(", "$", "injectTemplate", ")", "{", "echo", "\" * @param TemplateInterface \\$template The template used by this controller\\n\"", ";", "echo", "\" * @param HtmlBlock \\$content The main content block of the page\\n\"", ";", "}", "if", "(", "$", "injectTwig", ")", "{", "echo", "\" * @param Twig_Environment \\$twig The Twig environment (used to render Twig templates)\\n\"", ";", "}", "?>\n */\n public function __construct(<?php", "$", "parameters", "=", "array", "(", ")", ";", "if", "(", "$", "injectLogger", ")", "{", "$", "parameters", "[", "]", "=", "'LoggerInterface $logger'", ";", "}", "if", "(", "$", "injectTemplate", ")", "{", "$", "parameters", "[", "]", "=", "'TemplateInterface $template'", ";", "$", "parameters", "[", "]", "=", "'HtmlBlock $content'", ";", "}", "if", "(", "$", "injectTwig", ")", "{", "$", "parameters", "[", "]", "=", "'Twig_Environment $twig'", ";", "}", "echo", "implode", "(", "', '", ",", "$", "parameters", ")", ";", "?>) {\n<?php", "if", "(", "$", "injectLogger", ")", "{", "?>\n $this->logger = $logger;\n<?php", "}", "if", "(", "$", "injectTemplate", ")", "{", "?>\n $this->template = $template;\n $this->content = $content;\n<?php", "}", "if", "(", "$", "injectTwig", ")", "{", "?>\n $this->twig = $twig;\n<?php", "}", "?>\n }\n\n<?php", "foreach", "(", "$", "actions", "as", "$", "action", ")", ":", "?>\n /**\n * @URL(\"<?=", "addslashes", "(", "$", "action", "[", "'url'", "]", ")", "?>\")\n<?php", "if", "(", "$", "action", "[", "'anyMethod'", "]", "==", "'false'", ")", "{", "if", "(", "$", "action", "[", "'getMethod'", "]", "==", "'true'", ")", "{", "echo", "\" * @Get\\n\"", ";", "}", "if", "(", "$", "action", "[", "'postMethod'", "]", "==", "'true'", ")", "{", "echo", "\" * @Post\\n\"", ";", "}", "if", "(", "$", "action", "[", "'putMethod'", "]", "==", "'true'", ")", "{", "echo", "\" * @Put\\n\"", ";", "}", "if", "(", "$", "action", "[", "'deleteMethod'", "]", "==", "'true'", ")", "{", "echo", "\" * @Delete\\n\"", ";", "}", "}", "// let's detect the {parameters} in the URL and add them if necessary", "if", "(", "isset", "(", "$", "action", "[", "'parameters'", "]", ")", ")", "{", "$", "parameters", "=", "$", "action", "[", "'parameters'", "]", ";", "foreach", "(", "$", "parameters", "as", "$", "parameter", ")", "{", "echo", "' * @param '", ".", "$", "parameter", "[", "'type'", "]", ".", "' $'", ".", "$", "parameter", "[", "'name'", "]", ".", "\"\\n\"", ";", "}", "}", "else", "{", "$", "parameters", "=", "array", "(", ")", ";", "}", "?>\n */\n public function <?=", "$", "action", "[", "'method'", "]", "?>(<?php", "$", "parametersCode", "=", "array", "(", ")", ";", "foreach", "(", "$", "parameters", "as", "$", "parameter", ")", "{", "$", "parameterCode", "=", "'$'", ".", "$", "parameter", "[", "'name'", "]", ";", "if", "(", "$", "parameter", "[", "'optionnal'", "]", "==", "'true'", ")", "{", "if", "(", "$", "parameter", "[", "'type'", "]", "==", "'int'", ")", "{", "$", "defaultValue", "=", "(", "int", ")", "$", "parameter", "[", "'defaultValue'", "]", ";", "}", "elseif", "(", "$", "parameter", "[", "'type'", "]", "==", "'number'", ")", "{", "$", "defaultValue", "=", "(", "float", ")", "$", "parameter", "[", "'defaultValue'", "]", ";", "}", "else", "{", "$", "defaultValue", "=", "$", "parameter", "[", "'defaultValue'", "]", ";", "}", "$", "parameterCode", ".=", "' = '", ".", "var_export", "(", "$", "defaultValue", ",", "true", ")", ";", "}", "$", "parametersCode", "[", "]", "=", "$", "parameterCode", ";", "}", "echo", "implode", "(", "', '", ",", "$", "parametersCode", ")", ";", "?>): ResponseInterface {\n // TODO: write content of action here\n\n<?php", "if", "(", "$", "injectTemplate", "&&", "$", "action", "[", "'view'", "]", "==", "'twig'", ")", ":", "?>\n // Let's add the twig file to the template.\n $this->content->addHtmlElement(new TwigTemplate($this->twig, <?php", "var_export", "(", "$", "action", "[", "'twigFile'", "]", ")", ";", "?>, array(\"message\"=>\"world\")));\n\n return new HtmlResponse($this->template);\n<?php", "elseif", "(", "$", "injectTemplate", "&&", "$", "action", "[", "'view'", "]", "==", "'php'", ")", ":", "?>\n // Let's add the view to the content.\n // Note: $this is passed as the scope, so in the view file, you can refer to protected\n // and public variables and methods of this constructor using \"$this\".\n $this->content->addFile(ROOT_PATH.<?php", "var_export", "(", "$", "action", "[", "'phpFile'", "]", ")", "?>, $this);\n\n return new HtmlResponse($this->template);\n<?php", "elseif", "(", "$", "action", "[", "'view'", "]", "==", "'json'", ")", ":", "?>\n\n return new JsonResponse([ \"status\"=>\"ok\" ]);\n<?php", "elseif", "(", "$", "action", "[", "'view'", "]", "==", "'redirect'", ")", ":", "?>\n\n return new RedirectResponse(<?php", "var_export", "(", "$", "action", "[", "'redirect'", "]", ")", ";", "?>);\n<?php", "endif", ";", "?>\n }\n<?php", "endforeach", ";", "?>\n}\n<?php", "$", "file", "=", "ob_get_clean", "(", ")", ";", "file_put_contents", "(", "ROOT_PATH", ".", "'../../../'", ".", "$", "fileName", ",", "$", "file", ")", ";", "chmod", "(", "ROOT_PATH", ".", "'../../../'", ".", "$", "fileName", ",", "0664", ")", ";", "// Now, let's create the views files", "foreach", "(", "$", "actions", "as", "$", "action", ")", "{", "if", "(", "$", "injectTemplate", "&&", "$", "action", "[", "'view'", "]", "==", "'twig'", ")", "{", "$", "twigFile", "=", "ltrim", "(", "$", "action", "[", "'twigFile'", "]", ",", "'/\\\\'", ")", ";", "if", "(", "!", "file_exists", "(", "ROOT_PATH", ".", "'../../../'", ".", "$", "twigFile", ")", ")", "{", "$", "twigTemplateFile", "=", "$", "this", "->", "generateTwigView", "(", ")", ";", "file_put_contents", "(", "ROOT_PATH", ".", "'../../../'", ".", "$", "twigFile", ",", "$", "twigTemplateFile", ")", ";", "chmod", "(", "ROOT_PATH", ".", "'../../../'", ".", "$", "twigFile", ",", "0664", ")", ";", "}", "}", "elseif", "(", "$", "injectTemplate", "&&", "$", "action", "[", "'view'", "]", "==", "'php'", ")", "{", "$", "phpFile", "=", "ltrim", "(", "$", "action", "[", "'phpFile'", "]", ",", "'/\\\\'", ")", ";", "if", "(", "!", "file_exists", "(", "ROOT_PATH", ".", "'../../../'", ".", "$", "phpFile", ")", ")", "{", "$", "phpTemplateFile", "=", "$", "this", "->", "generatePhpView", "(", "$", "namespace", ".", "'\\\\'", ".", "$", "controllerName", ")", ";", "file_put_contents", "(", "ROOT_PATH", ".", "'../../../'", ".", "$", "phpFile", ",", "$", "phpTemplateFile", ")", ";", "chmod", "(", "ROOT_PATH", ".", "'../../../'", ".", "$", "phpFile", ",", "0664", ")", ";", "}", "}", "}", "// Now, let's create the instance", "$", "controllerInstance", "=", "$", "moufManager", "->", "createInstance", "(", "$", "namespace", ".", "'\\\\'", ".", "$", "controllerName", ")", ";", "$", "controllerInstance", "->", "setName", "(", "$", "instanceName", ")", ";", "if", "(", "$", "injectLogger", ")", "{", "if", "(", "$", "moufManager", "->", "has", "(", "'psr.errorLogLogger'", ")", ")", "{", "$", "controllerInstance", "->", "getProperty", "(", "'logger'", ")", "->", "setValue", "(", "$", "moufManager", "->", "getInstanceDescriptor", "(", "'psr.errorLogLogger'", ")", ")", ";", "}", "}", "if", "(", "$", "injectTemplate", ")", "{", "if", "(", "$", "moufManager", "->", "has", "(", "'bootstrapTemplate'", ")", ")", "{", "$", "controllerInstance", "->", "getProperty", "(", "'template'", ")", "->", "setValue", "(", "$", "moufManager", "->", "getInstanceDescriptor", "(", "'bootstrapTemplate'", ")", ")", ";", "}", "if", "(", "$", "moufManager", "->", "has", "(", "'block.content'", ")", ")", "{", "$", "controllerInstance", "->", "getProperty", "(", "'content'", ")", "->", "setValue", "(", "$", "moufManager", "->", "getInstanceDescriptor", "(", "'block.content'", ")", ")", ";", "}", "}", "if", "(", "$", "injectTwig", ")", "{", "if", "(", "$", "moufManager", "->", "has", "(", "'twigEnvironment'", ")", ")", "{", "$", "controllerInstance", "->", "getProperty", "(", "'twig'", ")", "->", "setValue", "(", "$", "moufManager", "->", "getInstanceDescriptor", "(", "'twigEnvironment'", ")", ")", ";", "}", "}", "$", "moufManager", "->", "rewriteMouf", "(", ")", ";", "// There is a new class, let's purge the cache", "$", "moufCache", "=", "new", "MoufCache", "(", ")", ";", "$", "moufCache", "->", "purgeAll", "(", ")", ";", "// TODO: purge cache", "}", "}", "if", "(", "$", "errors", ")", "{", "$", "exception", "=", "new", "SplashCreateControllerServiceException", "(", "'Errors detected : '", ".", "var_export", "(", "$", "errors", ",", "true", ")", ")", ";", "$", "exception", "->", "setErrors", "(", "$", "errors", ")", ";", "throw", "$", "exception", ";", "}", "}" ]
Generates a controller, view, and sets the instance up. @param string $controllerName @param string $instanceName @param string $namespace @param string $injectLogger @param string $injectTemplate @param array $actions
[ "Generates", "a", "controller", "view", "and", "sets", "the", "instance", "up", "." ]
train
https://github.com/thecodingmachine/mvc.splash-common/blob/eed0269ceda4d7d090a330a220490906a7aa60bd/src/Mouf/Mvc/Splash/Services/SplashCreateControllerService.php#L28-L404
thecodingmachine/mvc.splash-common
src/Mouf/Mvc/Splash/Services/SplashCreateControllerService.php
SplashCreateControllerService.createDirectory
private function createDirectory($directory) { if (!file_exists($directory)) { // Let's create the directory: $old = umask(0); $result = @mkdir($directory, 0775, true); umask($old); return $result; } return true; }
php
private function createDirectory($directory) { if (!file_exists($directory)) { // Let's create the directory: $old = umask(0); $result = @mkdir($directory, 0775, true); umask($old); return $result; } return true; }
[ "private", "function", "createDirectory", "(", "$", "directory", ")", "{", "if", "(", "!", "file_exists", "(", "$", "directory", ")", ")", "{", "// Let's create the directory:", "$", "old", "=", "umask", "(", "0", ")", ";", "$", "result", "=", "@", "mkdir", "(", "$", "directory", ",", "0775", ",", "true", ")", ";", "umask", "(", "$", "old", ")", ";", "return", "$", "result", ";", "}", "return", "true", ";", "}" ]
@param string $directory @return bool
[ "@param", "string", "$directory" ]
train
https://github.com/thecodingmachine/mvc.splash-common/blob/eed0269ceda4d7d090a330a220490906a7aa60bd/src/Mouf/Mvc/Splash/Services/SplashCreateControllerService.php#L422-L434
xiewulong/yii2-fileupload
oss/libs/symfony/yaml/Symfony/Component/Yaml/Dumper.php
Dumper.dump
public function dump($input, $inline = 0, $indent = 0, $exceptionOnInvalidType = false, $objectSupport = false) { $output = ''; $prefix = $indent ? str_repeat(' ', $indent) : ''; if ($inline <= 0 || !is_array($input) || empty($input)) { $output .= $prefix.Inline::dump($input, $exceptionOnInvalidType, $objectSupport); } else { $isAHash = array_keys($input) !== range(0, count($input) - 1); foreach ($input as $key => $value) { $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value); $output .= sprintf('%s%s%s%s', $prefix, $isAHash ? Inline::dump($key, $exceptionOnInvalidType, $objectSupport).':' : '-', $willBeInlined ? ' ' : "\n", $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $exceptionOnInvalidType, $objectSupport) ).($willBeInlined ? "\n" : ''); } } return $output; }
php
public function dump($input, $inline = 0, $indent = 0, $exceptionOnInvalidType = false, $objectSupport = false) { $output = ''; $prefix = $indent ? str_repeat(' ', $indent) : ''; if ($inline <= 0 || !is_array($input) || empty($input)) { $output .= $prefix.Inline::dump($input, $exceptionOnInvalidType, $objectSupport); } else { $isAHash = array_keys($input) !== range(0, count($input) - 1); foreach ($input as $key => $value) { $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value); $output .= sprintf('%s%s%s%s', $prefix, $isAHash ? Inline::dump($key, $exceptionOnInvalidType, $objectSupport).':' : '-', $willBeInlined ? ' ' : "\n", $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $exceptionOnInvalidType, $objectSupport) ).($willBeInlined ? "\n" : ''); } } return $output; }
[ "public", "function", "dump", "(", "$", "input", ",", "$", "inline", "=", "0", ",", "$", "indent", "=", "0", ",", "$", "exceptionOnInvalidType", "=", "false", ",", "$", "objectSupport", "=", "false", ")", "{", "$", "output", "=", "''", ";", "$", "prefix", "=", "$", "indent", "?", "str_repeat", "(", "' '", ",", "$", "indent", ")", ":", "''", ";", "if", "(", "$", "inline", "<=", "0", "||", "!", "is_array", "(", "$", "input", ")", "||", "empty", "(", "$", "input", ")", ")", "{", "$", "output", ".=", "$", "prefix", ".", "Inline", "::", "dump", "(", "$", "input", ",", "$", "exceptionOnInvalidType", ",", "$", "objectSupport", ")", ";", "}", "else", "{", "$", "isAHash", "=", "array_keys", "(", "$", "input", ")", "!==", "range", "(", "0", ",", "count", "(", "$", "input", ")", "-", "1", ")", ";", "foreach", "(", "$", "input", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "willBeInlined", "=", "$", "inline", "-", "1", "<=", "0", "||", "!", "is_array", "(", "$", "value", ")", "||", "empty", "(", "$", "value", ")", ";", "$", "output", ".=", "sprintf", "(", "'%s%s%s%s'", ",", "$", "prefix", ",", "$", "isAHash", "?", "Inline", "::", "dump", "(", "$", "key", ",", "$", "exceptionOnInvalidType", ",", "$", "objectSupport", ")", ".", "':'", ":", "'-'", ",", "$", "willBeInlined", "?", "' '", ":", "\"\\n\"", ",", "$", "this", "->", "dump", "(", "$", "value", ",", "$", "inline", "-", "1", ",", "$", "willBeInlined", "?", "0", ":", "$", "indent", "+", "$", "this", "->", "indentation", ",", "$", "exceptionOnInvalidType", ",", "$", "objectSupport", ")", ")", ".", "(", "$", "willBeInlined", "?", "\"\\n\"", ":", "''", ")", ";", "}", "}", "return", "$", "output", ";", "}" ]
Dumps a PHP value to YAML. @param mixed $input The PHP value @param integer $inline The level where you switch to inline YAML @param integer $indent The level of indentation (used internally) @param Boolean $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise @param Boolean $objectSupport true if object support is enabled, false otherwise @return string The YAML representation of the PHP value
[ "Dumps", "a", "PHP", "value", "to", "YAML", "." ]
train
https://github.com/xiewulong/yii2-fileupload/blob/3e75b17a4a18dd8466e3f57c63136de03470ca82/oss/libs/symfony/yaml/Symfony/Component/Yaml/Dumper.php#L49-L72
technote-space/wordpress-plugin-base
src/classes/models/lib/uninstall.php
Uninstall.uninstall
public function uninstall() { $uninstall = $this->_uninstall; ksort( $uninstall ); if ( ! is_multisite() ) { foreach ( $uninstall as $priority => $items ) { foreach ( $items as $item ) { if ( is_callable( $item ) ) { call_user_func( $item ); } } } } else { /** @var \wpdb $wpdb */ global $wpdb; $current_blog_id = get_current_blog_id(); $blog_ids = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" ); foreach ( $blog_ids as $blog_id ) { switch_to_blog( $blog_id ); foreach ( $uninstall as $priority => $items ) { foreach ( $items as $item ) { if ( is_callable( $item ) ) { call_user_func( $item ); } } } } switch_to_blog( $current_blog_id ); } $this->_uninstall = []; }
php
public function uninstall() { $uninstall = $this->_uninstall; ksort( $uninstall ); if ( ! is_multisite() ) { foreach ( $uninstall as $priority => $items ) { foreach ( $items as $item ) { if ( is_callable( $item ) ) { call_user_func( $item ); } } } } else { /** @var \wpdb $wpdb */ global $wpdb; $current_blog_id = get_current_blog_id(); $blog_ids = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" ); foreach ( $blog_ids as $blog_id ) { switch_to_blog( $blog_id ); foreach ( $uninstall as $priority => $items ) { foreach ( $items as $item ) { if ( is_callable( $item ) ) { call_user_func( $item ); } } } } switch_to_blog( $current_blog_id ); } $this->_uninstall = []; }
[ "public", "function", "uninstall", "(", ")", "{", "$", "uninstall", "=", "$", "this", "->", "_uninstall", ";", "ksort", "(", "$", "uninstall", ")", ";", "if", "(", "!", "is_multisite", "(", ")", ")", "{", "foreach", "(", "$", "uninstall", "as", "$", "priority", "=>", "$", "items", ")", "{", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "if", "(", "is_callable", "(", "$", "item", ")", ")", "{", "call_user_func", "(", "$", "item", ")", ";", "}", "}", "}", "}", "else", "{", "/** @var \\wpdb $wpdb */", "global", "$", "wpdb", ";", "$", "current_blog_id", "=", "get_current_blog_id", "(", ")", ";", "$", "blog_ids", "=", "$", "wpdb", "->", "get_col", "(", "\"SELECT blog_id FROM $wpdb->blogs\"", ")", ";", "foreach", "(", "$", "blog_ids", "as", "$", "blog_id", ")", "{", "switch_to_blog", "(", "$", "blog_id", ")", ";", "foreach", "(", "$", "uninstall", "as", "$", "priority", "=>", "$", "items", ")", "{", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "if", "(", "is_callable", "(", "$", "item", ")", ")", "{", "call_user_func", "(", "$", "item", ")", ";", "}", "}", "}", "}", "switch_to_blog", "(", "$", "current_blog_id", ")", ";", "}", "$", "this", "->", "_uninstall", "=", "[", "]", ";", "}" ]
uninstall
[ "uninstall" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/classes/models/lib/uninstall.php#L73-L104
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Core/Transformer/Writer/Xml/InterfaceConverter.php
InterfaceConverter.convert
public function convert(\DOMElement $parent, InterfaceDescriptor $interface) { $child = new \DOMElement('interface'); $parent->appendChild($child); /** @var InterfaceDescriptor $parentInterface */ foreach ($interface->getParent() as $parentInterface) { $parentFqcn = is_string($parentInterface) === false ? $parentInterface->getFullyQualifiedStructuralElementName() : $parentInterface; $child->appendChild(new \DOMElement('extends', $parentFqcn)); } $namespace = $interface->getNamespace()->getFullyQualifiedStructuralElementName(); $child->setAttribute('namespace', ltrim($namespace, '\\')); $child->setAttribute('line', $interface->getLine()); $child->appendChild(new \DOMElement('name', $interface->getName())); $child->appendChild(new \DOMElement('full_name', $interface->getFullyQualifiedStructuralElementName())); $this->docBlockConverter->convert($child, $interface); foreach ($interface->getConstants() as $constant) { $this->constantConverter->convert($child, $constant); } foreach ($interface->getMethods() as $method) { $this->methodConverter->convert($child, $method); } return $child; }
php
public function convert(\DOMElement $parent, InterfaceDescriptor $interface) { $child = new \DOMElement('interface'); $parent->appendChild($child); /** @var InterfaceDescriptor $parentInterface */ foreach ($interface->getParent() as $parentInterface) { $parentFqcn = is_string($parentInterface) === false ? $parentInterface->getFullyQualifiedStructuralElementName() : $parentInterface; $child->appendChild(new \DOMElement('extends', $parentFqcn)); } $namespace = $interface->getNamespace()->getFullyQualifiedStructuralElementName(); $child->setAttribute('namespace', ltrim($namespace, '\\')); $child->setAttribute('line', $interface->getLine()); $child->appendChild(new \DOMElement('name', $interface->getName())); $child->appendChild(new \DOMElement('full_name', $interface->getFullyQualifiedStructuralElementName())); $this->docBlockConverter->convert($child, $interface); foreach ($interface->getConstants() as $constant) { $this->constantConverter->convert($child, $constant); } foreach ($interface->getMethods() as $method) { $this->methodConverter->convert($child, $method); } return $child; }
[ "public", "function", "convert", "(", "\\", "DOMElement", "$", "parent", ",", "InterfaceDescriptor", "$", "interface", ")", "{", "$", "child", "=", "new", "\\", "DOMElement", "(", "'interface'", ")", ";", "$", "parent", "->", "appendChild", "(", "$", "child", ")", ";", "/** @var InterfaceDescriptor $parentInterface */", "foreach", "(", "$", "interface", "->", "getParent", "(", ")", "as", "$", "parentInterface", ")", "{", "$", "parentFqcn", "=", "is_string", "(", "$", "parentInterface", ")", "===", "false", "?", "$", "parentInterface", "->", "getFullyQualifiedStructuralElementName", "(", ")", ":", "$", "parentInterface", ";", "$", "child", "->", "appendChild", "(", "new", "\\", "DOMElement", "(", "'extends'", ",", "$", "parentFqcn", ")", ")", ";", "}", "$", "namespace", "=", "$", "interface", "->", "getNamespace", "(", ")", "->", "getFullyQualifiedStructuralElementName", "(", ")", ";", "$", "child", "->", "setAttribute", "(", "'namespace'", ",", "ltrim", "(", "$", "namespace", ",", "'\\\\'", ")", ")", ";", "$", "child", "->", "setAttribute", "(", "'line'", ",", "$", "interface", "->", "getLine", "(", ")", ")", ";", "$", "child", "->", "appendChild", "(", "new", "\\", "DOMElement", "(", "'name'", ",", "$", "interface", "->", "getName", "(", ")", ")", ")", ";", "$", "child", "->", "appendChild", "(", "new", "\\", "DOMElement", "(", "'full_name'", ",", "$", "interface", "->", "getFullyQualifiedStructuralElementName", "(", ")", ")", ")", ";", "$", "this", "->", "docBlockConverter", "->", "convert", "(", "$", "child", ",", "$", "interface", ")", ";", "foreach", "(", "$", "interface", "->", "getConstants", "(", ")", "as", "$", "constant", ")", "{", "$", "this", "->", "constantConverter", "->", "convert", "(", "$", "child", ",", "$", "constant", ")", ";", "}", "foreach", "(", "$", "interface", "->", "getMethods", "(", ")", "as", "$", "method", ")", "{", "$", "this", "->", "methodConverter", "->", "convert", "(", "$", "child", ",", "$", "method", ")", ";", "}", "return", "$", "child", ";", "}" ]
Export the given reflected interface definition to the provided parent element. This method creates a new child element on the given parent XML element and takes the properties of the Reflection argument and sets the elements and attributes on the child. If a child DOMElement is provided then the properties and attributes are set on this but the child element is not appended onto the parent. This is the responsibility of the invoker. Essentially this means that the $parent argument is ignored in this case. @param \DOMElement $parent Element to augment. @param InterfaceDescriptor $interface Element to export. @return \DOMElement
[ "Export", "the", "given", "reflected", "interface", "definition", "to", "the", "provided", "parent", "element", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Transformer/Writer/Xml/InterfaceConverter.php#L66-L97
webdevvie/pheanstalk-task-queue-bundle
Command/WorkerTenderCommand.php
WorkerTenderCommand.execute
protected function execute( InputInterface $input, OutputInterface $output ) { $this->initialiseWorker($input, $output); $this->verboseOutput("<info>Starting up</info>"); while ($this->keepWorking) { //do stuff //check if the processes are still working foreach ($this->family as $key => &$child) { $this->handle($key, $child); } $this->familyPlanning(); //go to sleep for a bit usleep(100000); } $this->verboseOutput("<info>DONE!</info>"); }
php
protected function execute( InputInterface $input, OutputInterface $output ) { $this->initialiseWorker($input, $output); $this->verboseOutput("<info>Starting up</info>"); while ($this->keepWorking) { //do stuff //check if the processes are still working foreach ($this->family as $key => &$child) { $this->handle($key, $child); } $this->familyPlanning(); //go to sleep for a bit usleep(100000); } $this->verboseOutput("<info>DONE!</info>"); }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "initialiseWorker", "(", "$", "input", ",", "$", "output", ")", ";", "$", "this", "->", "verboseOutput", "(", "\"<info>Starting up</info>\"", ")", ";", "while", "(", "$", "this", "->", "keepWorking", ")", "{", "//do stuff", "//check if the processes are still working", "foreach", "(", "$", "this", "->", "family", "as", "$", "key", "=>", "&", "$", "child", ")", "{", "$", "this", "->", "handle", "(", "$", "key", ",", "$", "child", ")", ";", "}", "$", "this", "->", "familyPlanning", "(", ")", ";", "//go to sleep for a bit", "usleep", "(", "100000", ")", ";", "}", "$", "this", "->", "verboseOutput", "(", "\"<info>DONE!</info>\"", ")", ";", "}" ]
{@inheritDoc} @param InputInterface $input @param OutputInterface $output @return void @throws \InvalidArgumentException
[ "{", "@inheritDoc", "}" ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/WorkerTenderCommand.php#L80-L97
webdevvie/pheanstalk-task-queue-bundle
Command/WorkerTenderCommand.php
WorkerTenderCommand.handle
private function handle($key, ChildProcessContainer $child) { $tube = $this->tube; $child->processOutput('child_' . $tube . $key); //send unhealthy child processes to bed (kill em off) if (!$child->checkHealth()) { $child->getReadyForBed(); } //send old children to bed (kill em off) $readyStatusses = array(ChildProcessContainer::STATUS_READY, ChildProcessContainer::STATUS_ALIVE); if ($child->getAge() >= $this->input->getOption('max-worker-age') && in_array($child->status, $readyStatusses) ) { $child->bedtime(); } //Kill off processes that have used up too much memory already if ($child->getBufferLength() >= $this->input->getOption('max-worker-buffer') && in_array($child->status, $readyStatusses) ) { $child->bedtime(); } //if the child is dead ,clean up the mess if ($child->isDead()) { $child->cleanUp(); } //if the child is cleaned up remove the object and clean up some memory if ($child->isCleanedUp()) { $this->verboseOutput("<info>Unsetting Child</info>: $key"); unset($this->family[$key]); $this->verboseOutput("<info>Children left</info>: " . count($this->family)); } }
php
private function handle($key, ChildProcessContainer $child) { $tube = $this->tube; $child->processOutput('child_' . $tube . $key); //send unhealthy child processes to bed (kill em off) if (!$child->checkHealth()) { $child->getReadyForBed(); } //send old children to bed (kill em off) $readyStatusses = array(ChildProcessContainer::STATUS_READY, ChildProcessContainer::STATUS_ALIVE); if ($child->getAge() >= $this->input->getOption('max-worker-age') && in_array($child->status, $readyStatusses) ) { $child->bedtime(); } //Kill off processes that have used up too much memory already if ($child->getBufferLength() >= $this->input->getOption('max-worker-buffer') && in_array($child->status, $readyStatusses) ) { $child->bedtime(); } //if the child is dead ,clean up the mess if ($child->isDead()) { $child->cleanUp(); } //if the child is cleaned up remove the object and clean up some memory if ($child->isCleanedUp()) { $this->verboseOutput("<info>Unsetting Child</info>: $key"); unset($this->family[$key]); $this->verboseOutput("<info>Children left</info>: " . count($this->family)); } }
[ "private", "function", "handle", "(", "$", "key", ",", "ChildProcessContainer", "$", "child", ")", "{", "$", "tube", "=", "$", "this", "->", "tube", ";", "$", "child", "->", "processOutput", "(", "'child_'", ".", "$", "tube", ".", "$", "key", ")", ";", "//send unhealthy child processes to bed (kill em off)", "if", "(", "!", "$", "child", "->", "checkHealth", "(", ")", ")", "{", "$", "child", "->", "getReadyForBed", "(", ")", ";", "}", "//send old children to bed (kill em off)", "$", "readyStatusses", "=", "array", "(", "ChildProcessContainer", "::", "STATUS_READY", ",", "ChildProcessContainer", "::", "STATUS_ALIVE", ")", ";", "if", "(", "$", "child", "->", "getAge", "(", ")", ">=", "$", "this", "->", "input", "->", "getOption", "(", "'max-worker-age'", ")", "&&", "in_array", "(", "$", "child", "->", "status", ",", "$", "readyStatusses", ")", ")", "{", "$", "child", "->", "bedtime", "(", ")", ";", "}", "//Kill off processes that have used up too much memory already", "if", "(", "$", "child", "->", "getBufferLength", "(", ")", ">=", "$", "this", "->", "input", "->", "getOption", "(", "'max-worker-buffer'", ")", "&&", "in_array", "(", "$", "child", "->", "status", ",", "$", "readyStatusses", ")", ")", "{", "$", "child", "->", "bedtime", "(", ")", ";", "}", "//if the child is dead ,clean up the mess", "if", "(", "$", "child", "->", "isDead", "(", ")", ")", "{", "$", "child", "->", "cleanUp", "(", ")", ";", "}", "//if the child is cleaned up remove the object and clean up some memory", "if", "(", "$", "child", "->", "isCleanedUp", "(", ")", ")", "{", "$", "this", "->", "verboseOutput", "(", "\"<info>Unsetting Child</info>: $key\"", ")", ";", "unset", "(", "$", "this", "->", "family", "[", "$", "key", "]", ")", ";", "$", "this", "->", "verboseOutput", "(", "\"<info>Children left</info>: \"", ".", "count", "(", "$", "this", "->", "family", ")", ")", ";", "}", "}" ]
Handles all child communication things @param string $key @param ChildProcessContainer $child @return void
[ "Handles", "all", "child", "communication", "things" ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/WorkerTenderCommand.php#L106-L137
webdevvie/pheanstalk-task-queue-bundle
Command/WorkerTenderCommand.php
WorkerTenderCommand.familyPlanning
private function familyPlanning() { list($total, $available) = $this->countWorkers(); if ($this->shutdownGracefully) { if ($total > 0) { $this->verboseOutput("<info>Shutting down</info> $total remaining children"); foreach ($this->family as $cnr => $child) { $this->verboseOutput("<info>Child: $cnr </info>" . $child->status); } $this->tellChildrenToPrepareForBed(); } else { $this->keepWorking = false; } return; } list($shouldHaveLessWorkers, $shouldHaveMoreWorkers) = $this->moreOrLess($total, $available); if ($shouldHaveMoreWorkers) { $this->family[] = $this->spawnChild(); } if ($shouldHaveLessWorkers) { //find one of the family members not doing anything and cap it! if ($this->findDisposableWorkers()) { //we found one $this->verboseOutput("<info>Found a disposable worker</info>"); } } }
php
private function familyPlanning() { list($total, $available) = $this->countWorkers(); if ($this->shutdownGracefully) { if ($total > 0) { $this->verboseOutput("<info>Shutting down</info> $total remaining children"); foreach ($this->family as $cnr => $child) { $this->verboseOutput("<info>Child: $cnr </info>" . $child->status); } $this->tellChildrenToPrepareForBed(); } else { $this->keepWorking = false; } return; } list($shouldHaveLessWorkers, $shouldHaveMoreWorkers) = $this->moreOrLess($total, $available); if ($shouldHaveMoreWorkers) { $this->family[] = $this->spawnChild(); } if ($shouldHaveLessWorkers) { //find one of the family members not doing anything and cap it! if ($this->findDisposableWorkers()) { //we found one $this->verboseOutput("<info>Found a disposable worker</info>"); } } }
[ "private", "function", "familyPlanning", "(", ")", "{", "list", "(", "$", "total", ",", "$", "available", ")", "=", "$", "this", "->", "countWorkers", "(", ")", ";", "if", "(", "$", "this", "->", "shutdownGracefully", ")", "{", "if", "(", "$", "total", ">", "0", ")", "{", "$", "this", "->", "verboseOutput", "(", "\"<info>Shutting down</info> $total remaining children\"", ")", ";", "foreach", "(", "$", "this", "->", "family", "as", "$", "cnr", "=>", "$", "child", ")", "{", "$", "this", "->", "verboseOutput", "(", "\"<info>Child: $cnr </info>\"", ".", "$", "child", "->", "status", ")", ";", "}", "$", "this", "->", "tellChildrenToPrepareForBed", "(", ")", ";", "}", "else", "{", "$", "this", "->", "keepWorking", "=", "false", ";", "}", "return", ";", "}", "list", "(", "$", "shouldHaveLessWorkers", ",", "$", "shouldHaveMoreWorkers", ")", "=", "$", "this", "->", "moreOrLess", "(", "$", "total", ",", "$", "available", ")", ";", "if", "(", "$", "shouldHaveMoreWorkers", ")", "{", "$", "this", "->", "family", "[", "]", "=", "$", "this", "->", "spawnChild", "(", ")", ";", "}", "if", "(", "$", "shouldHaveLessWorkers", ")", "{", "//find one of the family members not doing anything and cap it!", "if", "(", "$", "this", "->", "findDisposableWorkers", "(", ")", ")", "{", "//we found one", "$", "this", "->", "verboseOutput", "(", "\"<info>Found a disposable worker</info>\"", ")", ";", "}", "}", "}" ]
Produce more hands for the work needed @return void
[ "Produce", "more", "hands", "for", "the", "work", "needed" ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/WorkerTenderCommand.php#L144-L171