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_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
buse974/Dal | src/Dal/Paginator/Paginator.php | Paginator.getStatementPagination | public function getStatementPagination()
{
if (null !== $this->c && is_array($this->c)) {
$co = (reset($this->c) === 'ASC' || reset($this->c) === '>') ? '>' : '<';
$cc = key($this->c);
} else
if (null !== $this->c && ! is_array($this->c)) {
$co = ($this->o === 'ASC' || $this->o === '>') ? '>' : '<';
$cc = $this->c;
$this->o = [];
}
if (is_array($this->select)) {
$query = $this->select[0];
if (! empty($cc)) {
// @TODO check choise AND or WHERE and insertion before ORDER LIMIT GROUPBY
$query = sprintf('%s AND %s %s %s', $query, $cc, $co, $this->s);
}
if(null !== $this->p && null !== $this->n) {
$query = sprintf('%s LIMIT %d OFFSET %d', $query, $this->n, (($this->p - 1) * $this->n));
}
$adt = $this->sql->getAdapter();
$statement = $adt->query($query, $adt::QUERY_MODE_PREPARE);
} else {
$table = $this->select->getRawState(Select::TABLE);
$cols = $this->select->getRawState(Select::COLUMNS);
$joins = $this->select->getRawState(Select::JOINS);
$ords = array_merge($this->o, $this->select->getRawState(Select::ORDER));
$fords = [];
foreach ($joins as $value) {
if(!empty($value['columns'])) {
$cols = array_merge($cols,$value['columns']);
}
}
if (count($cols) === 1 && reset($cols) === '*') {
foreach ($ords as $ok => $ov) {
if(strpos($ok, '.') === false) {
$fords[$ok] = $ov;
} else {
$tmp = explode('.', $ok);
if($tmp[0] === $table) {
$fords[$tmp[1]] = $ov;
}
}
}
} else {
foreach ($ords as $ok => $ov) {
if (is_int($ok) && is_string($ov)) {
$tmp = explode(' ', $ov);
$ok = $tmp[0];
$ov = (count($tmp) === 2) ? $tmp[1] : 'ASC';
}
if(!is_int($ok)) {
$tmp = $this->checkColumns($ok, $table, $cols);
if ($tmp !== false) {
$fords[$tmp] = $ov;
}
}
}
}
$Select = new Select();
$Select->columns(array('*'));
$Select->from(array('original_select' => $this->select));
if (! empty($cc)) {
if (count($cols) === 1 && reset($cols) === '*') {
if(strpos($cc, '.') !== false) {
$tmp = explode('.', $ok);
$cc = ($tmp[0] === $table) ? $tmp[1] : false;
}
} else {
$cc = $this->checkColumns($cc, $table, $cols);
}
if ($cc !== false) {
$Select->where(array($cc . ' ' . $co . ' ?' => $this->s));
}
}
if(null !== $this->p && null !== $this->n) {
$Select->offset((($this->p - 1) * $this->n));
$Select->limit($this->n);
}
$Select->order($fords);
$statement = $this->sql->prepareStatementForSqlObject($Select);
}
return $statement;
} | php | public function getStatementPagination()
{
if (null !== $this->c && is_array($this->c)) {
$co = (reset($this->c) === 'ASC' || reset($this->c) === '>') ? '>' : '<';
$cc = key($this->c);
} else
if (null !== $this->c && ! is_array($this->c)) {
$co = ($this->o === 'ASC' || $this->o === '>') ? '>' : '<';
$cc = $this->c;
$this->o = [];
}
if (is_array($this->select)) {
$query = $this->select[0];
if (! empty($cc)) {
// @TODO check choise AND or WHERE and insertion before ORDER LIMIT GROUPBY
$query = sprintf('%s AND %s %s %s', $query, $cc, $co, $this->s);
}
if(null !== $this->p && null !== $this->n) {
$query = sprintf('%s LIMIT %d OFFSET %d', $query, $this->n, (($this->p - 1) * $this->n));
}
$adt = $this->sql->getAdapter();
$statement = $adt->query($query, $adt::QUERY_MODE_PREPARE);
} else {
$table = $this->select->getRawState(Select::TABLE);
$cols = $this->select->getRawState(Select::COLUMNS);
$joins = $this->select->getRawState(Select::JOINS);
$ords = array_merge($this->o, $this->select->getRawState(Select::ORDER));
$fords = [];
foreach ($joins as $value) {
if(!empty($value['columns'])) {
$cols = array_merge($cols,$value['columns']);
}
}
if (count($cols) === 1 && reset($cols) === '*') {
foreach ($ords as $ok => $ov) {
if(strpos($ok, '.') === false) {
$fords[$ok] = $ov;
} else {
$tmp = explode('.', $ok);
if($tmp[0] === $table) {
$fords[$tmp[1]] = $ov;
}
}
}
} else {
foreach ($ords as $ok => $ov) {
if (is_int($ok) && is_string($ov)) {
$tmp = explode(' ', $ov);
$ok = $tmp[0];
$ov = (count($tmp) === 2) ? $tmp[1] : 'ASC';
}
if(!is_int($ok)) {
$tmp = $this->checkColumns($ok, $table, $cols);
if ($tmp !== false) {
$fords[$tmp] = $ov;
}
}
}
}
$Select = new Select();
$Select->columns(array('*'));
$Select->from(array('original_select' => $this->select));
if (! empty($cc)) {
if (count($cols) === 1 && reset($cols) === '*') {
if(strpos($cc, '.') !== false) {
$tmp = explode('.', $ok);
$cc = ($tmp[0] === $table) ? $tmp[1] : false;
}
} else {
$cc = $this->checkColumns($cc, $table, $cols);
}
if ($cc !== false) {
$Select->where(array($cc . ' ' . $co . ' ?' => $this->s));
}
}
if(null !== $this->p && null !== $this->n) {
$Select->offset((($this->p - 1) * $this->n));
$Select->limit($this->n);
}
$Select->order($fords);
$statement = $this->sql->prepareStatementForSqlObject($Select);
}
return $statement;
} | Get Statement Pagination
@return \Zend\Db\Adapter\Driver\StatementInterface | https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/Paginator/Paginator.php#L253-L347 |
buse974/Dal | src/Dal/Paginator/Paginator.php | Paginator.getTotalItemCount | public function getTotalItemCount()
{
if ($this->rowCount !== null) {
return $this->rowCount;
}
$param = null;
if (is_array($this->select)) {
$select = $this->select[0];
$param = $this->select[1];
$adt = $this->sql->getAdapter();
$statement = $adt->query(sprintf("SELECT COUNT(1) AS c FROM (%s) AS original_select", $select), $adt::QUERY_MODE_PREPARE);
} else {
$select = clone $this->select;
$select->reset(Select::LIMIT);
$select->reset(Select::OFFSET);
$select->reset(Select::ORDER);
$countSelect = new Select();
$countSelect->columns(array('c' => new Expression('COUNT(1)')));
$countSelect->from(array('original_select' => $select));
$statement = $this->sql->prepareStatementForSqlObject($countSelect);
}
$result = $statement->execute($param);
$row = $result->current();
$this->rowCount = $row['c'];
return $this->rowCount;
} | php | public function getTotalItemCount()
{
if ($this->rowCount !== null) {
return $this->rowCount;
}
$param = null;
if (is_array($this->select)) {
$select = $this->select[0];
$param = $this->select[1];
$adt = $this->sql->getAdapter();
$statement = $adt->query(sprintf("SELECT COUNT(1) AS c FROM (%s) AS original_select", $select), $adt::QUERY_MODE_PREPARE);
} else {
$select = clone $this->select;
$select->reset(Select::LIMIT);
$select->reset(Select::OFFSET);
$select->reset(Select::ORDER);
$countSelect = new Select();
$countSelect->columns(array('c' => new Expression('COUNT(1)')));
$countSelect->from(array('original_select' => $select));
$statement = $this->sql->prepareStatementForSqlObject($countSelect);
}
$result = $statement->execute($param);
$row = $result->current();
$this->rowCount = $row['c'];
return $this->rowCount;
} | Returns the total number of rows in the result set
@return int | https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/Paginator/Paginator.php#L354-L387 |
buse974/Dal | src/Dal/Paginator/Paginator.php | Paginator.checkColumns | private function checkColumns($ok, $table, $cols)
{
$fords = false;
foreach ($cols as $ck => $cv) {
if ($cv instanceof Expression || $cv instanceof Select || is_string($cv)) {
if ($ok === $ck) {
$fords = $ok;
break;
} elseif (
($cv instanceof Expression && $ok === $cv->getExpression()) ||
(str_replace('.','$',$ok) === $ck) ||
(is_string($cv) && ($ok == $table . '.' . $cv) ) ) {
$fords = $ck;
break;
}
}
}
return $fords;
} | php | private function checkColumns($ok, $table, $cols)
{
$fords = false;
foreach ($cols as $ck => $cv) {
if ($cv instanceof Expression || $cv instanceof Select || is_string($cv)) {
if ($ok === $ck) {
$fords = $ok;
break;
} elseif (
($cv instanceof Expression && $ok === $cv->getExpression()) ||
(str_replace('.','$',$ok) === $ck) ||
(is_string($cv) && ($ok == $table . '.' . $cv) ) ) {
$fords = $ck;
break;
}
}
}
return $fords;
} | Check Column name
@param string $ok
@return array | https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/Paginator/Paginator.php#L395-L414 |
Tuna-CMS/tuna-bundle | src/Tuna/Bundle/EditablesBundle/Factory/EditableFactory.php | EditableFactory.getTypeConfig | protected function getTypeConfig($type)
{
if (is_object($type)) {
$type = $this->getTypeName($type);
} else if (class_exists($type)) {
$type = $this->getTypeFromClassName($type);
}
if (!$this->types->containsKey($type)) {
$this->throwInvalidTypeException($type);
}
return $this->types->get($type);
} | php | protected function getTypeConfig($type)
{
if (is_object($type)) {
$type = $this->getTypeName($type);
} else if (class_exists($type)) {
$type = $this->getTypeFromClassName($type);
}
if (!$this->types->containsKey($type)) {
$this->throwInvalidTypeException($type);
}
return $this->types->get($type);
} | @param object|string $type
@return TypeConfig
@throws \Exception | https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/EditablesBundle/Factory/EditableFactory.php#L88-L101 |
ZeinEddin/ZeDoctrineExtensions | lib/ZeDoctrineExtensions/Query/MySQL/TimeToSec.php | TimeToSec.getSql | public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
return sprintf(
'TIME_TO_SEC(%s)',
$this->time->dispatch($sqlWalker)
);
} | php | public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
return sprintf(
'TIME_TO_SEC(%s)',
$this->time->dispatch($sqlWalker)
);
} | {@inheritDoc} | https://github.com/ZeinEddin/ZeDoctrineExtensions/blob/3e9d8b022395122a39a7115ce02b20203d0e1dae/lib/ZeDoctrineExtensions/Query/MySQL/TimeToSec.php#L43-L49 |
acacha/forge-publish | src/Console/Commands/PublishDNS.php | PublishDNS.handle | public function handle()
{
$this->info('Checking DNS configuration');
$this->abortCommandExecution();
if ($this->dnsAlreadyResolved) {
$this->info("DNS resolution is ok. ");
return;
}
$this->info("DNS resolution is not correct. Let me help you configure it...");
$type = $this->option('type') ?
$this->option('type') :
$this->choice('Which system do you want to use?', ['hosts'], 0);
if ($type != 'hosts') {
//TODO Support Other services OpenDNS/Hover.com? DNS service wiht API
// https://laracasts.com/series/server-management-with-forge/episodes/8
$this->error('Type not supported');
die();
}
$this->addEntryToEtcHostsFile($this->domain, $this->ip);
$this->info('File ' . self::ETC_HOSTS . ' configured ok');
} | php | public function handle()
{
$this->info('Checking DNS configuration');
$this->abortCommandExecution();
if ($this->dnsAlreadyResolved) {
$this->info("DNS resolution is ok. ");
return;
}
$this->info("DNS resolution is not correct. Let me help you configure it...");
$type = $this->option('type') ?
$this->option('type') :
$this->choice('Which system do you want to use?', ['hosts'], 0);
if ($type != 'hosts') {
//TODO Support Other services OpenDNS/Hover.com? DNS service wiht API
// https://laracasts.com/series/server-management-with-forge/episodes/8
$this->error('Type not supported');
die();
}
$this->addEntryToEtcHostsFile($this->domain, $this->ip);
$this->info('File ' . self::ETC_HOSTS . ' configured ok');
} | Execute the console command. | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishDNS.php#L64-L89 |
acacha/forge-publish | src/Console/Commands/PublishDNS.php | PublishDNS.abortCommandExecution | protected function abortCommandExecution()
{
$this->domain = $this->checkEnv('domain', 'ACACHA_FORGE_DOMAIN', 'argument');
$this->ip = $this->checkEnv('ip', 'ACACHA_FORGE_IP_ADDRESS', 'argument');
if ($this->dnsResolutionIsOk()) {
return ;
}
$this->checkForRootPermission();
} | php | protected function abortCommandExecution()
{
$this->domain = $this->checkEnv('domain', 'ACACHA_FORGE_DOMAIN', 'argument');
$this->ip = $this->checkEnv('ip', 'ACACHA_FORGE_IP_ADDRESS', 'argument');
if ($this->dnsResolutionIsOk()) {
return ;
}
$this->checkForRootPermission();
} | Abort command execution. | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishDNS.php#L106-L116 |
thiagodp/http | lib/Mime.php | Mime.make | static function make( $mime, $param = null, $paramValue = null ) {
if ( null === $param || null === $paramValue ) {
return $mime;
}
return "$mime;$param=$paramValue";
} | php | static function make( $mime, $param = null, $paramValue = null ) {
if ( null === $param || null === $paramValue ) {
return $mime;
}
return "$mime;$param=$paramValue";
} | USEFUL STATIC METHODS | https://github.com/thiagodp/http/blob/e9ccb5e352015213dfcbf1d648c81afb293f4f24/lib/Mime.php#L70-L75 |
gwa/zero-library | src/Theme/AbstractTheme.php | AbstractTheme.addImageSize | final protected function addImageSize($name, $width, $height, $crop = false)
{
$this->getWpBridge()->addImageSize($name, $width, $height, $crop);
} | php | final protected function addImageSize($name, $width, $height, $crop = false)
{
$this->getWpBridge()->addImageSize($name, $width, $height, $crop);
} | Register a WP image size.
@param string $name
@param integer $width
@param integer $height
@param boolean|array $crop | https://github.com/gwa/zero-library/blob/2c1e700640f527ace3d58bc0e90bd71a096dcf41/src/Theme/AbstractTheme.php#L203-L206 |
gwa/zero-library | src/Theme/AbstractTheme.php | AbstractTheme.createController | public function createController($classname)
{
return (new $classname())
->setTheme($this)
->setTimberBridge($this->getTimberBridge())
->setWpBridge($this->getWpBridge());
} | php | public function createController($classname)
{
return (new $classname())
->setTheme($this)
->setTimberBridge($this->getTimberBridge())
->setWpBridge($this->getWpBridge());
} | Creates a controller (typically from a WP theme PHP file).
@param string $classname
@return \Gwa\Wordpress\Zero\Controller\AbstractController | https://github.com/gwa/zero-library/blob/2c1e700640f527ace3d58bc0e90bd71a096dcf41/src/Theme/AbstractTheme.php#L227-L233 |
faganchalabizada/portmanat-laravel | src/Portmanat.php | Portmanat.result | public function result()
{
$hash = strtoupper(md5($this->p_id . $this->s_id . $this->o_id . $this->tr_id . $this->key));
if ($hash == $this->hash) //Əgər dogrudursa 1, yoxsa 0 qaytarılmalı
{
return true;
} else {
return false;
}
} | php | public function result()
{
$hash = strtoupper(md5($this->p_id . $this->s_id . $this->o_id . $this->tr_id . $this->key));
if ($hash == $this->hash) //Əgər dogrudursa 1, yoxsa 0 qaytarılmalı
{
return true;
} else {
return false;
}
} | Check request
@return bool | https://github.com/faganchalabizada/portmanat-laravel/blob/7876fc4958508f719dd879299eabd02b8756791a/src/Portmanat.php#L40-L50 |
davin-bao/php-git | src/Console/Commands/PatchDb.php | PatchDb.handle | public function handle()
{
$self = $this;
$self->info("Patching database... \n");
$unOption = $this->option('uninstall');
$inOption = $this->option('install');
$sqlPath = app('config')->get('phpgit.path');
$branch = $self->getBranch($self);
$uninstallSqlFile = strtolower(dirname(app_path()).$sqlPath.$branch."-uninstall.sql");
$installSqlFile = strtolower(dirname(app_path()).$sqlPath.$branch."-install.sql");
$productionUninstallSqlFile = strtolower(dirname(app_path()).$sqlPath."production-uninstall.sql");
$productionInstallSqlFile = strtolower(dirname(app_path()).$sqlPath."production-install.sql");
$production =(env('APP_ENV') === 'production');
if($production){
$self->executeSql($unOption,$inOption,$productionUninstallSqlFile,$productionInstallSqlFile);
}else{
$self->executeSql($unOption,$inOption,$uninstallSqlFile,$installSqlFile);
}
return $self->info("Patching Database Success\n");
} | php | public function handle()
{
$self = $this;
$self->info("Patching database... \n");
$unOption = $this->option('uninstall');
$inOption = $this->option('install');
$sqlPath = app('config')->get('phpgit.path');
$branch = $self->getBranch($self);
$uninstallSqlFile = strtolower(dirname(app_path()).$sqlPath.$branch."-uninstall.sql");
$installSqlFile = strtolower(dirname(app_path()).$sqlPath.$branch."-install.sql");
$productionUninstallSqlFile = strtolower(dirname(app_path()).$sqlPath."production-uninstall.sql");
$productionInstallSqlFile = strtolower(dirname(app_path()).$sqlPath."production-install.sql");
$production =(env('APP_ENV') === 'production');
if($production){
$self->executeSql($unOption,$inOption,$productionUninstallSqlFile,$productionInstallSqlFile);
}else{
$self->executeSql($unOption,$inOption,$uninstallSqlFile,$installSqlFile);
}
return $self->info("Patching Database Success\n");
} | Execute the console command.
@return mixed | https://github.com/davin-bao/php-git/blob/9ae1997dc07978a3e647d44cba433d6638474c5c/src/Console/Commands/PatchDb.php#L55-L78 |
davin-bao/php-git | src/Console/Commands/PatchDb.php | PatchDb.getBranch | public function getBranch($self){
$branch = @file_get_contents(base_path() . '/.git/HEAD');
if (!empty($branch)) {
$branch = trim($branch);
$i = strripos($branch, '/');
$branch = strtolower(substr($branch, $i + 1));
return $branch;
}else{
return $self->error("Expect parameter '--branch'\n");
}
} | php | public function getBranch($self){
$branch = @file_get_contents(base_path() . '/.git/HEAD');
if (!empty($branch)) {
$branch = trim($branch);
$i = strripos($branch, '/');
$branch = strtolower(substr($branch, $i + 1));
return $branch;
}else{
return $self->error("Expect parameter '--branch'\n");
}
} | 获取当前分支名称
@return mixed | https://github.com/davin-bao/php-git/blob/9ae1997dc07978a3e647d44cba433d6638474c5c/src/Console/Commands/PatchDb.php#L85-L96 |
davin-bao/php-git | src/Console/Commands/PatchDb.php | PatchDb.executeSql | public function executeSql($unOption,$inOption,$uninstallSqlFile,$installSqlFile){
$self = $this;
if($unOption){
try {
set_time_limit(0);
if(file_exists($uninstallSqlFile)){
$self->info("Patching database file: $uninstallSqlFile\n");
DB::unprepared(file_get_contents($uninstallSqlFile));
}else{
return $self->info("No Configuration\n");
}
} catch (\Exception $e) {
return $self->error($e->getMessage(). "\n" . $e->getTraceAsString() . "\n");
}
}
if($inOption){
try {
set_time_limit(0);
if(file_exists($installSqlFile)){
$self->info("Patching database file: $installSqlFile\n");
DB::unprepared(file_get_contents($installSqlFile));
}else{
return $self->info("No Configuration\n");
}
} catch (\Exception $e) {
return $self->error($e->getMessage(). "\n" . $e->getTraceAsString() . "\n");
}
}
} | php | public function executeSql($unOption,$inOption,$uninstallSqlFile,$installSqlFile){
$self = $this;
if($unOption){
try {
set_time_limit(0);
if(file_exists($uninstallSqlFile)){
$self->info("Patching database file: $uninstallSqlFile\n");
DB::unprepared(file_get_contents($uninstallSqlFile));
}else{
return $self->info("No Configuration\n");
}
} catch (\Exception $e) {
return $self->error($e->getMessage(). "\n" . $e->getTraceAsString() . "\n");
}
}
if($inOption){
try {
set_time_limit(0);
if(file_exists($installSqlFile)){
$self->info("Patching database file: $installSqlFile\n");
DB::unprepared(file_get_contents($installSqlFile));
}else{
return $self->info("No Configuration\n");
}
} catch (\Exception $e) {
return $self->error($e->getMessage(). "\n" . $e->getTraceAsString() . "\n");
}
}
} | 根据SQL语句进行安装和卸载
@param string $unOption 卸载指令
@param string $inOption 安装指令
@param string $uninstallSqlFile 卸载内容
@param string $installSqlFile 安装内容
@return mixed | https://github.com/davin-bao/php-git/blob/9ae1997dc07978a3e647d44cba433d6638474c5c/src/Console/Commands/PatchDb.php#L107-L136 |
crisu83/yii-seo | behaviors/SeoActiveRecordBehavior.php | SeoActiveRecordBehavior.createUrl | public function createUrl($params=array())
{
return Yii::app()->createUrl($this->route, CMap::mergeArray($params, $this->evaluateParams($this->params)));
} | php | public function createUrl($params=array())
{
return Yii::app()->createUrl($this->route, CMap::mergeArray($params, $this->evaluateParams($this->params)));
} | Returns the URL for this model.
@param array $params additional GET parameters (name=>value)
@return string the URL | https://github.com/crisu83/yii-seo/blob/0cf100b2b89c09ba74a8b4c43b14539a023a9225/behaviors/SeoActiveRecordBehavior.php#L26-L29 |
crisu83/yii-seo | behaviors/SeoActiveRecordBehavior.php | SeoActiveRecordBehavior.evaluateParams | protected function evaluateParams($params)
{
foreach ($params as $name => $value)
{
if (is_callable($value))
$params[$name] = $this->evaluateExpression($value, array('data' => $this->owner));
}
return $params;
} | php | protected function evaluateParams($params)
{
foreach ($params as $name => $value)
{
if (is_callable($value))
$params[$name] = $this->evaluateExpression($value, array('data' => $this->owner));
}
return $params;
} | Evaluates the given params.
@param array $params the parameters.
@return array the evaluated params. | https://github.com/crisu83/yii-seo/blob/0cf100b2b89c09ba74a8b4c43b14539a023a9225/behaviors/SeoActiveRecordBehavior.php#L46-L54 |
bennybi/yii2-cza-base | widgets/ui/common/navigation/SubNavBar.php | SubNavBar.renderItem | protected function renderItem($item) {
$linkTemplate = empty($item['items']) ? $this->linkTemplate : $this->itemSubmenuLinkTemplate;
$labelTemplate = empty($item['items']) ? $this->labelTemplate : $this->itemSubmenuLabelTemplate;
if (isset($item['url'])) {
$template = ArrayHelper::getValue($item, 'template', $linkTemplate);
$params = [
'{url}' => Html::encode(Url::to($item['url'])),
'{label}' => $item['label'],
'{icon}' => isset($item['icon']) ? "<i class='{$item['icon']}'></i>" : '',
];
return strtr($template, $params);
} else {
$template = ArrayHelper::getValue($item, 'template', $labelTemplate);
return strtr($template, [
'{label}' => $item['label'],
'{icon}' => isset($item['icon']) ? "<i class='{$item['icon']}'></i>" : '',
]);
}
} | php | protected function renderItem($item) {
$linkTemplate = empty($item['items']) ? $this->linkTemplate : $this->itemSubmenuLinkTemplate;
$labelTemplate = empty($item['items']) ? $this->labelTemplate : $this->itemSubmenuLabelTemplate;
if (isset($item['url'])) {
$template = ArrayHelper::getValue($item, 'template', $linkTemplate);
$params = [
'{url}' => Html::encode(Url::to($item['url'])),
'{label}' => $item['label'],
'{icon}' => isset($item['icon']) ? "<i class='{$item['icon']}'></i>" : '',
];
return strtr($template, $params);
} else {
$template = ArrayHelper::getValue($item, 'template', $labelTemplate);
return strtr($template, [
'{label}' => $item['label'],
'{icon}' => isset($item['icon']) ? "<i class='{$item['icon']}'></i>" : '',
]);
}
} | Renders the content of a menu item.
Note that the container and the sub-menus are not rendered here.
@param array $item the menu item to be rendered. Please refer to [[items]] to see what data might be in the item.
@return string the rendering result | https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/widgets/ui/common/navigation/SubNavBar.php#L117-L139 |
smalldb/libSmalldb | class/Utils/UnionFind.php | UnionFind.add | public function add($x)
{
if (!isset($this->parents[$x])) {
$this->parents[$x] = $x;
}
} | php | public function add($x)
{
if (!isset($this->parents[$x])) {
$this->parents[$x] = $x;
}
} | Create set $x, the $x may or may not exist before | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/UnionFind.php#L41-L46 |
smalldb/libSmalldb | class/Utils/UnionFind.php | UnionFind.addUnique | public function addUnique($x)
{
if (isset($this->parents[$x])) {
throw new \RuntimeException('Element "'.$x.'" is already present in the union find.');
}
$this->parents[$x] = $x;
} | php | public function addUnique($x)
{
if (isset($this->parents[$x])) {
throw new \RuntimeException('Element "'.$x.'" is already present in the union find.');
}
$this->parents[$x] = $x;
} | Create set $x, the $x must not exist before | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/UnionFind.php#L52-L58 |
smalldb/libSmalldb | class/Utils/UnionFind.php | UnionFind.union | public function union($a, $b)
{
$ar = $this->find($a);
$br = $this->find($b);
if ($ar !== $br) {
$this->parents[$br] = $ar;
}
/*
$c = function($x) {
return sprintf('<span style="background:#%x">%s</span>', crc32($x) & 0xffffff | 0x808080, $x);
};
echo '<br><b>', $c($a), ' == ', $c($b), "</b><br>";
var_dump($this->parents);
echo ' ', $c($a), ' … ', ($ar === $this->parents[$ar] ? $c($ar).' is root' : '<b>'.$c($ar).' is NOT root!</b>'), "<br>";
echo ' ', $c($b), ' … ', ($br === $this->parents[$br] ? $c($br).' is root' : '<b>'.$c($br).' is NOT root!</b>'), "<br>";
echo ' ', $c($ar), ' =?= ', $c($br), "<br>";
echo ' ', $c($br), ' --> ', $c($this->parents[$br]), "<br>";
// */
} | php | public function union($a, $b)
{
$ar = $this->find($a);
$br = $this->find($b);
if ($ar !== $br) {
$this->parents[$br] = $ar;
}
/*
$c = function($x) {
return sprintf('<span style="background:#%x">%s</span>', crc32($x) & 0xffffff | 0x808080, $x);
};
echo '<br><b>', $c($a), ' == ', $c($b), "</b><br>";
var_dump($this->parents);
echo ' ', $c($a), ' … ', ($ar === $this->parents[$ar] ? $c($ar).' is root' : '<b>'.$c($ar).' is NOT root!</b>'), "<br>";
echo ' ', $c($b), ' … ', ($br === $this->parents[$br] ? $c($br).' is root' : '<b>'.$c($br).' is NOT root!</b>'), "<br>";
echo ' ', $c($ar), ' =?= ', $c($br), "<br>";
echo ' ', $c($br), ' --> ', $c($this->parents[$br]), "<br>";
// */
} | Union sets $a and $b. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/UnionFind.php#L64-L85 |
smalldb/libSmalldb | class/Utils/UnionFind.php | UnionFind.find | public function find($r)
{
if (!isset($this->parents[$r])) {
throw new \InvalidArgumentException('Element "'.$r.'" is not defined.');
}
while ($r !== $this->parents[$r]) {
$this->parents[$r] = $this->parents[$this->parents[$r]]; // Optimize nodes a little on the way to the root
$r = $this->parents[$r];
}
return $r;
} | php | public function find($r)
{
if (!isset($this->parents[$r])) {
throw new \InvalidArgumentException('Element "'.$r.'" is not defined.');
}
while ($r !== $this->parents[$r]) {
$this->parents[$r] = $this->parents[$this->parents[$r]]; // Optimize nodes a little on the way to the root
$r = $this->parents[$r];
}
return $r;
} | Get representative of $x | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/UnionFind.php#L100-L110 |
smalldb/libSmalldb | class/Utils/UnionFind.php | UnionFind.findAll | public function findAll()
{
$a = [];
foreach ($this->parents as $x => $r) {
$a[$x] = $this->find($x);
}
return $a;
} | php | public function findAll()
{
$a = [];
foreach ($this->parents as $x => $r) {
$a[$x] = $this->find($x);
}
return $a;
} | Get map of all items -> representative | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/UnionFind.php#L116-L123 |
smalldb/libSmalldb | class/Utils/UnionFind.php | UnionFind.findDistinct | public function findDistinct()
{
$a = [];
foreach ($this->parents as $x => $r) {
$a[$this->find($x)] = null;
}
return array_keys($a);
} | php | public function findDistinct()
{
$a = [];
foreach ($this->parents as $x => $r) {
$a[$this->find($x)] = null;
}
return array_keys($a);
} | Get a representative for each component. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/UnionFind.php#L129-L136 |
smalldb/libSmalldb | class/Utils/UnionFind.php | UnionFind.updateMap | public function updateMap(array $map, callable $resolveConflict = null): array
{
$new_map = [];
foreach ($map as $k => $v) {
$new_k = $this->find($k);
if (isset($new_map[$new_k])) {
if ($resolveConflict !== null) {
$new_map[$new_k] = $resolveConflict($v, $new_map[$new_k]);
} else {
throw new RuntimeException('Conflicting representatives in the map.');
}
} else {
$new_map[$new_k] = $v;
}
}
return $new_map;
} | php | public function updateMap(array $map, callable $resolveConflict = null): array
{
$new_map = [];
foreach ($map as $k => $v) {
$new_k = $this->find($k);
if (isset($new_map[$new_k])) {
if ($resolveConflict !== null) {
$new_map[$new_k] = $resolveConflict($v, $new_map[$new_k]);
} else {
throw new RuntimeException('Conflicting representatives in the map.');
}
} else {
$new_map[$new_k] = $v;
}
}
return $new_map;
} | Update keys in the $map to match representatives.
@param array $map Map to update
@param callable|null $resolveConflict Callable (function($a, $b)) returning a new value to resolve conflicts if two keys has the same representative.
@return array New map with old values and new keys. | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/UnionFind.php#L146-L162 |
smalldb/libSmalldb | class/Utils/UnionFind.php | UnionFind.dumpDot | public function dumpDot()
{
$dot = '';
foreach ($this->parents as $x => $r) {
$dot .= sprintf("\"[UF] %s\" [fillcolor=\"#%x\"];\n", $x, crc32($x) & 0xffffff | 0x808080);
$dot .= "\"[UF] $r\" -> \"[UF] $x\" [arrowhead=none,arrowtail=vee];\n";
}
return $dot;
} | php | public function dumpDot()
{
$dot = '';
foreach ($this->parents as $x => $r) {
$dot .= sprintf("\"[UF] %s\" [fillcolor=\"#%x\"];\n", $x, crc32($x) & 0xffffff | 0x808080);
$dot .= "\"[UF] $r\" -> \"[UF] $x\" [arrowhead=none,arrowtail=vee];\n";
}
return $dot;
} | Debug: Dump the UF tree to Dot for Graphviz | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Utils/UnionFind.php#L168-L176 |
liufee/cms-core | frontend/controllers/SearchController.php | SearchController.actionIndex | public function actionIndex()
{
$where = ['type' => Article::ARTICLE];
$query = Article::find()->select([])->where($where);
$keyword = htmlspecialchars(yii::$app->getRequest()->get('q'));
$query->andFilterWhere(['like', 'title', $keyword]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'sort' => SORT_ASC,
'id' => SORT_DESC,
]
]
]);
return $this->render('/article/index', [
'dataProvider' => $dataProvider,
'type' => yii::t('cms', 'Search keyword {keyword} results', ['keyword'=>$keyword]),
]);
} | php | public function actionIndex()
{
$where = ['type' => Article::ARTICLE];
$query = Article::find()->select([])->where($where);
$keyword = htmlspecialchars(yii::$app->getRequest()->get('q'));
$query->andFilterWhere(['like', 'title', $keyword]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'sort' => SORT_ASC,
'id' => SORT_DESC,
]
]
]);
return $this->render('/article/index', [
'dataProvider' => $dataProvider,
'type' => yii::t('cms', 'Search keyword {keyword} results', ['keyword'=>$keyword]),
]);
} | 搜索
@return string | https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/frontend/controllers/SearchController.php#L25-L44 |
phPoirot/Loader | fixes/LoaderAggregate.php | LoaderAggregate.resolve | function resolve($name)
{
$resolve = false;
/** @var iLoader $loader */
foreach(clone $this->_t_loader_aggregate_getQueue() as $loader) {
$resolve = call_user_func_array(array($loader, 'resolve'), func_get_args());
if ($resolve)
break;
}
return $resolve;
} | php | function resolve($name)
{
$resolve = false;
/** @var iLoader $loader */
foreach(clone $this->_t_loader_aggregate_getQueue() as $loader) {
$resolve = call_user_func_array(array($loader, 'resolve'), func_get_args());
if ($resolve)
break;
}
return $resolve;
} | Resolve To Resource
@param string $name
@return mixed | https://github.com/phPoirot/Loader/blob/c645a56bbb81aac99271e077652f6f53f58c0675/fixes/LoaderAggregate.php#L46-L57 |
phPoirot/Loader | fixes/LoaderAggregate.php | LoaderAggregate.attach | function attach(iLoader $loader, $priority = 0)
{
$this->_t_loader_aggregate_getQueue()->insert($loader, $priority);
$loaderClass = get_class($loader);
$loaderClass = $this->_normalizeLoaderName($loaderClass);
$this->_t_loader_aggregate_Names[$loaderClass] = $loader;
return $this;
} | php | function attach(iLoader $loader, $priority = 0)
{
$this->_t_loader_aggregate_getQueue()->insert($loader, $priority);
$loaderClass = get_class($loader);
$loaderClass = $this->_normalizeLoaderName($loaderClass);
$this->_t_loader_aggregate_Names[$loaderClass] = $loader;
return $this;
} | Attach (insert) Loader
- it will store loader can retrieved by ClassName
@param iLoader $loader
@param int $priority
@return $this | https://github.com/phPoirot/Loader/blob/c645a56bbb81aac99271e077652f6f53f58c0675/fixes/LoaderAggregate.php#L69-L78 |
phPoirot/Loader | fixes/LoaderAggregate.php | LoaderAggregate.loader | function loader($loaderName)
{
$loaderName = $this->_normalizeLoaderName($loaderName);
if (!$this->hasAttached($loaderName))
throw new \Exception(sprintf(
'Loader with name (%s) has not attached.'
, $loaderName
));
return $this->_t_loader_aggregate_Names[$loaderName];
} | php | function loader($loaderName)
{
$loaderName = $this->_normalizeLoaderName($loaderName);
if (!$this->hasAttached($loaderName))
throw new \Exception(sprintf(
'Loader with name (%s) has not attached.'
, $loaderName
));
return $this->_t_loader_aggregate_Names[$loaderName];
} | Get Loader By Name
[code:]
$aggregateLoader->loader(\Poirot\Loader\Autoloader\LoaderAutoloadNamespace::class)
->with([..options])
[code]
@param string $loaderName Loader Name, default is class name
@throws \Exception Loader class not found
@return iLoader | https://github.com/phPoirot/Loader/blob/c645a56bbb81aac99271e077652f6f53f58c0675/fixes/LoaderAggregate.php#L93-L104 |
phPoirot/Loader | fixes/LoaderAggregate.php | LoaderAggregate.hasAttached | function hasAttached($loaderName)
{
$loaderName = $this->_normalizeLoaderName($loaderName);
return in_array($loaderName, $this->listAttached());
} | php | function hasAttached($loaderName)
{
$loaderName = $this->_normalizeLoaderName($loaderName);
return in_array($loaderName, $this->listAttached());
} | Has Loader With This Name Attached?
[code:]
$aggregateLoader->hasAttached(\Poirot\Loader\Autoloader\LoaderAutoloadNamespace::class)
[code]
@param string $loaderName Loader Name, default is class name
@return bool | https://github.com/phPoirot/Loader/blob/c645a56bbb81aac99271e077652f6f53f58c0675/fixes/LoaderAggregate.php#L117-L121 |
IftekherSunny/Planet-Framework | src/Sun/Security/Encrypter.php | Encrypter.encrypt | public function encrypt($data)
{
$iv = openssl_random_pseudo_bytes($this->getSize());
$value = openssl_encrypt(serialize($data), $this->method, $this->key, 0, $iv);
$mac = $this->hash($iv = base64_encode($iv), $value);
return base64_encode(json_encode(compact('iv', 'value', 'mac')));
} | php | public function encrypt($data)
{
$iv = openssl_random_pseudo_bytes($this->getSize());
$value = openssl_encrypt(serialize($data), $this->method, $this->key, 0, $iv);
$mac = $this->hash($iv = base64_encode($iv), $value);
return base64_encode(json_encode(compact('iv', 'value', 'mac')));
} | To encrypt data
@param $data
@return string | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Security/Encrypter.php#L63-L72 |
IftekherSunny/Planet-Framework | src/Sun/Security/Encrypter.php | Encrypter.decrypt | public function decrypt($data)
{
$json = base64_decode($data);
$data = json_decode($json);
// check mac
if ($this->hashCheck($data->iv, $data->value, $data->mac)) {
$iv = base64_decode($data->iv);
$data = openssl_decrypt($data->value, $this->method, $this->key, 0, $iv);
return unserialize($data);
}
throw new Exception('Mac not match.');
} | php | public function decrypt($data)
{
$json = base64_decode($data);
$data = json_decode($json);
// check mac
if ($this->hashCheck($data->iv, $data->value, $data->mac)) {
$iv = base64_decode($data->iv);
$data = openssl_decrypt($data->value, $this->method, $this->key, 0, $iv);
return unserialize($data);
}
throw new Exception('Mac not match.');
} | To decrypt data
@param $data
@return mixed|string
@throws Exception | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Security/Encrypter.php#L82-L99 |
IftekherSunny/Planet-Framework | src/Sun/Security/Encrypter.php | Encrypter.hashCheck | protected function hashCheck($iv, $value, $mac)
{
$salt = Str::random($this->keySize);
$mainMac = hash_hmac('sha256', $this->hash($iv, $value), $salt);
$checkMac = hash_hmac('sha256', $mac, $salt);
if ($mainMac === $checkMac) {
return true;
}
return false;
} | php | protected function hashCheck($iv, $value, $mac)
{
$salt = Str::random($this->keySize);
$mainMac = hash_hmac('sha256', $this->hash($iv, $value), $salt);
$checkMac = hash_hmac('sha256', $mac, $salt);
if ($mainMac === $checkMac) {
return true;
}
return false;
} | To check mac
@param $iv
@param $value
@param $mac
@return bool | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Security/Encrypter.php#L110-L123 |
smartboxgroup/camel-config-bundle | ProcessorDefinitions/TryCatchDefinition.php | TryCatchDefinition.buildProcessor | public function buildProcessor($configNode, $id)
{
// Build pipeline
$pipeline = $this->builder->getBasicDefinition($this->pipelineClass);
// Build try/catch
$innerId = $id.self::INNER_SUFFIX;
$tryCatch = parent::buildProcessor($configNode, $innerId);
// Build Pipeline itinerary with try/catch as first node
$itineraryName = $this->getBuilder()->generateNextUniqueReproducibleIdForContext($id);
$mainItinerary = $this->builder->buildItinerary($itineraryName);
$pipeline->addMethodCall('setItinerary', [$mainItinerary]);
$this->builder->addProcessorDefinitionToItinerary($mainItinerary, $tryCatch, $innerId);
// Configure try/catch and pipeline
foreach ($configNode as $nodeName => $nodeValue) {
switch ($nodeName) {
case self::DESCRIPTION:
$tryCatch->addMethodCall('setDescription', [(string) $nodeValue]);
break;
case self::CATCH_CLAUSE:
$clauseParams = $this->buildCatchClauseParams($nodeValue, $id);
$tryCatch->addMethodCall('addCatch', $clauseParams);
break;
case self::FINALLY_CLAUSE:
$mainItinerary = $this->buildFinallyItineray($nodeValue, $id);
$tryCatch->addMethodCall('setFinallyItinerary', [$mainItinerary]);
break;
default:
$this->builder->addNodeToItinerary($mainItinerary, $nodeName, $nodeValue);
break;
}
}
// Return the pipeline
return $pipeline;
} | php | public function buildProcessor($configNode, $id)
{
// Build pipeline
$pipeline = $this->builder->getBasicDefinition($this->pipelineClass);
// Build try/catch
$innerId = $id.self::INNER_SUFFIX;
$tryCatch = parent::buildProcessor($configNode, $innerId);
// Build Pipeline itinerary with try/catch as first node
$itineraryName = $this->getBuilder()->generateNextUniqueReproducibleIdForContext($id);
$mainItinerary = $this->builder->buildItinerary($itineraryName);
$pipeline->addMethodCall('setItinerary', [$mainItinerary]);
$this->builder->addProcessorDefinitionToItinerary($mainItinerary, $tryCatch, $innerId);
// Configure try/catch and pipeline
foreach ($configNode as $nodeName => $nodeValue) {
switch ($nodeName) {
case self::DESCRIPTION:
$tryCatch->addMethodCall('setDescription', [(string) $nodeValue]);
break;
case self::CATCH_CLAUSE:
$clauseParams = $this->buildCatchClauseParams($nodeValue, $id);
$tryCatch->addMethodCall('addCatch', $clauseParams);
break;
case self::FINALLY_CLAUSE:
$mainItinerary = $this->buildFinallyItineray($nodeValue, $id);
$tryCatch->addMethodCall('setFinallyItinerary', [$mainItinerary]);
break;
default:
$this->builder->addNodeToItinerary($mainItinerary, $nodeName, $nodeValue);
break;
}
}
// Return the pipeline
return $pipeline;
} | {@inheritdoc} | https://github.com/smartboxgroup/camel-config-bundle/blob/f38505c50a446707b8e8f79ecaa1addd0a6cca11/ProcessorDefinitions/TryCatchDefinition.php#L39-L76 |
chadicus/coding-standard | Chadicus/Sniffs/Commenting/FunctionCommentSniff.php | Chadicus_Sniffs_Commenting_FunctionCommentSniff.process | public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$methodProperties = $phpcsFile->getMethodProperties($stackPtr);
if ($methodProperties['scope'] !== 'public') {
return;
}
parent::process($phpcsFile, $stackPtr);
} | php | public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$methodProperties = $phpcsFile->getMethodProperties($stackPtr);
if ($methodProperties['scope'] !== 'public') {
return;
}
parent::process($phpcsFile, $stackPtr);
} | Ensures only public methods are processed.
@param PHP_CodeSniffer_File $phpcsFile The file being scanned.
@param int $stackPtr The position of the current token in the stack passed in $tokens.
@return void | https://github.com/chadicus/coding-standard/blob/e877151eed0c300e4e33e00308470e3873aa04ea/Chadicus/Sniffs/Commenting/FunctionCommentSniff.php#L27-L35 |
chadicus/coding-standard | Chadicus/Sniffs/Commenting/FunctionCommentSniff.php | Chadicus_Sniffs_Commenting_FunctionCommentSniff.processReturn | protected function processReturn(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart)
{
$tokens = $phpcsFile->getTokens();
// Skip constructor and destructor.
$methodName = $phpcsFile->getDeclarationName($stackPtr);
$isSpecialMethod = ($methodName === '__construct' || $methodName === '__destruct');
$return = null;
foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
if ($tokens[$tag]['content'] === '@return') {
if ($return !== null) {
$error = 'Only 1 @return tag is allowed in a function comment';
$phpcsFile->addError($error, $tag, 'DuplicateReturn');
return;
}
$return = $tag;
}
}
if ($isSpecialMethod === true) {
return;
}
if ($return !== null) {
$content = $tokens[($return + 2)]['content'];
if (empty($content) === true || $tokens[($return + 2)]['code'] !== T_DOC_COMMENT_STRING) {
$error = 'Return type missing for @return tag in function comment';
$phpcsFile->addError($error, $return, 'MissingReturnType');
} else {
// Support both a return type and a description.
$split = preg_match('`^((?:\|?(?:array\([^\)]*\)|[\\\\a-z0-9\[\]]+))*)( .*)?`i', $content, $returnParts);
if (isset($returnParts[1]) === false) {
return;
}
$returnType = $returnParts[1];
// Check return type (can be multiple, separated by '|').
$typeNames = explode('|', $returnType);
$suggestedNames = array();
foreach ($typeNames as $i => $typeName) {
$suggestedName = self::suggestType($typeName);
if (in_array($suggestedName, $suggestedNames) === false) {
$suggestedNames[] = $suggestedName;
}
}
$suggestedType = implode('|', $suggestedNames);
if ($returnType !== $suggestedType) {
$error = 'Expected "%s" but found "%s" for function return type';
$data = array(
$suggestedType,
$returnType,
);
$fix = $phpcsFile->addFixableError($error, $return, 'InvalidReturn', $data);
if ($fix === true) {
$replacement = $suggestedType;
if (empty($returnParts[2]) === false) {
$replacement .= $returnParts[2];
}
$phpcsFile->fixer->replaceToken(($return + 2), $replacement);
unset($replacement);
}
}
// If the return type is void, make sure there is
// no return statement in the function.
if ($returnType === 'void') {
if (!$this->isReturnVoid($phpcsFile, $tokens, $stackPtr)) {
$error = 'Function return type is void, but function contains return statement';
$phpcsFile->addError($error, $return, 'InvalidReturnVoid');
}//end if
} else if ($returnType !== 'mixed' && in_array('void', $typeNames, true) === false) {
// If return type is not void, there needs to be a return statement
// somewhere in the function that returns something.
if (isset($tokens[$stackPtr]['scope_closer']) === true) {
$endToken = $tokens[$stackPtr]['scope_closer'];
$returnToken = $phpcsFile->findNext(array(T_RETURN, T_YIELD, T_YIELD_FROM), $stackPtr, $endToken);
if ($returnToken === false) {
$error = 'Function return type is not void, but function has no return statement';
$phpcsFile->addError($error, $return, 'InvalidNoReturn');
} else {
$semicolon = $phpcsFile->findNext(T_WHITESPACE, ($returnToken + 1), null, true);
if ($tokens[$semicolon]['code'] === T_SEMICOLON) {
$error = 'Function return type is not void, but function is returning void here';
$phpcsFile->addError($error, $returnToken, 'InvalidReturnNotVoid');
}
}
}
}//end if
}//end if
} else {
if (!$this->isReturnVoid($phpcsFile, $tokens, $stackPtr)) {
$error = 'Missing @return tag in function comment';
$phpcsFile->addError($error, $tokens[$commentStart]['comment_closer'], 'MissingReturn');
}
}//end if
} | php | protected function processReturn(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart)
{
$tokens = $phpcsFile->getTokens();
// Skip constructor and destructor.
$methodName = $phpcsFile->getDeclarationName($stackPtr);
$isSpecialMethod = ($methodName === '__construct' || $methodName === '__destruct');
$return = null;
foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
if ($tokens[$tag]['content'] === '@return') {
if ($return !== null) {
$error = 'Only 1 @return tag is allowed in a function comment';
$phpcsFile->addError($error, $tag, 'DuplicateReturn');
return;
}
$return = $tag;
}
}
if ($isSpecialMethod === true) {
return;
}
if ($return !== null) {
$content = $tokens[($return + 2)]['content'];
if (empty($content) === true || $tokens[($return + 2)]['code'] !== T_DOC_COMMENT_STRING) {
$error = 'Return type missing for @return tag in function comment';
$phpcsFile->addError($error, $return, 'MissingReturnType');
} else {
// Support both a return type and a description.
$split = preg_match('`^((?:\|?(?:array\([^\)]*\)|[\\\\a-z0-9\[\]]+))*)( .*)?`i', $content, $returnParts);
if (isset($returnParts[1]) === false) {
return;
}
$returnType = $returnParts[1];
// Check return type (can be multiple, separated by '|').
$typeNames = explode('|', $returnType);
$suggestedNames = array();
foreach ($typeNames as $i => $typeName) {
$suggestedName = self::suggestType($typeName);
if (in_array($suggestedName, $suggestedNames) === false) {
$suggestedNames[] = $suggestedName;
}
}
$suggestedType = implode('|', $suggestedNames);
if ($returnType !== $suggestedType) {
$error = 'Expected "%s" but found "%s" for function return type';
$data = array(
$suggestedType,
$returnType,
);
$fix = $phpcsFile->addFixableError($error, $return, 'InvalidReturn', $data);
if ($fix === true) {
$replacement = $suggestedType;
if (empty($returnParts[2]) === false) {
$replacement .= $returnParts[2];
}
$phpcsFile->fixer->replaceToken(($return + 2), $replacement);
unset($replacement);
}
}
// If the return type is void, make sure there is
// no return statement in the function.
if ($returnType === 'void') {
if (!$this->isReturnVoid($phpcsFile, $tokens, $stackPtr)) {
$error = 'Function return type is void, but function contains return statement';
$phpcsFile->addError($error, $return, 'InvalidReturnVoid');
}//end if
} else if ($returnType !== 'mixed' && in_array('void', $typeNames, true) === false) {
// If return type is not void, there needs to be a return statement
// somewhere in the function that returns something.
if (isset($tokens[$stackPtr]['scope_closer']) === true) {
$endToken = $tokens[$stackPtr]['scope_closer'];
$returnToken = $phpcsFile->findNext(array(T_RETURN, T_YIELD, T_YIELD_FROM), $stackPtr, $endToken);
if ($returnToken === false) {
$error = 'Function return type is not void, but function has no return statement';
$phpcsFile->addError($error, $return, 'InvalidNoReturn');
} else {
$semicolon = $phpcsFile->findNext(T_WHITESPACE, ($returnToken + 1), null, true);
if ($tokens[$semicolon]['code'] === T_SEMICOLON) {
$error = 'Function return type is not void, but function is returning void here';
$phpcsFile->addError($error, $returnToken, 'InvalidReturnNotVoid');
}
}
}
}//end if
}//end if
} else {
if (!$this->isReturnVoid($phpcsFile, $tokens, $stackPtr)) {
$error = 'Missing @return tag in function comment';
$phpcsFile->addError($error, $tokens[$commentStart]['comment_closer'], 'MissingReturn');
}
}//end if
} | Process the return comment of this function comment.
@param PHP_CodeSniffer_File $phpcsFile The file being scanned.
@param int $stackPtr The position of the current token
in the stack passed in $tokens.
@param int $commentStart The position in the stack where the comment started.
@return void | https://github.com/chadicus/coding-standard/blob/e877151eed0c300e4e33e00308470e3873aa04ea/Chadicus/Sniffs/Commenting/FunctionCommentSniff.php#L47-L148 |
chadicus/coding-standard | Chadicus/Sniffs/Commenting/FunctionCommentSniff.php | Chadicus_Sniffs_Commenting_FunctionCommentSniff.isReturnVoid | private function isReturnVoid($phpcsFile, $tokens, $stackPtr) : bool
{
if (isset($tokens[$stackPtr]['scope_closer']) !== true) {
return true;
}
$endToken = $tokens[$stackPtr]['scope_closer'];
for ($returnToken = $stackPtr; $returnToken < $endToken; $returnToken++) {
if ($tokens[$returnToken]['code'] === T_CLOSURE
|| $tokens[$returnToken]['code'] === T_ANON_CLASS
) {
$returnToken = $tokens[$returnToken]['scope_closer'];
continue;
}
if ($tokens[$returnToken]['code'] === T_RETURN
|| $tokens[$returnToken]['code'] === T_YIELD
|| $tokens[$returnToken]['code'] === T_YIELD_FROM
) {
break;
}
}
if ($returnToken === $endToken) {
return true;
}
// If the function is not returning anything, just
// exiting, then there is no problem.
$semicolon = $phpcsFile->findNext(T_WHITESPACE, ($returnToken + 1), null, true);
if ($tokens[$semicolon]['code'] !== T_SEMICOLON) {
return false;
}
return true;
} | php | private function isReturnVoid($phpcsFile, $tokens, $stackPtr) : bool
{
if (isset($tokens[$stackPtr]['scope_closer']) !== true) {
return true;
}
$endToken = $tokens[$stackPtr]['scope_closer'];
for ($returnToken = $stackPtr; $returnToken < $endToken; $returnToken++) {
if ($tokens[$returnToken]['code'] === T_CLOSURE
|| $tokens[$returnToken]['code'] === T_ANON_CLASS
) {
$returnToken = $tokens[$returnToken]['scope_closer'];
continue;
}
if ($tokens[$returnToken]['code'] === T_RETURN
|| $tokens[$returnToken]['code'] === T_YIELD
|| $tokens[$returnToken]['code'] === T_YIELD_FROM
) {
break;
}
}
if ($returnToken === $endToken) {
return true;
}
// If the function is not returning anything, just
// exiting, then there is no problem.
$semicolon = $phpcsFile->findNext(T_WHITESPACE, ($returnToken + 1), null, true);
if ($tokens[$semicolon]['code'] !== T_SEMICOLON) {
return false;
}
return true;
} | end processReturn() | https://github.com/chadicus/coding-standard/blob/e877151eed0c300e4e33e00308470e3873aa04ea/Chadicus/Sniffs/Commenting/FunctionCommentSniff.php#L150-L185 |
chadicus/coding-standard | Chadicus/Sniffs/Commenting/FunctionCommentSniff.php | Chadicus_Sniffs_Commenting_FunctionCommentSniff.processThrows | protected function processThrows(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart)
{
$tokens = $phpcsFile->getTokens();
$throws = array();
foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag) {
if ($tokens[$tag]['content'] !== '@throws') {
continue;
}
$exception = null;
$comment = null;
if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) {
$matches = array();
preg_match('/([^\s]+)(?:\s+(.*))?/', $tokens[($tag + 2)]['content'], $matches);
$exception = $matches[1];
if (isset($matches[2]) === true && trim($matches[2]) !== '') {
$comment = $matches[2];
}
}
if ($exception === null) {
$error = 'Exception type and comment missing for @throws tag in function comment';
$phpcsFile->addError($error, $tag, 'InvalidThrows');
} else if ($comment === null) {
$error = 'Comment missing for @throws tag in function comment';
$phpcsFile->addError($error, $tag, 'EmptyThrows');
} else {
// Any strings until the next tag belong to this comment.
if (isset($tokens[$commentStart]['comment_tags'][($pos + 1)]) === true) {
$end = $tokens[$commentStart]['comment_tags'][($pos + 1)];
} else {
$end = $tokens[$commentStart]['comment_closer'];
}
for ($i = ($tag + 3); $i < $end; $i++) {
if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING) {
$comment .= ' '.$tokens[$i]['content'];
}
}
}//end if
}//end foreach
} | php | protected function processThrows(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart)
{
$tokens = $phpcsFile->getTokens();
$throws = array();
foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag) {
if ($tokens[$tag]['content'] !== '@throws') {
continue;
}
$exception = null;
$comment = null;
if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) {
$matches = array();
preg_match('/([^\s]+)(?:\s+(.*))?/', $tokens[($tag + 2)]['content'], $matches);
$exception = $matches[1];
if (isset($matches[2]) === true && trim($matches[2]) !== '') {
$comment = $matches[2];
}
}
if ($exception === null) {
$error = 'Exception type and comment missing for @throws tag in function comment';
$phpcsFile->addError($error, $tag, 'InvalidThrows');
} else if ($comment === null) {
$error = 'Comment missing for @throws tag in function comment';
$phpcsFile->addError($error, $tag, 'EmptyThrows');
} else {
// Any strings until the next tag belong to this comment.
if (isset($tokens[$commentStart]['comment_tags'][($pos + 1)]) === true) {
$end = $tokens[$commentStart]['comment_tags'][($pos + 1)];
} else {
$end = $tokens[$commentStart]['comment_closer'];
}
for ($i = ($tag + 3); $i < $end; $i++) {
if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING) {
$comment .= ' '.$tokens[$i]['content'];
}
}
}//end if
}//end foreach
} | Process any throw tags that this function comment has.
@param PHP_CodeSniffer_File $phpcsFile The file being scanned.
@param int $stackPtr The position of the current token
in the stack passed in $tokens.
@param int $commentStart The position in the stack where the comment started.
@return void | https://github.com/chadicus/coding-standard/blob/e877151eed0c300e4e33e00308470e3873aa04ea/Chadicus/Sniffs/Commenting/FunctionCommentSniff.php#L197-L240 |
chadicus/coding-standard | Chadicus/Sniffs/Commenting/FunctionCommentSniff.php | Chadicus_Sniffs_Commenting_FunctionCommentSniff.checkSpacingAfterParamType | protected function checkSpacingAfterParamType(PHP_CodeSniffer_File $phpcsFile, $param, $maxType, $spacing = 1)
{
// Check number of spaces after the type.
$spaces = ($maxType - strlen($param['type']) + $spacing);
if ($param['type_space'] !== $spaces) {
$error = 'Expected %s spaces after parameter type; %s found';
$data = array(
$spaces,
$param['type_space'],
);
$fix = $phpcsFile->addFixableError($error, $param['tag'], 'SpacingAfterParamType', $data);
if ($fix === true) {
$phpcsFile->fixer->beginChangeset();
$content = $param['type'];
$content .= str_repeat(' ', $spaces);
$content .= $param['var'];
$content .= str_repeat(' ', $param['var_space']);
$content .= $param['commentLines'][0]['comment'];
$phpcsFile->fixer->replaceToken(($param['tag'] + 2), $content);
// Fix up the indent of additional comment lines.
foreach ($param['commentLines'] as $lineNum => $line) {
if ($lineNum === 0
|| $param['commentLines'][$lineNum]['indent'] === 0
) {
continue;
}
$diff = ($param['type_space'] - $spaces);
$newIndent = ($param['commentLines'][$lineNum]['indent'] - $diff);
$phpcsFile->fixer->replaceToken(
($param['commentLines'][$lineNum]['token'] - 1),
str_repeat(' ', $newIndent)
);
}
$phpcsFile->fixer->endChangeset();
}//end if
}//end if
} | php | protected function checkSpacingAfterParamType(PHP_CodeSniffer_File $phpcsFile, $param, $maxType, $spacing = 1)
{
// Check number of spaces after the type.
$spaces = ($maxType - strlen($param['type']) + $spacing);
if ($param['type_space'] !== $spaces) {
$error = 'Expected %s spaces after parameter type; %s found';
$data = array(
$spaces,
$param['type_space'],
);
$fix = $phpcsFile->addFixableError($error, $param['tag'], 'SpacingAfterParamType', $data);
if ($fix === true) {
$phpcsFile->fixer->beginChangeset();
$content = $param['type'];
$content .= str_repeat(' ', $spaces);
$content .= $param['var'];
$content .= str_repeat(' ', $param['var_space']);
$content .= $param['commentLines'][0]['comment'];
$phpcsFile->fixer->replaceToken(($param['tag'] + 2), $content);
// Fix up the indent of additional comment lines.
foreach ($param['commentLines'] as $lineNum => $line) {
if ($lineNum === 0
|| $param['commentLines'][$lineNum]['indent'] === 0
) {
continue;
}
$diff = ($param['type_space'] - $spaces);
$newIndent = ($param['commentLines'][$lineNum]['indent'] - $diff);
$phpcsFile->fixer->replaceToken(
($param['commentLines'][$lineNum]['token'] - 1),
str_repeat(' ', $newIndent)
);
}
$phpcsFile->fixer->endChangeset();
}//end if
}//end if
} | Check the spacing after the type of a parameter.
@param PHP_CodeSniffer_File $phpcsFile The file being scanned.
@param array $param The parameter to be checked.
@param int $maxType The maxlength of the longest parameter type.
@param int $spacing The number of spaces to add after the type.
@return void | https://github.com/chadicus/coding-standard/blob/e877151eed0c300e4e33e00308470e3873aa04ea/Chadicus/Sniffs/Commenting/FunctionCommentSniff.php#L558-L600 |
as3io/modlr | src/DataTypes/Types/BooleanType.php | BooleanType.convertToModlrValue | public function convertToModlrValue($value)
{
if (null === $value) {
return $value;
}
if ('true' === strtolower($value)) {
return true;
}
if ('false' === strtolower($value)) {
return false;
}
return (Boolean) $value;
} | php | public function convertToModlrValue($value)
{
if (null === $value) {
return $value;
}
if ('true' === strtolower($value)) {
return true;
}
if ('false' === strtolower($value)) {
return false;
}
return (Boolean) $value;
} | {@inheritDoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/DataTypes/Types/BooleanType.php#L15-L27 |
martinvium/seine | src/Seine/Writer/OfficeOpenXML2007/SharedStringsHelper.php | SharedStringsHelper.writeString | public function writeString($string)
{
fwrite($this->stream, ' <si><t>' . Utils::escape($string) . '</t></si>' . MyWriter::EOL);
return $this->id++;
} | php | public function writeString($string)
{
fwrite($this->stream, ' <si><t>' . Utils::escape($string) . '</t></si>' . MyWriter::EOL);
return $this->id++;
} | String MUST already be escaped
@param string $string
@return integer id referencing string | https://github.com/martinvium/seine/blob/b361241c88bb73e81c66259f59193b175223c2eb/src/Seine/Writer/OfficeOpenXML2007/SharedStringsHelper.php#L65-L69 |
anklimsk/cakephp-console-installer | Model/InstallerInit.php | InstallerInit.initDbTable | public function initDbTable($table = null) {
if (empty($table)) {
return false;
}
$initModel = ClassRegistry::init(Inflector::classify($table), true);
if ($initModel === false) {
return false;
}
if (!method_exists($initModel, 'initDbTable')) {
return false;
}
$ds = $initModel->getDataSource();
if (!$ds->truncate($initModel)) {
return false;
}
return $initModel->initDbTable();
} | php | public function initDbTable($table = null) {
if (empty($table)) {
return false;
}
$initModel = ClassRegistry::init(Inflector::classify($table), true);
if ($initModel === false) {
return false;
}
if (!method_exists($initModel, 'initDbTable')) {
return false;
}
$ds = $initModel->getDataSource();
if (!$ds->truncate($initModel)) {
return false;
}
return $initModel->initDbTable();
} | Initialization of database table the initial values
@param string $table Database table name for initialization.
Seeking method `initDbTable()` in the appropriate model and call it.
@return bool Result of coll method `initDbTable()` | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerInit.php#L47-L67 |
emaphp/omocha | lib/Omocha.php | Omocha.getAnnotations | public static function getAnnotations(\Reflector $reflector) {
$annotations = (new Parser($reflector->getDocComment()))->parse();
return new AnnotationBag($annotations);
} | php | public static function getAnnotations(\Reflector $reflector) {
$annotations = (new Parser($reflector->getDocComment()))->parse();
return new AnnotationBag($annotations);
} | Retrieve annotations from docblock of a given reflector
@param \Reflector $reflector
@return \Omocha\AnnotationBag | https://github.com/emaphp/omocha/blob/6635b2a7d5feeb7c8627a1a50a871220b1861024/lib/Omocha.php#L10-L13 |
brick/validation | src/Validator/NumberValidator.php | NumberValidator.validate | protected function validate(string $value) : void
{
try {
$value = Decimal::parse($value);
} catch (\InvalidArgumentException $e) {
$this->addFailureMessage('validator.number.invalid');
return;
}
try {
if ($this->min !== null && $value->isLessThan($this->min)) {
$this->addFailureMessage('validator.number.min');
return;
}
if ($this->max !== null && $value->isGreaterThan($this->max)) {
$this->addFailureMessage('validator.number.max');
return;
}
if ($this->step !== null) {
if ($this->min !== null) {
$value = $value->minus($this->min);
}
if (! $value->isDivisibleBy($this->step)) {
$this->addFailureMessage('validator.number.step');
}
}
} catch (\RangeException $e) {
$this->addFailureMessage('validator.number.overflow');
}
} | php | protected function validate(string $value) : void
{
try {
$value = Decimal::parse($value);
} catch (\InvalidArgumentException $e) {
$this->addFailureMessage('validator.number.invalid');
return;
}
try {
if ($this->min !== null && $value->isLessThan($this->min)) {
$this->addFailureMessage('validator.number.min');
return;
}
if ($this->max !== null && $value->isGreaterThan($this->max)) {
$this->addFailureMessage('validator.number.max');
return;
}
if ($this->step !== null) {
if ($this->min !== null) {
$value = $value->minus($this->min);
}
if (! $value->isDivisibleBy($this->step)) {
$this->addFailureMessage('validator.number.step');
}
}
} catch (\RangeException $e) {
$this->addFailureMessage('validator.number.overflow');
}
} | {@inheritdoc} | https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/Validator/NumberValidator.php#L56-L91 |
brick/validation | src/Validator/NumberValidator.php | NumberValidator.setMin | public function setMin(?string $min) : self
{
if ($min !== null) {
$min = Decimal::parse($min);
}
$this->min = $min;
return $this;
} | php | public function setMin(?string $min) : self
{
if ($min !== null) {
$min = Decimal::parse($min);
}
$this->min = $min;
return $this;
} | @param string|null $min The minimum value, or null to remove it.
@return NumberValidator
@throws \InvalidArgumentException If not a valid number. | https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/Validator/NumberValidator.php#L100-L109 |
brick/validation | src/Validator/NumberValidator.php | NumberValidator.setMax | public function setMax(?string $max) : self
{
if ($max !== null) {
$max = Decimal::parse($max);
}
$this->max = $max;
return $this;
} | php | public function setMax(?string $max) : self
{
if ($max !== null) {
$max = Decimal::parse($max);
}
$this->max = $max;
return $this;
} | @param string|null $max The maximum value, or null to remove it.
@return NumberValidator
@throws \InvalidArgumentException If not a valid number. | https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/Validator/NumberValidator.php#L118-L127 |
brick/validation | src/Validator/NumberValidator.php | NumberValidator.setStep | public function setStep(?string $step) : self
{
if ($step !== null) {
$step = Decimal::parse($step);
if ($step->isNegativeOrZero()) {
throw new \InvalidArgumentException('The step must be strictly positive.');
}
}
$this->step = $step;
return $this;
} | php | public function setStep(?string $step) : self
{
if ($step !== null) {
$step = Decimal::parse($step);
if ($step->isNegativeOrZero()) {
throw new \InvalidArgumentException('The step must be strictly positive.');
}
}
$this->step = $step;
return $this;
} | @param string|null $step The step, or null to remove it.
@return NumberValidator
@throws \InvalidArgumentException If not a valid number or not positive. | https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/Validator/NumberValidator.php#L136-L149 |
PhoxPHP/Glider | src/Connection/Domain.php | Domain.matches | public static function matches($providedDomain=null)
{
if (strtolower(php_sapi_name()) == 'cli') {
return true;
}
if (is_string($providedDomain)) {
return $_SERVER['HTTP_HOST'] == $providedDomain;
}
if (is_array($providedDomain)) {
if (in_array($_SERVER['HTTP_HOST'], $providedDomain)) {
return true;
}
}
return false;
} | php | public static function matches($providedDomain=null)
{
if (strtolower(php_sapi_name()) == 'cli') {
return true;
}
if (is_string($providedDomain)) {
return $_SERVER['HTTP_HOST'] == $providedDomain;
}
if (is_array($providedDomain)) {
if (in_array($_SERVER['HTTP_HOST'], $providedDomain)) {
return true;
}
}
return false;
} | Checks if the server host matches provided domain(s). A single
domain (string) or array of domains can be provided.
Note: This does not work when dealing with the cli.
@param $providedDomain <Mixed>
@access public
@static
@return <Boolean> | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Connection/Domain.php#L38-L55 |
fxpio/fxp-doctrine-console | Command/Undelete.php | Undelete.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$id = $input->getArgument($this->adapter->getIdentifierArgument());
$instance = $this->adapter->undelete($id);
$this->showMessage($output, $instance, 'The %s <info>%s</info> was undeleted with successfully');
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$id = $input->getArgument($this->adapter->getIdentifierArgument());
$instance = $this->adapter->undelete($id);
$this->showMessage($output, $instance, 'The %s <info>%s</info> was undeleted with successfully');
} | {@inheritdoc} | https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Command/Undelete.php#L30-L36 |
laasti/warden | src/Repositories/PdoUserRepository.php | PdoUserRepository.getById | public function getById($id)
{
if (is_null($this->byIdStatement)) {
$this->byIdStatement = $this->pdo->prepare('SELECT * FROM '.$this->table.' WHERE '.$this->id.' = :id LIMIT 1');
}
$result = $this->byIdStatement->execute([':id' => $id]);
if ($result) {
$userInfo = $this->byIdStatement->fetch(PDO::FETCH_ASSOC);
return new PdoUser($userInfo);
}
return null;
} | php | public function getById($id)
{
if (is_null($this->byIdStatement)) {
$this->byIdStatement = $this->pdo->prepare('SELECT * FROM '.$this->table.' WHERE '.$this->id.' = :id LIMIT 1');
}
$result = $this->byIdStatement->execute([':id' => $id]);
if ($result) {
$userInfo = $this->byIdStatement->fetch(PDO::FETCH_ASSOC);
return new PdoUser($userInfo);
}
return null;
} | {@inheritdoc} | https://github.com/laasti/warden/blob/97f979e53ddb4e12bc1ca0ead62a45db0ce67ecd/src/Repositories/PdoUserRepository.php#L48-L61 |
laasti/warden | src/Repositories/PdoUserRepository.php | PdoUserRepository.getByIdentifier | public function getByIdentifier($identifier)
{
if (is_null($this->byIdentifierStatement)) {
$this->byIdentifierStatement = $this->pdo->prepare('SELECT * FROM '.$this->table.' WHERE '.$this->identifier.' = :identifier');
}
$result = $this->byIdentifierStatement->execute([':identifier' => $identifier]);
if ($result) {
$userInfo = $this->byIdentifierStatement->fetch(PDO::FETCH_ASSOC);
$userInfo[$this->permissions] = explode(',', $userInfo[$this->permissions]);
$userInfo[$this->roles] = explode(',', $userInfo[$this->roles]);
return new PdoUser($userInfo);
}
return null;
} | php | public function getByIdentifier($identifier)
{
if (is_null($this->byIdentifierStatement)) {
$this->byIdentifierStatement = $this->pdo->prepare('SELECT * FROM '.$this->table.' WHERE '.$this->identifier.' = :identifier');
}
$result = $this->byIdentifierStatement->execute([':identifier' => $identifier]);
if ($result) {
$userInfo = $this->byIdentifierStatement->fetch(PDO::FETCH_ASSOC);
$userInfo[$this->permissions] = explode(',', $userInfo[$this->permissions]);
$userInfo[$this->roles] = explode(',', $userInfo[$this->roles]);
return new PdoUser($userInfo);
}
return null;
} | {@inheritdoc} | https://github.com/laasti/warden/blob/97f979e53ddb4e12bc1ca0ead62a45db0ce67ecd/src/Repositories/PdoUserRepository.php#L66-L81 |
Tuna-CMS/tuna-bundle | src/Tuna/Bundle/FileBundle/Entity/AbstractAttachment.php | AbstractAttachment.setTranslations | public function setTranslations(ArrayCollection $translations)
{
foreach ($translations as $translation) {
$translation->setObject($this);
}
$this->translations = $translations;
} | php | public function setTranslations(ArrayCollection $translations)
{
foreach ($translations as $translation) {
$translation->setObject($this);
}
$this->translations = $translations;
} | Set translations
@param ArrayCollection $translations | https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/FileBundle/Entity/AbstractAttachment.php#L168-L175 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.setOptions | public function setOptions(
int $width,
int $height,
int $quality,
bool $maintain_aspect = true,
array $canvas_color = array('r' => 255, 'g' => 255, 'b' => 255)
) : AbstractResize {
if ($width < 1) {
throw new \InvalidArgumentException(Helper::ERROR_WIDTH_INVALID);
}
if ($height < 1) {
throw new \InvalidArgumentException(Helper::ERROR_HEIGHT_INVALID);
}
if (Helper::colorIndexValid('r', $canvas_color) === false ||
Helper::colorIndexValid('g', $canvas_color) === false ||
Helper::colorIndexValid('b', $canvas_color) === false
) {
throw new \InvalidArgumentException(Helper::ERROR_CANVAS_COLOR_ARRAY_INVALID);
}
$this->canvas['width'] = $width;
$this->canvas['height'] = $height;
$this->canvas['quality'] = $quality;
$this->canvas['color'] = $canvas_color;
$this->intermediate['maintain_aspect'] = $maintain_aspect;
return $this;
} | php | public function setOptions(
int $width,
int $height,
int $quality,
bool $maintain_aspect = true,
array $canvas_color = array('r' => 255, 'g' => 255, 'b' => 255)
) : AbstractResize {
if ($width < 1) {
throw new \InvalidArgumentException(Helper::ERROR_WIDTH_INVALID);
}
if ($height < 1) {
throw new \InvalidArgumentException(Helper::ERROR_HEIGHT_INVALID);
}
if (Helper::colorIndexValid('r', $canvas_color) === false ||
Helper::colorIndexValid('g', $canvas_color) === false ||
Helper::colorIndexValid('b', $canvas_color) === false
) {
throw new \InvalidArgumentException(Helper::ERROR_CANVAS_COLOR_ARRAY_INVALID);
}
$this->canvas['width'] = $width;
$this->canvas['height'] = $height;
$this->canvas['quality'] = $quality;
$this->canvas['color'] = $canvas_color;
$this->intermediate['maintain_aspect'] = $maintain_aspect;
return $this;
} | Set the required options for the image resizer.
@param integer $width Required width for the new image
@param integer $height Required height for the new image
@param integer $quality Quality or compression level for new image, this value depends
on the desired format, the format classes will document the acceptable values
@param boolean $maintain_aspect Maintain aspect ratio of the original image? If set to
true padding will be calculated and added around a best fit re-sampled image, otherwise,
the image will be stretched to fit the desired canvas
@param array $canvas_color Canvas background color, passed in as an rgb array
@return AbstractResize
@throws \InvalidArgumentException If any of the params are invalid we throw an exception | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L70-L99 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.setWidth | public function setWidth(int $width) : AbstractResize
{
if ($width < 1) {
throw new \InvalidArgumentException(Helper::ERROR_WIDTH_INVALID);
}
$this->canvas['width'] = $width;
return $this;
} | php | public function setWidth(int $width) : AbstractResize
{
if ($width < 1) {
throw new \InvalidArgumentException(Helper::ERROR_WIDTH_INVALID);
}
$this->canvas['width'] = $width;
return $this;
} | Set a new width value, useful if you are using the resize class within a loop/iterator
@param int $width
@return AbstractResize
@throws \Exception | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L109-L118 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.setHeight | public function setHeight(int $height) : AbstractResize
{
if ($height < 1) {
throw new \InvalidArgumentException(Helper::ERROR_HEIGHT_INVALID);
}
$this->canvas['height'] = $height;
return $this;
} | php | public function setHeight(int $height) : AbstractResize
{
if ($height < 1) {
throw new \InvalidArgumentException(Helper::ERROR_HEIGHT_INVALID);
}
$this->canvas['height'] = $height;
return $this;
} | Set a new height value, useful if you are using the resize class within a loop/iterator
@param int $height
@return AbstractResize
@throws \Exception | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L128-L137 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.setCanvasColor | public function setCanvasColor(array $canvas_color) : AbstractResize
{
if (Helper::colorIndexValid('r', $canvas_color) === false ||
Helper::colorIndexValid('g', $canvas_color) === false ||
Helper::colorIndexValid('b', $canvas_color) === false
) {
throw new \InvalidArgumentException(Helper::ERROR_CANVAS_COLOR_ARRAY_INVALID);
}
$this->canvas['color'] = $canvas_color;
} | php | public function setCanvasColor(array $canvas_color) : AbstractResize
{
if (Helper::colorIndexValid('r', $canvas_color) === false ||
Helper::colorIndexValid('g', $canvas_color) === false ||
Helper::colorIndexValid('b', $canvas_color) === false
) {
throw new \InvalidArgumentException(Helper::ERROR_CANVAS_COLOR_ARRAY_INVALID);
}
$this->canvas['color'] = $canvas_color;
} | Set a new canvas color
@param array $canvas_color Indexed array, r, g, b for color
@return AbstractResize
@throws \Exception | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L147-L157 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.loadImage | public function loadImage(string $file, string $path = '') : AbstractResize
{
if (file_exists($path . $file) === true) {
$this->source['path'] = $path;
$this->source['file'] = $file;
$this->sourceProperties();
} else {
throw new \Exception("File couldn't be found in supplied destination: '" . $path . $file . "'");
}
// Reset the processed status when a new image is loaded
$this->processed = false;
$this->file = null;
$this->path = null;
return $this;
} | php | public function loadImage(string $file, string $path = '') : AbstractResize
{
if (file_exists($path . $file) === true) {
$this->source['path'] = $path;
$this->source['file'] = $file;
$this->sourceProperties();
} else {
throw new \Exception("File couldn't be found in supplied destination: '" . $path . $file . "'");
}
// Reset the processed status when a new image is loaded
$this->processed = false;
$this->file = null;
$this->path = null;
return $this;
} | Load the image
@param string $file File name and extension
@param string $path Full patch to image
@return AbstractResize
@throws \Exception Throws an exception if the image can't be loaded | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L168-L184 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.sourceProperties | protected function sourceProperties()
{
$properties = Helper::imageProperties($this->source['file'], $this->source['path']);
if ($properties['width'] !== null) {
$this->source['width'] = $properties['width'];
$this->source['height'] = $properties['height'];
$this->source['aspect_ratio'] = $properties['aspect_ratio'];
} else {
throw new \Exception(Helper::ERROR_CALL_GETIMAGESIZE);
}
if ($this->canvas['width'] > $this->source['width'] || $this->canvas['height'] > $this->source['height']) {
throw new \Exception(Helper::ERROR_UPSCALE);
}
} | php | protected function sourceProperties()
{
$properties = Helper::imageProperties($this->source['file'], $this->source['path']);
if ($properties['width'] !== null) {
$this->source['width'] = $properties['width'];
$this->source['height'] = $properties['height'];
$this->source['aspect_ratio'] = $properties['aspect_ratio'];
} else {
throw new \Exception(Helper::ERROR_CALL_GETIMAGESIZE);
}
if ($this->canvas['width'] > $this->source['width'] || $this->canvas['height'] > $this->source['height']) {
throw new \Exception(Helper::ERROR_UPSCALE);
}
} | Fetch the dimensions of the source image and calculate the aspect ratio. We also check
to ensure that the image is being resized down, currently we don't support upscaling the
image
@return void
@throws \Exception | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L194-L209 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.resizeSource | public function resizeSource() : AbstractResize
{
if ($this->intermediate['maintain_aspect'] === true) {
if ($this->source['aspect_ratio'] > 1.00) {
$this->intermediateSizeLandscape();
} else {
if ($this->source['aspect_ratio'] === 1.00) {
$this->intermediateSizeSquare();
} else {
$this->intermediateSizePortrait();
}
}
} else {
$this->intermediate['width'] = $this->canvas['width'];
$this->intermediate['height'] = $this->canvas['height'];
}
$this->canvasSpacingX();
$this->canvasSpacingY();
$this->processed = true;
return $this;
} | php | public function resizeSource() : AbstractResize
{
if ($this->intermediate['maintain_aspect'] === true) {
if ($this->source['aspect_ratio'] > 1.00) {
$this->intermediateSizeLandscape();
} else {
if ($this->source['aspect_ratio'] === 1.00) {
$this->intermediateSizeSquare();
} else {
$this->intermediateSizePortrait();
}
}
} else {
$this->intermediate['width'] = $this->canvas['width'];
$this->intermediate['height'] = $this->canvas['height'];
}
$this->canvasSpacingX();
$this->canvasSpacingY();
$this->processed = true;
return $this;
} | Process the request, generate the size required for the image along with the
canvas spacing
@return AbstractResize
@throws \Exception Throws an exception if unable to create image | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L218-L241 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.intermediateSizeLandscape | protected function intermediateSizeLandscape()
{
// Set width and then calculate height
$this->intermediate['width'] = $this->canvas['width'];
$this->intermediate['height'] = intval(round(
$this->intermediate['width'] / $this->source['aspect_ratio'], 0));
// If height larger than requested, set and calculate new width
if ($this->intermediate['height'] > $this->canvas['height']) {
$this->intermediate['height'] = $this->canvas['height'];
$this->intermediate['width'] = intval(round(
$this->intermediate['height'] * $this->source['aspect_ratio'], 0));
}
} | php | protected function intermediateSizeLandscape()
{
// Set width and then calculate height
$this->intermediate['width'] = $this->canvas['width'];
$this->intermediate['height'] = intval(round(
$this->intermediate['width'] / $this->source['aspect_ratio'], 0));
// If height larger than requested, set and calculate new width
if ($this->intermediate['height'] > $this->canvas['height']) {
$this->intermediate['height'] = $this->canvas['height'];
$this->intermediate['width'] = intval(round(
$this->intermediate['height'] * $this->source['aspect_ratio'], 0));
}
} | The source image is landscape, maintaining aspect ratio calculate the intermediate
image height and width
@return void | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L249-L262 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.intermediateSizeSquare | protected function intermediateSizeSquare()
{
if ($this->canvas['height'] === $this->canvas['width']) {
$this->intermediate['width'] = $this->canvas['width'];
$this->intermediate['height'] = $this->canvas['height'];
} else {
if ($this->canvas['width'] > $this->canvas['height']) {
$this->intermediate['width'] = $this->canvas['height'];
$this->intermediate['height'] = $this->canvas['height'];
} else {
$this->intermediate['height'] = $this->canvas['width'];
$this->intermediate['width'] = $this->canvas['width'];
}
}
} | php | protected function intermediateSizeSquare()
{
if ($this->canvas['height'] === $this->canvas['width']) {
$this->intermediate['width'] = $this->canvas['width'];
$this->intermediate['height'] = $this->canvas['height'];
} else {
if ($this->canvas['width'] > $this->canvas['height']) {
$this->intermediate['width'] = $this->canvas['height'];
$this->intermediate['height'] = $this->canvas['height'];
} else {
$this->intermediate['height'] = $this->canvas['width'];
$this->intermediate['width'] = $this->canvas['width'];
}
}
} | The source image is landscape, fit as appropriate
@return void | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L269-L283 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.intermediateSizePortrait | protected function intermediateSizePortrait()
{
// Set height and then calculate width
$this->intermediate['height'] = $this->canvas['height'];
$this->intermediate['width'] = intval(round(
$this->intermediate['height'] * $this->source['aspect_ratio'], 0));
// If width larger than requested, set and calculate new height
if ($this->intermediate['width'] > $this->canvas['width']) {
$this->intermediate['width'] = $this->canvas['width'];
$this->intermediate['height'] = intval(round(
$this->intermediate['width'] / $this->source['aspect_ratio'], 0));
}
} | php | protected function intermediateSizePortrait()
{
// Set height and then calculate width
$this->intermediate['height'] = $this->canvas['height'];
$this->intermediate['width'] = intval(round(
$this->intermediate['height'] * $this->source['aspect_ratio'], 0));
// If width larger than requested, set and calculate new height
if ($this->intermediate['width'] > $this->canvas['width']) {
$this->intermediate['width'] = $this->canvas['width'];
$this->intermediate['height'] = intval(round(
$this->intermediate['width'] / $this->source['aspect_ratio'], 0));
}
} | The source image is portrait, maintaining aspect ratio calculate the intermediate
image height and width
@return void | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L291-L304 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.canvasSpacingX | protected function canvasSpacingX()
{
$this->canvas['spacing']['x'] = 0;
if ($this->intermediate['width'] < $this->canvas['width']) {
$difference = $this->canvas['width'] - $this->intermediate['width'];
if ($difference % 2 === 0) {
$this->canvas['spacing']['x'] = $difference / 2;
} else {
if ($difference > 1) {
$this->canvas['spacing']['x'] = ($difference - 1) / 2 + 1;
} else {
$this->canvas['spacing']['x'] = 1;
}
}
}
} | php | protected function canvasSpacingX()
{
$this->canvas['spacing']['x'] = 0;
if ($this->intermediate['width'] < $this->canvas['width']) {
$difference = $this->canvas['width'] - $this->intermediate['width'];
if ($difference % 2 === 0) {
$this->canvas['spacing']['x'] = $difference / 2;
} else {
if ($difference > 1) {
$this->canvas['spacing']['x'] = ($difference - 1) / 2 + 1;
} else {
$this->canvas['spacing']['x'] = 1;
}
}
}
} | Calculate any required x canvas spacing, necessary if the intermediate image will be
smaller than the canvas
@return void | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L312-L329 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.canvasSpacingY | protected function canvasSpacingY()
{
$this->canvas['spacing']['y'] = 0;
if ($this->intermediate['height'] < $this->canvas['height']) {
$difference = $this->canvas['height'] - $this->intermediate['height'];
if ($difference % 2 === 0) {
$this->canvas['spacing']['y'] = $difference / 2;
} else {
if ($difference > 1) {
$this->canvas['spacing']['y'] = ($difference - 1) / 2 + 1;
} else {
$this->canvas['spacing']['y'] = 1;
}
}
}
} | php | protected function canvasSpacingY()
{
$this->canvas['spacing']['y'] = 0;
if ($this->intermediate['height'] < $this->canvas['height']) {
$difference = $this->canvas['height'] - $this->intermediate['height'];
if ($difference % 2 === 0) {
$this->canvas['spacing']['y'] = $difference / 2;
} else {
if ($difference > 1) {
$this->canvas['spacing']['y'] = ($difference - 1) / 2 + 1;
} else {
$this->canvas['spacing']['y'] = 1;
}
}
}
} | Calculate any required y canvas spacing, necessary if the intermediate image will be
smaller than the canvas
@return void | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L337-L355 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.getInfo | public function getInfo() : array
{
if ($this->processed === true) {
return [
'canvas' => [
'width' => $this->canvas['width'],
'height' => $this->canvas['height'],
'color' => $this->canvas['color']
],
'resized-image' => [
'width' => $this->intermediate['width'],
'height' => $this->intermediate['height']
],
'canvas-placement' => [
'x' => $this->canvas['spacing']['x'],
'y' => $this->canvas['spacing']['y']
],
'resizer' => [
'maintain-aspect-ratio' => $this->intermediate['maintain_aspect'],
'quality' => $this->canvas['quality']
]
];
} else {
throw new \Exception(Helper::ERROR_CALL_GETINFO);
}
} | php | public function getInfo() : array
{
if ($this->processed === true) {
return [
'canvas' => [
'width' => $this->canvas['width'],
'height' => $this->canvas['height'],
'color' => $this->canvas['color']
],
'resized-image' => [
'width' => $this->intermediate['width'],
'height' => $this->intermediate['height']
],
'canvas-placement' => [
'x' => $this->canvas['spacing']['x'],
'y' => $this->canvas['spacing']['y']
],
'resizer' => [
'maintain-aspect-ratio' => $this->intermediate['maintain_aspect'],
'quality' => $this->canvas['quality']
]
];
} else {
throw new \Exception(Helper::ERROR_CALL_GETINFO);
}
} | Return all the info for the image that will/has be/been created
@return array
@throws \Exception Throws an exception if called before process() | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L378-L403 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.createCanvas | protected function createCanvas()
{
$this->canvas['canvas'] = imagecreatetruecolor($this->canvas['width'], $this->canvas['height']);
if ($this->canvas['canvas'] === false) {
throw new \Exception(Helper::ERROR_CALL_IMAGECREATETRUECOLOR);
}
$fill_color = imagecolorallocate($this->canvas['canvas'], $this->canvas['color']['r'],
$this->canvas['color']['g'], $this->canvas['color']['b']);
if ($fill_color === false) {
throw new \Exception(Helper::ERROR_CALL_IMAGECOLORALLOCATE);
}
if (imagefill($this->canvas['canvas'], 0, 0, $fill_color) === false) {
throw new \Exception(Helper::ERROR_CALL_IMAGEFILL);
};
} | php | protected function createCanvas()
{
$this->canvas['canvas'] = imagecreatetruecolor($this->canvas['width'], $this->canvas['height']);
if ($this->canvas['canvas'] === false) {
throw new \Exception(Helper::ERROR_CALL_IMAGECREATETRUECOLOR);
}
$fill_color = imagecolorallocate($this->canvas['canvas'], $this->canvas['color']['r'],
$this->canvas['color']['g'], $this->canvas['color']['b']);
if ($fill_color === false) {
throw new \Exception(Helper::ERROR_CALL_IMAGECOLORALLOCATE);
}
if (imagefill($this->canvas['canvas'], 0, 0, $fill_color) === false) {
throw new \Exception(Helper::ERROR_CALL_IMAGEFILL);
};
} | Create the canvas and fill with the canvas colour
@throws \Exception | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L410-L426 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.resampleCopy | protected function resampleCopy()
{
$result = imagecopyresampled($this->canvas['canvas'], $this->intermediate['copy'],
$this->canvas['spacing']['x'], $this->canvas['spacing']['y'], 0 ,0,
$this->intermediate['width'], $this->intermediate['height'], $this->source['width'],
$this->source['height']);
if($result === false) {
throw new \Exception(Helper::ERROR_CALL_IMAGECOPYRESAMPLED);
}
} | php | protected function resampleCopy()
{
$result = imagecopyresampled($this->canvas['canvas'], $this->intermediate['copy'],
$this->canvas['spacing']['x'], $this->canvas['spacing']['y'], 0 ,0,
$this->intermediate['width'], $this->intermediate['height'], $this->source['width'],
$this->source['height']);
if($result === false) {
throw new \Exception(Helper::ERROR_CALL_IMAGECOPYRESAMPLED);
}
} | Resample the image copy
@throws \Exception | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L433-L443 |
deanblackborough/random-grab-bag | src/ImageResize/AbstractResize.php | AbstractResize.save | public function save() : AbstractResize
{
if ($this->file === null) {
$this->file = str_replace($this->extension, '-copy' . $this->extension, $this->source['file']);
}
if ($this->path === null) {
$this->path = $this->source['path'];
}
$this->saveFile();
return $this;
} | php | public function save() : AbstractResize
{
if ($this->file === null) {
$this->file = str_replace($this->extension, '-copy' . $this->extension, $this->source['file']);
}
if ($this->path === null) {
$this->path = $this->source['path'];
}
$this->saveFile();
return $this;
} | Save the new image
@return AbstractResize
@throws \Exception Throws an exception if the save fails | https://github.com/deanblackborough/random-grab-bag/blob/b72814a80357d5dbd344b99c3d242678c8cf080f/src/ImageResize/AbstractResize.php#L496-L508 |
foothing/laravel-wrappr | src/Foothing/Wrappr/Installer/Parser.php | Parser.parsePattern | public function parsePattern($pattern) {
$count = 0;
$pattern = preg_replace("/\{(.*?)\}/", "[0-9]+", $pattern, 1, $count);
if ($count > 1) {
throw new \Exception("Pattern cannot contain more than one resource identifiers.");
}
$pattern = preg_replace("/\*.*$/", ".*", $pattern);
$index = $offset = 0;
foreach (explode("/", $pattern) as $chunk) {
if ($chunk == "[0-9]+" && $index == 0) {
throw new \Exception('Resource position in pattern not allowed: ' . $pattern);
} else if ($chunk == "[0-9]+") {
$offset = $index;
break;
}
$index++;
}
return new Route(['pattern' => $pattern, 'resourceOffset' => $offset]);
// Explode it. We are using explode / foreach method instead
// of a plain regex to match resources position.
$chunks = explode("/", $pattern);
// Initialize offset.
$offset = 0;
if (count($chunks) > 1) {
$count = 0;
foreach ($chunks as $key => $token) {
// If token contains parameters in the form of {param},
// we save the corresponding regex pattern. We use $offset
// variable to check that rewritings take place one time only.
if (preg_match("/\{(.*?)\}/", $token) && $offset == 0) {
if ($count == 0) {
throw new \Exception('Resource position in pattern not allowed: ' . $pattern);
}
$chunks[$key] = "[0-9]+";
$offset = $count;
}
// Token is a wildcard: ignore following chunks.
else if($token === '*') {
$chunks[$key] = "\\*";
$chunks = array_slice($chunks, 0, $count+1);
// Break, since wildcard must be the very last token.
break;
}
$count++;
}
$pattern = implode("/", $chunks);
}
return new Route(['pattern' => $pattern, 'resourceOffset' => $offset]);
} | php | public function parsePattern($pattern) {
$count = 0;
$pattern = preg_replace("/\{(.*?)\}/", "[0-9]+", $pattern, 1, $count);
if ($count > 1) {
throw new \Exception("Pattern cannot contain more than one resource identifiers.");
}
$pattern = preg_replace("/\*.*$/", ".*", $pattern);
$index = $offset = 0;
foreach (explode("/", $pattern) as $chunk) {
if ($chunk == "[0-9]+" && $index == 0) {
throw new \Exception('Resource position in pattern not allowed: ' . $pattern);
} else if ($chunk == "[0-9]+") {
$offset = $index;
break;
}
$index++;
}
return new Route(['pattern' => $pattern, 'resourceOffset' => $offset]);
// Explode it. We are using explode / foreach method instead
// of a plain regex to match resources position.
$chunks = explode("/", $pattern);
// Initialize offset.
$offset = 0;
if (count($chunks) > 1) {
$count = 0;
foreach ($chunks as $key => $token) {
// If token contains parameters in the form of {param},
// we save the corresponding regex pattern. We use $offset
// variable to check that rewritings take place one time only.
if (preg_match("/\{(.*?)\}/", $token) && $offset == 0) {
if ($count == 0) {
throw new \Exception('Resource position in pattern not allowed: ' . $pattern);
}
$chunks[$key] = "[0-9]+";
$offset = $count;
}
// Token is a wildcard: ignore following chunks.
else if($token === '*') {
$chunks[$key] = "\\*";
$chunks = array_slice($chunks, 0, $count+1);
// Break, since wildcard must be the very last token.
break;
}
$count++;
}
$pattern = implode("/", $chunks);
}
return new Route(['pattern' => $pattern, 'resourceOffset' => $offset]);
} | Encodes a friendly url pattern to database implementation.
It performs resource identifiers rewrite and wildcards handling,
like the following:
- 'foo' will be encoded in 'foo'
- 'foo/bar' will be encoded in 'foo/bar'
- 'foo/{id}' will be encoded in 'foo/[0-9]+'
- 'foo/{id}/*' will be encoded in 'foo/[0-9]+/' -> regex * will be appended
- 'foo/{id}/* /bar/baz' will be encoded in 'foo/[0-9]+/' -> regex * will be appended
A route pattern can NOT start with a resource identifier.
@param string $pattern
User friendly pattern.
@return Route
@throws \Exception
When route doesn't match a proper format. | https://github.com/foothing/laravel-wrappr/blob/4f6b0181679866b2e42c2e86bdbc1d9fb5d2390b/src/Foothing/Wrappr/Installer/Parser.php#L27-L85 |
foothing/laravel-wrappr | src/Foothing/Wrappr/Installer/Parser.php | Parser.getResourceFromPath | public function getResourceFromPath(Route $route, $path) {
// Explode it.
$chunks = explode("/", $path);
return $route->resourceOffset ? $chunks[$route->resourceOffset ] : null;
} | php | public function getResourceFromPath(Route $route, $path) {
// Explode it.
$chunks = explode("/", $path);
return $route->resourceOffset ? $chunks[$route->resourceOffset ] : null;
} | Extract the resource identifier from the given path.
@param Route $route
@param $path
@return mixed resource identifier | https://github.com/foothing/laravel-wrappr/blob/4f6b0181679866b2e42c2e86bdbc1d9fb5d2390b/src/Foothing/Wrappr/Installer/Parser.php#L95-L99 |
foothing/laravel-wrappr | src/Foothing/Wrappr/Installer/Parser.php | Parser.trimPath | public function trimPath($path) {
// Rewrite leading double slashes.
$path = preg_replace("/^\/\//", "/", $path);
// If there are more double slashes route is invalid.
if (preg_match("/\/{2,}/", $path)) {
throw new \Exception('Route path has invalid format ' . $path);
}
// Trim chars.
return trim($path, " \t\n\r\0\x0B/");
} | php | public function trimPath($path) {
// Rewrite leading double slashes.
$path = preg_replace("/^\/\//", "/", $path);
// If there are more double slashes route is invalid.
if (preg_match("/\/{2,}/", $path)) {
throw new \Exception('Route path has invalid format ' . $path);
}
// Trim chars.
return trim($path, " \t\n\r\0\x0B/");
} | Right and left trim route from blanks and undesired characters.
@param $path
@return string
@throws \Exception | https://github.com/foothing/laravel-wrappr/blob/4f6b0181679866b2e42c2e86bdbc1d9fb5d2390b/src/Foothing/Wrappr/Installer/Parser.php#L109-L120 |
rawcreative/Receiptful | src/Api.php | Api.factory | public static function factory(array $config)
{
if ( ! array_key_exists('apiKey', $config)) {
throw new \Exception('Api factory requires $apiKey parameter.');
}
$client = new Client([
'defaults' => [
'headers' => [
'X-ApiKey' => $config['apiKey'],
],
],
], [], $config);
$description = self::getDescriptionFromConfig($config);
$apiVersion = isset($config['apiVersion']) ? $config['apiVersion'] : 1;
return new self($client, $description, ['defaults' => ['api_version' => $apiVersion]]);
} | php | public static function factory(array $config)
{
if ( ! array_key_exists('apiKey', $config)) {
throw new \Exception('Api factory requires $apiKey parameter.');
}
$client = new Client([
'defaults' => [
'headers' => [
'X-ApiKey' => $config['apiKey'],
],
],
], [], $config);
$description = self::getDescriptionFromConfig($config);
$apiVersion = isset($config['apiVersion']) ? $config['apiVersion'] : 1;
return new self($client, $description, ['defaults' => ['api_version' => $apiVersion]]);
} | Creates and returns an Api client instance
@param array $config
@return Api
@throws \Exception | https://github.com/rawcreative/Receiptful/blob/1075a189a1e0c4ef01fcdfc5cd75c91cc2fb8f14/src/Api.php#L18-L37 |
rawcreative/Receiptful | src/Api.php | Api.getDescriptionFromConfig | private static function getDescriptionFromConfig(array $config)
{
$data = isset($config['descriptionPath']) && is_readable($config['descriptionPath'])
? include $config['descriptionPath']
: include __DIR__ . '/receiptful-api.php';
return new Description($data);
} | php | private static function getDescriptionFromConfig(array $config)
{
$data = isset($config['descriptionPath']) && is_readable($config['descriptionPath'])
? include $config['descriptionPath']
: include __DIR__ . '/receiptful-api.php';
return new Description($data);
} | Loads the api service description
@param array $config
@return Description | https://github.com/rawcreative/Receiptful/blob/1075a189a1e0c4ef01fcdfc5cd75c91cc2fb8f14/src/Api.php#L45-L52 |
rawcreative/Receiptful | src/Api.php | Api.useCoupon | public function useCoupon($id, $reference, $amount, $currency)
{
$command = $this->getCommand('useCoupon', [
'coupon_id' => $id,
'reference' => $reference,
'amount' => $amount,
'currency' => $currency
]);
return $this->execute($command);
} | php | public function useCoupon($id, $reference, $amount, $currency)
{
$command = $this->getCommand('useCoupon', [
'coupon_id' => $id,
'reference' => $reference,
'amount' => $amount,
'currency' => $currency
]);
return $this->execute($command);
} | Mark a coupon as used
TODO maybe pass params as array?
@param string $id
@param string $reference Order reference id
@param number $amount Amount of order
@param string $currency currency of amount
@return array | https://github.com/rawcreative/Receiptful/blob/1075a189a1e0c4ef01fcdfc5cd75c91cc2fb8f14/src/Api.php#L126-L138 |
headzoo/web-tools | src/Headzoo/Web/Tools/Parsers/Headers.php | Headers.parse | public function parse($headers, &$options = null)
{
$methods = HttpMethods::getValues();
$methods = join("|", $methods);
$regex = "~^({$methods})\\b~i";
$parsed = [];
$lines = preg_split("/\\R/", $headers);
foreach($lines as $line) {
if (preg_match($regex, $line)) {
$options = $line;
} else if (preg_match("~^HTTP/~", $line)) {
$options = $line;
} else if (!empty($line)) {
list($name, $value) = preg_split("/:\\S*/", $line, 2);
$name = Utils::normalizeHeaderName($name);
$parsed[$name] = trim($value);
}
}
return $parsed;
} | php | public function parse($headers, &$options = null)
{
$methods = HttpMethods::getValues();
$methods = join("|", $methods);
$regex = "~^({$methods})\\b~i";
$parsed = [];
$lines = preg_split("/\\R/", $headers);
foreach($lines as $line) {
if (preg_match($regex, $line)) {
$options = $line;
} else if (preg_match("~^HTTP/~", $line)) {
$options = $line;
} else if (!empty($line)) {
list($name, $value) = preg_split("/:\\S*/", $line, 2);
$name = Utils::normalizeHeaderName($name);
$parsed[$name] = trim($value);
}
}
return $parsed;
} | {@inheritDoc} | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/Parsers/Headers.php#L15-L36 |
fxpio/fxp-gluon | Block/Extension/AbstractAddonExtension.php | AbstractAddonExtension.buildView | public function buildView(BlockView $view, BlockInterface $form, array $options)
{
$prepend = $options['prepend'];
$append = $options['append'];
$view->vars = array_replace($view->vars, [
'addon_attr' => $options['addon_attr'],
'prepend_attr' => $options['prepend_attr'],
'append_attr' => $options['append_attr'],
'prepend_type' => $this->definedType($prepend, $options['prepend_type']),
'append_type' => $this->definedType($append, $options['append_type']),
]);
// prepend
if (\is_string($prepend)) {
$view->vars['prepend_string'] = $prepend;
} elseif ($prepend instanceof BlockInterface) {
$view->vars['prepend_block'] = $prepend->createView($view);
}
// append
if (\is_string($append)) {
$view->vars['append_string'] = $append;
} elseif ($append instanceof BlockInterface) {
$view->vars['append_block'] = $append->createView($view);
}
} | php | public function buildView(BlockView $view, BlockInterface $form, array $options)
{
$prepend = $options['prepend'];
$append = $options['append'];
$view->vars = array_replace($view->vars, [
'addon_attr' => $options['addon_attr'],
'prepend_attr' => $options['prepend_attr'],
'append_attr' => $options['append_attr'],
'prepend_type' => $this->definedType($prepend, $options['prepend_type']),
'append_type' => $this->definedType($append, $options['append_type']),
]);
// prepend
if (\is_string($prepend)) {
$view->vars['prepend_string'] = $prepend;
} elseif ($prepend instanceof BlockInterface) {
$view->vars['prepend_block'] = $prepend->createView($view);
}
// append
if (\is_string($append)) {
$view->vars['append_string'] = $append;
} elseif ($append instanceof BlockInterface) {
$view->vars['append_block'] = $append->createView($view);
}
} | {@inheritdoc} | https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Extension/AbstractAddonExtension.php#L31-L57 |
fxpio/fxp-gluon | Block/Extension/AbstractAddonExtension.php | AbstractAddonExtension.definedType | protected function definedType($addon, $type)
{
if (\is_string($addon)) {
return null !== $type ? $type : 'addon';
} elseif ($addon instanceof BlockInterface) {
if (null === $type && BlockUtil::isBlockType($addon, ButtonType::class)) {
$type = 'btn';
}
return $type;
}
return 'addon';
} | php | protected function definedType($addon, $type)
{
if (\is_string($addon)) {
return null !== $type ? $type : 'addon';
} elseif ($addon instanceof BlockInterface) {
if (null === $type && BlockUtil::isBlockType($addon, ButtonType::class)) {
$type = 'btn';
}
return $type;
}
return 'addon';
} | @param string|BlockInterface $addon
@param string $type
@return string The addon type | https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Extension/AbstractAddonExtension.php#L94-L107 |
newup/core | src/Console/Commands/Composer/Update.php | Update.handle | public function handle()
{
$wasUpdated = $this->composer->selfUpdate();
if ($wasUpdated) {
$this->info('Composer was updated');
$this->comment($this->composer->getVersion());
} else {
$this->comment('Composer is already up to date');
}
} | php | public function handle()
{
$wasUpdated = $this->composer->selfUpdate();
if ($wasUpdated) {
$this->info('Composer was updated');
$this->comment($this->composer->getVersion());
} else {
$this->comment('Composer is already up to date');
}
} | Execute the console command.
@return mixed | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Console/Commands/Composer/Update.php#L43-L54 |
flipboxfactory/craft-psr16 | src/SimpleCacheAdapter.php | SimpleCacheAdapter.get | public function get($key, $default = null)
{
$key = $this->buildKey($key);
$data = $this->getCache()->get($key);
if ($data === false) {
return $default;
}
if ($data === null) {
return false;
}
return $data;
} | php | public function get($key, $default = null)
{
$key = $this->buildKey($key);
$data = $this->getCache()->get($key);
if ($data === false) {
return $default;
}
if ($data === null) {
return false;
}
return $data;
} | Cache::get() return false if the value is not in the cache or expired, but PSR-16 return $default(null)
@param string $key
@param null $default
@return bool|mixed|null
@throws InvalidArgumentException | https://github.com/flipboxfactory/craft-psr16/blob/25fc4197f5b75adbf299ee023804fdea3afe8f97/src/SimpleCacheAdapter.php#L67-L82 |
diatem-net/jin-social | src/Social/Jasig/CAS/CASSSO.php | CASSSO.configure | public static function configure($host, $port, $serviceId, $context = 'cas', $ssl = true, $debugging = false)
{
self::$host = $host;
self::$port = $port;
self::$context = $context;
self::$ssl = $ssl;
self::$debugging = $debugging;
self::$serviceId = $serviceId;
if (self::$debugging) {
PhpCAS::setDebug();
}
$serviceId = urlencode(self::$serviceId);
PhpCAS::client(CAS_VERSION_2_0, self::$host, self::$port, self::$context);
if (!self::$ssl) {
PhpCAS::setNoCasServerValidation();
}
PhpCAS::setServerLoginURL(static::getBaseUrl().'login?service='.$serviceId);
PhpCAS::setServerServiceValidateURL(static::getBaseUrl().'serviceValidate');
PhpCAS::setServerProxyValidateURL(static::getBaseUrl().'proxyValidate');
PhpCAS::setServerLogoutURL(static::getBaseUrl().'logout?destination='.$serviceId);
self::$initialized = true;
} | php | public static function configure($host, $port, $serviceId, $context = 'cas', $ssl = true, $debugging = false)
{
self::$host = $host;
self::$port = $port;
self::$context = $context;
self::$ssl = $ssl;
self::$debugging = $debugging;
self::$serviceId = $serviceId;
if (self::$debugging) {
PhpCAS::setDebug();
}
$serviceId = urlencode(self::$serviceId);
PhpCAS::client(CAS_VERSION_2_0, self::$host, self::$port, self::$context);
if (!self::$ssl) {
PhpCAS::setNoCasServerValidation();
}
PhpCAS::setServerLoginURL(static::getBaseUrl().'login?service='.$serviceId);
PhpCAS::setServerServiceValidateURL(static::getBaseUrl().'serviceValidate');
PhpCAS::setServerProxyValidateURL(static::getBaseUrl().'proxyValidate');
PhpCAS::setServerLogoutURL(static::getBaseUrl().'logout?destination='.$serviceId);
self::$initialized = true;
} | Configure l'accès au serveur CAS. Nécessaire pour que les méthodes de connexion puissent fonctionner correctement
@param string $host Url du serveur CAS
@param integer $port Port du serveur CAS
@param string $serviceId ID du service (pour CAS)
@param string $context Contexte, ou namespace
@param boolean $ssl (optional) SSL activé (true par défaut)
@param boolean $debugging (optional) Mode debug activé (false par défaut) | https://github.com/diatem-net/jin-social/blob/c49bc8d1b28264ae58e0af9e0452c8d17623e25d/src/Social/Jasig/CAS/CASSSO.php#L38-L64 |
diatem-net/jin-social | src/Social/Jasig/CAS/CASSSO.php | CASSSO.getBaseUrl | protected static function getBaseUrl()
{
$baseUrl = 'https://';
if (!self::$ssl) {
$baseUrl = 'http://';
}
$baseUrl .= sprintf('%s:%s/%s/', self::$host, self::$port, self::$context);
return $baseUrl;
} | php | protected static function getBaseUrl()
{
$baseUrl = 'https://';
if (!self::$ssl) {
$baseUrl = 'http://';
}
$baseUrl .= sprintf('%s:%s/%s/', self::$host, self::$port, self::$context);
return $baseUrl;
} | Construit l'url de connexion au serveur
@return string | https://github.com/diatem-net/jin-social/blob/c49bc8d1b28264ae58e0af9e0452c8d17623e25d/src/Social/Jasig/CAS/CASSSO.php#L149-L157 |
schpill/thin | src/Redisraw.php | Redisraw.db | public static function db($connectionInfos, $name = 'default')
{
if (!isset(static::$databases[$name])) {
extract($connectionInfos);
static::$databases[$name] = new self($host, $port, $database);
}
return static::$databases[$name];
} | php | public static function db($connectionInfos, $name = 'default')
{
if (!isset(static::$databases[$name])) {
extract($connectionInfos);
static::$databases[$name] = new self($host, $port, $database);
}
return static::$databases[$name];
} | Get a Redis database connection instance.
The given name should correspond to a Redis database in the configuration file.
<code>
// Get the default Redis database instance
$redis = Redis::db();
// Get a specified Redis database instance
$reids = Redis::db('redis_2');
</code>
@param string $name
@return Redis | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Redisraw.php#L77-L84 |
schpill/thin | src/Redisraw.php | Redisraw.run | public function run($method, $parameters)
{dieDump($method);
fwrite($this->connect(), $this->command($method, (array) $parameters));
$response = trim(fgets($this->connect()));
return $this->parse($response);
} | php | public function run($method, $parameters)
{dieDump($method);
fwrite($this->connect(), $this->command($method, (array) $parameters));
$response = trim(fgets($this->connect()));
return $this->parse($response);
} | Execute a command against the Redis database.
<code>
// Execute the GET command for the "name" key
$name = Redis::db()->run('get', array('name'));
// Execute the LRANGE command for the "list" key
$list = Redis::db()->run('lrange', array(0, 5));
</code>
@param string $method
@param array $parameters
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Redisraw.php#L101-L106 |
schpill/thin | src/Redisraw.php | Redisraw.parse | protected function parse($response)
{
switch (substr($response, 0, 1)) {
case '-':
throw new Exception('Redis error: ' . substr(trim($response), 4));
case '+':
case ':':
return $this->inline($response);
case '$':
return $this->bulk($response);
case '*':
return $this->multibulk($response);
default:
throw new Exception("Unknown Redis response: " . substr($response, 0, 1));
}
} | php | protected function parse($response)
{
switch (substr($response, 0, 1)) {
case '-':
throw new Exception('Redis error: ' . substr(trim($response), 4));
case '+':
case ':':
return $this->inline($response);
case '$':
return $this->bulk($response);
case '*':
return $this->multibulk($response);
default:
throw new Exception("Unknown Redis response: " . substr($response, 0, 1));
}
} | Parse and return the response from the Redis database.
@param string $response
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Redisraw.php#L114-L133 |
schpill/thin | src/Redisraw.php | Redisraw.connect | protected function connect()
{
if (!is_null($this->connection)) {
return $this->connection;
}
// $this->connection = fsockopen($this->host, $this->port, $error, $message);
$remote_socket = 'tcp://'.$this->host.':' . $this->port;
$this->connection = @stream_socket_client($remote_socket, $errno, $error, 30);
if ($this->connection === false) {
throw new Exception("Error making Redis connection: {$error} - {$message}");
}
// $this->select($this->database);
return $this->connection;
} | php | protected function connect()
{
if (!is_null($this->connection)) {
return $this->connection;
}
// $this->connection = fsockopen($this->host, $this->port, $error, $message);
$remote_socket = 'tcp://'.$this->host.':' . $this->port;
$this->connection = @stream_socket_client($remote_socket, $errno, $error, 30);
if ($this->connection === false) {
throw new Exception("Error making Redis connection: {$error} - {$message}");
}
// $this->select($this->database);
return $this->connection;
} | Establish the connection to the Redis database.
@return resource | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Redisraw.php#L140-L153 |
villermen/runescape-lookup-commons | src/HighScore/SkillHighScore.php | SkillHighScore.getCombatLevel | public function getCombatLevel($includeSummoning = true): int
{
$attackLevel = $this->getSkill(Skill::SKILL_ATTACK) ? $this->getSkill(Skill::SKILL_ATTACK)->getLevel() : 1;
$defenceLevel = $this->getSkill(Skill::SKILL_DEFENCE) ? $this->getSkill(Skill::SKILL_DEFENCE)->getLevel() : 1;
$strengthLevel = $this->getSkill(Skill::SKILL_STRENGTH) ? $this->getSkill(Skill::SKILL_STRENGTH)->getLevel() : 1;
$constitutionLevel = $this->getSkill(Skill::SKILL_CONSTITUTION) ? $this->getSkill(Skill::SKILL_CONSTITUTION)->getLevel() : 10;
$rangedLevel = $this->getSkill(Skill::SKILL_RANGED) ? $this->getSkill(Skill::SKILL_RANGED)->getLevel() : 1;
$prayerLevel = $this->getSkill(Skill::SKILL_PRAYER) ? $this->getSkill(Skill::SKILL_PRAYER)->getLevel() : 1;
$magicLevel = $this->getSkill(Skill::SKILL_MAGIC) ? $this->getSkill(Skill::SKILL_MAGIC)->getLevel() : 1;
$summoningLevel = $includeSummoning && $this->getSkill(Skill::SKILL_SUMMONING) ? $this->getSkill(Skill::SKILL_SUMMONING)->getLevel() : 1;
return (int)((
max($attackLevel + $strengthLevel, $magicLevel * 2, $rangedLevel * 2) * 1.3 +
$defenceLevel + $constitutionLevel + floor($prayerLevel / 2) + floor($summoningLevel / 2)
) / 4);
} | php | public function getCombatLevel($includeSummoning = true): int
{
$attackLevel = $this->getSkill(Skill::SKILL_ATTACK) ? $this->getSkill(Skill::SKILL_ATTACK)->getLevel() : 1;
$defenceLevel = $this->getSkill(Skill::SKILL_DEFENCE) ? $this->getSkill(Skill::SKILL_DEFENCE)->getLevel() : 1;
$strengthLevel = $this->getSkill(Skill::SKILL_STRENGTH) ? $this->getSkill(Skill::SKILL_STRENGTH)->getLevel() : 1;
$constitutionLevel = $this->getSkill(Skill::SKILL_CONSTITUTION) ? $this->getSkill(Skill::SKILL_CONSTITUTION)->getLevel() : 10;
$rangedLevel = $this->getSkill(Skill::SKILL_RANGED) ? $this->getSkill(Skill::SKILL_RANGED)->getLevel() : 1;
$prayerLevel = $this->getSkill(Skill::SKILL_PRAYER) ? $this->getSkill(Skill::SKILL_PRAYER)->getLevel() : 1;
$magicLevel = $this->getSkill(Skill::SKILL_MAGIC) ? $this->getSkill(Skill::SKILL_MAGIC)->getLevel() : 1;
$summoningLevel = $includeSummoning && $this->getSkill(Skill::SKILL_SUMMONING) ? $this->getSkill(Skill::SKILL_SUMMONING)->getLevel() : 1;
return (int)((
max($attackLevel + $strengthLevel, $magicLevel * 2, $rangedLevel * 2) * 1.3 +
$defenceLevel + $constitutionLevel + floor($prayerLevel / 2) + floor($summoningLevel / 2)
) / 4);
} | Returns the combat level of this high score.
@param bool $includeSummoning Whether to include the summoning skill while calculating the combat level.
@return int | https://github.com/villermen/runescape-lookup-commons/blob/3e24dadbdc5e20b755280e5110f4ca0a1758b04c/src/HighScore/SkillHighScore.php#L33-L48 |
chilimatic/chilimatic-framework | lib/file/Image.php | Image.__contruct | public function __contruct($file_name = '')
{
if (empty($file_name)) return;
$this->open($file_name);
$this->imagemagik = new \Imagick($file_name);
} | php | public function __contruct($file_name = '')
{
if (empty($file_name)) return;
$this->open($file_name);
$this->imagemagik = new \Imagick($file_name);
} | constructor
@param string $file_name
@internal param string $filename
@return bool | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/file/Image.php#L30-L38 |
chilimatic/chilimatic-framework | lib/file/Image.php | Image.open | public function open($file_name = '')
{
if (!parent::open($file_name)) return false;
$this->imagemagik = new \Imagick($file_name);
return true;
} | php | public function open($file_name = '')
{
if (!parent::open($file_name)) return false;
$this->imagemagik = new \Imagick($file_name);
return true;
} | (non-PHPdoc)
@see File::open()
@param string $file_name
@return boolean | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/file/Image.php#L50-L57 |
chilimatic/chilimatic-framework | lib/file/Image.php | Image.create_thumbnail | public function create_thumbnail($width = 200, $height = 200, $bestfit = false, $fill = false)
{
if (empty($this->imagemagik) || empty($this->filename)) return false;
try {
$this->imagemagik->thumbnailimage($width, $height, $bestfit, $fill);
} catch (\ImagickException $e) {
throw $e;
}
return true;
} | php | public function create_thumbnail($width = 200, $height = 200, $bestfit = false, $fill = false)
{
if (empty($this->imagemagik) || empty($this->filename)) return false;
try {
$this->imagemagik->thumbnailimage($width, $height, $bestfit, $fill);
} catch (\ImagickException $e) {
throw $e;
}
return true;
} | Wrapper for Imagick thumbnail
@param int $width
@param int $height
@param boolean $bestfit
@param boolean $fill
@throws \Exception
@throws \ImagickException
@return boolean | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/file/Image.php#L72-L83 |
chilimatic/chilimatic-framework | lib/file/Image.php | Image.saveThumb | public function saveThumb($path = '', $filename = '')
{
if (empty($this->filename)) return false;
try {
$save_name = (empty($path) ? $this->path : $path);
$save_name = "$save_name/" . (empty($filename) ? 'th_' . $this->filename : $filename);
$this->imagemagik->writeImage($save_name);
} catch (\ImagickException $e) {
throw $e;
}
return $this->open($save_name);
} | php | public function saveThumb($path = '', $filename = '')
{
if (empty($this->filename)) return false;
try {
$save_name = (empty($path) ? $this->path : $path);
$save_name = "$save_name/" . (empty($filename) ? 'th_' . $this->filename : $filename);
$this->imagemagik->writeImage($save_name);
} catch (\ImagickException $e) {
throw $e;
}
return $this->open($save_name);
} | saves the file and opens the fileinfo for this file
@param string $path
@param string $filename
@throws \Exception
@throws \ImagickException
@return boolean | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/file/Image.php#L96-L109 |
BenGorFile/FileBundle | src/BenGorFile/FileBundle/Controller/OverwriteAction.php | OverwriteAction.overwriteAction | public function overwriteAction($anId, Request $aRequest, FileCommandBus $aCommandBus, $aProperty)
{
if (false === $aRequest->files->has($aProperty)) {
throw new \InvalidArgumentException(sprintf('Given %s property is not in the request', $aProperty));
}
$uploadedFile = $aRequest->files->get($aProperty);
$command = new OverwriteFileCommand(
$anId,
$uploadedFile->getClientOriginalName(),
file_get_contents($uploadedFile->getPathname()),
$uploadedFile->getMimeType()
);
$aCommandBus->handle($command);
$aRequest->files->remove($aProperty);
return [
'id' => $command->id(),
'filename' => $uploadedFile->getClientOriginalName(),
'mime_type' => $uploadedFile->getMimeType(),
];
} | php | public function overwriteAction($anId, Request $aRequest, FileCommandBus $aCommandBus, $aProperty)
{
if (false === $aRequest->files->has($aProperty)) {
throw new \InvalidArgumentException(sprintf('Given %s property is not in the request', $aProperty));
}
$uploadedFile = $aRequest->files->get($aProperty);
$command = new OverwriteFileCommand(
$anId,
$uploadedFile->getClientOriginalName(),
file_get_contents($uploadedFile->getPathname()),
$uploadedFile->getMimeType()
);
$aCommandBus->handle($command);
$aRequest->files->remove($aProperty);
return [
'id' => $command->id(),
'filename' => $uploadedFile->getClientOriginalName(),
'mime_type' => $uploadedFile->getMimeType(),
];
} | Overwrite action.
@param string $anId The file id
@param Request $aRequest The request
@param FileCommandBus $aCommandBus The command bus
@param string $aProperty The file property that want to get from request
@return array | https://github.com/BenGorFile/FileBundle/blob/82c1fa952e7e7b7a188141a34053ab612b699a21/src/BenGorFile/FileBundle/Controller/OverwriteAction.php#L36-L58 |
phPoirot/Stream | Wrapper/WrapperPsrToPhpResource.php | WrapperPsrToPhpResource.convertToResource | static function convertToResource(StreamInterface $stream)
{
# register wrapper if not
$self = new self;
if(!RegistryOfWrapperStream::isRegistered($self->getLabel()))
RegistryOfWrapperStream::register($self);
# make resource
$mode = new AccessMode();
(!$stream->isWritable()) ?: $mode->openForWrite();
(!$stream->isReadable()) ?: $mode->openForRead();
$label = $self->getLabel();
$context = new ContextStreamBase( $label, array('stream' => $stream) );
$context = $context->toContext();
$resource = fopen($label.'://stream'
, (string) $mode
, null
## set options to wrapper
, $context
);
return $resource;
} | php | static function convertToResource(StreamInterface $stream)
{
# register wrapper if not
$self = new self;
if(!RegistryOfWrapperStream::isRegistered($self->getLabel()))
RegistryOfWrapperStream::register($self);
# make resource
$mode = new AccessMode();
(!$stream->isWritable()) ?: $mode->openForWrite();
(!$stream->isReadable()) ?: $mode->openForRead();
$label = $self->getLabel();
$context = new ContextStreamBase( $label, array('stream' => $stream) );
$context = $context->toContext();
$resource = fopen($label.'://stream'
, (string) $mode
, null
## set options to wrapper
, $context
);
return $resource;
} | Convert StreamInterface To PHP resource
@param StreamInterface $stream
@return resource | https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Wrapper/WrapperPsrToPhpResource.php#L47-L71 |
phPoirot/Stream | Wrapper/WrapperPsrToPhpResource.php | WrapperPsrToPhpResource.stream_open | public function stream_open($path, $mode, $options, &$opened_path)
{
$stream = $this->optsData()->getStream();
if (!$stream || !$stream instanceof StreamInterface)
return false;
$this->_w__mode = $mode;
$this->_w__stream = $stream;
return true;
} | php | public function stream_open($path, $mode, $options, &$opened_path)
{
$stream = $this->optsData()->getStream();
if (!$stream || !$stream instanceof StreamInterface)
return false;
$this->_w__mode = $mode;
$this->_w__stream = $stream;
return true;
} | Implement Wrapper: | https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Wrapper/WrapperPsrToPhpResource.php#L76-L86 |
antaresproject/search | src/Http/Breadcrumb/Breadcrumb.php | Breadcrumb.onIndex | public function onIndex()
{
Breadcrumbs::register('search', function($breadcrumbs) {
$query = e(request()->get('search'));
$breadcrumbs->push(trans('antares/search::messages.breadcrumb_search', ['query' => $query]), '#');
});
view()->share('breadcrumbs', Breadcrumbs::render('search'));
} | php | public function onIndex()
{
Breadcrumbs::register('search', function($breadcrumbs) {
$query = e(request()->get('search'));
$breadcrumbs->push(trans('antares/search::messages.breadcrumb_search', ['query' => $query]), '#');
});
view()->share('breadcrumbs', Breadcrumbs::render('search'));
} | on search | https://github.com/antaresproject/search/blob/3bcb994e69c03792d20dfa688a3281f80cd8dde8/src/Http/Breadcrumb/Breadcrumb.php#L31-L38 |
diasbruno/stc | lib/stc/DataLoader.php | DataLoader.read_file | private function read_file($file)
{
$handler = fopen($file, "r");
$file_content = fread($handler, filesize($file));
fclose($handler);
return $file_content;
} | php | private function read_file($file)
{
$handler = fopen($file, "r");
$file_content = fread($handler, filesize($file));
fclose($handler);
return $file_content;
} | Creates the handler and reads the files.
@param $file string | The filename.
@return string | https://github.com/diasbruno/stc/blob/43f62c3b28167bff76274f954e235413a9e9c707/lib/stc/DataLoader.php#L21-L28 |
diasbruno/stc | lib/stc/DataLoader.php | DataLoader.load | public function load($path, $file)
{
$the_file = $path . '/' . $file;
return json_decode($this->read_file($the_file), true);
} | php | public function load($path, $file)
{
$the_file = $path . '/' . $file;
return json_decode($this->read_file($the_file), true);
} | Load the file.
@param $path string | The path where the file is located.
@param $file string | The filename.
@return string | https://github.com/diasbruno/stc/blob/43f62c3b28167bff76274f954e235413a9e9c707/lib/stc/DataLoader.php#L36-L41 |
brainexe/core | src/DependencyInjection/CompilerPass/EventListenerCompilerPass.php | EventListenerCompilerPass.process | public function process(ContainerBuilder $container)
{
$this->container = $container;
$dispatcher = $container->findDefinition('EventDispatcher');
$services = $container->findTaggedServiceIds(self::TAG);
foreach (array_keys($services) as $serviceId) {
/** @var EventSubscriberInterface $class */
$class = $container->findDefinition($serviceId)->getClass();
if (method_exists($class, 'getSubscribedEvents')) {
foreach ($class::getSubscribedEvents() as $eventName => $params) {
$this->addEvent($dispatcher, $params, $eventName, $serviceId);
}
}
}
$this->processMethods($container, $dispatcher);
} | php | public function process(ContainerBuilder $container)
{
$this->container = $container;
$dispatcher = $container->findDefinition('EventDispatcher');
$services = $container->findTaggedServiceIds(self::TAG);
foreach (array_keys($services) as $serviceId) {
/** @var EventSubscriberInterface $class */
$class = $container->findDefinition($serviceId)->getClass();
if (method_exists($class, 'getSubscribedEvents')) {
foreach ($class::getSubscribedEvents() as $eventName => $params) {
$this->addEvent($dispatcher, $params, $eventName, $serviceId);
}
}
}
$this->processMethods($container, $dispatcher);
} | {@inheritdoc} | https://github.com/brainexe/core/blob/9ef69c6f045306abd20e271572386970db9b3e54/src/DependencyInjection/CompilerPass/EventListenerCompilerPass.php#L31-L48 |
bennybi/yii2-cza-base | models/traits/TreeTrait.php | TreeTrait.initDefaults | public function initDefaults() {
/**
* @var Tree $this
*/
$module = Yii::$app->controller->module;
$iconTypeAttribute = null;
extract($module->dataStructure);
$this->setDefault($iconTypeAttribute, TreeView::ICON_CSS);
foreach (static::$boolAttribs as $attr) {
$val = in_array($attr, static::$falseAttribs) ? false : true;
$this->setDefault($attr, $val);
}
} | php | public function initDefaults() {
/**
* @var Tree $this
*/
$module = Yii::$app->controller->module;
$iconTypeAttribute = null;
extract($module->dataStructure);
$this->setDefault($iconTypeAttribute, TreeView::ICON_CSS);
foreach (static::$boolAttribs as $attr) {
$val = in_array($attr, static::$falseAttribs) ? false : true;
$this->setDefault($attr, $val);
}
} | Initialize default values | https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/models/traits/TreeTrait.php#L146-L158 |
bennybi/yii2-cza-base | models/traits/TreeTrait.php | TreeTrait.activateNode | public function activateNode($currNode = true) {
/**
* @var Tree $this
*/
$this->nodeActivationErrors = [];
$module = Yii::$app->controller->module;
extract($module->treeStructure);
if ($this->isRemovableAll()) {
$children = $this->children()->all();
foreach ($children as $child) {
/**
* @var Tree $child
*/
$child->active = true;
if (!$child->save()) {
/** @noinspection PhpUndefinedFieldInspection */
/** @noinspection PhpUndefinedVariableInspection */
$this->nodeActivationErrors[] = [
'id' => $child->$idAttribute,
'name' => $child->$nameAttribute,
'error' => $child->getFirstErrors(),
];
}
}
}
if ($currNode) {
$this->active = true;
if (!$this->save()) {
/** @noinspection PhpUndefinedFieldInspection */
/** @noinspection PhpUndefinedVariableInspection */
$this->nodeActivationErrors[] = [
'id' => $this->$idAttribute,
'name' => $this->$nameAttribute,
'error' => $this->getFirstErrors(),
];
return false;
}
}
return true;
} | php | public function activateNode($currNode = true) {
/**
* @var Tree $this
*/
$this->nodeActivationErrors = [];
$module = Yii::$app->controller->module;
extract($module->treeStructure);
if ($this->isRemovableAll()) {
$children = $this->children()->all();
foreach ($children as $child) {
/**
* @var Tree $child
*/
$child->active = true;
if (!$child->save()) {
/** @noinspection PhpUndefinedFieldInspection */
/** @noinspection PhpUndefinedVariableInspection */
$this->nodeActivationErrors[] = [
'id' => $child->$idAttribute,
'name' => $child->$nameAttribute,
'error' => $child->getFirstErrors(),
];
}
}
}
if ($currNode) {
$this->active = true;
if (!$this->save()) {
/** @noinspection PhpUndefinedFieldInspection */
/** @noinspection PhpUndefinedVariableInspection */
$this->nodeActivationErrors[] = [
'id' => $this->$idAttribute,
'name' => $this->$nameAttribute,
'error' => $this->getFirstErrors(),
];
return false;
}
}
return true;
} | Activates a node (for undoing a soft deletion scenario)
@param boolean $currNode whether to update the current node value also
@return boolean status of activation | https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/models/traits/TreeTrait.php#L251-L290 |
bennybi/yii2-cza-base | models/traits/TreeTrait.php | TreeTrait.removeNode | public function removeNode($softDelete = true, $currNode = true) {
/**
* @var Tree $this
* @var Tree $child
*/
if ($softDelete) {
$this->nodeRemovalErrors = [];
$module = Yii::$app->controller->module;
extract($module->treeStructure);
extract($module->dataStructure);
if ($this->isRemovableAll()) {
$children = $this->children()->all();
foreach ($children as $child) {
$child->active = false;
if (!$child->save()) {
/** @noinspection PhpUndefinedFieldInspection */
/** @noinspection PhpUndefinedVariableInspection */
$this->nodeRemovalErrors[] = [
'id' => $child->$keyAttribute,
'name' => $child->$nameAttribute,
'error' => $child->getFirstErrors(),
];
}
}
}
if ($currNode) {
$this->active = false;
if (!$this->save()) {
/** @noinspection PhpUndefinedFieldInspection */
/** @noinspection PhpUndefinedVariableInspection */
$this->nodeRemovalErrors[] = [
'id' => $this->$keyAttribute,
'name' => $this->$nameAttribute,
'error' => $this->getFirstErrors(),
];
return false;
}
}
return true;
} else {
return $this->removable_all || $this->isRoot() && $this->children()->count() == 0 ?
$this->deleteWithChildren() : $this->delete();
}
} | php | public function removeNode($softDelete = true, $currNode = true) {
/**
* @var Tree $this
* @var Tree $child
*/
if ($softDelete) {
$this->nodeRemovalErrors = [];
$module = Yii::$app->controller->module;
extract($module->treeStructure);
extract($module->dataStructure);
if ($this->isRemovableAll()) {
$children = $this->children()->all();
foreach ($children as $child) {
$child->active = false;
if (!$child->save()) {
/** @noinspection PhpUndefinedFieldInspection */
/** @noinspection PhpUndefinedVariableInspection */
$this->nodeRemovalErrors[] = [
'id' => $child->$keyAttribute,
'name' => $child->$nameAttribute,
'error' => $child->getFirstErrors(),
];
}
}
}
if ($currNode) {
$this->active = false;
if (!$this->save()) {
/** @noinspection PhpUndefinedFieldInspection */
/** @noinspection PhpUndefinedVariableInspection */
$this->nodeRemovalErrors[] = [
'id' => $this->$keyAttribute,
'name' => $this->$nameAttribute,
'error' => $this->getFirstErrors(),
];
return false;
}
}
return true;
} else {
return $this->removable_all || $this->isRoot() && $this->children()->count() == 0 ?
$this->deleteWithChildren() : $this->delete();
}
} | Removes a node
@param boolean $softDelete whether to soft delete or hard delete
@param boolean $currNode whether to update the current node value also
@return boolean status of activation/inactivation | https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/models/traits/TreeTrait.php#L300-L346 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.