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
comoyi/redis
src/Redis/RedisClient.php
RedisClient.getMasterConfigsBySentinel
protected function getMasterConfigsBySentinel() { $masters = $this->sentinel->getMasters($this->masterName); $config = [ 'host' => $masters[0], 'port' => $masters[1], 'password' => $this->configs['password'], ]; return $config; }
php
protected function getMasterConfigsBySentinel() { $masters = $this->sentinel->getMasters($this->masterName); $config = [ 'host' => $masters[0], 'port' => $masters[1], 'password' => $this->configs['password'], ]; return $config; }
通过sentinel获取master配置
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L147-L155
comoyi/redis
src/Redis/RedisClient.php
RedisClient.getSlaveConfigsBySentinel
protected function getSlaveConfigsBySentinel() { $slaves = $this->sentinel->getSlaves($this->masterName); if(0 === count($slaves)) { // 没有slave则取master return $this->getMasterConfigsBySentinel(); } $random = rand(0, (count($slaves) - 1)); // 随机取一个slave的配置 $config = [ 'host' => $slaves[$random]['ip'], 'port' => $slaves[$random]['port'], 'password' => $this->configs['password'], ]; return $config; }
php
protected function getSlaveConfigsBySentinel() { $slaves = $this->sentinel->getSlaves($this->masterName); if(0 === count($slaves)) { // 没有slave则取master return $this->getMasterConfigsBySentinel(); } $random = rand(0, (count($slaves) - 1)); // 随机取一个slave的配置 $config = [ 'host' => $slaves[$random]['ip'], 'port' => $slaves[$random]['port'], 'password' => $this->configs['password'], ]; return $config; }
通过sentinel获取slave配置
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L160-L172
comoyi/redis
src/Redis/RedisClient.php
RedisClient.getHandler
protected function getHandler($masterOrSlave) { if (!isset($this->pool[$masterOrSlave]) || is_null($this->pool[$masterOrSlave])) { // 创建 switch($masterOrSlave) { case 'master': $redis = new RedisMaster($this->getMasterConfigs()); break; case 'slave': $redis = new RedisSlave($this->getSlaveConfigs()); break; default: throw new Exception('must be master or slave'); } $this->pool[$masterOrSlave] = $redis; $handler = $this->pool[$masterOrSlave]->getHandler(); // 如果当前不在默认库则切换到指定库 if (0 != $this->currentDb) { $res = $handler->select($this->currentDb); if (!$res) { throw new Exception('change selected database failed'); } } } return $this->pool[$masterOrSlave]->getHandler(); }
php
protected function getHandler($masterOrSlave) { if (!isset($this->pool[$masterOrSlave]) || is_null($this->pool[$masterOrSlave])) { // 创建 switch($masterOrSlave) { case 'master': $redis = new RedisMaster($this->getMasterConfigs()); break; case 'slave': $redis = new RedisSlave($this->getSlaveConfigs()); break; default: throw new Exception('must be master or slave'); } $this->pool[$masterOrSlave] = $redis; $handler = $this->pool[$masterOrSlave]->getHandler(); // 如果当前不在默认库则切换到指定库 if (0 != $this->currentDb) { $res = $handler->select($this->currentDb); if (!$res) { throw new Exception('change selected database failed'); } } } return $this->pool[$masterOrSlave]->getHandler(); }
获取连接 @param string $masterOrSlave [master / slave] @return mixed @throws Exception
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L216-L242
comoyi/redis
src/Redis/RedisClient.php
RedisClient.select
public function select($index = 0) { $index = intval($index); if (isset($this->pool['master']) && !is_null($this->pool['master'])) { $res = $this->pool['master']->getHandler()->select($index); if (!$res) { throw new Exception('change selected database failed'); } } if (isset($this->pool['slave']) && !is_null($this->pool['slave'])) { $res = $this->pool['slave']->getHandler()->select($index); if (!$res) { throw new Exception('change selected database failed'); } } // 记录当前redis db $this->currentDb = $index; }
php
public function select($index = 0) { $index = intval($index); if (isset($this->pool['master']) && !is_null($this->pool['master'])) { $res = $this->pool['master']->getHandler()->select($index); if (!$res) { throw new Exception('change selected database failed'); } } if (isset($this->pool['slave']) && !is_null($this->pool['slave'])) { $res = $this->pool['slave']->getHandler()->select($index); if (!$res) { throw new Exception('change selected database failed'); } } // 记录当前redis db $this->currentDb = $index; }
切换database @param int $index db索引 @throws Exception
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L250-L270
comoyi/redis
src/Redis/RedisClient.php
RedisClient.evaluate
public function evaluate ($script, $args, $quantity) { return $this->getHandler($this->judge(__FUNCTION__))->eval($script, $args, $quantity); }
php
public function evaluate ($script, $args, $quantity) { return $this->getHandler($this->judge(__FUNCTION__))->eval($script, $args, $quantity); }
执行lua脚本 eval是PHP关键字PHP7以下不能作为方法名 @param string $script 脚本代码 @param array $args 传给脚本的KEYS, ARGV组成的索引数组(不是key-value对应,是先KEYS再ARGV的索引数组,KEYS, ARGV数量可以不同) 例:['key1', 'key2', 'argv1', 'argv2', 'argv3'] @param int $quantity 传给脚本的KEY数量 @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L282-L284
comoyi/redis
src/Redis/RedisClient.php
RedisClient.evalSha
public function evalSha($scriptSha, $args, $quantity) { return $this->getHandler($this->judge(__FUNCTION__))->evalSha($scriptSha, $args, $quantity); }
php
public function evalSha($scriptSha, $args, $quantity) { return $this->getHandler($this->judge(__FUNCTION__))->evalSha($scriptSha, $args, $quantity); }
根据脚本sha1执行对应lua脚本 Evaluates a script cached on the server side by its SHA1 digest. @param string $scriptSha 脚本代码sha1值 @param array $args 传给脚本的KEYS, ARGV组成的索引数组(不是key-value对应,是先KEYS再ARGV的索引数组,KEYS, ARGV数量可以不同) 例:['key1', 'key2', 'argv1', 'argv2', 'argv3'] @param int $quantity 传给脚本的KEY数量 @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L296-L298
comoyi/redis
src/Redis/RedisClient.php
RedisClient.script
public function script($command, $script) { return $this->getHandler($this->judge(__FUNCTION__))->script($command, $script); }
php
public function script($command, $script) { return $this->getHandler($this->judge(__FUNCTION__))->script($command, $script); }
执行script @param string $command @param string $script @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L307-L309
comoyi/redis
src/Redis/RedisClient.php
RedisClient.set
public function set($key, $value, $opt = null) { return $this->getHandler($this->judge(__FUNCTION__))->set($key, $value, $opt); }
php
public function set($key, $value, $opt = null) { return $this->getHandler($this->judge(__FUNCTION__))->set($key, $value, $opt); }
设置key - value set('key', 'value'); set('key', 'value', ['nx']); set('key', 'value', ['xx']); set('key', 'value', ['ex' => 10]); set('key', 'value', ['px' => 1000]); set('key', 'value', ['nx', 'ex' => 10]); set('key', 'value', ['nx', 'px' => 1000]); set('key', 'value', ['xx', 'ex' => 10]); set('key', 'value', ['xx', 'px' => 1000]); @param string $key key @param string $value value @param array $opt 可选参数 可选参数可以自由组合 nx: key不存在时有效, xx: key存在时有效, ex: ttl[单位:s], px: ttl[单位:ms] @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L349-L351
comoyi/redis
src/Redis/RedisClient.php
RedisClient.setEx
public function setEx($key, $seconds, $value) { return $this->getHandler($this->judge(__FUNCTION__))->setEx($key, $seconds, $value); }
php
public function setEx($key, $seconds, $value) { return $this->getHandler($this->judge(__FUNCTION__))->setEx($key, $seconds, $value); }
设置key - value同时设置剩余有效期 不建议使用 请使用set方式代替 Note: Since the SET command options can replace SETNX, SETEX, PSETEX, it is possible that in future versions of Redis these three commands will be deprecated and finally removed. @param string $key key @param int $seconds 剩余有效期 (单位:s / 秒) @param string $value @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L367-L369
comoyi/redis
src/Redis/RedisClient.php
RedisClient.setNx
public function setNx($key, $value) { return $this->getHandler($this->judge(__FUNCTION__))->setNx($key, $value); }
php
public function setNx($key, $value) { return $this->getHandler($this->judge(__FUNCTION__))->setNx($key, $value); }
设置key - value (仅在当前key不存在时有效) 不建议使用 请使用set方式代替 Note: Since the SET command options can replace SETNX, SETEX, PSETEX, it is possible that in future versions of Redis these three commands will be deprecated and finally removed. @param string $key key @param string $value value @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L384-L386
comoyi/redis
src/Redis/RedisClient.php
RedisClient.expire
public function expire($key, $seconds) { return $this->getHandler($this->judge(__FUNCTION__))->expire($key, $seconds); }
php
public function expire($key, $seconds) { return $this->getHandler($this->judge(__FUNCTION__))->expire($key, $seconds); }
设置生存时长 @param string $key key @param int $seconds 生存时长(单位:秒) @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L395-L397
comoyi/redis
src/Redis/RedisClient.php
RedisClient.pExpire
public function pExpire($key, $milliseconds) { return $this->getHandler($this->judge(__FUNCTION__))->pExpire($key, $milliseconds); }
php
public function pExpire($key, $milliseconds) { return $this->getHandler($this->judge(__FUNCTION__))->pExpire($key, $milliseconds); }
设置生存时长 - 毫秒级 @param string $key @param int $milliseconds 生存时长(单位:毫秒) @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L406-L408
comoyi/redis
src/Redis/RedisClient.php
RedisClient.expireAt
public function expireAt($key, $timestamp) { return $this->getHandler($this->judge(__FUNCTION__))->expireAt($key, $timestamp); }
php
public function expireAt($key, $timestamp) { return $this->getHandler($this->judge(__FUNCTION__))->expireAt($key, $timestamp); }
设置生存截止时间戳 @param string $key key @param int $timestamp 生存截止时间戳 @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L417-L419
comoyi/redis
src/Redis/RedisClient.php
RedisClient.pExpireAt
public function pExpireAt($key, $millisecondsTimestamp) { return $this->getHandler($this->judge(__FUNCTION__))->pExpireAt($key, $millisecondsTimestamp); }
php
public function pExpireAt($key, $millisecondsTimestamp) { return $this->getHandler($this->judge(__FUNCTION__))->pExpireAt($key, $millisecondsTimestamp); }
设置生存截止时间戳 - 毫秒极 @param string $key key @param int $millisecondsTimestamp 生存截止时间戳(单位:毫秒) @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L428-L430
comoyi/redis
src/Redis/RedisClient.php
RedisClient.publish
public function publish($channel, $message) { return $this->getHandler($this->judge(__FUNCTION__))->publish($channel, $message); }
php
public function publish($channel, $message) { return $this->getHandler($this->judge(__FUNCTION__))->publish($channel, $message); }
发布消息到指定频道 @param string $channel 频道 @param string $message 消息内容 @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L468-L470
comoyi/redis
src/Redis/RedisClient.php
RedisClient.incrBy
public function incrBy($key, $increment) { return $this->getHandler($this->judge(__FUNCTION__))->incrBy($key, $increment); }
php
public function incrBy($key, $increment) { return $this->getHandler($this->judge(__FUNCTION__))->incrBy($key, $increment); }
自增 - 增幅为指定值 @param string $key key @param int $increment 增量 @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L489-L491
comoyi/redis
src/Redis/RedisClient.php
RedisClient.decrBy
public function decrBy($key, $decrement) { return $this->getHandler($this->judge(__FUNCTION__))->decrBy($key, $decrement); }
php
public function decrBy($key, $decrement) { return $this->getHandler($this->judge(__FUNCTION__))->decrBy($key, $decrement); }
自减 - 减幅为指定值 @param string $key key @param int $decrement 减量 @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L510-L512
comoyi/redis
src/Redis/RedisClient.php
RedisClient.hGet
public function hGet($key, $field) { return $this->getHandler($this->judge(__FUNCTION__))->hGet($key, $field); }
php
public function hGet($key, $field) { return $this->getHandler($this->judge(__FUNCTION__))->hGet($key, $field); }
获取hash一个指定field的值 @param string $key key @param string $field @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L521-L523
comoyi/redis
src/Redis/RedisClient.php
RedisClient.hSet
public function hSet($key, $field, $value) { return $this->getHandler($this->judge(__FUNCTION__))->hSet($key, $field, $value); }
php
public function hSet($key, $field, $value) { return $this->getHandler($this->judge(__FUNCTION__))->hSet($key, $field, $value); }
设置hash一个field @param string $key key @param string $field @param string $value @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L554-L556
comoyi/redis
src/Redis/RedisClient.php
RedisClient.hExists
public function hExists($key, $field) { return $this->getHandler($this->judge(__FUNCTION__))->hExists($key, $field); }
php
public function hExists($key, $field) { return $this->getHandler($this->judge(__FUNCTION__))->hExists($key, $field); }
hash中是否存在指定field 1 if the hash contains field. 0 if the hash does not contain field, or key does not exist. @param string $key key @param string $field @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L579-L581
comoyi/redis
src/Redis/RedisClient.php
RedisClient.hDel
public function hDel($key, $field) { return $this->getHandler($this->judge(__FUNCTION__))->hDel($key, $field); }
php
public function hDel($key, $field) { return $this->getHandler($this->judge(__FUNCTION__))->hDel($key, $field); }
移除hash中指定field @param string $key key @param string $field @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L601-L603
comoyi/redis
src/Redis/RedisClient.php
RedisClient.lPush
public function lPush($key, $value) { return $this->getHandler($this->judge(__FUNCTION__))->lPush($key, $value); }
php
public function lPush($key, $value) { return $this->getHandler($this->judge(__FUNCTION__))->lPush($key, $value); }
添加到队列头 @param string $key key @param string $value value @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L612-L614
comoyi/redis
src/Redis/RedisClient.php
RedisClient.rPush
public function rPush($key, $value) { return $this->getHandler($this->judge(__FUNCTION__))->rPush($key, $value); }
php
public function rPush($key, $value) { return $this->getHandler($this->judge(__FUNCTION__))->rPush($key, $value); }
添加到队列尾 @param string $key key @param string $value value @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L623-L625
comoyi/redis
src/Redis/RedisClient.php
RedisClient.lRange
public function lRange($key, $start, $stop) { return $this->getHandler($this->judge(__FUNCTION__))->lRange($key, $start, $stop); }
php
public function lRange($key, $start, $stop) { return $this->getHandler($this->judge(__FUNCTION__))->lRange($key, $start, $stop); }
从队列中取出指定范围内的元素 start stop 从0开始 - The offsets start and stop are zero-based indexes, with 0 being the first element of the list These offsets can also be negative numbers indicating offsets starting at the end of the list. For example, -1 is the last element of the list, -2 the penultimate, and so on. @param string $key @param int $start 起始 @param int $stop 截止 @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L658-L660
comoyi/redis
src/Redis/RedisClient.php
RedisClient.lTrim
public function lTrim($key, $start, $stop) { return $this->getHandler($this->judge(__FUNCTION__))->lTrim($key, $start, $stop); }
php
public function lTrim($key, $start, $stop) { return $this->getHandler($this->judge(__FUNCTION__))->lTrim($key, $start, $stop); }
对列表进行修剪 @param string $key @param int $start 起始 @param int $stop 截止 @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L670-L672
comoyi/redis
src/Redis/RedisClient.php
RedisClient.sAdd
public function sAdd($key, $member) { return $this->getHandler($this->judge(__FUNCTION__))->sAdd($key, $member); }
php
public function sAdd($key, $member) { return $this->getHandler($this->judge(__FUNCTION__))->sAdd($key, $member); }
往set集合添加成员 @param string $key key @param string $member 成员 @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L691-L693
comoyi/redis
src/Redis/RedisClient.php
RedisClient.sRem
public function sRem($key, $member) { return $this->getHandler($this->judge(__FUNCTION__))->sRem($key, $member); }
php
public function sRem($key, $member) { return $this->getHandler($this->judge(__FUNCTION__))->sRem($key, $member); }
从集合中移除指定的成员 @param string $key key @param string $member 成员 @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L712-L714
comoyi/redis
src/Redis/RedisClient.php
RedisClient.zAdd
public function zAdd($key, $score, $value) { return $this->getHandler($this->judge(__FUNCTION__))->zAdd($key, $score, $value); }
php
public function zAdd($key, $score, $value) { return $this->getHandler($this->judge(__FUNCTION__))->zAdd($key, $score, $value); }
往有序集合添加成员 @param string $key key @param int $score score @param string $value value @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L724-L726
comoyi/redis
src/Redis/RedisClient.php
RedisClient.zScore
public function zScore($key, $member) { return $this->getHandler($this->judge(__FUNCTION__))->zScore($key, $member); }
php
public function zScore($key, $member) { return $this->getHandler($this->judge(__FUNCTION__))->zScore($key, $member); }
获取有序集合中成员的score @param string $key @param string $member @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L735-L737
comoyi/redis
src/Redis/RedisClient.php
RedisClient.zIncrBy
public function zIncrBy($key, $increment, $value) { return $this->getHandler($this->judge(__FUNCTION__))->zIncrBy($key, $increment, $value); }
php
public function zIncrBy($key, $increment, $value) { return $this->getHandler($this->judge(__FUNCTION__))->zIncrBy($key, $increment, $value); }
增加有序集合score值 @param string $key key @param int $increment 增长的数值 @param string $value value值 @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L747-L749
comoyi/redis
src/Redis/RedisClient.php
RedisClient.zRevRange
public function zRevRange($key, $start, $stop, $isWithScore = false) { return $this->getHandler($this->judge(__FUNCTION__))->zRevRange($key, $start, $stop, $isWithScore); }
php
public function zRevRange($key, $start, $stop, $isWithScore = false) { return $this->getHandler($this->judge(__FUNCTION__))->zRevRange($key, $start, $stop, $isWithScore); }
获取有序集合指定范围内的元素,根据score从高到低 @param string $key @param int $start @param int $stop @param bool $isWithScore @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L773-L775
comoyi/redis
src/Redis/RedisClient.php
RedisClient.zRevRangeByScore
public function zRevRangeByScore($key, $max, $min, $isWithScore = false) { return $this->getHandler($this->judge(__FUNCTION__))->zRevRangeByScore($key, $max, $min, $isWithScore); }
php
public function zRevRangeByScore($key, $max, $min, $isWithScore = false) { return $this->getHandler($this->judge(__FUNCTION__))->zRevRangeByScore($key, $max, $min, $isWithScore); }
获取score在max和min之间的所有元素 @param string $key @param int $max 最大值 @param int $min 最小值 @param bool $isWithScore @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L786-L789
comoyi/redis
src/Redis/RedisClient.php
RedisClient.zRevRank
public function zRevRank($key, $member) { return $this->getHandler($this->judge(__FUNCTION__))->zRevRank($key, $member); }
php
public function zRevRank($key, $member) { return $this->getHandler($this->judge(__FUNCTION__))->zRevRank($key, $member); }
获取member的排名,排名根据score从高到低,排名从0开始 @param string $key @param string $member @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L798-L800
comoyi/redis
src/Redis/RedisClient.php
RedisClient.zRem
public function zRem($key, $member) { return $this->getHandler($this->judge(__FUNCTION__))->zRem($key, $member); }
php
public function zRem($key, $member) { return $this->getHandler($this->judge(__FUNCTION__))->zRem($key, $member); }
从有序集合移除指定的成员 @param string $key key @param string $member 成员 @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L809-L811
comoyi/redis
src/Redis/RedisClient.php
RedisClient.zRemRangeByRank
public function zRemRangeByRank($key, $start, $stop) { return $this->getHandler($this->judge(__FUNCTION__))->zRemRangeByRank($key, $start, $stop); }
php
public function zRemRangeByRank($key, $start, $stop) { return $this->getHandler($this->judge(__FUNCTION__))->zRemRangeByRank($key, $start, $stop); }
从有序集合中移除指定排名范围内的成员 @param string $key key @param int $start 起始排名 (包含) 从0开始 @param int $stop 截止排名 (包含) 从0开始 @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L821-L823
comoyi/redis
src/Redis/RedisClient.php
RedisClient.zRemRangeByScore
public function zRemRangeByScore($key, $min, $max) { return $this->getHandler($this->judge(__FUNCTION__))->zRemRangeByScore($key, $min, $max); }
php
public function zRemRangeByScore($key, $min, $max) { return $this->getHandler($this->judge(__FUNCTION__))->zRemRangeByScore($key, $min, $max); }
从有序集合中移除指定score范围内的成员 @param string $key key @param int $min 起始score (包含) @param int $max 截止score (包含) @return mixed
https://github.com/comoyi/redis/blob/1c9313ce49e17b141dd87b900457b159f554f065/src/Redis/RedisClient.php#L833-L835
METANETAG/formHandler
lib/ch/metanet/formHandler/field/FileField.php
FileField.convertMultiFileArray
protected function convertMultiFileArray(array $filesArr) { $files = array(); $filesCount = count($filesArr[self::VALUE_NAME]); for($i = 0; $i < $filesCount; ++$i) { $files[] = array( self::VALUE_NAME => $filesArr[self::VALUE_NAME][$i], self::VALUE_TYPE => $filesArr[self::VALUE_TYPE][$i], self::VALUE_TMP_NAME => $filesArr[self::VALUE_TMP_NAME][$i], self::VALUE_ERROR => $filesArr[self::VALUE_ERROR][$i], self::VALUE_SIZE => $filesArr[self::VALUE_SIZE][$i], ); } return $files; }
php
protected function convertMultiFileArray(array $filesArr) { $files = array(); $filesCount = count($filesArr[self::VALUE_NAME]); for($i = 0; $i < $filesCount; ++$i) { $files[] = array( self::VALUE_NAME => $filesArr[self::VALUE_NAME][$i], self::VALUE_TYPE => $filesArr[self::VALUE_TYPE][$i], self::VALUE_TMP_NAME => $filesArr[self::VALUE_TMP_NAME][$i], self::VALUE_ERROR => $filesArr[self::VALUE_ERROR][$i], self::VALUE_SIZE => $filesArr[self::VALUE_SIZE][$i], ); } return $files; }
Restructures an input array of multiple files @param array $filesArr @return array
https://github.com/METANETAG/formHandler/blob/4f6e556e54e3a683edd7da0d2f72ed64e6bf1580/lib/ch/metanet/formHandler/field/FileField.php#L178-L194
selikhovleonid/nadir
src/core/AbstractCliCtrl.php
AbstractCliCtrl.printLog
protected function printLog($sMessage) { $oDate = new \DateTime(); echo $oDate->format('H:i:s')."\t{$sMessage}".PHP_EOL; return '('.$oDate->format('H:i:s').') '.preg_replace( '#(\[[0-9]+m)#', '', $sMessage ); }
php
protected function printLog($sMessage) { $oDate = new \DateTime(); echo $oDate->format('H:i:s')."\t{$sMessage}".PHP_EOL; return '('.$oDate->format('H:i:s').') '.preg_replace( '#(\[[0-9]+m)#', '', $sMessage ); }
Print message to console @param string $sMessage Message to print @return string Message with time
https://github.com/selikhovleonid/nadir/blob/47545fccd8516c8f0a20c02ba62f68269c7199da/src/core/AbstractCliCtrl.php#L29-L38
Elephant418/Staq
src/Staq/Core/Data/Stack/Attribute/Relation/OneToMany.php
OneToMany.initBySetting
public function initBySetting($model, $setting) { parent::initBySetting($model, $setting); $this->model = $model; if (is_array($setting)) { if (!isset($setting['remote_class_type'])) { throw new \Stack\Exception\MissingSetting('"remote_class_type" missing for the OneToMany relation.'); } if (!isset($setting['related_attribute_name'])) { throw new \Stack\Exception\MissingSetting('"related_attribute_name" missing for the OneToMany relation.'); } if (isset($setting['filter_list'])) { $this->filterList = $setting['filter_list']; } if (isset($setting['unique_remote'])) { $this->uniqueRemote = !!$setting['unique_remote']; } $this->remoteModelType = $setting['remote_class_type']; $this->relatedAttributeName = $setting['related_attribute_name']; } }
php
public function initBySetting($model, $setting) { parent::initBySetting($model, $setting); $this->model = $model; if (is_array($setting)) { if (!isset($setting['remote_class_type'])) { throw new \Stack\Exception\MissingSetting('"remote_class_type" missing for the OneToMany relation.'); } if (!isset($setting['related_attribute_name'])) { throw new \Stack\Exception\MissingSetting('"related_attribute_name" missing for the OneToMany relation.'); } if (isset($setting['filter_list'])) { $this->filterList = $setting['filter_list']; } if (isset($setting['unique_remote'])) { $this->uniqueRemote = !!$setting['unique_remote']; } $this->remoteModelType = $setting['remote_class_type']; $this->relatedAttributeName = $setting['related_attribute_name']; } }
/* CONSTRUCTOR ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/Data/Stack/Attribute/Relation/OneToMany.php#L25-L45
Elephant418/Staq
src/Staq/Core/Data/Stack/Attribute/Relation/OneToMany.php
OneToMany.reload
public function reload() { $class = $this->getRemoteClass(); $count = false; $limit = null; if ($this->uniqueRemote) { $limit = 1; } $this->remoteModels = (new $class)->entity->fetchByRelated($this->relatedAttributeName, $this->model, $limit, null, $count, $this->filterList); }
php
public function reload() { $class = $this->getRemoteClass(); $count = false; $limit = null; if ($this->uniqueRemote) { $limit = 1; } $this->remoteModels = (new $class)->entity->fetchByRelated($this->relatedAttributeName, $this->model, $limit, null, $count, $this->filterList); }
/* PUBLIC USER METHODS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/Data/Stack/Attribute/Relation/OneToMany.php#L50-L59
Elephant418/Staq
src/Staq/Core/Data/Stack/Attribute/Relation/OneToMany.php
OneToMany.saveHandler
public function saveHandler() { if ($this->changed) { $class = $this->getRemoteClass(); (new $class)->entity->updateRelated($this->relatedAttributeName, $this->getIds(), $this->model, $this->filterList); } }
php
public function saveHandler() { if ($this->changed) { $class = $this->getRemoteClass(); (new $class)->entity->updateRelated($this->relatedAttributeName, $this->getIds(), $this->model, $this->filterList); } }
/* HANDLER METHODS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/Data/Stack/Attribute/Relation/OneToMany.php#L118-L124
moneyworks/Model
src/Helper.php
Helper.snake
public static function snake($value, $delimiter = '_') { if (!ctype_lower($value)) { $value = preg_replace('/\s+/', '', $value); $value = strtolower(preg_replace('/(.)(?=[A-Z])/', '$1' . $delimiter, $value)); } return $value; }
php
public static function snake($value, $delimiter = '_') { if (!ctype_lower($value)) { $value = preg_replace('/\s+/', '', $value); $value = strtolower(preg_replace('/(.)(?=[A-Z])/', '$1' . $delimiter, $value)); } return $value; }
Convert a string to snake case. @param string $value @param string $delimiter @return string
https://github.com/moneyworks/Model/blob/739f5014dd0e3da214a248d1da91107ef086acb1/src/Helper.php#L57-L65
moneyworks/Model
src/Helper.php
Helper.studly
public static function studly($value, $lc_first = true) { $value = ucwords(str_replace(['-', '_'], ' ', $value)); if ($lc_first) { $value = lcfirst($value); } return str_replace(' ', '', $value); }
php
public static function studly($value, $lc_first = true) { $value = ucwords(str_replace(['-', '_'], ' ', $value)); if ($lc_first) { $value = lcfirst($value); } return str_replace(' ', '', $value); }
Convert a value to studly caps case. @param string $value @param bool $lc_first @return string
https://github.com/moneyworks/Model/blob/739f5014dd0e3da214a248d1da91107ef086acb1/src/Helper.php#L74-L83
the-kbA-team/sap-datetime
src/SapDateTime.php
SapDateTime.createFromSapWeek
public static function createFromSapWeek($sapWeek, $timezone = null) { if (preg_match(static::$sapWeekRegex, $sapWeek, $matches) !== 1) { return false; } $week = sprintf('%sW%s', $matches[1], $matches[2]); return new parent($week, $timezone); }
php
public static function createFromSapWeek($sapWeek, $timezone = null) { if (preg_match(static::$sapWeekRegex, $sapWeek, $matches) !== 1) { return false; } $week = sprintf('%sW%s', $matches[1], $matches[2]); return new parent($week, $timezone); }
Parse an SAP week string into a new DateTime object. @param string $sapWeek String representing the SAP week. @param \DateTimeZone $timezone A DateTimeZone object representing the desired time zone. @return \DateTime|boolean @throws \Exception
https://github.com/the-kbA-team/sap-datetime/blob/30c1f7549f4848c7626c2832bf57257dc61bd062/src/SapDateTime.php#L55-L62
the-kbA-team/sap-datetime
src/SapDateTime.php
SapDateTime.createFromFormat
public static function createFromFormat( $format, $time, $timezone = null ) { if ($format === static::SAP_WEEK) { return static::createFromSapWeek($time, $timezone); } if ($timezone === null) { return parent::createFromFormat($format, $time); } //@codeCoverageIgnoreStart return parent::createFromFormat($format, $time, $timezone); //@codeCoverageIgnoreEnd }
php
public static function createFromFormat( $format, $time, $timezone = null ) { if ($format === static::SAP_WEEK) { return static::createFromSapWeek($time, $timezone); } if ($timezone === null) { return parent::createFromFormat($format, $time); } //@codeCoverageIgnoreStart return parent::createFromFormat($format, $time, $timezone); //@codeCoverageIgnoreEnd }
Parse a string into a new DateTime object according to the specified format. @param string $format Format accepted by date(). @param string $time String representing the time. @param \DateTimeZone $timezone A DateTimeZone object representing the desired time zone. @return \DateTime|boolean @throws \Exception @link https://php.net/manual/en/datetime.createfromformat.php
https://github.com/the-kbA-team/sap-datetime/blob/30c1f7549f4848c7626c2832bf57257dc61bd062/src/SapDateTime.php#L76-L90
slickframework/form
src/Form.php
Form.getElementData
protected function getElementData( ContainerInterface $container, &$data = [] ) { foreach ($container as $element) { if ($element instanceof InputInterface) { $data[$element->getName()] = $element->getValue(); continue; } if ($element instanceof ContainerInterface) { $this->getElementData($element, $data); continue; } } }
php
protected function getElementData( ContainerInterface $container, &$data = [] ) { foreach ($container as $element) { if ($element instanceof InputInterface) { $data[$element->getName()] = $element->getValue(); continue; } if ($element instanceof ContainerInterface) { $this->getElementData($element, $data); continue; } } }
Recursively collects all posted data @param ContainerInterface $container @param array $data
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Form.php#L100-L114
slickframework/form
src/Form.php
Form.add
public function add(ElementInterface $element) { if ($element instanceof File) { $this->setAttribute('enctype', 'multipart/form-data'); } return parent::add($element); }
php
public function add(ElementInterface $element) { if ($element instanceof File) { $this->setAttribute('enctype', 'multipart/form-data'); } return parent::add($element); }
Adds an element to the container @param ElementInterface $element @return self|$this|ContainerInterface
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Form.php#L156-L162
slickframework/form
src/Form.php
Form.wasSubmitted
public function wasSubmitted() { $formMethod = strtoupper($this->getAttribute('method', 'post')); $formId = $this->getRequest()->getPost('form-id', false); $formId = $formId ? $formId : $this->getRequest()->getQuery('form-id', null); $submitted = $this->request->getMethod() == $formMethod && $formId == $this->getId(); if ($submitted) { $this->updateValuesFromRequest(); } return $submitted; }
php
public function wasSubmitted() { $formMethod = strtoupper($this->getAttribute('method', 'post')); $formId = $this->getRequest()->getPost('form-id', false); $formId = $formId ? $formId : $this->getRequest()->getQuery('form-id', null); $submitted = $this->request->getMethod() == $formMethod && $formId == $this->getId(); if ($submitted) { $this->updateValuesFromRequest(); } return $submitted; }
Check if for was submitted or not @return boolean
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Form.php#L169-L183
slickframework/form
src/Form.php
Form.updateValuesFromRequest
protected function updateValuesFromRequest() { $data = $this->getRequest()->isPost() ? $this->getRequest()->getPost() : $this->getRequest()->getQuery(); if (isset($_FILES)) { $data = array_merge($data, $this->request->getUploadedFiles()); } $this->setValues($data); }
php
protected function updateValuesFromRequest() { $data = $this->getRequest()->isPost() ? $this->getRequest()->getPost() : $this->getRequest()->getQuery(); if (isset($_FILES)) { $data = array_merge($data, $this->request->getUploadedFiles()); } $this->setValues($data); }
Assign form values from request
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Form.php#L201-L211
Synapse-Cmf/synapse-cmf
src/Synapse/Cmf/Framework/Theme/Zone/Domain/Command/CreateCommand.php
CreateCommand.resolve
public function resolve() { $this->zone = new $this->zoneClass(); $this->zone->setZoneType($this->zoneType); $this->zone->setComponents( $this->components->buildRanking() ); $this->assertEntityIsValid($this->zone, array('Zone', 'creation')); $this->fireEvent( ZoneEvents::ZONE_CREATED, new ZoneEvent($this->zone, $this) ); return $this->zone; }
php
public function resolve() { $this->zone = new $this->zoneClass(); $this->zone->setZoneType($this->zoneType); $this->zone->setComponents( $this->components->buildRanking() ); $this->assertEntityIsValid($this->zone, array('Zone', 'creation')); $this->fireEvent( ZoneEvents::ZONE_CREATED, new ZoneEvent($this->zone, $this) ); return $this->zone; }
Zone creation method. @return Zone
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Framework/Theme/Zone/Domain/Command/CreateCommand.php#L47-L63
wigedev/farm
src/DataInterface/Grid.php
Grid.addRow
public function addRow(array $data = []) : int { $this->crudEnabled(); $table_name = static::$table_name; if (0 == count($data)) { // Insert a blank row $sql = "INSERT INTO {$table_name} DEFAULT VALUES"; // TODO: Move this to the DAO class $this->dbc->query($sql); } else { // Generate the values $components = $this->dbc->generateParameterizedComponents($data); $fields = $components['fields']; $values = $components['values']; $params = $components['params']; // Execute the query $sql = "INSERT INTO {$table_name} ({$fields}) VALUES ({$values})"; $this->dbc->query($sql, ['params' => $params]); } // Return the id of the new field return $this->dbc->lastInsertId(); }
php
public function addRow(array $data = []) : int { $this->crudEnabled(); $table_name = static::$table_name; if (0 == count($data)) { // Insert a blank row $sql = "INSERT INTO {$table_name} DEFAULT VALUES"; // TODO: Move this to the DAO class $this->dbc->query($sql); } else { // Generate the values $components = $this->dbc->generateParameterizedComponents($data); $fields = $components['fields']; $values = $components['values']; $params = $components['params']; // Execute the query $sql = "INSERT INTO {$table_name} ({$fields}) VALUES ({$values})"; $this->dbc->query($sql, ['params' => $params]); } // Return the id of the new field return $this->dbc->lastInsertId(); }
Add a row to the table represented by this grid. If a table name, id column or structure for the table is not defined above, this function will not work. @param string[] $data The parameters to be added to the row @return int The id of the generated row @throws \Exception If required values have not been set on the child class.
https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/DataInterface/Grid.php#L43-L66
wigedev/farm
src/DataInterface/Grid.php
Grid.deleteRow
public function deleteRow(int $id) : void { $this->crudEnabled(); // Generate the values $table_name = static::$table_name; $id_column = static::$id_column; $sql = "DELETE FROM {$table_name} WHERE {$id_column} = :key"; $this->dbc->query($sql, ['params' => [':key' => $id]]); }
php
public function deleteRow(int $id) : void { $this->crudEnabled(); // Generate the values $table_name = static::$table_name; $id_column = static::$id_column; $sql = "DELETE FROM {$table_name} WHERE {$id_column} = :key"; $this->dbc->query($sql, ['params' => [':key' => $id]]); }
Delete the row specified by the passed identifier. If the necessary crud fields have not been identified in the child class, this function will throw an exception. @param int $id @throws \Exception
https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/DataInterface/Grid.php#L75-L85
wigedev/farm
src/DataInterface/Grid.php
Grid.updateRow
public function updateRow($id, array $data) : void { $this->crudEnabled(); // Generate the values $components = $this->dbc->generateParameterizedComponents($data); $table_name = static::$table_name; $id_column = static::$id_column; $fields = $components['update']; $params = $components['params']; $params[':key'] = $id; // Execute the query $sql = "UPDATE {$table_name} SET {$fields} WHERE {$id_column} = :key"; $this->dbc->query($sql, ['params' => $params]); }
php
public function updateRow($id, array $data) : void { $this->crudEnabled(); // Generate the values $components = $this->dbc->generateParameterizedComponents($data); $table_name = static::$table_name; $id_column = static::$id_column; $fields = $components['update']; $params = $components['params']; $params[':key'] = $id; // Execute the query $sql = "UPDATE {$table_name} SET {$fields} WHERE {$id_column} = :key"; $this->dbc->query($sql, ['params' => $params]); }
Updates an existing row, based on the passed identifier. If the necessary crud fields have not been identified in the child class, this function will throw an exception. @param mixed $id The id of the row to update @param array $data The new data to enter @throws \Exception
https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/DataInterface/Grid.php#L95-L110
fxpio/fxp-doctrine-console
Command/Update.php
Update.execute
protected function execute(InputInterface $input, OutputInterface $output) { $id = $input->getArgument($this->adapter->getIdentifierArgument()); $instance = $this->adapter->get($id); $this->validateInstance($instance); $this->helper->injectNewValues($input, $instance); $this->adapter->update($instance); $this->showMessage($output, $instance, 'The %s <info>%s</info> was updated with successfully'); }
php
protected function execute(InputInterface $input, OutputInterface $output) { $id = $input->getArgument($this->adapter->getIdentifierArgument()); $instance = $this->adapter->get($id); $this->validateInstance($instance); $this->helper->injectNewValues($input, $instance); $this->adapter->update($instance); $this->showMessage($output, $instance, 'The %s <info>%s</info> was updated with successfully'); }
{@inheritdoc}
https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Command/Update.php#L35-L45
diasbruno/stc
lib/stc/Database.php
Database.store
public function store($key = '', $value = array(), $lock = true) { if ($key == '') { $this->fault('[Error] Cannot store data without a key. Key is "' . $key . '".'); } if (!$this->has_key($key)) { $this->create($key, $lock); $this->store_data($key, $value); } else { if (!$this->is_locked($key)) { $this->store_data($key, $value); } else { $this->fault('[Error] Cannot store data with a registered key that is locked.'); } } }
php
public function store($key = '', $value = array(), $lock = true) { if ($key == '') { $this->fault('[Error] Cannot store data without a key. Key is "' . $key . '".'); } if (!$this->has_key($key)) { $this->create($key, $lock); $this->store_data($key, $value); } else { if (!$this->is_locked($key)) { $this->store_data($key, $value); } else { $this->fault('[Error] Cannot store data with a registered key that is locked.'); } } }
Saves some data by key value. @param $key string | The key name. @param $value any | The value.
https://github.com/diasbruno/stc/blob/43f62c3b28167bff76274f954e235413a9e9c707/lib/stc/Database.php#L81-L97
openclerk/users
src/User.php
User.getInstance
static function getInstance(\Db\Connection $db) { if (User::$instance === null) { if (session_status() === PHP_SESSION_NONE) { throw new UserStatusException("Session needs to be started before requesting User instance"); } // try autologin if we don't have session variables set $used_auto_login = false; if (!isset($_SESSION['user_id']) && !isset($_SESSION['user_key']) && !isset($_SESSION['no_autologin'])) { User::tryAutoLogin(); $used_auto_login = true; } // if the session variables are still not set after autologin, bail if (!isset($_SESSION['user_id']) && !isset($_SESSION['user_key'])) { return User::$instance; } // now try to find the valid user $q = $db->prepare("SELECT * FROM user_valid_keys WHERE user_id=? AND user_key=? LIMIT 1"); $q->execute(array($_SESSION['user_id'], $_SESSION['user_key'])); if ($user = $q->fetch()) { // find the associated user User::$instance = User::findUser($db, $user['user_id']); if (User::$instance) { User::$instance->is_auto_logged_in = $used_auto_login; } } } return User::$instance; }
php
static function getInstance(\Db\Connection $db) { if (User::$instance === null) { if (session_status() === PHP_SESSION_NONE) { throw new UserStatusException("Session needs to be started before requesting User instance"); } // try autologin if we don't have session variables set $used_auto_login = false; if (!isset($_SESSION['user_id']) && !isset($_SESSION['user_key']) && !isset($_SESSION['no_autologin'])) { User::tryAutoLogin(); $used_auto_login = true; } // if the session variables are still not set after autologin, bail if (!isset($_SESSION['user_id']) && !isset($_SESSION['user_key'])) { return User::$instance; } // now try to find the valid user $q = $db->prepare("SELECT * FROM user_valid_keys WHERE user_id=? AND user_key=? LIMIT 1"); $q->execute(array($_SESSION['user_id'], $_SESSION['user_key'])); if ($user = $q->fetch()) { // find the associated user User::$instance = User::findUser($db, $user['user_id']); if (User::$instance) { User::$instance->is_auto_logged_in = $used_auto_login; } } } return User::$instance; }
Get the current logged in user instance, or {@code null} if there is none, based on session variables. @return the {@link User} logged in or {@code null} if none
https://github.com/openclerk/users/blob/550c7610c154a2f6655ce65a2df377ccb207bc6d/src/User.php#L36-L68
openclerk/users
src/User.php
User.forceLogin
static function forceLogin(\Db\Connection $db, $user_id) { User::$instance = User::findUser($db, $user_id); }
php
static function forceLogin(\Db\Connection $db, $user_id) { User::$instance = User::findUser($db, $user_id); }
Login as the given user_id.
https://github.com/openclerk/users/blob/550c7610c154a2f6655ce65a2df377ccb207bc6d/src/User.php#L102-L104
openclerk/users
src/User.php
User.delete
function delete(\Db\Connection $db) { // delete all possible identities $q = $db->prepare("DELETE FROM user_passwords WHERE user_id=?"); $q->execute(array($this->getId())); $q = $db->prepare("DELETE FROM user_openid_identities WHERE user_id=?"); $q->execute(array($this->getId())); $q = $db->prepare("DELETE FROM user_oauth2_identities WHERE user_id=?"); $q->execute(array($this->getId())); $q = $db->prepare("DELETE FROM user_valid_keys WHERE user_id=?"); $q->execute(array($this->getId())); $q = $db->prepare("DELETE FROM users WHERE id=?"); $q->execute(array($this->getId())); \Openclerk\Events::trigger('user_deleted', $this); }
php
function delete(\Db\Connection $db) { // delete all possible identities $q = $db->prepare("DELETE FROM user_passwords WHERE user_id=?"); $q->execute(array($this->getId())); $q = $db->prepare("DELETE FROM user_openid_identities WHERE user_id=?"); $q->execute(array($this->getId())); $q = $db->prepare("DELETE FROM user_oauth2_identities WHERE user_id=?"); $q->execute(array($this->getId())); $q = $db->prepare("DELETE FROM user_valid_keys WHERE user_id=?"); $q->execute(array($this->getId())); $q = $db->prepare("DELETE FROM users WHERE id=?"); $q->execute(array($this->getId())); \Openclerk\Events::trigger('user_deleted', $this); }
Delete the given user. Triggers a 'user_deleted' event with the current user as an argument.
https://github.com/openclerk/users/blob/550c7610c154a2f6655ce65a2df377ccb207bc6d/src/User.php#L155-L169
tetreum/apache-vhost-processor
src/VirtualHost.php
VirtualHost.toString
public function toString () { $content = "<VirtualHost {$this->address}:{$this->port}>" . PHP_EOL; foreach ($this->directives as $directive) { $content .= $directive->toString() . PHP_EOL; } $content .= PHP_EOL; foreach ($this->directories as $directory) { $content .= $directory->toString() . PHP_EOL; } $content .= PHP_EOL; $content .= "</VirtualHost>"; return $content; }
php
public function toString () { $content = "<VirtualHost {$this->address}:{$this->port}>" . PHP_EOL; foreach ($this->directives as $directive) { $content .= $directive->toString() . PHP_EOL; } $content .= PHP_EOL; foreach ($this->directories as $directory) { $content .= $directory->toString() . PHP_EOL; } $content .= PHP_EOL; $content .= "</VirtualHost>"; return $content; }
Converts vh to plain text @return
https://github.com/tetreum/apache-vhost-processor/blob/bdf46a3a32126dc9667f0ff4c51b2a39dcc796e2/src/VirtualHost.php#L30-L48
DBRisinajumi/d2company
models/DbrUser.php
DbrUser.isCustomerOfficeUser
static public function isCustomerOfficeUser(){ if(Yii::app()->user->isGuest){ return FALSE; } $a = self::getRoles(); return isset($a[self::RoleCustomerOffice]); }
php
static public function isCustomerOfficeUser(){ if(Yii::app()->user->isGuest){ return FALSE; } $a = self::getRoles(); return isset($a[self::RoleCustomerOffice]); }
verify has role OfficeUser @return boolean
https://github.com/DBRisinajumi/d2company/blob/20df0db96ac2c8e73471c4bab7d487b67ef4ed0a/models/DbrUser.php#L75-L81
DBRisinajumi/d2company
models/DbrUser.php
DbrUser.isSysCompanyUser
static public function isSysCompanyUser(){ if(Yii::app()->user->isGuest){ return FALSE; } $a = self::getRoles(); return isset($a[self::RoleSysCompanyUser]); }
php
static public function isSysCompanyUser(){ if(Yii::app()->user->isGuest){ return FALSE; } $a = self::getRoles(); return isset($a[self::RoleSysCompanyUser]); }
verify has role OfficeUser @return boolean
https://github.com/DBRisinajumi/d2company/blob/20df0db96ac2c8e73471c4bab7d487b67ef4ed0a/models/DbrUser.php#L87-L93
apitude/user
src/OAuth/Authentication/OAuth2OptionalListener.php
OAuth2OptionalListener.handle
public function handle(GetResponseEvent $event) { $request = $event->getRequest(); if ($request->getMethod() === Request::METHOD_OPTIONS) { $this->getTokenStorage()->setToken(new AnonymousToken('', 'anonymous', [])); return; } if ( !$request->headers->has('Authorization') || !preg_match('/Bearer (.*)/', $request->headers->get('Authorization')) ) { $token = new AnonymousToken('', 'anonymous'); $this->getTokenStorage()->setToken($token); return; } $this->doHandle($event); }
php
public function handle(GetResponseEvent $event) { $request = $event->getRequest(); if ($request->getMethod() === Request::METHOD_OPTIONS) { $this->getTokenStorage()->setToken(new AnonymousToken('', 'anonymous', [])); return; } if ( !$request->headers->has('Authorization') || !preg_match('/Bearer (.*)/', $request->headers->get('Authorization')) ) { $token = new AnonymousToken('', 'anonymous'); $this->getTokenStorage()->setToken($token); return; } $this->doHandle($event); }
This interface must be implemented by firewall listeners. @param GetResponseEvent $event
https://github.com/apitude/user/blob/24adf733cf628d321c2bcae328c383113928d019/src/OAuth/Authentication/OAuth2OptionalListener.php#L15-L34
keboola/developer-portal-php-client
src/Keboola/DeveloperPortal/Client.php
Client.updateApp
public function updateApp($vendor, $id, $params) { return $this->authRequest('PATCH', sprintf('vendors/%s/apps/%s', $vendor, $id), $params); }
php
public function updateApp($vendor, $id, $params) { return $this->authRequest('PATCH', sprintf('vendors/%s/apps/%s', $vendor, $id), $params); }
Pass attributes of the app in $params array: [ 'repository' => [ 'type' => 'ecr', 'uri' => 'my.repo.uri', 'tag' => '1.23.0', 'options' => [] ] ... ] @param $vendor @param $id @param $params @return array
https://github.com/keboola/developer-portal-php-client/blob/bde490be1b455c7f5b0230befa66ea3c747e6fc7/src/Keboola/DeveloperPortal/Client.php#L374-L377
jtallant/skimpy-engine
src/Http/Middleware/ContentCacheHandler.php
ContentCacheHandler.handleRequest
public function handleRequest(Request $request, Application $app) { # Rebuild on every request in dev environment if ($this->isAutoRebuildMode($app)) { $this->rebuildDatabase(); return; } if ($this->dbHasNotBeenBuilt()) { $this->rebuildDatabase(); return; } if ($this->isValidRebuildRequest($request, $app)) { $this->rebuildDatabase(); } }
php
public function handleRequest(Request $request, Application $app) { # Rebuild on every request in dev environment if ($this->isAutoRebuildMode($app)) { $this->rebuildDatabase(); return; } if ($this->dbHasNotBeenBuilt()) { $this->rebuildDatabase(); return; } if ($this->isValidRebuildRequest($request, $app)) { $this->rebuildDatabase(); } }
If the request includes an instruction to rebuild the db, do that @param Request $request @param Application $app
https://github.com/jtallant/skimpy-engine/blob/2fce5bc16f8745e54fd66a1c291fcea47fc1b4b2/src/Http/Middleware/ContentCacheHandler.php#L42-L60
jtallant/skimpy-engine
src/Http/Middleware/ContentCacheHandler.php
ContentCacheHandler.rebuildDatabase
protected function rebuildDatabase() { $this->populator->populate(); $path = $this->buildIndicator->getPathname(); $content = 'Initial Build: '.date('Y-m-d H:i:s'); $this->filesystem->remove($path); $this->filesystem->dumpFile($path, $content); }
php
protected function rebuildDatabase() { $this->populator->populate(); $path = $this->buildIndicator->getPathname(); $content = 'Initial Build: '.date('Y-m-d H:i:s'); $this->filesystem->remove($path); $this->filesystem->dumpFile($path, $content); }
Builds the DB and creates a file indicating that the DB has been built at least once. @return void
https://github.com/jtallant/skimpy-engine/blob/2fce5bc16f8745e54fd66a1c291fcea47fc1b4b2/src/Http/Middleware/ContentCacheHandler.php#L78-L87
jtallant/skimpy-engine
src/Http/Middleware/ContentCacheHandler.php
ContentCacheHandler.isValidRebuildRequest
protected function isValidRebuildRequest(Request $request, Application $app) { # No indication to rebuild site, do nothing. if (false === $request->query->has('rebuild')) { return false; } # No build key present to validate site owner # is the one attempting to rebuild. Do Nothing. if (empty($app['build_key'])) { return false; } # build_key does match rebuild query param value. Do nothing. if ($app['build_key'] !== $request->query->get('rebuild')) { return false; } return true; }
php
protected function isValidRebuildRequest(Request $request, Application $app) { # No indication to rebuild site, do nothing. if (false === $request->query->has('rebuild')) { return false; } # No build key present to validate site owner # is the one attempting to rebuild. Do Nothing. if (empty($app['build_key'])) { return false; } # build_key does match rebuild query param value. Do nothing. if ($app['build_key'] !== $request->query->get('rebuild')) { return false; } return true; }
@param Request $request @param Application $app @return bool
https://github.com/jtallant/skimpy-engine/blob/2fce5bc16f8745e54fd66a1c291fcea47fc1b4b2/src/Http/Middleware/ContentCacheHandler.php#L103-L122
SpoonX/SxBootstrap
src/SxBootstrap/View/Helper/Bootstrap/Form/Element.php
Element.render
protected function render(ElementInterface $element) { $renderer = $this->getView(); if (!method_exists($renderer, 'plugin')) { throw new Exception\RuntimeException( 'Renderer does not have a plugin method.' ); } if ($element instanceof FormElement\Button) { $helper = $renderer->plugin('sxb_button'); return $helper($element); } if ($element instanceof FormElement\Captcha) { $helper = $renderer->plugin('form_captcha'); return $helper($element); } if ($element instanceof FormElement\Csrf) { $helper = $renderer->plugin('sxb_form_hidden'); return $helper($element); } if ($element instanceof FormElement\Collection) { $helper = $renderer->plugin('form_collection'); return $helper($element); } if ($element instanceof FormElement\DateTimeSelect) { $helper = $renderer->plugin('form_date_time_select'); return $helper($element); } if ($element instanceof FormElement\DateSelect) { $helper = $renderer->plugin('form_date_select'); return $helper($element); } if ($element instanceof FormElement\MonthSelect) { $helper = $renderer->plugin('form_month_select'); return $helper($element); } $type = $element->getAttribute('type'); if ('checkbox' === $type) { $helper = $renderer->plugin('form_checkbox'); return $helper($element); } if ('color' === $type) { $helper = $renderer->plugin('sxb_form_color'); return $helper($element); } if ('date' === $type) { $helper = $renderer->plugin('sxb_form_date'); return $helper($element); } if ('datetime' === $type) { $helper = $renderer->plugin('sxb_form_date_time'); return $helper($element); } if ('datetime-local' === $type) { $helper = $renderer->plugin('sxb_form_date_time_local'); return $helper($element); } if ('email' === $type) { $helper = $renderer->plugin('sxb_form_email'); return $helper($element); } if ('file' === $type) { $helper = $renderer->plugin('sxb_form_file'); return $helper($element); } if ('hidden' === $type) { $helper = $renderer->plugin('sxb_form_hidden'); return $helper($element); } if ('image' === $type) { $helper = $renderer->plugin('sxb_form_image'); return $helper($element); } if ('month' === $type) { $helper = $renderer->plugin('sxb_form_month'); return $helper($element); } if ('multi_checkbox' === $type) { $helper = $renderer->plugin('form_multi_checkbox'); return $helper($element); } if ('number' === $type) { $helper = $renderer->plugin('sxb_form_number'); return $helper($element); } if ('password' === $type) { $helper = $renderer->plugin('sxb_form_password'); return $helper($element); } if ('radio' === $type) { $helper = $renderer->plugin('form_radio'); return $helper($element); } if ('range' === $type) { $helper = $renderer->plugin('sxb_form_range'); return $helper($element); } if ('reset' === $type) { $helper = $renderer->plugin('sxb_form_reset'); return $helper($element); } if ('search' === $type) { $helper = $renderer->plugin('sxb_form_search'); return $helper($element); } if ('select' === $type) { $helper = $renderer->plugin('form_select'); return $helper($element); } if ('submit' === $type) { $helper = $renderer->plugin('sxb_form_submit'); return $helper($element); } if ('tel' === $type) { $helper = $renderer->plugin('sxb_form_tel'); return $helper($element); } if ('text' === $type) { $helper = $renderer->plugin('sxb_form_input'); return $helper($element); } if ('textarea' === $type) { $helper = $renderer->plugin('form_textarea'); return $helper($element); } if ('time' === $type) { $helper = $renderer->plugin('sxb_form_time'); return $helper($element); } if ('url' === $type) { $helper = $renderer->plugin('sxb_form_url'); return $helper($element); } if ('week' === $type) { $helper = $renderer->plugin('sxb_form_week'); return $helper($element); } $helper = $renderer->plugin('sxb_form_input'); return $helper($element); }
php
protected function render(ElementInterface $element) { $renderer = $this->getView(); if (!method_exists($renderer, 'plugin')) { throw new Exception\RuntimeException( 'Renderer does not have a plugin method.' ); } if ($element instanceof FormElement\Button) { $helper = $renderer->plugin('sxb_button'); return $helper($element); } if ($element instanceof FormElement\Captcha) { $helper = $renderer->plugin('form_captcha'); return $helper($element); } if ($element instanceof FormElement\Csrf) { $helper = $renderer->plugin('sxb_form_hidden'); return $helper($element); } if ($element instanceof FormElement\Collection) { $helper = $renderer->plugin('form_collection'); return $helper($element); } if ($element instanceof FormElement\DateTimeSelect) { $helper = $renderer->plugin('form_date_time_select'); return $helper($element); } if ($element instanceof FormElement\DateSelect) { $helper = $renderer->plugin('form_date_select'); return $helper($element); } if ($element instanceof FormElement\MonthSelect) { $helper = $renderer->plugin('form_month_select'); return $helper($element); } $type = $element->getAttribute('type'); if ('checkbox' === $type) { $helper = $renderer->plugin('form_checkbox'); return $helper($element); } if ('color' === $type) { $helper = $renderer->plugin('sxb_form_color'); return $helper($element); } if ('date' === $type) { $helper = $renderer->plugin('sxb_form_date'); return $helper($element); } if ('datetime' === $type) { $helper = $renderer->plugin('sxb_form_date_time'); return $helper($element); } if ('datetime-local' === $type) { $helper = $renderer->plugin('sxb_form_date_time_local'); return $helper($element); } if ('email' === $type) { $helper = $renderer->plugin('sxb_form_email'); return $helper($element); } if ('file' === $type) { $helper = $renderer->plugin('sxb_form_file'); return $helper($element); } if ('hidden' === $type) { $helper = $renderer->plugin('sxb_form_hidden'); return $helper($element); } if ('image' === $type) { $helper = $renderer->plugin('sxb_form_image'); return $helper($element); } if ('month' === $type) { $helper = $renderer->plugin('sxb_form_month'); return $helper($element); } if ('multi_checkbox' === $type) { $helper = $renderer->plugin('form_multi_checkbox'); return $helper($element); } if ('number' === $type) { $helper = $renderer->plugin('sxb_form_number'); return $helper($element); } if ('password' === $type) { $helper = $renderer->plugin('sxb_form_password'); return $helper($element); } if ('radio' === $type) { $helper = $renderer->plugin('form_radio'); return $helper($element); } if ('range' === $type) { $helper = $renderer->plugin('sxb_form_range'); return $helper($element); } if ('reset' === $type) { $helper = $renderer->plugin('sxb_form_reset'); return $helper($element); } if ('search' === $type) { $helper = $renderer->plugin('sxb_form_search'); return $helper($element); } if ('select' === $type) { $helper = $renderer->plugin('form_select'); return $helper($element); } if ('submit' === $type) { $helper = $renderer->plugin('sxb_form_submit'); return $helper($element); } if ('tel' === $type) { $helper = $renderer->plugin('sxb_form_tel'); return $helper($element); } if ('text' === $type) { $helper = $renderer->plugin('sxb_form_input'); return $helper($element); } if ('textarea' === $type) { $helper = $renderer->plugin('form_textarea'); return $helper($element); } if ('time' === $type) { $helper = $renderer->plugin('sxb_form_time'); return $helper($element); } if ('url' === $type) { $helper = $renderer->plugin('sxb_form_url'); return $helper($element); } if ('week' === $type) { $helper = $renderer->plugin('sxb_form_week'); return $helper($element); } $helper = $renderer->plugin('sxb_form_input'); return $helper($element); }
@param ElementInterface $element @return string @throws \SxBootstrap\Exception\RuntimeException
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Form/Element.php#L29-L236
IftekherSunny/Planet-Framework
src/Sun/Console/Commands/MakeListener.php
MakeListener.handle
public function handle() { $listenerName = $this->input->getArgument('name'); $eventName = $this->input->getOption('event'); $listenerNamespace = $this->getNamespace('Listeners', $listenerName); if(!is_null($eventName)) { $eventName = str_replace('/','\\', $eventName); $eventNamespace = $this->app->getNamespace(). "Events\\{$eventName}"; $listenerStubs = $this->filesystem->get(__DIR__.'/../stubs/MakeListenerEvent.txt'); $listenerStubs = str_replace([ 'dummyListenerName', 'dummyEventNameVariable', 'dummyEventName', 'dummyNamespace', 'dummyUse', '\\\\' ], [ basename($listenerName), lcfirst(basename($eventName)), basename($eventName), $listenerNamespace, $eventNamespace, '\\' ], $listenerStubs); } else { $listenerStubs = $this->filesystem->get(__DIR__.'/../stubs/MakeListener.txt'); $listenerStubs = str_replace([ 'dummyListenerName', 'dummyNamespace', '\\\\' ], [ basename($listenerName), $listenerNamespace, '\\' ], $listenerStubs); } if(!file_exists($filename = app_path() ."/Listeners/{$listenerName}.php")) { $this->filesystem->create($filename, $listenerStubs); $this->info("{$listenerName} has been created successfully."); } else { $this->info("{$listenerName} already exists."); } }
php
public function handle() { $listenerName = $this->input->getArgument('name'); $eventName = $this->input->getOption('event'); $listenerNamespace = $this->getNamespace('Listeners', $listenerName); if(!is_null($eventName)) { $eventName = str_replace('/','\\', $eventName); $eventNamespace = $this->app->getNamespace(). "Events\\{$eventName}"; $listenerStubs = $this->filesystem->get(__DIR__.'/../stubs/MakeListenerEvent.txt'); $listenerStubs = str_replace([ 'dummyListenerName', 'dummyEventNameVariable', 'dummyEventName', 'dummyNamespace', 'dummyUse', '\\\\' ], [ basename($listenerName), lcfirst(basename($eventName)), basename($eventName), $listenerNamespace, $eventNamespace, '\\' ], $listenerStubs); } else { $listenerStubs = $this->filesystem->get(__DIR__.'/../stubs/MakeListener.txt'); $listenerStubs = str_replace([ 'dummyListenerName', 'dummyNamespace', '\\\\' ], [ basename($listenerName), $listenerNamespace, '\\' ], $listenerStubs); } if(!file_exists($filename = app_path() ."/Listeners/{$listenerName}.php")) { $this->filesystem->create($filename, $listenerStubs); $this->info("{$listenerName} has been created successfully."); } else { $this->info("{$listenerName} already exists."); } }
To handle console command
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Commands/MakeListener.php#L42-L68
rujiali/acquia-site-factory-cli
src/AppBundle/Commands/GetLastBackupTimeCommand.php
GetLastBackupTimeCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $timestamp = $this->connectorSites->getLastBackupTime(); $output->write($timestamp); }
php
protected function execute(InputInterface $input, OutputInterface $output) { $timestamp = $this->connectorSites->getLastBackupTime(); $output->write($timestamp); }
{@inheritdoc}
https://github.com/rujiali/acquia-site-factory-cli/blob/c9dbb9dfd71408adff0ea26db94678a61c584df6/src/AppBundle/Commands/GetLastBackupTimeCommand.php#L43-L47
SpoonX/SxBootstrap
src/SxBootstrap/View/Helper/Bootstrap/Form/Row.php
Row.renderRow
public function renderRow(ElementInterface $element) { /* @var $rowPlugin \SxBootstrap\View\Helper\Bootstrap\Form\ControlGroup */ $rowPlugin = $this->getView()->plugin('sxb_form_control_group'); $rowPlugin = $rowPlugin(); $errors = $this->renderError($element); $label = $this->renderLabel($element); $description = $this->renderDescription($element); $controls = $this->renderControls($element, null !== $errors ? $errors : $description); if (null !== $errors) { $rowPlugin->error(); } $rowPlugin->addContents(array( $label, $controls, )); return $rowPlugin; }
php
public function renderRow(ElementInterface $element) { /* @var $rowPlugin \SxBootstrap\View\Helper\Bootstrap\Form\ControlGroup */ $rowPlugin = $this->getView()->plugin('sxb_form_control_group'); $rowPlugin = $rowPlugin(); $errors = $this->renderError($element); $label = $this->renderLabel($element); $description = $this->renderDescription($element); $controls = $this->renderControls($element, null !== $errors ? $errors : $description); if (null !== $errors) { $rowPlugin->error(); } $rowPlugin->addContents(array( $label, $controls, )); return $rowPlugin; }
@param ElementInterface $element @return ControlGroup
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Form/Row.php#L28-L48
SpoonX/SxBootstrap
src/SxBootstrap/View/Helper/Bootstrap/Form/Row.php
Row.renderActionsRow
public function renderActionsRow($actions) { /* @var $rowPlugin \SxBootstrap\View\Helper\Bootstrap\Form\Actions */ /* @var $elementPlugin \SxBootstrap\View\Helper\Bootstrap\Form\Element */ $rowPlugin = $this->getView()->plugin('sxb_form_actions'); $rowPlugin = $rowPlugin(); $elementPlugin = $this->getView()->plugin('sxb_form_element'); if ($actions instanceof ElementInterface) { return $rowPlugin->addContent($elementPlugin($actions)); } if (!is_array($actions)) { throw new Exception\RuntimeException( 'Invalid actions type supplied' ); } foreach ($actions as $action) { $rowPlugin->addContent($elementPlugin($action)); } return $rowPlugin; }
php
public function renderActionsRow($actions) { /* @var $rowPlugin \SxBootstrap\View\Helper\Bootstrap\Form\Actions */ /* @var $elementPlugin \SxBootstrap\View\Helper\Bootstrap\Form\Element */ $rowPlugin = $this->getView()->plugin('sxb_form_actions'); $rowPlugin = $rowPlugin(); $elementPlugin = $this->getView()->plugin('sxb_form_element'); if ($actions instanceof ElementInterface) { return $rowPlugin->addContent($elementPlugin($actions)); } if (!is_array($actions)) { throw new Exception\RuntimeException( 'Invalid actions type supplied' ); } foreach ($actions as $action) { $rowPlugin->addContent($elementPlugin($action)); } return $rowPlugin; }
@param $actions @return \SxBootstrap\View\Helper\Bootstrap\AbstractElementHelper|Actions @throws \SxBootstrap\Exception\RuntimeException
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Form/Row.php#L56-L79
SpoonX/SxBootstrap
src/SxBootstrap/View/Helper/Bootstrap/Form/Row.php
Row.renderLabel
protected function renderLabel(ElementInterface $element) { $labelPlugin = $this->getView()->plugin('sxb_form_control_label'); $label = $element->getLabel(); if (null !== $label) { $label = $labelPlugin($label, $element->getName(), $element->getLabelAttributes()); } return $label; }
php
protected function renderLabel(ElementInterface $element) { $labelPlugin = $this->getView()->plugin('sxb_form_control_label'); $label = $element->getLabel(); if (null !== $label) { $label = $labelPlugin($label, $element->getName(), $element->getLabelAttributes()); } return $label; }
@param ElementInterface $element @return string
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Form/Row.php#L86-L96
SpoonX/SxBootstrap
src/SxBootstrap/View/Helper/Bootstrap/Form/Row.php
Row.renderControls
protected function renderControls(ElementInterface $element, $help = null) { $elementPlugin = $this->getView()->plugin('sxb_form_element'); $controlsPlugin = $this->getView()->plugin('sxb_form_controls'); return $controlsPlugin(array( (string) $elementPlugin($element), $help, )); }
php
protected function renderControls(ElementInterface $element, $help = null) { $elementPlugin = $this->getView()->plugin('sxb_form_element'); $controlsPlugin = $this->getView()->plugin('sxb_form_controls'); return $controlsPlugin(array( (string) $elementPlugin($element), $help, )); }
@param ElementInterface $element @param null|string $help @return \SxBootstrap\View\Helper\Bootstrap\Form\Controls
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Form/Row.php#L104-L113
SpoonX/SxBootstrap
src/SxBootstrap/View/Helper/Bootstrap/Form/Row.php
Row.renderError
protected function renderError(ElementInterface $element) { $messages = $element->getMessages(); if (empty($messages)) { return null; } $errorPlugin = $this->getView()->plugin('sxb_form_errors'); return $errorPlugin($element); }
php
protected function renderError(ElementInterface $element) { $messages = $element->getMessages(); if (empty($messages)) { return null; } $errorPlugin = $this->getView()->plugin('sxb_form_errors'); return $errorPlugin($element); }
Render errors. @param ElementInterface $element @return null|\SxBootstrap\View\Helper\Bootstrap\Form\Errors
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Form/Row.php#L134-L145
ben-gibson/foursquare-venue-client
src/Factory/Tip/TipGroupFactory.php
TipGroupFactory.create
public function create(Description $description) { return new TipGroup( $description->getMandatoryProperty('name'), $description->getMandatoryProperty('type'), $this->getTips($description) ); }
php
public function create(Description $description) { return new TipGroup( $description->getMandatoryProperty('name'), $description->getMandatoryProperty('type'), $this->getTips($description) ); }
Create a tip group from a description. @param Description $description The tip group description. @return TipGroup
https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Factory/Tip/TipGroupFactory.php#L33-L40
ben-gibson/foursquare-venue-client
src/Factory/Tip/TipGroupFactory.php
TipGroupFactory.getTips
private function getTips(Description $description) { return array_map( function (\stdClass $tipDescription) { return $this->tipFactory->create(new Description($tipDescription)); }, $description->getOptionalProperty('items', []) ); }
php
private function getTips(Description $description) { return array_map( function (\stdClass $tipDescription) { return $this->tipFactory->create(new Description($tipDescription)); }, $description->getOptionalProperty('items', []) ); }
Get the venue tips. @param Description $description The tip group description. @return Tip[]
https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Factory/Tip/TipGroupFactory.php#L49-L57
kvantstudio/site_orders
src/Form/SiteOrdersAddCartForm.php
SiteOrdersAddCartForm.buildForm
public function buildForm(array $form, FormStateInterface $form_state, $pid = 0, $type = '') { $form_state->disableRedirect(); // Загружаем конфигурацию. $config = $this->config('kvantstudio.settings'); // Текущий пользователь. $account = \Drupal::currentUser(); // Загружаем позицию. $position = (object) $this->databaseSendOrder->loadPosition($pid, $type); $form['position'] = array( '#type' => 'value', '#value' => $position, ); // Примечание к корзине. Заполняется в карточке товара. $form['description'] = array( '#markup' => $position->get('field_cart')->description, '#prefix' => '<div class="site-orders-add-cart-form__description">', '#suffix' => '</div>', '#attributes' => array('placeholder' => ''), '#access' => $position->get('field_cart')->description ? TRUE : FALSE, ); // Стоимость для текущего пользователя. // TODO: Пока реализовано отображение для ценовой группы по умолчанию равной 1. $group = 1; $cost = getCostValueForUserPriceGroup($position, $group, TRUE, FALSE); $form['cost_view'] = array( '#markup' => $cost, '#prefix' => '<div class="site-orders-add-cart-form__cost">', '#suffix' => '</div>', '#access' => $cost ? TRUE : FALSE, ); $form['group'] = array( '#type' => 'value', '#value' => $group, ); // Количество для заказа. $form['quantity'] = array( '#type' => 'number', '#title' => $this->t('Quantity') . ', ' . $position->get('field_quantity')->unit, '#required' => FALSE, '#default_value' => '', '#min' => $position->get('field_quantity')->min, '#description' => '', '#attributes' => array('class' => ['site-orders-add-cart-form__quantity'], 'placeholder' => $position->get('field_quantity')->min), '#access' => $position->get('field_quantity')->visible ? TRUE : FALSE, '#suffix' => '<div class="site-orders-add-cart-form__quantity-validation"></div>', ); // Параметры товара. $site_commerce_database = \Drupal::service('site_commerce.database'); $characteristics = $site_commerce_database->characteristicDataReadProductItems($pid, 1); foreach ($characteristics as $key => $value) { if ($characteristics_group = $value['group']) { $form['cid'] = [ '#type' => 'select', '#title' => $this->t('@value', ['@value' => $characteristics_group->title]), '#options' => $site_commerce_database->characteristicsProductReadItems($pid, $characteristics_group->gid), '#empty_option' => $this->t('- None -'), '#ajax' => [ 'callback' => [$this, 'ajaxCallChangeSelectCharacteristic'], 'progress' => [], ], ]; } } // Добавляем нашу кнопку для отправки. $label_add = trim($position->get('field_cart')->label_add); $form['actions']['#type'] = 'actions'; $form['actions']['#attributes'] = array('class' => ['site-orders-add-cart-form__actions']); $form['actions']['submit'] = array( '#type' => 'submit', '#value' => $this->t($label_add), '#button_type' => 'primary', '#ajax' => [ 'callback' => '::ajaxSubmitCallback', 'progress' => array(), ], '#attributes' => array('class' => ['site-orders-add-cart-form__submit']), '#suffix' => '<div class="site-orders-add-cart-form__submit-note"></div>', '#access' => $label_add ? TRUE : FALSE, ); $form['actions']['buy_one_click'] = [ '#title' => $this->t($position->get('field_cart')->label_click), '#type' => 'link', '#url' => Url::fromUserInput('#javascript:void(0);'), '#prefix' => '<div class="site-orders-add-cart-form__buy-one-click">', '#suffix' => '</div>', '#attributes' => $label_add ? array('class' => ['site-orders-add-cart-form__buy-one-click-link']) : array('class' => ['site-orders-add-cart-form__buy-one-click-link site-orders-add-cart-form__buy-one-click-btn']), ]; $form['buy'] = array( '#prefix' => '<div class="site-orders-add-cart-form__buy site-orders-add-cart-form__buy_hide">', '#suffix' => '</div>', ); $form['buy']['close'] = array( '#markup' => '<span class="site-orders-form__close site-orders-add-cart-form__close"></span>', ); $form['buy']['title'] = array( '#markup' => '<h2>' . $this->t('Write phone number') . '</h2>' . $this->t('We calculate the cost of checkout.'), ); // Поле телефон. $form['buy']['phone'] = array( '#type' => 'tel', '#title' => $this->t('Phone number'), '#required' => FALSE, '#description' => '', '#attributes' => $config->get('phone_mask') ? ['class' => ['phone-mask']] : [], '#suffix' => '<div class="site-orders-form__phone-validation-order"></div>', ); // Соглашение об обработке персональных данных. if ($data_policy_information = $config->get('text_data_policy')) { $form['buy']['data_policy'] = array( '#type' => 'checkbox', '#attributes' => array('class' => array('site-orders-form__data-policy')), '#default_value' => 1, '#prefix' => '<div class="site-orders-form__data-policy-block">', '#ajax' => [ 'callback' => '::validateDataPolicy', 'event' => 'change', 'progress' => array( 'message' => NULL, ), ], ); $data_policy_information = str_replace("@submit_label", $this->t('Send request'), $data_policy_information); $nid = $config->get('node_agreement_personal_data'); $data_policy_information = str_replace("@data_policy_url", "/node/" . $nid, $data_policy_information); $form['buy']['data_policy_information'] = array( '#markup' => $data_policy_information, '#suffix' => '</div>', ); } // Добавляем нашу кнопку для отправки заявки. $form['buy']['actions']['#type'] = 'actions'; $form['buy']['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Send request'), '#button_type' => 'primary', '#ajax' => [ 'callback' => '::ajaxSubmitBuyCallback', 'progress' => [], ], '#attributes' => array('class' => array('site-orders-form__submit')), '#suffix' => '<div class="site-orders-form__submit-label"></div>', ]; $form['#attached']['library'][] = 'site_orders/module'; $form['#attached']['library'][] = 'kvantstudio/mask'; // TODO: Сделать блокировку загрузки если не используется маска. return $form; }
php
public function buildForm(array $form, FormStateInterface $form_state, $pid = 0, $type = '') { $form_state->disableRedirect(); // Загружаем конфигурацию. $config = $this->config('kvantstudio.settings'); // Текущий пользователь. $account = \Drupal::currentUser(); // Загружаем позицию. $position = (object) $this->databaseSendOrder->loadPosition($pid, $type); $form['position'] = array( '#type' => 'value', '#value' => $position, ); // Примечание к корзине. Заполняется в карточке товара. $form['description'] = array( '#markup' => $position->get('field_cart')->description, '#prefix' => '<div class="site-orders-add-cart-form__description">', '#suffix' => '</div>', '#attributes' => array('placeholder' => ''), '#access' => $position->get('field_cart')->description ? TRUE : FALSE, ); // Стоимость для текущего пользователя. // TODO: Пока реализовано отображение для ценовой группы по умолчанию равной 1. $group = 1; $cost = getCostValueForUserPriceGroup($position, $group, TRUE, FALSE); $form['cost_view'] = array( '#markup' => $cost, '#prefix' => '<div class="site-orders-add-cart-form__cost">', '#suffix' => '</div>', '#access' => $cost ? TRUE : FALSE, ); $form['group'] = array( '#type' => 'value', '#value' => $group, ); // Количество для заказа. $form['quantity'] = array( '#type' => 'number', '#title' => $this->t('Quantity') . ', ' . $position->get('field_quantity')->unit, '#required' => FALSE, '#default_value' => '', '#min' => $position->get('field_quantity')->min, '#description' => '', '#attributes' => array('class' => ['site-orders-add-cart-form__quantity'], 'placeholder' => $position->get('field_quantity')->min), '#access' => $position->get('field_quantity')->visible ? TRUE : FALSE, '#suffix' => '<div class="site-orders-add-cart-form__quantity-validation"></div>', ); // Параметры товара. $site_commerce_database = \Drupal::service('site_commerce.database'); $characteristics = $site_commerce_database->characteristicDataReadProductItems($pid, 1); foreach ($characteristics as $key => $value) { if ($characteristics_group = $value['group']) { $form['cid'] = [ '#type' => 'select', '#title' => $this->t('@value', ['@value' => $characteristics_group->title]), '#options' => $site_commerce_database->characteristicsProductReadItems($pid, $characteristics_group->gid), '#empty_option' => $this->t('- None -'), '#ajax' => [ 'callback' => [$this, 'ajaxCallChangeSelectCharacteristic'], 'progress' => [], ], ]; } } // Добавляем нашу кнопку для отправки. $label_add = trim($position->get('field_cart')->label_add); $form['actions']['#type'] = 'actions'; $form['actions']['#attributes'] = array('class' => ['site-orders-add-cart-form__actions']); $form['actions']['submit'] = array( '#type' => 'submit', '#value' => $this->t($label_add), '#button_type' => 'primary', '#ajax' => [ 'callback' => '::ajaxSubmitCallback', 'progress' => array(), ], '#attributes' => array('class' => ['site-orders-add-cart-form__submit']), '#suffix' => '<div class="site-orders-add-cart-form__submit-note"></div>', '#access' => $label_add ? TRUE : FALSE, ); $form['actions']['buy_one_click'] = [ '#title' => $this->t($position->get('field_cart')->label_click), '#type' => 'link', '#url' => Url::fromUserInput('#javascript:void(0);'), '#prefix' => '<div class="site-orders-add-cart-form__buy-one-click">', '#suffix' => '</div>', '#attributes' => $label_add ? array('class' => ['site-orders-add-cart-form__buy-one-click-link']) : array('class' => ['site-orders-add-cart-form__buy-one-click-link site-orders-add-cart-form__buy-one-click-btn']), ]; $form['buy'] = array( '#prefix' => '<div class="site-orders-add-cart-form__buy site-orders-add-cart-form__buy_hide">', '#suffix' => '</div>', ); $form['buy']['close'] = array( '#markup' => '<span class="site-orders-form__close site-orders-add-cart-form__close"></span>', ); $form['buy']['title'] = array( '#markup' => '<h2>' . $this->t('Write phone number') . '</h2>' . $this->t('We calculate the cost of checkout.'), ); // Поле телефон. $form['buy']['phone'] = array( '#type' => 'tel', '#title' => $this->t('Phone number'), '#required' => FALSE, '#description' => '', '#attributes' => $config->get('phone_mask') ? ['class' => ['phone-mask']] : [], '#suffix' => '<div class="site-orders-form__phone-validation-order"></div>', ); // Соглашение об обработке персональных данных. if ($data_policy_information = $config->get('text_data_policy')) { $form['buy']['data_policy'] = array( '#type' => 'checkbox', '#attributes' => array('class' => array('site-orders-form__data-policy')), '#default_value' => 1, '#prefix' => '<div class="site-orders-form__data-policy-block">', '#ajax' => [ 'callback' => '::validateDataPolicy', 'event' => 'change', 'progress' => array( 'message' => NULL, ), ], ); $data_policy_information = str_replace("@submit_label", $this->t('Send request'), $data_policy_information); $nid = $config->get('node_agreement_personal_data'); $data_policy_information = str_replace("@data_policy_url", "/node/" . $nid, $data_policy_information); $form['buy']['data_policy_information'] = array( '#markup' => $data_policy_information, '#suffix' => '</div>', ); } // Добавляем нашу кнопку для отправки заявки. $form['buy']['actions']['#type'] = 'actions'; $form['buy']['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Send request'), '#button_type' => 'primary', '#ajax' => [ 'callback' => '::ajaxSubmitBuyCallback', 'progress' => [], ], '#attributes' => array('class' => array('site-orders-form__submit')), '#suffix' => '<div class="site-orders-form__submit-label"></div>', ]; $form['#attached']['library'][] = 'site_orders/module'; $form['#attached']['library'][] = 'kvantstudio/mask'; // TODO: Сделать блокировку загрузки если не используется маска. return $form; }
{@inheritdoc}.
https://github.com/kvantstudio/site_orders/blob/ed670d41f1ed044e740001aa46b8a1aa79bc0a7a/src/Form/SiteOrdersAddCartForm.php#L58-L222
kvantstudio/site_orders
src/Form/SiteOrdersAddCartForm.php
SiteOrdersAddCartForm.ajaxCallChangeSelectCharacteristic
public function ajaxCallChangeSelectCharacteristic(array &$form, FormStateInterface $form_state) { $response = new AjaxResponse(); // Получаем значение выбранного элемента. $element = $form_state->getTriggeringElement(); $value = $element['#value']; if ($value) { // Товар и идентификатор. $position = $form_state->getValue('position'); $pid = $position->id(); $site_commerce_database = \Drupal::service('site_commerce.database'); $characteristic = $site_commerce_database->characteristicDataReadItem($pid, $value); // Изменяем изображение товара. if ($fid = $characteristic->fid) { $file = file_load($fid); $style = \Drupal::entityTypeManager()->getStorage('image_style')->load('product_main'); $url_style = $style->buildUrl($file->getFileUri()); $url = Url::fromUri($file->getFileUri()); $variables['image'] = [ '#theme' => 'image_style', '#style_name' => 'product_main', '#uri' => $file->getFileUri(), ]; $response->addCommand(new HtmlCommand('.product__images', $variables)); } } return $response; }
php
public function ajaxCallChangeSelectCharacteristic(array &$form, FormStateInterface $form_state) { $response = new AjaxResponse(); // Получаем значение выбранного элемента. $element = $form_state->getTriggeringElement(); $value = $element['#value']; if ($value) { // Товар и идентификатор. $position = $form_state->getValue('position'); $pid = $position->id(); $site_commerce_database = \Drupal::service('site_commerce.database'); $characteristic = $site_commerce_database->characteristicDataReadItem($pid, $value); // Изменяем изображение товара. if ($fid = $characteristic->fid) { $file = file_load($fid); $style = \Drupal::entityTypeManager()->getStorage('image_style')->load('product_main'); $url_style = $style->buildUrl($file->getFileUri()); $url = Url::fromUri($file->getFileUri()); $variables['image'] = [ '#theme' => 'image_style', '#style_name' => 'product_main', '#uri' => $file->getFileUri(), ]; $response->addCommand(new HtmlCommand('.product__images', $variables)); } } return $response; }
Ajax callback.
https://github.com/kvantstudio/site_orders/blob/ed670d41f1ed044e740001aa46b8a1aa79bc0a7a/src/Form/SiteOrdersAddCartForm.php#L227-L261
kvantstudio/site_orders
src/Form/SiteOrdersAddCartForm.php
SiteOrdersAddCartForm.submitForm
public function submitForm(array &$form, FormStateInterface $form_state) { $group = $form_state->getValue('group'); $position = $form_state->getValue('position'); $cost = getCostValueForUserPriceGroup($position, $group, FALSE, TRUE); }
php
public function submitForm(array &$form, FormStateInterface $form_state) { $group = $form_state->getValue('group'); $position = $form_state->getValue('position'); $cost = getCostValueForUserPriceGroup($position, $group, FALSE, TRUE); }
{@inheritdoc}
https://github.com/kvantstudio/site_orders/blob/ed670d41f1ed044e740001aa46b8a1aa79bc0a7a/src/Form/SiteOrdersAddCartForm.php#L272-L276
kvantstudio/site_orders
src/Form/SiteOrdersAddCartForm.php
SiteOrdersAddCartForm.ajaxSubmitCallback
public function ajaxSubmitCallback(array &$form, FormStateInterface $form_state) { $response = new AjaxResponse(); // Выполняет стандартную валидацию полей формы и добавляет примечания об ошибках. FormBase::validateForm($form, $form_state); if (!$form_state->getValue('validate_error')) { $position = $form_state->getValue('position'); $type = $position->getEntityTypeId(); $pid = $position->id(); $quantity = trim($form_state->getValue('quantity')); if (!$quantity || $quantity < 0) { $quantity = $position->get('field_quantity')->min; } if ($quantity < $position->get('field_quantity')->min) { $quantity = $position->get('field_quantity')->min; } $group = $form_state->getValue('group'); $cost = getCostValueForUserPriceGroup($position, $group, FALSE, TRUE); // Регистрирует позицию в корзине. if ($cost) { $this->databaseSendOrder->createCartPosition($type, $pid, 0, $quantity, $cost); // Загрузка формы действия после добавления в корзину. $response->addCommand(new InvokeCommand('.product__cart-data', 'hide', array(''))); $response->addCommand(new InvokeCommand('.product__cart-data-event', 'removeClass', array('product__cart-data-event_hide'))); } } else { $text = '<i class="fa fa-info" aria-hidden="true"></i> ' . $this->t('Fill in the correct form field.'); $response->addCommand(new HtmlCommand('.site-orders-add-cart-form__submit-note', $text)); } return $response; }
php
public function ajaxSubmitCallback(array &$form, FormStateInterface $form_state) { $response = new AjaxResponse(); // Выполняет стандартную валидацию полей формы и добавляет примечания об ошибках. FormBase::validateForm($form, $form_state); if (!$form_state->getValue('validate_error')) { $position = $form_state->getValue('position'); $type = $position->getEntityTypeId(); $pid = $position->id(); $quantity = trim($form_state->getValue('quantity')); if (!$quantity || $quantity < 0) { $quantity = $position->get('field_quantity')->min; } if ($quantity < $position->get('field_quantity')->min) { $quantity = $position->get('field_quantity')->min; } $group = $form_state->getValue('group'); $cost = getCostValueForUserPriceGroup($position, $group, FALSE, TRUE); // Регистрирует позицию в корзине. if ($cost) { $this->databaseSendOrder->createCartPosition($type, $pid, 0, $quantity, $cost); // Загрузка формы действия после добавления в корзину. $response->addCommand(new InvokeCommand('.product__cart-data', 'hide', array(''))); $response->addCommand(new InvokeCommand('.product__cart-data-event', 'removeClass', array('product__cart-data-event_hide'))); } } else { $text = '<i class="fa fa-info" aria-hidden="true"></i> ' . $this->t('Fill in the correct form field.'); $response->addCommand(new HtmlCommand('.site-orders-add-cart-form__submit-note', $text)); } return $response; }
{@inheritdoc}
https://github.com/kvantstudio/site_orders/blob/ed670d41f1ed044e740001aa46b8a1aa79bc0a7a/src/Form/SiteOrdersAddCartForm.php#L298-L336
kvantstudio/site_orders
src/Form/SiteOrdersAddCartForm.php
SiteOrdersAddCartForm.ajaxSubmitBuyCallback
public function ajaxSubmitBuyCallback(array &$form, FormStateInterface $form_state) { $response = new AjaxResponse(); // Выполняет стандартную валидацию полей формы и добавляет примечания об ошибках. FormBase::validateForm($form, $form_state); // Выполняет дополнительную валидацию полей формы. $error = FALSE; $phone = trim($form_state->getValue('phone')); if (!$phone) { $response->addCommand(new HtmlCommand('.site-orders-form__phone-validation-order', '<i class="fa fa-exclamation-circle" aria-hidden="true"></i> ' . $this->t('It should be filled.'))); $error = TRUE; } else { $response->addCommand(new HtmlCommand('.site-orders-form__phone-validation-order', '')); $error = FALSE; } if (!drupal_get_messages() && !$form_state->getValue('validate_error') && !$error) { // Блокирует кнопку отправки формы. $response->addCommand(new InvokeCommand('.site-orders-form__submit', 'attr', array(['disabled' => 'disabled']))); $loader = '<div style="text-align: center;"><span class="ouro ouro3"><span class="left"><span class="anim"></span></span><span class="right"><span class="anim"></span></span></span></div>'; $response->addCommand(new InvokeCommand('.form-actions', 'html', array($loader))); $position = $form_state->getValue('position'); $type = $position->getEntityTypeId(); $pid = $position->id(); $quantity = trim($form_state->getValue('quantity')); if (!$quantity || $quantity < 0) { $quantity = $position->get('field_quantity')->min; } if ($quantity < $position->get('field_quantity')->min) { $quantity = $position->get('field_quantity')->min; } // Стоимость. $cost = (float) $form_state->getValue('cost'); // Регистрирует позицию в корзине. $this->databaseSendOrder->createCartPosition($type, $pid, 0, $quantity, $cost); // Регистрирует заказ. $data = [ 'name' => "", 'phone' => $phone, 'mail' => "", 'address' => "", 'comment' => "", ]; $insert_id = $this->databaseSendOrder->createOrder($data); // Уведомление об успешной отправке формы и очистка полей. if ($insert_id) { // Отправка сообщения о заказе на почту. site_orders_to_email($insert_id); // Редирект на страницу уведомления о заказе. $route_name = 'site_orders.order_successfully_issued'; $response->addCommand(new RedirectCommand($this->url($route_name, ['order' => $insert_id]))); } } else { $text = '<i class="fa fa-info" aria-hidden="true"></i> ' . $this->t('Fill in the correct form field.'); $response->addCommand(new HtmlCommand('.site-orders-form__submit-label', $text)); } return $response; }
php
public function ajaxSubmitBuyCallback(array &$form, FormStateInterface $form_state) { $response = new AjaxResponse(); // Выполняет стандартную валидацию полей формы и добавляет примечания об ошибках. FormBase::validateForm($form, $form_state); // Выполняет дополнительную валидацию полей формы. $error = FALSE; $phone = trim($form_state->getValue('phone')); if (!$phone) { $response->addCommand(new HtmlCommand('.site-orders-form__phone-validation-order', '<i class="fa fa-exclamation-circle" aria-hidden="true"></i> ' . $this->t('It should be filled.'))); $error = TRUE; } else { $response->addCommand(new HtmlCommand('.site-orders-form__phone-validation-order', '')); $error = FALSE; } if (!drupal_get_messages() && !$form_state->getValue('validate_error') && !$error) { // Блокирует кнопку отправки формы. $response->addCommand(new InvokeCommand('.site-orders-form__submit', 'attr', array(['disabled' => 'disabled']))); $loader = '<div style="text-align: center;"><span class="ouro ouro3"><span class="left"><span class="anim"></span></span><span class="right"><span class="anim"></span></span></span></div>'; $response->addCommand(new InvokeCommand('.form-actions', 'html', array($loader))); $position = $form_state->getValue('position'); $type = $position->getEntityTypeId(); $pid = $position->id(); $quantity = trim($form_state->getValue('quantity')); if (!$quantity || $quantity < 0) { $quantity = $position->get('field_quantity')->min; } if ($quantity < $position->get('field_quantity')->min) { $quantity = $position->get('field_quantity')->min; } // Стоимость. $cost = (float) $form_state->getValue('cost'); // Регистрирует позицию в корзине. $this->databaseSendOrder->createCartPosition($type, $pid, 0, $quantity, $cost); // Регистрирует заказ. $data = [ 'name' => "", 'phone' => $phone, 'mail' => "", 'address' => "", 'comment' => "", ]; $insert_id = $this->databaseSendOrder->createOrder($data); // Уведомление об успешной отправке формы и очистка полей. if ($insert_id) { // Отправка сообщения о заказе на почту. site_orders_to_email($insert_id); // Редирект на страницу уведомления о заказе. $route_name = 'site_orders.order_successfully_issued'; $response->addCommand(new RedirectCommand($this->url($route_name, ['order' => $insert_id]))); } } else { $text = '<i class="fa fa-info" aria-hidden="true"></i> ' . $this->t('Fill in the correct form field.'); $response->addCommand(new HtmlCommand('.site-orders-form__submit-label', $text)); } return $response; }
{@inheritdoc}
https://github.com/kvantstudio/site_orders/blob/ed670d41f1ed044e740001aa46b8a1aa79bc0a7a/src/Form/SiteOrdersAddCartForm.php#L341-L410
imatic/controller-bundle
Resource/ConfigurationProcessor.php
ConfigurationProcessor.arrayMap
public static function arrayMap(callable $callback, array $array) { foreach ($array as $key => $value) { $array[$key] = \call_user_func($callback, $value, $key); } return $array; }
php
public static function arrayMap(callable $callback, array $array) { foreach ($array as $key => $value) { $array[$key] = \call_user_func($callback, $value, $key); } return $array; }
- array keys are available in callback - array keys have not been changed
https://github.com/imatic/controller-bundle/blob/df71c12166928f9d4f1548d4ee1e09a183a68eb6/Resource/ConfigurationProcessor.php#L203-L210
smalldb/libSmalldb
class/Graph/Graph.php
Graph.getNodesByAttr
public function getNodesByAttr(string $key, $value = true): array { return $this->nodeAttrIndex->getElements($key, $value); }
php
public function getNodesByAttr(string $key, $value = true): array { return $this->nodeAttrIndex->getElements($key, $value); }
Get nodes which have attribute $key equal to $value @param string $key @param mixed $value @return Node[]
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Graph/Graph.php#L83-L86
smalldb/libSmalldb
class/Graph/Graph.php
Graph.getEdgesByAttr
public function getEdgesByAttr(string $key, $value = true): array { return $this->edgeAttrIndex->getElements($key, $value); }
php
public function getEdgesByAttr(string $key, $value = true): array { return $this->edgeAttrIndex->getElements($key, $value); }
Get edges which have attribute $key equal to $value @param string $key @param mixed $value @return Node[]
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/Graph/Graph.php#L96-L99
codemaxbr/reliese
src/Coders/Model/Factory.php
Factory.fillTemplate
protected function fillTemplate($template, Model $model) { $template = str_replace('{{date}}', Carbon::now()->toRssString(), $template); $template = str_replace('{{namespace}}', $model->getBaseNamespace(), $template); $template = str_replace('{{parent}}', $model->getParentClass(), $template); $template = str_replace('{{properties}}', $this->properties($model), $template); $template = str_replace('{{class}}', $model->getClassName(), $template); $template = str_replace('{{body}}', $this->body($model), $template); return $template; }
php
protected function fillTemplate($template, Model $model) { $template = str_replace('{{date}}', Carbon::now()->toRssString(), $template); $template = str_replace('{{namespace}}', $model->getBaseNamespace(), $template); $template = str_replace('{{parent}}', $model->getParentClass(), $template); $template = str_replace('{{properties}}', $this->properties($model), $template); $template = str_replace('{{class}}', $model->getClassName(), $template); $template = str_replace('{{body}}', $this->body($model), $template); return $template; }
@param string $template @param \Codemax\Coders\Model\Model $model @return mixed
https://github.com/codemaxbr/reliese/blob/efaac021ba4d936edd7e9fda2bd7bcdac18d8497/src/Coders/Model/Factory.php#L226-L236
liufee/cms-core
frontend/controllers/ArticleController.php
ArticleController.actionIndex
public function actionIndex($cat = '') { yii::$app->setViewPath('@cms/frontend/views'); if ($cat == '') { $cat = yii::$app->getRequest()->getPathInfo(); } $where = ['type' => Article::ARTICLE, 'status' => Article::ARTICLE_PUBLISHED]; if ($cat != '' && $cat != 'index') { if ($cat == yii::t('cms', 'uncategoried')) { $where['cid'] = 0; } else { if (! $category = Category::findOne(['alias' => $cat])) { throw new NotFoundHttpException(yii::t('cms', 'None category named {name}', ['name' => $cat])); } $descendants = Category::getDescendants($category['id']); if( empty($descendants) ) { $where['cid'] = $category['id']; }else{ $cids = ArrayHelper::getColumn($descendants, 'id'); $cids[] = $category['id']; $where['cid'] = $cids; } } } $query = Article::find()->with('category')->where($where); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'sort' => [ 'defaultOrder' => [ 'sort' => SORT_ASC, 'created_at' => SORT_DESC, 'id' => SORT_DESC, ] ] ]); return $this->render('index', [ 'dataProvider' => $dataProvider, 'type' => ( !empty($cat) ? yii::t('cms', 'Category {cat} articles', ['cat'=>$cat]) : yii::t('cms', 'Latest Articles') ), ]); }
php
public function actionIndex($cat = '') { yii::$app->setViewPath('@cms/frontend/views'); if ($cat == '') { $cat = yii::$app->getRequest()->getPathInfo(); } $where = ['type' => Article::ARTICLE, 'status' => Article::ARTICLE_PUBLISHED]; if ($cat != '' && $cat != 'index') { if ($cat == yii::t('cms', 'uncategoried')) { $where['cid'] = 0; } else { if (! $category = Category::findOne(['alias' => $cat])) { throw new NotFoundHttpException(yii::t('cms', 'None category named {name}', ['name' => $cat])); } $descendants = Category::getDescendants($category['id']); if( empty($descendants) ) { $where['cid'] = $category['id']; }else{ $cids = ArrayHelper::getColumn($descendants, 'id'); $cids[] = $category['id']; $where['cid'] = $cids; } } } $query = Article::find()->with('category')->where($where); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'sort' => [ 'defaultOrder' => [ 'sort' => SORT_ASC, 'created_at' => SORT_DESC, 'id' => SORT_DESC, ] ] ]); return $this->render('index', [ 'dataProvider' => $dataProvider, 'type' => ( !empty($cat) ? yii::t('cms', 'Category {cat} articles', ['cat'=>$cat]) : yii::t('cms', 'Latest Articles') ), ]); }
分类列表页 @param string $cat 分类名称 @return string @throws \yii\web\NotFoundHttpException
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/frontend/controllers/ArticleController.php#L55-L94
liufee/cms-core
frontend/controllers/ArticleController.php
ArticleController.actionView
public function actionView($id) { $model = Article::findOne(['id' => $id, 'type' => Article::ARTICLE, 'status' => Article::ARTICLE_PUBLISHED]); if( $model === null ) throw new NotFoundHttpException(yii::t("frontend", "Article id {id} is not exists", ['id' => $id])); $prev = Article::find() ->where(['cid' => $model->cid]) ->andWhere(['>', 'id', $id]) ->orderBy("sort asc,created_at desc,id desc") ->limit(1) ->one(); $next = Article::find() ->where(['cid' => $model->cid]) ->andWhere(['<', 'id', $id]) ->orderBy("sort desc,created_at desc,id asc") ->limit(1) ->one();//->createCommand()->getRawSql(); $commentModel = new Comment(); $commentList = $commentModel->getCommentByAid($id); $recommends = Article::find() ->where(['type' => Article::ARTICLE, 'status' => Article::ARTICLE_PUBLISHED]) ->andWhere(['<>', 'thumb', '']) ->orderBy("rand()") ->limit(8) ->all(); switch ($model->visibility){ case Constants::ARTICLE_VISIBILITY_COMMENT://评论可见 if( yii::$app->getUser()->getIsGuest() ){ $result = Comment::find()->where(['aid'=>$model->id, 'ip'=>yii::$app->getRequest()->getUserIP()])->one(); }else{ $result = Comment::find()->where(['aid'=>$model->id, 'uid'=>yii::$app->getUser()->getId()])->one(); } if( $result === null ) { $model->articleContent->content = "<p style='color: red'>" . yii::t('cms', "Only commented user can visit this article") . "</p>"; } break; case Constants::ARTICLE_VISIBILITY_SECRET://加密文章 $authorized = yii::$app->getSession()->get("article_password_" . $model->id, null); if( $authorized === null ) $this->redirect(Url::toRoute(['password', 'id'=>$id])); break; case Constants::ARTICLE_VISIBILITY_LOGIN://登陆可见 if( yii::$app->getUser()->getIsGuest() ) { $model->articleContent->content = "<p style='color: red'>" . yii::t('cms', "Only login user can visit this article") . "</p>"; } break; } return $this->render('view', [ 'model' => $model, 'prev' => $prev, 'next' => $next, 'recommends' => $recommends, 'commentModel' => $commentModel, 'commentList' => $commentList, ]); }
php
public function actionView($id) { $model = Article::findOne(['id' => $id, 'type' => Article::ARTICLE, 'status' => Article::ARTICLE_PUBLISHED]); if( $model === null ) throw new NotFoundHttpException(yii::t("frontend", "Article id {id} is not exists", ['id' => $id])); $prev = Article::find() ->where(['cid' => $model->cid]) ->andWhere(['>', 'id', $id]) ->orderBy("sort asc,created_at desc,id desc") ->limit(1) ->one(); $next = Article::find() ->where(['cid' => $model->cid]) ->andWhere(['<', 'id', $id]) ->orderBy("sort desc,created_at desc,id asc") ->limit(1) ->one();//->createCommand()->getRawSql(); $commentModel = new Comment(); $commentList = $commentModel->getCommentByAid($id); $recommends = Article::find() ->where(['type' => Article::ARTICLE, 'status' => Article::ARTICLE_PUBLISHED]) ->andWhere(['<>', 'thumb', '']) ->orderBy("rand()") ->limit(8) ->all(); switch ($model->visibility){ case Constants::ARTICLE_VISIBILITY_COMMENT://评论可见 if( yii::$app->getUser()->getIsGuest() ){ $result = Comment::find()->where(['aid'=>$model->id, 'ip'=>yii::$app->getRequest()->getUserIP()])->one(); }else{ $result = Comment::find()->where(['aid'=>$model->id, 'uid'=>yii::$app->getUser()->getId()])->one(); } if( $result === null ) { $model->articleContent->content = "<p style='color: red'>" . yii::t('cms', "Only commented user can visit this article") . "</p>"; } break; case Constants::ARTICLE_VISIBILITY_SECRET://加密文章 $authorized = yii::$app->getSession()->get("article_password_" . $model->id, null); if( $authorized === null ) $this->redirect(Url::toRoute(['password', 'id'=>$id])); break; case Constants::ARTICLE_VISIBILITY_LOGIN://登陆可见 if( yii::$app->getUser()->getIsGuest() ) { $model->articleContent->content = "<p style='color: red'>" . yii::t('cms', "Only login user can visit this article") . "</p>"; } break; } return $this->render('view', [ 'model' => $model, 'prev' => $prev, 'next' => $next, 'recommends' => $recommends, 'commentModel' => $commentModel, 'commentList' => $commentList, ]); }
文章详情 @param $id @return string @throws \yii\web\NotFoundHttpException
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/frontend/controllers/ArticleController.php#L103-L156
liufee/cms-core
frontend/controllers/ArticleController.php
ArticleController.actionViewAjax
public function actionViewAjax($id) { $model = Article::findOne($id); if( $model === null ) throw new NotFoundHttpException("None exists article id"); return [ 'likeCount' => (int)$model->getArticleLikeCount(), 'scanCount' => $model->scan_count * 100, 'commentCount' => $model->comment_count, ]; }
php
public function actionViewAjax($id) { $model = Article::findOne($id); if( $model === null ) throw new NotFoundHttpException("None exists article id"); return [ 'likeCount' => (int)$model->getArticleLikeCount(), 'scanCount' => $model->scan_count * 100, 'commentCount' => $model->comment_count, ]; }
获取文章的点赞数和浏览数 @param $id @return array @throws NotFoundHttpException
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/frontend/controllers/ArticleController.php#L165-L174
liufee/cms-core
frontend/controllers/ArticleController.php
ArticleController.actionComment
public function actionComment() { if (yii::$app->getRequest()->getIsPost()) { $commentModel = new Comment(); if ($commentModel->load(yii::$app->getRequest()->post()) && $commentModel->save()) { $avatar = 'https://secure.gravatar.com/avatar?s=50'; if ($commentModel->email != '') { $avatar = "https://secure.gravatar.com/avatar/" . md5($commentModel->email) . "?s=50"; } $tips = ''; if (yii::$app->feehi->website_comment_need_verify) { $tips = "<span class='c-approved'>" . yii::t('cms', 'Comment waiting for approved.') . "</span><br />"; } $commentModel->afterFind(); return " <li class='comment even thread-even depth-1' id='comment-{$commentModel->id}'> <div class='c-avatar'><img src='{$avatar}' class='avatar avatar-108' height='50' width='50'> <div class='c-main' id='div-comment-{$commentModel->id}'><p>{$commentModel->content}</p> {$tips} <div class='c-meta'><span class='c-author'><a href='{$commentModel->website_url}' rel='external nofollow' class='url'>{$commentModel->nickname}</a></span> (" . yii::t('cms', 'a minutes ago') . ")</div> </div> </div>"; } else { $temp = $commentModel->getErrors(); $str = ''; foreach ($temp as $v) { $str .= $v[0] . "<br>"; } return "<font color='red'>" . $str . "</font>"; } } }
php
public function actionComment() { if (yii::$app->getRequest()->getIsPost()) { $commentModel = new Comment(); if ($commentModel->load(yii::$app->getRequest()->post()) && $commentModel->save()) { $avatar = 'https://secure.gravatar.com/avatar?s=50'; if ($commentModel->email != '') { $avatar = "https://secure.gravatar.com/avatar/" . md5($commentModel->email) . "?s=50"; } $tips = ''; if (yii::$app->feehi->website_comment_need_verify) { $tips = "<span class='c-approved'>" . yii::t('cms', 'Comment waiting for approved.') . "</span><br />"; } $commentModel->afterFind(); return " <li class='comment even thread-even depth-1' id='comment-{$commentModel->id}'> <div class='c-avatar'><img src='{$avatar}' class='avatar avatar-108' height='50' width='50'> <div class='c-main' id='div-comment-{$commentModel->id}'><p>{$commentModel->content}</p> {$tips} <div class='c-meta'><span class='c-author'><a href='{$commentModel->website_url}' rel='external nofollow' class='url'>{$commentModel->nickname}</a></span> (" . yii::t('cms', 'a minutes ago') . ")</div> </div> </div>"; } else { $temp = $commentModel->getErrors(); $str = ''; foreach ($temp as $v) { $str .= $v[0] . "<br>"; } return "<font color='red'>" . $str . "</font>"; } } }
评论
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/frontend/controllers/ArticleController.php#L180-L211
liufee/cms-core
frontend/controllers/ArticleController.php
ArticleController.actionLike
public function actionLike() { $aid = yii::$app->getRequest()->post("aid"); $model = new ArticleMetaLike(); $model->setLike($aid); return $model->getLikeCount($aid); }
php
public function actionLike() { $aid = yii::$app->getRequest()->post("aid"); $model = new ArticleMetaLike(); $model->setLike($aid); return $model->getLikeCount($aid); }
点赞 @return int|string
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/frontend/controllers/ArticleController.php#L236-L243
liufee/cms-core
frontend/controllers/ArticleController.php
ArticleController.actionRss
public function actionRss() { $xml['channel']['title'] = yii::$app->feehi->website_title; $xml['channel']['description'] = yii::$app->feehi->seo_description; $xml['channel']['lin'] = yii::$app->getUrlManager()->getHostInfo(); $xml['channel']['generator'] = yii::$app->getUrlManager()->getHostInfo(); $models = Article::find()->limit(10)->where(['status'=>Article::ARTICLE_PUBLISHED, 'type'=>Article::ARTICLE])->orderBy('id desc')->all(); foreach ($models as $model){ $xml['channel']['item'][] = [ 'title' => $model->title, 'link' => Url::to(['article/view', 'id'=>$model->id]), 'pubData' => date('Y-m-d H:i:s', $model->created_at), 'source' => yii::$app->feehi->website_title, 'author' => $model->author_name, 'description' => $model->summary, ]; } yii::configure(yii::$app->getResponse(), [ 'formatters' => [ Response::FORMAT_XML => [ 'class' => XmlResponseFormatter::className(), 'rootTag' => 'rss', 'version' => '1.0', 'encoding' => 'utf-8' ] ] ]); yii::$app->getResponse()->format = Response::FORMAT_XML; return $xml; }
php
public function actionRss() { $xml['channel']['title'] = yii::$app->feehi->website_title; $xml['channel']['description'] = yii::$app->feehi->seo_description; $xml['channel']['lin'] = yii::$app->getUrlManager()->getHostInfo(); $xml['channel']['generator'] = yii::$app->getUrlManager()->getHostInfo(); $models = Article::find()->limit(10)->where(['status'=>Article::ARTICLE_PUBLISHED, 'type'=>Article::ARTICLE])->orderBy('id desc')->all(); foreach ($models as $model){ $xml['channel']['item'][] = [ 'title' => $model->title, 'link' => Url::to(['article/view', 'id'=>$model->id]), 'pubData' => date('Y-m-d H:i:s', $model->created_at), 'source' => yii::$app->feehi->website_title, 'author' => $model->author_name, 'description' => $model->summary, ]; } yii::configure(yii::$app->getResponse(), [ 'formatters' => [ Response::FORMAT_XML => [ 'class' => XmlResponseFormatter::className(), 'rootTag' => 'rss', 'version' => '1.0', 'encoding' => 'utf-8' ] ] ]); yii::$app->getResponse()->format = Response::FORMAT_XML; return $xml; }
rss订阅 @return mixed
https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/frontend/controllers/ArticleController.php#L250-L279
danhanly/signalert
src/Signalert/Config.php
Config.expandConfigDirectories
private function expandConfigDirectories() { $newPaths = []; foreach ($this->configDirectories as $filePath) { $newPaths[] = __DIR__ . '/../../../../../' . $filePath; } $this->configDirectories = $newPaths; }
php
private function expandConfigDirectories() { $newPaths = []; foreach ($this->configDirectories as $filePath) { $newPaths[] = __DIR__ . '/../../../../../' . $filePath; } $this->configDirectories = $newPaths; }
Ensures that config directories are relative paths
https://github.com/danhanly/signalert/blob/21ee50e3fc0352306a2966b555984b5c9eada582/src/Signalert/Config.php#L114-L121
digipolisgent/robo-digipolis-deploy
src/Common/DatabaseCommand.php
DatabaseCommand.createDbTask
protected function createDbTask($task, $database, $opts) { $filesystemConfig = $opts['file-system-config'] ? : $this->defaultFileSystemConfig(); $dbConfig = $opts['database-config'] ? : $this->defaultDbConfig(); return $this->{$task}($filesystemConfig, $dbConfig) ->compression($opts['compression']) ->database($database); }
php
protected function createDbTask($task, $database, $opts) { $filesystemConfig = $opts['file-system-config'] ? : $this->defaultFileSystemConfig(); $dbConfig = $opts['database-config'] ? : $this->defaultDbConfig(); return $this->{$task}($filesystemConfig, $dbConfig) ->compression($opts['compression']) ->database($database); }
Apply the database argument and the correct options to the database task. @param string $task The task method to call. @param string $database The database argument. @param array $opts The command options. @return TaskInterface The task with the arguments and options applied.
https://github.com/digipolisgent/robo-digipolis-deploy/blob/fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab/src/Common/DatabaseCommand.php#L46-L58
apitude/user
src/OAuth/OauthProviderTrait.php
OauthProviderTrait.requireAuthorization
protected function requireAuthorization(Application $app) { /** @var ResourceServer $server */ $server = $app[ResourceServer::class]; try { $server->isValidRequest(false); } catch(OAuthException $e) { return new JsonResponse( [ 'error' => $e->errorType, 'message' => $e->getMessage(), ], $e->httpStatusCode, $e->getHttpHeaders() ); } return null; }
php
protected function requireAuthorization(Application $app) { /** @var ResourceServer $server */ $server = $app[ResourceServer::class]; try { $server->isValidRequest(false); } catch(OAuthException $e) { return new JsonResponse( [ 'error' => $e->errorType, 'message' => $e->getMessage(), ], $e->httpStatusCode, $e->getHttpHeaders() ); } return null; }
Middleware to be used in before() @param Application $app @return JsonResponse
https://github.com/apitude/user/blob/24adf733cf628d321c2bcae328c383113928d019/src/OAuth/OauthProviderTrait.php#L18-L35
apitude/user
src/OAuth/OauthProviderTrait.php
OauthProviderTrait.requireScope
protected function requireScope(Application $app, $scopeName) { /** @var ResourceServer $server */ $server = $app[ResourceServer::class]; if ($response = $this->requireAuthorization($app)) { return $response; } $accessToken = $server->getAccessToken(); if (!$accessToken->hasScope($scopeName)) { return new JsonResponse( [ 'error' => 'UNAUTHORIZED', 'message' => 'Token does not contain scope: '.$scopeName ], Response::HTTP_FORBIDDEN ); } }
php
protected function requireScope(Application $app, $scopeName) { /** @var ResourceServer $server */ $server = $app[ResourceServer::class]; if ($response = $this->requireAuthorization($app)) { return $response; } $accessToken = $server->getAccessToken(); if (!$accessToken->hasScope($scopeName)) { return new JsonResponse( [ 'error' => 'UNAUTHORIZED', 'message' => 'Token does not contain scope: '.$scopeName ], Response::HTTP_FORBIDDEN ); } }
Middleware to be used in before() @param Application $app @param string $scopeName @return JsonResponse
https://github.com/apitude/user/blob/24adf733cf628d321c2bcae328c383113928d019/src/OAuth/OauthProviderTrait.php#L43-L60
neneaX/IoC
src/Container.php
Container.register
public function register($alias, $binding, $shared = false) { $this->registry[$alias] = new Resolver(new Builder($binding), $shared); }
php
public function register($alias, $binding, $shared = false) { $this->registry[$alias] = new Resolver(new Builder($binding), $shared); }
Register a binding with the registry @param string $alias The alias used for registering the binding @param \Closure|object|string|null $binding The binding requested to register @param boolean $shared The type of the binding: shared (singleton) or not
https://github.com/neneaX/IoC/blob/404888c3252880f8bb48253f9aa636cd7c396416/src/Container.php#L108-L111
neneaX/IoC
src/Container.php
Container.resolve
public function resolve($alias, array $parameters = array(), $force = false) { if ($this->registered($alias)) { $resolver = $this->registry[$alias]; return $resolver->execute($parameters, $force); } throw new \Exception('No class found registered with that name: ' . $alias); }
php
public function resolve($alias, array $parameters = array(), $force = false) { if ($this->registered($alias)) { $resolver = $this->registry[$alias]; return $resolver->execute($parameters, $force); } throw new \Exception('No class found registered with that name: ' . $alias); }
Execute the Resolver and return the requested binding instance @param string $alias The registered binding's alias @param array $parameters @param boolean $force Force the overriding of the "shared" option and return a new instance of the requested binding @return object @throws \Exception When no resolver is found for the handle name.
https://github.com/neneaX/IoC/blob/404888c3252880f8bb48253f9aa636cd7c396416/src/Container.php#L134-L143
nasumilu/geometry
src/Serializer/WktFormatFinder.php
WktFormatFinder.findFormat
public function findFormat($argument): ?string { $format = null; if (is_string($argument)) { $pattern = '/point|linestring|polygon|multipoint|multilinestring|multipolygon|geometrycollection/i'; if (1 === preg_match($pattern, $argument)) { if (1 === preg_match('/^(SRID)/i', $argument)) { $format = 'ewkt'; } else { $format = 'wkt'; } } } return $format; }
php
public function findFormat($argument): ?string { $format = null; if (is_string($argument)) { $pattern = '/point|linestring|polygon|multipoint|multilinestring|multipolygon|geometrycollection/i'; if (1 === preg_match($pattern, $argument)) { if (1 === preg_match('/^(SRID)/i', $argument)) { $format = 'ewkt'; } else { $format = 'wkt'; } } } return $format; }
{@inheritDoc}
https://github.com/nasumilu/geometry/blob/000fafe3e61f1d0682952ad236b7486dded65eae/src/Serializer/WktFormatFinder.php#L51-L64
acacha/forge-publish
src/Console/Commands/PublishUpdateAssignment.php
PublishUpdateAssignment.handle
public function handle() { $this->abortCommandExecution(); $this->assignment = $this->argument('assignment') ? $this->argument('assignment') : $this->askAssignment(); $this->assignmentName = $this->argument('name') ? $this->argument('name') : $this->askName(); $this->repository_uri = $this->argument('repository_uri') ? $this->argument('repository_uri') : $this->askRepositoryUri(); $this->repository_type = $this->argument('repository_type') ? $this->argument('repository_type') : $this->askRepositoryType(); $this->forge_site = $this->argument('forge_site') ? $this->argument('forge_site') : $this->askForgeSite(); $this->forge_server = $this->argument('forge_server') ? $this->argument('forge_server') : $this->askForgeServer(); $this->updateAssignment(); }
php
public function handle() { $this->abortCommandExecution(); $this->assignment = $this->argument('assignment') ? $this->argument('assignment') : $this->askAssignment(); $this->assignmentName = $this->argument('name') ? $this->argument('name') : $this->askName(); $this->repository_uri = $this->argument('repository_uri') ? $this->argument('repository_uri') : $this->askRepositoryUri(); $this->repository_type = $this->argument('repository_type') ? $this->argument('repository_type') : $this->askRepositoryType(); $this->forge_site = $this->argument('forge_site') ? $this->argument('forge_site') : $this->askForgeSite(); $this->forge_server = $this->argument('forge_server') ? $this->argument('forge_server') : $this->askForgeServer(); $this->updateAssignment(); }
Execute the console command.
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishUpdateAssignment.php#L111-L123
acacha/forge-publish
src/Console/Commands/PublishUpdateAssignment.php
PublishUpdateAssignment.updateAssignment
protected function updateAssignment() { $uri = str_replace('{assignment}', $this->assignment, config('forge-publish.update_assignment_uri')); $url = config('forge-publish.url') . $uri; try { $response = $this->http->put($url, [ 'form_params' => [ 'name' => $this->assignmentName, 'repository_uri' => $this->repository_uri, 'repository_type' => $this->repository_type, 'forge_site' => $this->forge_site, 'forge_server' => $this->forge_server ], 'headers' => [ 'X-Requested-With' => 'XMLHttpRequest', 'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN') ] ]); } catch (\Exception $e) { $this->error('And error occurs connecting to the api url: ' . $url); $this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase()); return []; } return json_decode((string) $response->getBody()); }
php
protected function updateAssignment() { $uri = str_replace('{assignment}', $this->assignment, config('forge-publish.update_assignment_uri')); $url = config('forge-publish.url') . $uri; try { $response = $this->http->put($url, [ 'form_params' => [ 'name' => $this->assignmentName, 'repository_uri' => $this->repository_uri, 'repository_type' => $this->repository_type, 'forge_site' => $this->forge_site, 'forge_server' => $this->forge_server ], 'headers' => [ 'X-Requested-With' => 'XMLHttpRequest', 'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN') ] ]); } catch (\Exception $e) { $this->error('And error occurs connecting to the api url: ' . $url); $this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase()); return []; } return json_decode((string) $response->getBody()); }
Update assignment. @return array|mixed
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishUpdateAssignment.php#L130-L154