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
|
---|---|---|---|---|---|---|---|
4devs/serializer | DataType/ObjectType.php | ObjectType.denormalize | public function denormalize($data, array $options, array $context = [])
{
if (!$options['data_class'] && !isset($context[$options['key']])) {
throw new MappingException(sprintf('set "data_class" or set context with key "%s"', $options['key']));
}
$dataClass = $options['data_class'] ?: $context[$options['key']];
return $this->getDenormalizer()->denormalize($data, $dataClass, $options['format'], $context);
} | php | public function denormalize($data, array $options, array $context = [])
{
if (!$options['data_class'] && !isset($context[$options['key']])) {
throw new MappingException(sprintf('set "data_class" or set context with key "%s"', $options['key']));
}
$dataClass = $options['data_class'] ?: $context[$options['key']];
return $this->getDenormalizer()->denormalize($data, $dataClass, $options['format'], $context);
} | {@inheritdoc} | https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/DataType/ObjectType.php#L29-L37 |
4devs/serializer | DataType/ObjectType.php | ObjectType.normalize | public function normalize($object, array $options, array $context = [])
{
$data = null;
if (!isset($context[self::KEY_MAX_DEPTH]) || $context[self::KEY_MAX_DEPTH] > 0) {
$context[self::KEY_MAX_DEPTH] = isset($context[self::KEY_MAX_DEPTH]) ? $context[self::KEY_MAX_DEPTH] - 1 : $options['max_depth'];
$data = $this->getNormalizer()->normalize($object, $options['format'], $context);
}
return $data;
} | php | public function normalize($object, array $options, array $context = [])
{
$data = null;
if (!isset($context[self::KEY_MAX_DEPTH]) || $context[self::KEY_MAX_DEPTH] > 0) {
$context[self::KEY_MAX_DEPTH] = isset($context[self::KEY_MAX_DEPTH]) ? $context[self::KEY_MAX_DEPTH] - 1 : $options['max_depth'];
$data = $this->getNormalizer()->normalize($object, $options['format'], $context);
}
return $data;
} | {@inheritdoc} | https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/DataType/ObjectType.php#L42-L51 |
4devs/serializer | DataType/ObjectType.php | ObjectType.configureOptions | public function configureOptions(OptionsResolver $resolver)
{
$resolver
->setDefined(['max_depth', 'format', 'data_class', 'key'])
->setDefaults([
'max_depth' => 2,
'format' => null,
'data_class' => null,
'key' => 'data_class',
])
->addAllowedTypes('data_class', ['string', 'null'])
->addAllowedTypes('key', ['string'])
->addAllowedTypes('max_depth', ['integer'])
->addAllowedTypes('format', ['integer', 'null']);
} | php | public function configureOptions(OptionsResolver $resolver)
{
$resolver
->setDefined(['max_depth', 'format', 'data_class', 'key'])
->setDefaults([
'max_depth' => 2,
'format' => null,
'data_class' => null,
'key' => 'data_class',
])
->addAllowedTypes('data_class', ['string', 'null'])
->addAllowedTypes('key', ['string'])
->addAllowedTypes('max_depth', ['integer'])
->addAllowedTypes('format', ['integer', 'null']);
} | {@inheritdoc} | https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/DataType/ObjectType.php#L56-L70 |
schpill/thin | src/Phonetic.php | Phonetic.setTolerance | public function setTolerance($tolerance = 0.20)
{
if ($tolerance < 0 || $tolerance > 1) {
return false;
}
$this->_tolerance = round($tolerance, 2);
return $this;
} | php | public function setTolerance($tolerance = 0.20)
{
if ($tolerance < 0 || $tolerance > 1) {
return false;
}
$this->_tolerance = round($tolerance, 2);
return $this;
} | Set fault tolerance for what is considered 'similar'.
@param float $tol a percentage setting how close the strings need to be to be considered similar. | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Phonetic.php#L43-L52 |
schpill/thin | src/Phonetic.php | Phonetic.similarity | public function similarity($string = null, $cmp = null, $language = 'french')
{
if (empty($string) || empty($cmp)) {
return false;
}
if (strlen($string) > 255 || strlen($cmp) > 255) {
return false;
}
$processedStr = $this->phoneme($string, $language);
$processedCmp = $this->phoneme($cmp, $language);
$score = levenshtein($processedStr, $processedCmp);
$smaller = strlen($processedStr) < strlen($processedCmp) ? $processedStr : $processedCmp;
$biggest = strlen($processedStr) < strlen($processedCmp) ? $processedCmp : $processedStr;
$phonexStr = $this->getPhonex($string);
$phonexCmp = $this->getPhonex($cmp);
$scorePhonex = ($phonexStr + $phonexCmp) / 2;
if (empty($biggest) || empty($smaller)) {
return false;
}
$contain = strstr($biggest, $smaller);
$avgLength = (strlen($processedStr) + strlen($processedCmp)) / 2;
$finalScore = round((1.0 / $avgLength) * $score, 6);
$finalScore = round(((1 - $finalScore) * 100), 2);
$finalScore = 0 > $finalScore && false !== $contain ? 100 + $finalScore : $finalScore;
$finalScore = 100 < $finalScore ? 100 : $finalScore;
$finalScore = 0 > $finalScore ? 0 : $finalScore;
if ($finalScore / 100 >= $this->_tolerance) {
$grade = 1;
} else {
$grade = 0;
}
$proxMatch = self::checkProx(self::_iconv($string), self::_iconv($cmp));
$pctg = $finalScore > $proxMatch ? $finalScore : $proxMatch;
if (strstr($string, ' ') && strstr($cmp, ' ')) {
$matchWords = self::matchWords(self::_iconv($string), self::_iconv($cmp));
$pctg = $matchWords > $pctg ? $matchWords : $pctg;
}
$finalScore = $pctg > $finalScore ? $pctg : $finalScore;
$data = array(
'cost' => $score,
'score' => $finalScore,
'similar' => $grade
);
return $data;
} | php | public function similarity($string = null, $cmp = null, $language = 'french')
{
if (empty($string) || empty($cmp)) {
return false;
}
if (strlen($string) > 255 || strlen($cmp) > 255) {
return false;
}
$processedStr = $this->phoneme($string, $language);
$processedCmp = $this->phoneme($cmp, $language);
$score = levenshtein($processedStr, $processedCmp);
$smaller = strlen($processedStr) < strlen($processedCmp) ? $processedStr : $processedCmp;
$biggest = strlen($processedStr) < strlen($processedCmp) ? $processedCmp : $processedStr;
$phonexStr = $this->getPhonex($string);
$phonexCmp = $this->getPhonex($cmp);
$scorePhonex = ($phonexStr + $phonexCmp) / 2;
if (empty($biggest) || empty($smaller)) {
return false;
}
$contain = strstr($biggest, $smaller);
$avgLength = (strlen($processedStr) + strlen($processedCmp)) / 2;
$finalScore = round((1.0 / $avgLength) * $score, 6);
$finalScore = round(((1 - $finalScore) * 100), 2);
$finalScore = 0 > $finalScore && false !== $contain ? 100 + $finalScore : $finalScore;
$finalScore = 100 < $finalScore ? 100 : $finalScore;
$finalScore = 0 > $finalScore ? 0 : $finalScore;
if ($finalScore / 100 >= $this->_tolerance) {
$grade = 1;
} else {
$grade = 0;
}
$proxMatch = self::checkProx(self::_iconv($string), self::_iconv($cmp));
$pctg = $finalScore > $proxMatch ? $finalScore : $proxMatch;
if (strstr($string, ' ') && strstr($cmp, ' ')) {
$matchWords = self::matchWords(self::_iconv($string), self::_iconv($cmp));
$pctg = $matchWords > $pctg ? $matchWords : $pctg;
}
$finalScore = $pctg > $finalScore ? $pctg : $finalScore;
$data = array(
'cost' => $score,
'score' => $finalScore,
'similar' => $grade
);
return $data;
} | Compare 2 strings to see how similar they are.
@param string $string The first string to compare. Max length of 255 chars.
@param string $cmp The second string to comapre against the first. Max length of 255 chars.
@param string $language The language to make phonemes
@return mixed false if $string or $cmp is empty or longer then 255 chars, the max length for a PHP levenshtein. | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Phonetic.php#L98-L157 |
schpill/thin | src/Phonetic.php | Phonetic.phoneme | public function phoneme($string = '', $language = 'french')
{
$parts = explode(' ', $string);
$phonemes = array();
foreach ($parts as $p) {
$p = $this->partCases(Inflector::lower($p));
$phon = $this->$language($p);
if ($phon != ' ' && strlen($phon)) {
array_push($phonemes, $phon);
}
}
if($this->_sort) {
sort($phonemes);
}
$string = implode(' ', $phonemes);
return $string;
} | php | public function phoneme($string = '', $language = 'french')
{
$parts = explode(' ', $string);
$phonemes = array();
foreach ($parts as $p) {
$p = $this->partCases(Inflector::lower($p));
$phon = $this->$language($p);
if ($phon != ' ' && strlen($phon)) {
array_push($phonemes, $phon);
}
}
if($this->_sort) {
sort($phonemes);
}
$string = implode(' ', $phonemes);
return $string;
} | Transform a given string into its phoneme equivalent.
@param string $string The string to be transformed in phonemes.
@param string $language The language to make phonemes
@return string Phoneme string. | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Phonetic.php#L178-L199 |
schpill/thin | src/Phonetic.php | Phonetic.aReplace | private function aReplace($string, array $aTab, $bPreg = false)
{
if (false === $bPreg) {
$string = repl(array_keys($aTab), array_values($aTab), $string);
} else {
$string = preg_replace(array_keys($aTab), array_values($aTab), $string);
}
} | php | private function aReplace($string, array $aTab, $bPreg = false)
{
if (false === $bPreg) {
$string = repl(array_keys($aTab), array_values($aTab), $string);
} else {
$string = preg_replace(array_keys($aTab), array_values($aTab), $string);
}
} | private function aReplace ()
method used to replace letters, given an array
@Param array aTab : the replacement array to be used
@Param bool bPreg : is the array an array of regular expressions patterns : true => yes`| false => no | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Phonetic.php#L299-L306 |
schpill/thin | src/Phonetic.php | Phonetic.trimLast | private function trimLast($string)
{
$length = strlen($string) - 1;
if (Arrays::in($string{$length}, array('t', 'x'))) {
$string = substr($string, 0, $length);
}
} | php | private function trimLast($string)
{
$length = strlen($string) - 1;
if (Arrays::in($string{$length}, array('t', 'x'))) {
$string = substr($string, 0, $length);
}
} | private function trimLast ()
method to trim the bad endings | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Phonetic.php#L312-L319 |
schpill/thin | src/Phonetic.php | Phonetic.mapNum | private static function mapNum($val, $key)
{
$except = array (
'1',
'2',
'3',
'4',
'5',
'e',
'f',
'g',
'h',
'i',
'k',
'l',
'n',
'o',
'r',
's',
't',
'u',
'w',
'x',
'y',
'z'
);
$num = array_search($val, $except);
$num *= pow (22, - ($key + 1));
return $num;
} | php | private static function mapNum($val, $key)
{
$except = array (
'1',
'2',
'3',
'4',
'5',
'e',
'f',
'g',
'h',
'i',
'k',
'l',
'n',
'o',
'r',
's',
't',
'u',
'w',
'x',
'y',
'z'
);
$num = array_search($val, $except);
$num *= pow (22, - ($key + 1));
return $num;
} | private static function mapNum ()
callback method to create the phonex numeric code, base 22
@Param int val : current value
@Param int clef : current key
@Returns int num : the calculated base 22 value | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Phonetic.php#L328-L359 |
schpill/thin | src/Phonetic.php | Phonetic.getPhonex | private function getPhonex($string)
{
$array = str_split($string);
$aNum = array_map(array ('self', 'mapNum'), array_values($array), array_keys($array));
$score = (float) array_sum($aNum) * 1000;
return round($score, 3);
} | php | private function getPhonex($string)
{
$array = str_split($string);
$aNum = array_map(array ('self', 'mapNum'), array_values($array), array_keys($array));
$score = (float) array_sum($aNum) * 1000;
return round($score, 3);
} | private function getPhonex ()
method to get a numeric array from the main string
we call the callback function mapNum and we sum all the values of the obtained array to get the final phonex code | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Phonetic.php#L366-L373 |
chilimatic/chilimatic-framework | lib/formatter/Log.php | Log.format | public function format(array $input)
{
$output = $this->formatString;
foreach ($input as $key => $value)
{
if (!isset($this->map[$key])) {
continue;
}
if (is_array($value)) {
$value = implode('\n\t', $value);
}
$output = str_replace($this->map[$key], $value, $output);
}
return $output;
} | php | public function format(array $input)
{
$output = $this->formatString;
foreach ($input as $key => $value)
{
if (!isset($this->map[$key])) {
continue;
}
if (is_array($value)) {
$value = implode('\n\t', $value);
}
$output = str_replace($this->map[$key], $value, $output);
}
return $output;
} | @param array $input
@return array | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/formatter/Log.php#L41-L58 |
feelinc/laravel-api | src/Sule/Api/Resources/Collection.php | Collection.getEtags | public function getEtags()
{
$etag = '';
if ($this->data instanceof ArrayableInterface) {
$this->data = $this->data->toArray();
}
foreach ( $this->data as $item ) {
$item = new Resource($item);
$etag .= $item->getEtag();
unset($item);
}
return md5( $etag );
} | php | public function getEtags()
{
$etag = '';
if ($this->data instanceof ArrayableInterface) {
$this->data = $this->data->toArray();
}
foreach ( $this->data as $item ) {
$item = new Resource($item);
$etag .= $item->getEtag();
unset($item);
}
return md5( $etag );
} | Return ETag based on collection of items
@return string md5 of all ETags | https://github.com/feelinc/laravel-api/blob/8b4abc4f1be255b441e09f5014e863a130c666d8/src/Sule/Api/Resources/Collection.php#L37-L52 |
courtney-miles/schnoop-schema | src/MySQL/Routine/AbstractRoutine.php | AbstractRoutine.makeCharacteristicsDDL | protected function makeCharacteristicsDDL()
{
return implode(
" ",
array_filter(
[
$this->deterministic ? 'DETERMINISTIC' : 'NOT DETERMINISTIC',
$this->dataAccess,
!empty($this->sqlSecurity) ? 'SQL SECURITY ' . $this->sqlSecurity : null,
!empty($this->comment) ? "\nCOMMENT '" . addslashes($this->comment) . "'" : null
]
)
);
} | php | protected function makeCharacteristicsDDL()
{
return implode(
" ",
array_filter(
[
$this->deterministic ? 'DETERMINISTIC' : 'NOT DETERMINISTIC',
$this->dataAccess,
!empty($this->sqlSecurity) ? 'SQL SECURITY ' . $this->sqlSecurity : null,
!empty($this->comment) ? "\nCOMMENT '" . addslashes($this->comment) . "'" : null
]
)
);
} | Make the portion of the routine DDL statement that describes deterministic, sql security and comment.
@return string Characteristics DDL. | https://github.com/courtney-miles/schnoop-schema/blob/f96e9922257860171ecdcdbb6b78182276e2f60d/src/MySQL/Routine/AbstractRoutine.php#L338-L351 |
valu-digital/valuso | src/ValuSo/Service/BatchService.php | BatchService.execute | protected function execute(array $commands, $options = array())
{
$options = is_array($options) ? $options : array();
$options = array_merge(
array('verbose' => false),
$options
);
$workers = array();
foreach ($commands as $key => &$data) {
$data['service'] = isset($data['service'])
? $data['service'] : $options['service'];
$data['operation'] = isset($data['operation'])
? $data['operation'] : $options['operation'];
$data['params'] = isset($data['params'])
? $data['params'] : array();
if (!isset($data['service'])) {
throw new Exception\InvalidCommandException(
"Missing 'service' from command definition");
} elseif ($data['service'] === $this->command->getService()) {
throw new Exception\InvalidCommandException(
"Cannot call 'Batch' recursively");
}
if (!isset($data['operation'])) {
throw new Exception\InvalidCommandException(
"Missing 'operation' from command definition");
}
if (!is_array($data['params'])) {
throw new Exception\InvalidCommandException(
"Invalid 'params' in command definition");
}
// Initialize new worker
$workers[$key] = $this->createWorker($data['service'])->args($data['params']);
}
$responses = array();
$errors = array();
foreach ($workers as $key => $worker) {
try{
$responses[$key] = $worker
->exec($commands[$key]['operation'])
->first();
} catch(\Exception $e) {
$responses[$key] = false;
if ($e instanceof Exception\ServiceException) {
$errors[$key] = ['m' => $e->getRawMessage(), 'c' => $e->getCode(), 'a' => $e->getVars()];
} else {
$errors[$key] = ['m' => 'Unknown error', 'c' => $e->getCode()];
}
}
}
if ($options['verbose']) {
return [
'results' => $responses,
'errors' => $errors
];
} else {
return $responses;
}
} | php | protected function execute(array $commands, $options = array())
{
$options = is_array($options) ? $options : array();
$options = array_merge(
array('verbose' => false),
$options
);
$workers = array();
foreach ($commands as $key => &$data) {
$data['service'] = isset($data['service'])
? $data['service'] : $options['service'];
$data['operation'] = isset($data['operation'])
? $data['operation'] : $options['operation'];
$data['params'] = isset($data['params'])
? $data['params'] : array();
if (!isset($data['service'])) {
throw new Exception\InvalidCommandException(
"Missing 'service' from command definition");
} elseif ($data['service'] === $this->command->getService()) {
throw new Exception\InvalidCommandException(
"Cannot call 'Batch' recursively");
}
if (!isset($data['operation'])) {
throw new Exception\InvalidCommandException(
"Missing 'operation' from command definition");
}
if (!is_array($data['params'])) {
throw new Exception\InvalidCommandException(
"Invalid 'params' in command definition");
}
// Initialize new worker
$workers[$key] = $this->createWorker($data['service'])->args($data['params']);
}
$responses = array();
$errors = array();
foreach ($workers as $key => $worker) {
try{
$responses[$key] = $worker
->exec($commands[$key]['operation'])
->first();
} catch(\Exception $e) {
$responses[$key] = false;
if ($e instanceof Exception\ServiceException) {
$errors[$key] = ['m' => $e->getRawMessage(), 'c' => $e->getCode(), 'a' => $e->getVars()];
} else {
$errors[$key] = ['m' => 'Unknown error', 'c' => $e->getCode()];
}
}
}
if ($options['verbose']) {
return [
'results' => $responses,
'errors' => $errors
];
} else {
return $responses;
}
} | Batch execute operations in other service(s)
Example of using batchExec():
<code>
$broker->service('Batch')->execute(
[
'cmd1' => ["service" => "filesystem.directory", "operation" => "create", "params" => ["path" => "/accounts/mc"]],
'cmd2' => ["service" => "filesystem", "operation" => "exists", "params" => ["query" => "/accounts/mc"]],
]
);
</code>
The above might return something like this:
<code>
[
'cmd1' => {object},
'cmd2' => true
]
</code>
Currently any error will simply result to false. If the first operation
of the previous example failed, the result might be something like:
<code>
[
'cmd1' => false,
'cmd2' => true
]
</code>
@param array $commands
@param array $options
@throws Exception\InvalidCommandException
@return array | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Service/BatchService.php#L81-L152 |
valu-digital/valuso | src/ValuSo/Service/BatchService.php | BatchService.createWorker | protected function createWorker($service)
{
return $this->getServiceBroker()
->service($service)
->context($this->command->getContext());
} | php | protected function createWorker($service)
{
return $this->getServiceBroker()
->service($service)
->context($this->command->getContext());
} | Create service worker
@return \ValuSo\Broker\Worker | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Service/BatchService.php#L159-L164 |
silvercommerce/contact-admin | src/model/ContactLocation.php | ContactLocation.onAfterWrite | public function onAfterWrite()
{
parent::onAfterWrite();
if ($this->Default) {
foreach ($this->Contact()->Locations() as $location) {
if ($location->ID != $this->ID && $location->Default) {
$location->Default = false;
$location->write();
}
}
}
} | php | public function onAfterWrite()
{
parent::onAfterWrite();
if ($this->Default) {
foreach ($this->Contact()->Locations() as $location) {
if ($location->ID != $this->ID && $location->Default) {
$location->Default = false;
$location->write();
}
}
}
} | If we have assigned this as a default location, loop through
other locations and disable default.
@return void | https://github.com/silvercommerce/contact-admin/blob/32cbc2ef2589f93f9dd1796e5db2f11ad15d888c/src/model/ContactLocation.php#L232-L244 |
igorwanbarros/autenticacao-laravel | src/Migrations/2016_12_13_160954_autenticacao_create_perfis_empresas_permissoes_table.php | AutenticacaoCreatePerfisEmpresasPermissoesTable.up | public function up()
{
Schema::create('autenticacao_perfis_empresas_permissoes', function (Blueprint $tb) {
$tb->integer('perfil_empresa_id', false, true);
$tb->foreign('perfil_empresa_id', 'autenticacao_perfil_empresa_id_foreign')->references('id')->on('autenticacao_perfis_empresas');
$tb->integer('permissao_id', false, true);
$tb->foreign('permissao_id', 'autenticacao_perfil_permissao_id_foreign')->references('id')->on('autenticacao_permissoes');
});
} | php | public function up()
{
Schema::create('autenticacao_perfis_empresas_permissoes', function (Blueprint $tb) {
$tb->integer('perfil_empresa_id', false, true);
$tb->foreign('perfil_empresa_id', 'autenticacao_perfil_empresa_id_foreign')->references('id')->on('autenticacao_perfis_empresas');
$tb->integer('permissao_id', false, true);
$tb->foreign('permissao_id', 'autenticacao_perfil_permissao_id_foreign')->references('id')->on('autenticacao_permissoes');
});
} | Run the migrations.
@return void | https://github.com/igorwanbarros/autenticacao-laravel/blob/e7e8217dae433934fe46c34516fb2f6f5f932fc1/src/Migrations/2016_12_13_160954_autenticacao_create_perfis_empresas_permissoes_table.php#L13-L21 |
Elephant418/Staq | src/Staq/Util/Auth/Stack/Controller/Auth.php | Auth.actionInscription | public function actionInscription()
{
$form = $this->getInscriptionForm();
if ($form->isValid()) {
$user = $this->getUserModel()
->set('login', $form->login)
->set('password', $form->password);
try {
$saved = FALSE;
$saved = $user->save();
} catch (\PDOException $e) {
}
if ($saved) {
$this->login($user);
Notif::success(sprintf(static::MSG_INSCRIPTION_VALID, $form->login));
\Staq\Util::httpRedirectUri($this->getRedirectUri());
} else {
Notif::error(static::MSG_INSCRIPTION_KO);
}
}
$view = $this->createView('inscription');
$view['form'] = $form;
$view['redirect'] = $this->getRedirectUri();
return $view;
} | php | public function actionInscription()
{
$form = $this->getInscriptionForm();
if ($form->isValid()) {
$user = $this->getUserModel()
->set('login', $form->login)
->set('password', $form->password);
try {
$saved = FALSE;
$saved = $user->save();
} catch (\PDOException $e) {
}
if ($saved) {
$this->login($user);
Notif::success(sprintf(static::MSG_INSCRIPTION_VALID, $form->login));
\Staq\Util::httpRedirectUri($this->getRedirectUri());
} else {
Notif::error(static::MSG_INSCRIPTION_KO);
}
}
$view = $this->createView('inscription');
$view['form'] = $form;
$view['redirect'] = $this->getRedirectUri();
return $view;
} | /* ACTION METHODS
*********************************************************************** | https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Util/Auth/Stack/Controller/Auth.php#L54-L78 |
Elephant418/Staq | src/Staq/Util/Auth/Stack/Controller/Auth.php | Auth.getRedirectUri | protected function getRedirectUri()
{
if (isset($_POST['redirect'])) {
return $_POST['redirect'];
}
if (isset($_GET['redirect'])) {
return $_GET['redirect'];
}
return \Staq::App()->getCurrentUri();
} | php | protected function getRedirectUri()
{
if (isset($_POST['redirect'])) {
return $_POST['redirect'];
}
if (isset($_GET['redirect'])) {
return $_GET['redirect'];
}
return \Staq::App()->getCurrentUri();
} | /* PROTECTED METHODS
*********************************************************************** | https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Util/Auth/Stack/Controller/Auth.php#L111-L120 |
Elephant418/Staq | src/Staq/Util/Auth/Stack/Controller/Auth.php | Auth.currentUser | public function currentUser()
{
// Already initialized
if (!is_null(static::$currentUser)) {
return static::$currentUser;
}
// Find the current user
if (!isset($_SESSION['Staq']['loggedUser'])) {
$user = FALSE;
} else {
$user = $this->getUserEntity()->fetchById($_SESSION['Staq']['loggedUser']);
if (!$user->exists()) {
$user = FALSE;
}
}
static::$currentUser = $user;
return static::$currentUser;
} | php | public function currentUser()
{
// Already initialized
if (!is_null(static::$currentUser)) {
return static::$currentUser;
}
// Find the current user
if (!isset($_SESSION['Staq']['loggedUser'])) {
$user = FALSE;
} else {
$user = $this->getUserEntity()->fetchById($_SESSION['Staq']['loggedUser']);
if (!$user->exists()) {
$user = FALSE;
}
}
static::$currentUser = $user;
return static::$currentUser;
} | /* UTIL METHODS
*********************************************************************** | https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Util/Auth/Stack/Controller/Auth.php#L136-L155 |
4devs/serializer | DataTypeFactory.php | DataTypeFactory.resolveOptions | public function resolveOptions(MetadataType $type)
{
return $this->getResolvedType($type)->getOptionsResolver()->resolve($type->getOptions());
} | php | public function resolveOptions(MetadataType $type)
{
return $this->getResolvedType($type)->getOptionsResolver()->resolve($type->getOptions());
} | @param MetadataType $type
@return array | https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/DataTypeFactory.php#L86-L89 |
4devs/serializer | DataTypeFactory.php | DataTypeFactory.createType | public function createType($type, array $options = [])
{
$class = isset($this->mappingTypeList[$type]) ? $this->mappingTypeList[$type] : $type;
if (!class_exists($class)) {
throw new DataTypeNotFoundException($type, $class);
}
return new MetadataType($class, $options);
} | php | public function createType($type, array $options = [])
{
$class = isset($this->mappingTypeList[$type]) ? $this->mappingTypeList[$type] : $type;
if (!class_exists($class)) {
throw new DataTypeNotFoundException($type, $class);
}
return new MetadataType($class, $options);
} | @param string $type
@param array $options
@throws DataTypeNotFoundException
@return MetadataType | https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/DataTypeFactory.php#L111-L119 |
4devs/serializer | DataTypeFactory.php | DataTypeFactory.getResolvedType | private function getResolvedType(MetadataType $type)
{
$class = $type->getName();
if (!isset($this->resolvedTypeList[$class])) {
if (isset($this->typeList[$class])) {
$type = $this->typeList[$class];
unset($this->typeList[$class]);
} else {
$type = new $class();
}
if ($type instanceof DenormalizerAwareInterface && $denormalizer = $this->getDenormalizer()) {
$type->setDenormalizer($denormalizer);
}
if ($type instanceof NormalizerAwareInterface && $normalizer = $this->getNormalizer()) {
$type->setNormalizer($normalizer);
}
$this->resolvedTypeList[$class] = $this->resolveType($type);
}
return $this->resolvedTypeList[$class];
} | php | private function getResolvedType(MetadataType $type)
{
$class = $type->getName();
if (!isset($this->resolvedTypeList[$class])) {
if (isset($this->typeList[$class])) {
$type = $this->typeList[$class];
unset($this->typeList[$class]);
} else {
$type = new $class();
}
if ($type instanceof DenormalizerAwareInterface && $denormalizer = $this->getDenormalizer()) {
$type->setDenormalizer($denormalizer);
}
if ($type instanceof NormalizerAwareInterface && $normalizer = $this->getNormalizer()) {
$type->setNormalizer($normalizer);
}
$this->resolvedTypeList[$class] = $this->resolveType($type);
}
return $this->resolvedTypeList[$class];
} | @param MetadataType $type
@return ResolvedDataType | https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/DataTypeFactory.php#L139-L160 |
PhoxPHP/Glider | src/Connection/ConnectionLoader.php | ConnectionLoader.getConnectionsFromResource | public function getConnectionsFromResource() : Array
{
$baseDir = dirname(__DIR__);
$configLocation = $baseDir . '/config.php';
if (!file_exists($configLocation) && class_exists(Config::class)) {
$resourceConfig = Config::get('database');
}else{
$resourceConfig = include $configLocation;
}
if (gettype($resourceConfig) !== 'array') {
throw new Exception('Invalid configuration type.');
}
return $resourceConfig;
} | php | public function getConnectionsFromResource() : Array
{
$baseDir = dirname(__DIR__);
$configLocation = $baseDir . '/config.php';
if (!file_exists($configLocation) && class_exists(Config::class)) {
$resourceConfig = Config::get('database');
}else{
$resourceConfig = include $configLocation;
}
if (gettype($resourceConfig) !== 'array') {
throw new Exception('Invalid configuration type.');
}
return $resourceConfig;
} | Loads connection configuration.
@access public
@return <Array> | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Connection/ConnectionLoader.php#L37-L53 |
Tuna-CMS/tuna-bundle | src/Tuna/Bundle/GalleryBundle/Entity/Gallery.php | Gallery.setItems | public function setItems($items)
{
foreach ($items as $item) {
$item->setGallery($this);
}
$this->items = $items;
return $this;
} | php | public function setItems($items)
{
foreach ($items as $item) {
$item->setGallery($this);
}
$this->items = $items;
return $this;
} | @param PersistentCollection|array $items
@return Gallery | https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/GalleryBundle/Entity/Gallery.php#L86-L94 |
zbox/UnifiedPush | src/Zbox/UnifiedPush/Dispatcher.php | Dispatcher.getConnection | public function getConnection($serviceName)
{
if (empty($this->connectionPool[$serviceName])) {
$this->initConnection($serviceName);
}
return $this->connectionPool[$serviceName];
} | php | public function getConnection($serviceName)
{
if (empty($this->connectionPool[$serviceName])) {
$this->initConnection($serviceName);
}
return $this->connectionPool[$serviceName];
} | Gets a service client connection by service name
@param string $serviceName
@return ServiceClientInterface | https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/Dispatcher.php#L100-L107 |
zbox/UnifiedPush | src/Zbox/UnifiedPush/Dispatcher.php | Dispatcher.initConnection | public function initConnection($serviceName)
{
$connection = $this->clientFactory->createServiceClient($serviceName);
$this->connectionPool[$serviceName] = $connection;
return $this;
} | php | public function initConnection($serviceName)
{
$connection = $this->clientFactory->createServiceClient($serviceName);
$this->connectionPool[$serviceName] = $connection;
return $this;
} | Initialize service client connection by service name
@param string $serviceName
@return $this | https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/Dispatcher.php#L115-L121 |
zbox/UnifiedPush | src/Zbox/UnifiedPush/Dispatcher.php | Dispatcher.dispatch | public function dispatch(MessageInterface $message)
{
$builder = $this->notificationBuilder;
$notifications = $builder->buildNotifications($message);
/** @var Notification $notification */
foreach ($notifications as $notification) {
$this->sendNotification($notification);
}
return $this;
} | php | public function dispatch(MessageInterface $message)
{
$builder = $this->notificationBuilder;
$notifications = $builder->buildNotifications($message);
/** @var Notification $notification */
foreach ($notifications as $notification) {
$this->sendNotification($notification);
}
return $this;
} | Build notification and send it to notification service
@param MessageInterface $message
@return $this | https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/Dispatcher.php#L148-L160 |
zbox/UnifiedPush | src/Zbox/UnifiedPush/Dispatcher.php | Dispatcher.dispatchAll | public function dispatchAll(MessageCollection $messages)
{
$collection = $messages->getMessageCollection();
while ($collection->valid()) {
$message = $collection->current();
$this->dispatch($message);
$collection->next();
}
return $this;
} | php | public function dispatchAll(MessageCollection $messages)
{
$collection = $messages->getMessageCollection();
while ($collection->valid()) {
$message = $collection->current();
$this->dispatch($message);
$collection->next();
}
return $this;
} | Tries to dispatch all messages to notification service
@param MessageCollection $messages
@return $this | https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/Dispatcher.php#L168-L179 |
zbox/UnifiedPush | src/Zbox/UnifiedPush/Dispatcher.php | Dispatcher.sendNotification | public function sendNotification(Notification $notification)
{
try {
$connection = $this->getConnection($notification->getType());
$connection->setNotification($notification);
$this->logger->info(
sprintf(
"Dispatching notification id: %s",
$notification->getIdentifier()
)
);
$this
->responseHandler
->addIdentifiedResponse(
$notification->getIdentifier(),
$connection->sendRequest()
);
return true;
} catch (ClientException $e) {
$this->logger->error(
sprintf("Client connection error: %s", $e->getMessage())
);
} catch (RuntimeException $e) {
$this->logger->error(
sprintf("Runtime error: %s", $e->getMessage())
);
} catch (\Exception $e) {
$this->logger->error(
sprintf("Error occurs: %s", $e->getMessage())
);
}
return false;
} | php | public function sendNotification(Notification $notification)
{
try {
$connection = $this->getConnection($notification->getType());
$connection->setNotification($notification);
$this->logger->info(
sprintf(
"Dispatching notification id: %s",
$notification->getIdentifier()
)
);
$this
->responseHandler
->addIdentifiedResponse(
$notification->getIdentifier(),
$connection->sendRequest()
);
return true;
} catch (ClientException $e) {
$this->logger->error(
sprintf("Client connection error: %s", $e->getMessage())
);
} catch (RuntimeException $e) {
$this->logger->error(
sprintf("Runtime error: %s", $e->getMessage())
);
} catch (\Exception $e) {
$this->logger->error(
sprintf("Error occurs: %s", $e->getMessage())
);
}
return false;
} | Tries to connect and send a notification
@param Notification $notification
@return bool | https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/Dispatcher.php#L187-L226 |
zbox/UnifiedPush | src/Zbox/UnifiedPush/Dispatcher.php | Dispatcher.loadFeedback | public function loadFeedback()
{
$serviceName = NotificationServices::APPLE_PUSH_NOTIFICATIONS_SERVICE;
try {
$this->logger->info(sprintf("Querying the feedback service '%s'", $serviceName));
$connection = $this->initFeedbackConnection($serviceName);
$this
->responseHandler
->addResponse(
$connection->sendRequest()
);
} catch (RuntimeException $e) {
$this->logger->error(
sprintf("Runtime error while acquiring feedback: %s", $e->getMessage())
);
} catch (\Exception $e) {
$this->logger->error(
sprintf("Error occurs while acquiring feedback: %s", $e->getMessage())
);
}
return $this;
} | php | public function loadFeedback()
{
$serviceName = NotificationServices::APPLE_PUSH_NOTIFICATIONS_SERVICE;
try {
$this->logger->info(sprintf("Querying the feedback service '%s'", $serviceName));
$connection = $this->initFeedbackConnection($serviceName);
$this
->responseHandler
->addResponse(
$connection->sendRequest()
);
} catch (RuntimeException $e) {
$this->logger->error(
sprintf("Runtime error while acquiring feedback: %s", $e->getMessage())
);
} catch (\Exception $e) {
$this->logger->error(
sprintf("Error occurs while acquiring feedback: %s", $e->getMessage())
);
}
return $this;
} | Tries to connect and load feedback data
@return $this
@throws RuntimeException
@throws \Exception | https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/Dispatcher.php#L235-L262 |
gwa/zero-library | src/Module/AbstractThemeModule.php | AbstractThemeModule.registerShortcodes | final private function registerShortcodes(array $shortcodeclasses)
{
foreach ($shortcodeclasses as $shortcodeclass) {
$instance = new $shortcodeclass;
$instance->init($this->getWpBridge(), $this);
}
} | php | final private function registerShortcodes(array $shortcodeclasses)
{
foreach ($shortcodeclasses as $shortcodeclass) {
$instance = new $shortcodeclass;
$instance->init($this->getWpBridge(), $this);
}
} | /* ---------------- | https://github.com/gwa/zero-library/blob/2c1e700640f527ace3d58bc0e90bd71a096dcf41/src/Module/AbstractThemeModule.php#L109-L115 |
wartw98/core | StripeClone/Facade/Charge.php | Charge.cardData | private function cardData($c) {$p = $this->pathToCard(); return
/** @var object|array(string => string) $r */
/** @var string $p */
($r = (is_array($c) || $c instanceof \ArrayAccess) ? $c[$p] : (
!is_object($c) ? null : (
/**
* 2017-10-08
* It is for Paymill:
* @uses \Paymill\Models\Response\Transaction::getPayment()
* @var callable $callable
* https://github.com/mage2pro/paymill-sdk/blob/v4.4.4/lib/Paymill/Models/Response/Transaction.php#L411-L419
* public function getPayment() {
* return $this->_payment;
* }
*/
is_callable($callable = [$c, 'get' . ucfirst($p)]) ? call_user_func($callable) :
/**
* 2017-10-08
* It is for Spryng:
* @uses \SpryngPaymentsApiPhp\Object\Transaction::$card
* https://github.com/mage2pro/spryng-sdk/blob/1.2.5/src/Complexity/SpryngPaymentsApiPhp/Object/Transaction.php#L68-L73
* public $card;
*/
dfo($c, $p)
)
)) ?: df_error('You should implement cardData().')
;} | php | private function cardData($c) {$p = $this->pathToCard(); return
/** @var object|array(string => string) $r */
/** @var string $p */
($r = (is_array($c) || $c instanceof \ArrayAccess) ? $c[$p] : (
!is_object($c) ? null : (
/**
* 2017-10-08
* It is for Paymill:
* @uses \Paymill\Models\Response\Transaction::getPayment()
* @var callable $callable
* https://github.com/mage2pro/paymill-sdk/blob/v4.4.4/lib/Paymill/Models/Response/Transaction.php#L411-L419
* public function getPayment() {
* return $this->_payment;
* }
*/
is_callable($callable = [$c, 'get' . ucfirst($p)]) ? call_user_func($callable) :
/**
* 2017-10-08
* It is for Spryng:
* @uses \SpryngPaymentsApiPhp\Object\Transaction::$card
* https://github.com/mage2pro/spryng-sdk/blob/1.2.5/src/Complexity/SpryngPaymentsApiPhp/Object/Transaction.php#L68-L73
* public $card;
*/
dfo($c, $p)
)
)) ?: df_error('You should implement cardData().')
;} | 2017-02-11
@used-by card()
@param object|array(string => mixed) $c
@return object|array(string => string) | https://github.com/wartw98/core/blob/e1f44f6b4798a7b988f6a1cae639ff3745c9cd2a/StripeClone/Facade/Charge.php#L176-L202 |
RadialCorp/magento-core | src/app/code/community/Radial/Amqp/controllers/Exchange/System/Config/ValidateController.php | Radial_Amqp_Exchange_System_Config_ValidateController.validateamqpAction | public function validateamqpAction()
{
$request = $this->getRequest();
$configMap = Mage::getModel('radial_amqp/config');
$hostname = $this->_validatorHelper->getParamOrFallbackValue(
$request,
self::HOSTNAME_PARAM,
self::HOSTNAME_USE_DEFAULT_PARAM,
$configMap->getPathForKey('hostname')
);
$username = $this->_validatorHelper->getParamOrFallbackValue(
$request,
self::USERNAME_PARAM,
self::USERNAME_USE_DEFAULT_PARAM,
$configMap->getPathForKey('username')
);
$password = $this->_validatorHelper->getEncryptedParamOrFallbackValue(
$request,
self::PASSWORD_PARAM,
self::PASSWORD_USE_DEFAULT_PARAM,
$configMap->getPathForKey('password')
);
$validator = $this->_getAmqpApiValidator($this->_getSourceStore());
$this->getResponse()->setHeader('Content-Type', 'text/json')
->setBody(json_encode($validator->testConnection($hostname, $username, $password)));
return $this;
} | php | public function validateamqpAction()
{
$request = $this->getRequest();
$configMap = Mage::getModel('radial_amqp/config');
$hostname = $this->_validatorHelper->getParamOrFallbackValue(
$request,
self::HOSTNAME_PARAM,
self::HOSTNAME_USE_DEFAULT_PARAM,
$configMap->getPathForKey('hostname')
);
$username = $this->_validatorHelper->getParamOrFallbackValue(
$request,
self::USERNAME_PARAM,
self::USERNAME_USE_DEFAULT_PARAM,
$configMap->getPathForKey('username')
);
$password = $this->_validatorHelper->getEncryptedParamOrFallbackValue(
$request,
self::PASSWORD_PARAM,
self::PASSWORD_USE_DEFAULT_PARAM,
$configMap->getPathForKey('password')
);
$validator = $this->_getAmqpApiValidator($this->_getSourceStore());
$this->getResponse()->setHeader('Content-Type', 'text/json')
->setBody(json_encode($validator->testConnection($hostname, $username, $password)));
return $this;
} | Test connecting to the AMQP server
@return self | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Amqp/controllers/Exchange/System/Config/ValidateController.php#L75-L103 |
RadialCorp/magento-core | src/app/code/community/Radial/Amqp/controllers/Exchange/System/Config/ValidateController.php | Radial_Amqp_Exchange_System_Config_ValidateController._getSourceStore | protected function _getSourceStore()
{
// this may return a Mage_Core_Model_Store or a Mage_Core_Model_Website
$configSource = $this->_validatorHelper->getConfigSource($this->getRequest());
// When given a website, get the default store for that website.
// AMQP config is only at global and website level, so no *current*
// possibility for the default store to have a different value than the website.
if ($configSource instanceof Mage_Core_Model_Website) {
return $configSource->getDefaultStore();
}
return $configSource;
} | php | protected function _getSourceStore()
{
// this may return a Mage_Core_Model_Store or a Mage_Core_Model_Website
$configSource = $this->_validatorHelper->getConfigSource($this->getRequest());
// When given a website, get the default store for that website.
// AMQP config is only at global and website level, so no *current*
// possibility for the default store to have a different value than the website.
if ($configSource instanceof Mage_Core_Model_Website) {
return $configSource->getDefaultStore();
}
return $configSource;
} | Get a store context to use as the source of configuration.
@return Mage_Core_Model_Store | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Amqp/controllers/Exchange/System/Config/ValidateController.php#L108-L119 |
morrislaptop/error-tracker-adapter | src/Adapter/Bugsnag.php | Bugsnag.report | public function report(Exception $e, array $extra = [])
{
$this->bugsnag->setMetaData($extra);
return $this->bugsnag->exceptionHandler($e);
} | php | public function report(Exception $e, array $extra = [])
{
$this->bugsnag->setMetaData($extra);
return $this->bugsnag->exceptionHandler($e);
} | {@inheritDoc} | https://github.com/morrislaptop/error-tracker-adapter/blob/955aea67c45892da2b8813517600f338bada6a01/src/Adapter/Bugsnag.php#L25-L29 |
romaricdrigon/OrchestraBundle | Core/Entity/Action/EntityActionBuilder.php | EntityActionBuilder.buildName | protected function buildName($name)
{
$name = preg_replace('/([A-Z]{1})/', ' $1', $name);
$name = ucfirst($name);
return trim($name);
} | php | protected function buildName($name)
{
$name = preg_replace('/([A-Z]{1})/', ' $1', $name);
$name = ucfirst($name);
return trim($name);
} | Humanize name, adding a space before each capital
@param string $name
@return string | https://github.com/romaricdrigon/OrchestraBundle/blob/4abb9736fcb6b23ed08ebd14ab169867339a4785/Core/Entity/Action/EntityActionBuilder.php#L78-L85 |
romaricdrigon/OrchestraBundle | Core/Entity/Action/EntityActionBuilder.php | EntityActionBuilder.findCommand | protected function findCommand(\ReflectionMethod $reflectionMethod)
{
$parameters = $reflectionMethod->getParameters();
/** @var \ReflectionParameter $parameter */
foreach ($parameters as $parameter) {
$class = $parameter->getClass();
if (null !== $class && true === $class->implementsInterface('RomaricDrigon\OrchestraBundle\Domain\Command\CommandInterface')) {
return $class->getName();
}
}
return null;
} | php | protected function findCommand(\ReflectionMethod $reflectionMethod)
{
$parameters = $reflectionMethod->getParameters();
/** @var \ReflectionParameter $parameter */
foreach ($parameters as $parameter) {
$class = $parameter->getClass();
if (null !== $class && true === $class->implementsInterface('RomaricDrigon\OrchestraBundle\Domain\Command\CommandInterface')) {
return $class->getName();
}
}
return null;
} | Look if we have a parameter of type "CommandInterface", and then return its precise class name
@param \ReflectionMethod $reflectionMethod
@return null|string | https://github.com/romaricdrigon/OrchestraBundle/blob/4abb9736fcb6b23ed08ebd14ab169867339a4785/Core/Entity/Action/EntityActionBuilder.php#L104-L118 |
x2ts/x2ts | src/cache/RCache.php | RCache.inc | public function inc($key, $step = 1) {
X::logger()->trace("RCache inc '$key' by $step");
if ($step > 1) {
return $this->cache->incrBy($key, $step);
}
return $this->cache->incr($key);
} | php | public function inc($key, $step = 1) {
X::logger()->trace("RCache inc '$key' by $step");
if ($step > 1) {
return $this->cache->incrBy($key, $step);
}
return $this->cache->incr($key);
} | @param string $key
@param int $step
@return int | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/cache/RCache.php#L90-L97 |
x2ts/x2ts | src/cache/RCache.php | RCache.dec | public function dec($key, $step = 1) {
X::logger()->trace("RCache dec '$key' by $step");
if ($step > 1) {
return $this->cache->decrBy($key, $step);
}
return $this->cache->decr($key);
} | php | public function dec($key, $step = 1) {
X::logger()->trace("RCache dec '$key' by $step");
if ($step > 1) {
return $this->cache->decrBy($key, $step);
}
return $this->cache->decr($key);
} | @param string $key
@param int $step
@return int | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/cache/RCache.php#L105-L112 |
fxpio/fxp-doctrine-console | Exception/ValidationException.php | ValidationException.buildMessage | private function buildMessage(ConstraintViolationListInterface $violations)
{
$msg = '';
$errors = [];
$childrenErrors = [];
/* @var ConstraintViolationInterface $violation */
foreach ($violations as $violation) {
if (null === $violation->getPropertyPath()) {
$errors[] = $violation->getMessage();
} else {
$childrenErrors[$violation->getPropertyPath()][] = $violation->getMessage();
}
}
$msg = $this->buildGlobalErrors($errors, $msg);
$msg = $this->buildChildrenErrors($childrenErrors, $msg);
return $msg;
} | php | private function buildMessage(ConstraintViolationListInterface $violations)
{
$msg = '';
$errors = [];
$childrenErrors = [];
/* @var ConstraintViolationInterface $violation */
foreach ($violations as $violation) {
if (null === $violation->getPropertyPath()) {
$errors[] = $violation->getMessage();
} else {
$childrenErrors[$violation->getPropertyPath()][] = $violation->getMessage();
}
}
$msg = $this->buildGlobalErrors($errors, $msg);
$msg = $this->buildChildrenErrors($childrenErrors, $msg);
return $msg;
} | Build the message.
@param ConstraintViolationListInterface $violations The constraint violation list
@return string | https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Exception/ValidationException.php#L44-L63 |
fxpio/fxp-doctrine-console | Exception/ValidationException.php | ValidationException.buildGlobalErrors | private function buildGlobalErrors(array $errors, $msg)
{
if (!empty($errors)) {
$msg .= sprintf('%s- errors:', PHP_EOL);
foreach ($errors as $error) {
$msg .= sprintf('%s - %s', PHP_EOL, $error);
}
}
return $msg;
} | php | private function buildGlobalErrors(array $errors, $msg)
{
if (!empty($errors)) {
$msg .= sprintf('%s- errors:', PHP_EOL);
foreach ($errors as $error) {
$msg .= sprintf('%s - %s', PHP_EOL, $error);
}
}
return $msg;
} | Build the global errors and returns the exception message.
@param string[] $errors The error messages
@param string $msg The exception message
@return string | https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Exception/ValidationException.php#L73-L84 |
fxpio/fxp-doctrine-console | Exception/ValidationException.php | ValidationException.buildChildrenErrors | private function buildChildrenErrors(array $childrenErrors, $msg)
{
if (!empty($childrenErrors)) {
$msg .= PHP_EOL.'- children:';
foreach ($childrenErrors as $child => $errors) {
$msg .= sprintf('%s - %s', PHP_EOL, $child);
$msg .= sprintf('%s - errors:', PHP_EOL);
foreach ($errors as $error) {
$msg .= sprintf('%s - %s', PHP_EOL, $error);
}
}
}
return $msg;
} | php | private function buildChildrenErrors(array $childrenErrors, $msg)
{
if (!empty($childrenErrors)) {
$msg .= PHP_EOL.'- children:';
foreach ($childrenErrors as $child => $errors) {
$msg .= sprintf('%s - %s', PHP_EOL, $child);
$msg .= sprintf('%s - errors:', PHP_EOL);
foreach ($errors as $error) {
$msg .= sprintf('%s - %s', PHP_EOL, $error);
}
}
}
return $msg;
} | Build the children errors and returns the exception message.
@param array $childrenErrors The children error messages
@param string $msg The exception message
@return string | https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Exception/ValidationException.php#L94-L110 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/Simple.php | Simple.fetch_simple_list | public function fetch_simple_list($sql)
{
if (empty($sql)) return false;
$result = array();
$res = $this->query($sql);
while (($row = @mysql_fetch_array($res)) !== false) {
$result[] = $row[0];
}
$this->free($res);
return $result;
} | php | public function fetch_simple_list($sql)
{
if (empty($sql)) return false;
$result = array();
$res = $this->query($sql);
while (($row = @mysql_fetch_array($res)) !== false) {
$result[] = $row[0];
}
$this->free($res);
return $result;
} | fetches an array with only 1 dimension
"SELECT <col_name> FROM <tablename>
array($col_entry1,$col_entry2)
@param $sql string
@return array | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/Simple.php#L56-L70 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/Simple.php | Simple.fetch_assoc | public function fetch_assoc($sql)
{
if (empty($sql)) return false;
$res = $this->query($sql);
$result = @mysql_fetch_assoc($res);
$this->free($res);
return $result;
} | php | public function fetch_assoc($sql)
{
if (empty($sql)) return false;
$res = $this->query($sql);
$result = @mysql_fetch_assoc($res);
$this->free($res);
return $result;
} | fetches an associative array
@param $sql string
@return bool array | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/Simple.php#L80-L90 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/Simple.php | Simple.fetch_assoc_list | public function fetch_assoc_list($sql, $assign_by = null)
{
if (empty($sql)) return false;
$result = array();
// send the query
$res = $this->query($sql);
if (empty($res)) return false;
while (($row = @mysql_fetch_assoc($res)) !== false) {
if (!empty($assign_by)) {
$result[$row[$assign_by]] = $row;
} elseif (!empty($assign_by) && is_array($assign_by)) {
$key = '';
// for more complex keys
foreach ($assign_by as $key_w) {
$key = "- $row[$key_w]";
}
// removes the first '- '
$key = substr($key, 2);
$result[$key] = $row;
} else {
$result[] = $row;
}
}
// free the ressource afterwards
$this->free($res);
return $result;
} | php | public function fetch_assoc_list($sql, $assign_by = null)
{
if (empty($sql)) return false;
$result = array();
// send the query
$res = $this->query($sql);
if (empty($res)) return false;
while (($row = @mysql_fetch_assoc($res)) !== false) {
if (!empty($assign_by)) {
$result[$row[$assign_by]] = $row;
} elseif (!empty($assign_by) && is_array($assign_by)) {
$key = '';
// for more complex keys
foreach ($assign_by as $key_w) {
$key = "- $row[$key_w]";
}
// removes the first '- '
$key = substr($key, 2);
$result[$key] = $row;
} else {
$result[] = $row;
}
}
// free the ressource afterwards
$this->free($res);
return $result;
} | simple wrapper for those lazy bastards who don't wanna
control their own ressources
@param $sql string
@param $assign_by string
@return array bool | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/Simple.php#L102-L135 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/Simple.php | Simple.fetch_object | public function fetch_object($sql)
{
if (empty($sql)) return false;
$res = $this->query($sql);
$result = @mysql_fetch_object($res);
$this->free($res);
return $result;
} | php | public function fetch_object($sql)
{
if (empty($sql)) return false;
$res = $this->query($sql);
$result = @mysql_fetch_object($res);
$this->free($res);
return $result;
} | fetches an object of the current row
@param $sql string
@return bool object | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/Simple.php#L145-L155 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/Simple.php | Simple.fetch_string | public function fetch_string($sql)
{
if (empty($sql)) return false;
$res = $this->query($sql);
$row = @mysql_fetch_array($res);
return (string)$row[0];
} | php | public function fetch_string($sql)
{
if (empty($sql)) return false;
$res = $this->query($sql);
$row = @mysql_fetch_array($res);
return (string)$row[0];
} | fetches a string wrapper for
easy use
@param $sql string
@return string | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/Simple.php#L207-L216 |
enebe-nb/phergie-irc-plugin-react-tell | src/Db/PdoWrapper.php | PdoWrapper.retrieveMessages | public function retrieveMessages($recipient)
{
$statement = $this->connection->prepare(
'SELECT "timestamp", "sender", "message"
FROM "phergie-plugin-tell"
WHERE "recipient" = ?;'
);
if ($statement->execute([ $recipient ])) {
$messages = $statement->fetchAll(\PDO::FETCH_ASSOC);
$this->connection->prepare(
'DELETE FROM "phergie-plugin-tell"
WHERE "recipient" = ?;'
)->execute([ $recipient ]);
return $messages;
}
return [];
} | php | public function retrieveMessages($recipient)
{
$statement = $this->connection->prepare(
'SELECT "timestamp", "sender", "message"
FROM "phergie-plugin-tell"
WHERE "recipient" = ?;'
);
if ($statement->execute([ $recipient ])) {
$messages = $statement->fetchAll(\PDO::FETCH_ASSOC);
$this->connection->prepare(
'DELETE FROM "phergie-plugin-tell"
WHERE "recipient" = ?;'
)->execute([ $recipient ]);
return $messages;
}
return [];
} | Remove and returns messages for $recipient
@param string $recipient
@return array messages | https://github.com/enebe-nb/phergie-irc-plugin-react-tell/blob/8f18133c4165ce93f09434643c11ceea625b408c/src/Db/PdoWrapper.php#L72-L92 |
enebe-nb/phergie-irc-plugin-react-tell | src/Db/PdoWrapper.php | PdoWrapper.postMessage | public function postMessage($sender, $recipient, $message)
{
if ($this->maxMessages) {
$statement = $this->connection->prepare(
'SELECT COUNT(*) FROM "phergie-plugin-tell"
WHERE "recipient" = ?;'
);
$statement->execute([ $recipient ]);
if ($statement->fetchColumn(0) >= $this->maxMessages) {
return false;
}
}
$this->connection->prepare(
'INSERT INTO "phergie-plugin-tell"
("sender", "recipient", "message")
VALUES (?, ?, ?);'
)->execute([ $sender, $recipient, $message ]);
return true;
} | php | public function postMessage($sender, $recipient, $message)
{
if ($this->maxMessages) {
$statement = $this->connection->prepare(
'SELECT COUNT(*) FROM "phergie-plugin-tell"
WHERE "recipient" = ?;'
);
$statement->execute([ $recipient ]);
if ($statement->fetchColumn(0) >= $this->maxMessages) {
return false;
}
}
$this->connection->prepare(
'INSERT INTO "phergie-plugin-tell"
("sender", "recipient", "message")
VALUES (?, ?, ?);'
)->execute([ $sender, $recipient, $message ]);
return true;
} | Post a message from $sender to $recipient
@param string $sender
@param string $recipient
@param string $message
@return boolean true on success, false on failure | https://github.com/enebe-nb/phergie-irc-plugin-react-tell/blob/8f18133c4165ce93f09434643c11ceea625b408c/src/Db/PdoWrapper.php#L102-L123 |
takashiki/mis | src/App.php | App.map | public function map(array $methods, $pattern, $callable)
{
$callable = is_string($callable) ? $this->resolveCallable($callable) : $callable;
if ($callable instanceof Closure) {
$callable = $callable->bindTo($this);
}
$route = $this->container->get('router')->map($methods, $pattern, $callable);
if (is_callable([$route, 'setContainer'])) {
$route->setContainer($this->container);
}
if (is_callable([$route, 'setOutputBuffering'])) {
$route->setOutputBuffering($this->container->get('settings')['outputBuffering']);
}
return $route;
} | php | public function map(array $methods, $pattern, $callable)
{
$callable = is_string($callable) ? $this->resolveCallable($callable) : $callable;
if ($callable instanceof Closure) {
$callable = $callable->bindTo($this);
}
$route = $this->container->get('router')->map($methods, $pattern, $callable);
if (is_callable([$route, 'setContainer'])) {
$route->setContainer($this->container);
}
if (is_callable([$route, 'setOutputBuffering'])) {
$route->setOutputBuffering($this->container->get('settings')['outputBuffering']);
}
return $route;
} | Add route with multiple methods.
@param string[] $methods Numeric array of HTTP method names
@param string $pattern The route URI pattern
@param mixed $callable The route callback routine
@return RouteInterface | https://github.com/takashiki/mis/blob/a40d228d868af4e77c6156d297086ca94b8fbac8/src/App.php#L170-L187 |
takashiki/mis | src/App.php | App.group | public function group($pattern, $callable)
{
/** @var RouteGroup $group */
$group = $this->container->get('router')->pushGroup($pattern, $callable);
$group->setContainer($this->container);
$group($this);
$this->container->get('router')->popGroup();
return $group;
} | php | public function group($pattern, $callable)
{
/** @var RouteGroup $group */
$group = $this->container->get('router')->pushGroup($pattern, $callable);
$group->setContainer($this->container);
$group($this);
$this->container->get('router')->popGroup();
return $group;
} | Route Groups.
This method accepts a route pattern and a callback. All route
declarations in the callback will be prepended by the group(s)
that it is in.
@param string $pattern
@param callable $callable
@return RouteGroupInterface | https://github.com/takashiki/mis/blob/a40d228d868af4e77c6156d297086ca94b8fbac8/src/App.php#L201-L210 |
ekyna/AdminBundle | Dashboard/Dashboard.php | Dashboard.hasWidget | public function hasWidget($nameOrWidget)
{
$name = $nameOrWidget instanceof WidgetInterface ? $nameOrWidget->getName() : $nameOrWidget;
return array_key_exists($name, $this->widgets);
} | php | public function hasWidget($nameOrWidget)
{
$name = $nameOrWidget instanceof WidgetInterface ? $nameOrWidget->getName() : $nameOrWidget;
return array_key_exists($name, $this->widgets);
} | Returns whether the dashboard has the widget or not.
@param string|WidgetInterface $nameOrWidget
@return bool | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Dashboard/Dashboard.php#L34-L39 |
ekyna/AdminBundle | Dashboard/Dashboard.php | Dashboard.addWidget | public function addWidget(WidgetInterface $widget)
{
if ($this->hasWidget($widget)) {
throw new \InvalidArgumentException(sprintf('Widget "%s" is already registered.', $widget->getName()));
}
$this->widgets[$widget->getName()] = $widget;
return $this;
} | php | public function addWidget(WidgetInterface $widget)
{
if ($this->hasWidget($widget)) {
throw new \InvalidArgumentException(sprintf('Widget "%s" is already registered.', $widget->getName()));
}
$this->widgets[$widget->getName()] = $widget;
return $this;
} | Adds the widget.
@param WidgetInterface $widget
@return Dashboard | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Dashboard/Dashboard.php#L47-L56 |
schpill/thin | src/OneModel.php | OneWrapper.filter | public function filter()
{
$args = func_get_args();
$filter_function = array_shift($args);
array_unshift($args, $this);
if (method_exists($this->_class_name, $filter_function)) {
return call_user_func_array([$this->_class_name, $filter_function], $args);
}
} | php | public function filter()
{
$args = func_get_args();
$filter_function = array_shift($args);
array_unshift($args, $this);
if (method_exists($this->_class_name, $filter_function)) {
return call_user_func_array([$this->_class_name, $filter_function], $args);
}
} | Add a custom filter to the method chain specified on the
model class. This allows custom queries to be added
to models. The filter should take an instance of the
One wrapper as its first argument and return an instance
of the One wrapper. Any arguments passed to this method
after the name of the filter will be passed to the called
filter function as arguments after the One class.
@return OneWrapper | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/OneModel.php#L35-L44 |
schpill/thin | src/OneModel.php | OneWrapper.for_table | public static function for_table($table_name, $connection_name = parent::DEFAULT_CONNECTION)
{
self::_setupDb($connection_name);
return new self($table_name, [], $connection_name);
} | php | public static function for_table($table_name, $connection_name = parent::DEFAULT_CONNECTION)
{
self::_setupDb($connection_name);
return new self($table_name, [], $connection_name);
} | Factory method, return an instance of this
class bound to the supplied table name.
A repeat of content in parent::for_table, so that
created class is OneWrapper, not One
@param string $table_name
@param string $connection_name
@return OneWrapper | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/OneModel.php#L57-L62 |
schpill/thin | src/OneModel.php | OneWrapper._createModelInstance | protected function _createModelInstance($One)
{
if ($One === false) {
return false;
}
$model = new $this->_class_name();
$model->set_one($One);
return $model;
} | php | protected function _createModelInstance($One)
{
if ($One === false) {
return false;
}
$model = new $this->_class_name();
$model->set_one($One);
return $model;
} | Method to create an instance of the model class
associated with this wrapper and populate
it with the supplied One instance.
@param One $One
@return bool|Model | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/OneModel.php#L72-L82 |
schpill/thin | src/OneModel.php | OneWrapper.find_many | public function find_many()
{
$results = parent::find_many();
foreach($results as $key => $result) {
$results[$key] = $this->_createModelInstance($result);
}
return $results;
} | php | public function find_many()
{
$results = parent::find_many();
foreach($results as $key => $result) {
$results[$key] = $this->_createModelInstance($result);
}
return $results;
} | Wrap One's find_many method to return
an array of instances of the class associated
with this wrapper instead of the raw One class.
@return Array | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/OneModel.php#L104-L113 |
schpill/thin | src/OneModel.php | OneModel._getStaticProperty | protected static function _getStaticProperty($class_name, $property, $default = null)
{
if (!class_exists($class_name) || !property_exists($class_name, $property)) {
return $default;
}
$properties = get_class_vars($class_name);
return $properties[$property];
} | php | protected static function _getStaticProperty($class_name, $property, $default = null)
{
if (!class_exists($class_name) || !property_exists($class_name, $property)) {
return $default;
}
$properties = get_class_vars($class_name);
return $properties[$property];
} | Retrieve the value of a static property on a class. If the
class or the property does not exist, returns the default
value supplied as the third argument (which defaults to null).
@param string $class_name
@param string $property
@param null|string $default
@return string | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/OneModel.php#L175-L184 |
schpill/thin | src/OneModel.php | OneModel._getTableName | protected static function _getTableName($class_name)
{
$specified_table_name = self::_getStaticProperty($class_name, '_table');
$use_short_class_name = self::_getStaticProperty($class_name, '_table_use_short_name');
if ($use_short_class_name) {
$exploded_class_name = explode('\\', $class_name);
$class_name = end($exploded_class_name);
}
if (is_null($specified_table_name)) {
return self::_classNameToTableName($class_name);
}
return $specified_table_name;
} | php | protected static function _getTableName($class_name)
{
$specified_table_name = self::_getStaticProperty($class_name, '_table');
$use_short_class_name = self::_getStaticProperty($class_name, '_table_use_short_name');
if ($use_short_class_name) {
$exploded_class_name = explode('\\', $class_name);
$class_name = end($exploded_class_name);
}
if (is_null($specified_table_name)) {
return self::_classNameToTableName($class_name);
}
return $specified_table_name;
} | Static method to get a table name given a class name.
If the supplied class has a public static property
named $_table, the value of this property will be
returned.
If not, the class name will be converted using
the _classNameToTableName method method.
If public static property $_table_use_short_name == true
then $class_name passed to _classNameToTableName is
stripped of namespace infOneation.
@param string $class_name
@return string | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/OneModel.php#L202-L217 |
schpill/thin | src/OneModel.php | OneModel.factory | public static function factory($class_name, $connection_name = null)
{
$class_name = self::$auto_prefix_models . $class_name;
$table_name = self::_getTableName($class_name);
if ($connection_name == null) {
$connection_name = self::_getStaticProperty(
$class_name,
'_connection_name',
OneWrapper::DEFAULT_CONNECTION
);
}
$wrapper = OneWrapper::for_table($table_name, $connection_name);
$wrapper->set_class_name($class_name);
$wrapper->use_id_column(self::_getIdColumnName($class_name));
return $wrapper;
} | php | public static function factory($class_name, $connection_name = null)
{
$class_name = self::$auto_prefix_models . $class_name;
$table_name = self::_getTableName($class_name);
if ($connection_name == null) {
$connection_name = self::_getStaticProperty(
$class_name,
'_connection_name',
OneWrapper::DEFAULT_CONNECTION
);
}
$wrapper = OneWrapper::for_table($table_name, $connection_name);
$wrapper->set_class_name($class_name);
$wrapper->use_id_column(self::_getIdColumnName($class_name));
return $wrapper;
} | Factory method used to acquire instances of the given class.
The class name should be supplied as a string, and the class
should already have been loaded by PHP (or a suitable autoloader
should exist). This method actually returns a wrapped One object
which allows a database query to be built. The wrapped One object is
responsible for returning instances of the correct class when
its find_one or find_many methods are called.
@param string $class_name
@param null|string $connection_name
@return OneWrapper | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/OneModel.php#L286-L304 |
schpill/thin | src/OneModel.php | OneModel._hasOneOrMany | protected function _hasOneOrMany($associated_class_name, $foreign_key_name = null, $foreign_key_name_in_current_models_table = null, $connection_name = null)
{
$base_table_name = self::_getTableName(get_class($this));
$foreign_key_name = self::_buildForeignKeyName($foreign_key_name, $base_table_name);
$where_value = ''; //Value of foreign_table.{$foreign_key_name} we're
//looking for. Where foreign_table is the actual
//database table in the associated model.
if(is_null($foreign_key_name_in_current_models_table)) {
//Match foreign_table.{$foreign_key_name} with the value of
//{$this->_table}.{$this->id()}
$where_value = $this->id();
} else {
//Match foreign_table.{$foreign_key_name} with the value of
//{$this->_table}.{$foreign_key_name_in_current_models_table}
$where_value = $this->$foreign_key_name_in_current_models_table;
}
return self::factory($associated_class_name, $connection_name)->where($foreign_key_name, $where_value);
} | php | protected function _hasOneOrMany($associated_class_name, $foreign_key_name = null, $foreign_key_name_in_current_models_table = null, $connection_name = null)
{
$base_table_name = self::_getTableName(get_class($this));
$foreign_key_name = self::_buildForeignKeyName($foreign_key_name, $base_table_name);
$where_value = ''; //Value of foreign_table.{$foreign_key_name} we're
//looking for. Where foreign_table is the actual
//database table in the associated model.
if(is_null($foreign_key_name_in_current_models_table)) {
//Match foreign_table.{$foreign_key_name} with the value of
//{$this->_table}.{$this->id()}
$where_value = $this->id();
} else {
//Match foreign_table.{$foreign_key_name} with the value of
//{$this->_table}.{$foreign_key_name_in_current_models_table}
$where_value = $this->$foreign_key_name_in_current_models_table;
}
return self::factory($associated_class_name, $connection_name)->where($foreign_key_name, $where_value);
} | Internal method to construct the queries for both the has_one and
has_many methods. These two types of association are identical; the
only difference is whether find_one or find_many is used to complete
the method chain.
@param string $associated_class_name
@param null|string $foreign_key_name
@param null|string $foreign_key_name_in_current_models_table
@param null|string $connection_name
@return OneWrapper | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/OneModel.php#L318-L338 |
schpill/thin | src/OneModel.php | OneModel.has_one | protected function has_one($associated_class_name, $foreign_key_name = null, $foreign_key_name_in_current_models_table = null, $connection_name = null)
{
return $this->_hasOneOrMany($associated_class_name, $foreign_key_name, $foreign_key_name_in_current_models_table, $connection_name);
} | php | protected function has_one($associated_class_name, $foreign_key_name = null, $foreign_key_name_in_current_models_table = null, $connection_name = null)
{
return $this->_hasOneOrMany($associated_class_name, $foreign_key_name, $foreign_key_name_in_current_models_table, $connection_name);
} | Helper method to manage one-to-one relations where the foreign
key is on the associated table.
@param string $associated_class_name
@param null|string $foreign_key_name
@param null|string $foreign_key_name_in_current_models_table
@param null|string $connection_name
@return OneWrapper | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/OneModel.php#L350-L353 |
schpill/thin | src/OneModel.php | OneModel.has_many | protected function has_many($associated_class_name, $foreign_key_name = null, $foreign_key_name_in_current_models_table = null, $connection_name = null)
{
return $this->_hasOneOrMany($associated_class_name, $foreign_key_name, $foreign_key_name_in_current_models_table, $connection_name);
} | php | protected function has_many($associated_class_name, $foreign_key_name = null, $foreign_key_name_in_current_models_table = null, $connection_name = null)
{
return $this->_hasOneOrMany($associated_class_name, $foreign_key_name, $foreign_key_name_in_current_models_table, $connection_name);
} | Helper method to manage one-to-many relations where the foreign
key is on the associated table.
@param string $associated_class_name
@param null|string $foreign_key_name
@param null|string $foreign_key_name_in_current_models_table
@param null|string $connection_name
@return OneWrapper | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/OneModel.php#L365-L368 |
schpill/thin | src/OneModel.php | OneModel.belongs_to | protected function belongs_to($associated_class_name, $foreign_key_name = null, $foreign_key_name_in_associated_models_table = null, $connection_name = null)
{
$associated_table_name = self::_getTableName(self::$auto_prefix_models . $associated_class_name);
$foreign_key_name = self::_buildForeignKeyName($foreign_key_name, $associated_table_name);
$associated_object_id = $this->$foreign_key_name;
$desired_record = null;
if( is_null($foreign_key_name_in_associated_models_table) ) {
//"{$associated_table_name}.primary_key = {$associated_object_id}"
//NOTE: primary_key is a placeholder for the actual primary key column's name
//in $associated_table_name
$desired_record = self::factory($associated_class_name, $connection_name)->where_id_is($associated_object_id);
} else {
//"{$associated_table_name}.{$foreign_key_name_in_associated_models_table} = {$associated_object_id}"
$desired_record = self::factory($associated_class_name, $connection_name)->where($foreign_key_name_in_associated_models_table, $associated_object_id);
}
return $desired_record;
} | php | protected function belongs_to($associated_class_name, $foreign_key_name = null, $foreign_key_name_in_associated_models_table = null, $connection_name = null)
{
$associated_table_name = self::_getTableName(self::$auto_prefix_models . $associated_class_name);
$foreign_key_name = self::_buildForeignKeyName($foreign_key_name, $associated_table_name);
$associated_object_id = $this->$foreign_key_name;
$desired_record = null;
if( is_null($foreign_key_name_in_associated_models_table) ) {
//"{$associated_table_name}.primary_key = {$associated_object_id}"
//NOTE: primary_key is a placeholder for the actual primary key column's name
//in $associated_table_name
$desired_record = self::factory($associated_class_name, $connection_name)->where_id_is($associated_object_id);
} else {
//"{$associated_table_name}.{$foreign_key_name_in_associated_models_table} = {$associated_object_id}"
$desired_record = self::factory($associated_class_name, $connection_name)->where($foreign_key_name_in_associated_models_table, $associated_object_id);
}
return $desired_record;
} | Helper method to manage one-to-one and one-to-many relations where
the foreign key is on the base table.
@param string $associated_class_name
@param null|string $foreign_key_name
@param null|string $foreign_key_name_in_associated_models_table
@param null|string $connection_name
@return $this|null | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/OneModel.php#L380-L399 |
schpill/thin | src/OneModel.php | OneModel.has_many_through | protected function has_many_through($associated_class_name, $join_class_name = null, $key_to_base_table = null, $key_to_associated_table = null, $key_in_base_table = null, $key_in_associated_table = null, $connection_name = null)
{
$base_class_name = get_class($this);
// The class name of the join model, if not supplied, is
// fOneed by concatenating the names of the base class
// and the associated class, in alphabetical order.
if (is_null($join_class_name)) {
$model = explode('\\', $base_class_name);
$model_name = end($model);
if (substr($model_name, 0, strlen(self::$auto_prefix_models)) == self::$auto_prefix_models) {
$model_name = substr($model_name, strlen(self::$auto_prefix_models), strlen($model_name));
}
$class_names = [$model_name, $associated_class_name];
sort($class_names, SORT_STRING);
$join_class_name = join("", $class_names);
}
// Get table names for each class
$base_table_name = self::_getTableName($base_class_name);
$associated_table_name = self::_getTableName(self::$auto_prefix_models . $associated_class_name);
$join_table_name = self::_getTableName(self::$auto_prefix_models . $join_class_name);
// Get ID column names
$base_table_id_column = (is_null($key_in_base_table)) ?
self::_getIdColumnName($base_class_name) :
$key_in_base_table;
$associated_table_id_column = (is_null($key_in_associated_table)) ?
self::_getIdColumnName(self::$auto_prefix_models . $associated_class_name) :
$key_in_associated_table;
// Get the column names for each side of the join table
$key_to_base_table = self::_buildForeignKeyName($key_to_base_table, $base_table_name);
$key_to_associated_table = self::_buildForeignKeyName($key_to_associated_table, $associated_table_name);
/*
" SELECT {$associated_table_name}.*
FROM {$associated_table_name} JOIN {$join_table_name}
ON {$associated_table_name}.{$associated_table_id_column} = {$join_table_name}.{$key_to_associated_table}
WHERE {$join_table_name}.{$key_to_base_table} = {$this->$base_table_id_column} ;"
*/
return self::factory($associated_class_name, $connection_name)
->select("{$associated_table_name}.*")
->join($join_table_name, ["{$associated_table_name}.{$associated_table_id_column}", '=', "{$join_table_name}.{$key_to_associated_table}"])
->where("{$join_table_name}.{$key_to_base_table}", $this->$base_table_id_column);
} | php | protected function has_many_through($associated_class_name, $join_class_name = null, $key_to_base_table = null, $key_to_associated_table = null, $key_in_base_table = null, $key_in_associated_table = null, $connection_name = null)
{
$base_class_name = get_class($this);
// The class name of the join model, if not supplied, is
// fOneed by concatenating the names of the base class
// and the associated class, in alphabetical order.
if (is_null($join_class_name)) {
$model = explode('\\', $base_class_name);
$model_name = end($model);
if (substr($model_name, 0, strlen(self::$auto_prefix_models)) == self::$auto_prefix_models) {
$model_name = substr($model_name, strlen(self::$auto_prefix_models), strlen($model_name));
}
$class_names = [$model_name, $associated_class_name];
sort($class_names, SORT_STRING);
$join_class_name = join("", $class_names);
}
// Get table names for each class
$base_table_name = self::_getTableName($base_class_name);
$associated_table_name = self::_getTableName(self::$auto_prefix_models . $associated_class_name);
$join_table_name = self::_getTableName(self::$auto_prefix_models . $join_class_name);
// Get ID column names
$base_table_id_column = (is_null($key_in_base_table)) ?
self::_getIdColumnName($base_class_name) :
$key_in_base_table;
$associated_table_id_column = (is_null($key_in_associated_table)) ?
self::_getIdColumnName(self::$auto_prefix_models . $associated_class_name) :
$key_in_associated_table;
// Get the column names for each side of the join table
$key_to_base_table = self::_buildForeignKeyName($key_to_base_table, $base_table_name);
$key_to_associated_table = self::_buildForeignKeyName($key_to_associated_table, $associated_table_name);
/*
" SELECT {$associated_table_name}.*
FROM {$associated_table_name} JOIN {$join_table_name}
ON {$associated_table_name}.{$associated_table_id_column} = {$join_table_name}.{$key_to_associated_table}
WHERE {$join_table_name}.{$key_to_base_table} = {$this->$base_table_id_column} ;"
*/
return self::factory($associated_class_name, $connection_name)
->select("{$associated_table_name}.*")
->join($join_table_name, ["{$associated_table_name}.{$associated_table_id_column}", '=', "{$join_table_name}.{$key_to_associated_table}"])
->where("{$join_table_name}.{$key_to_base_table}", $this->$base_table_id_column);
} | Helper method to manage many-to-many relationships via an intermediate model. See
README for a full explanation of the parameters.
@param string $associated_class_name
@param null|string $join_class_name
@param null|string $key_to_base_table
@param null|string $key_to_associated_table
@param null|string $key_in_base_table
@param null|string $key_in_associated_table
@param null|string $connection_name
@return OneWrapper | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/OneModel.php#L414-L462 |
schpill/thin | src/OneModel.php | OneModel.set | public function set($property, $value = null)
{
$this->One->set($property, $value);
return $this;
} | php | public function set($property, $value = null)
{
$this->One->set($property, $value);
return $this;
} | Setter method, allows $model->set('property', 'value') access to data.
@param string|array $property
@param string|null $value
@return Model | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/OneModel.php#L527-L532 |
schpill/thin | src/OneModel.php | OneModel.set_expr | public function set_expr($property, $value = null)
{
$this->One->set_expr($property, $value);
return $this;
} | php | public function set_expr($property, $value = null)
{
$this->One->set_expr($property, $value);
return $this;
} | Setter method, allows $model->set_expr('property', 'value') access to data.
@param string|array $property
@param string|null $value
@return Model | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/OneModel.php#L541-L546 |
nasumilu/geometry | src/Serializer/Encoder/AbstractEncoder.php | AbstractEncoder.encode | public function encode($data, $format, array $context = []) {
return $this->encoder->encode($data, $format, $context);
} | php | public function encode($data, $format, array $context = []) {
return $this->encoder->encode($data, $format, $context);
} | {@inheritDoc} | https://github.com/nasumilu/geometry/blob/000fafe3e61f1d0682952ad236b7486dded65eae/src/Serializer/Encoder/AbstractEncoder.php#L80-L82 |
3ev/wordpress-core | src/Tev/Field/Factory.php | Factory.create | public function create($field, AbstractPost $post)
{
$data = get_field_object($field, $post->getId());
return $this->createFromField($data);
} | php | public function create($field, AbstractPost $post)
{
$data = get_field_object($field, $post->getId());
return $this->createFromField($data);
} | Create a new custom field object.
If the field is not registered, a `\Tev\Field\Model\NullField` will be
returned.
@param string $field Field name or ID
@param \Tev\Post\Model\AbstractPost $post Post object field is for
@return \Tev\Field\Model\AbstractField Field object
@throws \Exception If field type is not registered | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Field/Factory.php#L97-L102 |
3ev/wordpress-core | src/Tev/Field/Factory.php | Factory.createFromField | public function createFromField($field, $value = null)
{
if (!is_array($field)) {
return new NullField;
}
if ($value !== null) {
$field['value'] = $value;
}
return $this->resolve($field['type'], $field);
} | php | public function createFromField($field, $value = null)
{
if (!is_array($field)) {
return new NullField;
}
if ($value !== null) {
$field['value'] = $value;
}
return $this->resolve($field['type'], $field);
} | Create a new custom field object from an existing set of field data.
If the field is not registered, a `\Tev\Field\Model\NullField` will be
returned.
@param array $field Field data array
@param mixed $value If supplied, will be set as the fields value
@return \Tev\Field\Model\AbstractField Field object
@throws \Exception If field type is not registered | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Field/Factory.php#L116-L127 |
3ev/wordpress-core | src/Tev/Field/Factory.php | Factory.resolve | protected function resolve($type, array $data)
{
if ($this->registered($type)) {
$f = $this->registry[$type];
if ($f instanceof Closure) {
return $f($data, $this->app);
} else {
return new $f($data);
}
} else {
throw new Exception("Field type $type not registered");
}
} | php | protected function resolve($type, array $data)
{
if ($this->registered($type)) {
$f = $this->registry[$type];
if ($f instanceof Closure) {
return $f($data, $this->app);
} else {
return new $f($data);
}
} else {
throw new Exception("Field type $type not registered");
}
} | Resolve a field object using its type, from the registered factory
functions.
@param string $type Field type
@param array $data Field data
@return \Tev\Field\Model\AbstractField Field object
@throws \Exception If field type is not registered | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Field/Factory.php#L153-L165 |
MDooley47/laravel-urlvalidator | src/Rules/Path.php | Path.passes | public function passes($attribute, $value, $parameters, $validator)
{
return Str::is(Str::lower($parameters[0]), Str::lower(parse_url($value, PHP_URL_PATH)));
} | php | public function passes($attribute, $value, $parameters, $validator)
{
return Str::is(Str::lower($parameters[0]), Str::lower(parse_url($value, PHP_URL_PATH)));
} | Determine if the validation rule passes.
@param $attribute
@param $value
@param $parameters
@param $validator
@return bool | https://github.com/MDooley47/laravel-urlvalidator/blob/e35863a5ed70e010e316916c503b90adf4f0115c/src/Rules/Path.php#L22-L25 |
werx/validation | src/Validator.php | Validator.date | public static function date($input = null, $format = 'MM/DD/YYYY')
{
if (empty($input)) {
return true;
}
switch($format) {
case 'YYYY/MM/DD':
case 'YYYY-MM-DD':
list($y, $m, $d) = preg_split('/[-\.\/ ]/', $input);
break;
case 'YYYY/DD/MM':
case 'YYYY-DD-MM':
list($y, $d, $m) = preg_split('/[-\.\/ ]/', $input);
break;
case 'DD-MM-YYYY':
case 'DD/MM/YYYY':
list($d, $m, $y) = preg_split('/[-\.\/ ]/', $input);
break;
case 'MM-DD-YYYY':
case 'MM/DD/YYYY':
list($m, $d, $y) = preg_split('/[-\.\/ ]/', $input);
break;
case 'YYYYMMDD':
$y = substr($input, 0, 4);
$m = substr($input, 4, 2);
$d = substr($input, 6, 2);
break;
case 'YYYYDDMM':
$y = substr($input, 0, 4);
$d = substr($input, 4, 2);
$m = substr($input, 6, 2);
break;
default:
throw new \InvalidArgumentException("Invalid Date Format");
}
return checkdate($m, $d, $y);
} | php | public static function date($input = null, $format = 'MM/DD/YYYY')
{
if (empty($input)) {
return true;
}
switch($format) {
case 'YYYY/MM/DD':
case 'YYYY-MM-DD':
list($y, $m, $d) = preg_split('/[-\.\/ ]/', $input);
break;
case 'YYYY/DD/MM':
case 'YYYY-DD-MM':
list($y, $d, $m) = preg_split('/[-\.\/ ]/', $input);
break;
case 'DD-MM-YYYY':
case 'DD/MM/YYYY':
list($d, $m, $y) = preg_split('/[-\.\/ ]/', $input);
break;
case 'MM-DD-YYYY':
case 'MM/DD/YYYY':
list($m, $d, $y) = preg_split('/[-\.\/ ]/', $input);
break;
case 'YYYYMMDD':
$y = substr($input, 0, 4);
$m = substr($input, 4, 2);
$d = substr($input, 6, 2);
break;
case 'YYYYDDMM':
$y = substr($input, 0, 4);
$d = substr($input, 4, 2);
$m = substr($input, 6, 2);
break;
default:
throw new \InvalidArgumentException("Invalid Date Format");
}
return checkdate($m, $d, $y);
} | Datetime validation from http://www.phpro.org/examples/Validate-Date-Using-PHP.html | https://github.com/werx/validation/blob/d77bfa69fe14ca5c389a67220e8d1bfb7913310a/src/Validator.php#L13-L56 |
pmdevelopment/tool-bundle | Framework/Configuration/FontAwesomeConfig.php | FontAwesomeConfig.getClasses | public static function getClasses($version)
{
if (false === in_array($version, self::getVersions())) {
throw new \LogicException(sprintf("Version is not supported. Available: %s", implode(", ", self::getVersions())));
}
$version = explode(".", $version);
$subVersion = $version[1];
$icons = array();
/**
* 4.4.0 Icons
*/
if (4 <= $subVersion) {
$icons = FontAwesome\Version440::getIconsAll();
}
return $icons;
} | php | public static function getClasses($version)
{
if (false === in_array($version, self::getVersions())) {
throw new \LogicException(sprintf("Version is not supported. Available: %s", implode(", ", self::getVersions())));
}
$version = explode(".", $version);
$subVersion = $version[1];
$icons = array();
/**
* 4.4.0 Icons
*/
if (4 <= $subVersion) {
$icons = FontAwesome\Version440::getIconsAll();
}
return $icons;
} | Get Icon Classes
@param string $version
@return array | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Framework/Configuration/FontAwesomeConfig.php#L40-L59 |
phavour/phavour | Phavour/Session/Storage.php | Storage.lock | public function lock()
{
$this->_validate();
$_SESSION[$this->secretStorage]['locks'][$this->_namespaceName] = true;
return true;
} | php | public function lock()
{
$this->_validate();
$_SESSION[$this->secretStorage]['locks'][$this->_namespaceName] = true;
return true;
} | Lock the namespace, this will prevent removal of keys
@return boolean
@throws \Exception | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Session/Storage.php#L102-L107 |
phavour/phavour | Phavour/Session/Storage.php | Storage.unlock | public function unlock()
{
$this->_validate();
$_SESSION[$this->secretStorage]['locks'][$this->_namespaceName] = false;
return true;
} | php | public function unlock()
{
$this->_validate();
$_SESSION[$this->secretStorage]['locks'][$this->_namespaceName] = false;
return true;
} | Unlock the namespace, this will allow removal of keys
@return boolean
@throws \Exception | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Session/Storage.php#L115-L120 |
phavour/phavour | Phavour/Session/Storage.php | Storage.isLocked | public function isLocked()
{
$this->_validate();
if ($_SESSION[$this->secretStorage]['locks'][$this->_namespaceName] == true) {
return true;
}
return false;
} | php | public function isLocked()
{
$this->_validate();
if ($_SESSION[$this->secretStorage]['locks'][$this->_namespaceName] == true) {
return true;
}
return false;
} | Check if a namespace is currently locked.
@return boolean
@throws \Exception | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Session/Storage.php#L128-L135 |
phavour/phavour | Phavour/Session/Storage.php | Storage.set | public function set($name, $value)
{
if (!$this->isLocked()) {
$_SESSION[$this->publicStorage]['store'][$this->_namespaceName][$name] = $value;
return true;
}
return false;
} | php | public function set($name, $value)
{
if (!$this->isLocked()) {
$_SESSION[$this->publicStorage]['store'][$this->_namespaceName][$name] = $value;
return true;
}
return false;
} | Set a value in the current namespace
@param string $name
@param mixed $value
@return boolean result of save
@throws \Exception | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Session/Storage.php#L145-L152 |
phavour/phavour | Phavour/Session/Storage.php | Storage.get | public function get($name)
{
$this->_validate();
if (array_key_exists($name, $_SESSION[$this->publicStorage]['store'][$this->_namespaceName])) {
return $_SESSION[$this->publicStorage]['store'][$this->_namespaceName][$name];
}
return false;
} | php | public function get($name)
{
$this->_validate();
if (array_key_exists($name, $_SESSION[$this->publicStorage]['store'][$this->_namespaceName])) {
return $_SESSION[$this->publicStorage]['store'][$this->_namespaceName][$name];
}
return false;
} | Retrieve a single value from the namespace
@param string $name
@return mixed
@throws \Exception | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Session/Storage.php#L161-L168 |
phavour/phavour | Phavour/Session/Storage.php | Storage.getAll | public function getAll()
{
$this->_validate();
if (array_key_exists($this->_namespaceName, $_SESSION[$this->publicStorage]['store'])) {
return $_SESSION[$this->publicStorage]['store'][$this->_namespaceName];
}
return false;
} | php | public function getAll()
{
$this->_validate();
if (array_key_exists($this->_namespaceName, $_SESSION[$this->publicStorage]['store'])) {
return $_SESSION[$this->publicStorage]['store'][$this->_namespaceName];
}
return false;
} | Retrieve the entire namespace
@return array success | boolean false failure
@throws \Exception | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Session/Storage.php#L176-L183 |
phavour/phavour | Phavour/Session/Storage.php | Storage.remove | public function remove($name)
{
$this->_validate();
if (!$this->isLocked()) {
if (!$this->get($name)) {
return true;
}
unset($_SESSION[$this->publicStorage]['store'][$this->_namespaceName][$name]);
return true;
}
return false;
} | php | public function remove($name)
{
$this->_validate();
if (!$this->isLocked()) {
if (!$this->get($name)) {
return true;
}
unset($_SESSION[$this->publicStorage]['store'][$this->_namespaceName][$name]);
return true;
}
return false;
} | Remove an key from the namespace
@param string $name
@return boolean result of removal
@throws \Exception | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Session/Storage.php#L192-L203 |
phavour/phavour | Phavour/Session/Storage.php | Storage.removeAll | public function removeAll()
{
$this->_validate();
if (!$this->isLocked()) {
$_SESSION[$this->publicStorage]['store'][$this->_namespaceName] = array();
return true;
}
return false;
} | php | public function removeAll()
{
$this->_validate();
if (!$this->isLocked()) {
$_SESSION[$this->publicStorage]['store'][$this->_namespaceName] = array();
return true;
}
return false;
} | Clear all values currently held in this namespace
@return boolean status of removal
@throws \Exception | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Session/Storage.php#L211-L219 |
phavour/phavour | Phavour/Session/Storage.php | Storage.setup | protected function setup()
{
if (array_key_exists($this->secretStorage, $_SESSION)) {
if (!is_array($_SESSION[$this->secretStorage])) {
$_SESSION[$this->secretStorage] = array('locks' => array($this->_namespaceName => false));
} else {
if (!array_key_exists($this->_namespaceName, $_SESSION[$this->secretStorage]['locks'])) {
$_SESSION[$this->secretStorage]['locks'][$this->_namespaceName] = false;
} else {
if (!is_bool($_SESSION[$this->secretStorage]['locks'][$this->_namespaceName])) {
$_SESSION[$this->secretStorage]['locks'][$this->_namespaceName] = false;
}
}
}
} else {
$_SESSION[$this->secretStorage] = array('locks' => array($this->_namespaceName => false));
}
if (array_key_exists($this->publicStorage, $_SESSION)) {
if (array_key_exists('store', $_SESSION[$this->publicStorage])) {
if (!array_key_exists($this->_namespaceName, $_SESSION[$this->publicStorage]['store'])) {
$_SESSION[$this->publicStorage]['store'][$this->_namespaceName] = array();
}
} else {
$_SESSION[$this->publicStorage]['store'] = array($this->_namespaceName => array());
}
} else {
$_SESSION[$this->publicStorage] = array('store' => array($this->_namespaceName => array()));
}
return true;
} | php | protected function setup()
{
if (array_key_exists($this->secretStorage, $_SESSION)) {
if (!is_array($_SESSION[$this->secretStorage])) {
$_SESSION[$this->secretStorage] = array('locks' => array($this->_namespaceName => false));
} else {
if (!array_key_exists($this->_namespaceName, $_SESSION[$this->secretStorage]['locks'])) {
$_SESSION[$this->secretStorage]['locks'][$this->_namespaceName] = false;
} else {
if (!is_bool($_SESSION[$this->secretStorage]['locks'][$this->_namespaceName])) {
$_SESSION[$this->secretStorage]['locks'][$this->_namespaceName] = false;
}
}
}
} else {
$_SESSION[$this->secretStorage] = array('locks' => array($this->_namespaceName => false));
}
if (array_key_exists($this->publicStorage, $_SESSION)) {
if (array_key_exists('store', $_SESSION[$this->publicStorage])) {
if (!array_key_exists($this->_namespaceName, $_SESSION[$this->publicStorage]['store'])) {
$_SESSION[$this->publicStorage]['store'][$this->_namespaceName] = array();
}
} else {
$_SESSION[$this->publicStorage]['store'] = array($this->_namespaceName => array());
}
} else {
$_SESSION[$this->publicStorage] = array('store' => array($this->_namespaceName => array()));
}
return true;
} | Ensure the session contains the data we expect to see.
@return boolean | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Session/Storage.php#L243-L274 |
thelia-modules/SmartyFilter | Loop/SmartyFilterLoop.php | SmartyFilterLoop.parseResults | public function parseResults(LoopResult $loopResult)
{
foreach ($loopResult->getResultDataCollection() as $filter) {
$loopResultRow = new LoopResultRow($filter);
$loopResultRow->set("ID", $filter->getId())
->set("IS_TRANSLATED", $filter->getVirtualColumn('IS_TRANSLATED'))
->set("LOCALE", $filter->locale)
->set("TITLE", $filter->getVirtualColumn('i18n_TITLE'))
->set("CODE", $filter->getCode())
->set("DESCRIPTION", $filter->getVirtualColumn('i18n_DESCRIPTION'))
->set("ACTIVATE", $filter->getActive())
->set("TYPE", $filter->getFiltertype());
$loopResult->addRow($loopResultRow);
}
return $loopResult;
} | php | public function parseResults(LoopResult $loopResult)
{
foreach ($loopResult->getResultDataCollection() as $filter) {
$loopResultRow = new LoopResultRow($filter);
$loopResultRow->set("ID", $filter->getId())
->set("IS_TRANSLATED", $filter->getVirtualColumn('IS_TRANSLATED'))
->set("LOCALE", $filter->locale)
->set("TITLE", $filter->getVirtualColumn('i18n_TITLE'))
->set("CODE", $filter->getCode())
->set("DESCRIPTION", $filter->getVirtualColumn('i18n_DESCRIPTION'))
->set("ACTIVATE", $filter->getActive())
->set("TYPE", $filter->getFiltertype());
$loopResult->addRow($loopResultRow);
}
return $loopResult;
} | @param LoopResult $loopResult
@return LoopResult | https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Loop/SmartyFilterLoop.php#L41-L60 |
thelia-modules/SmartyFilter | Loop/SmartyFilterLoop.php | SmartyFilterLoop.getArgDefinitions | protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
new Argument(
'filtertype',
new TypeCollection(
new Type\AlphaNumStringListType()
)
),
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array(
'alpha',
'alpha-reverse',
'random',
'given_id'
))
),
'alpha'
)
);
} | php | protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
new Argument(
'filtertype',
new TypeCollection(
new Type\AlphaNumStringListType()
)
),
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array(
'alpha',
'alpha-reverse',
'random',
'given_id'
))
),
'alpha'
)
);
} | Definition of loop arguments
@return \Thelia\Core\Template\Loop\Argument\ArgumentCollection | https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Loop/SmartyFilterLoop.php#L67-L90 |
thelia-modules/SmartyFilter | Loop/SmartyFilterLoop.php | SmartyFilterLoop.buildModelCriteria | public function buildModelCriteria()
{
$search = SmartyFilterQuery::create();
/* manage translations */
$this->configureI18nProcessing($search, array('TITLE', 'DESCRIPTION'));
$id = $this->getId();
if (!is_null($id)) {
$search->filterById($id, Criteria::IN);
}
$type = $this->getFiltertype();
if (!is_null($type)) {
$search->filterByFiltertype($type, Criteria::IN);
}
$orders = $this->getOrder();
foreach ($orders as $order) {
switch ($order) {
case "alpha":
$search->addAscendingOrderByColumn('i18n_TITLE');
break;
case "alpha-reverse":
$search->addDescendingOrderByColumn('i18n_TITLE');
break;
case "given_id":
if (null === $id) {
throw new \InvalidArgumentException('Given_id order cannot be set without `id` argument');
}
foreach ($id as $singleId) {
$givenIdMatched = 'given_id_matched_' . $singleId;
$search->withColumn(SmartyFilterTableMap::ID . "='$singleId'", $givenIdMatched);
$search->orderBy($givenIdMatched, Criteria::DESC);
}
break;
case "random":
$search->clearOrderByColumns();
$search->addAscendingOrderByColumn('RAND()');
break(2);
}
}
return $search;
} | php | public function buildModelCriteria()
{
$search = SmartyFilterQuery::create();
/* manage translations */
$this->configureI18nProcessing($search, array('TITLE', 'DESCRIPTION'));
$id = $this->getId();
if (!is_null($id)) {
$search->filterById($id, Criteria::IN);
}
$type = $this->getFiltertype();
if (!is_null($type)) {
$search->filterByFiltertype($type, Criteria::IN);
}
$orders = $this->getOrder();
foreach ($orders as $order) {
switch ($order) {
case "alpha":
$search->addAscendingOrderByColumn('i18n_TITLE');
break;
case "alpha-reverse":
$search->addDescendingOrderByColumn('i18n_TITLE');
break;
case "given_id":
if (null === $id) {
throw new \InvalidArgumentException('Given_id order cannot be set without `id` argument');
}
foreach ($id as $singleId) {
$givenIdMatched = 'given_id_matched_' . $singleId;
$search->withColumn(SmartyFilterTableMap::ID . "='$singleId'", $givenIdMatched);
$search->orderBy($givenIdMatched, Criteria::DESC);
}
break;
case "random":
$search->clearOrderByColumns();
$search->addAscendingOrderByColumn('RAND()');
break(2);
}
}
return $search;
} | this method returns a Propel ModelCriteria
@return \Propel\Runtime\ActiveQuery\ModelCriteria | https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Loop/SmartyFilterLoop.php#L97-L145 |
Tuna-CMS/tuna-bundle | src/Tuna/Bundle/MenuBundle/DependencyInjection/TypeConfig.php | TypeConfig.getTemplate | public function getTemplate($name)
{
if (!array_key_exists($name, $this->getTemplates())) {
throw new \Exception('Template not found');
}
return $this->getTemplates()[$name];
} | php | public function getTemplate($name)
{
if (!array_key_exists($name, $this->getTemplates())) {
throw new \Exception('Template not found');
}
return $this->getTemplates()[$name];
} | @param $name
@return string
@throws \Exception | https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/MenuBundle/DependencyInjection/TypeConfig.php#L101-L108 |
kiler129/TinyWs | src/NetworkFrame.php | NetworkFrame.collectHeader | private function collectHeader()
{
if ($this->headersCollected) {
throw new LogicException("Frame header already collected!");
}
$this->logger->debug("Collecting frame header...");
$bufferLength = strlen($this->buffer);
if ($bufferLength < 2) //Nothing to do here for now, unlikely in real-life but possible
{
$this->logger->debug("Nothing to collect - not enough data in buffer");
return false;
}
if ($this->firstFrameByte === null && $bufferLength >= 2) { //Basic header (fin+rsv[1-3]+opcode+mask+1st byte of payload len) not yet present & can be read
$this->logger->debug("Collecting basic header [got at least 2B]");
$this->firstFrameByte = ord($this->buffer[0]);
$this->secondFrameByte = ord($this->buffer[1]);
$this->buffer = substr($this->buffer, 2);
$bufferLength -= 2;
$this->logger->debug("1st byte: " . decbin($this->firstFrameByte) . " [" . $this->firstFrameByte . "], 2nd byte: " . decbin($this->secondFrameByte) . " [" . $this->secondFrameByte . "]");
$this->payloadLengthDiscriminator = $this->secondFrameByte & ~128;
if ($this->payloadLengthDiscriminator < 126) { //Payload length fits in first byte [7 bits]
$this->payloadLength = $this->payloadLengthDiscriminator;
$this->remainingPayloadBytes = $this->payloadLength;
$this->logger->debug("Payload length got from 1st bte [l=" . $this->payloadLength . "]");
}
}
if ($this->firstFrameByte & 112) { //Note: tinyWS doesn't support extensions yet
throw new WebSocketException("Used RSV w/o ext. negotiation", DataFrame::CODE_PROTOCOL_ERROR);
}
$currentFrameOpcode = $this->firstFrameByte & ~240;
if (($currentFrameOpcode === DataFrame::OPCODE_CLOSE || $currentFrameOpcode === DataFrame::OPCODE_PING || $currentFrameOpcode === DataFrame::OPCODE_PONG) && (!$this->isFin() || $this->payloadLengthDiscriminator > 125)
) {
throw new WebSocketException("Control frames cannot be fragmented or contain payload larger than 125 bytes",
DataFrame::CODE_PROTOCOL_ERROR);
}
if ($this->payloadLength === null) { //Payload len. not collected yet (will exec. only if payload length is extended, >125 bytes)
$this->logger->debug("Payload length exceed 1st bte [>125B], trying to get total");
if ($this->payloadLengthDiscriminator === 126 && $bufferLength >= 2) { //7+16 bits
$this->payloadLength = unpack("n",
$this->buffer[0] . $this->buffer[1]); //Actually it's faster than substr ;)
$this->payloadLength = $this->payloadLength[1]; //Array dereference on call is allowed from 5.4
$this->remainingPayloadBytes = $this->payloadLength;
$this->buffer = substr($this->buffer, 2);
$bufferLength -= 2;
$this->logger->debug("Payload length got from 16b [l=" . $this->payloadLength . "]");
} elseif ($this->payloadLengthDiscriminator === 127 && $bufferLength >= 4) { //7+64 bits
//Note that this also WORKS on 32-bits system & Window$ - PHP will automagically converts to float on integer overflow
//In this case pack("J") is ~40% faster, but it supported since 5.6.3 which is not very common now
list($higher, $lower) = array_values(unpack('N2', substr($this->buffer, 0, 8)));
$this->payloadLength = $higher << 32 | $lower;
$this->remainingPayloadBytes = $this->payloadLength;
$this->buffer = substr($this->buffer, 8);
$bufferLength -= 8;
$this->logger->debug("Payload length got from 64b [l=" . $this->payloadLength . "]");
} else {
$this->logger->debug("Extracting payload length not [yet] possible, skipping mask");
return false; //Unless payload length is determined it's impossible to try reading mask (fucking RFC...)
}
if ($this->payloadLength > DataFrame::MAXIMUM_FRAME_PAYLOAD) {
throw new WebSocketException("Frame too large (>" . DataFrame::MAXIMUM_FRAME_PAYLOAD . " bytes)",
DataFrame::CODE_MESSAGE_TOO_LONG);
}
}
if ($this->secondFrameByte & 128) {
$this->logger->debug("Frame is masked - trying to collect mask");
if (empty($this->maskingKey)) { //After collecting payload size it's possible to get masking key (if present and not yet collected)
if ($bufferLength < 4) {
$this->logger->debug("Cannot collect mask - not enough buffer [cbl=$bufferLength]");
return false; //Packet is masked, but there's not enough data to get mask, so header cannot be completed [yet]
}
$this->maskingKey = substr($this->buffer, 0, 4);
$this->buffer = substr($this->buffer, 4);
//Since this it's last operation in a row there's no need to decrement $bufferLength
$this->logger->debug("Got frame mask");
}
}
$this->logger->debug("Got full header");
$this->headersCollected = true;
return true;
} | php | private function collectHeader()
{
if ($this->headersCollected) {
throw new LogicException("Frame header already collected!");
}
$this->logger->debug("Collecting frame header...");
$bufferLength = strlen($this->buffer);
if ($bufferLength < 2) //Nothing to do here for now, unlikely in real-life but possible
{
$this->logger->debug("Nothing to collect - not enough data in buffer");
return false;
}
if ($this->firstFrameByte === null && $bufferLength >= 2) { //Basic header (fin+rsv[1-3]+opcode+mask+1st byte of payload len) not yet present & can be read
$this->logger->debug("Collecting basic header [got at least 2B]");
$this->firstFrameByte = ord($this->buffer[0]);
$this->secondFrameByte = ord($this->buffer[1]);
$this->buffer = substr($this->buffer, 2);
$bufferLength -= 2;
$this->logger->debug("1st byte: " . decbin($this->firstFrameByte) . " [" . $this->firstFrameByte . "], 2nd byte: " . decbin($this->secondFrameByte) . " [" . $this->secondFrameByte . "]");
$this->payloadLengthDiscriminator = $this->secondFrameByte & ~128;
if ($this->payloadLengthDiscriminator < 126) { //Payload length fits in first byte [7 bits]
$this->payloadLength = $this->payloadLengthDiscriminator;
$this->remainingPayloadBytes = $this->payloadLength;
$this->logger->debug("Payload length got from 1st bte [l=" . $this->payloadLength . "]");
}
}
if ($this->firstFrameByte & 112) { //Note: tinyWS doesn't support extensions yet
throw new WebSocketException("Used RSV w/o ext. negotiation", DataFrame::CODE_PROTOCOL_ERROR);
}
$currentFrameOpcode = $this->firstFrameByte & ~240;
if (($currentFrameOpcode === DataFrame::OPCODE_CLOSE || $currentFrameOpcode === DataFrame::OPCODE_PING || $currentFrameOpcode === DataFrame::OPCODE_PONG) && (!$this->isFin() || $this->payloadLengthDiscriminator > 125)
) {
throw new WebSocketException("Control frames cannot be fragmented or contain payload larger than 125 bytes",
DataFrame::CODE_PROTOCOL_ERROR);
}
if ($this->payloadLength === null) { //Payload len. not collected yet (will exec. only if payload length is extended, >125 bytes)
$this->logger->debug("Payload length exceed 1st bte [>125B], trying to get total");
if ($this->payloadLengthDiscriminator === 126 && $bufferLength >= 2) { //7+16 bits
$this->payloadLength = unpack("n",
$this->buffer[0] . $this->buffer[1]); //Actually it's faster than substr ;)
$this->payloadLength = $this->payloadLength[1]; //Array dereference on call is allowed from 5.4
$this->remainingPayloadBytes = $this->payloadLength;
$this->buffer = substr($this->buffer, 2);
$bufferLength -= 2;
$this->logger->debug("Payload length got from 16b [l=" . $this->payloadLength . "]");
} elseif ($this->payloadLengthDiscriminator === 127 && $bufferLength >= 4) { //7+64 bits
//Note that this also WORKS on 32-bits system & Window$ - PHP will automagically converts to float on integer overflow
//In this case pack("J") is ~40% faster, but it supported since 5.6.3 which is not very common now
list($higher, $lower) = array_values(unpack('N2', substr($this->buffer, 0, 8)));
$this->payloadLength = $higher << 32 | $lower;
$this->remainingPayloadBytes = $this->payloadLength;
$this->buffer = substr($this->buffer, 8);
$bufferLength -= 8;
$this->logger->debug("Payload length got from 64b [l=" . $this->payloadLength . "]");
} else {
$this->logger->debug("Extracting payload length not [yet] possible, skipping mask");
return false; //Unless payload length is determined it's impossible to try reading mask (fucking RFC...)
}
if ($this->payloadLength > DataFrame::MAXIMUM_FRAME_PAYLOAD) {
throw new WebSocketException("Frame too large (>" . DataFrame::MAXIMUM_FRAME_PAYLOAD . " bytes)",
DataFrame::CODE_MESSAGE_TOO_LONG);
}
}
if ($this->secondFrameByte & 128) {
$this->logger->debug("Frame is masked - trying to collect mask");
if (empty($this->maskingKey)) { //After collecting payload size it's possible to get masking key (if present and not yet collected)
if ($bufferLength < 4) {
$this->logger->debug("Cannot collect mask - not enough buffer [cbl=$bufferLength]");
return false; //Packet is masked, but there's not enough data to get mask, so header cannot be completed [yet]
}
$this->maskingKey = substr($this->buffer, 0, 4);
$this->buffer = substr($this->buffer, 4);
//Since this it's last operation in a row there's no need to decrement $bufferLength
$this->logger->debug("Got frame mask");
}
}
$this->logger->debug("Got full header");
$this->headersCollected = true;
return true;
} | This method will suck you into the vortex of nowhere, will rape you & stole every penny from your wallet
...and if you're lucky it'll collect headers for WebSocket frame from given buffer.
Please, do not swear on my skills after reading that piece of code, I've really tried
@wastedHoursCounter 23.5 Increment after every failure of this method performance or OO optimization
@return bool Returns true if headers has been collected, false otherwise
@throws LogicException Thrown if called after headers collection has been completed
@throws WebSocketException | https://github.com/kiler129/TinyWs/blob/85f0335b87b3ec73ab47f5a5631eb86ba70b64a1/src/NetworkFrame.php#L77-L185 |
kiler129/TinyWs | src/NetworkFrame.php | NetworkFrame.collectPayload | private function collectPayload()
{
if ($this->payloadLength === 0) {
$this->logger->debug("Skipping payload collection [expected length === 0]");
return true;
}
$this->logger->debug("Trying to collect payload...");
if (!$this->headersCollected) {
throw new LogicException("Cannot collect payload before headers!");
}
$payloadData = substr($this->buffer, 0, $this->remainingPayloadBytes);
$payloadDataLen = strlen($payloadData);
$this->buffer = substr($this->buffer, $payloadDataLen);
$this->remainingPayloadBytes -= $payloadDataLen;
$this->payload .= $payloadData;
$this->logger->debug("Got $payloadDataLen bytes of payload, " . $this->remainingPayloadBytes . " left");
if ($this->remainingPayloadBytes === 0 && ($this->secondFrameByte & 128)) { //Unmask after full payload is received
$this->logger->debug("Unmasking payload");
$this->payload = $this->getMaskedPayload();
return true;
}
return ($this->remainingPayloadBytes === 0);
} | php | private function collectPayload()
{
if ($this->payloadLength === 0) {
$this->logger->debug("Skipping payload collection [expected length === 0]");
return true;
}
$this->logger->debug("Trying to collect payload...");
if (!$this->headersCollected) {
throw new LogicException("Cannot collect payload before headers!");
}
$payloadData = substr($this->buffer, 0, $this->remainingPayloadBytes);
$payloadDataLen = strlen($payloadData);
$this->buffer = substr($this->buffer, $payloadDataLen);
$this->remainingPayloadBytes -= $payloadDataLen;
$this->payload .= $payloadData;
$this->logger->debug("Got $payloadDataLen bytes of payload, " . $this->remainingPayloadBytes . " left");
if ($this->remainingPayloadBytes === 0 && ($this->secondFrameByte & 128)) { //Unmask after full payload is received
$this->logger->debug("Unmasking payload");
$this->payload = $this->getMaskedPayload();
return true;
}
return ($this->remainingPayloadBytes === 0);
} | Collects payload from buffer. Masked packets are decoded.
@return bool|null Returns false if payload not yet collected, true if it was collected. Null is returned if
payload cannot be collected yet
@throws LogicException In case of calling before collecting headers | https://github.com/kiler129/TinyWs/blob/85f0335b87b3ec73ab47f5a5631eb86ba70b64a1/src/NetworkFrame.php#L194-L222 |
kiler129/TinyWs | src/NetworkFrame.php | NetworkFrame.isComplete | public function isComplete()
{
$this->logger->debug("NetworkFrame::isComplete?");
if ($this->remainingPayloadBytes === 0 && $this->headersCollected) {
$this->logger->debug("NetworkFrame::isComplete => OK, buffer load - " . strlen($this->buffer));
return true;
}
$this->logger->debug("NetworkFrame::isComplete => not yet, buffer load - " . strlen($this->buffer));
if (!empty($this->buffer)) {
if ($this->headersCollected || $this->collectHeader()) {
return $this->collectPayload();
}
}
return false;
} | php | public function isComplete()
{
$this->logger->debug("NetworkFrame::isComplete?");
if ($this->remainingPayloadBytes === 0 && $this->headersCollected) {
$this->logger->debug("NetworkFrame::isComplete => OK, buffer load - " . strlen($this->buffer));
return true;
}
$this->logger->debug("NetworkFrame::isComplete => not yet, buffer load - " . strlen($this->buffer));
if (!empty($this->buffer)) {
if ($this->headersCollected || $this->collectHeader()) {
return $this->collectPayload();
}
}
return false;
} | Returns frame status - whatever its completed (payload can be fetched) or not.
If frame is not completed it tries to fetch remaining data.
@return bool
@throws LogicException
@throws WebSocketException | https://github.com/kiler129/TinyWs/blob/85f0335b87b3ec73ab47f5a5631eb86ba70b64a1/src/NetworkFrame.php#L232-L249 |
kiler129/TinyWs | src/NetworkFrame.php | NetworkFrame.getPayloadPart | public function getPayloadPart($start = 0, $length = null)
{
$this->logger->debug("Chunking $start-$length from payload [hl=" . $this->payloadLength . ", rl=" . strlen($this->payload) . "]");
if (!$this->isComplete()) {
throw new UnderflowException("Cannot get frame payload - frame not ready");
}
return ($length === null) ? substr($this->payload, $start) : substr($this->payload, $start, $length);
} | php | public function getPayloadPart($start = 0, $length = null)
{
$this->logger->debug("Chunking $start-$length from payload [hl=" . $this->payloadLength . ", rl=" . strlen($this->payload) . "]");
if (!$this->isComplete()) {
throw new UnderflowException("Cannot get frame payload - frame not ready");
}
return ($length === null) ? substr($this->payload, $start) : substr($this->payload, $start, $length);
} | Returns part of the payload [to save memory]
@param integer $start Offset from start
@param null|integer $length Number of bytes to return. If null it will return payload from $start to end.
@return string
@throws UnderflowException Payload is not collected yet | https://github.com/kiler129/TinyWs/blob/85f0335b87b3ec73ab47f5a5631eb86ba70b64a1/src/NetworkFrame.php#L260-L269 |
samsonos/php_core | src/XMLBuilder.php | XMLBuilder.setAttribute | protected function setAttribute(string $value, \DOMElement $node, array $classesMetadata)
{
if (array_key_exists($value, $classesMetadata)) {
$node->setAttribute('service', $value);
} elseif (class_exists($value)) {
$node->setAttribute('class', $value);
} else {
$node->setAttribute('value', $value);
}
} | php | protected function setAttribute(string $value, \DOMElement $node, array $classesMetadata)
{
if (array_key_exists($value, $classesMetadata)) {
$node->setAttribute('service', $value);
} elseif (class_exists($value)) {
$node->setAttribute('class', $value);
} else {
$node->setAttribute('value', $value);
}
} | Set XML property or method argument value.
@param string $value
@param \DOMElement $node
@param ClassMetadata[] $classesMetadata | https://github.com/samsonos/php_core/blob/15f30528e2efab9e9cf16e9aad3899edced49de1/src/XMLBuilder.php#L24-L33 |
samsonos/php_core | src/XMLBuilder.php | XMLBuilder.buildXMLConfig | public function buildXMLConfig(array $classesMetadata, string $path)
{
foreach ($classesMetadata as $alias => $classMetadata) {
$dom = new \DOMDocument("1.0", "utf-8");
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$root = $dom->createElement("dependencies");
$dom->appendChild($root);
// Build alias from class name if missing
$alias = $alias ?? strtolower(str_replace('\\', '_', $classMetadata->className));
$classData = $dom->createElement('instance');
$classData->setAttribute('service', $alias);
$classData->setAttribute('class', $classMetadata->className);
foreach ($classMetadata->scopes as $scope) {
$classData->setAttribute('scope', $scope);
}
$methodsData = $dom->createElement('methods');
foreach ($classMetadata->methodsMetadata as $method => $methodMetadata) {
if (count($methodMetadata->dependencies)) {
$methodData = $dom->createElement($method);
$argumentsData = $dom->createElement('arguments');
foreach ($methodMetadata->dependencies as $argument => $dependency) {
$argumentData = $dom->createElement($argument);
$this->setAttribute($dependency, $argumentData, $classesMetadata);
$argumentsData->appendChild($argumentData);
}
$methodData->appendChild($argumentsData);
$methodsData->appendChild($methodData);
}
}
$classData->appendChild($methodsData);
$propertiesData = $dom->createElement('properties');
foreach ($classMetadata->propertiesMetadata as $property => $propertyMetadata) {
if ($propertyMetadata->dependency !== null && $propertyMetadata->dependency !== '') {
$propertyData = $dom->createElement($property);
$this->setAttribute($propertyMetadata->dependency, $propertyData, $classesMetadata);
$propertiesData->appendChild($propertyData);
}
}
$classData->appendChild($propertiesData);
$root->appendChild($classData);
$dom->save($path . $alias . '.xml');
}
} | php | public function buildXMLConfig(array $classesMetadata, string $path)
{
foreach ($classesMetadata as $alias => $classMetadata) {
$dom = new \DOMDocument("1.0", "utf-8");
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$root = $dom->createElement("dependencies");
$dom->appendChild($root);
// Build alias from class name if missing
$alias = $alias ?? strtolower(str_replace('\\', '_', $classMetadata->className));
$classData = $dom->createElement('instance');
$classData->setAttribute('service', $alias);
$classData->setAttribute('class', $classMetadata->className);
foreach ($classMetadata->scopes as $scope) {
$classData->setAttribute('scope', $scope);
}
$methodsData = $dom->createElement('methods');
foreach ($classMetadata->methodsMetadata as $method => $methodMetadata) {
if (count($methodMetadata->dependencies)) {
$methodData = $dom->createElement($method);
$argumentsData = $dom->createElement('arguments');
foreach ($methodMetadata->dependencies as $argument => $dependency) {
$argumentData = $dom->createElement($argument);
$this->setAttribute($dependency, $argumentData, $classesMetadata);
$argumentsData->appendChild($argumentData);
}
$methodData->appendChild($argumentsData);
$methodsData->appendChild($methodData);
}
}
$classData->appendChild($methodsData);
$propertiesData = $dom->createElement('properties');
foreach ($classMetadata->propertiesMetadata as $property => $propertyMetadata) {
if ($propertyMetadata->dependency !== null && $propertyMetadata->dependency !== '') {
$propertyData = $dom->createElement($property);
$this->setAttribute($propertyMetadata->dependency, $propertyData, $classesMetadata);
$propertiesData->appendChild($propertyData);
}
}
$classData->appendChild($propertiesData);
$root->appendChild($classData);
$dom->save($path . $alias . '.xml');
}
} | Build class xml config from class metadata.
TODO: Scan for existing config and change only not filled values.
@param ClassMetadata[] $classesMetadata
@param string $path Path where to store XML files | https://github.com/samsonos/php_core/blob/15f30528e2efab9e9cf16e9aad3899edced49de1/src/XMLBuilder.php#L43-L92 |
chilimatic/chilimatic-framework | lib/config/ConfigFactory.php | ConfigFactory.make | public static function make($type, $param = null)
{
if (!$type) {
throw new \LogicException("The Config Type has to be specified ... \$type is empty");
}
$className = (string)__NAMESPACE__ . '\\' . (string)ucfirst($type);
if (!class_exists($className, true)) {
throw new \LogicException("The Config class has to be implemented and accessible ... $className is not found");
}
return new $className($param);
} | php | public static function make($type, $param = null)
{
if (!$type) {
throw new \LogicException("The Config Type has to be specified ... \$type is empty");
}
$className = (string)__NAMESPACE__ . '\\' . (string)ucfirst($type);
if (!class_exists($className, true)) {
throw new \LogicException("The Config class has to be implemented and accessible ... $className is not found");
}
return new $className($param);
} | Factory for creating Config objects
the type specifies the Config Type like 'ini' or 'file' or another one implemented lateron
@param string $type
@param array $param
@throws \LogicException
@return AbstractConfig | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/config/ConfigFactory.php#L33-L46 |
Elephant418/Staq | src/Staq/Url.php | Url.from | public function from($mixed)
{
if (is_object($mixed)) {
return $mixed;
}
if (is_array($mixed)) {
return $this->fromArray($mixed);
}
if (is_string($mixed)) {
return $this->fromString($mixed);
}
if (is_null($mixed)) {
return $this->fromString('/');
}
} | php | public function from($mixed)
{
if (is_object($mixed)) {
return $mixed;
}
if (is_array($mixed)) {
return $this->fromArray($mixed);
}
if (is_string($mixed)) {
return $this->fromString($mixed);
}
if (is_null($mixed)) {
return $this->fromString('/');
}
} | /* CONSTRUCTOR
*********************************************************************** | https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Url.php#L21-L35 |
Elephant418/Staq | src/Staq/Url.php | Url.diff | public function diff($url)
{
if (is_object($url)) {
if (isset($url->host)) {
unset($url->host);
}
if (isset($url->port)) {
unset($url->port);
}
$this->diffUri($url);
}
return $this;
} | php | public function diff($url)
{
if (is_object($url)) {
if (isset($url->host)) {
unset($url->host);
}
if (isset($url->port)) {
unset($url->port);
}
$this->diffUri($url);
}
return $this;
} | /* TREATMENT METHODS
*********************************************************************** | https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Url.php#L121-L133 |
Elephant418/Staq | src/Staq/Url.php | Url.diffUri | public function diffUri($url)
{
if (is_object($url) && !empty($url->uri)) {
$this->uri = \UString::substrAfter($this->uri, $url->uri);
\UString::doStartWith($this->uri, '/');
}
return $this;
} | php | public function diffUri($url)
{
if (is_object($url) && !empty($url->uri)) {
$this->uri = \UString::substrAfter($this->uri, $url->uri);
\UString::doStartWith($this->uri, '/');
}
return $this;
} | /* URI TREATMENT METHODS
*********************************************************************** | https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Url.php#L138-L145 |
IStranger/yii2-resource-smart-load | base/Helper.php | Helper.filterByKeys | public static function filterByKeys($array, array $keysInc = null, array $keysExc = null)
{
if ($keysInc !== null) {
$array = array_intersect_key($array, array_flip($keysInc));
}
if ($keysExc) {
$array = array_diff_key($array, array_flip($keysExc));
}
return $array;
} | php | public static function filterByKeys($array, array $keysInc = null, array $keysExc = null)
{
if ($keysInc !== null) {
$array = array_intersect_key($array, array_flip($keysInc));
}
if ($keysExc) {
$array = array_diff_key($array, array_flip($keysExc));
}
return $array;
} | Filters items by given keys.
@param array $array source assoc array
@param array $keysInc keys of items, that should be included
@param array $keysExc keys of items, that should be excluded
@return array|mixed|null filtered array | https://github.com/IStranger/yii2-resource-smart-load/blob/a4f203745d9a02fd97853b49c55b287aea6d7e6d/base/Helper.php#L72-L81 |
IStranger/yii2-resource-smart-load | base/Helper.php | Helper.filterByFn | public static function filterByFn(array $array, callable $callback, $data = null, $bind = true)
{
$handler = function (&$array, $key, $item, $result) {
if ($result) {
$array[$key] = $item;
}
};
return self::_execute($array, $callback, $handler, $data, $bind);
} | php | public static function filterByFn(array $array, callable $callback, $data = null, $bind = true)
{
$handler = function (&$array, $key, $item, $result) {
if ($result) {
$array[$key] = $item;
}
};
return self::_execute($array, $callback, $handler, $data, $bind);
} | Filters values of given array by $callback.
If $callback function return true, current element included in result array
<code>
// Select only elements with height>$data
$items = A::filter($a, function($key, $val, $data){{
return $val['height'] > $data;
}, $data);
</code>
@param array $array
@param callable $callback
@param null $data
@return array
@param boolean $bind
@see firstByFn(), lastByFn()
@uses execute() | https://github.com/IStranger/yii2-resource-smart-load/blob/a4f203745d9a02fd97853b49c55b287aea6d7e6d/base/Helper.php#L102-L110 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.