repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
nails/module-auth
src/Model/Auth.php
Auth.logout
public function logout() { $oUserModel = Factory::model('User', 'nails/module-auth'); $oUserModel->clearRememberCookie(); // -------------------------------------------------------------------------- // null the remember_code so that auto-logins stop $oDb = Factory::service('Database'); $oDb->set('remember_code', null); $oDb->where('id', activeUser('id')); $oDb->update(NAILS_DB_PREFIX . 'user'); // -------------------------------------------------------------------------- // Destroy key parts of the session (enough for user_model to report user as logged out) $oUserModel->clearLoginData(); // -------------------------------------------------------------------------- // Destroy CI session $oSession = Factory::service('Session', 'nails/module-auth'); $oSession->destroy(); // -------------------------------------------------------------------------- // Destroy PHP session if it exists if (session_id()) { session_destroy(); } // -------------------------------------------------------------------------- return true; }
php
public function logout() { $oUserModel = Factory::model('User', 'nails/module-auth'); $oUserModel->clearRememberCookie(); // -------------------------------------------------------------------------- // null the remember_code so that auto-logins stop $oDb = Factory::service('Database'); $oDb->set('remember_code', null); $oDb->where('id', activeUser('id')); $oDb->update(NAILS_DB_PREFIX . 'user'); // -------------------------------------------------------------------------- // Destroy key parts of the session (enough for user_model to report user as logged out) $oUserModel->clearLoginData(); // -------------------------------------------------------------------------- // Destroy CI session $oSession = Factory::service('Session', 'nails/module-auth'); $oSession->destroy(); // -------------------------------------------------------------------------- // Destroy PHP session if it exists if (session_id()) { session_destroy(); } // -------------------------------------------------------------------------- return true; }
[ "public", "function", "logout", "(", ")", "{", "$", "oUserModel", "=", "Factory", "::", "model", "(", "'User'", ",", "'nails/module-auth'", ")", ";", "$", "oUserModel", "->", "clearRememberCookie", "(", ")", ";", "// -------------------------------------------------...
Log a user out @return boolean
[ "Log", "a", "user", "out" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/Auth.php#L228-L262
train
nails/module-auth
src/Model/Auth.php
Auth.mfaTokenGenerate
public function mfaTokenGenerate($iUserId) { $oPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); $oNow = Factory::factory('DateTime'); $oInput = Factory::service('Input'); $oDb = Factory::service('Database'); $sSalt = $oPasswordModel->salt(); $sIp = $oInput->ipAddress(); $sCreated = $oNow->format('Y-m-d H:i:s'); $sExpires = $oNow->add(new \DateInterval('PT10M'))->format('Y-m-d H:i:s'); $aToken = [ 'token' => sha1(sha1(APP_PRIVATE_KEY . $iUserId . $sCreated . $sExpires . $sIp) . $sSalt), 'salt' => md5($sSalt), ]; // Add this to the DB $oDb->set('user_id', $iUserId); $oDb->set('token', $aToken['token']); $oDb->set('salt', $aToken['salt']); $oDb->set('created', $sCreated); $oDb->set('expires', $sExpires); $oDb->set('ip', $sIp); if ($oDb->insert(NAILS_DB_PREFIX . 'user_auth_two_factor_token')) { $aToken['id'] = $oDb->insert_id(); return $aToken; } else { $error = lang('auth_twofactor_token_could_not_generate'); $this->setError($error); return false; } }
php
public function mfaTokenGenerate($iUserId) { $oPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); $oNow = Factory::factory('DateTime'); $oInput = Factory::service('Input'); $oDb = Factory::service('Database'); $sSalt = $oPasswordModel->salt(); $sIp = $oInput->ipAddress(); $sCreated = $oNow->format('Y-m-d H:i:s'); $sExpires = $oNow->add(new \DateInterval('PT10M'))->format('Y-m-d H:i:s'); $aToken = [ 'token' => sha1(sha1(APP_PRIVATE_KEY . $iUserId . $sCreated . $sExpires . $sIp) . $sSalt), 'salt' => md5($sSalt), ]; // Add this to the DB $oDb->set('user_id', $iUserId); $oDb->set('token', $aToken['token']); $oDb->set('salt', $aToken['salt']); $oDb->set('created', $sCreated); $oDb->set('expires', $sExpires); $oDb->set('ip', $sIp); if ($oDb->insert(NAILS_DB_PREFIX . 'user_auth_two_factor_token')) { $aToken['id'] = $oDb->insert_id(); return $aToken; } else { $error = lang('auth_twofactor_token_could_not_generate'); $this->setError($error); return false; } }
[ "public", "function", "mfaTokenGenerate", "(", "$", "iUserId", ")", "{", "$", "oPasswordModel", "=", "Factory", "::", "model", "(", "'UserPassword'", ",", "'nails/module-auth'", ")", ";", "$", "oNow", "=", "Factory", "::", "factory", "(", "'DateTime'", ")", ...
Generate an MFA token @param int $iUserId The user ID to generate the token for @return array|false
[ "Generate", "an", "MFA", "token" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/Auth.php#L273-L305
train
nails/module-auth
src/Model/Auth.php
Auth.mfaTokenValidate
public function mfaTokenValidate($iUserId, $sSalt, $sToken, $sIp) { $oDb = Factory::service('Database'); $oDb->where('user_id', $iUserId); $oDb->where('salt', $sSalt); $oDb->where('token', $sToken); $oToken = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_token')->row(); $bReturn = true; if (!$oToken) { $this->setError(lang('auth_twofactor_token_invalid')); return false; } elseif (strtotime($oToken->expires) <= time()) { $this->setError(lang('auth_twofactor_token_expired')); $bReturn = false; } elseif ($oToken->ip != $sIp) { $this->setError(lang('auth_twofactor_token_bad_ip')); $bReturn = false; } // Delete the token $this->mfaTokenDelete($oToken->id); return $bReturn; }
php
public function mfaTokenValidate($iUserId, $sSalt, $sToken, $sIp) { $oDb = Factory::service('Database'); $oDb->where('user_id', $iUserId); $oDb->where('salt', $sSalt); $oDb->where('token', $sToken); $oToken = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_token')->row(); $bReturn = true; if (!$oToken) { $this->setError(lang('auth_twofactor_token_invalid')); return false; } elseif (strtotime($oToken->expires) <= time()) { $this->setError(lang('auth_twofactor_token_expired')); $bReturn = false; } elseif ($oToken->ip != $sIp) { $this->setError(lang('auth_twofactor_token_bad_ip')); $bReturn = false; } // Delete the token $this->mfaTokenDelete($oToken->id); return $bReturn; }
[ "public", "function", "mfaTokenValidate", "(", "$", "iUserId", ",", "$", "sSalt", ",", "$", "sToken", ",", "$", "sIp", ")", "{", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "oDb", "->", "where", "(", "'user_id'", ",...
Validate a MFA token @param int $iUserId The ID of the user the token belongs to @param string $sSalt The token's salt @param string $sToken The token's hash @param string $sIp The user's IP address @return boolean
[ "Validate", "a", "MFA", "token" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/Auth.php#L319-L349
train
nails/module-auth
src/Model/Auth.php
Auth.mfaTokenDelete
public function mfaTokenDelete($iTokenId) { $oDb = Factory::service('Database'); $oDb->where('id', $iTokenId); $oDb->delete(NAILS_DB_PREFIX . 'user_auth_two_factor_token'); return (bool) $oDb->affected_rows(); }
php
public function mfaTokenDelete($iTokenId) { $oDb = Factory::service('Database'); $oDb->where('id', $iTokenId); $oDb->delete(NAILS_DB_PREFIX . 'user_auth_two_factor_token'); return (bool) $oDb->affected_rows(); }
[ "public", "function", "mfaTokenDelete", "(", "$", "iTokenId", ")", "{", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "oDb", "->", "where", "(", "'id'", ",", "$", "iTokenId", ")", ";", "$", "oDb", "->", "delete", "(",...
Delete an MFA token @param int $iTokenId The token's ID @return boolean
[ "Delete", "an", "MFA", "token" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/Auth.php#L360-L366
train
nails/module-auth
src/Model/Auth.php
Auth.mfaQuestionGet
public function mfaQuestionGet($iUserId) { $oDb = Factory::service('Database'); $oInput = Factory::service('Input'); $oDb->where('user_id', $iUserId); $oDb->order_by('last_requested', 'DESC'); $aQuestions = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_question')->result(); if (!$aQuestions) { $this->setError('No security questions available for this user.'); return false; } // -------------------------------------------------------------------------- // Choose a question to return if (count($aQuestions) == 1) { // No choice, just return the lonely question $oOut = reset($aQuestions); } elseif (count($aQuestions) > 1) { /** * Has the most recently asked question been asked in the last 10 minutes? * If so, return that one again (to make harvesting all the user's questions * a little more time consuming). If not randomly choose one. */ $oOut = reset($aQuestions); if (strtotime($oOut->last_requested) < strtotime('-10 MINS')) { $oOut = $aQuestions[array_rand($aQuestions)]; } } else { $this->setError('Could not determine security question.'); return false; } // Decode the question $oEncrypt = Factory::service('Encrypt'); $oOut->question = $oEncrypt->decode($oOut->question, APP_PRIVATE_KEY . $oOut->salt); // Update the last requested details $oDb->set('last_requested', 'NOW()', false); $oDb->set('last_requested_ip', $oInput->ipAddress()); $oDb->where('id', $oOut->id); $oDb->update(NAILS_DB_PREFIX . 'user_auth_two_factor_question'); return $oOut; }
php
public function mfaQuestionGet($iUserId) { $oDb = Factory::service('Database'); $oInput = Factory::service('Input'); $oDb->where('user_id', $iUserId); $oDb->order_by('last_requested', 'DESC'); $aQuestions = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_question')->result(); if (!$aQuestions) { $this->setError('No security questions available for this user.'); return false; } // -------------------------------------------------------------------------- // Choose a question to return if (count($aQuestions) == 1) { // No choice, just return the lonely question $oOut = reset($aQuestions); } elseif (count($aQuestions) > 1) { /** * Has the most recently asked question been asked in the last 10 minutes? * If so, return that one again (to make harvesting all the user's questions * a little more time consuming). If not randomly choose one. */ $oOut = reset($aQuestions); if (strtotime($oOut->last_requested) < strtotime('-10 MINS')) { $oOut = $aQuestions[array_rand($aQuestions)]; } } else { $this->setError('Could not determine security question.'); return false; } // Decode the question $oEncrypt = Factory::service('Encrypt'); $oOut->question = $oEncrypt->decode($oOut->question, APP_PRIVATE_KEY . $oOut->salt); // Update the last requested details $oDb->set('last_requested', 'NOW()', false); $oDb->set('last_requested_ip', $oInput->ipAddress()); $oDb->where('id', $oOut->id); $oDb->update(NAILS_DB_PREFIX . 'user_auth_two_factor_question'); return $oOut; }
[ "public", "function", "mfaQuestionGet", "(", "$", "iUserId", ")", "{", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "oInput", "=", "Factory", "::", "service", "(", "'Input'", ")", ";", "$", "oDb", "->", "where", "(", ...
Fetches a random MFA question for a user @param int $iUserId The user's ID @return boolean|\stdClass
[ "Fetches", "a", "random", "MFA", "question", "for", "a", "user" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/Auth.php#L377-L428
train
nails/module-auth
src/Model/Auth.php
Auth.mfaQuestionValidate
public function mfaQuestionValidate($iQuestionId, $iUserId, $answer) { $oDb = Factory::service('Database'); $oDb->select('answer, salt'); $oDb->where('id', $iQuestionId); $oDb->where('user_id', $iUserId); $oQuestion = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_question')->row(); if (!$oQuestion) { return false; } $hash = sha1(sha1(strtolower($answer)) . APP_PRIVATE_KEY . $oQuestion->salt); return $hash === $oQuestion->answer; }
php
public function mfaQuestionValidate($iQuestionId, $iUserId, $answer) { $oDb = Factory::service('Database'); $oDb->select('answer, salt'); $oDb->where('id', $iQuestionId); $oDb->where('user_id', $iUserId); $oQuestion = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_question')->row(); if (!$oQuestion) { return false; } $hash = sha1(sha1(strtolower($answer)) . APP_PRIVATE_KEY . $oQuestion->salt); return $hash === $oQuestion->answer; }
[ "public", "function", "mfaQuestionValidate", "(", "$", "iQuestionId", ",", "$", "iUserId", ",", "$", "answer", ")", "{", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "oDb", "->", "select", "(", "'answer, salt'", ")", ";"...
Validates the answer to an MFA Question @param int $iQuestionId The question's ID @param int $iUserId The user's ID @param string $answer The user's answer @return boolean
[ "Validates", "the", "answer", "to", "an", "MFA", "Question" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/Auth.php#L441-L456
train
nails/module-auth
src/Model/Auth.php
Auth.mfaQuestionSet
public function mfaQuestionSet($iUserId, $aData, $bClearOld = true) { // Check input foreach ($aData as $oDatum) { if (empty($oDatum->question) || empty($oDatum->answer)) { $this->setError('Malformed question/answer data.'); return false; } } // Begin transaction $oDb = Factory::service('Database'); $oDb->trans_begin(); // Delete old questions? if ($bClearOld) { $oDb->where('user_id', $iUserId); $oDb->delete(NAILS_DB_PREFIX . 'user_auth_two_factor_question'); } $oPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); $oEncrypt = Factory::service('Encrypt'); $aQuestionData = []; $iCounter = 0; $oNow = Factory::factory('DateTime'); $sDateTime = $oNow->format('Y-m-d H:i:s'); foreach ($aData as $oDatum) { $sSalt = $oPasswordModel->salt(); $aQuestionData[$iCounter] = [ 'user_id' => $iUserId, 'salt' => $sSalt, 'question' => $oEncrypt->encode($oDatum->question, APP_PRIVATE_KEY . $sSalt), 'answer' => sha1(sha1(strtolower($oDatum->answer)) . APP_PRIVATE_KEY . $sSalt), 'created' => $sDateTime, 'last_requested' => null, ]; $iCounter++; } if ($aQuestionData) { $oDb->insert_batch(NAILS_DB_PREFIX . 'user_auth_two_factor_question', $aQuestionData); if ($oDb->trans_status() !== false) { $oDb->trans_commit(); return true; } else { $oDb->trans_rollback(); return false; } } else { $oDb->trans_rollback(); $this->setError('No data to save.'); return false; } }
php
public function mfaQuestionSet($iUserId, $aData, $bClearOld = true) { // Check input foreach ($aData as $oDatum) { if (empty($oDatum->question) || empty($oDatum->answer)) { $this->setError('Malformed question/answer data.'); return false; } } // Begin transaction $oDb = Factory::service('Database'); $oDb->trans_begin(); // Delete old questions? if ($bClearOld) { $oDb->where('user_id', $iUserId); $oDb->delete(NAILS_DB_PREFIX . 'user_auth_two_factor_question'); } $oPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); $oEncrypt = Factory::service('Encrypt'); $aQuestionData = []; $iCounter = 0; $oNow = Factory::factory('DateTime'); $sDateTime = $oNow->format('Y-m-d H:i:s'); foreach ($aData as $oDatum) { $sSalt = $oPasswordModel->salt(); $aQuestionData[$iCounter] = [ 'user_id' => $iUserId, 'salt' => $sSalt, 'question' => $oEncrypt->encode($oDatum->question, APP_PRIVATE_KEY . $sSalt), 'answer' => sha1(sha1(strtolower($oDatum->answer)) . APP_PRIVATE_KEY . $sSalt), 'created' => $sDateTime, 'last_requested' => null, ]; $iCounter++; } if ($aQuestionData) { $oDb->insert_batch(NAILS_DB_PREFIX . 'user_auth_two_factor_question', $aQuestionData); if ($oDb->trans_status() !== false) { $oDb->trans_commit(); return true; } else { $oDb->trans_rollback(); return false; } } else { $oDb->trans_rollback(); $this->setError('No data to save.'); return false; } }
[ "public", "function", "mfaQuestionSet", "(", "$", "iUserId", ",", "$", "aData", ",", "$", "bClearOld", "=", "true", ")", "{", "// Check input", "foreach", "(", "$", "aData", "as", "$", "oDatum", ")", "{", "if", "(", "empty", "(", "$", "oDatum", "->", ...
Sets MFA questions for a user @param int $iUserId The user's ID @param array $aData An array of question and answers @param boolean $bClearOld Whether or not to clear old questions @return boolean
[ "Sets", "MFA", "questions", "for", "a", "user" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/Auth.php#L469-L527
train
nails/module-auth
src/Model/Auth.php
Auth.mfaDeviceSecretGet
public function mfaDeviceSecretGet($iUserId) { $oDb = Factory::service('Database'); $oEncrypt = Factory::service('Encrypt'); $oDb->where('user_id', $iUserId); $oDb->limit(1); $aResult = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_device_secret')->result(); if (empty($aResult)) { return false; } $oReturn = reset($aResult); $oReturn->secret = $oEncrypt->decode($oReturn->secret, APP_PRIVATE_KEY); return $oReturn; }
php
public function mfaDeviceSecretGet($iUserId) { $oDb = Factory::service('Database'); $oEncrypt = Factory::service('Encrypt'); $oDb->where('user_id', $iUserId); $oDb->limit(1); $aResult = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_device_secret')->result(); if (empty($aResult)) { return false; } $oReturn = reset($aResult); $oReturn->secret = $oEncrypt->decode($oReturn->secret, APP_PRIVATE_KEY); return $oReturn; }
[ "public", "function", "mfaDeviceSecretGet", "(", "$", "iUserId", ")", "{", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "oEncrypt", "=", "Factory", "::", "service", "(", "'Encrypt'", ")", ";", "$", "oDb", "->", "where", ...
Gets the user's MFA device if there is one @param int $iUserId The user's ID @return mixed \stdClass on success, false on failure
[ "Gets", "the", "user", "s", "MFA", "device", "if", "there", "is", "one" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/Auth.php#L538-L555
train
nails/module-auth
src/Model/Auth.php
Auth.mfaDeviceSecretGenerate
public function mfaDeviceSecretGenerate($iUserId, $sExistingSecret = null) { // Get an identifier for the user $oUserModel = Factory::model('User', 'nails/module-auth'); $oUser = $oUserModel->getById($iUserId); if (!$oUser) { $this->setError('User does not exist.'); return false; } $oGoogleAuth = new GoogleAuthenticator(); // Generate the secret if (empty($sExistingSecret)) { $sSecret = $oGoogleAuth->generateSecret(); } else { $sSecret = $sExistingSecret; } // Get the hostname $sHostname = Functions::getDomainFromUrl(BASE_URL); // User identifier $sUsername = $oUser->username; $sUsername = empty($sUsername) ? preg_replace('/[^a-z]/', '', strtolower($oUser->first_name . $oUser->last_name)) : $sUsername; $sUsername = empty($sUsername) ? preg_replace('/[^a-z]/', '', strtolower($oUser->email)) : $sUsername; return [ 'secret' => $sSecret, 'url' => $oGoogleAuth->getUrl($sUsername, $sHostname, $sSecret), ]; }
php
public function mfaDeviceSecretGenerate($iUserId, $sExistingSecret = null) { // Get an identifier for the user $oUserModel = Factory::model('User', 'nails/module-auth'); $oUser = $oUserModel->getById($iUserId); if (!$oUser) { $this->setError('User does not exist.'); return false; } $oGoogleAuth = new GoogleAuthenticator(); // Generate the secret if (empty($sExistingSecret)) { $sSecret = $oGoogleAuth->generateSecret(); } else { $sSecret = $sExistingSecret; } // Get the hostname $sHostname = Functions::getDomainFromUrl(BASE_URL); // User identifier $sUsername = $oUser->username; $sUsername = empty($sUsername) ? preg_replace('/[^a-z]/', '', strtolower($oUser->first_name . $oUser->last_name)) : $sUsername; $sUsername = empty($sUsername) ? preg_replace('/[^a-z]/', '', strtolower($oUser->email)) : $sUsername; return [ 'secret' => $sSecret, 'url' => $oGoogleAuth->getUrl($sUsername, $sHostname, $sSecret), ]; }
[ "public", "function", "mfaDeviceSecretGenerate", "(", "$", "iUserId", ",", "$", "sExistingSecret", "=", "null", ")", "{", "// Get an identifier for the user", "$", "oUserModel", "=", "Factory", "::", "model", "(", "'User'", ",", "'nails/module-auth'", ")", ";", "...
Generates a MFA Device Secret @param int $iUserId The user ID to generate for @param string $sExistingSecret The existing secret to use instead of generating a new one @return boolean|array
[ "Generates", "a", "MFA", "Device", "Secret" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/Auth.php#L567-L599
train
nails/module-auth
src/Model/Auth.php
Auth.mfaDeviceSecretValidate
public function mfaDeviceSecretValidate($iUserId, $sSecret, $iCode) { // Tidy up codes so that they only contain digits $sCode = preg_replace('/[^\d]/', '', $iCode); // New instance of the authenticator $oGoogleAuth = new GoogleAuthenticator(); if ($oGoogleAuth->checkCode($sSecret, $sCode)) { $oDb = Factory::service('Database'); $oEncrypt = Factory::service('Encrypt'); $oDb->set('user_id', $iUserId); $oDb->set('secret', $oEncrypt->encode($sSecret, APP_PRIVATE_KEY)); $oDb->set('created', 'NOW()', false); if ($oDb->insert(NAILS_DB_PREFIX . 'user_auth_two_factor_device_secret')) { $iSecretId = $oDb->insert_id(); $oNow = Factory::factory('DateTime'); $oDb->set('secret_id', $iSecretId); $oDb->set('code', $sCode); $oDb->set('used', $oNow->format('Y-m-d H:i:s')); $oDb->insert(NAILS_DB_PREFIX . 'user_auth_two_factor_device_code'); return true; } else { $this->setError('Could not save secret.'); return false; } } else { $this->setError('Codes did not validate.'); return false; } }
php
public function mfaDeviceSecretValidate($iUserId, $sSecret, $iCode) { // Tidy up codes so that they only contain digits $sCode = preg_replace('/[^\d]/', '', $iCode); // New instance of the authenticator $oGoogleAuth = new GoogleAuthenticator(); if ($oGoogleAuth->checkCode($sSecret, $sCode)) { $oDb = Factory::service('Database'); $oEncrypt = Factory::service('Encrypt'); $oDb->set('user_id', $iUserId); $oDb->set('secret', $oEncrypt->encode($sSecret, APP_PRIVATE_KEY)); $oDb->set('created', 'NOW()', false); if ($oDb->insert(NAILS_DB_PREFIX . 'user_auth_two_factor_device_secret')) { $iSecretId = $oDb->insert_id(); $oNow = Factory::factory('DateTime'); $oDb->set('secret_id', $iSecretId); $oDb->set('code', $sCode); $oDb->set('used', $oNow->format('Y-m-d H:i:s')); $oDb->insert(NAILS_DB_PREFIX . 'user_auth_two_factor_device_code'); return true; } else { $this->setError('Could not save secret.'); return false; } } else { $this->setError('Codes did not validate.'); return false; } }
[ "public", "function", "mfaDeviceSecretValidate", "(", "$", "iUserId", ",", "$", "sSecret", ",", "$", "iCode", ")", "{", "// Tidy up codes so that they only contain digits", "$", "sCode", "=", "preg_replace", "(", "'/[^\\d]/'", ",", "''", ",", "$", "iCode", ")", ...
Validates a secret against two given codes, if valid adds as a device for the user @param int $iUserId The user's ID @param string $sSecret The secret being used @param int $iCode The first code to be generate @return boolean
[ "Validates", "a", "secret", "against", "two", "given", "codes", "if", "valid", "adds", "as", "a", "device", "for", "the", "user" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/Auth.php#L613-L651
train
nails/module-auth
src/Model/Auth.php
Auth.mfaDeviceCodeValidate
public function mfaDeviceCodeValidate($iUserId, $sCode) { // Get the user's secret $oSecret = $this->mfaDeviceSecretGet($iUserId); if (!$oSecret) { $this->setError('Invalid User'); return false; } // Has the code been used before? $oDb = Factory::service('Database'); $oDb->where('secret_id', $oSecret->id); $oDb->where('code', $sCode); if ($oDb->count_all_results(NAILS_DB_PREFIX . 'user_auth_two_factor_device_code')) { $this->setError('Code has already been used.'); return false; } // Tidy up codes so that they only contain digits $sCode = preg_replace('/[^\d]/', '', $sCode); // New instance of the authenticator $oGoogleAuth = new GoogleAuthenticator(); $checkCode = $oGoogleAuth->checkCode($oSecret->secret, $sCode); if ($checkCode) { // Log the code so it can't be used again $oDb->set('secret_id', $oSecret->id); $oDb->set('code', $sCode); $oDb->set('used', 'NOW()', false); $oDb->insert(NAILS_DB_PREFIX . 'user_auth_two_factor_device_code'); return true; } else { return false; } }
php
public function mfaDeviceCodeValidate($iUserId, $sCode) { // Get the user's secret $oSecret = $this->mfaDeviceSecretGet($iUserId); if (!$oSecret) { $this->setError('Invalid User'); return false; } // Has the code been used before? $oDb = Factory::service('Database'); $oDb->where('secret_id', $oSecret->id); $oDb->where('code', $sCode); if ($oDb->count_all_results(NAILS_DB_PREFIX . 'user_auth_two_factor_device_code')) { $this->setError('Code has already been used.'); return false; } // Tidy up codes so that they only contain digits $sCode = preg_replace('/[^\d]/', '', $sCode); // New instance of the authenticator $oGoogleAuth = new GoogleAuthenticator(); $checkCode = $oGoogleAuth->checkCode($oSecret->secret, $sCode); if ($checkCode) { // Log the code so it can't be used again $oDb->set('secret_id', $oSecret->id); $oDb->set('code', $sCode); $oDb->set('used', 'NOW()', false); $oDb->insert(NAILS_DB_PREFIX . 'user_auth_two_factor_device_code'); return true; } else { return false; } }
[ "public", "function", "mfaDeviceCodeValidate", "(", "$", "iUserId", ",", "$", "sCode", ")", "{", "// Get the user's secret", "$", "oSecret", "=", "$", "this", "->", "mfaDeviceSecretGet", "(", "$", "iUserId", ")", ";", "if", "(", "!", "$", "oSecret", ")", ...
Validates an MFA Device code @param int $iUserId The user's ID @param string $sCode The code to validate @return boolean
[ "Validates", "an", "MFA", "Device", "code" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/Auth.php#L663-L704
train
TuumPHP/Respond
src/Helper/Referrer.php
Referrer.saveReferrer
private function saveReferrer(ServerRequestInterface $request) { Respond::session()->set(self::REFERRER, $request->getUri()->__toString()); }
php
private function saveReferrer(ServerRequestInterface $request) { Respond::session()->set(self::REFERRER, $request->getUri()->__toString()); }
[ "private", "function", "saveReferrer", "(", "ServerRequestInterface", "$", "request", ")", "{", "Respond", "::", "session", "(", ")", "->", "set", "(", "self", "::", "REFERRER", ",", "$", "request", "->", "getUri", "(", ")", "->", "__toString", "(", ")", ...
saves the referrer uri to session. @param ServerRequestInterface $request
[ "saves", "the", "referrer", "uri", "to", "session", "." ]
5861ec0bffc97c500d88bf307a53277f1c2fe12f
https://github.com/TuumPHP/Respond/blob/5861ec0bffc97c500d88bf307a53277f1c2fe12f/src/Helper/Referrer.php#L46-L49
train
TuumPHP/Respond
src/Service/ViewData.php
ViewData.setMessage
public function setMessage($type, $message) { if (!is_null($message)) { $this->messages[] = [ 'message' => $message, 'type' => $type, ]; } return $this; }
php
public function setMessage($type, $message) { if (!is_null($message)) { $this->messages[] = [ 'message' => $message, 'type' => $type, ]; } return $this; }
[ "public", "function", "setMessage", "(", "$", "type", ",", "$", "message", ")", "{", "if", "(", "!", "is_null", "(", "$", "message", ")", ")", "{", "$", "this", "->", "messages", "[", "]", "=", "[", "'message'", "=>", "$", "message", ",", "'type'",...
a generic message method for Message helper. use success, alert, and error methods. @param string $type @param string $message @return ViewData
[ "a", "generic", "message", "method", "for", "Message", "helper", ".", "use", "success", "alert", "and", "error", "methods", "." ]
5861ec0bffc97c500d88bf307a53277f1c2fe12f
https://github.com/TuumPHP/Respond/blob/5861ec0bffc97c500d88bf307a53277f1c2fe12f/src/Service/ViewData.php#L143-L153
train
mirko-pagliai/me-cms
src/Utility/Checkups/Apache.php
Apache.modules
public function modules() { $modules = []; foreach ($this->modulesToCheck as $module) { $modules[$module] = in_array('mod_' . $module, apache_get_modules()); } return $modules; }
php
public function modules() { $modules = []; foreach ($this->modulesToCheck as $module) { $modules[$module] = in_array('mod_' . $module, apache_get_modules()); } return $modules; }
[ "public", "function", "modules", "(", ")", "{", "$", "modules", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "modulesToCheck", "as", "$", "module", ")", "{", "$", "modules", "[", "$", "module", "]", "=", "in_array", "(", "'mod_'", ".", "$...
Checks if some modules are loaded @return array @uses $modulesToCheck
[ "Checks", "if", "some", "modules", "are", "loaded" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/Checkups/Apache.php#L34-L43
train
helsingborg-stad/broken-link-detector
source/php/App.php
App.brokenLinksColumnSorting
public function brokenLinksColumnSorting() { add_filter('posts_fields', function ($fields, $query) { if ($query->get('orderby') !== 'broken-links') { return $fields; } global $wpdb; $fields .= ", ( SELECT COUNT(*) FROM " . self::$dbTable . " WHERE post_id = {$wpdb->posts}.ID ) AS broken_links_count"; return $fields; }, 10, 2); add_filter('posts_orderby', function ($orderby, $query) { if ($query->get('orderby') !== 'broken-links') { return $orderby; } $orderby = "broken_links_count {$query->get('order')}, " . $orderby; return $orderby; }, 10, 2); }
php
public function brokenLinksColumnSorting() { add_filter('posts_fields', function ($fields, $query) { if ($query->get('orderby') !== 'broken-links') { return $fields; } global $wpdb; $fields .= ", ( SELECT COUNT(*) FROM " . self::$dbTable . " WHERE post_id = {$wpdb->posts}.ID ) AS broken_links_count"; return $fields; }, 10, 2); add_filter('posts_orderby', function ($orderby, $query) { if ($query->get('orderby') !== 'broken-links') { return $orderby; } $orderby = "broken_links_count {$query->get('order')}, " . $orderby; return $orderby; }, 10, 2); }
[ "public", "function", "brokenLinksColumnSorting", "(", ")", "{", "add_filter", "(", "'posts_fields'", ",", "function", "(", "$", "fields", ",", "$", "query", ")", "{", "if", "(", "$", "query", "->", "get", "(", "'orderby'", ")", "!==", "'broken-links'", ")...
Sort post if sorting on broken-links column @return void
[ "Sort", "post", "if", "sorting", "on", "broken", "-", "links", "column" ]
f7ddc4a7258235b67dbfabe994de7335e7bcb73b
https://github.com/helsingborg-stad/broken-link-detector/blob/f7ddc4a7258235b67dbfabe994de7335e7bcb73b/source/php/App.php#L82-L108
train
helsingborg-stad/broken-link-detector
source/php/App.php
App.addListTablePage
public function addListTablePage() { add_submenu_page( 'options-general.php', 'Broken links', 'Broken links', 'edit_posts', 'broken-links-detector', function () { \BrokenLinkDetector\App::checkInstall(); $listTable = new \BrokenLinkDetector\ListTable(); $offset = get_option('gmt_offset'); if ($offset > -1) { $offset = '+' . $offset; } else { $offset = '-' . (1 * abs($offset)); } $nextRun = date('Y-m-d H:i', strtotime($offset . ' hours', wp_next_scheduled('broken-links-detector-external'))); include BROKENLINKDETECTOR_TEMPLATE_PATH . 'list-table.php'; } ); }
php
public function addListTablePage() { add_submenu_page( 'options-general.php', 'Broken links', 'Broken links', 'edit_posts', 'broken-links-detector', function () { \BrokenLinkDetector\App::checkInstall(); $listTable = new \BrokenLinkDetector\ListTable(); $offset = get_option('gmt_offset'); if ($offset > -1) { $offset = '+' . $offset; } else { $offset = '-' . (1 * abs($offset)); } $nextRun = date('Y-m-d H:i', strtotime($offset . ' hours', wp_next_scheduled('broken-links-detector-external'))); include BROKENLINKDETECTOR_TEMPLATE_PATH . 'list-table.php'; } ); }
[ "public", "function", "addListTablePage", "(", ")", "{", "add_submenu_page", "(", "'options-general.php'", ",", "'Broken links'", ",", "'Broken links'", ",", "'edit_posts'", ",", "'broken-links-detector'", ",", "function", "(", ")", "{", "\\", "BrokenLinkDetector", "\...
Adds the list table page of broken links
[ "Adds", "the", "list", "table", "page", "of", "broken", "links" ]
f7ddc4a7258235b67dbfabe994de7335e7bcb73b
https://github.com/helsingborg-stad/broken-link-detector/blob/f7ddc4a7258235b67dbfabe994de7335e7bcb73b/source/php/App.php#L151-L177
train
helsingborg-stad/broken-link-detector
source/php/App.php
App.checkSavedPost
public function checkSavedPost($data, $postarr) { remove_action('wp_insert_post_data', array($this, 'checkSavedPost'), 10, 2); $detector = new \BrokenLinkDetector\InternalDetector($data, $postarr); return $data; }
php
public function checkSavedPost($data, $postarr) { remove_action('wp_insert_post_data', array($this, 'checkSavedPost'), 10, 2); $detector = new \BrokenLinkDetector\InternalDetector($data, $postarr); return $data; }
[ "public", "function", "checkSavedPost", "(", "$", "data", ",", "$", "postarr", ")", "{", "remove_action", "(", "'wp_insert_post_data'", ",", "array", "(", "$", "this", ",", "'checkSavedPost'", ")", ",", "10", ",", "2", ")", ";", "$", "detector", "=", "ne...
Checks if a saved posts permalink is changed and updates permalinks throughout the site @param array $data Post data @param array $postarr $_POST data @return array Post data (do not change)
[ "Checks", "if", "a", "saved", "posts", "permalink", "is", "changed", "and", "updates", "permalinks", "throughout", "the", "site" ]
f7ddc4a7258235b67dbfabe994de7335e7bcb73b
https://github.com/helsingborg-stad/broken-link-detector/blob/f7ddc4a7258235b67dbfabe994de7335e7bcb73b/source/php/App.php#L226-L232
train
helsingborg-stad/broken-link-detector
source/php/App.php
App.deleteBrokenLinks
public function deleteBrokenLinks($postId) { global $wpdb; $tableName = self::$dbTable; $wpdb->delete($tableName, array('post_id' => $postId), array('%d')); }
php
public function deleteBrokenLinks($postId) { global $wpdb; $tableName = self::$dbTable; $wpdb->delete($tableName, array('post_id' => $postId), array('%d')); }
[ "public", "function", "deleteBrokenLinks", "(", "$", "postId", ")", "{", "global", "$", "wpdb", ";", "$", "tableName", "=", "self", "::", "$", "dbTable", ";", "$", "wpdb", "->", "delete", "(", "$", "tableName", ",", "array", "(", "'post_id'", "=>", "$"...
Remove broken links when deleting a page @param int $postId The post id that is being deleted
[ "Remove", "broken", "links", "when", "deleting", "a", "page" ]
f7ddc4a7258235b67dbfabe994de7335e7bcb73b
https://github.com/helsingborg-stad/broken-link-detector/blob/f7ddc4a7258235b67dbfabe994de7335e7bcb73b/source/php/App.php#L238-L243
train
mirko-pagliai/me-cms
src/Model/Table/UsersTable.php
UsersTable.findAuth
public function findAuth(Query $query, array $options) { return $query->contain('Groups', function (Query $q) { return $q->select(['name']); }); }
php
public function findAuth(Query $query, array $options) { return $query->contain('Groups', function (Query $q) { return $q->select(['name']); }); }
[ "public", "function", "findAuth", "(", "Query", "$", "query", ",", "array", "$", "options", ")", "{", "return", "$", "query", "->", "contain", "(", "'Groups'", ",", "function", "(", "Query", "$", "q", ")", "{", "return", "$", "q", "->", "select", "("...
"auth" find method @param Query $query Query object @param array $options Options @return Query Query object @since 2.25.1
[ "auth", "find", "method" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Model/Table/UsersTable.php#L89-L94
train
mirko-pagliai/me-cms
src/Model/Table/UsersTable.php
UsersTable.findBanned
public function findBanned(Query $query, array $options) { return $query->where([sprintf('%s.banned', $this->getAlias()) => true]); }
php
public function findBanned(Query $query, array $options) { return $query->where([sprintf('%s.banned', $this->getAlias()) => true]); }
[ "public", "function", "findBanned", "(", "Query", "$", "query", ",", "array", "$", "options", ")", "{", "return", "$", "query", "->", "where", "(", "[", "sprintf", "(", "'%s.banned'", ",", "$", "this", "->", "getAlias", "(", ")", ")", "=>", "true", "...
"banned" find method @param Query $query Query object @param array $options Options @return Query Query object
[ "banned", "find", "method" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Model/Table/UsersTable.php#L102-L105
train
mirko-pagliai/me-cms
src/Model/Table/UsersTable.php
UsersTable.findPending
public function findPending(Query $query, array $options) { return $query->where([ sprintf('%s.active', $this->getAlias()) => false, sprintf('%s.banned', $this->getAlias()) => false, ]); }
php
public function findPending(Query $query, array $options) { return $query->where([ sprintf('%s.active', $this->getAlias()) => false, sprintf('%s.banned', $this->getAlias()) => false, ]); }
[ "public", "function", "findPending", "(", "Query", "$", "query", ",", "array", "$", "options", ")", "{", "return", "$", "query", "->", "where", "(", "[", "sprintf", "(", "'%s.active'", ",", "$", "this", "->", "getAlias", "(", ")", ")", "=>", "false", ...
"pending" find method @param Query $query Query object @param array $options Options @return Query Query object
[ "pending", "find", "method" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Model/Table/UsersTable.php#L113-L119
train
mirko-pagliai/me-cms
src/Model/Table/UsersTable.php
UsersTable.getActiveList
public function getActiveList() { return $this->find() ->select(['id', 'first_name', 'last_name']) ->where([sprintf('%s.active', $this->getAlias()) => true]) ->order(['username' => 'ASC']) ->formatResults(function (ResultSet $results) { return $results->indexBy('id')->map(function (User $user) { return $user->first_name . ' ' . $user->last_name; }); }) ->cache(sprintf('active_%s_list', $this->getTable()), $this->getCacheName()); }
php
public function getActiveList() { return $this->find() ->select(['id', 'first_name', 'last_name']) ->where([sprintf('%s.active', $this->getAlias()) => true]) ->order(['username' => 'ASC']) ->formatResults(function (ResultSet $results) { return $results->indexBy('id')->map(function (User $user) { return $user->first_name . ' ' . $user->last_name; }); }) ->cache(sprintf('active_%s_list', $this->getTable()), $this->getCacheName()); }
[ "public", "function", "getActiveList", "(", ")", "{", "return", "$", "this", "->", "find", "(", ")", "->", "select", "(", "[", "'id'", ",", "'first_name'", ",", "'last_name'", "]", ")", "->", "where", "(", "[", "sprintf", "(", "'%s.active'", ",", "$", ...
Gets active users as list @return Query $query Query object
[ "Gets", "active", "users", "as", "list" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Model/Table/UsersTable.php#L125-L137
train
mirko-pagliai/me-cms
src/Model/Table/UsersTable.php
UsersTable.validationDoNotRequirePresence
public function validationDoNotRequirePresence(UserValidator $validator) { //No field is required foreach ($validator->getIterator() as $field => $rules) { $validator->requirePresence($field, false); } return $validator; }
php
public function validationDoNotRequirePresence(UserValidator $validator) { //No field is required foreach ($validator->getIterator() as $field => $rules) { $validator->requirePresence($field, false); } return $validator; }
[ "public", "function", "validationDoNotRequirePresence", "(", "UserValidator", "$", "validator", ")", "{", "//No field is required", "foreach", "(", "$", "validator", "->", "getIterator", "(", ")", "as", "$", "field", "=>", "$", "rules", ")", "{", "$", "validator...
Validation "do not require presence". This validator doesn't require the presence of fields. @param UserValidator $validator Validator instance @return UserValidator
[ "Validation", "do", "not", "require", "presence", "." ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Model/Table/UsersTable.php#L220-L228
train
mirko-pagliai/me-cms
src/View/Cell/PostsTagsWidgetsCell.php
PostsTagsWidgetsCell.getFontSizes
protected function getFontSizes(array $style = []) { //Maximum and minimun font sizes we want to use $maxFont = empty($style['maxFont']) ? 40 : $style['maxFont']; $minFont = empty($style['minFont']) ? 12 : $style['minFont']; is_true_or_fail($maxFont > $minFont, __d('me_cms', 'Invalid values'), InvalidArgumentException::class); return [$maxFont, $minFont]; }
php
protected function getFontSizes(array $style = []) { //Maximum and minimun font sizes we want to use $maxFont = empty($style['maxFont']) ? 40 : $style['maxFont']; $minFont = empty($style['minFont']) ? 12 : $style['minFont']; is_true_or_fail($maxFont > $minFont, __d('me_cms', 'Invalid values'), InvalidArgumentException::class); return [$maxFont, $minFont]; }
[ "protected", "function", "getFontSizes", "(", "array", "$", "style", "=", "[", "]", ")", "{", "//Maximum and minimun font sizes we want to use", "$", "maxFont", "=", "empty", "(", "$", "style", "[", "'maxFont'", "]", ")", "?", "40", ":", "$", "style", "[", ...
Internal method to get the font sizes @param array|bool $style Style for tags. Array with `maxFont` and `minFont` keys or `false` to disable @return array @throws InvalidArgumentException
[ "Internal", "method", "to", "get", "the", "font", "sizes" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/Cell/PostsTagsWidgetsCell.php#L41-L49
train
mirko-pagliai/me-cms
src/View/Cell/PostsTagsWidgetsCell.php
PostsTagsWidgetsCell.popular
public function popular( $limit = 10, $prefix = '#', $render = 'cloud', $shuffle = true, $style = ['maxFont' => 40, 'minFont' => 12] ) { $this->viewBuilder()->setTemplate(sprintf('popular_as_%s', $render)); //Returns on tags index if ($this->request->isUrl(['_name' => 'postsTags'])) { return; } //Sets default maximum and minimun font sizes we want to use $maxFont = $minFont = 0; //Sets the initial cache name $cache = sprintf('widget_tags_popular_%s', $limit); if ($style && is_array($style)) { //Updates maximum and minimun font sizes we want to use list($maxFont, $minFont) = $this->getFontSizes($style); //Updates the cache name $cache = sprintf('%s_max_%s_min_%s', $cache, $maxFont, $minFont); } $tags = $this->Tags->find() ->select(['tag', 'post_count']) ->limit($limit) ->order([ sprintf('%s.post_count', $this->Tags->getAlias()) => 'DESC', sprintf('%s.tag', $this->Tags->getAlias()) => 'ASC', ]) ->formatResults(function (ResultSet $results) use ($style, $maxFont, $minFont) { $results = $results->indexBy('slug'); if (!$results->count() || !$style || !$maxFont || !$minFont) { return $results; } //Highest and lowest numbers of occurrences and their difference $minCount = $results->last()->post_count; $diffCount = $results->first()->post_count - $minCount; $diffFont = $maxFont - $minFont; return $results->map(function (Tag $tag) use ($minCount, $diffCount, $maxFont, $minFont, $diffFont) { $tag->size = $diffCount ? round((($tag->post_count - $minCount) / $diffCount * $diffFont) + $minFont) : $maxFont; return $tag; }); }) ->cache($cache, $this->Tags->getCacheName()) ->all(); if ($shuffle) { $tags = $tags->shuffle(); } $this->set(compact('prefix', 'tags')); }
php
public function popular( $limit = 10, $prefix = '#', $render = 'cloud', $shuffle = true, $style = ['maxFont' => 40, 'minFont' => 12] ) { $this->viewBuilder()->setTemplate(sprintf('popular_as_%s', $render)); //Returns on tags index if ($this->request->isUrl(['_name' => 'postsTags'])) { return; } //Sets default maximum and minimun font sizes we want to use $maxFont = $minFont = 0; //Sets the initial cache name $cache = sprintf('widget_tags_popular_%s', $limit); if ($style && is_array($style)) { //Updates maximum and minimun font sizes we want to use list($maxFont, $minFont) = $this->getFontSizes($style); //Updates the cache name $cache = sprintf('%s_max_%s_min_%s', $cache, $maxFont, $minFont); } $tags = $this->Tags->find() ->select(['tag', 'post_count']) ->limit($limit) ->order([ sprintf('%s.post_count', $this->Tags->getAlias()) => 'DESC', sprintf('%s.tag', $this->Tags->getAlias()) => 'ASC', ]) ->formatResults(function (ResultSet $results) use ($style, $maxFont, $minFont) { $results = $results->indexBy('slug'); if (!$results->count() || !$style || !$maxFont || !$minFont) { return $results; } //Highest and lowest numbers of occurrences and their difference $minCount = $results->last()->post_count; $diffCount = $results->first()->post_count - $minCount; $diffFont = $maxFont - $minFont; return $results->map(function (Tag $tag) use ($minCount, $diffCount, $maxFont, $minFont, $diffFont) { $tag->size = $diffCount ? round((($tag->post_count - $minCount) / $diffCount * $diffFont) + $minFont) : $maxFont; return $tag; }); }) ->cache($cache, $this->Tags->getCacheName()) ->all(); if ($shuffle) { $tags = $tags->shuffle(); } $this->set(compact('prefix', 'tags')); }
[ "public", "function", "popular", "(", "$", "limit", "=", "10", ",", "$", "prefix", "=", "'#'", ",", "$", "render", "=", "'cloud'", ",", "$", "shuffle", "=", "true", ",", "$", "style", "=", "[", "'maxFont'", "=>", "40", ",", "'minFont'", "=>", "12",...
Popular tags widgets @param int $limit Limit @param string $prefix Prefix for each tag. This works only with the cloud @param string $render Render type (`cloud`, `form` or `list`) @param bool $shuffle Shuffles tags @param array|bool $style Style for tags. Array with `maxFont` and `minFont` keys or `false` to disable @return void @uses getFontSizes()
[ "Popular", "tags", "widgets" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/Cell/PostsTagsWidgetsCell.php#L62-L123
train
gnugat/GnugatWizardBundle
EventListener/ComposerListener.php
ComposerListener.registerPackage
public static function registerPackage(Event $event) { $installedPackage = $event->getOperation()->getPackage(); if (!self::isBundle($installedPackage)) { return; } self::enablePackage($installedPackage); }
php
public static function registerPackage(Event $event) { $installedPackage = $event->getOperation()->getPackage(); if (!self::isBundle($installedPackage)) { return; } self::enablePackage($installedPackage); }
[ "public", "static", "function", "registerPackage", "(", "Event", "$", "event", ")", "{", "$", "installedPackage", "=", "$", "event", "->", "getOperation", "(", ")", "->", "getPackage", "(", ")", ";", "if", "(", "!", "self", "::", "isBundle", "(", "$", ...
On Composer's "post-package-install" event, register the package. @param Event $event
[ "On", "Composer", "s", "post", "-", "package", "-", "install", "event", "register", "the", "package", "." ]
caffb6f12f4d5346ae68a931e572f662128b68be
https://github.com/gnugat/GnugatWizardBundle/blob/caffb6f12f4d5346ae68a931e572f662128b68be/EventListener/ComposerListener.php#L33-L42
train
TuumPHP/Respond
src/Responder/Redirect.php
Redirect.toPath
public function toPath($path) { $uri = $this->request->getUri()->withPath($path); return $this->toAbsoluteUri($uri); }
php
public function toPath($path) { $uri = $this->request->getUri()->withPath($path); return $this->toAbsoluteUri($uri); }
[ "public", "function", "toPath", "(", "$", "path", ")", "{", "$", "uri", "=", "$", "this", "->", "request", "->", "getUri", "(", ")", "->", "withPath", "(", "$", "path", ")", ";", "return", "$", "this", "->", "toAbsoluteUri", "(", "$", "uri", ")", ...
redirects to a path in string. uses current hosts and scheme. @param string $path @return ResponseInterface
[ "redirects", "to", "a", "path", "in", "string", ".", "uses", "current", "hosts", "and", "scheme", "." ]
5861ec0bffc97c500d88bf307a53277f1c2fe12f
https://github.com/TuumPHP/Respond/blob/5861ec0bffc97c500d88bf307a53277f1c2fe12f/src/Responder/Redirect.php#L75-L80
train
mirko-pagliai/me-cms
src/View/Cell/PostsWidgetsCell.php
PostsWidgetsCell.months
public function months($render = 'form') { $this->viewBuilder()->setTemplate(sprintf('months_as_%s', $render)); //Returns on posts index if ($this->request->isUrl(['_name' => 'posts'])) { return; } $query = $this->Posts->find('active'); $time = $query->func()->date_format(['created' => 'identifier', "'%Y/%m'" => 'literal']); $months = $query->select([ 'month' => $time, 'post_count' => $query->func()->count($time), ]) ->distinct(['month']) ->formatResults(function (ResultSet $results) { return $results->indexBy('month') ->map(function (Post $post) { list($year, $month) = explode('/', $post->month); $post->month = (new FrozenDate())->day(1)->month($month)->year($year); return $post; }); }) ->order(['month' => 'DESC']) ->cache('widget_months', $this->Posts->getCacheName()) ->all(); $this->set(compact('months')); }
php
public function months($render = 'form') { $this->viewBuilder()->setTemplate(sprintf('months_as_%s', $render)); //Returns on posts index if ($this->request->isUrl(['_name' => 'posts'])) { return; } $query = $this->Posts->find('active'); $time = $query->func()->date_format(['created' => 'identifier', "'%Y/%m'" => 'literal']); $months = $query->select([ 'month' => $time, 'post_count' => $query->func()->count($time), ]) ->distinct(['month']) ->formatResults(function (ResultSet $results) { return $results->indexBy('month') ->map(function (Post $post) { list($year, $month) = explode('/', $post->month); $post->month = (new FrozenDate())->day(1)->month($month)->year($year); return $post; }); }) ->order(['month' => 'DESC']) ->cache('widget_months', $this->Posts->getCacheName()) ->all(); $this->set(compact('months')); }
[ "public", "function", "months", "(", "$", "render", "=", "'form'", ")", "{", "$", "this", "->", "viewBuilder", "(", ")", "->", "setTemplate", "(", "sprintf", "(", "'months_as_%s'", ",", "$", "render", ")", ")", ";", "//Returns on posts index", "if", "(", ...
Posts by month widget @param string $render Render type (`form` or `list`) @return void
[ "Posts", "by", "month", "widget" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/Cell/PostsWidgetsCell.php#L87-L117
train
yawik/settings
src/Entity/Hydrator/Strategy/DisableElementsCapableFormSettings.php
DisableElementsCapableFormSettings.filterArrayStrings
protected function filterArrayStrings($array, $search, $replace) { $return = array(); foreach ((array)$array as $key => $value) { $key = str_replace($search, $replace, $key); $value = is_array($value) ? $this->filterArrayStrings($value, $search, $replace) : str_replace($search, $replace, $value); $return[$key] = $value; } return $return; }
php
protected function filterArrayStrings($array, $search, $replace) { $return = array(); foreach ((array)$array as $key => $value) { $key = str_replace($search, $replace, $key); $value = is_array($value) ? $this->filterArrayStrings($value, $search, $replace) : str_replace($search, $replace, $value); $return[$key] = $value; } return $return; }
[ "protected", "function", "filterArrayStrings", "(", "$", "array", ",", "$", "search", ",", "$", "replace", ")", "{", "$", "return", "=", "array", "(", ")", ";", "foreach", "(", "(", "array", ")", "$", "array", "as", "$", "key", "=>", "$", "value", ...
Replaces strings in array keys and values recursively. @param array $array Target array @param string|array $search Search string(s) @param string|array $replace Replacement string(s) @return array
[ "Replaces", "strings", "in", "array", "keys", "and", "values", "recursively", "." ]
fc49d14a5eec21fcc074ce29b1428d91191efecf
https://github.com/yawik/settings/blob/fc49d14a5eec21fcc074ce29b1428d91191efecf/src/Entity/Hydrator/Strategy/DisableElementsCapableFormSettings.php#L56-L69
train
s9e/RegexpBuilder
src/Escaper.php
Escaper.escapeCharacterClass
public function escapeCharacterClass($char) { return (isset($this->inCharacterClass[$char])) ? $this->inCharacterClass[$char] : $char; }
php
public function escapeCharacterClass($char) { return (isset($this->inCharacterClass[$char])) ? $this->inCharacterClass[$char] : $char; }
[ "public", "function", "escapeCharacterClass", "(", "$", "char", ")", "{", "return", "(", "isset", "(", "$", "this", "->", "inCharacterClass", "[", "$", "char", "]", ")", ")", "?", "$", "this", "->", "inCharacterClass", "[", "$", "char", "]", ":", "$", ...
Escape given character to be used in a character class @param string $char Original character @return string Escaped character
[ "Escape", "given", "character", "to", "be", "used", "in", "a", "character", "class" ]
59d0167a909659d718f53964f7653d2c83a5f8fe
https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/Escaper.php#L44-L47
train
s9e/RegexpBuilder
src/Escaper.php
Escaper.escapeLiteral
public function escapeLiteral($char) { return (isset($this->inLiteral[$char])) ? $this->inLiteral[$char] : $char; }
php
public function escapeLiteral($char) { return (isset($this->inLiteral[$char])) ? $this->inLiteral[$char] : $char; }
[ "public", "function", "escapeLiteral", "(", "$", "char", ")", "{", "return", "(", "isset", "(", "$", "this", "->", "inLiteral", "[", "$", "char", "]", ")", ")", "?", "$", "this", "->", "inLiteral", "[", "$", "char", "]", ":", "$", "char", ";", "}...
Escape given character to be used outside of a character class @param string $char Original character @return string Escaped character
[ "Escape", "given", "character", "to", "be", "used", "outside", "of", "a", "character", "class" ]
59d0167a909659d718f53964f7653d2c83a5f8fe
https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/Escaper.php#L55-L58
train
CradlePHP/cradle-queue
src/Service/RedisService.php
RedisService.add
public function add($id, $data = 1) { try { return $this->resource->hSet(static::CACHE_KEY, $id, $data); } catch (ConnectionException $e) { return false; } }
php
public function add($id, $data = 1) { try { return $this->resource->hSet(static::CACHE_KEY, $id, $data); } catch (ConnectionException $e) { return false; } }
[ "public", "function", "add", "(", "$", "id", ",", "$", "data", "=", "1", ")", "{", "try", "{", "return", "$", "this", "->", "resource", "->", "hSet", "(", "static", "::", "CACHE_KEY", ",", "$", "id", ",", "$", "data", ")", ";", "}", "catch", "(...
Cache an id @param *string $id @return bool
[ "Cache", "an", "id" ]
24e07509cddea99383967650bab41480706b3d4b
https://github.com/CradlePHP/cradle-queue/blob/24e07509cddea99383967650bab41480706b3d4b/src/Service/RedisService.php#L51-L58
train
CradlePHP/cradle-queue
src/Service/RedisService.php
RedisService.exists
public function exists($id) { try { return !!$this->resource->hExists(static::CACHE_KEY, $id); } catch (ConnectionException $e) { return false; } }
php
public function exists($id) { try { return !!$this->resource->hExists(static::CACHE_KEY, $id); } catch (ConnectionException $e) { return false; } }
[ "public", "function", "exists", "(", "$", "id", ")", "{", "try", "{", "return", "!", "!", "$", "this", "->", "resource", "->", "hExists", "(", "static", "::", "CACHE_KEY", ",", "$", "id", ")", ";", "}", "catch", "(", "ConnectionException", "$", "e", ...
Returns true if a key exists @param *string $id @return bool
[ "Returns", "true", "if", "a", "key", "exists" ]
24e07509cddea99383967650bab41480706b3d4b
https://github.com/CradlePHP/cradle-queue/blob/24e07509cddea99383967650bab41480706b3d4b/src/Service/RedisService.php#L83-L90
train
CradlePHP/cradle-queue
src/Service/RedisService.php
RedisService.remove
public function remove($id) { try { return $this->resource->hDel(static::CACHE_KEY, $id); } catch (ConnectionException $e) { return false; } }
php
public function remove($id) { try { return $this->resource->hDel(static::CACHE_KEY, $id); } catch (ConnectionException $e) { return false; } }
[ "public", "function", "remove", "(", "$", "id", ")", "{", "try", "{", "return", "$", "this", "->", "resource", "->", "hDel", "(", "static", "::", "CACHE_KEY", ",", "$", "id", ")", ";", "}", "catch", "(", "ConnectionException", "$", "e", ")", "{", "...
Remove a cache key @param *string $id @return array
[ "Remove", "a", "cache", "key" ]
24e07509cddea99383967650bab41480706b3d4b
https://github.com/CradlePHP/cradle-queue/blob/24e07509cddea99383967650bab41480706b3d4b/src/Service/RedisService.php#L99-L106
train
s9e/RegexpBuilder
src/Passes/MergeSuffix.php
MergeSuffix.hasMatchingSuffix
protected function hasMatchingSuffix(array $strings) { $suffix = end($strings[1]); foreach ($strings as $string) { if (end($string) !== $suffix) { return false; } } return ($suffix !== false); }
php
protected function hasMatchingSuffix(array $strings) { $suffix = end($strings[1]); foreach ($strings as $string) { if (end($string) !== $suffix) { return false; } } return ($suffix !== false); }
[ "protected", "function", "hasMatchingSuffix", "(", "array", "$", "strings", ")", "{", "$", "suffix", "=", "end", "(", "$", "strings", "[", "1", "]", ")", ";", "foreach", "(", "$", "strings", "as", "$", "string", ")", "{", "if", "(", "end", "(", "$"...
Test whether all given strings have the same last element @param array[] $strings @return bool
[ "Test", "whether", "all", "given", "strings", "have", "the", "same", "last", "element" ]
59d0167a909659d718f53964f7653d2c83a5f8fe
https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/Passes/MergeSuffix.php#L45-L57
train
s9e/RegexpBuilder
src/Passes/MergeSuffix.php
MergeSuffix.pop
protected function pop(array $strings) { $cnt = count($strings); $i = $cnt; while (--$i >= 0) { array_pop($strings[$i]); } // Remove empty elements then prepend one back at the start of the array if applicable $strings = array_filter($strings); if (count($strings) < $cnt) { array_unshift($strings, []); } return $strings; }
php
protected function pop(array $strings) { $cnt = count($strings); $i = $cnt; while (--$i >= 0) { array_pop($strings[$i]); } // Remove empty elements then prepend one back at the start of the array if applicable $strings = array_filter($strings); if (count($strings) < $cnt) { array_unshift($strings, []); } return $strings; }
[ "protected", "function", "pop", "(", "array", "$", "strings", ")", "{", "$", "cnt", "=", "count", "(", "$", "strings", ")", ";", "$", "i", "=", "$", "cnt", ";", "while", "(", "--", "$", "i", ">=", "0", ")", "{", "array_pop", "(", "$", "strings"...
Remove the last element of every string @param array[] $strings Original strings @return array[] Processed strings
[ "Remove", "the", "last", "element", "of", "every", "string" ]
59d0167a909659d718f53964f7653d2c83a5f8fe
https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/Passes/MergeSuffix.php#L65-L82
train
nails/module-auth
src/Api/Controller/User.php
User.getSearch
public function getSearch($aData = []) { if (!userHasPermission('admin:auth:accounts:browse')) { $oHttpCodes = Factory::service('HttpCodes'); throw new ApiException( 'You are not authorised to search users', $oHttpCodes::STATUS_UNAUTHORIZED ); } return parent::getSearch($aData); }
php
public function getSearch($aData = []) { if (!userHasPermission('admin:auth:accounts:browse')) { $oHttpCodes = Factory::service('HttpCodes'); throw new ApiException( 'You are not authorised to search users', $oHttpCodes::STATUS_UNAUTHORIZED ); } return parent::getSearch($aData); }
[ "public", "function", "getSearch", "(", "$", "aData", "=", "[", "]", ")", "{", "if", "(", "!", "userHasPermission", "(", "'admin:auth:accounts:browse'", ")", ")", "{", "$", "oHttpCodes", "=", "Factory", "::", "service", "(", "'HttpCodes'", ")", ";", "throw...
Search for an item @return array
[ "Search", "for", "an", "item" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Api/Controller/User.php#L64-L75
train
nails/module-auth
src/Api/Controller/User.php
User.getEmail
public function getEmail() { $oHttpCodes = Factory::service('HttpCodes'); if (!userHasPermission('admin:auth:accounts:browse')) { throw new ApiException( 'You are not authorised to browse users', $oHttpCodes::STATUS_UNAUTHORIZED ); } $oInput = Factory::service('Input'); $sEmail = $oInput->get('email'); if (!valid_email($sEmail)) { throw new ApiException( '"' . $sEmail . '" is not a valid email', $oHttpCodes::STATUS_BAD_REQUEST ); } $oUserModel = Factory::model(static::CONFIG_MODEL_NAME, static::CONFIG_MODEL_PROVIDER); $oUser = $oUserModel->getByEmail($sEmail); if (empty($oUser)) { throw new ApiException( 'No user found for email "' . $sEmail . '"', $oHttpCodes::STATUS_NOT_FOUND ); } return Factory::factory('ApiResponse', 'nails/module-api') ->setData($this->formatObject($oUser)); }
php
public function getEmail() { $oHttpCodes = Factory::service('HttpCodes'); if (!userHasPermission('admin:auth:accounts:browse')) { throw new ApiException( 'You are not authorised to browse users', $oHttpCodes::STATUS_UNAUTHORIZED ); } $oInput = Factory::service('Input'); $sEmail = $oInput->get('email'); if (!valid_email($sEmail)) { throw new ApiException( '"' . $sEmail . '" is not a valid email', $oHttpCodes::STATUS_BAD_REQUEST ); } $oUserModel = Factory::model(static::CONFIG_MODEL_NAME, static::CONFIG_MODEL_PROVIDER); $oUser = $oUserModel->getByEmail($sEmail); if (empty($oUser)) { throw new ApiException( 'No user found for email "' . $sEmail . '"', $oHttpCodes::STATUS_NOT_FOUND ); } return Factory::factory('ApiResponse', 'nails/module-api') ->setData($this->formatObject($oUser)); }
[ "public", "function", "getEmail", "(", ")", "{", "$", "oHttpCodes", "=", "Factory", "::", "service", "(", "'HttpCodes'", ")", ";", "if", "(", "!", "userHasPermission", "(", "'admin:auth:accounts:browse'", ")", ")", "{", "throw", "new", "ApiException", "(", "...
Returns a user by their email @return array
[ "Returns", "a", "user", "by", "their", "email" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Api/Controller/User.php#L84-L117
train
nails/module-auth
src/Api/Controller/User.php
User.postRemap
public function postRemap() { $oUri = Factory::service('Uri'); $iItemId = (int) $oUri->segment(4); if ($iItemId && $iItemId != activeUSer('id') && !userHasPermission('admin:auth:accounts:editothers')) { return [ 'status' => 401, 'error' => 'You do not have permission to update this resource', ]; } elseif (!$iItemId && !userHasPermission('admin:auth:accounts:create')) { return [ 'status' => 401, 'error' => 'You do not have permission to create this type of resource', ]; } return parent::postRemap(); }
php
public function postRemap() { $oUri = Factory::service('Uri'); $iItemId = (int) $oUri->segment(4); if ($iItemId && $iItemId != activeUSer('id') && !userHasPermission('admin:auth:accounts:editothers')) { return [ 'status' => 401, 'error' => 'You do not have permission to update this resource', ]; } elseif (!$iItemId && !userHasPermission('admin:auth:accounts:create')) { return [ 'status' => 401, 'error' => 'You do not have permission to create this type of resource', ]; } return parent::postRemap(); }
[ "public", "function", "postRemap", "(", ")", "{", "$", "oUri", "=", "Factory", "::", "service", "(", "'Uri'", ")", ";", "$", "iItemId", "=", "(", "int", ")", "$", "oUri", "->", "segment", "(", "4", ")", ";", "if", "(", "$", "iItemId", "&&", "$", ...
Creates or updates a user @return array
[ "Creates", "or", "updates", "a", "user" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Api/Controller/User.php#L126-L143
train
nails/module-auth
src/Api/Controller/User.php
User.formatObject
public function formatObject($oObj) { return [ 'id' => $oObj->id, 'first_name' => $oObj->first_name, 'last_name' => $oObj->last_name, 'email' => $oObj->email, ]; }
php
public function formatObject($oObj) { return [ 'id' => $oObj->id, 'first_name' => $oObj->first_name, 'last_name' => $oObj->last_name, 'email' => $oObj->email, ]; }
[ "public", "function", "formatObject", "(", "$", "oObj", ")", "{", "return", "[", "'id'", "=>", "$", "oObj", "->", "id", ",", "'first_name'", "=>", "$", "oObj", "->", "first_name", ",", "'last_name'", "=>", "$", "oObj", "->", "last_name", ",", "'email'", ...
Format the output @param \stdClass $oObj The object to format @return array
[ "Format", "the", "output" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Api/Controller/User.php#L154-L162
train
PitonCMS/Engine
app/Library/Handlers/FileUploadHandler.php
FileUploadHandler.upload
public function upload(string $fileKey) { if (!isset($this->uploadedFiles[$fileKey])) { throw new Exception('PitonCMS: File upload key does not exist'); } $file = $this->uploadedFiles[$fileKey]; if ($file->getError() === UPLOAD_ERR_OK) { // Get file name and extension $uploadFileName = $file->getClientFilename(); $ext = strtolower(pathinfo($uploadFileName, PATHINFO_EXTENSION)); // Create new file name and directory and ensure it is unique do { $name = $this->generateName(); $path = $this->getFilePath($name); $exists = $this->makeFileDirectory($path); } while (!$exists); $this->fileName = "$name.$ext"; $file->moveTo("{$this->publicRoot}{$path}{$this->fileName}"); unset($file); return true; } // Save error code $this->error = $file->getError(); return false; }
php
public function upload(string $fileKey) { if (!isset($this->uploadedFiles[$fileKey])) { throw new Exception('PitonCMS: File upload key does not exist'); } $file = $this->uploadedFiles[$fileKey]; if ($file->getError() === UPLOAD_ERR_OK) { // Get file name and extension $uploadFileName = $file->getClientFilename(); $ext = strtolower(pathinfo($uploadFileName, PATHINFO_EXTENSION)); // Create new file name and directory and ensure it is unique do { $name = $this->generateName(); $path = $this->getFilePath($name); $exists = $this->makeFileDirectory($path); } while (!$exists); $this->fileName = "$name.$ext"; $file->moveTo("{$this->publicRoot}{$path}{$this->fileName}"); unset($file); return true; } // Save error code $this->error = $file->getError(); return false; }
[ "public", "function", "upload", "(", "string", "$", "fileKey", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "uploadedFiles", "[", "$", "fileKey", "]", ")", ")", "{", "throw", "new", "Exception", "(", "'PitonCMS: File upload key does not exist'"...
Upload File Action Upload file from $_FILES array @param string $fileKey Array key for file @return boolean True|False
[ "Upload", "File", "Action" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Handlers/FileUploadHandler.php#L70-L102
train
PitonCMS/Engine
app/Library/Handlers/FileUploadHandler.php
FileUploadHandler.getErrorMessage
public function getErrorMessage() { switch ($this->error) { case UPLOAD_ERR_INI_SIZE: $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; break; case UPLOAD_ERR_FORM_SIZE: $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; break; case UPLOAD_ERR_PARTIAL: $message = "The uploaded file was only partially uploaded"; break; case UPLOAD_ERR_NO_FILE: $message = "No file was uploaded"; break; case UPLOAD_ERR_NO_TMP_DIR: $message = "Missing a temporary folder"; break; case UPLOAD_ERR_CANT_WRITE: $message = "Failed to write file to disk"; break; case UPLOAD_ERR_EXTENSION: $message = "File upload stopped by extension"; break; default: $message = "Unknown upload error"; } return $message; }
php
public function getErrorMessage() { switch ($this->error) { case UPLOAD_ERR_INI_SIZE: $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; break; case UPLOAD_ERR_FORM_SIZE: $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; break; case UPLOAD_ERR_PARTIAL: $message = "The uploaded file was only partially uploaded"; break; case UPLOAD_ERR_NO_FILE: $message = "No file was uploaded"; break; case UPLOAD_ERR_NO_TMP_DIR: $message = "Missing a temporary folder"; break; case UPLOAD_ERR_CANT_WRITE: $message = "Failed to write file to disk"; break; case UPLOAD_ERR_EXTENSION: $message = "File upload stopped by extension"; break; default: $message = "Unknown upload error"; } return $message; }
[ "public", "function", "getErrorMessage", "(", ")", "{", "switch", "(", "$", "this", "->", "error", ")", "{", "case", "UPLOAD_ERR_INI_SIZE", ":", "$", "message", "=", "\"The uploaded file exceeds the upload_max_filesize directive in php.ini\"", ";", "break", ";", "case...
Get Upload Error Message Converts PHP UPLOAD_ERR_* codes to text @param void @return string
[ "Get", "Upload", "Error", "Message" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Handlers/FileUploadHandler.php#L134-L164
train
PitonCMS/Engine
app/Library/Handlers/FileUploadHandler.php
FileUploadHandler.makeFileDirectory
protected function makeFileDirectory($directoryPath) { $filePath = $this->publicRoot . $directoryPath; // Create the path if the directory does not exist if (!is_dir($filePath)) { try { mkdir($filePath, 0775, true); return true; } catch (Exception $e) { throw new Exception('PitonCMS: Failed to create file upload directory'); } } // The directory already exists return false; }
php
protected function makeFileDirectory($directoryPath) { $filePath = $this->publicRoot . $directoryPath; // Create the path if the directory does not exist if (!is_dir($filePath)) { try { mkdir($filePath, 0775, true); return true; } catch (Exception $e) { throw new Exception('PitonCMS: Failed to create file upload directory'); } } // The directory already exists return false; }
[ "protected", "function", "makeFileDirectory", "(", "$", "directoryPath", ")", "{", "$", "filePath", "=", "$", "this", "->", "publicRoot", ".", "$", "directoryPath", ";", "// Create the path if the directory does not exist", "if", "(", "!", "is_dir", "(", "$", "fil...
Make Directory Path Creates the directory path @param string $directoryPath @return bool True|False
[ "Make", "Directory", "Path" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Handlers/FileUploadHandler.php#L173-L189
train
s9e/RegexpBuilder
src/Input/Utf8.php
Utf8.charsToCodepointsWithSurrogates
protected function charsToCodepointsWithSurrogates(array $chars) { $codepoints = []; foreach ($chars as $char) { $cp = $this->cp($char); if ($cp < 0x10000) { $codepoints[] = $cp; } else { $codepoints[] = 0xD7C0 + ($cp >> 10); $codepoints[] = 0xDC00 + ($cp & 0x3FF); } } return $codepoints; }
php
protected function charsToCodepointsWithSurrogates(array $chars) { $codepoints = []; foreach ($chars as $char) { $cp = $this->cp($char); if ($cp < 0x10000) { $codepoints[] = $cp; } else { $codepoints[] = 0xD7C0 + ($cp >> 10); $codepoints[] = 0xDC00 + ($cp & 0x3FF); } } return $codepoints; }
[ "protected", "function", "charsToCodepointsWithSurrogates", "(", "array", "$", "chars", ")", "{", "$", "codepoints", "=", "[", "]", ";", "foreach", "(", "$", "chars", "as", "$", "char", ")", "{", "$", "cp", "=", "$", "this", "->", "cp", "(", "$", "ch...
Convert a list of UTF-8 characters into a list of Unicode codepoint with surrogates @param string[] $chars @return integer[]
[ "Convert", "a", "list", "of", "UTF", "-", "8", "characters", "into", "a", "list", "of", "Unicode", "codepoint", "with", "surrogates" ]
59d0167a909659d718f53964f7653d2c83a5f8fe
https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/Input/Utf8.php#L57-L75
train
s9e/RegexpBuilder
src/Input/Utf8.php
Utf8.cp
protected function cp($char) { $cp = ord($char[0]); if ($cp >= 0xF0) { $cp = ($cp << 18) + (ord($char[1]) << 12) + (ord($char[2]) << 6) + ord($char[3]) - 0x3C82080; } elseif ($cp >= 0xE0) { $cp = ($cp << 12) + (ord($char[1]) << 6) + ord($char[2]) - 0xE2080; } elseif ($cp >= 0xC0) { $cp = ($cp << 6) + ord($char[1]) - 0x3080; } return $cp; }
php
protected function cp($char) { $cp = ord($char[0]); if ($cp >= 0xF0) { $cp = ($cp << 18) + (ord($char[1]) << 12) + (ord($char[2]) << 6) + ord($char[3]) - 0x3C82080; } elseif ($cp >= 0xE0) { $cp = ($cp << 12) + (ord($char[1]) << 6) + ord($char[2]) - 0xE2080; } elseif ($cp >= 0xC0) { $cp = ($cp << 6) + ord($char[1]) - 0x3080; } return $cp; }
[ "protected", "function", "cp", "(", "$", "char", ")", "{", "$", "cp", "=", "ord", "(", "$", "char", "[", "0", "]", ")", ";", "if", "(", "$", "cp", ">=", "0xF0", ")", "{", "$", "cp", "=", "(", "$", "cp", "<<", "18", ")", "+", "(", "ord", ...
Compute and return the Unicode codepoint for given UTF-8 char @param string $char UTF-8 char @return integer
[ "Compute", "and", "return", "the", "Unicode", "codepoint", "for", "given", "UTF", "-", "8", "char" ]
59d0167a909659d718f53964f7653d2c83a5f8fe
https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/Input/Utf8.php#L83-L100
train
PitonCMS/Engine
app/Models/Entities/Page.php
Page.getPublishedStatus
public function getPublishedStatus() { $today = date('Y-m-d'); if (empty($this->published_date)) { return 'draft'; } elseif ($this->published_date > $today) { return 'pending'; } elseif ($this->published_date <= $today) { return 'published'; } return null; }
php
public function getPublishedStatus() { $today = date('Y-m-d'); if (empty($this->published_date)) { return 'draft'; } elseif ($this->published_date > $today) { return 'pending'; } elseif ($this->published_date <= $today) { return 'published'; } return null; }
[ "public", "function", "getPublishedStatus", "(", ")", "{", "$", "today", "=", "date", "(", "'Y-m-d'", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "published_date", ")", ")", "{", "return", "'draft'", ";", "}", "elseif", "(", "$", "this", "-...
Get Published Status @param void @return string
[ "Get", "Published", "Status" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Models/Entities/Page.php#L36-L49
train
locomotivemtl/charcoal-attachment
src/Charcoal/Attachment/Traits/AttachmentAwareTrait.php
AttachmentAwareTrait.addAttachment
public function addAttachment($attachment, $group = 'contents') { if (!$attachment instanceof AttachableInterface && !$attachment instanceof ModelInterface) { return false; } $join = $this->modelFactory()->create(Join::class); $objId = $this->id(); $objType = $this->objType(); $attId = $attachment->id(); $join->setAttachmentId($attId); $join->setObjectId($objId); $join->setGroup($group); $join->setObjectType($objType); $join->save(); return $this; }
php
public function addAttachment($attachment, $group = 'contents') { if (!$attachment instanceof AttachableInterface && !$attachment instanceof ModelInterface) { return false; } $join = $this->modelFactory()->create(Join::class); $objId = $this->id(); $objType = $this->objType(); $attId = $attachment->id(); $join->setAttachmentId($attId); $join->setObjectId($objId); $join->setGroup($group); $join->setObjectType($objType); $join->save(); return $this; }
[ "public", "function", "addAttachment", "(", "$", "attachment", ",", "$", "group", "=", "'contents'", ")", "{", "if", "(", "!", "$", "attachment", "instanceof", "AttachableInterface", "&&", "!", "$", "attachment", "instanceof", "ModelInterface", ")", "{", "retu...
Attach an node to the current object. @param AttachableInterface|ModelInterface $attachment An attachment or object. @param string $group Attachment group, defaults to contents. @return boolean|self
[ "Attach", "an", "node", "to", "the", "current", "object", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Traits/AttachmentAwareTrait.php#L281-L301
train
locomotivemtl/charcoal-attachment
src/Charcoal/Attachment/Traits/AttachmentAwareTrait.php
AttachmentAwareTrait.removeAttachmentJoins
public function removeAttachmentJoins() { $joinProto = $this->modelFactory()->get(Join::class); $loader = $this->collectionLoader(); $loader ->setModel($joinProto) ->addFilter('object_type', $this->objType()) ->addFilter('object_id', $this->id()); $collection = $loader->load(); foreach ($collection as $obj) { $obj->delete(); } return true; }
php
public function removeAttachmentJoins() { $joinProto = $this->modelFactory()->get(Join::class); $loader = $this->collectionLoader(); $loader ->setModel($joinProto) ->addFilter('object_type', $this->objType()) ->addFilter('object_id', $this->id()); $collection = $loader->load(); foreach ($collection as $obj) { $obj->delete(); } return true; }
[ "public", "function", "removeAttachmentJoins", "(", ")", "{", "$", "joinProto", "=", "$", "this", "->", "modelFactory", "(", ")", "->", "get", "(", "Join", "::", "class", ")", ";", "$", "loader", "=", "$", "this", "->", "collectionLoader", "(", ")", ";...
Remove all joins linked to a specific attachment. @return boolean
[ "Remove", "all", "joins", "linked", "to", "a", "specific", "attachment", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Traits/AttachmentAwareTrait.php#L325-L342
train
froq/froq-pager
src/Pager.php
Pager.generateLinksCenter
public function generateLinksCenter(string $page = null, string $ignoredKeys = null, $linksClassName = null): string { // only one page? $totalPages = $this->totalPages; if ($totalPages == 1) { return $this->template(['<a class="current" href="#">1</a>'], $linksClassName, true); } $links = (array) $this->linksCenter; if ($links != null) { return $this->template($links, $linksClassName, true); } $linksTemplate = $this->linksTemplate; $s = $this->startKey; $query = $this->prepareQuery($ignoredKeys); $start = max(1, ($this->start / $this->stop) + 1); // add first & prev links $prev = $start - 1; if ($prev >= 1) { $links[] = sprintf('<a class="first" rel="first" href="%s%s=1">%s</a>', $query, $s, $linksTemplate['first']); $links[] = sprintf('<a class="prev" rel="prev" href="%s%s=%s">%s</a>', $query, $s, $prev, $linksTemplate['prev']); } $links[] = sprintf('<a class="current" href="#">%s %s</a>', $page ?? $linksTemplate['page'], $start); // add next & last link $next = $start + 1; if ($start < $totalPages) { $links[] = sprintf('<a class="next" rel="next" href="%s%s=%s">%s</a>', $query, $s, $next, $linksTemplate['next']); $links[] = sprintf('<a class="last" rel="last" href="%s%s=%s">%s</a>', $query, $s, $totalPages, $linksTemplate['last']); } // store $this->linksCenter = $links; return $this->template($links, $linksClassName, true); }
php
public function generateLinksCenter(string $page = null, string $ignoredKeys = null, $linksClassName = null): string { // only one page? $totalPages = $this->totalPages; if ($totalPages == 1) { return $this->template(['<a class="current" href="#">1</a>'], $linksClassName, true); } $links = (array) $this->linksCenter; if ($links != null) { return $this->template($links, $linksClassName, true); } $linksTemplate = $this->linksTemplate; $s = $this->startKey; $query = $this->prepareQuery($ignoredKeys); $start = max(1, ($this->start / $this->stop) + 1); // add first & prev links $prev = $start - 1; if ($prev >= 1) { $links[] = sprintf('<a class="first" rel="first" href="%s%s=1">%s</a>', $query, $s, $linksTemplate['first']); $links[] = sprintf('<a class="prev" rel="prev" href="%s%s=%s">%s</a>', $query, $s, $prev, $linksTemplate['prev']); } $links[] = sprintf('<a class="current" href="#">%s %s</a>', $page ?? $linksTemplate['page'], $start); // add next & last link $next = $start + 1; if ($start < $totalPages) { $links[] = sprintf('<a class="next" rel="next" href="%s%s=%s">%s</a>', $query, $s, $next, $linksTemplate['next']); $links[] = sprintf('<a class="last" rel="last" href="%s%s=%s">%s</a>', $query, $s, $totalPages, $linksTemplate['last']); } // store $this->linksCenter = $links; return $this->template($links, $linksClassName, true); }
[ "public", "function", "generateLinksCenter", "(", "string", "$", "page", "=", "null", ",", "string", "$", "ignoredKeys", "=", "null", ",", "$", "linksClassName", "=", "null", ")", ":", "string", "{", "// only one page?", "$", "totalPages", "=", "$", "this", ...
Generate links center. @param string|null $page @param string|null $ignoredKeys @param string $linksClassName @return string
[ "Generate", "links", "center", "." ]
5a19c621d7e5ab8d9deb3ad1d565a178a0c62e30
https://github.com/froq/froq-pager/blob/5a19c621d7e5ab8d9deb3ad1d565a178a0c62e30/src/Pager.php#L418-L462
train
mirko-pagliai/me-cms
src/Controller/Traits/GetStartAndEndDateTrait.php
GetStartAndEndDateTrait.getStartAndEndDate
protected function getStartAndEndDate($date) { $year = $month = $day = null; //Sets the start date if (in_array($date, ['today', 'yesterday'])) { $start = Time::parse($date); } else { list($year, $month, $day) = array_replace([null, null, null], explode('/', $date)); $start = Time::now()->setDate($year, $month ?: 1, $day ?: 1); } $start = $start->setTime(0, 0, 0); $end = Time::parse($start); if (($year && $month && $day) || in_array($date, ['today', 'yesterday'])) { $end = $end->addDay(1); } else { $end = $year && $month ? $end->addMonth(1) : $end->addYear(1); } return [$start, $end]; }
php
protected function getStartAndEndDate($date) { $year = $month = $day = null; //Sets the start date if (in_array($date, ['today', 'yesterday'])) { $start = Time::parse($date); } else { list($year, $month, $day) = array_replace([null, null, null], explode('/', $date)); $start = Time::now()->setDate($year, $month ?: 1, $day ?: 1); } $start = $start->setTime(0, 0, 0); $end = Time::parse($start); if (($year && $month && $day) || in_array($date, ['today', 'yesterday'])) { $end = $end->addDay(1); } else { $end = $year && $month ? $end->addMonth(1) : $end->addYear(1); } return [$start, $end]; }
[ "protected", "function", "getStartAndEndDate", "(", "$", "date", ")", "{", "$", "year", "=", "$", "month", "=", "$", "day", "=", "null", ";", "//Sets the start date", "if", "(", "in_array", "(", "$", "date", ",", "[", "'today'", ",", "'yesterday'", "]", ...
Gets start and end date as `Time` instances starting from a string. These can be used for a `where` condition to search for records based on a date. @param string $date Date as `today`, `yesterday`, `YYYY/MM/dd`, `YYYY/MM` or `YYYY` @return array Array with start and end date as `Time` instances
[ "Gets", "start", "and", "end", "date", "as", "Time", "instances", "starting", "from", "a", "string", ".", "These", "can", "be", "used", "for", "a", "where", "condition", "to", "search", "for", "records", "based", "on", "a", "date", "." ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Traits/GetStartAndEndDateTrait.php#L33-L55
train
gregorybesson/PlaygroundUser
src/Entity/User.php
User.addTeams
public function addTeams(ArrayCollection $teams) { foreach ($teams as $team) { $team->addUser($this); $this->teams->add($team); } }
php
public function addTeams(ArrayCollection $teams) { foreach ($teams as $team) { $team->addUser($this); $this->teams->add($team); } }
[ "public", "function", "addTeams", "(", "ArrayCollection", "$", "teams", ")", "{", "foreach", "(", "$", "teams", "as", "$", "team", ")", "{", "$", "team", "->", "addUser", "(", "$", "this", ")", ";", "$", "this", "->", "teams", "->", "add", "(", "$"...
Add teams to the user @param ArrayCollection $teams @return void
[ "Add", "teams", "to", "the", "user" ]
b07c9969b5da1c173001fbba343f0a006d87eb8e
https://github.com/gregorybesson/PlaygroundUser/blob/b07c9969b5da1c173001fbba343f0a006d87eb8e/src/Entity/User.php#L238-L244
train
gregorybesson/PlaygroundUser
src/Entity/User.php
User.removeTeams
public function removeTeams(ArrayCollection $teams) { foreach ($teams as $team) { $team->removeUser($this); $this->teams->removeElement($team); } }
php
public function removeTeams(ArrayCollection $teams) { foreach ($teams as $team) { $team->removeUser($this); $this->teams->removeElement($team); } }
[ "public", "function", "removeTeams", "(", "ArrayCollection", "$", "teams", ")", "{", "foreach", "(", "$", "teams", "as", "$", "team", ")", "{", "$", "team", "->", "removeUser", "(", "$", "this", ")", ";", "$", "this", "->", "teams", "->", "removeElemen...
Remove teams from the app. @param ArrayCollection $teams @return void
[ "Remove", "teams", "from", "the", "app", "." ]
b07c9969b5da1c173001fbba343f0a006d87eb8e
https://github.com/gregorybesson/PlaygroundUser/blob/b07c9969b5da1c173001fbba343f0a006d87eb8e/src/Entity/User.php#L253-L259
train
au-research/ANDS-DOI-Service
src/Transformer/XMLTransformer.php
XMLTransformer.transform
public static function transform($xslFileName, DOMDocument $xml) { $xsl = new DOMDocument; $xsl->load(__DIR__.'/../../xslt/'.$xslFileName.'.xsl'); $proc = new XSLTProcessor; $proc->importStyleSheet($xsl); libxml_use_internal_errors(true); $result = $proc->transformToXML($xml); foreach (libxml_get_errors() as $error) { //throw new \Exception($error->message); } return $result; }
php
public static function transform($xslFileName, DOMDocument $xml) { $xsl = new DOMDocument; $xsl->load(__DIR__.'/../../xslt/'.$xslFileName.'.xsl'); $proc = new XSLTProcessor; $proc->importStyleSheet($xsl); libxml_use_internal_errors(true); $result = $proc->transformToXML($xml); foreach (libxml_get_errors() as $error) { //throw new \Exception($error->message); } return $result; }
[ "public", "static", "function", "transform", "(", "$", "xslFileName", ",", "DOMDocument", "$", "xml", ")", "{", "$", "xsl", "=", "new", "DOMDocument", ";", "$", "xsl", "->", "load", "(", "__DIR__", ".", "'/../../xslt/'", ".", "$", "xslFileName", ".", "'....
Common transform functionality @param $xslFileName @param DOMDocument $xml @return string @throws \Exception
[ "Common", "transform", "functionality" ]
c8e2cc98eca23a0c550af9a45b5c5dee230da1c9
https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/Transformer/XMLTransformer.php#L34-L51
train
mirko-pagliai/me-cms
src/Controller/Admin/PostsCategoriesController.php
PostsCategoriesController.delete
public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $category = $this->PostsCategories->get($id); //Before deleting, it checks if the category has some posts if (!$category->post_count) { $this->PostsCategories->deleteOrFail($category); $this->Flash->success(I18N_OPERATION_OK); } else { $this->Flash->alert(I18N_BEFORE_DELETE); } return $this->redirect(['action' => 'index']); }
php
public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $category = $this->PostsCategories->get($id); //Before deleting, it checks if the category has some posts if (!$category->post_count) { $this->PostsCategories->deleteOrFail($category); $this->Flash->success(I18N_OPERATION_OK); } else { $this->Flash->alert(I18N_BEFORE_DELETE); } return $this->redirect(['action' => 'index']); }
[ "public", "function", "delete", "(", "$", "id", "=", "null", ")", "{", "$", "this", "->", "request", "->", "allowMethod", "(", "[", "'post'", ",", "'delete'", "]", ")", ";", "$", "category", "=", "$", "this", "->", "PostsCategories", "->", "get", "("...
Deletes posts category @param string $id Posts category ID @return \Cake\Network\Response|null
[ "Deletes", "posts", "category" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/PostsCategoriesController.php#L130-L145
train
vanilla/garden-db
src/TableQuery.php
TableQuery.setOption
protected function setOption($name, $value, $reset = false) { $changed = !isset($this->options[$name]) || $this->options[$name] !== $value; if ($changed && $reset) { $this->data = null; } $this->options[$name] = $value; return $this; }
php
protected function setOption($name, $value, $reset = false) { $changed = !isset($this->options[$name]) || $this->options[$name] !== $value; if ($changed && $reset) { $this->data = null; } $this->options[$name] = $value; return $this; }
[ "protected", "function", "setOption", "(", "$", "name", ",", "$", "value", ",", "$", "reset", "=", "false", ")", "{", "$", "changed", "=", "!", "isset", "(", "$", "this", "->", "options", "[", "$", "name", "]", ")", "||", "$", "this", "->", "opti...
Set a query option. @param string $name The name of the option to set. @param mixed $value The new value of the option. @param bool $reset Pass **true** and the data will be queried again if the option value has changed. @return $this
[ "Set", "a", "query", "option", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/TableQuery.php#L168-L177
train
TuumPHP/Respond
src/Service/SessionStorage.php
SessionStorage.forge
public static function forge($name, $cookie = null) { $factory = new SessionFactory(); $cookie = $cookie ?: $_COOKIE; $session = $factory->newInstance($cookie); $self = new self($session); $self->start(); return $self->withStorage($name); }
php
public static function forge($name, $cookie = null) { $factory = new SessionFactory(); $cookie = $cookie ?: $_COOKIE; $session = $factory->newInstance($cookie); $self = new self($session); $self->start(); return $self->withStorage($name); }
[ "public", "static", "function", "forge", "(", "$", "name", ",", "$", "cookie", "=", "null", ")", "{", "$", "factory", "=", "new", "SessionFactory", "(", ")", ";", "$", "cookie", "=", "$", "cookie", "?", ":", "$", "_COOKIE", ";", "$", "session", "="...
construct a SessionStorage using Aura.Session as a default implementation. @param string $name @param null|array $cookie @return SessionStorage
[ "construct", "a", "SessionStorage", "using", "Aura", ".", "Session", "as", "a", "default", "implementation", "." ]
5861ec0bffc97c500d88bf307a53277f1c2fe12f
https://github.com/TuumPHP/Respond/blob/5861ec0bffc97c500d88bf307a53277f1c2fe12f/src/Service/SessionStorage.php#L50-L59
train
TuumPHP/Respond
src/Service/SessionStorage.php
SessionStorage.withStorage
public function withStorage($name) { $self = clone($this); $self->segment = $this->session->getSegment($name); return $self; }
php
public function withStorage($name) { $self = clone($this); $self->segment = $this->session->getSegment($name); return $self; }
[ "public", "function", "withStorage", "(", "$", "name", ")", "{", "$", "self", "=", "clone", "(", "$", "this", ")", ";", "$", "self", "->", "segment", "=", "$", "this", "->", "session", "->", "getSegment", "(", "$", "name", ")", ";", "return", "$", ...
create a new segment @param string $name @return SessionStorage
[ "create", "a", "new", "segment" ]
5861ec0bffc97c500d88bf307a53277f1c2fe12f
https://github.com/TuumPHP/Respond/blob/5861ec0bffc97c500d88bf307a53277f1c2fe12f/src/Service/SessionStorage.php#L109-L115
train
nails/module-auth
auth/controllers/Login.php
Login.index
public function index() { // If you're logged in you shouldn't be accessing this method if (isLoggedIn()) { redirect($this->data['return_to']); } // -------------------------------------------------------------------------- // If there's POST data attempt to log user in $oInput = Factory::service('Input'); if ($oInput->post()) { // Validate input $oFormValidation = Factory::service('FormValidation'); // The rules vary depending on what login methods are enabled. switch (APP_NATIVE_LOGIN_USING) { case 'EMAIL': $oFormValidation->set_rules('identifier', 'Email', 'required|trim|valid_email'); break; case 'USERNAME': $oFormValidation->set_rules('identifier', 'Username', 'required|trim'); break; default: $oFormValidation->set_rules('identifier', 'Username or Email', 'trim'); break; } // Password is always required, obviously. $oFormValidation->set_rules('password', 'Password', 'required'); $oFormValidation->set_message('required', lang('fv_required')); $oFormValidation->set_message('valid_email', lang('fv_valid_email')); if ($oFormValidation->run()) { // Attempt the log in $sIdentifier = $oInput->post('identifier'); $sPassword = $oInput->post('password'); $bRememberMe = (bool) $oInput->post('remember'); $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oUser = $oAuthModel->login($sIdentifier, $sPassword, $bRememberMe); if ($oUser) { $this->_login($oUser, $bRememberMe); } else { $this->data['error'] = $oAuthModel->lastError(); } } else { $this->data['error'] = lang('fv_there_were_errors'); } } // -------------------------------------------------------------------------- $oSocial = Factory::service('SocialSignOn', 'nails/module-auth'); $this->data['social_signon_enabled'] = $oSocial->isEnabled(); $this->data['social_signon_providers'] = $oSocial->getProviders('ENABLED'); // -------------------------------------------------------------------------- $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/login/form.php'); Factory::service('View') ->load([ 'structure/header/blank', 'auth/login/form', 'structure/footer/blank', ]); }
php
public function index() { // If you're logged in you shouldn't be accessing this method if (isLoggedIn()) { redirect($this->data['return_to']); } // -------------------------------------------------------------------------- // If there's POST data attempt to log user in $oInput = Factory::service('Input'); if ($oInput->post()) { // Validate input $oFormValidation = Factory::service('FormValidation'); // The rules vary depending on what login methods are enabled. switch (APP_NATIVE_LOGIN_USING) { case 'EMAIL': $oFormValidation->set_rules('identifier', 'Email', 'required|trim|valid_email'); break; case 'USERNAME': $oFormValidation->set_rules('identifier', 'Username', 'required|trim'); break; default: $oFormValidation->set_rules('identifier', 'Username or Email', 'trim'); break; } // Password is always required, obviously. $oFormValidation->set_rules('password', 'Password', 'required'); $oFormValidation->set_message('required', lang('fv_required')); $oFormValidation->set_message('valid_email', lang('fv_valid_email')); if ($oFormValidation->run()) { // Attempt the log in $sIdentifier = $oInput->post('identifier'); $sPassword = $oInput->post('password'); $bRememberMe = (bool) $oInput->post('remember'); $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oUser = $oAuthModel->login($sIdentifier, $sPassword, $bRememberMe); if ($oUser) { $this->_login($oUser, $bRememberMe); } else { $this->data['error'] = $oAuthModel->lastError(); } } else { $this->data['error'] = lang('fv_there_were_errors'); } } // -------------------------------------------------------------------------- $oSocial = Factory::service('SocialSignOn', 'nails/module-auth'); $this->data['social_signon_enabled'] = $oSocial->isEnabled(); $this->data['social_signon_providers'] = $oSocial->getProviders('ENABLED'); // -------------------------------------------------------------------------- $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/login/form.php'); Factory::service('View') ->load([ 'structure/header/blank', 'auth/login/form', 'structure/footer/blank', ]); }
[ "public", "function", "index", "(", ")", "{", "// If you're logged in you shouldn't be accessing this method", "if", "(", "isLoggedIn", "(", ")", ")", "{", "redirect", "(", "$", "this", "->", "data", "[", "'return_to'", "]", ")", ";", "}", "// -------------------...
Validate data and log the user in. @return void @throws \Nails\Common\Exception\FactoryException
[ "Validate", "data", "and", "log", "the", "user", "in", "." ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/auth/controllers/Login.php#L77-L151
train
nails/module-auth
auth/controllers/Login.php
Login.with_hashes
public function with_hashes() { $oUri = Factory::service('Uri'); $oConfig = Factory::service('Config'); if (!$oConfig->item('authEnableHashedLogin')) { show404(); } // -------------------------------------------------------------------------- $hash['id'] = $oUri->segment(4); $hash['pw'] = $oUri->segment(5); if (empty($hash['id']) || empty($hash['pw'])) { throw new NailsException(lang('auth_with_hashes_incomplete_creds'), 1); } // -------------------------------------------------------------------------- /** * If the user is already logged in we need to check to see if we check to see if they are * attempting to login as themselves, if so we redirect, otherwise we log them out and try * again using the hashes. */ if (isLoggedIn()) { if (md5(activeUser('id')) == $hash['id']) { // We are attempting to log in as who we're already logged in as, redirect normally if ($this->data['return_to']) { redirect($this->data['return_to']); } else { // Nowhere to go? Send them to their default homepage redirect(activeUser('group_homepage')); } } else { // We are logging in as someone else, log the current user out and try again $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oAuthModel->logout(); redirect(preg_replace('/^\//', '', $_SERVER['REQUEST_URI'])); } } // -------------------------------------------------------------------------- /** * The active user is a guest, we must look up the hashed user and log them in * if all is ok otherwise we report an error. */ $oSession = Factory::service('Session', 'nails/module-auth'); $oUserModel = Factory::model('User', 'nails/module-auth'); $oUser = $oUserModel->getByHashes($hash['id'], $hash['pw']); // -------------------------------------------------------------------------- if ($oUser) { // User was verified, log the user in $oUserModel->setLoginData($oUser->id); // -------------------------------------------------------------------------- // Say hello if ($oUser->last_login) { $lastLogin = $oConfig->item('authShowNicetimeOnLogin') ? niceTime(strtotime($oUser->last_login)) : toUserDatetime($oUser->last_login); if ($oConfig->item('authShowLastIpOnLogin')) { $sStatus = 'positive'; $sMessage = lang('auth_login_ok_welcome_with_ip', [ $oUser->first_name, $lastLogin, $oUser->last_ip, ]); } else { $sStatus = 'positive'; $sMessage = lang('auth_login_ok_welcome', [$oUser->first_name, $oUser->last_login]); } } else { $sStatus = 'positive'; $sMessage = lang('auth_login_ok_welcome_notime', [$oUser->first_name]); } $oSession->setFlashData($sStatus, $sMessage); // -------------------------------------------------------------------------- // Update their last login $oUserModel->updateLastLogin($oUser->id); // -------------------------------------------------------------------------- // Redirect user if ($this->data['return_to'] != site_url()) { // We have somewhere we want to go redirect($this->data['return_to']); } else { // Nowhere to go? Send them to their default homepage redirect($oUser->group_homepage); } } else { // Bad lookup, invalid hash. $oSession->setFlashData('error', lang('auth_with_hashes_autologin_fail')); redirect($this->data['return_to']); } }
php
public function with_hashes() { $oUri = Factory::service('Uri'); $oConfig = Factory::service('Config'); if (!$oConfig->item('authEnableHashedLogin')) { show404(); } // -------------------------------------------------------------------------- $hash['id'] = $oUri->segment(4); $hash['pw'] = $oUri->segment(5); if (empty($hash['id']) || empty($hash['pw'])) { throw new NailsException(lang('auth_with_hashes_incomplete_creds'), 1); } // -------------------------------------------------------------------------- /** * If the user is already logged in we need to check to see if we check to see if they are * attempting to login as themselves, if so we redirect, otherwise we log them out and try * again using the hashes. */ if (isLoggedIn()) { if (md5(activeUser('id')) == $hash['id']) { // We are attempting to log in as who we're already logged in as, redirect normally if ($this->data['return_to']) { redirect($this->data['return_to']); } else { // Nowhere to go? Send them to their default homepage redirect(activeUser('group_homepage')); } } else { // We are logging in as someone else, log the current user out and try again $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oAuthModel->logout(); redirect(preg_replace('/^\//', '', $_SERVER['REQUEST_URI'])); } } // -------------------------------------------------------------------------- /** * The active user is a guest, we must look up the hashed user and log them in * if all is ok otherwise we report an error. */ $oSession = Factory::service('Session', 'nails/module-auth'); $oUserModel = Factory::model('User', 'nails/module-auth'); $oUser = $oUserModel->getByHashes($hash['id'], $hash['pw']); // -------------------------------------------------------------------------- if ($oUser) { // User was verified, log the user in $oUserModel->setLoginData($oUser->id); // -------------------------------------------------------------------------- // Say hello if ($oUser->last_login) { $lastLogin = $oConfig->item('authShowNicetimeOnLogin') ? niceTime(strtotime($oUser->last_login)) : toUserDatetime($oUser->last_login); if ($oConfig->item('authShowLastIpOnLogin')) { $sStatus = 'positive'; $sMessage = lang('auth_login_ok_welcome_with_ip', [ $oUser->first_name, $lastLogin, $oUser->last_ip, ]); } else { $sStatus = 'positive'; $sMessage = lang('auth_login_ok_welcome', [$oUser->first_name, $oUser->last_login]); } } else { $sStatus = 'positive'; $sMessage = lang('auth_login_ok_welcome_notime', [$oUser->first_name]); } $oSession->setFlashData($sStatus, $sMessage); // -------------------------------------------------------------------------- // Update their last login $oUserModel->updateLastLogin($oUser->id); // -------------------------------------------------------------------------- // Redirect user if ($this->data['return_to'] != site_url()) { // We have somewhere we want to go redirect($this->data['return_to']); } else { // Nowhere to go? Send them to their default homepage redirect($oUser->group_homepage); } } else { // Bad lookup, invalid hash. $oSession->setFlashData('error', lang('auth_with_hashes_autologin_fail')); redirect($this->data['return_to']); } }
[ "public", "function", "with_hashes", "(", ")", "{", "$", "oUri", "=", "Factory", "::", "service", "(", "'Uri'", ")", ";", "$", "oConfig", "=", "Factory", "::", "service", "(", "'Config'", ")", ";", "if", "(", "!", "$", "oConfig", "->", "item", "(", ...
Log a user in using hashes of their user ID and password; easy way of automatically logging a user in from the likes of an email. @throws NailsException @return void
[ "Log", "a", "user", "in", "using", "hashes", "of", "their", "user", "ID", "and", "password", ";", "easy", "way", "of", "automatically", "logging", "a", "user", "in", "from", "the", "likes", "of", "an", "email", "." ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/auth/controllers/Login.php#L324-L444
train
nails/module-auth
auth/controllers/Login.php
Login.requestData
protected function requestData(&$aRequiredData, $provider) { $oInput = Factory::service('Input'); if ($oInput->post()) { $oFormValidation = Factory::service('FormValidation'); if (isset($aRequiredData['email'])) { $oFormValidation->set_rules('email', 'email', 'trim|required|valid_email|is_unique[' . NAILS_DB_PREFIX . 'user_email.email]'); } if (isset($aRequiredData['username'])) { $oFormValidation->set_rules('username', 'username', 'trim|required|is_unique[' . NAILS_DB_PREFIX . 'user.username]'); } if (empty($aRequiredData['first_name'])) { $oFormValidation->set_rules('first_name', '', 'trim|required'); } if (empty($aRequiredData['last_name'])) { $oFormValidation->set_rules('last_name', '', 'trim|required'); } $oFormValidation->set_message('required', lang('fv_required')); $oFormValidation->set_message('valid_email', lang('fv_valid_email')); if (APP_NATIVE_LOGIN_USING == 'EMAIL') { $oFormValidation->set_message( 'is_unique', lang('fv_email_already_registered', site_url('auth/password/forgotten')) ); } elseif (APP_NATIVE_LOGIN_USING == 'USERNAME') { $oFormValidation->set_message( 'is_unique', lang('fv_username_already_registered', site_url('auth/password/forgotten')) ); } else { $oFormValidation->set_message( 'is_unique', lang('fv_identity_already_registered', site_url('auth/password/forgotten')) ); } if ($oFormValidation->run()) { // Valid!Ensure required data is set correctly then allow system to move on. if (isset($aRequiredData['email'])) { $aRequiredData['email'] = $oInput->post('email'); } if (isset($aRequiredData['username'])) { $aRequiredData['username'] = $oInput->post('username'); } if (empty($aRequiredData['first_name'])) { $aRequiredData['first_name'] = $oInput->post('first_name'); } if (empty($aRequiredData['last_name'])) { $aRequiredData['last_name'] = $oInput->post('last_name'); } } else { $this->data['error'] = lang('fv_there_were_errors'); $this->requestDataForm($aRequiredData, $provider); } } else { $this->requestDataForm($aRequiredData, $provider); } }
php
protected function requestData(&$aRequiredData, $provider) { $oInput = Factory::service('Input'); if ($oInput->post()) { $oFormValidation = Factory::service('FormValidation'); if (isset($aRequiredData['email'])) { $oFormValidation->set_rules('email', 'email', 'trim|required|valid_email|is_unique[' . NAILS_DB_PREFIX . 'user_email.email]'); } if (isset($aRequiredData['username'])) { $oFormValidation->set_rules('username', 'username', 'trim|required|is_unique[' . NAILS_DB_PREFIX . 'user.username]'); } if (empty($aRequiredData['first_name'])) { $oFormValidation->set_rules('first_name', '', 'trim|required'); } if (empty($aRequiredData['last_name'])) { $oFormValidation->set_rules('last_name', '', 'trim|required'); } $oFormValidation->set_message('required', lang('fv_required')); $oFormValidation->set_message('valid_email', lang('fv_valid_email')); if (APP_NATIVE_LOGIN_USING == 'EMAIL') { $oFormValidation->set_message( 'is_unique', lang('fv_email_already_registered', site_url('auth/password/forgotten')) ); } elseif (APP_NATIVE_LOGIN_USING == 'USERNAME') { $oFormValidation->set_message( 'is_unique', lang('fv_username_already_registered', site_url('auth/password/forgotten')) ); } else { $oFormValidation->set_message( 'is_unique', lang('fv_identity_already_registered', site_url('auth/password/forgotten')) ); } if ($oFormValidation->run()) { // Valid!Ensure required data is set correctly then allow system to move on. if (isset($aRequiredData['email'])) { $aRequiredData['email'] = $oInput->post('email'); } if (isset($aRequiredData['username'])) { $aRequiredData['username'] = $oInput->post('username'); } if (empty($aRequiredData['first_name'])) { $aRequiredData['first_name'] = $oInput->post('first_name'); } if (empty($aRequiredData['last_name'])) { $aRequiredData['last_name'] = $oInput->post('last_name'); } } else { $this->data['error'] = lang('fv_there_were_errors'); $this->requestDataForm($aRequiredData, $provider); } } else { $this->requestDataForm($aRequiredData, $provider); } }
[ "protected", "function", "requestData", "(", "&", "$", "aRequiredData", ",", "$", "provider", ")", "{", "$", "oInput", "=", "Factory", "::", "service", "(", "'Input'", ")", ";", "if", "(", "$", "oInput", "->", "post", "(", ")", ")", "{", "$", "oFormV...
Handles requesting of additional data from the user @param array &$aRequiredData An array of fields to request @param string $provider The provider to use @throws \Nails\Common\Exception\FactoryException
[ "Handles", "requesting", "of", "additional", "data", "from", "the", "user" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/auth/controllers/Login.php#L883-L953
train
nails/module-auth
auth/controllers/Login.php
Login.requestDataForm
protected function requestDataForm(&$aRequiredData, $provider) { $oUri = Factory::service('Uri'); $this->data['required_data'] = $aRequiredData; $this->data['form_url'] = 'auth/login/' . $provider; if ($oUri->segment(4) == 'register') { $this->data['form_url'] .= '/register'; } if ($this->data['return_to']) { $this->data['form_url'] .= '?return_to=' . urlencode($this->data['return_to']); } Factory::service('View') ->load([ 'structure/header/blank', 'auth/register/social_request_data', 'structure/footer/blank', ]); $oOutput = Factory::service('Output'); echo $oOutput->get_output(); exit(); }
php
protected function requestDataForm(&$aRequiredData, $provider) { $oUri = Factory::service('Uri'); $this->data['required_data'] = $aRequiredData; $this->data['form_url'] = 'auth/login/' . $provider; if ($oUri->segment(4) == 'register') { $this->data['form_url'] .= '/register'; } if ($this->data['return_to']) { $this->data['form_url'] .= '?return_to=' . urlencode($this->data['return_to']); } Factory::service('View') ->load([ 'structure/header/blank', 'auth/register/social_request_data', 'structure/footer/blank', ]); $oOutput = Factory::service('Output'); echo $oOutput->get_output(); exit(); }
[ "protected", "function", "requestDataForm", "(", "&", "$", "aRequiredData", ",", "$", "provider", ")", "{", "$", "oUri", "=", "Factory", "::", "service", "(", "'Uri'", ")", ";", "$", "this", "->", "data", "[", "'required_data'", "]", "=", "$", "aRequired...
Renders the "request data" form @param array &$aRequiredData An array of fields to request @param string $provider The provider being used @throws \Nails\Common\Exception\FactoryException
[ "Renders", "the", "request", "data", "form" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/auth/controllers/Login.php#L965-L989
train
nails/module-auth
auth/controllers/Login.php
Login._remap
public function _remap() { $oUri = Factory::service('Uri'); $method = $oUri->segment(3) ? $oUri->segment(3) : 'index'; if (method_exists($this, $method) && substr($method, 0, 1) != '_') { $this->{$method}(); } else { // Assume the 3rd segment is a login provider supported by Hybrid Auth $oSocial = Factory::service('SocialSignOn', 'nails/module-auth'); if ($oSocial->isValidProvider($method)) { $this->socialSignon($method); } else { show404(); } } }
php
public function _remap() { $oUri = Factory::service('Uri'); $method = $oUri->segment(3) ? $oUri->segment(3) : 'index'; if (method_exists($this, $method) && substr($method, 0, 1) != '_') { $this->{$method}(); } else { // Assume the 3rd segment is a login provider supported by Hybrid Auth $oSocial = Factory::service('SocialSignOn', 'nails/module-auth'); if ($oSocial->isValidProvider($method)) { $this->socialSignon($method); } else { show404(); } } }
[ "public", "function", "_remap", "(", ")", "{", "$", "oUri", "=", "Factory", "::", "service", "(", "'Uri'", ")", ";", "$", "method", "=", "$", "oUri", "->", "segment", "(", "3", ")", "?", "$", "oUri", "->", "segment", "(", "3", ")", ":", "'index'"...
Route requests appropriately @throws \Nails\Common\Exception\FactoryException
[ "Route", "requests", "appropriately" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/auth/controllers/Login.php#L998-L1017
train
PitonCMS/Engine
app/Library/Twig/Front.php
Front.getBlockElementsHtml
public function getBlockElementsHtml($block) { if (empty($block)) { return ''; } $blockHtml = ''; foreach ($block as $element) { $blockHtml .= $this->getElementHtml($element) . PHP_EOL; } return $blockHtml; }
php
public function getBlockElementsHtml($block) { if (empty($block)) { return ''; } $blockHtml = ''; foreach ($block as $element) { $blockHtml .= $this->getElementHtml($element) . PHP_EOL; } return $blockHtml; }
[ "public", "function", "getBlockElementsHtml", "(", "$", "block", ")", "{", "if", "(", "empty", "(", "$", "block", ")", ")", "{", "return", "''", ";", "}", "$", "blockHtml", "=", "''", ";", "foreach", "(", "$", "block", "as", "$", "element", ")", "{...
Get All Block Elements HTML Gets all all Element's HTML within a Block, rendered with data @param array $block Array of Elements within a Block @return string HTML
[ "Get", "All", "Block", "Elements", "HTML" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Twig/Front.php#L62-L74
train
PitonCMS/Engine
app/Library/Twig/Front.php
Front.getElementHtml
public function getElementHtml($element) { // Ensure we have an element type if (!isset($element->template) && empty($element->template)) { throw new Exception("Missing page element template"); } return $this->container->view->fetch("elements/{$element->template}", ['element' => $element]); }
php
public function getElementHtml($element) { // Ensure we have an element type if (!isset($element->template) && empty($element->template)) { throw new Exception("Missing page element template"); } return $this->container->view->fetch("elements/{$element->template}", ['element' => $element]); }
[ "public", "function", "getElementHtml", "(", "$", "element", ")", "{", "// Ensure we have an element type", "if", "(", "!", "isset", "(", "$", "element", "->", "template", ")", "&&", "empty", "(", "$", "element", "->", "template", ")", ")", "{", "throw", "...
Get HTML Element Gets Element HTML fragments rendered with data @param array $element Element values @return string HTML
[ "Get", "HTML", "Element" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Twig/Front.php#L83-L91
train
PitonCMS/Engine
app/Library/Twig/Front.php
Front.getCollectionPages
public function getCollectionPages($collectionId) { $pageMapper = ($this->container->dataMapper)('PageMapper'); // Page Collection $data = $pageMapper->findCollectionPagesById($collectionId); return $data; }
php
public function getCollectionPages($collectionId) { $pageMapper = ($this->container->dataMapper)('PageMapper'); // Page Collection $data = $pageMapper->findCollectionPagesById($collectionId); return $data; }
[ "public", "function", "getCollectionPages", "(", "$", "collectionId", ")", "{", "$", "pageMapper", "=", "(", "$", "this", "->", "container", "->", "dataMapper", ")", "(", "'PageMapper'", ")", ";", "// Page Collection", "$", "data", "=", "$", "pageMapper", "-...
Get Collection Page List Get collection pages by collection ID For use in page element as collection landing page @param int $collectionId Collection ID @return mixed Array | null
[ "Get", "Collection", "Page", "List" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Twig/Front.php#L101-L109
train
PitonCMS/Engine
app/Library/Twig/Front.php
Front.getGallery
public function getGallery(int $galleryId = null) { $mediaCategory = ($this->container->dataMapper)('MediaCategoryMapper'); return $mediaCategory->findMediaByCategoryId($galleryId); }
php
public function getGallery(int $galleryId = null) { $mediaCategory = ($this->container->dataMapper)('MediaCategoryMapper'); return $mediaCategory->findMediaByCategoryId($galleryId); }
[ "public", "function", "getGallery", "(", "int", "$", "galleryId", "=", "null", ")", "{", "$", "mediaCategory", "=", "(", "$", "this", "->", "container", "->", "dataMapper", ")", "(", "'MediaCategoryMapper'", ")", ";", "return", "$", "mediaCategory", "->", ...
Get Gallery by ID @param int $galleryId @return mixed
[ "Get", "Gallery", "by", "ID" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Twig/Front.php#L117-L122
train
froq/froq-http
src/request/Uri.php
Uri.generateSegments
public function generateSegments(string $root = null): void { $path = rawurldecode($this->sourceData['path'] ?? ''); if ($path && $path != '/') { // drop root if exists if ($root && $root != '/') { $root = '/'. trim($root, '/'). '/'; // prevent wrong generate action if (strpos($path, $root) === false) { throw new HttpException("Uri path '{$path}' has no root such '{$root}'"); } $path = substr($path, strlen($root)); // update segments root $this->segmentsRoot = $root; } $segments = array_map('trim', preg_split('~/+~', $path, -1, PREG_SPLIT_NO_EMPTY)); if ($segments != null) { // push index next foreach ($segments as $i => $segment) { $this->segments[$i + 1] = $segment; } } } }
php
public function generateSegments(string $root = null): void { $path = rawurldecode($this->sourceData['path'] ?? ''); if ($path && $path != '/') { // drop root if exists if ($root && $root != '/') { $root = '/'. trim($root, '/'). '/'; // prevent wrong generate action if (strpos($path, $root) === false) { throw new HttpException("Uri path '{$path}' has no root such '{$root}'"); } $path = substr($path, strlen($root)); // update segments root $this->segmentsRoot = $root; } $segments = array_map('trim', preg_split('~/+~', $path, -1, PREG_SPLIT_NO_EMPTY)); if ($segments != null) { // push index next foreach ($segments as $i => $segment) { $this->segments[$i + 1] = $segment; } } } }
[ "public", "function", "generateSegments", "(", "string", "$", "root", "=", "null", ")", ":", "void", "{", "$", "path", "=", "rawurldecode", "(", "$", "this", "->", "sourceData", "[", "'path'", "]", "??", "''", ")", ";", "if", "(", "$", "path", "&&", ...
Generate segments. @param string $root @return void
[ "Generate", "segments", "." ]
067207669b5054b867b7df2b5557acf1d43f572a
https://github.com/froq/froq-http/blob/067207669b5054b867b7df2b5557acf1d43f572a/src/request/Uri.php#L191-L217
train
PitonCMS/Engine
app/Controllers/AdminMessageController.php
AdminMessageController.showMessages
public function showMessages() { $messageMapper = ($this->container->dataMapper)('MessageMapper'); $messages = $messageMapper->findAllInDateOrder(); return $this->render('messages.html', ['messages' => $messages]); }
php
public function showMessages() { $messageMapper = ($this->container->dataMapper)('MessageMapper'); $messages = $messageMapper->findAllInDateOrder(); return $this->render('messages.html', ['messages' => $messages]); }
[ "public", "function", "showMessages", "(", ")", "{", "$", "messageMapper", "=", "(", "$", "this", "->", "container", "->", "dataMapper", ")", "(", "'MessageMapper'", ")", ";", "$", "messages", "=", "$", "messageMapper", "->", "findAllInDateOrder", "(", ")", ...
Show All Messages Displays all messages in descending date order
[ "Show", "All", "Messages" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminMessageController.php#L23-L29
train
PitonCMS/Engine
app/Models/MediaCategoryMapper.php
MediaCategoryMapper.findMediaByCategoryId
public function findMediaByCategoryId(int $catId = null) { if (null === $catId) { return; } $this->sql = <<<SQL select mc.category, m.id, m.file, m.caption from media_category mc join media_category_map mcp on mc.id = mcp.category_id join media m on mcp.media_id = m.id where mc.id = ? SQL; $this->bindValues[] = $catId; return $this->find(); }
php
public function findMediaByCategoryId(int $catId = null) { if (null === $catId) { return; } $this->sql = <<<SQL select mc.category, m.id, m.file, m.caption from media_category mc join media_category_map mcp on mc.id = mcp.category_id join media m on mcp.media_id = m.id where mc.id = ? SQL; $this->bindValues[] = $catId; return $this->find(); }
[ "public", "function", "findMediaByCategoryId", "(", "int", "$", "catId", "=", "null", ")", "{", "if", "(", "null", "===", "$", "catId", ")", "{", "return", ";", "}", "$", "this", "->", "sql", "=", " <<<SQL\nselect\n mc.category,\n m.id,\n m.file,\n m...
Find Media By Category ID Find media by category ID @param int $catId @return mixed
[ "Find", "Media", "By", "Category", "ID" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Models/MediaCategoryMapper.php#L45-L64
train
PitonCMS/Engine
app/Models/MediaCategoryMapper.php
MediaCategoryMapper.saveMediaCategoryAssignments
public function saveMediaCategoryAssignments(int $mediaId, array $categoryIds = null) { // Delete current category assignments for this media ID $this->deleteMediaCategoryAssignments($mediaId); // Insert all assignments, if the category ID's array is not empty if (null !== $categoryIds) { $this->sql = 'insert into media_category_map (media_id, category_id) values '; foreach ($categoryIds as $id) { $this->sql .= '(?, ?),'; $this->bindValues[] = $mediaId; $this->bindValues[] = $id; } $this->sql = rtrim($this->sql, ',') . ';'; $this->execute(); } }
php
public function saveMediaCategoryAssignments(int $mediaId, array $categoryIds = null) { // Delete current category assignments for this media ID $this->deleteMediaCategoryAssignments($mediaId); // Insert all assignments, if the category ID's array is not empty if (null !== $categoryIds) { $this->sql = 'insert into media_category_map (media_id, category_id) values '; foreach ($categoryIds as $id) { $this->sql .= '(?, ?),'; $this->bindValues[] = $mediaId; $this->bindValues[] = $id; } $this->sql = rtrim($this->sql, ',') . ';'; $this->execute(); } }
[ "public", "function", "saveMediaCategoryAssignments", "(", "int", "$", "mediaId", ",", "array", "$", "categoryIds", "=", "null", ")", "{", "// Delete current category assignments for this media ID", "$", "this", "->", "deleteMediaCategoryAssignments", "(", "$", "mediaId",...
Save Media Category Assignments For a media ID, save category array @param int $mediaId @param array $categoryIds @return mixed
[ "Save", "Media", "Category", "Assignments" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Models/MediaCategoryMapper.php#L74-L90
train
PitonCMS/Engine
app/Models/MediaCategoryMapper.php
MediaCategoryMapper.deleteMediaCategoryAssignments
public function deleteMediaCategoryAssignments(int $mediaId) { $this->sql = 'delete from media_category_map where media_id = ?'; $this->bindValues[] = $mediaId; $this->execute(); }
php
public function deleteMediaCategoryAssignments(int $mediaId) { $this->sql = 'delete from media_category_map where media_id = ?'; $this->bindValues[] = $mediaId; $this->execute(); }
[ "public", "function", "deleteMediaCategoryAssignments", "(", "int", "$", "mediaId", ")", "{", "$", "this", "->", "sql", "=", "'delete from media_category_map where media_id = ?'", ";", "$", "this", "->", "bindValues", "[", "]", "=", "$", "mediaId", ";", "$", "th...
Delete Media Category Assignments @param int $mediaId @return mixed
[ "Delete", "Media", "Category", "Assignments" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Models/MediaCategoryMapper.php#L110-L115
train
nails/module-auth
src/Api/Controller/Me.php
Me.anyIndex
public function anyIndex() { return Factory::factory('ApiResponse', 'nails/module-api') ->setData([ 'id' => (int) activeUser('id'), 'first_name' => activeUser('first_name') ?: null, 'last_name' => activeUser('last_name') ?: null, 'email' => activeUser('email') ?: null, 'username' => activeUser('username') ?: null, 'avatar' => cdnAvatar() ?: null, 'gender' => activeUser('gender') ?: null, ]); }
php
public function anyIndex() { return Factory::factory('ApiResponse', 'nails/module-api') ->setData([ 'id' => (int) activeUser('id'), 'first_name' => activeUser('first_name') ?: null, 'last_name' => activeUser('last_name') ?: null, 'email' => activeUser('email') ?: null, 'username' => activeUser('username') ?: null, 'avatar' => cdnAvatar() ?: null, 'gender' => activeUser('gender') ?: null, ]); }
[ "public", "function", "anyIndex", "(", ")", "{", "return", "Factory", "::", "factory", "(", "'ApiResponse'", ",", "'nails/module-api'", ")", "->", "setData", "(", "[", "'id'", "=>", "(", "int", ")", "activeUser", "(", "'id'", ")", ",", "'first_name'", "=>"...
Returns basic details about the currently logged in user @return ApiResponse
[ "Returns", "basic", "details", "about", "the", "currently", "logged", "in", "user" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Api/Controller/Me.php#L31-L43
train
ekowabaka/clearice
src/argparser/HelpMessageGenerator.php
HelpMessageGenerator.wrapHelp
private function wrapHelp($argumentPart, &$help, $minSize = 29) { if (strlen($argumentPart) <= $minSize) { return $argumentPart . array_shift($help); } else { return $argumentPart; } }
php
private function wrapHelp($argumentPart, &$help, $minSize = 29) { if (strlen($argumentPart) <= $minSize) { return $argumentPart . array_shift($help); } else { return $argumentPart; } }
[ "private", "function", "wrapHelp", "(", "$", "argumentPart", ",", "&", "$", "help", ",", "$", "minSize", "=", "29", ")", "{", "if", "(", "strlen", "(", "$", "argumentPart", ")", "<=", "$", "minSize", ")", "{", "return", "$", "argumentPart", ".", "arr...
Wraps the help message arround the argument by producing two different columns. The argument is placed in the first column and the help message is placed in the second column. @param string $argumentPart @param array $help @param integer $minSize @return string
[ "Wraps", "the", "help", "message", "arround", "the", "argument", "by", "producing", "two", "different", "columns", ".", "The", "argument", "is", "placed", "in", "the", "first", "column", "and", "the", "help", "message", "is", "placed", "in", "the", "second",...
8762c8a75e62df5c1a5505f2c78d6809ab5b3658
https://github.com/ekowabaka/clearice/blob/8762c8a75e62df5c1a5505f2c78d6809ab5b3658/src/argparser/HelpMessageGenerator.php#L129-L136
train
mirko-pagliai/me-cms
src/Controller/Component/KcFinderComponent.php
KcFinderComponent.getDefaultConfig
protected function getDefaultConfig() { $defaultConfig = [ 'denyExtensionRename' => true, 'denyUpdateCheck' => true, 'dirnameChangeChars' => [' ' => '_', ':' => '_'], 'disabled' => false, 'filenameChangeChars' => [' ' => '_', ':' => '_'], 'jpegQuality' => 100, 'uploadDir' => UPLOADED, 'uploadURL' => Router::url('/files', true), 'types' => $this->getTypes(), ]; //If the user is not and admin if (!$this->Auth->isGroup(['admin'])) { //Only admins can delete or rename directories $defaultConfig['access']['dirs'] = [ 'create' => true, 'delete' => false, 'rename' => false, ]; //Only admins can delete, move or rename files $defaultConfig['access']['files'] = [ 'upload' => true, 'delete' => false, 'copy' => true, 'move' => false, 'rename' => false, ]; } return $defaultConfig; }
php
protected function getDefaultConfig() { $defaultConfig = [ 'denyExtensionRename' => true, 'denyUpdateCheck' => true, 'dirnameChangeChars' => [' ' => '_', ':' => '_'], 'disabled' => false, 'filenameChangeChars' => [' ' => '_', ':' => '_'], 'jpegQuality' => 100, 'uploadDir' => UPLOADED, 'uploadURL' => Router::url('/files', true), 'types' => $this->getTypes(), ]; //If the user is not and admin if (!$this->Auth->isGroup(['admin'])) { //Only admins can delete or rename directories $defaultConfig['access']['dirs'] = [ 'create' => true, 'delete' => false, 'rename' => false, ]; //Only admins can delete, move or rename files $defaultConfig['access']['files'] = [ 'upload' => true, 'delete' => false, 'copy' => true, 'move' => false, 'rename' => false, ]; } return $defaultConfig; }
[ "protected", "function", "getDefaultConfig", "(", ")", "{", "$", "defaultConfig", "=", "[", "'denyExtensionRename'", "=>", "true", ",", "'denyUpdateCheck'", "=>", "true", ",", "'dirnameChangeChars'", "=>", "[", "' '", "=>", "'_'", ",", "':'", "=>", "'_'", "]",...
Internal method to get the default config @return array @uses getTypes()
[ "Internal", "method", "to", "get", "the", "default", "config" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Component/KcFinderComponent.php#L61-L94
train
mirko-pagliai/me-cms
src/Controller/Component/KcFinderComponent.php
KcFinderComponent.getTypes
public function getTypes() { //Gets the folders list list($folders) = (new Folder(UPLOADED))->read(true, true); //Each folder is a file type supported by KCFinder foreach ($folders as $type) { $types[$type] = ''; } //Adds the "images" type by default $types['images'] = '*img'; return $types; }
php
public function getTypes() { //Gets the folders list list($folders) = (new Folder(UPLOADED))->read(true, true); //Each folder is a file type supported by KCFinder foreach ($folders as $type) { $types[$type] = ''; } //Adds the "images" type by default $types['images'] = '*img'; return $types; }
[ "public", "function", "getTypes", "(", ")", "{", "//Gets the folders list", "list", "(", "$", "folders", ")", "=", "(", "new", "Folder", "(", "UPLOADED", ")", ")", "->", "read", "(", "true", ",", "true", ")", ";", "//Each folder is a file type supported by KCF...
Gets the file types supported by KCFinder @return array
[ "Gets", "the", "file", "types", "supported", "by", "KCFinder" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Component/KcFinderComponent.php#L100-L114
train
mirko-pagliai/me-cms
src/Controller/Component/KcFinderComponent.php
KcFinderComponent.uploadedDirIsWriteable
protected function uploadedDirIsWriteable() { $result = $this->Checkup->Webroot->isWriteable(); return $result && array_key_exists(UPLOADED, $result) ? $result[UPLOADED] : false; }
php
protected function uploadedDirIsWriteable() { $result = $this->Checkup->Webroot->isWriteable(); return $result && array_key_exists(UPLOADED, $result) ? $result[UPLOADED] : false; }
[ "protected", "function", "uploadedDirIsWriteable", "(", ")", "{", "$", "result", "=", "$", "this", "->", "Checkup", "->", "Webroot", "->", "isWriteable", "(", ")", ";", "return", "$", "result", "&&", "array_key_exists", "(", "UPLOADED", ",", "$", "result", ...
Internal method to check if the uploaded directory is writeable @return bool @since 2.22.8 @uses $Checkup
[ "Internal", "method", "to", "check", "if", "the", "uploaded", "directory", "is", "writeable" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Component/KcFinderComponent.php#L133-L138
train
bright-components/services
src/ServiceCaller.php
ServiceCaller.call
public function call($service, ...$params) { if (! $this->hasHandler($service)) { throw ServiceHandlerMethodException::notFound($service); } return $this->container->make($service)->{$this::$handlerMethod}(...$params); }
php
public function call($service, ...$params) { if (! $this->hasHandler($service)) { throw ServiceHandlerMethodException::notFound($service); } return $this->container->make($service)->{$this::$handlerMethod}(...$params); }
[ "public", "function", "call", "(", "$", "service", ",", "...", "$", "params", ")", "{", "if", "(", "!", "$", "this", "->", "hasHandler", "(", "$", "service", ")", ")", "{", "throw", "ServiceHandlerMethodException", "::", "notFound", "(", "$", "service", ...
Call a service through its appropriate handler. @param string $service @param mixed ...$params @return mixed
[ "Call", "a", "service", "through", "its", "appropriate", "handler", "." ]
c8f1c4a578a1fc805fd36cae8d3625fd95c11cdc
https://github.com/bright-components/services/blob/c8f1c4a578a1fc805fd36cae8d3625fd95c11cdc/src/ServiceCaller.php#L42-L49
train
nails/module-auth
admin/controllers/Groups.php
Groups.getPostObject
protected function getPostObject(): array { $oInput = Factory::service('Input'); $oUserGroupModel = Factory::model('UserGroup', 'nails/module-auth'); $oUserPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); return [ 'slug' => $oInput->post('slug'), 'label' => $oInput->post('label'), 'description' => $oInput->post('description'), 'default_homepage' => $oInput->post('default_homepage'), 'registration_redirect' => $oInput->post('registration_redirect'), 'acl' => $oUserGroupModel->processPermissions($oInput->post('acl')), 'password_rules' => $oUserPasswordModel->processRules($oInput->post('pw')), ]; }
php
protected function getPostObject(): array { $oInput = Factory::service('Input'); $oUserGroupModel = Factory::model('UserGroup', 'nails/module-auth'); $oUserPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); return [ 'slug' => $oInput->post('slug'), 'label' => $oInput->post('label'), 'description' => $oInput->post('description'), 'default_homepage' => $oInput->post('default_homepage'), 'registration_redirect' => $oInput->post('registration_redirect'), 'acl' => $oUserGroupModel->processPermissions($oInput->post('acl')), 'password_rules' => $oUserPasswordModel->processRules($oInput->post('pw')), ]; }
[ "protected", "function", "getPostObject", "(", ")", ":", "array", "{", "$", "oInput", "=", "Factory", "::", "service", "(", "'Input'", ")", ";", "$", "oUserGroupModel", "=", "Factory", "::", "model", "(", "'UserGroup'", ",", "'nails/module-auth'", ")", ";", ...
Extract data from post variable @return array
[ "Extract", "data", "from", "post", "variable" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/admin/controllers/Groups.php#L108-L123
train
nails/module-auth
admin/controllers/Groups.php
Groups.set_default
public function set_default(): void { if (!userHasPermission('admin:auth:groups:setDefault')) { show404(); } $oUri = Factory::service('Uri'); $oUserGroupModel = Factory::model('UserGroup', 'nails/module-auth'); $oSession = Factory::service('Session', 'nails/module-auth'); if ($oUserGroupModel->setAsDefault($oUri->segment(5))) { $oSession->setFlashData( 'success', 'Group set as default successfully.' ); } else { $oSession->setFlashData( 'error', 'Failed to set default user group. ' . $oUserGroupModel->lastError() ); } redirect('admin/auth/groups'); }
php
public function set_default(): void { if (!userHasPermission('admin:auth:groups:setDefault')) { show404(); } $oUri = Factory::service('Uri'); $oUserGroupModel = Factory::model('UserGroup', 'nails/module-auth'); $oSession = Factory::service('Session', 'nails/module-auth'); if ($oUserGroupModel->setAsDefault($oUri->segment(5))) { $oSession->setFlashData( 'success', 'Group set as default successfully.' ); } else { $oSession->setFlashData( 'error', 'Failed to set default user group. ' . $oUserGroupModel->lastError() ); } redirect('admin/auth/groups'); }
[ "public", "function", "set_default", "(", ")", ":", "void", "{", "if", "(", "!", "userHasPermission", "(", "'admin:auth:groups:setDefault'", ")", ")", "{", "show404", "(", ")", ";", "}", "$", "oUri", "=", "Factory", "::", "service", "(", "'Uri'", ")", ";...
Set the default user group @return void
[ "Set", "the", "default", "user", "group" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/admin/controllers/Groups.php#L166-L189
train
yawik/settings
src/Form/DisableElementsCapableFormSettingsFieldset.php
DisableElementsCapableFormSettingsFieldset.build
public function build() { if ($this->isBuild) { return; } $settings = $this->getObject(); $form = $this->formManager->get($settings->getForm()); $this->setLabel( $form->getOption('settings_label') ?: sprintf( /*@translate*/ 'Customize enabled elements for %s', get_class($form) ) ); $this->add( array( 'type' => 'Checkbox', 'name' => 'isActive', 'options' => array( 'label' => /*@translate*/ 'Activate', 'long_label' => /*@translate*/ 'Enables the form element customization.', ), 'attributes' => array( 'class' => 'decfs-active-toggle', ), ) ); $element = new DisableElementsCapableFormSettings('disableElements'); $element->setForm($form); $this->add($element); $this->isBuild = true; }
php
public function build() { if ($this->isBuild) { return; } $settings = $this->getObject(); $form = $this->formManager->get($settings->getForm()); $this->setLabel( $form->getOption('settings_label') ?: sprintf( /*@translate*/ 'Customize enabled elements for %s', get_class($form) ) ); $this->add( array( 'type' => 'Checkbox', 'name' => 'isActive', 'options' => array( 'label' => /*@translate*/ 'Activate', 'long_label' => /*@translate*/ 'Enables the form element customization.', ), 'attributes' => array( 'class' => 'decfs-active-toggle', ), ) ); $element = new DisableElementsCapableFormSettings('disableElements'); $element->setForm($form); $this->add($element); $this->isBuild = true; }
[ "public", "function", "build", "(", ")", "{", "if", "(", "$", "this", "->", "isBuild", ")", "{", "return", ";", "}", "$", "settings", "=", "$", "this", "->", "getObject", "(", ")", ";", "$", "form", "=", "$", "this", "->", "formManager", "->", "g...
Builds this fieldset. Adds the disableElements element and populate its values, which is only possible, if the bound object is set.
[ "Builds", "this", "fieldset", "." ]
fc49d14a5eec21fcc074ce29b1428d91191efecf
https://github.com/yawik/settings/blob/fc49d14a5eec21fcc074ce29b1428d91191efecf/src/Form/DisableElementsCapableFormSettingsFieldset.php#L75-L109
train
mirko-pagliai/me-cms
src/Database/Type/JsonEntityType.php
JsonEntityType.toPHP
public function toPHP($value, Driver $driver) { $value = parent::toPHP($value, $driver); return is_array($value) ? array_map(function ($value) { return is_array($value) ? new Entity($value) : $value; }, $value) : $value; }
php
public function toPHP($value, Driver $driver) { $value = parent::toPHP($value, $driver); return is_array($value) ? array_map(function ($value) { return is_array($value) ? new Entity($value) : $value; }, $value) : $value; }
[ "public", "function", "toPHP", "(", "$", "value", ",", "Driver", "$", "driver", ")", "{", "$", "value", "=", "parent", "::", "toPHP", "(", "$", "value", ",", "$", "driver", ")", ";", "return", "is_array", "(", "$", "value", ")", "?", "array_map", "...
Convert string values to PHP arrays. @param mixed $value The value to convert @param \Cake\Database\Driver $driver The driver instance to convert with @return mixed
[ "Convert", "string", "values", "to", "PHP", "arrays", "." ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Database/Type/JsonEntityType.php#L33-L40
train
vanilla/garden-db
src/Utils/FetchModeTrait.php
FetchModeTrait.setFetchMode
public function setFetchMode($mode, ...$args) { if (is_string($mode)) { array_unshift($args, PDO::$mode); $mode = PDO::FETCH_CLASS; } $this->fetchArgs = array_merge([$mode], $args); return $this; }
php
public function setFetchMode($mode, ...$args) { if (is_string($mode)) { array_unshift($args, PDO::$mode); $mode = PDO::FETCH_CLASS; } $this->fetchArgs = array_merge([$mode], $args); return $this; }
[ "public", "function", "setFetchMode", "(", "$", "mode", ",", "...", "$", "args", ")", "{", "if", "(", "is_string", "(", "$", "mode", ")", ")", "{", "array_unshift", "(", "$", "args", ",", "PDO", "::", "$", "mode", ")", ";", "$", "mode", "=", "PDO...
Set the default fetch mode. @param int|string $mode One of the **PDO::FETCH_*** constants or a class name. @param mixed ...$args Additional arguments for {@link \PDOStatement::fetchAll()}. @return $this @see http://php.net/manual/en/pdostatement.fetchall.php
[ "Set", "the", "default", "fetch", "mode", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Utils/FetchModeTrait.php#L44-L52
train
Kuestenschmiede/QueueBundle
Controller/QueueController.php
QueueController.sendResponse
protected function sendResponse($output, $status = 200, $header = array(), $json = true) { $output = date('Y.m.d H:i:s') . " - $output"; $data = json_encode(['output' => $output]); return new JsonResponse($data, $status, $header, $json); }
php
protected function sendResponse($output, $status = 200, $header = array(), $json = true) { $output = date('Y.m.d H:i:s') . " - $output"; $data = json_encode(['output' => $output]); return new JsonResponse($data, $status, $header, $json); }
[ "protected", "function", "sendResponse", "(", "$", "output", ",", "$", "status", "=", "200", ",", "$", "header", "=", "array", "(", ")", ",", "$", "json", "=", "true", ")", "{", "$", "output", "=", "date", "(", "'Y.m.d H:i:s'", ")", ".", "\" - $outpu...
Erstellt das Response. @param $output @param int $status @param array $header @param bool $json @return JsonResponse
[ "Erstellt", "das", "Response", "." ]
6a81c16ed17fed888ab96bcdc971357381477ef6
https://github.com/Kuestenschmiede/QueueBundle/blob/6a81c16ed17fed888ab96bcdc971357381477ef6/Controller/QueueController.php#L68-L73
train
milkyway-multimedia/ss-mwm-assets
code/Extensions/Controller.php
Controller.onBeforeInit
function onBeforeInit() { foreach (Requirements::$disable_cache_busted_file_extensions_for as $class) { if (is_a($this->owner, $class)) { Requirements::$use_cache_busted_file_extensions = false; } } }
php
function onBeforeInit() { foreach (Requirements::$disable_cache_busted_file_extensions_for as $class) { if (is_a($this->owner, $class)) { Requirements::$use_cache_busted_file_extensions = false; } } }
[ "function", "onBeforeInit", "(", ")", "{", "foreach", "(", "Requirements", "::", "$", "disable_cache_busted_file_extensions_for", "as", "$", "class", ")", "{", "if", "(", "is_a", "(", "$", "this", "->", "owner", ",", "$", "class", ")", ")", "{", "Requireme...
Disable cache busted file extensions for some classes (usually @LeftAndMain)
[ "Disable", "cache", "busted", "file", "extensions", "for", "some", "classes", "(", "usually" ]
330753f5050fec0c0d73bb4e0e99658a1eb311e1
https://github.com/milkyway-multimedia/ss-mwm-assets/blob/330753f5050fec0c0d73bb4e0e99658a1eb311e1/code/Extensions/Controller.php#L19-L26
train
mirko-pagliai/me-cms
src/Command/Install/CopyConfigCommand.php
CopyConfigCommand.execute
public function execute(Arguments $args, ConsoleIo $io) { foreach ($this->config as $file) { list($plugin, $file) = pluginSplit($file); $this->copyFile( $io, Plugin::path($plugin, 'config' . DS . $file . '.php'), Folder::slashTerm(CONFIG) . $file . '.php' ); } return null; }
php
public function execute(Arguments $args, ConsoleIo $io) { foreach ($this->config as $file) { list($plugin, $file) = pluginSplit($file); $this->copyFile( $io, Plugin::path($plugin, 'config' . DS . $file . '.php'), Folder::slashTerm(CONFIG) . $file . '.php' ); } return null; }
[ "public", "function", "execute", "(", "Arguments", "$", "args", ",", "ConsoleIo", "$", "io", ")", "{", "foreach", "(", "$", "this", "->", "config", "as", "$", "file", ")", "{", "list", "(", "$", "plugin", ",", "$", "file", ")", "=", "pluginSplit", ...
Copies the configuration files @param Arguments $args The command arguments @param ConsoleIo $io The console io @return null|int The exit code or null for success @uses $config
[ "Copies", "the", "configuration", "files" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Command/Install/CopyConfigCommand.php#L56-L68
train
DarvinStudio/DarvinConfigBundle
Configuration/ConfigurationPool.php
ConfigurationPool.saveAll
public function saveAll() { $this->init(); $parameters = []; foreach ($this->configurations as $configuration) { $parameters = array_merge($parameters, $this->getConfigurationParameters($configuration)); } $this->parameterRepository->save($parameters); }
php
public function saveAll() { $this->init(); $parameters = []; foreach ($this->configurations as $configuration) { $parameters = array_merge($parameters, $this->getConfigurationParameters($configuration)); } $this->parameterRepository->save($parameters); }
[ "public", "function", "saveAll", "(", ")", "{", "$", "this", "->", "init", "(", ")", ";", "$", "parameters", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "configurations", "as", "$", "configuration", ")", "{", "$", "parameters", "=", "array...
Saves configurations.
[ "Saves", "configurations", "." ]
1070c186eeb2a553bcd420cb68378e0246fcc7ac
https://github.com/DarvinStudio/DarvinConfigBundle/blob/1070c186eeb2a553bcd420cb68378e0246fcc7ac/Configuration/ConfigurationPool.php#L106-L117
train
DarvinStudio/DarvinConfigBundle
Configuration/ConfigurationPool.php
ConfigurationPool.init
public function init() { if ($this->initialized) { return; } $parameters = []; foreach ($this->parameterRepository->getAllParameters() as $parameter) { $configurationName = $parameter->getConfigurationName(); if (!isset($parameters[$configurationName])) { $parameters[$configurationName] = []; } $parameters[$configurationName][$parameter->getName()] = $parameter; } $this->persistedParameters = $parameters; foreach ($this->configurations as $configuration) { $configurationName = $configuration->getName(); $this->initConfiguration( $configuration, isset($parameters[$configurationName]) ? $parameters[$configurationName] : [] ); } $this->initialized = true; }
php
public function init() { if ($this->initialized) { return; } $parameters = []; foreach ($this->parameterRepository->getAllParameters() as $parameter) { $configurationName = $parameter->getConfigurationName(); if (!isset($parameters[$configurationName])) { $parameters[$configurationName] = []; } $parameters[$configurationName][$parameter->getName()] = $parameter; } $this->persistedParameters = $parameters; foreach ($this->configurations as $configuration) { $configurationName = $configuration->getName(); $this->initConfiguration( $configuration, isset($parameters[$configurationName]) ? $parameters[$configurationName] : [] ); } $this->initialized = true; }
[ "public", "function", "init", "(", ")", "{", "if", "(", "$", "this", "->", "initialized", ")", "{", "return", ";", "}", "$", "parameters", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "parameterRepository", "->", "getAllParameters", "(", ")",...
Initializes configurations.
[ "Initializes", "configurations", "." ]
1070c186eeb2a553bcd420cb68378e0246fcc7ac
https://github.com/DarvinStudio/DarvinConfigBundle/blob/1070c186eeb2a553bcd420cb68378e0246fcc7ac/Configuration/ConfigurationPool.php#L132-L161
train
nails/module-auth
src/Service/Session.php
Session.setup
protected function setup($bForceSetup = false) { if (!empty($this->oSession)) { return; } $oInput = Factory::service('Input'); // class_exists check in case the class is called before CI has finished instanciating if (!$oInput::isCli() && class_exists('CI_Controller')) { /** * Look for the session cookie, if it exists, then a session exists * and the whole service should be loaded up. */ $oConfig = Factory::service('Config'); $sCookieName = $oConfig->item('sess_cookie_name'); if ($bForceSetup || $oInput::cookie($sCookieName)) { // @todo (Pablo - 2018-03-19) - Remove dependency on CI Sessions $oCi = get_instance(); $oCi->load->library('session'); if (empty($oCi->session)) { throw new NailsException('Failed to load CodeIgniter session library.'); } $this->oSession = $oCi->session; } } }
php
protected function setup($bForceSetup = false) { if (!empty($this->oSession)) { return; } $oInput = Factory::service('Input'); // class_exists check in case the class is called before CI has finished instanciating if (!$oInput::isCli() && class_exists('CI_Controller')) { /** * Look for the session cookie, if it exists, then a session exists * and the whole service should be loaded up. */ $oConfig = Factory::service('Config'); $sCookieName = $oConfig->item('sess_cookie_name'); if ($bForceSetup || $oInput::cookie($sCookieName)) { // @todo (Pablo - 2018-03-19) - Remove dependency on CI Sessions $oCi = get_instance(); $oCi->load->library('session'); if (empty($oCi->session)) { throw new NailsException('Failed to load CodeIgniter session library.'); } $this->oSession = $oCi->session; } } }
[ "protected", "function", "setup", "(", "$", "bForceSetup", "=", "false", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "oSession", ")", ")", "{", "return", ";", "}", "$", "oInput", "=", "Factory", "::", "service", "(", "'Input'", ")", ...
Attempts to restore or set up a session @param bool $bForceSetup Whether to force session set up
[ "Attempts", "to", "restore", "or", "set", "up", "a", "session" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Service/Session.php#L37-L63
train
nails/module-auth
src/Service/Session.php
Session.setFlashData
public function setFlashData($mKey, $mValue = null) { $this->setup(true); if (empty($this->oSession)) { return $this; } $this->oSession->set_flashdata($mKey, $mValue); return $this; }
php
public function setFlashData($mKey, $mValue = null) { $this->setup(true); if (empty($this->oSession)) { return $this; } $this->oSession->set_flashdata($mKey, $mValue); return $this; }
[ "public", "function", "setFlashData", "(", "$", "mKey", ",", "$", "mValue", "=", "null", ")", "{", "$", "this", "->", "setup", "(", "true", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "oSession", ")", ")", "{", "return", "$", "this", ";...
Sets session flashdata @param mixed $mKey The key to set, or an associative array of key=>value pairs @param mixed $mValue The value to store @return $this
[ "Sets", "session", "flashdata" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Service/Session.php#L75-L83
train
nails/module-auth
src/Service/Session.php
Session.getFlashData
public function getFlashData($sKey = null) { $this->setup(); if (empty($this->oSession)) { return null; } return $this->oSession->flashdata($sKey); }
php
public function getFlashData($sKey = null) { $this->setup(); if (empty($this->oSession)) { return null; } return $this->oSession->flashdata($sKey); }
[ "public", "function", "getFlashData", "(", "$", "sKey", "=", "null", ")", "{", "$", "this", "->", "setup", "(", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "oSession", ")", ")", "{", "return", "null", ";", "}", "return", "$", "this", "-...
Retrieves flash data from the session @param string $sKey The key to retrieve @return mixed
[ "Retrieves", "flash", "data", "from", "the", "session" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Service/Session.php#L94-L101
train
nails/module-auth
src/Service/Session.php
Session.setUserData
public function setUserData($mKey, $mValue = null) { $this->setup(true); if (empty($this->oSession)) { return $this; } $this->oSession->set_userdata($mKey, $mValue); return $this; }
php
public function setUserData($mKey, $mValue = null) { $this->setup(true); if (empty($this->oSession)) { return $this; } $this->oSession->set_userdata($mKey, $mValue); return $this; }
[ "public", "function", "setUserData", "(", "$", "mKey", ",", "$", "mValue", "=", "null", ")", "{", "$", "this", "->", "setup", "(", "true", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "oSession", ")", ")", "{", "return", "$", "this", ";"...
Writes data to the user's session @param mixed $mKey The key to set, or an associative array of key=>value pairs @param mixed $mValue The value to store @return $this
[ "Writes", "data", "to", "the", "user", "s", "session" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Service/Session.php#L144-L153
train
nails/module-auth
src/Service/Session.php
Session.getUserData
public function getUserData($sKey = null) { $this->setup(); if (empty($this->oSession)) { return null; } return $this->oSession->userdata($sKey); }
php
public function getUserData($sKey = null) { $this->setup(); if (empty($this->oSession)) { return null; } return $this->oSession->userdata($sKey); }
[ "public", "function", "getUserData", "(", "$", "sKey", "=", "null", ")", "{", "$", "this", "->", "setup", "(", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "oSession", ")", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->...
Retrieves data from the session @param string $sKey The key to retrieve @return mixed
[ "Retrieves", "data", "from", "the", "session" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Service/Session.php#L164-L171
train
nails/module-auth
src/Service/Session.php
Session.unsetUserData
public function unsetUserData($mKey) { if (empty($this->oSession)) { return $this; } $this->oSession->unset_userdata($mKey); return $this; }
php
public function unsetUserData($mKey) { if (empty($this->oSession)) { return $this; } $this->oSession->unset_userdata($mKey); return $this; }
[ "public", "function", "unsetUserData", "(", "$", "mKey", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "oSession", ")", ")", "{", "return", "$", "this", ";", "}", "$", "this", "->", "oSession", "->", "unset_userdata", "(", "$", "mKey", ")", ...
Removes data from the session @param mixed $mKey The key to set, or an associative array of key=>value pairs @return $this
[ "Removes", "data", "from", "the", "session" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Service/Session.php#L182-L190
train
nails/module-auth
src/Service/Session.php
Session.destroy
public function destroy() { if (empty($this->oSession)) { return $this; } $oConfig = Factory::service('Config'); $sCookieName = $oConfig->item('sess_cookie_name'); $this->oSession->sess_destroy(); if (isset($_COOKIE) && array_key_exists($sCookieName, $_COOKIE)) { delete_cookie($sCookieName); unset($_COOKIE[$sCookieName]); } return $this; }
php
public function destroy() { if (empty($this->oSession)) { return $this; } $oConfig = Factory::service('Config'); $sCookieName = $oConfig->item('sess_cookie_name'); $this->oSession->sess_destroy(); if (isset($_COOKIE) && array_key_exists($sCookieName, $_COOKIE)) { delete_cookie($sCookieName); unset($_COOKIE[$sCookieName]); } return $this; }
[ "public", "function", "destroy", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "oSession", ")", ")", "{", "return", "$", "this", ";", "}", "$", "oConfig", "=", "Factory", "::", "service", "(", "'Config'", ")", ";", "$", "sCookieName", ...
Destroy the user's session @return $this
[ "Destroy", "the", "user", "s", "session" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Service/Session.php#L199-L216
train
nails/module-auth
src/Service/Session.php
Session.regenerate
public function regenerate($bDestroy = false) { if (empty($this->oSession)) { return $this; } $this->oSession->sess_regenerate($bDestroy); return $this; }
php
public function regenerate($bDestroy = false) { if (empty($this->oSession)) { return $this; } $this->oSession->sess_regenerate($bDestroy); return $this; }
[ "public", "function", "regenerate", "(", "$", "bDestroy", "=", "false", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "oSession", ")", ")", "{", "return", "$", "this", ";", "}", "$", "this", "->", "oSession", "->", "sess_regenerate", "(", "$"...
Regenerate the user's session @param bool $bDestroy Whether to destroy the old session
[ "Regenerate", "the", "user", "s", "session" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Service/Session.php#L225-L233
train
ommu/mod-core
components/system/OFunction.php
OFunction.getDataProviderPager
public static function getDataProviderPager($dataProvider, $attr=true) { if($attr == true) $data = $dataProvider->getPagination(); else $data = $dataProvider; $pageCount = $data->itemCount >= $data->pageSize ? ($data->itemCount % $data->pageSize === 0 ? (int)($data->itemCount/$data->pageSize) : (int)($data->itemCount/$data->pageSize)+1) : 1; $currentPage = $data->itemCount != 0 ? $data->currentPage+1 : 1; $nextPage = (($pageCount != $currentPage) && ($pageCount > $currentPage)) ? $currentPage+1 : 0; $return = array( 'pageVar'=>$data->pageVar, 'itemCount'=>$data->itemCount, 'pageSize'=>$data->pageSize, 'pageCount'=>$pageCount, 'currentPage'=>$currentPage, 'nextPage'=>$nextPage, ); return $return; }
php
public static function getDataProviderPager($dataProvider, $attr=true) { if($attr == true) $data = $dataProvider->getPagination(); else $data = $dataProvider; $pageCount = $data->itemCount >= $data->pageSize ? ($data->itemCount % $data->pageSize === 0 ? (int)($data->itemCount/$data->pageSize) : (int)($data->itemCount/$data->pageSize)+1) : 1; $currentPage = $data->itemCount != 0 ? $data->currentPage+1 : 1; $nextPage = (($pageCount != $currentPage) && ($pageCount > $currentPage)) ? $currentPage+1 : 0; $return = array( 'pageVar'=>$data->pageVar, 'itemCount'=>$data->itemCount, 'pageSize'=>$data->pageSize, 'pageCount'=>$pageCount, 'currentPage'=>$currentPage, 'nextPage'=>$nextPage, ); return $return; }
[ "public", "static", "function", "getDataProviderPager", "(", "$", "dataProvider", ",", "$", "attr", "=", "true", ")", "{", "if", "(", "$", "attr", "==", "true", ")", "$", "data", "=", "$", "dataProvider", "->", "getPagination", "(", ")", ";", "else", "...
get data provider pager
[ "get", "data", "provider", "pager" ]
68c90e76440e74ee93bcf82905a54d86c941b771
https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/components/system/OFunction.php#L31-L51
train
ommu/mod-core
components/system/OFunction.php
OFunction.validHostURL
public static function validHostURL($targetUrl) { $req = Yii::app()->request; $url = ($req->port == 80? 'http://': 'https://') . $req->serverName; if(substr($targetUrl, 0, 1) != '/') $targetUrl = '/'.$targetUrl; return $url = $url.$targetUrl; }
php
public static function validHostURL($targetUrl) { $req = Yii::app()->request; $url = ($req->port == 80? 'http://': 'https://') . $req->serverName; if(substr($targetUrl, 0, 1) != '/') $targetUrl = '/'.$targetUrl; return $url = $url.$targetUrl; }
[ "public", "static", "function", "validHostURL", "(", "$", "targetUrl", ")", "{", "$", "req", "=", "Yii", "::", "app", "(", ")", "->", "request", ";", "$", "url", "=", "(", "$", "req", "->", "port", "==", "80", "?", "'http://'", ":", "'https://'", "...
Valid target api url, if application ecc3 datacenter is accessed from other place Defined host url + target url
[ "Valid", "target", "api", "url", "if", "application", "ecc3", "datacenter", "is", "accessed", "from", "other", "place", "Defined", "host", "url", "+", "target", "url" ]
68c90e76440e74ee93bcf82905a54d86c941b771
https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/components/system/OFunction.php#L87-L96
train
gregorybesson/PlaygroundUser
src/Mapper/User.php
User.remove
public function remove($entity) { $entity->setState(0); $this->em->persist($entity); $this->em->flush(); }
php
public function remove($entity) { $entity->setState(0); $this->em->persist($entity); $this->em->flush(); }
[ "public", "function", "remove", "(", "$", "entity", ")", "{", "$", "entity", "->", "setState", "(", "0", ")", ";", "$", "this", "->", "em", "->", "persist", "(", "$", "entity", ")", ";", "$", "this", "->", "em", "->", "flush", "(", ")", ";", "}...
We don't delete the user, but just disable it @param unknown_type $entity
[ "We", "don", "t", "delete", "the", "user", "but", "just", "disable", "it" ]
b07c9969b5da1c173001fbba343f0a006d87eb8e
https://github.com/gregorybesson/PlaygroundUser/blob/b07c9969b5da1c173001fbba343f0a006d87eb8e/src/Mapper/User.php#L128-L133
train
php-toolkit/php-utils
src/PhpDotEnv.php
PhpDotEnv.settingEnv
private function settingEnv(array $data): void { $loadedVars = \array_flip(\explode(',', \getenv(self::FULL_KEY))); unset($loadedVars['']); foreach ($data as $name => $value) { if (\is_int($name) || !\is_string($value)) { continue; } $name = \strtoupper($name); $notHttpName = 0 !== \strpos($name, 'HTTP_'); // don't check existence with getenv() because of thread safety issues if ((isset($_ENV[$name]) || (isset($_SERVER[$name]) && $notHttpName)) && !isset($loadedVars[$name])) { continue; } // is a constant var if ($value && \defined($value)) { $value = \constant($value); } // eg: "FOO=BAR" \putenv("$name=$value"); $_ENV[$name] = $value; if ($notHttpName) { $_SERVER[$name] = $value; } $loadedVars[$name] = true; } if ($loadedVars) { $loadedVars = \implode(',', \array_keys($loadedVars)); \putenv(self::FULL_KEY . "=$loadedVars"); $_ENV[self::FULL_KEY] = $loadedVars; $_SERVER[self::FULL_KEY] = $loadedVars; } }
php
private function settingEnv(array $data): void { $loadedVars = \array_flip(\explode(',', \getenv(self::FULL_KEY))); unset($loadedVars['']); foreach ($data as $name => $value) { if (\is_int($name) || !\is_string($value)) { continue; } $name = \strtoupper($name); $notHttpName = 0 !== \strpos($name, 'HTTP_'); // don't check existence with getenv() because of thread safety issues if ((isset($_ENV[$name]) || (isset($_SERVER[$name]) && $notHttpName)) && !isset($loadedVars[$name])) { continue; } // is a constant var if ($value && \defined($value)) { $value = \constant($value); } // eg: "FOO=BAR" \putenv("$name=$value"); $_ENV[$name] = $value; if ($notHttpName) { $_SERVER[$name] = $value; } $loadedVars[$name] = true; } if ($loadedVars) { $loadedVars = \implode(',', \array_keys($loadedVars)); \putenv(self::FULL_KEY . "=$loadedVars"); $_ENV[self::FULL_KEY] = $loadedVars; $_SERVER[self::FULL_KEY] = $loadedVars; } }
[ "private", "function", "settingEnv", "(", "array", "$", "data", ")", ":", "void", "{", "$", "loadedVars", "=", "\\", "array_flip", "(", "\\", "explode", "(", "','", ",", "\\", "getenv", "(", "self", "::", "FULL_KEY", ")", ")", ")", ";", "unset", "(",...
setting env data @param array $data
[ "setting", "env", "data" ]
6e4b249b1c3cae36e19db466ddf5c7dd2c985904
https://github.com/php-toolkit/php-utils/blob/6e4b249b1c3cae36e19db466ddf5c7dd2c985904/src/PhpDotEnv.php#L71-L111
train
vanilla/garden-db
src/TableDef.php
TableDef.setColumn
public function setColumn($name, $type, $nullDefault = false) { $this->columns[$name] = $this->createColumnDef($type, $nullDefault); return $this; }
php
public function setColumn($name, $type, $nullDefault = false) { $this->columns[$name] = $this->createColumnDef($type, $nullDefault); return $this; }
[ "public", "function", "setColumn", "(", "$", "name", ",", "$", "type", ",", "$", "nullDefault", "=", "false", ")", "{", "$", "this", "->", "columns", "[", "$", "name", "]", "=", "$", "this", "->", "createColumnDef", "(", "$", "type", ",", "$", "nul...
Define a column. @param string $name The column name. @param string $type The column type. @param mixed $nullDefault Whether the column is required or it's default. null|true : The column is not required. false : The column is required. Anything else : The column is required and this is its default. @return TableDef
[ "Define", "a", "column", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/TableDef.php#L73-L77
train