repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
andyburton/Sonic-Framework | src/Resource/User.php | User._Login | public static function _Login ($email, $password)
{
// Authenticate
if (static::_Authenticate ($email, $password) !== TRUE)
{
return 'authentication_fail';
}
// Get user
$user = static::_readFromEmail ($email);
if (!$user)
{
return 'invalid_user';
}
// Reset password
$user->reset ('password');
// Set timestamps
$user->loginTimestamp = time ();
$user->lastAction = $user->loginTimestamp;
// Set session
$user->setSessionData ();
// Return user object
return $user;
} | php | public static function _Login ($email, $password)
{
// Authenticate
if (static::_Authenticate ($email, $password) !== TRUE)
{
return 'authentication_fail';
}
// Get user
$user = static::_readFromEmail ($email);
if (!$user)
{
return 'invalid_user';
}
// Reset password
$user->reset ('password');
// Set timestamps
$user->loginTimestamp = time ();
$user->lastAction = $user->loginTimestamp;
// Set session
$user->setSessionData ();
// Return user object
return $user;
} | Log a user in
@param string $email User email address
@param string $password User password
@return \Sonic\Resource\User|boolean Error | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L620-L656 |
andyburton/Sonic-Framework | src/Resource/User.php | User._Authenticate | public static function _Authenticate ($email, $password)
{
// Get user
$user = static::_readFromEmail ($email);
if (!$user)
{
return FALSE;
}
// Check password
return $user->checkPassword ($password);
} | php | public static function _Authenticate ($email, $password)
{
// Get user
$user = static::_readFromEmail ($email);
if (!$user)
{
return FALSE;
}
// Check password
return $user->checkPassword ($password);
} | Authenticate and attempt to login a user
@param string $email User email address
@param string $password User password
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L666-L682 |
andyburton/Sonic-Framework | src/Resource/User.php | User._randomPassword | public static function _randomPassword ($length = self::DEFAULT_PASSWORD_LENGTH, $charset = self::DEFAULT_PASSWORD_CHARACTERS)
{
// Set password variable
$password = '';
// Set i to the password length
$i = $length;
// Loop until the password is the desired length
while ($i > 0)
{
// Choose a random character from the charset
$char = $charset[mt_rand (0, strlen ($charset) -1)];
// Make sure that the first character of the password is a number or letter
if ($password == '' && !preg_match('/[0-9A-Za-z]/', $char))
{
continue;
}
// Add the character to the password
$password .= $char;
// Decrement rounds
$i--;
}
// Return the password
return $password;
} | php | public static function _randomPassword ($length = self::DEFAULT_PASSWORD_LENGTH, $charset = self::DEFAULT_PASSWORD_CHARACTERS)
{
// Set password variable
$password = '';
// Set i to the password length
$i = $length;
// Loop until the password is the desired length
while ($i > 0)
{
// Choose a random character from the charset
$char = $charset[mt_rand (0, strlen ($charset) -1)];
// Make sure that the first character of the password is a number or letter
if ($password == '' && !preg_match('/[0-9A-Za-z]/', $char))
{
continue;
}
// Add the character to the password
$password .= $char;
// Decrement rounds
$i--;
}
// Return the password
return $password;
} | Generate a random password
@param integer $length Password length
@param string $charset Password character set
@return type | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L740-L781 |
slickframework/form | src/Element/AbstractElement.php | AbstractElement.setValue | public function setValue($value)
{
$this->value = $value;
if ($value instanceof ValueAwareInterface) {
$this->value = $value->getFormValue();
}
return $this;
} | php | public function setValue($value)
{
$this->value = $value;
if ($value instanceof ValueAwareInterface) {
$this->value = $value->getFormValue();
}
return $this;
} | Sets the value or content of the element
@param mixed $value
@return mixed | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Element/AbstractElement.php#L88-L95 |
slickframework/form | src/Element/AbstractElement.php | AbstractElement.getRenderer | protected function getRenderer()
{
if (null === $this->renderer) {
$this->setRenderer(new $this->rendererClass());
}
return $this->renderer;
} | php | protected function getRenderer()
{
if (null === $this->renderer) {
$this->setRenderer(new $this->rendererClass());
}
return $this->renderer;
} | Gets the HTML renderer for this element
@return RendererInterface | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Element/AbstractElement.php#L125-L131 |
liufee/cms-core | backend/actions/UpdateAction.php | UpdateAction.run | public function run($id)
{
if (! $id) throw new BadRequestHttpException(yii::t('cms', "Id doesn't exit"));
/* @var $model yii\db\ActiveRecord */
$model = call_user_func([$this->modelClass, 'findOne'], $id);
if (! $model) throw new BadRequestHttpException(yii::t('cms', "Cannot find model by $id"));
$model->setScenario( $this->scenario );
if (yii::$app->getRequest()->getIsPost()) {
if ($model->load(Yii::$app->getRequest()->post()) && $model->save()) {
if( yii::$app->getRequest()->getIsAjax() ){
return [];
}else {
yii::$app->getSession()->setFlash('success', yii::t('cms', 'Success'));
return $this->controller->redirect(['update', 'id' => $model->getPrimaryKey()]);
}
} else {
$errors = $model->getErrors();
$err = '';
foreach ($errors as $v) {
$err .= $v[0] . '<br>';
}
if( yii::$app->getRequest()->getIsAjax() ){
throw new UnprocessableEntityHttpException($err);
}else {
yii::$app->getSession()->setFlash('error', $err);
}
$model = call_user_func([$this->modelClass, 'findOne'], $id);
}
}
return $this->controller->render('update', [
'model' => $model,
]);
} | php | public function run($id)
{
if (! $id) throw new BadRequestHttpException(yii::t('cms', "Id doesn't exit"));
/* @var $model yii\db\ActiveRecord */
$model = call_user_func([$this->modelClass, 'findOne'], $id);
if (! $model) throw new BadRequestHttpException(yii::t('cms', "Cannot find model by $id"));
$model->setScenario( $this->scenario );
if (yii::$app->getRequest()->getIsPost()) {
if ($model->load(Yii::$app->getRequest()->post()) && $model->save()) {
if( yii::$app->getRequest()->getIsAjax() ){
return [];
}else {
yii::$app->getSession()->setFlash('success', yii::t('cms', 'Success'));
return $this->controller->redirect(['update', 'id' => $model->getPrimaryKey()]);
}
} else {
$errors = $model->getErrors();
$err = '';
foreach ($errors as $v) {
$err .= $v[0] . '<br>';
}
if( yii::$app->getRequest()->getIsAjax() ){
throw new UnprocessableEntityHttpException($err);
}else {
yii::$app->getSession()->setFlash('error', $err);
}
$model = call_user_func([$this->modelClass, 'findOne'], $id);
}
}
return $this->controller->render('update', [
'model' => $model,
]);
} | update修改
@param $id
@return array|string|\yii\web\Response
@throws \yii\web\BadRequestHttpException
@throws \yii\web\UnprocessableEntityHttpException | https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/backend/actions/UpdateAction.php#L31-L65 |
DBRisinajumi/d2company | models/CcmpCompany.php | CcmpCompany.searchForList | public function searchForList($criteria = null)
{
if (is_null($criteria)) {
$criteria = new CDbCriteria;
}
$criteria->select = "t.*,ccgr_name,ccxg_ccgr_id";
$criteria->compare('ccmp_id', $this->ccmp_id);
$criteria->compare('ccmp_name', $this->ccmp_name, true);
$criteria->compare('ccmp_ccnt_id', $this->ccmp_ccnt_id);
$criteria->compare('ccmp_registrtion_no', $this->ccmp_registrtion_no, true);
$criteria->compare('ccmp_vat_registrtion_no', $this->ccmp_vat_registrtion_no, true);
$criteria->compare('ccmp_registration_date', $this->ccmp_registration_date);
$criteria->compare('ccmp_registration_address', $this->ccmp_registration_address, true);
$criteria->compare('ccmp_official_ccit_id', $this->ccmp_official_ccit_id);
$criteria->compare('ccmp_official_address', $this->ccmp_official_address, true);
$criteria->compare('ccmp_official_zip_code', $this->ccmp_official_zip_code, true);
$criteria->compare('ccmp_office_ccit_id', $this->ccmp_office_ccit_id);
$criteria->compare('ccmp_office_address', $this->ccmp_office_address, true);
$criteria->compare('ccmp_office_zip_code', $this->ccmp_office_zip_code, true);
$criteria->compare('ccmp_statuss', $this->ccmp_statuss);
$criteria->compare('ccmp_description', $this->ccmp_description, true);
$criteria->compare('ccmp_office_phone', $this->ccmp_office_phone, true);
$criteria->compare('ccmp_office_email', $this->ccmp_office_email, true);
$criteria->compare('ccmp_agreement_nr', $this->ccmp_agreement_nr, true);
$criteria->compare('ccmp_agreement_date', $this->ccmp_agreement_date);
$criteria->compare('ccmp_sys_ccmp_id', $this->ccmp_sys_ccmp_id);
$criteria->compare('ccxg_ccgr_id', $this->ccxg_ccgr_id);
$criteria->join = "
LEFT OUTER JOIN ccxg_company_x_group
ON ccxg_ccmp_id = ccmp_id
LEFT OUTER JOIN ccgr_group
ON ccxg_ccgr_id = ccgr_id
";
return new CActiveDataProvider('CcmpCompany', array(
'criteria' => $criteria,
'sort'=>array('defaultOrder'=>'ccmp_name'),
'pagination'=>array('pageSize'=>50),
));
} | php | public function searchForList($criteria = null)
{
if (is_null($criteria)) {
$criteria = new CDbCriteria;
}
$criteria->select = "t.*,ccgr_name,ccxg_ccgr_id";
$criteria->compare('ccmp_id', $this->ccmp_id);
$criteria->compare('ccmp_name', $this->ccmp_name, true);
$criteria->compare('ccmp_ccnt_id', $this->ccmp_ccnt_id);
$criteria->compare('ccmp_registrtion_no', $this->ccmp_registrtion_no, true);
$criteria->compare('ccmp_vat_registrtion_no', $this->ccmp_vat_registrtion_no, true);
$criteria->compare('ccmp_registration_date', $this->ccmp_registration_date);
$criteria->compare('ccmp_registration_address', $this->ccmp_registration_address, true);
$criteria->compare('ccmp_official_ccit_id', $this->ccmp_official_ccit_id);
$criteria->compare('ccmp_official_address', $this->ccmp_official_address, true);
$criteria->compare('ccmp_official_zip_code', $this->ccmp_official_zip_code, true);
$criteria->compare('ccmp_office_ccit_id', $this->ccmp_office_ccit_id);
$criteria->compare('ccmp_office_address', $this->ccmp_office_address, true);
$criteria->compare('ccmp_office_zip_code', $this->ccmp_office_zip_code, true);
$criteria->compare('ccmp_statuss', $this->ccmp_statuss);
$criteria->compare('ccmp_description', $this->ccmp_description, true);
$criteria->compare('ccmp_office_phone', $this->ccmp_office_phone, true);
$criteria->compare('ccmp_office_email', $this->ccmp_office_email, true);
$criteria->compare('ccmp_agreement_nr', $this->ccmp_agreement_nr, true);
$criteria->compare('ccmp_agreement_date', $this->ccmp_agreement_date);
$criteria->compare('ccmp_sys_ccmp_id', $this->ccmp_sys_ccmp_id);
$criteria->compare('ccxg_ccgr_id', $this->ccxg_ccgr_id);
$criteria->join = "
LEFT OUTER JOIN ccxg_company_x_group
ON ccxg_ccmp_id = ccmp_id
LEFT OUTER JOIN ccgr_group
ON ccxg_ccgr_id = ccgr_id
";
return new CActiveDataProvider('CcmpCompany', array(
'criteria' => $criteria,
'sort'=>array('defaultOrder'=>'ccmp_name'),
'pagination'=>array('pageSize'=>50),
));
} | special search for company list. Main model:CcxgCompanyXGroup
@param CDbCriteria $criteria
@return \CActiveDataProvider | https://github.com/DBRisinajumi/d2company/blob/20df0db96ac2c8e73471c4bab7d487b67ef4ed0a/models/CcmpCompany.php#L319-L362 |
DBRisinajumi/d2company | models/CcmpCompany.php | CcmpCompany.getAllGroupCompanies | public static function getAllGroupCompanies($ccgr_id) {
$sql = "
SELECT
ccmp_id,
ccmp_name
FROM
ccxg_company_x_group
INNER JOIN ccmp_company
ON ccxg_ccmp_id = ccmp_id
WHERE ccxg_ccgr_id = :ccgr_id
ORDER BY ccmp_name
";
return Yii::app()->db
->createCommand($sql)
->bindParam(":ccgr_id", $ccgr_id, PDO::PARAM_INT)
->queryAll();
} | php | public static function getAllGroupCompanies($ccgr_id) {
$sql = "
SELECT
ccmp_id,
ccmp_name
FROM
ccxg_company_x_group
INNER JOIN ccmp_company
ON ccxg_ccmp_id = ccmp_id
WHERE ccxg_ccgr_id = :ccgr_id
ORDER BY ccmp_name
";
return Yii::app()->db
->createCommand($sql)
->bindParam(":ccgr_id", $ccgr_id, PDO::PARAM_INT)
->queryAll();
} | get all syscomanies array without access control
@param int $ccgr_id
@return array [
['ccmp_id' => 1, ccmp_name=>'company name1'],
['ccmp_id' => 2, ccmp_name=>'company name2'],
] | https://github.com/DBRisinajumi/d2company/blob/20df0db96ac2c8e73471c4bab7d487b67ef4ed0a/models/CcmpCompany.php#L439-L455 |
SpoonX/SxMail | src/SxMail/SxMail.php | SxMail.setLayout | public function setLayout($layout = null)
{
if (null !== $layout && !is_string($layout) && !($layout instanceof ViewModel)) {
throw new InvalidArgumentException(
'Invalid value supplied for setLayout.'.
'Expected null, string, or Zend\View\Model\ViewModel.'
);
}
if (null === $layout && empty($this->config['message']['layout'])) {
return;
}
if (null === $layout) {
$layout = (string) $this->config['message']['layout'];
unset($this->config['message']['layout']);
}
if (is_string($layout)) {
$template = $layout;
$layout = new ViewModel;
$layout->setTemplate($template);
}
$this->layout = $layout;
} | php | public function setLayout($layout = null)
{
if (null !== $layout && !is_string($layout) && !($layout instanceof ViewModel)) {
throw new InvalidArgumentException(
'Invalid value supplied for setLayout.'.
'Expected null, string, or Zend\View\Model\ViewModel.'
);
}
if (null === $layout && empty($this->config['message']['layout'])) {
return;
}
if (null === $layout) {
$layout = (string) $this->config['message']['layout'];
unset($this->config['message']['layout']);
}
if (is_string($layout)) {
$template = $layout;
$layout = new ViewModel;
$layout->setTemplate($template);
}
$this->layout = $layout;
} | Set the layout.
@param mixed $layout Either null (looks in config), ViewModel, or string.
@throws \SxMail\Exception\InvalidArgumentException | https://github.com/SpoonX/SxMail/blob/b0663169cd246ba091f7c84785c69d051a652385/src/SxMail/SxMail.php#L58-L86 |
SpoonX/SxMail | src/SxMail/SxMail.php | SxMail.manipulateBody | protected function manipulateBody($body, $mimeType = null)
{
// Make sure we have a string.
if ($body instanceof ViewModel) {
$body = $this->viewRenderer->render($body);
$detectedMimeType = 'text/html';
} elseif (null === $body) {
$detectedMimeType = 'text/plain';
$body = '';
}
if (null !== ($layout = $this->getLayout())) {
$layout->setVariables(array(
'content' => $body,
));
$detectedMimeType = 'text/html';
$body = $this->viewRenderer->render($layout);
}
if (null === $mimeType && !isset($detectedMimeType)) {
$mimeType = preg_match("/<[^<]+>/", $body) ? 'text/html' : 'text/plain';
} elseif (null === $mimeType) {
$mimeType = $detectedMimeType;
}
$mimePart = new MimePart($body);
$mimePart->type = $mimeType;
if (!empty($this->config['charset'])) {
$mimePart->charset = $this->config['charset'];
}
$message = new MimeMessage();
if (!isset($this->config['message']['generate_alternative_body'])) {
$this->config['message']['generate_alternative_body'] = true;
}
if ($this->config['message']['generate_alternative_body'] && $mimeType === 'text/html') {
$generatedBody = $this->renderTextBody($body);
$altPart = new MimePart($generatedBody);
$altPart->type = 'text/plain';
if (!empty($this->config['charset'])) {
$altPart->charset = $this->config['charset'];
}
$message->addPart($altPart);
}
$message->addPart($mimePart);
return $message;
} | php | protected function manipulateBody($body, $mimeType = null)
{
// Make sure we have a string.
if ($body instanceof ViewModel) {
$body = $this->viewRenderer->render($body);
$detectedMimeType = 'text/html';
} elseif (null === $body) {
$detectedMimeType = 'text/plain';
$body = '';
}
if (null !== ($layout = $this->getLayout())) {
$layout->setVariables(array(
'content' => $body,
));
$detectedMimeType = 'text/html';
$body = $this->viewRenderer->render($layout);
}
if (null === $mimeType && !isset($detectedMimeType)) {
$mimeType = preg_match("/<[^<]+>/", $body) ? 'text/html' : 'text/plain';
} elseif (null === $mimeType) {
$mimeType = $detectedMimeType;
}
$mimePart = new MimePart($body);
$mimePart->type = $mimeType;
if (!empty($this->config['charset'])) {
$mimePart->charset = $this->config['charset'];
}
$message = new MimeMessage();
if (!isset($this->config['message']['generate_alternative_body'])) {
$this->config['message']['generate_alternative_body'] = true;
}
if ($this->config['message']['generate_alternative_body'] && $mimeType === 'text/html') {
$generatedBody = $this->renderTextBody($body);
$altPart = new MimePart($generatedBody);
$altPart->type = 'text/plain';
if (!empty($this->config['charset'])) {
$altPart->charset = $this->config['charset'];
}
$message->addPart($altPart);
}
$message->addPart($mimePart);
return $message;
} | Manipulate the body based on configuration options.
@param mixed $body
@param string $mimeType
@return string | https://github.com/SpoonX/SxMail/blob/b0663169cd246ba091f7c84785c69d051a652385/src/SxMail/SxMail.php#L106-L161 |
SpoonX/SxMail | src/SxMail/SxMail.php | SxMail.renderTextBody | protected function renderTextBody($body)
{
$body = html_entity_decode(
trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $body))), ENT_QUOTES
);
if (empty($body)) {
$body = 'To view this email, open it an email client that supports HTML.';
}
return $body;
} | php | protected function renderTextBody($body)
{
$body = html_entity_decode(
trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $body))), ENT_QUOTES
);
if (empty($body)) {
$body = 'To view this email, open it an email client that supports HTML.';
}
return $body;
} | Strip html tags and render a text-only version.
@param string $body
@return string | https://github.com/SpoonX/SxMail/blob/b0663169cd246ba091f7c84785c69d051a652385/src/SxMail/SxMail.php#L170-L181 |
SpoonX/SxMail | src/SxMail/SxMail.php | SxMail.applyMessageOptions | protected function applyMessageOptions(Message $message)
{
if (empty($this->config['message']['options']) || !is_array($this->config['message']['options'])) {
return $message;
}
foreach ($this->config['message']['options'] as $key => $value) {
$method = 'set'.ucfirst($key);
if (is_callable(array($message, $method))) {
if (!is_array($value)) {
$value = array($value);
}
call_user_func_array(array($message, $method), $value);
}
}
return $message;
} | php | protected function applyMessageOptions(Message $message)
{
if (empty($this->config['message']['options']) || !is_array($this->config['message']['options'])) {
return $message;
}
foreach ($this->config['message']['options'] as $key => $value) {
$method = 'set'.ucfirst($key);
if (is_callable(array($message, $method))) {
if (!is_array($value)) {
$value = array($value);
}
call_user_func_array(array($message, $method), $value);
}
}
return $message;
} | @param \Zend\Mail\Message $message
@return \Zend\Mail\Message | https://github.com/SpoonX/SxMail/blob/b0663169cd246ba091f7c84785c69d051a652385/src/SxMail/SxMail.php#L188-L206 |
SpoonX/SxMail | src/SxMail/SxMail.php | SxMail.compose | public function compose($body = null, $mimeType = null)
{
// Supported types are null, ViewModel and string.
if (null !== $body && !is_string($body) && !($body instanceof ViewModel)) {
throw new InvalidArgumentException(
'Invalid value supplied. Expected null, string or instance of Zend\View\Model\ViewModel.'
);
}
$body = $this->manipulateBody($body, $mimeType);
$message = new Message;
$message->setBody($body);
if ($this->config['message']['generate_alternative_body'] && count($body->getParts()) > 1) {
$message->getHeaders()->get('content-type')->setType('multipart/alternative');
}
$this->applyMessageHeaders($message);
$this->applyMessageOptions($message);
return $message;
} | php | public function compose($body = null, $mimeType = null)
{
// Supported types are null, ViewModel and string.
if (null !== $body && !is_string($body) && !($body instanceof ViewModel)) {
throw new InvalidArgumentException(
'Invalid value supplied. Expected null, string or instance of Zend\View\Model\ViewModel.'
);
}
$body = $this->manipulateBody($body, $mimeType);
$message = new Message;
$message->setBody($body);
if ($this->config['message']['generate_alternative_body'] && count($body->getParts()) > 1) {
$message->getHeaders()->get('content-type')->setType('multipart/alternative');
}
$this->applyMessageHeaders($message);
$this->applyMessageOptions($message);
return $message;
} | Compose a new message.
@param mixed $body Accepts instance of ViewModel, string and null.
@param string $mimeType
@return \Zend\Mail\Message
@throws \SxMail\Exception\InvalidArgumentException | https://github.com/SpoonX/SxMail/blob/b0663169cd246ba091f7c84785c69d051a652385/src/SxMail/SxMail.php#L234-L256 |
DimNS/MFLPHP | src/Pages/User/ControllerReset.php | ControllerReset.start | public function start($request, $response, $service, $di)
{
$result = [];
if ($request->method('post') === true) {
$middleware = Middleware::start($request, $response, $service, $di, [
'token',
]);
if ($middleware) {
$result = $di->auth->resetPass($request->param('key'), $request->param('password'), $request->param('password'));
}
} else {
$result = $di->auth->getRequest($request->param('key'), 'reset');
}
if ($result['error'] === false) {
if ($request->method('post') == true) {
$service->message_code = 'success';
$service->message_text = $result['message'];
$template = 'auth';
} else {
$template = 'reset';
}
} else {
$service->message_code = 'danger';
$service->message_text = $result['message'];
if ($request->method('post') === true) {
$template = 'reset';
} else {
$template = 'auth';
}
}
$service->title = $di->auth->config->site_name;
$service->external_page = true;
$service->key = $request->param('key');
$service->render($service->app_root_path . '/' . $this->view_prefix . $template . '.php');
return;
} | php | public function start($request, $response, $service, $di)
{
$result = [];
if ($request->method('post') === true) {
$middleware = Middleware::start($request, $response, $service, $di, [
'token',
]);
if ($middleware) {
$result = $di->auth->resetPass($request->param('key'), $request->param('password'), $request->param('password'));
}
} else {
$result = $di->auth->getRequest($request->param('key'), 'reset');
}
if ($result['error'] === false) {
if ($request->method('post') == true) {
$service->message_code = 'success';
$service->message_text = $result['message'];
$template = 'auth';
} else {
$template = 'reset';
}
} else {
$service->message_code = 'danger';
$service->message_text = $result['message'];
if ($request->method('post') === true) {
$template = 'reset';
} else {
$template = 'auth';
}
}
$service->title = $di->auth->config->site_name;
$service->external_page = true;
$service->key = $request->param('key');
$service->render($service->app_root_path . '/' . $this->view_prefix . $template . '.php');
return;
} | Стартовый метод
@param object $request Объект запроса
@param object $response Объект ответа
@param object $service Объект сервисов
@param object $di Объект контейнера зависимостей
@return null
@version 25.04.2017
@author Дмитрий Щербаков <[email protected]> | https://github.com/DimNS/MFLPHP/blob/8da06f3f9aabf1da5796f9a3cea97425b30af201/src/Pages/User/ControllerReset.php#L41-L82 |
interactivesolutions/honeycomb-scripts | src/app/commands/HCRoutes.php | HCRoutes.handle | public function handle()
{
$rootDirectory = $this->argument('directory') ?? '';
if( $rootDirectory == '' ) {
$files = $this->getConfigFiles();
foreach ( $files as $file )
$this->generateRoutes(realpath(implode('/', array_slice(explode('/', $file), 0, -3))) . '/');
} else
$this->generateRoutes($rootDirectory);
} | php | public function handle()
{
$rootDirectory = $this->argument('directory') ?? '';
if( $rootDirectory == '' ) {
$files = $this->getConfigFiles();
foreach ( $files as $file )
$this->generateRoutes(realpath(implode('/', array_slice(explode('/', $file), 0, -3))) . '/');
} else
$this->generateRoutes($rootDirectory);
} | Execute the console command.
@return mixed | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/HCRoutes.php#L32-L44 |
interactivesolutions/honeycomb-scripts | src/app/commands/HCRoutes.php | HCRoutes.generateRoutes | private function generateRoutes($directory)
{
$dirPath = $directory . 'app/routes/';
if( ! file_exists($dirPath) )
return;
// get all files recursively
/** @var \Iterator $iterator */
$iterator = Finder::create()
->files()
->ignoreDotFiles(true)
->sortByName()
->in($dirPath);
// iterate to array
$files = iterator_to_array($iterator, true);
$finalContent = '<?php' . "\r\n";
foreach ( $files as $file ) {
$finalContent .= "\r\n";
$finalContent .= '//' . implode('/', array_slice(explode('/', $file), -6)) . "\r\n";
$finalContent .= str_replace('<?php', '', file_get_contents((string)$file)) . "\r\n";
}
file_put_contents($directory . HCRoutes::ROUTES_PATH, $finalContent);
$this->comment($directory . HCRoutes::ROUTES_PATH . ' file generated');
} | php | private function generateRoutes($directory)
{
$dirPath = $directory . 'app/routes/';
if( ! file_exists($dirPath) )
return;
// get all files recursively
/** @var \Iterator $iterator */
$iterator = Finder::create()
->files()
->ignoreDotFiles(true)
->sortByName()
->in($dirPath);
// iterate to array
$files = iterator_to_array($iterator, true);
$finalContent = '<?php' . "\r\n";
foreach ( $files as $file ) {
$finalContent .= "\r\n";
$finalContent .= '//' . implode('/', array_slice(explode('/', $file), -6)) . "\r\n";
$finalContent .= str_replace('<?php', '', file_get_contents((string)$file)) . "\r\n";
}
file_put_contents($directory . HCRoutes::ROUTES_PATH, $finalContent);
$this->comment($directory . HCRoutes::ROUTES_PATH . ' file generated');
} | Generating final routes file for package
@param $directory | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/HCRoutes.php#L51-L81 |
makinacorpus/drupal-plusql | src/ConstraintRegistry.php | ConstraintRegistry.createInstance | protected function createInstance(Connection $connection, string $type): ConstraintInterface
{
$driver = $connection->driver();
if (!isset($this->registry[$driver][$type])) {
throw new \InvalidArgumentException(sprintf("'%s' constraint is not supported by '%s' driver"));
}
$className = $this->registry[$driver][$type];
// Consider that if the user did not register an instance, then he is
// using the ConstraintTrait and its constructor, I do hope anyway.
// @todo provide other means of registration
if (!class_exists($className)) {
throw new \InvalidArgumentException(sprintf("'%s' class does not exist", $className));
}
return new $className($connection, $type);
} | php | protected function createInstance(Connection $connection, string $type): ConstraintInterface
{
$driver = $connection->driver();
if (!isset($this->registry[$driver][$type])) {
throw new \InvalidArgumentException(sprintf("'%s' constraint is not supported by '%s' driver"));
}
$className = $this->registry[$driver][$type];
// Consider that if the user did not register an instance, then he is
// using the ConstraintTrait and its constructor, I do hope anyway.
// @todo provide other means of registration
if (!class_exists($className)) {
throw new \InvalidArgumentException(sprintf("'%s' class does not exist", $className));
}
return new $className($connection, $type);
} | Create instance for the given connection | https://github.com/makinacorpus/drupal-plusql/blob/7182d653a117d53b6bb3e3edd53f07af11ff5d43/src/ConstraintRegistry.php#L28-L46 |
makinacorpus/drupal-plusql | src/ConstraintRegistry.php | ConstraintRegistry.get | public function get(Connection $connection, string $type): ConstraintInterface
{
$driver = $connection->driver();
if (isset($this->instances[$driver][$type])) {
return $this->instances[$driver][$type];
}
return $this->instances[$driver][$type] = $this->createInstance($connection, $type);
} | php | public function get(Connection $connection, string $type): ConstraintInterface
{
$driver = $connection->driver();
if (isset($this->instances[$driver][$type])) {
return $this->instances[$driver][$type];
}
return $this->instances[$driver][$type] = $this->createInstance($connection, $type);
} | Get constraint type handler for driver | https://github.com/makinacorpus/drupal-plusql/blob/7182d653a117d53b6bb3e3edd53f07af11ff5d43/src/ConstraintRegistry.php#L51-L60 |
makinacorpus/drupal-plusql | src/ConstraintRegistry.php | ConstraintRegistry.getAll | public function getAll(Connection $connection): array
{
foreach ($this->registry as $types) {
foreach (array_keys($types) as $type) {
$this->get($connection, $type);
}
}
return $this->instances[$connection->driver()];
} | php | public function getAll(Connection $connection): array
{
foreach ($this->registry as $types) {
foreach (array_keys($types) as $type) {
$this->get($connection, $type);
}
}
return $this->instances[$connection->driver()];
} | Get all defined handlers
@return ConstraintInterface[] | https://github.com/makinacorpus/drupal-plusql/blob/7182d653a117d53b6bb3e3edd53f07af11ff5d43/src/ConstraintRegistry.php#L67-L76 |
pmdevelopment/tool-bundle | Twig/Vendor/PicqerBarcodeGeneratorExtension.php | PicqerBarcodeGeneratorExtension.getHtml128 | public function getHtml128($string, $pixelPerByte = 2, $height = 30)
{
$generator = new BarcodeGeneratorHTML();
return $generator->getBarcode($string, BarcodeGeneratorHTML::TYPE_CODE_128, $pixelPerByte, $height);
} | php | public function getHtml128($string, $pixelPerByte = 2, $height = 30)
{
$generator = new BarcodeGeneratorHTML();
return $generator->getBarcode($string, BarcodeGeneratorHTML::TYPE_CODE_128, $pixelPerByte, $height);
} | Get HTML as CODE-128
@param string $string
@return string | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Twig/Vendor/PicqerBarcodeGeneratorExtension.php#L51-L56 |
pmdevelopment/tool-bundle | Twig/Vendor/PicqerBarcodeGeneratorExtension.php | PicqerBarcodeGeneratorExtension.getHtmlEan13 | public function getHtmlEan13($string, $pixelPerByte = 2, $height = 30)
{
$generator = new BarcodeGeneratorHTML();
return $generator->getBarcode($string, BarcodeGeneratorHTML::TYPE_EAN_13, $pixelPerByte, $height);
} | php | public function getHtmlEan13($string, $pixelPerByte = 2, $height = 30)
{
$generator = new BarcodeGeneratorHTML();
return $generator->getBarcode($string, BarcodeGeneratorHTML::TYPE_EAN_13, $pixelPerByte, $height);
} | Get HTML as EAN-13
@param string $string
@return string | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Twig/Vendor/PicqerBarcodeGeneratorExtension.php#L65-L70 |
pmdevelopment/tool-bundle | Twig/Vendor/PicqerBarcodeGeneratorExtension.php | PicqerBarcodeGeneratorExtension.getHtmlUpcA | public function getHtmlUpcA($string, $pixelPerByte = 2, $height = 30)
{
$generator = new BarcodeGeneratorHTML();
return $generator->getBarcode($string, BarcodeGeneratorHTML::TYPE_UPC_A, $pixelPerByte, $height);
} | php | public function getHtmlUpcA($string, $pixelPerByte = 2, $height = 30)
{
$generator = new BarcodeGeneratorHTML();
return $generator->getBarcode($string, BarcodeGeneratorHTML::TYPE_UPC_A, $pixelPerByte, $height);
} | Get HTML as UPC
@param string $string
@return string | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Twig/Vendor/PicqerBarcodeGeneratorExtension.php#L79-L84 |
zara-4/php-sdk | Zara4/API/Communication/Authentication/ApplicationAuthenticator.php | ApplicationAuthenticator.acquireAccessToken | public function acquireAccessToken() {
$grant = new ClientCredentialsGrantRequest($this->clientId, $this->clientSecret, $this->scopes);
$tokens = $grant->getTokens();
$accessToken = $tokens->{"access_token"};
$expiresAt = Util::calculateExpiryTime($tokens->{"expires_in"});
return new ReissuableAccessToken($this->clientId, $this->clientSecret, $accessToken, $expiresAt, $this->scopes);
} | php | public function acquireAccessToken() {
$grant = new ClientCredentialsGrantRequest($this->clientId, $this->clientSecret, $this->scopes);
$tokens = $grant->getTokens();
$accessToken = $tokens->{"access_token"};
$expiresAt = Util::calculateExpiryTime($tokens->{"expires_in"});
return new ReissuableAccessToken($this->clientId, $this->clientSecret, $accessToken, $expiresAt, $this->scopes);
} | Get an AccessToken for use when communicating with the Zara 4 API service.
@return ReissuableAccessToken | https://github.com/zara-4/php-sdk/blob/33a1bc9676d9d870a0e274ca44068b207e5dae78/Zara4/API/Communication/Authentication/ApplicationAuthenticator.php#L16-L24 |
phPoirot/Client-OAuth2 | mod/Authenticate/IdentifierHttpToken.php | IdentifierHttpToken.doRecognizedIdentity | protected function doRecognizedIdentity()
{
$token = $this->_parseTokenFromRequest();
try
{
if ($token) {
$itoken = $this->assertion->assertToken($token);
$token = new IdentityOAuthToken([
'owner_id' => $itoken->getOwnerIdentifier(),
'assert_token_entity' => $itoken,
'access_token' => new AccessTokenObject([
'access_token' => $itoken->getIdentifier(),
'client_id' => $itoken->getClientIdentifier(),
'datetime_expiration' => $itoken->getDateTimeExpiration(),
'scopes' => $itoken->getScopes(),
]),
'meta_data' => [],
]);
}
} catch (exOAuthAccessDenied $e) {
// any oauth server error will set token result to false
if ($e->getMessage() !== 'invalid_grant')
// Something other than token invalid or expire happen;
// its not accessDenied exception
throw $e;
$token = null;
}
return $token;
} | php | protected function doRecognizedIdentity()
{
$token = $this->_parseTokenFromRequest();
try
{
if ($token) {
$itoken = $this->assertion->assertToken($token);
$token = new IdentityOAuthToken([
'owner_id' => $itoken->getOwnerIdentifier(),
'assert_token_entity' => $itoken,
'access_token' => new AccessTokenObject([
'access_token' => $itoken->getIdentifier(),
'client_id' => $itoken->getClientIdentifier(),
'datetime_expiration' => $itoken->getDateTimeExpiration(),
'scopes' => $itoken->getScopes(),
]),
'meta_data' => [],
]);
}
} catch (exOAuthAccessDenied $e) {
// any oauth server error will set token result to false
if ($e->getMessage() !== 'invalid_grant')
// Something other than token invalid or expire happen;
// its not accessDenied exception
throw $e;
$token = null;
}
return $token;
} | Attain Identity Object From Signed Sign
exp. session, extract from authorize header,
load lazy data, etc.
!! called when user is signed in to retrieve user identity
note: almost retrieve identity data from cache or
storage that store user data. ie. session
@see withIdentity()
@return iIdentity|\Traversable|null Null if no change need | https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/mod/Authenticate/IdentifierHttpToken.php#L49-L81 |
phPoirot/Client-OAuth2 | mod/Authenticate/IdentifierHttpToken.php | IdentifierHttpToken._parseTokenFromRequest | private function _parseTokenFromRequest()
{
if ($this->_c_parsedToken)
// From Cached
return $this->_c_parsedToken;
$this->_c_parsedToken = $r = $this->assertion->parseTokenStrFromRequest(
new ServerRequestBridgeInPsr( $this->request() )
);
return $r;
} | php | private function _parseTokenFromRequest()
{
if ($this->_c_parsedToken)
// From Cached
return $this->_c_parsedToken;
$this->_c_parsedToken = $r = $this->assertion->parseTokenStrFromRequest(
new ServerRequestBridgeInPsr( $this->request() )
);
return $r;
} | Parse Token From Request
@return null|string | https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/mod/Authenticate/IdentifierHttpToken.php#L141-L153 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Framework/Media/File/Action/Dal/UploadAction.php | UploadAction.resolve | public function resolve()
{
if ($this->sourceFile instanceof UploadedFile) {
$extension = $this->sourceFile->guessExtension();
$name = preg_filter('/^php(.+)/', '$1', $this->sourceFile->getBasename());
$this->originalName = $this->sourceFile->getClientOriginalName();
} else {
$extension = $this->sourceFile->getExtension();
$this->originalName = $name = $this->sourceFile->getBasename('.'.$extension);
}
$this->setPhysicalFile(
$this->sourceFile->move(
$this->storePath,
sprintf('%s%s.%s',
strtolower($name),
base_convert(microtime(), 10, 36),
$extension
)
)
);
return parent::resolve();
} | php | public function resolve()
{
if ($this->sourceFile instanceof UploadedFile) {
$extension = $this->sourceFile->guessExtension();
$name = preg_filter('/^php(.+)/', '$1', $this->sourceFile->getBasename());
$this->originalName = $this->sourceFile->getClientOriginalName();
} else {
$extension = $this->sourceFile->getExtension();
$this->originalName = $name = $this->sourceFile->getBasename('.'.$extension);
}
$this->setPhysicalFile(
$this->sourceFile->move(
$this->storePath,
sprintf('%s%s.%s',
strtolower($name),
base_convert(microtime(), 10, 36),
$extension
)
)
);
return parent::resolve();
} | Override to handle upload before normal creation. | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Framework/Media/File/Action/Dal/UploadAction.php#L21-L44 |
BenGorFile/FileBundle | src/BenGorFile/FileBundle/DependencyInjection/Compiler/ApplicationCommandsPass.php | ApplicationCommandsPass.process | public function process(ContainerBuilder $container)
{
$config = $container->getParameter('bengor_file.config');
foreach ($config['file_class'] as $key => $file) {
(new SuffixNumberFileCommandBuilder($container, $file['persistence'], $file))->build($key);
(new OverwriteFileCommandBuilder($container, $file['persistence']))->build($key);
(new RenameFileCommandBuilder($container, $file['persistence']))->build($key);
(new RemoveFileCommandBuilder($container, $file['persistence']))->build($key);
}
} | php | public function process(ContainerBuilder $container)
{
$config = $container->getParameter('bengor_file.config');
foreach ($config['file_class'] as $key => $file) {
(new SuffixNumberFileCommandBuilder($container, $file['persistence'], $file))->build($key);
(new OverwriteFileCommandBuilder($container, $file['persistence']))->build($key);
(new RenameFileCommandBuilder($container, $file['persistence']))->build($key);
(new RemoveFileCommandBuilder($container, $file['persistence']))->build($key);
}
} | {@inheritdoc} | https://github.com/BenGorFile/FileBundle/blob/82c1fa952e7e7b7a188141a34053ab612b699a21/src/BenGorFile/FileBundle/DependencyInjection/Compiler/ApplicationCommandsPass.php#L35-L45 |
gorriecoe/silverstripe-gtm | src/extensions/GTMConfig.php | GTMConfig.updateCMSFields | public function updateCMSFields(FieldList $fields)
{
$fields->addFieldsToTab(
'Root.Main',
array(
TextField::create(
'GoogleTagManager',
_t(__CLASS__ . '.ID', 'Tag manager ID')
)
->setAttribute(
"placeholder",
"GTM-******"
),
)
);
return $fields;
} | php | public function updateCMSFields(FieldList $fields)
{
$fields->addFieldsToTab(
'Root.Main',
array(
TextField::create(
'GoogleTagManager',
_t(__CLASS__ . '.ID', 'Tag manager ID')
)
->setAttribute(
"placeholder",
"GTM-******"
),
)
);
return $fields;
} | Update Fields
@return FieldList | https://github.com/gorriecoe/silverstripe-gtm/blob/a67c3acd41680f9ef4ae99fc85864264d4bc8200/src/extensions/GTMConfig.php#L28-L44 |
iwyg/xmlconf | src/Thapp/XmlConf/Examples/Sections/SectionsSimpleXml.php | SectionsSimpleXml.getSections | public function getSections()
{
$sections = array();
foreach ($this->section as $sectionObj) {
$section = new Section;
foreach (static::$sectionattributes as $attribute) {
$section->{$attribute} = $this->getValue((string)$sectionObj->attributes()->{$attribute});
}
$fields = $sectionObj->fields;
$section->setFields($this->getFields($fields));
$sections[$section->id] = $section;
}
return $sections;
} | php | public function getSections()
{
$sections = array();
foreach ($this->section as $sectionObj) {
$section = new Section;
foreach (static::$sectionattributes as $attribute) {
$section->{$attribute} = $this->getValue((string)$sectionObj->attributes()->{$attribute});
}
$fields = $sectionObj->fields;
$section->setFields($this->getFields($fields));
$sections[$section->id] = $section;
}
return $sections;
} | getSections
@access public
@return array | https://github.com/iwyg/xmlconf/blob/1d8a657073f3fd46dacfb6bf5d173f9d5283661b/src/Thapp/XmlConf/Examples/Sections/SectionsSimpleXml.php#L60-L79 |
iwyg/xmlconf | src/Thapp/XmlConf/Examples/Sections/SectionsSimpleXml.php | SectionsSimpleXml.getFields | protected function getFields(&$sectionObj)
{
$fields = array();
foreach ($sectionObj->field as $fieldObj) {
$field = array();
foreach (static::$fieldattributes as $attribute) {
$field[$attribute] = $this->getValue((string)$fieldObj->attributes()->{$attribute});
}
$fields[] = $field;
}
return $fields;
} | php | protected function getFields(&$sectionObj)
{
$fields = array();
foreach ($sectionObj->field as $fieldObj) {
$field = array();
foreach (static::$fieldattributes as $attribute) {
$field[$attribute] = $this->getValue((string)$fieldObj->attributes()->{$attribute});
}
$fields[] = $field;
}
return $fields;
} | getFields
@param SectionXML $fields
@access protected
@return array | https://github.com/iwyg/xmlconf/blob/1d8a657073f3fd46dacfb6bf5d173f9d5283661b/src/Thapp/XmlConf/Examples/Sections/SectionsSimpleXml.php#L88-L104 |
iwyg/xmlconf | src/Thapp/XmlConf/Examples/Sections/SectionsSimpleXml.php | SectionsSimpleXml.getValue | protected function getValue($value)
{
if (is_numeric($value)) {
return false !== strpos('.', $value) ? (double)$value : (int)$value;
}
return $value;
} | php | protected function getValue($value)
{
if (is_numeric($value)) {
return false !== strpos('.', $value) ? (double)$value : (int)$value;
}
return $value;
} | getValue
@param mixed $value
@access protected
@return string|int|double | https://github.com/iwyg/xmlconf/blob/1d8a657073f3fd46dacfb6bf5d173f9d5283661b/src/Thapp/XmlConf/Examples/Sections/SectionsSimpleXml.php#L113-L119 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Framework/Media/Image/Action/Dal/UpdateAction.php | UpdateAction.init | public function init(ImageInterface $image = null)
{
if (!$image) {
return $this;
}
$this->image = $image;
return $this
->setName($image->getName())
->setTitle($image->getTitle())
->setHeadline($image->getHeadline())
->setAlt($image->getAlt())
->setExternalLink($image->getExternalLink())
->setTags(implode(', ', $image->getTags()))
;
} | php | public function init(ImageInterface $image = null)
{
if (!$image) {
return $this;
}
$this->image = $image;
return $this
->setName($image->getName())
->setTitle($image->getTitle())
->setHeadline($image->getHeadline())
->setAlt($image->getAlt())
->setExternalLink($image->getExternalLink())
->setTags(implode(', ', $image->getTags()))
;
} | {@inheritdoc} | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Framework/Media/Image/Action/Dal/UpdateAction.php#L17-L33 |
BenGorFile/FileBundle | src/BenGorFile/FileBundle/BenGorFileBundle.php | BenGorFileBundle.build | public function build(ContainerBuilder $container)
{
$container->addCompilerPass(new DomainServicesPass(), PassConfig::TYPE_OPTIMIZE);
$container->addCompilerPass(new SqlServicesPass(), PassConfig::TYPE_OPTIMIZE);
$container->addCompilerPass(new ApplicationCommandsPass(), PassConfig::TYPE_OPTIMIZE);
$container->addCompilerPass(new ApplicationDataTransformersPass(), PassConfig::TYPE_OPTIMIZE);
$container->addCompilerPass(new ApplicationQueriesPass(), PassConfig::TYPE_OPTIMIZE);
$container->addCompilerPass(new RoutesPass(), PassConfig::TYPE_OPTIMIZE);
$container->addCompilerPass(new TwigPass(), PassConfig::TYPE_OPTIMIZE);
$this->buildLoadableBundles($container);
} | php | public function build(ContainerBuilder $container)
{
$container->addCompilerPass(new DomainServicesPass(), PassConfig::TYPE_OPTIMIZE);
$container->addCompilerPass(new SqlServicesPass(), PassConfig::TYPE_OPTIMIZE);
$container->addCompilerPass(new ApplicationCommandsPass(), PassConfig::TYPE_OPTIMIZE);
$container->addCompilerPass(new ApplicationDataTransformersPass(), PassConfig::TYPE_OPTIMIZE);
$container->addCompilerPass(new ApplicationQueriesPass(), PassConfig::TYPE_OPTIMIZE);
$container->addCompilerPass(new RoutesPass(), PassConfig::TYPE_OPTIMIZE);
$container->addCompilerPass(new TwigPass(), PassConfig::TYPE_OPTIMIZE);
$this->buildLoadableBundles($container);
} | {@inheritdoc} | https://github.com/BenGorFile/FileBundle/blob/82c1fa952e7e7b7a188141a34053ab612b699a21/src/BenGorFile/FileBundle/BenGorFileBundle.php#L36-L47 |
devsdmf/annotations | src/Devsdmf/Annotations/Adapter/ReflectionFunctionAbstractAdapter.php | ReflectionFunctionAbstractAdapter.getDocBlock | public function getDocBlock($reflector)
{
if (!$reflector instanceof \ReflectionFunctionAbstract) {
throw new InvalidReflectorException(sprintf('Invalid reflector to $s, expected $s instance, $s given.',
get_class($this),'ReflectionFunctionAbstract',get_class($reflector)));
}
return $reflector->getDocComment();
} | php | public function getDocBlock($reflector)
{
if (!$reflector instanceof \ReflectionFunctionAbstract) {
throw new InvalidReflectorException(sprintf('Invalid reflector to $s, expected $s instance, $s given.',
get_class($this),'ReflectionFunctionAbstract',get_class($reflector)));
}
return $reflector->getDocComment();
} | {@inheritdoc} | https://github.com/devsdmf/annotations/blob/e543ff84db3ecedf56a149c1be0fdd36dbb9e62f/src/Devsdmf/Annotations/Adapter/ReflectionFunctionAbstractAdapter.php#L28-L36 |
makinacorpus/drupal-plusql | src/ConstraintTrait.php | ConstraintTrait.getSqlName | public function getSqlName(string $table, string $name): string
{
return $table . '_' . $this->getType() . '_' . $name;
} | php | public function getSqlName(string $table, string $name): string
{
return $table . '_' . $this->getType() . '_' . $name;
} | Get SQL constraint name | https://github.com/makinacorpus/drupal-plusql/blob/7182d653a117d53b6bb3e3edd53f07af11ff5d43/src/ConstraintTrait.php#L43-L46 |
makinacorpus/drupal-plusql | src/ConstraintTrait.php | ConstraintTrait.exists | final public function exists(string $table, string $name): bool
{
return $this->existsWithName($table, $this->getSqlName($table, $name));
} | php | final public function exists(string $table, string $name): bool
{
return $this->existsWithName($table, $this->getSqlName($table, $name));
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-plusql/blob/7182d653a117d53b6bb3e3edd53f07af11ff5d43/src/ConstraintTrait.php#L56-L59 |
makinacorpus/drupal-plusql | src/ConstraintTrait.php | ConstraintTrait.existsUnsafe | final public function existsUnsafe(string $table, string $name): bool
{
return $this->existsWithName($table, $name);
} | php | final public function existsUnsafe(string $table, string $name): bool
{
return $this->existsWithName($table, $name);
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-plusql/blob/7182d653a117d53b6bb3e3edd53f07af11ff5d43/src/ConstraintTrait.php#L64-L67 |
makinacorpus/drupal-plusql | src/ConstraintTrait.php | ConstraintTrait.drop | final public function drop(string $table, string $name)
{
$this->dropWithName($table, $this->getSqlName($table, $name));
} | php | final public function drop(string $table, string $name)
{
$this->dropWithName($table, $this->getSqlName($table, $name));
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-plusql/blob/7182d653a117d53b6bb3e3edd53f07af11ff5d43/src/ConstraintTrait.php#L83-L86 |
noizu/fragmented-keys | src/NoizuLabs/FragmentedKeys/Key/Standard.php | Standard.getKeyStr | public function getKeyStr($hash = true)
{
$key = $this->key . self::$INDEX_SEPERATOR . $this->groupId . self::$TAG_SEPERATOR . implode(self::$TAG_SEPERATOR, $this->gatherTags());
if($hash) {
$key = md5($key);
}
return $key;
} | php | public function getKeyStr($hash = true)
{
$key = $this->key . self::$INDEX_SEPERATOR . $this->groupId . self::$TAG_SEPERATOR . implode(self::$TAG_SEPERATOR, $this->gatherTags());
if($hash) {
$key = md5($key);
}
return $key;
} | calculate composite key
@param bool $hash use true to return md5 (memcache friendly) key or use false to return raw key for visual inspection.
@return string | https://github.com/noizu/fragmented-keys/blob/5eccc8553ba11920d6d84e20e89b50c28d941b45/src/NoizuLabs/FragmentedKeys/Key/Standard.php#L44-L51 |
noizu/fragmented-keys | src/NoizuLabs/FragmentedKeys/Key/Standard.php | Standard.GatherGroupVersions | protected function GatherGroupVersions() {
$tags = array_keys($this->keyGroups);
$handlers = array();
foreach($tags as $tag) {
$handler = $this->keyGroups[$tag]->getCacheHandler()->getGroupName();
if(!array_key_exists($handler, $handlers)) {
$handlers[$handler] = array();
}
$handlers[$handler][] = $tag;
}
$tags = array();
foreach($handlers as $handler => $group_tags) {
foreach ($group_tags as $group_tag) {
if($this->keyGroups[$group_tag]->DelegateMemcacheQuery($handler) == false) {
unset($group_tag);
}
}
if(!empty($group_tags)) {
$cacheHandler = $this->keyGroups[$group_tags[0]]->getCacheHandler();
$r = $cacheHandler->getMulti($group_tags);
if($r) {
$tags = array_merge($tags, $r);
}
}
}
foreach($this->keyGroups as $key => &$group) {
if(array_key_exists($key, $tags))
{
$group->setTagVersion($tags[$key],false);
} else {
$group->ResetTagVersion();
}
}
} | php | protected function GatherGroupVersions() {
$tags = array_keys($this->keyGroups);
$handlers = array();
foreach($tags as $tag) {
$handler = $this->keyGroups[$tag]->getCacheHandler()->getGroupName();
if(!array_key_exists($handler, $handlers)) {
$handlers[$handler] = array();
}
$handlers[$handler][] = $tag;
}
$tags = array();
foreach($handlers as $handler => $group_tags) {
foreach ($group_tags as $group_tag) {
if($this->keyGroups[$group_tag]->DelegateMemcacheQuery($handler) == false) {
unset($group_tag);
}
}
if(!empty($group_tags)) {
$cacheHandler = $this->keyGroups[$group_tags[0]]->getCacheHandler();
$r = $cacheHandler->getMulti($group_tags);
if($r) {
$tags = array_merge($tags, $r);
}
}
}
foreach($this->keyGroups as $key => &$group) {
if(array_key_exists($key, $tags))
{
$group->setTagVersion($tags[$key],false);
} else {
$group->ResetTagVersion();
}
}
} | Bulk Fetch tag-instance versions.
While it would be architecturally cleaner to gather group versions from a KeyGroup function call
the use of memcache/apc multiget helps us avoid some bottle-necking produced by the increased number of key-versions we
need to look-up when using this fragmented key system. | https://github.com/noizu/fragmented-keys/blob/5eccc8553ba11920d6d84e20e89b50c28d941b45/src/NoizuLabs/FragmentedKeys/Key/Standard.php#L59-L97 |
PHPColibri/framework | Database/ModelMultiCollection.php | ModelMultiCollection.instantiateItem | protected function instantiateItem(array $row)
{
if ( ! count($this->intermediateFields)) {
return parent::instantiateItem($row);
}
$itemAttributes = Arr::only($row, $this->itemFields);
$intermediateAttributes = Arr::only($row, $this->intermediateFields);
/** @var \Colibri\Database\Model $item */
$item = new static::$itemClass($itemAttributes);
return $item->setIntermediate($intermediateAttributes);
} | php | protected function instantiateItem(array $row)
{
if ( ! count($this->intermediateFields)) {
return parent::instantiateItem($row);
}
$itemAttributes = Arr::only($row, $this->itemFields);
$intermediateAttributes = Arr::only($row, $this->intermediateFields);
/** @var \Colibri\Database\Model $item */
$item = new static::$itemClass($itemAttributes);
return $item->setIntermediate($intermediateAttributes);
} | @param array $row
@return \Colibri\Database\Model | https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Database/ModelMultiCollection.php#L105-L117 |
PHPColibri/framework | Database/ModelMultiCollection.php | ModelMultiCollection.addToDb | protected function addToDb(Database\Model &$object)
{
$this->FKValue[1] = $object->id;
$this->doQuery($this->addToDbQuery());
} | php | protected function addToDb(Database\Model &$object)
{
$this->FKValue[1] = $object->id;
$this->doQuery($this->addToDbQuery());
} | @param \Colibri\Database\Model $object
@throws \Colibri\Database\DbException
@throws \Colibri\Database\Exception\SqlException
@throws \UnexpectedValueException | https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Database/ModelMultiCollection.php#L129-L133 |
digipolisgent/robo-digipolis-deploy | src/PushPackage.php | PushPackage.run | public function run()
{
$ssh = call_user_func(
[$this->sshFactory, 'create'],
$this->host,
$this->port,
$this->timeout
);
$this->printTaskInfo(sprintf(
'Establishing SFTP connection to %s on port %s.',
$this->host,
$this->port
));
$ssh->login($this->auth);
$mkdir = 'mkdir -p ' . $this->destinationFolder;
$this->printTaskInfo(sprintf(
'%s@%s:~$ %s',
$this->auth->getUser(),
$this->host,
$mkdir
));
$mkdirResult = $ssh->exec($mkdir, [$this, 'printTaskInfo']);
if ($mkdirResult !== false && $ssh->getExitStatus() !== 0) {
$errorMessage = sprintf(
'Could not execute %s on %s on port %s with message: %s',
$mkdir,
$this->host,
$this->port,
$ssh->getStdError()
);
return Result::error($this, $errorMessage);
}
$scp = call_user_func(
[$this->scpFactory, 'create'],
$this->host,
$this->auth,
$this->port,
$this->timeout
);
$this->printTaskInfo(sprintf(
'Uploading file %s on %s on port %s to directory %s.',
$this->package,
$this->host,
$this->port,
$this->destinationFolder
));
$uploadResult = $scp->put(
$this->destinationFolder . DIRECTORY_SEPARATOR . basename($this->package),
$this->package,
ScpAdapterInterface::SOURCE_LOCAL_FILE
);
if (!$uploadResult) {
$errorMessage = sprintf(
'Could not %s file %s on %s on port %s to directory %s.',
'upload',
$this->package,
$this->host,
$this->port,
$this->destinationFolder
);
return Result::error($this, $errorMessage);
}
$untar = 'cd ' . $this->destinationFolder .
' && tar -xzvf ' . basename($this->package) .
' && rm -rf ' . basename($this->package);
$this->printTaskInfo(sprintf(
'%s@%s:~$ %s',
$this->auth->getUser(),
$this->host,
$untar
));
$untarResult = $ssh->exec($untar, [$this, 'printTaskInfo']);
if ($untarResult === false || $ssh->getExitStatus() !== 0) {
$errorMessage = sprintf(
'Could not execute %s on %s on port %s with message: %s.',
$untar,
$this->host,
$this->port,
$ssh->getStdError()
);
return Result::error($this, $errorMessage);
}
return Result::success($this);
} | php | public function run()
{
$ssh = call_user_func(
[$this->sshFactory, 'create'],
$this->host,
$this->port,
$this->timeout
);
$this->printTaskInfo(sprintf(
'Establishing SFTP connection to %s on port %s.',
$this->host,
$this->port
));
$ssh->login($this->auth);
$mkdir = 'mkdir -p ' . $this->destinationFolder;
$this->printTaskInfo(sprintf(
'%s@%s:~$ %s',
$this->auth->getUser(),
$this->host,
$mkdir
));
$mkdirResult = $ssh->exec($mkdir, [$this, 'printTaskInfo']);
if ($mkdirResult !== false && $ssh->getExitStatus() !== 0) {
$errorMessage = sprintf(
'Could not execute %s on %s on port %s with message: %s',
$mkdir,
$this->host,
$this->port,
$ssh->getStdError()
);
return Result::error($this, $errorMessage);
}
$scp = call_user_func(
[$this->scpFactory, 'create'],
$this->host,
$this->auth,
$this->port,
$this->timeout
);
$this->printTaskInfo(sprintf(
'Uploading file %s on %s on port %s to directory %s.',
$this->package,
$this->host,
$this->port,
$this->destinationFolder
));
$uploadResult = $scp->put(
$this->destinationFolder . DIRECTORY_SEPARATOR . basename($this->package),
$this->package,
ScpAdapterInterface::SOURCE_LOCAL_FILE
);
if (!$uploadResult) {
$errorMessage = sprintf(
'Could not %s file %s on %s on port %s to directory %s.',
'upload',
$this->package,
$this->host,
$this->port,
$this->destinationFolder
);
return Result::error($this, $errorMessage);
}
$untar = 'cd ' . $this->destinationFolder .
' && tar -xzvf ' . basename($this->package) .
' && rm -rf ' . basename($this->package);
$this->printTaskInfo(sprintf(
'%s@%s:~$ %s',
$this->auth->getUser(),
$this->host,
$untar
));
$untarResult = $ssh->exec($untar, [$this, 'printTaskInfo']);
if ($untarResult === false || $ssh->getExitStatus() !== 0) {
$errorMessage = sprintf(
'Could not execute %s on %s on port %s with message: %s.',
$untar,
$this->host,
$this->port,
$ssh->getStdError()
);
return Result::error($this, $errorMessage);
}
return Result::success($this);
} | {@inheritdoc} | https://github.com/digipolisgent/robo-digipolis-deploy/blob/fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab/src/PushPackage.php#L210-L294 |
yangyao/queue | src/Adapter/AdapterRedis.php | AdapterRedis.publish | public function publish($queueName, $queueData )
{
$time = time();
$data = [
'queue_name' => $queueData['queue_name'],
'worker' => $queueData['worker'],
'params' => $queueData['params'],
'create_time' => $time,
];
return $this->pushRaw($this->createPayload($data), $queueName);
} | php | public function publish($queueName, $queueData )
{
$time = time();
$data = [
'queue_name' => $queueData['queue_name'],
'worker' => $queueData['worker'],
'params' => $queueData['params'],
'create_time' => $time,
];
return $this->pushRaw($this->createPayload($data), $queueName);
} | 创建一个队列任务
@param string $queueName 队列标示
@param array $data 执行队列参数
@return mixed | https://github.com/yangyao/queue/blob/334388bbad985f1f7834a5897d1fc59acd11c60f/src/Adapter/AdapterRedis.php#L28-L38 |
yangyao/queue | src/Adapter/AdapterRedis.php | AdapterRedis.pushRaw | public function pushRaw($payload, $queueName )
{
$this->__handler->rPush($queueName, $payload);
return Arr::get(json_decode($payload, true), 'id');
} | php | public function pushRaw($payload, $queueName )
{
$this->__handler->rPush($queueName, $payload);
return Arr::get(json_decode($payload, true), 'id');
} | 将队列保存到redis
@param string $payload
@param string $queue
@return mixed | https://github.com/yangyao/queue/blob/334388bbad985f1f7834a5897d1fc59acd11c60f/src/Adapter/AdapterRedis.php#L47-L52 |
yangyao/queue | src/Adapter/AdapterRedis.php | AdapterRedis.get | public function get($queueName)
{
if (! is_null($this->expire) )
{
$this->migrateAllExpiredJobs($queueName);
}
$objectReids = $this->__handler;
$objectReids->loadScripts('queueGet');
$queueData = $objectReids->queueGet($queueName, $queueName.':reserved', time() + $this->expire);
if( ! is_null($queueData) )
{
return new system_queue_message_redis($queueData);
}
return false;
} | php | public function get($queueName)
{
if (! is_null($this->expire) )
{
$this->migrateAllExpiredJobs($queueName);
}
$objectReids = $this->__handler;
$objectReids->loadScripts('queueGet');
$queueData = $objectReids->queueGet($queueName, $queueName.':reserved', time() + $this->expire);
if( ! is_null($queueData) )
{
return new system_queue_message_redis($queueData);
}
return false;
} | 获取一个队列任务ID
@param string $queueName
@return mixed 队列任务数据 | https://github.com/yangyao/queue/blob/334388bbad985f1f7834a5897d1fc59acd11c60f/src/Adapter/AdapterRedis.php#L60-L78 |
yangyao/queue | src/Adapter/AdapterRedis.php | AdapterRedis.ack | public function ack($queueMessage)
{
$queueName = $queueMessage->getQueueName();
$queueData = $queueMessage->getQueueData();
return $this->__handler->zrem($queueName.':reserved', $queueData);
} | php | public function ack($queueMessage)
{
$queueName = $queueMessage->getQueueName();
$queueData = $queueMessage->getQueueData();
return $this->__handler->zrem($queueName.':reserved', $queueData);
} | 确认消息已经被消费.
@param string $queueData
@return void | https://github.com/yangyao/queue/blob/334388bbad985f1f7834a5897d1fc59acd11c60f/src/Adapter/AdapterRedis.php#L86-L92 |
yangyao/queue | src/Adapter/AdapterRedis.php | AdapterRedis.migrateExpiredJobs | public function migrateExpiredJobs($from, $to)
{
$options = ['cas' => true, 'watch' => $from, 'retry' => 10];
$this->__handler->transaction($options, function ($transaction) use ($from, $to) {
$queueData = $this->getExpiredJobs(
$transaction, $from, $time = time()
);
if (count($queueData) > 0)
{
$this->removeExpiredJobs($transaction, $from, $time);
$this->pushExpiredJobsOntoNewQueue($transaction, $to, $queueData);
}
});
} | php | public function migrateExpiredJobs($from, $to)
{
$options = ['cas' => true, 'watch' => $from, 'retry' => 10];
$this->__handler->transaction($options, function ($transaction) use ($from, $to) {
$queueData = $this->getExpiredJobs(
$transaction, $from, $time = time()
);
if (count($queueData) > 0)
{
$this->removeExpiredJobs($transaction, $from, $time);
$this->pushExpiredJobsOntoNewQueue($transaction, $to, $queueData);
}
});
} | 将处理失败的或者处理超时的队列重新加入到队列中
@param string $from
@param string $to
@return void | https://github.com/yangyao/queue/blob/334388bbad985f1f7834a5897d1fc59acd11c60f/src/Adapter/AdapterRedis.php#L132-L149 |
yangyao/queue | src/Adapter/AdapterRedis.php | AdapterRedis.createPayload | protected function createPayload($data = '')
{
$payload = $this->setMeta($data, 'id', $this->getRandomId());
return $this->setMeta($payload, 'attempts', 1);
} | php | protected function createPayload($data = '')
{
$payload = $this->setMeta($data, 'id', $this->getRandomId());
return $this->setMeta($payload, 'attempts', 1);
} | 创建队列执行参数,数组转为字符串
@param mixed $data
@return string | https://github.com/yangyao/queue/blob/334388bbad985f1f7834a5897d1fc59acd11c60f/src/Adapter/AdapterRedis.php#L198-L203 |
ekyna/AdminBundle | Pool/ConfigurationFactory.php | ConfigurationFactory.createConfiguration | public function createConfiguration($prefix, $resourceName, $resourceClass, array $templateList, $eventClass = null, $parentId = null)
{
return new Configuration(
$prefix,
$resourceName,
$resourceClass,
$templateList,
$eventClass,
$parentId
);
} | php | public function createConfiguration($prefix, $resourceName, $resourceClass, array $templateList, $eventClass = null, $parentId = null)
{
return new Configuration(
$prefix,
$resourceName,
$resourceClass,
$templateList,
$eventClass,
$parentId
);
} | Creates and register a configuration
@param string $prefix
@param string $resourceName
@param string $resourceClass
@param array $templateList
@param string $eventClass
@param string $parentId
@return \Ekyna\Bundle\AdminBundle\Pool\Configuration | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Pool/ConfigurationFactory.php#L24-L34 |
Boolive/Core | data/stores/MySQLStore.php | MySQLStore.write | function write($entity)
{
// @todo
// Смена родителя/прототипа требует соответсвующие сдвиги в таблице отношений
// При смене uri нужно обновить uri подчиненных
$attr = $entity->attributes();
// Локальные id
$attr['parent'] = isset($attr['parent']) ? $this->localId($attr['parent']) : 0;
$attr['proto'] = isset($attr['proto']) ? $this->localId($attr['proto']) : 0;
$attr['author'] = isset($attr['author']) ? $this->localId($attr['author']) : 0;//$this->localId(Auth::get_user()->uri());
// Подбор уникального имени, если указана необходимость в этом
if ($entity->is_changed('uri') || !$entity->is_exists()) {
$q = $this->db->prepare('SELECT 1 FROM {objects} WHERE parent=? AND `name`=? LIMIT 0,1');
$q->execute(array($attr['parent'], $attr['name']));
if ($q->fetch()){
//Выбор записи по шаблону имени с самым большим префиксом
$q = $this->db->prepare('SELECT `name` FROM {objects} WHERE parent=? AND `name` REGEXP ? ORDER BY CAST((SUBSTRING_INDEX(`name`, "_", -1)+1) AS SIGNED) DESC LIMIT 0,1');
$q->execute(array($attr['parent'], '^'.$attr['name'].'(_[0-9]+)?$'));
if ($row = $q->fetch(DB::FETCH_ASSOC)){
preg_match('|^'.preg_quote($attr['name']).'(?:_([0-9]+))?$|u', $row['name'], $match);
$attr['name'].= '_'.(isset($match[1]) ? ($match[1]+1) : 1);
}
}
$entity->name($attr['name']);
$attr['uri'] = $entity->uri();
}
Buffer::set_entity($entity);
// Локальный идентификатор объекта
$attr['id'] = $this->localId($entity->uri($entity->is_exists()), true, $new_id);
// Если смена файла, то удалить текущий файл
if ($entity->is_changed('file')){
$current_file = $entity->changes('file');
if (is_string($current_file)) File::delete($entity->dir(true).$current_file);
}
// Если привязан файл
if (!$entity->is_default_file()){
if ($entity->is_file()){
$file_attache = $entity->file();
if (is_array($file_attache)){
// Загрузка файла
if (!($attr['file'] = Data::save_file($entity, $file_attache))){
$attr['file'] = '';
}
}else{
$attr['file'] = basename($file_attache);
}
}else{
// файла нет, но нужно отменить наследование файла
$attr['file'] = '';
}
}else{
$attr['file'] = '';
}
// Уникальность order
// Если изменено на конкретное значение (не максимальное)
if ($attr['order'] != Entity::MAX_ORDER && (!$entity->is_exists() || $entity->is_changed('order'))){
// Проверка, занят или нет новый order
$q = $this->db->prepare('SELECT 1 FROM {objects} WHERE `parent`=? AND `order`=?');
$q->execute(array($attr['parent'], $attr['order']));
if ($q->fetch()){
// Сдвиг order существующих записей, чтоб освободить значение для новой
$q = $this->db->prepare('
UPDATE {objects} SET `order` = `order`+1
WHERE `parent`=? AND `order`>=?'
);
$q->execute(array($attr['parent'], $attr['order']));
}
unset($q);
}else
// Новое максимальное значение для order, если объект новый или явно указано order=null
if (!$entity->is_exists() || $attr['order'] == Entity::MAX_ORDER){
// Порядковое значение вычисляется от максимального существующего
$q = $this->db->prepare('SELECT MAX(`order`) m FROM {objects} WHERE parent=?');
$q->execute(array($attr['parent']));
if ($row = $q->fetch(DB::FETCH_ASSOC)){
$attr['order'] = $row['m']+1;
}
unset($q);
}
$this->db->beginTransaction();
// Если новое имя или родитель, то обновить свой URI и URI подчиненных
if ($entity->is_changed('name') || $entity->is_changed('parent')){
if ($entity->is_exists()){
$current_uri = $entity->uri(true);
$current_name = $entity->is_changed('name')? $entity->changes('name') : $attr['name'];
// Текущий URI
$names = F::splitRight('/', $current_uri, true);
$uri = (isset($names[0])?$names[0].'/':'').$current_name;
// Новый URI
$names = F::splitRight('/', $attr['uri'], true);
$uri_new = (isset($names[0])?$names[0].'/':'').$attr['name'];
$entity->change('uri', $uri_new);
// @todo Обновление URI подчиенных в базе
// нужно знать текущий уковень вложенности и локальный id
//
// $q = $this->db->prepare('UPDATE {ids}, {parents} SET {ids}.uri = CONCAT(?, SUBSTRING(uri, ?)) WHERE {parents}.parent_id = ? AND {parents}.object_id = {ids}.id AND {parents}.is_delete=0');
// $v = array($uri_new, mb_strlen($uri)+1, $attr['id']);
// $q->execute($v);
// // Обновление уровней вложенностей в objects
// if (!empty($current) && $current['parent']!=$attr['parent']){
// $dl = $attr['parent_cnt'] - $current['parent_cnt'];
// $q = $this->db->prepare('UPDATE {objects}, {parents} SET parent_cnt = parent_cnt + ? WHERE {parents}.parent_id = ? AND {parents}.object_id = {objects}.id AND {parents}.is_delete=0');
// $q->execute(array($dl, $attr['id']));
// // Обновление отношений
// $this->makeParents($attr['id'], $attr['parent'], $dl, true);
// }
if (!empty($uri) && is_dir(DIR.$uri)){
// Переименование/перемещение папки объекта
$dir = DIR.$uri_new;
File::rename(DIR.$uri, $dir);
if ($entity->is_changed('name')){
// Переименование файла класса
File::rename($dir.'/'.$current_name.'.php', $dir.'/'.$attr['name'].'.php');
// Переименование .info файла
File::rename($dir.'/'.$current_name.'.info', $dir.'/'.$attr['name'].'.info');
}
}
unset($q);
}
// Обновить URI подчиненных объектов не фиксируя изменения
$entity->updateChildrenUri();
}
// Если значение больше 255
if (mb_strlen($attr['value']) > 255){
$q = $this->db->prepare('
INSERT INTO {text} (`id`, `value`)
VALUES (:id, :value)
ON DUPLICATE KEY UPDATE `value` = :value
');
$q->execute(array(':id' => $attr['id'], ':value' => $attr['value']));
$attr['value'] = mb_substr($attr['value'],0,255);
$attr['is_text'] = 1;
}else{
$attr['is_text'] = 0;
}
// Запись
$attr_names = array(
'id', 'parent', 'proto', 'author', 'order', 'name', 'value', 'file', 'is_text',
'is_draft', 'is_hidden', 'is_link', 'is_mandatory', 'is_property', 'is_relative',
'is_default_value', 'is_default_logic', 'created', 'updated'
);
$cnt = sizeof($attr_names);
// Запись объекта (создание или обновление при наличии)
// Объект идентифицируется по id
if (!$entity->is_exists()){
$q = $this->db->prepare('
INSERT INTO {objects} (`'.implode('`, `', $attr_names).'`)
VALUES ('.str_repeat('?,', $cnt-1).'?)
ON DUPLICATE KEY UPDATE `'.implode('`=?, `', $attr_names).'`=?
');
$i = 0;
foreach ($attr_names as $name){
$value = $attr[$name];
$i++;
$type = is_int($value)? DB::PARAM_INT : (is_bool($value) ? DB::PARAM_BOOL : (is_null($value)? DB::PARAM_NULL : DB::PARAM_STR));
$q->bindValue($i, $value, $type);
$q->bindValue($i+$cnt, $value, $type);
}
$q->execute();
}else{
$q = $this->db->prepare('
UPDATE {objects} SET `'.implode('`=?, `', $attr_names).'`=? WHERE id = ?
');
$i = 0;
foreach ($attr_names as $name){
$value = $attr[$name];
$i++;
$type = is_int($value)? DB::PARAM_INT : (is_bool($value) ? DB::PARAM_BOOL : (is_null($value)? DB::PARAM_NULL : DB::PARAM_STR));
$q->bindValue($i, $value, $type);
}
$q->bindValue(++$i, $attr['id']);
$q->execute();
}
$this->db->commit();
foreach ($entity->children() as $child){
Data::write($child);
}
return true;
} | php | function write($entity)
{
// @todo
// Смена родителя/прототипа требует соответсвующие сдвиги в таблице отношений
// При смене uri нужно обновить uri подчиненных
$attr = $entity->attributes();
// Локальные id
$attr['parent'] = isset($attr['parent']) ? $this->localId($attr['parent']) : 0;
$attr['proto'] = isset($attr['proto']) ? $this->localId($attr['proto']) : 0;
$attr['author'] = isset($attr['author']) ? $this->localId($attr['author']) : 0;//$this->localId(Auth::get_user()->uri());
// Подбор уникального имени, если указана необходимость в этом
if ($entity->is_changed('uri') || !$entity->is_exists()) {
$q = $this->db->prepare('SELECT 1 FROM {objects} WHERE parent=? AND `name`=? LIMIT 0,1');
$q->execute(array($attr['parent'], $attr['name']));
if ($q->fetch()){
//Выбор записи по шаблону имени с самым большим префиксом
$q = $this->db->prepare('SELECT `name` FROM {objects} WHERE parent=? AND `name` REGEXP ? ORDER BY CAST((SUBSTRING_INDEX(`name`, "_", -1)+1) AS SIGNED) DESC LIMIT 0,1');
$q->execute(array($attr['parent'], '^'.$attr['name'].'(_[0-9]+)?$'));
if ($row = $q->fetch(DB::FETCH_ASSOC)){
preg_match('|^'.preg_quote($attr['name']).'(?:_([0-9]+))?$|u', $row['name'], $match);
$attr['name'].= '_'.(isset($match[1]) ? ($match[1]+1) : 1);
}
}
$entity->name($attr['name']);
$attr['uri'] = $entity->uri();
}
Buffer::set_entity($entity);
// Локальный идентификатор объекта
$attr['id'] = $this->localId($entity->uri($entity->is_exists()), true, $new_id);
// Если смена файла, то удалить текущий файл
if ($entity->is_changed('file')){
$current_file = $entity->changes('file');
if (is_string($current_file)) File::delete($entity->dir(true).$current_file);
}
// Если привязан файл
if (!$entity->is_default_file()){
if ($entity->is_file()){
$file_attache = $entity->file();
if (is_array($file_attache)){
// Загрузка файла
if (!($attr['file'] = Data::save_file($entity, $file_attache))){
$attr['file'] = '';
}
}else{
$attr['file'] = basename($file_attache);
}
}else{
// файла нет, но нужно отменить наследование файла
$attr['file'] = '';
}
}else{
$attr['file'] = '';
}
// Уникальность order
// Если изменено на конкретное значение (не максимальное)
if ($attr['order'] != Entity::MAX_ORDER && (!$entity->is_exists() || $entity->is_changed('order'))){
// Проверка, занят или нет новый order
$q = $this->db->prepare('SELECT 1 FROM {objects} WHERE `parent`=? AND `order`=?');
$q->execute(array($attr['parent'], $attr['order']));
if ($q->fetch()){
// Сдвиг order существующих записей, чтоб освободить значение для новой
$q = $this->db->prepare('
UPDATE {objects} SET `order` = `order`+1
WHERE `parent`=? AND `order`>=?'
);
$q->execute(array($attr['parent'], $attr['order']));
}
unset($q);
}else
// Новое максимальное значение для order, если объект новый или явно указано order=null
if (!$entity->is_exists() || $attr['order'] == Entity::MAX_ORDER){
// Порядковое значение вычисляется от максимального существующего
$q = $this->db->prepare('SELECT MAX(`order`) m FROM {objects} WHERE parent=?');
$q->execute(array($attr['parent']));
if ($row = $q->fetch(DB::FETCH_ASSOC)){
$attr['order'] = $row['m']+1;
}
unset($q);
}
$this->db->beginTransaction();
// Если новое имя или родитель, то обновить свой URI и URI подчиненных
if ($entity->is_changed('name') || $entity->is_changed('parent')){
if ($entity->is_exists()){
$current_uri = $entity->uri(true);
$current_name = $entity->is_changed('name')? $entity->changes('name') : $attr['name'];
// Текущий URI
$names = F::splitRight('/', $current_uri, true);
$uri = (isset($names[0])?$names[0].'/':'').$current_name;
// Новый URI
$names = F::splitRight('/', $attr['uri'], true);
$uri_new = (isset($names[0])?$names[0].'/':'').$attr['name'];
$entity->change('uri', $uri_new);
// @todo Обновление URI подчиенных в базе
// нужно знать текущий уковень вложенности и локальный id
//
// $q = $this->db->prepare('UPDATE {ids}, {parents} SET {ids}.uri = CONCAT(?, SUBSTRING(uri, ?)) WHERE {parents}.parent_id = ? AND {parents}.object_id = {ids}.id AND {parents}.is_delete=0');
// $v = array($uri_new, mb_strlen($uri)+1, $attr['id']);
// $q->execute($v);
// // Обновление уровней вложенностей в objects
// if (!empty($current) && $current['parent']!=$attr['parent']){
// $dl = $attr['parent_cnt'] - $current['parent_cnt'];
// $q = $this->db->prepare('UPDATE {objects}, {parents} SET parent_cnt = parent_cnt + ? WHERE {parents}.parent_id = ? AND {parents}.object_id = {objects}.id AND {parents}.is_delete=0');
// $q->execute(array($dl, $attr['id']));
// // Обновление отношений
// $this->makeParents($attr['id'], $attr['parent'], $dl, true);
// }
if (!empty($uri) && is_dir(DIR.$uri)){
// Переименование/перемещение папки объекта
$dir = DIR.$uri_new;
File::rename(DIR.$uri, $dir);
if ($entity->is_changed('name')){
// Переименование файла класса
File::rename($dir.'/'.$current_name.'.php', $dir.'/'.$attr['name'].'.php');
// Переименование .info файла
File::rename($dir.'/'.$current_name.'.info', $dir.'/'.$attr['name'].'.info');
}
}
unset($q);
}
// Обновить URI подчиненных объектов не фиксируя изменения
$entity->updateChildrenUri();
}
// Если значение больше 255
if (mb_strlen($attr['value']) > 255){
$q = $this->db->prepare('
INSERT INTO {text} (`id`, `value`)
VALUES (:id, :value)
ON DUPLICATE KEY UPDATE `value` = :value
');
$q->execute(array(':id' => $attr['id'], ':value' => $attr['value']));
$attr['value'] = mb_substr($attr['value'],0,255);
$attr['is_text'] = 1;
}else{
$attr['is_text'] = 0;
}
// Запись
$attr_names = array(
'id', 'parent', 'proto', 'author', 'order', 'name', 'value', 'file', 'is_text',
'is_draft', 'is_hidden', 'is_link', 'is_mandatory', 'is_property', 'is_relative',
'is_default_value', 'is_default_logic', 'created', 'updated'
);
$cnt = sizeof($attr_names);
// Запись объекта (создание или обновление при наличии)
// Объект идентифицируется по id
if (!$entity->is_exists()){
$q = $this->db->prepare('
INSERT INTO {objects} (`'.implode('`, `', $attr_names).'`)
VALUES ('.str_repeat('?,', $cnt-1).'?)
ON DUPLICATE KEY UPDATE `'.implode('`=?, `', $attr_names).'`=?
');
$i = 0;
foreach ($attr_names as $name){
$value = $attr[$name];
$i++;
$type = is_int($value)? DB::PARAM_INT : (is_bool($value) ? DB::PARAM_BOOL : (is_null($value)? DB::PARAM_NULL : DB::PARAM_STR));
$q->bindValue($i, $value, $type);
$q->bindValue($i+$cnt, $value, $type);
}
$q->execute();
}else{
$q = $this->db->prepare('
UPDATE {objects} SET `'.implode('`=?, `', $attr_names).'`=? WHERE id = ?
');
$i = 0;
foreach ($attr_names as $name){
$value = $attr[$name];
$i++;
$type = is_int($value)? DB::PARAM_INT : (is_bool($value) ? DB::PARAM_BOOL : (is_null($value)? DB::PARAM_NULL : DB::PARAM_STR));
$q->bindValue($i, $value, $type);
}
$q->bindValue(++$i, $attr['id']);
$q->execute();
}
$this->db->commit();
foreach ($entity->children() as $child){
Data::write($child);
}
return true;
} | Сохранение сущности
@param Entity $entity
@throws Error | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/stores/MySQLStore.php#L146-L340 |
Boolive/Core | data/stores/MySQLStore.php | MySQLStore.localId | function localId($uri, $create = true, &$is_new = false)
{
$is_new = false;
if (!is_string($uri)){
return 0;
}
// Из кэша
if (!isset($this->_local_ids)){
// if ($local_ids = Cache::get('mysqlstore/localids')){
// $this->_local_ids = json_decode($local_ids, true);
// }else{
$this->_local_ids = array();
// }
}
if (isset($this->_local_ids[$uri])) return $this->_local_ids[$uri];
// Поиск идентифкатора URI
$q = $this->db->prepare('SELECT id FROM {ids} WHERE `uri`=? LIMIT 0,1 FOR UPDATE');
$q->execute(array($uri));
if ($row = $q->fetch(DB::FETCH_ASSOC)){
$id = $row['id'];
$is_new = false;
$this->_local_ids[$uri] = $id;
$this->_global_ids[$id] = $uri;
// Отношение с родителями
$q = $this->db->prepare('SELECT * FROM {parents1} WHERE `id`=? LIMIT 0,1');
$q->execute(array($id));
if ($row = $q->fetch(DB::FETCH_ASSOC)){
$this->_parents_ids[$id] = F::array_clear($row);
}
// Отношение с прототипами
$q = $this->db->prepare('SELECT * FROM {protos1} WHERE `id`=? LIMIT 0,1');
$q->execute(array($id));
if ($row = $q->fetch(DB::FETCH_ASSOC)){
$this->_protos_ids[$id] = F::array_clear($row);
}
}else
if ($create){
// Создание идентификатора для URI
$q = $this->db->prepare('INSERT INTO {ids} (`id`, `uri`) VALUES (null, ?)');
$q->execute([$uri]);
$id = $this->db->lastInsertId('id');
$is_new = true;
$obj = Data::read($uri);
// Отношения с родителями
$this->makeParents($id, $this->localId($obj->parent()));
// Отношения с прототипами
$this->makeProtos($id, $this->localId($obj->proto()));
}else{
return 0;
}
unset($q);
return intval($id);
} | php | function localId($uri, $create = true, &$is_new = false)
{
$is_new = false;
if (!is_string($uri)){
return 0;
}
// Из кэша
if (!isset($this->_local_ids)){
// if ($local_ids = Cache::get('mysqlstore/localids')){
// $this->_local_ids = json_decode($local_ids, true);
// }else{
$this->_local_ids = array();
// }
}
if (isset($this->_local_ids[$uri])) return $this->_local_ids[$uri];
// Поиск идентифкатора URI
$q = $this->db->prepare('SELECT id FROM {ids} WHERE `uri`=? LIMIT 0,1 FOR UPDATE');
$q->execute(array($uri));
if ($row = $q->fetch(DB::FETCH_ASSOC)){
$id = $row['id'];
$is_new = false;
$this->_local_ids[$uri] = $id;
$this->_global_ids[$id] = $uri;
// Отношение с родителями
$q = $this->db->prepare('SELECT * FROM {parents1} WHERE `id`=? LIMIT 0,1');
$q->execute(array($id));
if ($row = $q->fetch(DB::FETCH_ASSOC)){
$this->_parents_ids[$id] = F::array_clear($row);
}
// Отношение с прототипами
$q = $this->db->prepare('SELECT * FROM {protos1} WHERE `id`=? LIMIT 0,1');
$q->execute(array($id));
if ($row = $q->fetch(DB::FETCH_ASSOC)){
$this->_protos_ids[$id] = F::array_clear($row);
}
}else
if ($create){
// Создание идентификатора для URI
$q = $this->db->prepare('INSERT INTO {ids} (`id`, `uri`) VALUES (null, ?)');
$q->execute([$uri]);
$id = $this->db->lastInsertId('id');
$is_new = true;
$obj = Data::read($uri);
// Отношения с родителями
$this->makeParents($id, $this->localId($obj->parent()));
// Отношения с прототипами
$this->makeProtos($id, $this->localId($obj->proto()));
}else{
return 0;
}
unset($q);
return intval($id);
} | Создание идентификатора для указанного URI.
Если объект с указанным URI существует, то будет возвращен его идентификатор
@param string $uri URI для которого нужно получить идентификатор
@param bool $create Создать идентификатор, если отсутствует?
@param bool $is_new Возвращаемый прзнак, был ли создан новый идентификатор?
@return int|null | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/stores/MySQLStore.php#L450-L502 |
Boolive/Core | data/stores/MySQLStore.php | MySQLStore.globalId | function globalId($id)
{
if (empty($id)){
return null;
}
if (isset($this->_global_ids[$id])){
return $this->_global_ids[$id];
}
// Поиск URI по идентифкатору
$q = $this->db->prepare('SELECT uri FROM {ids} WHERE `id`=? LIMIT 0,1 FOR UPDATE');
$q->execute([$id]);
if ($row = $q->fetch(DB::FETCH_ASSOC)){
$uri = $row['uri'];
$this->_local_ids[$uri] = intval($id);
$this->_global_ids[$id] = $uri;
return $uri;
}
return null;
} | php | function globalId($id)
{
if (empty($id)){
return null;
}
if (isset($this->_global_ids[$id])){
return $this->_global_ids[$id];
}
// Поиск URI по идентифкатору
$q = $this->db->prepare('SELECT uri FROM {ids} WHERE `id`=? LIMIT 0,1 FOR UPDATE');
$q->execute([$id]);
if ($row = $q->fetch(DB::FETCH_ASSOC)){
$uri = $row['uri'];
$this->_local_ids[$uri] = intval($id);
$this->_global_ids[$id] = $uri;
return $uri;
}
return null;
} | Опредление URI по локальному идентификатору
@param int $id Локальный идентификатор
@return null|string URI или null, если не найдено соответствий | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/stores/MySQLStore.php#L509-L527 |
Boolive/Core | data/stores/MySQLStore.php | MySQLStore.createStore | static function createStore($connect, &$errors = null)
{
// try{
// if (!$errors) $errors = new \boolive\errors\Error('Некоректные параметры доступа к СУБД', 'db');
// // Проверка подключения и базы данных
// $db = new DB('mysql:host='.$connect['host'].';port='.$connect['port'], $connect['user'], $connect['password'], array(DB::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8" COLLATE "utf8_bin"'), $connect['prefix']);
// $db_auto_create = false;
// try{
// $db->exec('USE `'.$connect['dbname'].'`');
// }catch (\Exception $e){
// // Проверка исполнения команды USE
// if ((int)$db->errorCode()){
// $info = $db->errorInfo();
// // Нет прав на указанную бд (и нет прав для создания бд)?
// if ($info[1] == '1044'){
// $errors->dbname->no_access = "No access";
// throw $errors;
// }else
// // Отсутсвует указанная бд?
// if ($info[1] == '1049'){
// // создаем
// $db->exec('CREATE DATABASE `'.$connect['dbname'].'` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci');
// $db_auto_create = true;
// $db->exec('USE `'.$connect['dbname'].'`');
// }
// }
// }
// // Проверка поддержки типов таблиц InnoDB
// $support = false;
// $q = $db->query('SHOW ENGINES');
// while (!$support && ($row = $q->fetch(\PDO::FETCH_ASSOC))){
// if ($row['Engine'] == 'InnoDB' && in_array($row['Support'], array('YES', 'DEFAULT'))) $support = true;
// }
// if (!$support){
// // Удаляем автоматически созданную БД
// if ($db_auto_create) $db->exec('DROP DATABASE IF EXISTS `'.$connect['dbname'].'`');
// $errors->common->no_innodb = "No InnoDB";
// throw $errors;
// }
// // Есть ли таблицы в БД?
// $pfx = $connect['prefix'];
// $tables = array($pfx.'ids', $pfx.'objects', $pfx.'protos', $pfx.'parents');
// $q = $db->query('SHOW TABLES');
// while ($row = $q->fetch(DB::FETCH_NUM)/* && empty($config['prefix'])*/){
// if (in_array($row[0], $tables)){
// // Иначе ошибка
// $errors->dbname->db_not_empty = "Database is not empty";
// throw $errors;
// }
// }
// Создание таблиц
$db->exec("
CREATE TABLE {ids} (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`uri` varchar(1000) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `uri` (`uri`(255))
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='Идентификация путей (URI)'
");
$db->exec("
CREATE TABLE `objects` (
`id` int(10) unsigned NOT NULL COMMENT 'Идентификатор по таблице ids',
`parent` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'Идентификатор родителя',
`proto` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'Идентификатор прототипа',
`author` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'Идентификатор автора',
`order` int(11) NOT NULL DEFAULT '0' COMMENT 'Порядковый номер. Уникален в рамках родителя',
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'Имя',
`value` varchar(255) NOT NULL DEFAULT '' COMMENT 'Строковое значение',
`file` varchar(55) NOT NULL DEFAULT '' COMMENT 'Имя файла, если есть',
`is_text` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Признак, есть текст в таблице текста',
`is_draft` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Черновик или нет?',
`is_hidden` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Скрыт или нет?',
`is_link` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Используетя как ссылка или нет?',
`is_mandatory` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Обязательный (1) или нет (0)? ',
`is_property` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Свойство (1) или нет (0)? ',
`is_relative` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Относительный (1) или нет (0) прототип?',
`is_default_value` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Используется значение прототипа или своё',
`is_default_file` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Используется файл прототипа или свой?',
`is_default_logic` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Используется класс прототипа или свой?',
`created` int(11) unsigned NOT NULL DEFAULT '0' COMMENT 'Дата создания',
`updated` int(11) unsigned NOT NULL DEFAULT '0' COMMENT 'Дата изменения',
PRIMARY KEY (`id`),
KEY `child` (`parent`,`order`,`name`,`value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Объекты'
");
$db->exec("
CREATE TABLE `text` (
`id` INT(10) UNSIGNED NOT NULL COMMENT 'Идентификатор объекта',
`value` TEXT NOT NULL COMMENT 'Текстовое значение',
PRIMARY KEY (`id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 COMMENT='Текстовые значения объектов'
");
$db->exec("
CREATE TABLE `parents1` (
`id` INT(10) UNSIGNED NOT NULL,
`id1` INT(10) UNSIGNED NOT NULL,
`id2` INT(10) UNSIGNED NOT NULL,
`id3` INT(10) UNSIGNED NOT NULL,
`id4` INT(10) UNSIGNED NOT NULL,
`id5` INT(10) UNSIGNED NOT NULL,
`id6` INT(10) UNSIGNED NOT NULL,
`id7` INT(10) UNSIGNED NOT NULL,
`id8` INT(10) UNSIGNED NOT NULL,
`id9` INT(10) UNSIGNED NOT NULL,
`id10` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
");
$db->exec("
CREATE TABLE `protos1` (
`id` INT(10) UNSIGNED NOT NULL,
`id1` INT(10) UNSIGNED NOT NULL,
`id2` INT(10) UNSIGNED NOT NULL,
`id3` INT(10) UNSIGNED NOT NULL,
`id4` INT(10) UNSIGNED NOT NULL,
`id5` INT(10) UNSIGNED NOT NULL,
`id6` INT(10) UNSIGNED NOT NULL,
`id7` INT(10) UNSIGNED NOT NULL,
`id8` INT(10) UNSIGNED NOT NULL,
`id9` INT(10) UNSIGNED NOT NULL,
`id10` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
");
// }catch (\PDOException $e){
// // Ошибки подключения к СУБД
// if ($e->getCode() == '1045'){
// $errors->user->no_access = "No accecss";
// $errors->password->no_access = "No accecss";
// }else
// if ($e->getCode() == '2002'){
// $errors->host->not_found = "Host not found";
// if ($connect['port']!=3306){
// $errors->port->not_found = "Port no found";
// }
// }else{
// $errors->common = $e->getMessage();
// }
// if ($errors->is_exist()) throw $errors;
// }
} | php | static function createStore($connect, &$errors = null)
{
// try{
// if (!$errors) $errors = new \boolive\errors\Error('Некоректные параметры доступа к СУБД', 'db');
// // Проверка подключения и базы данных
// $db = new DB('mysql:host='.$connect['host'].';port='.$connect['port'], $connect['user'], $connect['password'], array(DB::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8" COLLATE "utf8_bin"'), $connect['prefix']);
// $db_auto_create = false;
// try{
// $db->exec('USE `'.$connect['dbname'].'`');
// }catch (\Exception $e){
// // Проверка исполнения команды USE
// if ((int)$db->errorCode()){
// $info = $db->errorInfo();
// // Нет прав на указанную бд (и нет прав для создания бд)?
// if ($info[1] == '1044'){
// $errors->dbname->no_access = "No access";
// throw $errors;
// }else
// // Отсутсвует указанная бд?
// if ($info[1] == '1049'){
// // создаем
// $db->exec('CREATE DATABASE `'.$connect['dbname'].'` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci');
// $db_auto_create = true;
// $db->exec('USE `'.$connect['dbname'].'`');
// }
// }
// }
// // Проверка поддержки типов таблиц InnoDB
// $support = false;
// $q = $db->query('SHOW ENGINES');
// while (!$support && ($row = $q->fetch(\PDO::FETCH_ASSOC))){
// if ($row['Engine'] == 'InnoDB' && in_array($row['Support'], array('YES', 'DEFAULT'))) $support = true;
// }
// if (!$support){
// // Удаляем автоматически созданную БД
// if ($db_auto_create) $db->exec('DROP DATABASE IF EXISTS `'.$connect['dbname'].'`');
// $errors->common->no_innodb = "No InnoDB";
// throw $errors;
// }
// // Есть ли таблицы в БД?
// $pfx = $connect['prefix'];
// $tables = array($pfx.'ids', $pfx.'objects', $pfx.'protos', $pfx.'parents');
// $q = $db->query('SHOW TABLES');
// while ($row = $q->fetch(DB::FETCH_NUM)/* && empty($config['prefix'])*/){
// if (in_array($row[0], $tables)){
// // Иначе ошибка
// $errors->dbname->db_not_empty = "Database is not empty";
// throw $errors;
// }
// }
// Создание таблиц
$db->exec("
CREATE TABLE {ids} (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`uri` varchar(1000) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `uri` (`uri`(255))
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='Идентификация путей (URI)'
");
$db->exec("
CREATE TABLE `objects` (
`id` int(10) unsigned NOT NULL COMMENT 'Идентификатор по таблице ids',
`parent` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'Идентификатор родителя',
`proto` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'Идентификатор прототипа',
`author` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'Идентификатор автора',
`order` int(11) NOT NULL DEFAULT '0' COMMENT 'Порядковый номер. Уникален в рамках родителя',
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'Имя',
`value` varchar(255) NOT NULL DEFAULT '' COMMENT 'Строковое значение',
`file` varchar(55) NOT NULL DEFAULT '' COMMENT 'Имя файла, если есть',
`is_text` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Признак, есть текст в таблице текста',
`is_draft` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Черновик или нет?',
`is_hidden` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Скрыт или нет?',
`is_link` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Используетя как ссылка или нет?',
`is_mandatory` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Обязательный (1) или нет (0)? ',
`is_property` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Свойство (1) или нет (0)? ',
`is_relative` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Относительный (1) или нет (0) прототип?',
`is_default_value` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Используется значение прототипа или своё',
`is_default_file` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Используется файл прототипа или свой?',
`is_default_logic` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Используется класс прототипа или свой?',
`created` int(11) unsigned NOT NULL DEFAULT '0' COMMENT 'Дата создания',
`updated` int(11) unsigned NOT NULL DEFAULT '0' COMMENT 'Дата изменения',
PRIMARY KEY (`id`),
KEY `child` (`parent`,`order`,`name`,`value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Объекты'
");
$db->exec("
CREATE TABLE `text` (
`id` INT(10) UNSIGNED NOT NULL COMMENT 'Идентификатор объекта',
`value` TEXT NOT NULL COMMENT 'Текстовое значение',
PRIMARY KEY (`id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 COMMENT='Текстовые значения объектов'
");
$db->exec("
CREATE TABLE `parents1` (
`id` INT(10) UNSIGNED NOT NULL,
`id1` INT(10) UNSIGNED NOT NULL,
`id2` INT(10) UNSIGNED NOT NULL,
`id3` INT(10) UNSIGNED NOT NULL,
`id4` INT(10) UNSIGNED NOT NULL,
`id5` INT(10) UNSIGNED NOT NULL,
`id6` INT(10) UNSIGNED NOT NULL,
`id7` INT(10) UNSIGNED NOT NULL,
`id8` INT(10) UNSIGNED NOT NULL,
`id9` INT(10) UNSIGNED NOT NULL,
`id10` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
");
$db->exec("
CREATE TABLE `protos1` (
`id` INT(10) UNSIGNED NOT NULL,
`id1` INT(10) UNSIGNED NOT NULL,
`id2` INT(10) UNSIGNED NOT NULL,
`id3` INT(10) UNSIGNED NOT NULL,
`id4` INT(10) UNSIGNED NOT NULL,
`id5` INT(10) UNSIGNED NOT NULL,
`id6` INT(10) UNSIGNED NOT NULL,
`id7` INT(10) UNSIGNED NOT NULL,
`id8` INT(10) UNSIGNED NOT NULL,
`id9` INT(10) UNSIGNED NOT NULL,
`id10` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
");
// }catch (\PDOException $e){
// // Ошибки подключения к СУБД
// if ($e->getCode() == '1045'){
// $errors->user->no_access = "No accecss";
// $errors->password->no_access = "No accecss";
// }else
// if ($e->getCode() == '2002'){
// $errors->host->not_found = "Host not found";
// if ($connect['port']!=3306){
// $errors->port->not_found = "Port no found";
// }
// }else{
// $errors->common = $e->getMessage();
// }
// if ($errors->is_exist()) throw $errors;
// }
} | Создание хранилища
@param $connect
@param null $errors
@throws Error|null | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/data/stores/MySQLStore.php#L535-L675 |
praxisnetau/silverware-navigation | src/Components/CrumbNavigation.php | CrumbNavigation.getCMSFields | public function getCMSFields()
{
// Obtain Field Objects (from parent):
$fields = parent::getCMSFields();
// Create Options Fields:
$fields->addFieldToTab(
'Root.Options',
FieldSection::create(
'NavigationOptions',
$this->fieldLabel('NavigationOptions'),
[
CheckboxField::create(
'HideTopLevel',
$this->fieldLabel('HideTopLevel')
)
]
)
);
// Answer Field Objects:
return $fields;
} | php | public function getCMSFields()
{
// Obtain Field Objects (from parent):
$fields = parent::getCMSFields();
// Create Options Fields:
$fields->addFieldToTab(
'Root.Options',
FieldSection::create(
'NavigationOptions',
$this->fieldLabel('NavigationOptions'),
[
CheckboxField::create(
'HideTopLevel',
$this->fieldLabel('HideTopLevel')
)
]
)
);
// Answer Field Objects:
return $fields;
} | Answers a list of field objects for the CMS interface.
@return FieldList | https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/CrumbNavigation.php#L119-L144 |
praxisnetau/silverware-navigation | src/Components/CrumbNavigation.php | CrumbNavigation.isDisabled | public function isDisabled()
{
// Obtain Current Page (with crumbs enabled):
if (($page = $this->getCurrentPage(Page::class)) && !$page->CrumbsDisabled) {
// Disable for Top-Level (if required):
if ($this->HideTopLevel && $this->getCrumbsCount() == 1) {
return true;
}
// Answer from Parent:
return parent::isDisabled();
}
// Disable (by default):
return true;
} | php | public function isDisabled()
{
// Obtain Current Page (with crumbs enabled):
if (($page = $this->getCurrentPage(Page::class)) && !$page->CrumbsDisabled) {
// Disable for Top-Level (if required):
if ($this->HideTopLevel && $this->getCrumbsCount() == 1) {
return true;
}
// Answer from Parent:
return parent::isDisabled();
}
// Disable (by default):
return true;
} | Answers true if the object is disabled within the template.
@return boolean | https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/CrumbNavigation.php#L238-L259 |
YiMAproject/yimaWidgetator | src/yimaWidgetator/Listener/WidgetizeAggregateListener.php | WidgetizeAggregateListener.attach | public function attach(EventManagerInterface $events)
{
$this->listeners[] = $events->attach(
ViewEvent::EVENT_RENDERER_POST
, array($this, 'onRenderRenderWidgets')
);
} | php | public function attach(EventManagerInterface $events)
{
$this->listeners[] = $events->attach(
ViewEvent::EVENT_RENDERER_POST
, array($this, 'onRenderRenderWidgets')
);
} | Attach one or more listeners
Implementors may add an optional $priority argument; the EventManager
implementation will pass this to the aggregate.
@param EventManagerInterface $events
@return void | https://github.com/YiMAproject/yimaWidgetator/blob/332bc9318e6ceaec918147b30317da2f5b3d2636/src/yimaWidgetator/Listener/WidgetizeAggregateListener.php#L39-L45 |
YiMAproject/yimaWidgetator | src/yimaWidgetator/Listener/WidgetizeAggregateListener.php | WidgetizeAggregateListener.onRenderRenderWidgets | function onRenderRenderWidgets(ViewEvent $e)
{
$viewModel = $e->getModel();
if (! $viewModel->terminate())
// Only base themes has a widgets rendered into
return;
/** @var RegionBoxContainer $rBoxContainer */
$rBoxContainer = $this->sm->get('yimaWidgetator.Widgetizer.Container');
foreach ($rBoxContainer->getWidgets() as $region => $wdgs) {
// Render Widget
$this->__renderWidgets($region, $wdgs, $viewModel);
}
} | php | function onRenderRenderWidgets(ViewEvent $e)
{
$viewModel = $e->getModel();
if (! $viewModel->terminate())
// Only base themes has a widgets rendered into
return;
/** @var RegionBoxContainer $rBoxContainer */
$rBoxContainer = $this->sm->get('yimaWidgetator.Widgetizer.Container');
foreach ($rBoxContainer->getWidgets() as $region => $wdgs) {
// Render Widget
$this->__renderWidgets($region, $wdgs, $viewModel);
}
} | Render Defined Widgets into Layout Sections(area)
@param ViewEvent $e MVC Event
@return void | https://github.com/YiMAproject/yimaWidgetator/blob/332bc9318e6ceaec918147b30317da2f5b3d2636/src/yimaWidgetator/Listener/WidgetizeAggregateListener.php#L54-L67 |
YiMAproject/yimaWidgetator | src/yimaWidgetator/Listener/WidgetizeAggregateListener.php | WidgetizeAggregateListener.__renderWidgets | protected function __renderWidgets($region, array $widgets, ModelInterface $viewModel)
{
k(__FUNCTION__);
foreach($widgets as $widget) {
$widget = $this->___attainWidgetInstance($widget);
// Render Widget
$content = $widget->render();
// TODO maybe we want to add filter or event on rendering widget contents
$viewModel->{$region} .= $content;
}
} | php | protected function __renderWidgets($region, array $widgets, ModelInterface $viewModel)
{
k(__FUNCTION__);
foreach($widgets as $widget) {
$widget = $this->___attainWidgetInstance($widget);
// Render Widget
$content = $widget->render();
// TODO maybe we want to add filter or event on rendering widget contents
$viewModel->{$region} .= $content;
}
} | Render Widget From Container Result
@param array $widgets Container Widget Entity
@param ModelInterface $viewModel View Model
@return bool | https://github.com/YiMAproject/yimaWidgetator/blob/332bc9318e6ceaec918147b30317da2f5b3d2636/src/yimaWidgetator/Listener/WidgetizeAggregateListener.php#L77-L90 |
delboy1978uk/del-countries-flags | src/DelCountriesFlags/Mapper/CountryHydrator.php | CountryHydrator.extract | public function extract($object)
{
if (!$object instanceof CountryEntityInterface) {
throw new Exception\InvalidArgumentException('$object must be an instance of DelCountriesFlags\Entity\CountryInterface');
}
/* @var $object CountryInterface*/
$data = parent::extract($object);
return $data;
} | php | public function extract($object)
{
if (!$object instanceof CountryEntityInterface) {
throw new Exception\InvalidArgumentException('$object must be an instance of DelCountriesFlags\Entity\CountryInterface');
}
/* @var $object CountryInterface*/
$data = parent::extract($object);
return $data;
} | Extract values from an object
@param object $object
@return array
@throws Exception\InvalidArgumentException | https://github.com/delboy1978uk/del-countries-flags/blob/da853154fe8a86db1deeca5f456b0759a7de0162/src/DelCountriesFlags/Mapper/CountryHydrator.php#L17-L25 |
delboy1978uk/del-countries-flags | src/DelCountriesFlags/Mapper/CountryHydrator.php | CountryHydrator.hydrate | public function hydrate(array $data, $object)
{
if (!$object instanceof CountryEntityInterface) {
throw new Exception\InvalidArgumentException('$object must be an instance of DelCountriesFlags\Entity\CountryInterface');
}
return parent::hydrate($data, $object);
} | php | public function hydrate(array $data, $object)
{
if (!$object instanceof CountryEntityInterface) {
throw new Exception\InvalidArgumentException('$object must be an instance of DelCountriesFlags\Entity\CountryInterface');
}
return parent::hydrate($data, $object);
} | Hydrate $object with the provided $data.
@param array $data
@param object $object
@return CountryInterface
@throws Exception\InvalidArgumentException | https://github.com/delboy1978uk/del-countries-flags/blob/da853154fe8a86db1deeca5f456b0759a7de0162/src/DelCountriesFlags/Mapper/CountryHydrator.php#L35-L41 |
anklimsk/cakephp-console-installer | Controller/CheckController.php | CheckController.beforeFilter | public function beforeFilter() {
if ($this->action === 'index') {
$isAppInstalled = $this->Installer->isAppInstalled();
if ($isAppInstalled) {
$this->redirect('/');
}
}
$this->Auth->allow('index');
parent::beforeFilter();
} | php | public function beforeFilter() {
if ($this->action === 'index') {
$isAppInstalled = $this->Installer->isAppInstalled();
if ($isAppInstalled) {
$this->redirect('/');
}
}
$this->Auth->allow('index');
parent::beforeFilter();
} | Called before the controller action. You can use this method to configure and customize components
or perform logic that needs to happen before each controller action.
Actions:
- Redirect to homepage if application is installed;
@return void
@link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Controller/CheckController.php#L85-L95 |
anklimsk/cakephp-console-installer | Controller/CheckController.php | CheckController.index | public function index() {
$isAppInstalled = $this->Installer->isAppInstalled();
$isAppReadyInstall = $this->InstallerCheck->isAppReadyToInstall();
$phpVesion = $this->InstallerCheck->checkPhpVersion();
$phpModules = $this->InstallerCheck->checkPhpExtensions();
$filesWritable = $this->InstallerCheck->checkFilesWritable();
$connectDB = $this->InstallerCheck->checkConnectDb();
$this->set(compact(
'isAppInstalled',
'isAppReadyInstall',
'phpVesion',
'phpModules',
'filesWritable',
'connectDB'
));
} | php | public function index() {
$isAppInstalled = $this->Installer->isAppInstalled();
$isAppReadyInstall = $this->InstallerCheck->isAppReadyToInstall();
$phpVesion = $this->InstallerCheck->checkPhpVersion();
$phpModules = $this->InstallerCheck->checkPhpExtensions();
$filesWritable = $this->InstallerCheck->checkFilesWritable();
$connectDB = $this->InstallerCheck->checkConnectDb();
$this->set(compact(
'isAppInstalled',
'isAppReadyInstall',
'phpVesion',
'phpModules',
'filesWritable',
'connectDB'
));
} | Action `index`. Used to view state of installation for application.
@return void | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Controller/CheckController.php#L102-L118 |
infusephp/auth | src/Libs/ResetPassword.php | ResetPassword.getUserFromToken | public function getUserFromToken($token)
{
$expiration = U::unixToDb(time() - UserLink::$forgotLinkTimeframe);
$link = UserLink::where('link', $token)
->where('type', UserLink::FORGOT_PASSWORD)
->where('created_at', $expiration, '>')
->first();
if (!$link) {
throw new AuthException('This link has expired or is invalid.');
}
$userClass = $this->auth->getUserClass();
return $userClass::find($link->user_id);
} | php | public function getUserFromToken($token)
{
$expiration = U::unixToDb(time() - UserLink::$forgotLinkTimeframe);
$link = UserLink::where('link', $token)
->where('type', UserLink::FORGOT_PASSWORD)
->where('created_at', $expiration, '>')
->first();
if (!$link) {
throw new AuthException('This link has expired or is invalid.');
}
$userClass = $this->auth->getUserClass();
return $userClass::find($link->user_id);
} | Looks up a user from a given forgot token.
@param string $token
@throws AuthException when the token is invalid.
@return \Infuse\Auth\Interfaces\UserInterface | https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/ResetPassword.php#L47-L62 |
infusephp/auth | src/Libs/ResetPassword.php | ResetPassword.step1 | public function step1($email, $ip, $userAgent)
{
$email = trim(strtolower($email));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new AuthException('Please enter a valid email address.');
}
$userClass = $this->auth->getUserClass();
$user = $userClass::where('email', $email)->first();
if (!$user || $user->isTemporary()) {
throw new AuthException('We could not find a match for that email address.');
}
// can only issue a single active forgot token at a time
$expiration = U::unixToDb(time() - UserLink::$forgotLinkTimeframe);
$nExisting = UserLink::where('user_id', $user->id())
->where('type', UserLink::FORGOT_PASSWORD)
->where('created_at', $expiration, '>')
->count();
if ($nExisting > 0) {
return true;
}
// generate a reset password link
$link = $this->buildLink($user->id(), $ip, $userAgent);
// and send it
return $user->sendEmail('forgot-password', [
'ip' => $ip,
'forgot' => $link->link,
]);
} | php | public function step1($email, $ip, $userAgent)
{
$email = trim(strtolower($email));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new AuthException('Please enter a valid email address.');
}
$userClass = $this->auth->getUserClass();
$user = $userClass::where('email', $email)->first();
if (!$user || $user->isTemporary()) {
throw new AuthException('We could not find a match for that email address.');
}
// can only issue a single active forgot token at a time
$expiration = U::unixToDb(time() - UserLink::$forgotLinkTimeframe);
$nExisting = UserLink::where('user_id', $user->id())
->where('type', UserLink::FORGOT_PASSWORD)
->where('created_at', $expiration, '>')
->count();
if ($nExisting > 0) {
return true;
}
// generate a reset password link
$link = $this->buildLink($user->id(), $ip, $userAgent);
// and send it
return $user->sendEmail('forgot-password', [
'ip' => $ip,
'forgot' => $link->link,
]);
} | The first step in the forgot password sequence.
@param string $email email address
@param string $ip ip address making the request
@param string $userAgent user agent used to make the request
@throws AuthException when the step cannot be completed.
@return bool | https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/ResetPassword.php#L75-L109 |
infusephp/auth | src/Libs/ResetPassword.php | ResetPassword.step2 | public function step2($token, array $password, $ip)
{
$user = $this->getUserFromToken($token);
// Update the password
$user->password = $password;
$success = $user->grantAllPermissions()->save();
$user->enforcePermissions();
if (!$success) {
$msg = implode(' ', $user->getErrors()->all());
throw new AuthException($msg);
}
$this->app['database']->getDefault()
->delete('UserLinks')
->where('user_id', $user->id())
->where('type', UserLink::FORGOT_PASSWORD)
->execute();
return true;
} | php | public function step2($token, array $password, $ip)
{
$user = $this->getUserFromToken($token);
// Update the password
$user->password = $password;
$success = $user->grantAllPermissions()->save();
$user->enforcePermissions();
if (!$success) {
$msg = implode(' ', $user->getErrors()->all());
throw new AuthException($msg);
}
$this->app['database']->getDefault()
->delete('UserLinks')
->where('user_id', $user->id())
->where('type', UserLink::FORGOT_PASSWORD)
->execute();
return true;
} | Step 2 in the forgot password process. Resets the password
given a valid token.
@param string $token token
@param array $password new password
@param string $ip ip address making the request
@throws AuthException when the step cannot be completed.
@return bool | https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/ResetPassword.php#L123-L144 |
infusephp/auth | src/Libs/ResetPassword.php | ResetPassword.buildLink | public function buildLink($userId, $ip, $userAgent)
{
$link = new UserLink();
$link->user_id = $userId;
$link->type = UserLink::FORGOT_PASSWORD;
try {
$link->save();
} catch (\Exception $e) {
throw new \Exception("Could not create reset password link for user # $userId: ".$e->getMessage());
}
// record the reset password request event
$event = new AccountSecurityEvent();
$event->user_id = $userId;
$event->type = AccountSecurityEvent::RESET_PASSWORD_REQUEST;
$event->ip = $ip;
$event->user_agent = $userAgent;
$event->save();
return $link;
} | php | public function buildLink($userId, $ip, $userAgent)
{
$link = new UserLink();
$link->user_id = $userId;
$link->type = UserLink::FORGOT_PASSWORD;
try {
$link->save();
} catch (\Exception $e) {
throw new \Exception("Could not create reset password link for user # $userId: ".$e->getMessage());
}
// record the reset password request event
$event = new AccountSecurityEvent();
$event->user_id = $userId;
$event->type = AccountSecurityEvent::RESET_PASSWORD_REQUEST;
$event->ip = $ip;
$event->user_agent = $userAgent;
$event->save();
return $link;
} | Builds a reset password link.
@param int $userId
@param string $ip
@param string $userAgent
@return UserLink | https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/ResetPassword.php#L155-L176 |
fsi-open/property-observer | lib/FSi/Component/PropertyObserver/MultiplePropertyObserver.php | MultiplePropertyObserver.saveValues | public function saveValues($object, array $propertyPaths)
{
foreach ($propertyPaths as $propertyPath) {
$this->saveValue($object, $propertyPath);
}
} | php | public function saveValues($object, array $propertyPaths)
{
foreach ($propertyPaths as $propertyPath) {
$this->saveValue($object, $propertyPath);
}
} | {@inheritdoc} | https://github.com/fsi-open/property-observer/blob/c63bba3660c3924e60e2c49a0385bbc3e72925b0/lib/FSi/Component/PropertyObserver/MultiplePropertyObserver.php#L17-L22 |
fsi-open/property-observer | lib/FSi/Component/PropertyObserver/MultiplePropertyObserver.php | MultiplePropertyObserver.hasChangedValues | public function hasChangedValues($object, array $propertyPaths, $notSavedAsNull = false)
{
$valueChanged = false;
foreach ($propertyPaths as $propertyPath) {
$valueChanged = $valueChanged || $this->hasChangedValue($object, $propertyPath, $notSavedAsNull);
}
return $valueChanged;
} | php | public function hasChangedValues($object, array $propertyPaths, $notSavedAsNull = false)
{
$valueChanged = false;
foreach ($propertyPaths as $propertyPath) {
$valueChanged = $valueChanged || $this->hasChangedValue($object, $propertyPath, $notSavedAsNull);
}
return $valueChanged;
} | {@inheritdoc} | https://github.com/fsi-open/property-observer/blob/c63bba3660c3924e60e2c49a0385bbc3e72925b0/lib/FSi/Component/PropertyObserver/MultiplePropertyObserver.php#L27-L34 |
mover-io/belt | lib/Dump.php | Dump.pretty | public static function pretty($subject, $depth = 3, $ignore = array(), $refChain = array(), $current = 1, $colors=false)
{
$str = '';
if ( $depth > 0 && is_object($subject) )
{
$str .= Text::shellColor("blue", get_class($subject). " Object (",$colors)."\n";
$subject = (array) $subject;
foreach ( $subject as $key => $val )
{
if ( is_array($ignore) && ! in_array($key, $ignore, 1) )
{
$str .= str_repeat(" ", $current * 4) . '\'';
if ( $key{0} == "\0" )
{
$keyParts = explode("\0", $key);
$str .= $keyParts[2] . (($keyParts[1] == '*') ? ':protected' : ':private');
}
else
{
$str .= $key;
}
$str .= '\' => ';
$str .= self::pretty($val, $depth - 1, $ignore, $refChain, $current + 1, $colors);
}
}
$str .= str_repeat(" ", ($current - 1) * 4) . Text::shellColor("blue",")",$colors). "\n";
array_pop($refChain);
}
else
{
if ( $depth > 0 && is_array($subject) )
{
$str .= Text::shellColor('yellow','[',$colors) . "\n";
foreach ( $subject as $key => $val )
{
if ( is_array($ignore) && ! in_array($key, $ignore, 1) )
{
$str .= str_repeat(" ", $current * 4) . '\'' . $key . '\'' . ' => ';
$str .= self::pretty($val, $depth - 1, $ignore, $refChain, $current + 1, $colors);
}
}
$str .= str_repeat(" ", ($current - 1) * 4) . Text::shellColor('yellow',"]",$colors) . "\n";
}
else
{
if ( is_array($subject) || is_object($subject) )
{
$str .= "Nested Element\n";
}
else
{
if($subject === true)
{
$subject = Text::shellColor('green','true',$colors);
}
else if ($subject === false)
{
$subject = Text::shellColor('red','false',$colors);
}
else if ($subject === null) {
$subject = Text::shellColor('magenta','null',$colors);
}
else if (is_float($subject)) {
if ($subject > 0) {
$formatted = number_format($subject);
} else {
$formatted = sprintf("%g", $subject);
}
$subject = Text::shellColor('cyan', $formatted . ' => :0x'. bin2hex(pack('d', $subject)), $colors);
}
else if (is_numeric($subject)) {
$subject = Text::shellColor('blue',$subject,$colors);
}
else if (is_string($subject)) {
if($colors) {
$matches = array();
preg_match('/^(\s*)?(.*?)(\s*)?$/s',$subject,$matches);
$subject = Text::shellColor('bg_red',$matches[1],$colors) .
'\'' . $matches[2] . '\'' .
Text::shellColor('bg_red',$matches[3],$colors);
}
}
$str .= $subject . "\n";
}
}
}
// Trim trailing newlines.
if($current == 1) { $str = rtrim($str,"\n"); }
return $str;
} | php | public static function pretty($subject, $depth = 3, $ignore = array(), $refChain = array(), $current = 1, $colors=false)
{
$str = '';
if ( $depth > 0 && is_object($subject) )
{
$str .= Text::shellColor("blue", get_class($subject). " Object (",$colors)."\n";
$subject = (array) $subject;
foreach ( $subject as $key => $val )
{
if ( is_array($ignore) && ! in_array($key, $ignore, 1) )
{
$str .= str_repeat(" ", $current * 4) . '\'';
if ( $key{0} == "\0" )
{
$keyParts = explode("\0", $key);
$str .= $keyParts[2] . (($keyParts[1] == '*') ? ':protected' : ':private');
}
else
{
$str .= $key;
}
$str .= '\' => ';
$str .= self::pretty($val, $depth - 1, $ignore, $refChain, $current + 1, $colors);
}
}
$str .= str_repeat(" ", ($current - 1) * 4) . Text::shellColor("blue",")",$colors). "\n";
array_pop($refChain);
}
else
{
if ( $depth > 0 && is_array($subject) )
{
$str .= Text::shellColor('yellow','[',$colors) . "\n";
foreach ( $subject as $key => $val )
{
if ( is_array($ignore) && ! in_array($key, $ignore, 1) )
{
$str .= str_repeat(" ", $current * 4) . '\'' . $key . '\'' . ' => ';
$str .= self::pretty($val, $depth - 1, $ignore, $refChain, $current + 1, $colors);
}
}
$str .= str_repeat(" ", ($current - 1) * 4) . Text::shellColor('yellow',"]",$colors) . "\n";
}
else
{
if ( is_array($subject) || is_object($subject) )
{
$str .= "Nested Element\n";
}
else
{
if($subject === true)
{
$subject = Text::shellColor('green','true',$colors);
}
else if ($subject === false)
{
$subject = Text::shellColor('red','false',$colors);
}
else if ($subject === null) {
$subject = Text::shellColor('magenta','null',$colors);
}
else if (is_float($subject)) {
if ($subject > 0) {
$formatted = number_format($subject);
} else {
$formatted = sprintf("%g", $subject);
}
$subject = Text::shellColor('cyan', $formatted . ' => :0x'. bin2hex(pack('d', $subject)), $colors);
}
else if (is_numeric($subject)) {
$subject = Text::shellColor('blue',$subject,$colors);
}
else if (is_string($subject)) {
if($colors) {
$matches = array();
preg_match('/^(\s*)?(.*?)(\s*)?$/s',$subject,$matches);
$subject = Text::shellColor('bg_red',$matches[1],$colors) .
'\'' . $matches[2] . '\'' .
Text::shellColor('bg_red',$matches[3],$colors);
}
}
$str .= $subject . "\n";
}
}
}
// Trim trailing newlines.
if($current == 1) { $str = rtrim($str,"\n"); }
return $str;
} | Depth limited print_r. Returns string instead of echoing by default.
@return string | https://github.com/mover-io/belt/blob/c966a70aa0f4eb51be55bbb86c89b1e85b773d68/lib/Dump.php#L14-L105 |
wdbo/webdocbook | src/WebDocBook/Helper.php | Helper.fetchArguments | public static function fetchArguments($_class = null, $_method = null, $args = null)
{
if (empty($_class) || empty($_method)) {
return null;
}
$args_def = array();
if (!empty($args)) {
$analyze = new ReflectionMethod($_class, $_method);
foreach($analyze->getParameters() as $_param) {
$arg_index = $_param->getName();
$args_def[$_param->getPosition()] = isset($args[$arg_index]) ?
$args[$arg_index] : ( $_param->isOptional() ? $_param->getDefaultValue() : null );
}
}
return call_user_func_array( array($_class, $_method), $args_def );
} | php | public static function fetchArguments($_class = null, $_method = null, $args = null)
{
if (empty($_class) || empty($_method)) {
return null;
}
$args_def = array();
if (!empty($args)) {
$analyze = new ReflectionMethod($_class, $_method);
foreach($analyze->getParameters() as $_param) {
$arg_index = $_param->getName();
$args_def[$_param->getPosition()] = isset($args[$arg_index]) ?
$args[$arg_index] : ( $_param->isOptional() ? $_param->getDefaultValue() : null );
}
}
return call_user_func_array( array($_class, $_method), $args_def );
} | Launch a class's method fetching arguments
@param string $_class The class name
@param string $_method The class method name
@param mixed $args A set of arguments to fetch
@return mixed | https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/Helper.php#L60-L75 |
rhosocial/helpers | BaseTimezone.php | BaseTimezone.generateList | public static function generateList($region = DateTimeZone::ALL)
{
$regions = array(
DateTimeZone::AFRICA,
DateTimeZone::AMERICA,
DateTimeZone::ANTARCTICA,
DateTimeZone::ASIA,
DateTimeZone::ATLANTIC,
DateTimeZone::AUSTRALIA,
DateTimeZone::EUROPE,
DateTimeZone::INDIAN,
DateTimeZone::PACIFIC,
);
if ($region !== DateTimeZone::ALL && !in_array($region, $regions)) {
$region = DateTimeZone::ALL;
}
$timezones = array();
if ($region == DateTimeZone::ALL) {
foreach ($regions as $r) {
$timezones = array_merge($timezones, DateTimeZone::listIdentifiers($r));
}
} else {
$timezones = DateTimeZone::listIdentifiers($region);
}
$timezone_offsets = array();
foreach ($timezones as $timezone) {
$tz = new DateTimeZone($timezone);
$timezone_offsets[$timezone] = $tz->getOffset(new DateTime);
}
asort($timezone_offsets);
$timezone_list = array();
foreach ($timezone_offsets as $timezone => $offset) {
$offset_prefix = $offset < 0 ? '-' : '+';
$offset_formatted = gmdate('H:i', abs($offset));
$pretty_offset = "UTC${offset_prefix}${offset_formatted}";
$t = new DateTimeZone($timezone);
$c = new DateTime(null, $t);
$timezone_list[$timezone] = $pretty_offset . " - " . $timezone;
}
return $timezone_list;
} | php | public static function generateList($region = DateTimeZone::ALL)
{
$regions = array(
DateTimeZone::AFRICA,
DateTimeZone::AMERICA,
DateTimeZone::ANTARCTICA,
DateTimeZone::ASIA,
DateTimeZone::ATLANTIC,
DateTimeZone::AUSTRALIA,
DateTimeZone::EUROPE,
DateTimeZone::INDIAN,
DateTimeZone::PACIFIC,
);
if ($region !== DateTimeZone::ALL && !in_array($region, $regions)) {
$region = DateTimeZone::ALL;
}
$timezones = array();
if ($region == DateTimeZone::ALL) {
foreach ($regions as $r) {
$timezones = array_merge($timezones, DateTimeZone::listIdentifiers($r));
}
} else {
$timezones = DateTimeZone::listIdentifiers($region);
}
$timezone_offsets = array();
foreach ($timezones as $timezone) {
$tz = new DateTimeZone($timezone);
$timezone_offsets[$timezone] = $tz->getOffset(new DateTime);
}
asort($timezone_offsets);
$timezone_list = array();
foreach ($timezone_offsets as $timezone => $offset) {
$offset_prefix = $offset < 0 ? '-' : '+';
$offset_formatted = gmdate('H:i', abs($offset));
$pretty_offset = "UTC${offset_prefix}${offset_formatted}";
$t = new DateTimeZone($timezone);
$c = new DateTime(null, $t);
$timezone_list[$timezone] = $pretty_offset . " - " . $timezone;
}
return $timezone_list;
} | Generate Time Zone List.
@param int $region
@return array | https://github.com/rhosocial/helpers/blob/547ee6bca153bd35ed21d27606a40748bffcd726/BaseTimezone.php#L31-L73 |
slickframework/form | src/Renderer/TextArea.php | TextArea.render | public function render($context = [])
{
if ($this->getElement()->hasAttribute('value')) {
$this->getElement()->getAttributes()->remove('value');
}
return parent::render($context);
} | php | public function render($context = [])
{
if ($this->getElement()->hasAttribute('value')) {
$this->getElement()->getAttributes()->remove('value');
}
return parent::render($context);
} | Overrides to remove the unnecessary value attribute
@param array $context
@return string | https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Renderer/TextArea.php#L25-L31 |
codemaxbr/reliese | src/Support/Dumper.php | Dumper.export | public static function export($value, $tabs = 2)
{
// Custom array exporting
if (is_array($value)) {
$indent = str_repeat("\t", $tabs);
$closingIndent = str_repeat("\t", $tabs - 1);
$keys = array_keys($value);
$array = array_map(function ($value, $key) use ($tabs) {
if (is_numeric($key)) {
return static::export($value, $tabs + 1);
}
return "'$key' => ".static::export($value, $tabs + 1);
}, $value, $keys);
return "[\n$indent".implode(",\n$indent", $array)."\n$closingIndent]";
}
// Default variable exporting
return var_export($value, true);
} | php | public static function export($value, $tabs = 2)
{
// Custom array exporting
if (is_array($value)) {
$indent = str_repeat("\t", $tabs);
$closingIndent = str_repeat("\t", $tabs - 1);
$keys = array_keys($value);
$array = array_map(function ($value, $key) use ($tabs) {
if (is_numeric($key)) {
return static::export($value, $tabs + 1);
}
return "'$key' => ".static::export($value, $tabs + 1);
}, $value, $keys);
return "[\n$indent".implode(",\n$indent", $array)."\n$closingIndent]";
}
// Default variable exporting
return var_export($value, true);
} | @param mixed $value
@param int $tabs
@return string | https://github.com/codemaxbr/reliese/blob/efaac021ba4d936edd7e9fda2bd7bcdac18d8497/src/Support/Dumper.php#L18-L38 |
Tuna-CMS/tuna-bundle | src/Tuna/Bundle/FileBundle/Form/AbstractFileType.php | AbstractFileType.configureOptions | public function configureOptions(OptionsResolver $resolver)
{
$defaultDropzoneOptions = static::getDropzoneDefaultOptions() + [
'maxFilesize' => self::getPHPMaxFilesize(),
'acceptedFiles' => '',
];
$resolver->setDefaults([
'translation_domain' => 'tuna_admin',
'data_class' => $this->getEntityClass(),
'error_bubbling' => false,
'dropzone_options' => $defaultDropzoneOptions,
'button_label' => 'ui.form.labels.file.button',
'show_filename' => true,
'init_dropzone' => true,
'attr' => [
'deletable' => true,
],
]);
$resolver->setNormalizer('dropzone_options', function (Options $options, $value) use ($defaultDropzoneOptions) {
if (array_key_exists('maxFilesize', $value)) {
$value['maxFilesize'] = min(self::getPHPMaxFilesize(), $value['maxFilesize']);
}
return array_merge($defaultDropzoneOptions, $value);
});
} | php | public function configureOptions(OptionsResolver $resolver)
{
$defaultDropzoneOptions = static::getDropzoneDefaultOptions() + [
'maxFilesize' => self::getPHPMaxFilesize(),
'acceptedFiles' => '',
];
$resolver->setDefaults([
'translation_domain' => 'tuna_admin',
'data_class' => $this->getEntityClass(),
'error_bubbling' => false,
'dropzone_options' => $defaultDropzoneOptions,
'button_label' => 'ui.form.labels.file.button',
'show_filename' => true,
'init_dropzone' => true,
'attr' => [
'deletable' => true,
],
]);
$resolver->setNormalizer('dropzone_options', function (Options $options, $value) use ($defaultDropzoneOptions) {
if (array_key_exists('maxFilesize', $value)) {
$value['maxFilesize'] = min(self::getPHPMaxFilesize(), $value['maxFilesize']);
}
return array_merge($defaultDropzoneOptions, $value);
});
} | {@inheritdoc} | https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/FileBundle/Form/AbstractFileType.php#L53-L80 |
Tuna-CMS/tuna-bundle | src/Tuna/Bundle/FileBundle/Form/AbstractFileType.php | AbstractFileType.getFilesize | protected static function getFilesize($filesize)
{
$value = (float)($filesize);
$unit = substr($filesize, -1);
switch ($unit) {
case 'K':
return $value / 1024;
case 'G':
return $value * 1024;
case 'M':
default:
return $value;
}
} | php | protected static function getFilesize($filesize)
{
$value = (float)($filesize);
$unit = substr($filesize, -1);
switch ($unit) {
case 'K':
return $value / 1024;
case 'G':
return $value * 1024;
case 'M':
default:
return $value;
}
} | Converts filesize string (compatible with php.ini values) to MB
@param $filesize in bytes, or with unit (`2043`, `273K`, `1.2M`, `0.3G`)
@return float | https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/FileBundle/Form/AbstractFileType.php#L104-L118 |
as3io/modlr | src/Store/Cache.php | Cache.clearType | public function clearType($typeKey)
{
if (isset($this->models[$typeKey])) {
unset($this->models[$typeKey]);
}
return $this;
} | php | public function clearType($typeKey)
{
if (isset($this->models[$typeKey])) {
unset($this->models[$typeKey]);
}
return $this;
} | Clears all models in the memory cache for a specific type.
@param string $typeKey
@return self | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Store/Cache.php#L53-L59 |
as3io/modlr | src/Store/Cache.php | Cache.push | public function push(Model $model)
{
$this->models[$model->getType()][$model->getId()] = $model;
return $this;
} | php | public function push(Model $model)
{
$this->models[$model->getType()][$model->getId()] = $model;
return $this;
} | Pushes a model into the memory cache.
@param Model $model
@return self | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Store/Cache.php#L78-L82 |
as3io/modlr | src/Store/Cache.php | Cache.remove | public function remove($typeKey, $identifier)
{
if (isset($this->models[$typeKey][$identifier])) {
unset($this->models[$typeKey][$identifier]);
}
return $this;
} | php | public function remove($typeKey, $identifier)
{
if (isset($this->models[$typeKey][$identifier])) {
unset($this->models[$typeKey][$identifier]);
}
return $this;
} | Removes a model from the memory cache, based on type and identifier.
@param string $typeKey
@param string $identifier
@return self | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Store/Cache.php#L91-L97 |
as3io/modlr | src/Store/Cache.php | Cache.get | public function get($typeKey, $identifier)
{
$map = $this->getAllForType($typeKey);
if (isset($map[$identifier])) {
return $map[$identifier];
}
return null;
} | php | public function get($typeKey, $identifier)
{
$map = $this->getAllForType($typeKey);
if (isset($map[$identifier])) {
return $map[$identifier];
}
return null;
} | Gets a model from the memory cache, based on type and identifier.
@param string $typeKey
@param string $identifier
@return Model|null | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Store/Cache.php#L106-L113 |
CampaignChain/activity-ezplatform | Controller/EZPlatformScheduleHandler.php | EZPlatformScheduleHandler.createContent | public function createContent(Location $location = null, Campaign $campaign = null)
{
$connection = $this->getRestApiConnectionByLocation($location);
$remoteContentTypes = $connection->getContentTypes();
foreach($remoteContentTypes as $remoteContentType){
$id = $location->getId().'-'.$remoteContentType['id'];
$name = $remoteContentType['names']['value'][0]['#text'];
$contentTypes[$id] = $name;
}
return $contentTypes;
} | php | public function createContent(Location $location = null, Campaign $campaign = null)
{
$connection = $this->getRestApiConnectionByLocation($location);
$remoteContentTypes = $connection->getContentTypes();
foreach($remoteContentTypes as $remoteContentType){
$id = $location->getId().'-'.$remoteContentType['id'];
$name = $remoteContentType['names']['value'][0]['#text'];
$contentTypes[$id] = $name;
}
return $contentTypes;
} | When a new Activity is being created, this handler method will be called
to retrieve a new Content object for the Activity.
Called in these views:
- new
@param Location $location
@param Campaign $campaign
@return null | https://github.com/CampaignChain/activity-ezplatform/blob/bf965121bda47d90bcdcf4ef1d651fd9ec42113e/Controller/EZPlatformScheduleHandler.php#L67-L79 |
CampaignChain/activity-ezplatform | Controller/EZPlatformScheduleHandler.php | EZPlatformScheduleHandler.processContentLocation | public function processContentLocation(Location $location, $data)
{
$connection = $this->getRestApiConnectionByLocation();
$remoteContentObject = $connection->getContentObject($data['content_object']);
$location->setIdentifier($remoteContentObject['_id']);
$location->setName($remoteContentObject['Name']);
return $location;
} | php | public function processContentLocation(Location $location, $data)
{
$connection = $this->getRestApiConnectionByLocation();
$remoteContentObject = $connection->getContentObject($data['content_object']);
$location->setIdentifier($remoteContentObject['_id']);
$location->setName($remoteContentObject['Name']);
return $location;
} | After a new Activity was created, this method makes it possible to alter
the data of the Content's Location (not the Activity's Location!) as per
the data provided for the Content.
Called in these views:
- new
@param Location $location Location of the Content.
@param $data Form submit data of the Content.
@return Location | https://github.com/CampaignChain/activity-ezplatform/blob/bf965121bda47d90bcdcf4ef1d651fd9ec42113e/Controller/EZPlatformScheduleHandler.php#L141-L149 |
kleijnweb/php-api-middleware | src/OperationMatcher.php | OperationMatcher.process | public function process(ServerRequestInterface $request, DelegateInterface $delegate)
{
$uriPath = $request->getUri()->getPath();
/** @var Description $description */
foreach ($this->repository as $description) {
$basePath = $description->getBasePath() ? "{$description->getBasePath()}/" : "";
foreach ($description->getPaths() as $path) {
$pathPattern = "$basePath{$path->getPath()}";
$parameterNames = [];
foreach ($path->getOperations() as $operation) {
foreach ($operation->getParameters() as $parameter) {
if ($parameter->getIn() === Parameter::IN_PATH
&& ($schema = $parameter->getSchema()) instanceof ScalarSchema
) {
$parameterName = $parameter->getName();
$parameterNames[] = $parameterName;
$typePattern = $this->typePatternResolver->resolve($schema);
$parameterPattern = "(?P<$parameterName>$typePattern)(?=(/|$))";
$pathPattern = str_replace('{' . $parameterName . '}', $parameterPattern, $pathPattern);
}
}
if (preg_match("#^$pathPattern$#", $uriPath, $matches) > 0) {
if (strtolower($request->getMethod()) !== $operation->getMethod()) {
return Factory::createResponse(405);
}
$request = Meta::requestWith($request, $description, $operation, $path);
foreach ($parameterNames as $parameterName) {
$request = $request->withAttribute($parameterName, $matches[$parameterName]);
}
return $delegate->process($request);
}
}
}
}
return Factory::createResponse(404);
} | php | public function process(ServerRequestInterface $request, DelegateInterface $delegate)
{
$uriPath = $request->getUri()->getPath();
/** @var Description $description */
foreach ($this->repository as $description) {
$basePath = $description->getBasePath() ? "{$description->getBasePath()}/" : "";
foreach ($description->getPaths() as $path) {
$pathPattern = "$basePath{$path->getPath()}";
$parameterNames = [];
foreach ($path->getOperations() as $operation) {
foreach ($operation->getParameters() as $parameter) {
if ($parameter->getIn() === Parameter::IN_PATH
&& ($schema = $parameter->getSchema()) instanceof ScalarSchema
) {
$parameterName = $parameter->getName();
$parameterNames[] = $parameterName;
$typePattern = $this->typePatternResolver->resolve($schema);
$parameterPattern = "(?P<$parameterName>$typePattern)(?=(/|$))";
$pathPattern = str_replace('{' . $parameterName . '}', $parameterPattern, $pathPattern);
}
}
if (preg_match("#^$pathPattern$#", $uriPath, $matches) > 0) {
if (strtolower($request->getMethod()) !== $operation->getMethod()) {
return Factory::createResponse(405);
}
$request = Meta::requestWith($request, $description, $operation, $path);
foreach ($parameterNames as $parameterName) {
$request = $request->withAttribute($parameterName, $matches[$parameterName]);
}
return $delegate->process($request);
}
}
}
}
return Factory::createResponse(404);
} | Process a server request and return a response.
@param ServerRequestInterface $request
@param DelegateInterface $delegate
@return ResponseInterface | https://github.com/kleijnweb/php-api-middleware/blob/e9e74706c3b30a0e06c7f0f7e2a3a43ef17e6df4/src/OperationMatcher.php#L51-L96 |
stefanotorresi/MyBase | src/Filter/FileArrayToString.php | FileArrayToString.filter | public function filter($value)
{
if (is_object($value) && ! method_exists($value, '__toString')) {
return '';
}
if (is_array($value)) {
$dummy = [
'name' => '',
'tmp_name' => '',
'error' => UPLOAD_ERR_NO_FILE,
'size' => 0,
'type' => '',
];
$value = ArrayUtils::merge($dummy, $value);
} else {
$value = (string) $value;
}
if (isset($value['error']) && $value['error'] !== UPLOAD_ERR_OK) {
return '';
}
if ($this->options['use_uploaded_name'] && isset($value['name'])) {
$value = $value['name'];
} elseif (isset($value['tmp_name'])) {
$value = $value['tmp_name'];
}
if ($this->options['basename']) {
$value = basename($value);
}
return $value;
} | php | public function filter($value)
{
if (is_object($value) && ! method_exists($value, '__toString')) {
return '';
}
if (is_array($value)) {
$dummy = [
'name' => '',
'tmp_name' => '',
'error' => UPLOAD_ERR_NO_FILE,
'size' => 0,
'type' => '',
];
$value = ArrayUtils::merge($dummy, $value);
} else {
$value = (string) $value;
}
if (isset($value['error']) && $value['error'] !== UPLOAD_ERR_OK) {
return '';
}
if ($this->options['use_uploaded_name'] && isset($value['name'])) {
$value = $value['name'];
} elseif (isset($value['tmp_name'])) {
$value = $value['tmp_name'];
}
if ($this->options['basename']) {
$value = basename($value);
}
return $value;
} | {@inheritdoc}
@return string | https://github.com/stefanotorresi/MyBase/blob/9ed131a1e36b4b6cbd9989ae27c849f60bba0a03/src/Filter/FileArrayToString.php#L30-L64 |
uiii/tense | src/Console/BoxOutputFormatterStyle.php | BoxOutputFormatterStyle.setPadding | public function setPadding($padding = 0) {
$padding = $this->parseSizes($padding);
foreach ($padding as $side => $value) {
if (! is_int($value) || $value < 0) {
throw new InvalidArgumentException(sprintf(
'Invalid %s padding: "%s". Must be a positive integer value.',
$side, $value
));
}
$this->padding[$side] = $value;
}
} | php | public function setPadding($padding = 0) {
$padding = $this->parseSizes($padding);
foreach ($padding as $side => $value) {
if (! is_int($value) || $value < 0) {
throw new InvalidArgumentException(sprintf(
'Invalid %s padding: "%s". Must be a positive integer value.',
$side, $value
));
}
$this->padding[$side] = $value;
}
} | Sets style padding.
@param array|int $padding The padding value/s | https://github.com/uiii/tense/blob/e5fb4d123f41dbf23796b445389b966c8de2bae1/src/Console/BoxOutputFormatterStyle.php#L102-L115 |
uiii/tense | src/Console/BoxOutputFormatterStyle.php | BoxOutputFormatterStyle.setMargin | public function setMargin($margin = 0) {
$margin = $this->parseSizes($margin);
foreach ($margin as $side => $value) {
if (! is_int($value) || $value < 0) {
throw new InvalidArgumentException(sprintf(
'Invalid %s margin: "%s". Must be a positive integer value.',
$side, $value
));
}
$this->margin[$side] = $value;
}
} | php | public function setMargin($margin = 0) {
$margin = $this->parseSizes($margin);
foreach ($margin as $side => $value) {
if (! is_int($value) || $value < 0) {
throw new InvalidArgumentException(sprintf(
'Invalid %s margin: "%s". Must be a positive integer value.',
$side, $value
));
}
$this->margin[$side] = $value;
}
} | Sets style margin.
@param array|int $margin The margin value/s | https://github.com/uiii/tense/blob/e5fb4d123f41dbf23796b445389b966c8de2bae1/src/Console/BoxOutputFormatterStyle.php#L122-L135 |
uiii/tense | src/Console/BoxOutputFormatterStyle.php | BoxOutputFormatterStyle.apply | public function apply($text) {
$lines = preg_split("/\\r\\n|\\n|\\r/", $text);
$lines = $this->wrapLines($lines, $this->padding);
$lines = array_map(function ($line) {
return parent::apply($line);
}, $lines);
$lines = $this->wrapLines($lines, $this->margin);
return implode(PHP_EOL, $lines);;
} | php | public function apply($text) {
$lines = preg_split("/\\r\\n|\\n|\\r/", $text);
$lines = $this->wrapLines($lines, $this->padding);
$lines = array_map(function ($line) {
return parent::apply($line);
}, $lines);
$lines = $this->wrapLines($lines, $this->margin);
return implode(PHP_EOL, $lines);;
} | Applies the style to a given text.
@param string $text The text to style
@return string | https://github.com/uiii/tense/blob/e5fb4d123f41dbf23796b445389b966c8de2bae1/src/Console/BoxOutputFormatterStyle.php#L144-L156 |
brainexe/core | src/Redis/Command/Export.php | Export.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$keys = $this->redis->keys('*');
$parts = [];
foreach ($keys as $key) {
$parts = array_merge($parts, $this->dump($key));
}
$content = implode("\n\n", $parts);
$output->writeln($content);
$file = $input->getArgument('file');
if ($file) {
file_put_contents($file, $content);
}
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$keys = $this->redis->keys('*');
$parts = [];
foreach ($keys as $key) {
$parts = array_merge($parts, $this->dump($key));
}
$content = implode("\n\n", $parts);
$output->writeln($content);
$file = $input->getArgument('file');
if ($file) {
file_put_contents($file, $content);
}
} | {@inheritdoc} | https://github.com/brainexe/core/blob/9ef69c6f045306abd20e271572386970db9b3e54/src/Redis/Command/Export.php#L37-L54 |
gplcart/file_manager | handlers/commands/Upload.php | Upload.submit | public function submit($controller)
{
$result = $controller->getSubmitted('uploaded', array());
$vars = array(
'@num_errors' => count($result['errors']),
'@num_success' => count($result['transferred'])
);
$files = $controller->getSubmitted('files');
/* @var $file \SplFileInfo */
$file = reset($files);
$query = array(
'cmd' => 'list',
'path' => $this->getRelativeFilePath($file->getRealPath())
);
return array(
'redirect' => $controller->url('', $query),
'severity' => empty($result['errors']) ? 'success' : 'warning',
'message' => $this->translation->text('Uploaded @num_success, errors: @num_errors', $vars)
);
} | php | public function submit($controller)
{
$result = $controller->getSubmitted('uploaded', array());
$vars = array(
'@num_errors' => count($result['errors']),
'@num_success' => count($result['transferred'])
);
$files = $controller->getSubmitted('files');
/* @var $file \SplFileInfo */
$file = reset($files);
$query = array(
'cmd' => 'list',
'path' => $this->getRelativeFilePath($file->getRealPath())
);
return array(
'redirect' => $controller->url('', $query),
'severity' => empty($result['errors']) ? 'success' : 'warning',
'message' => $this->translation->text('Uploaded @num_success, errors: @num_errors', $vars)
);
} | Upload files
@param \gplcart\core\Controller $controller
@return array | https://github.com/gplcart/file_manager/blob/45424e93eafea75d31af6410ac9cf110f08e500a/handlers/commands/Upload.php#L61-L85 |
loevgaard/dandomain-api | src/Endpoint/Order.php | Order.deleteOrder | public function deleteOrder(int $orderId) : bool
{
Assert::that($orderId)->greaterThan(0, 'The $orderId has to be positive');
return (bool)$this->master->doRequest('DELETE', sprintf('/admin/WEBAPI/Endpoints/v1_0/OrderService/{KEY}/%d', $orderId));
} | php | public function deleteOrder(int $orderId) : bool
{
Assert::that($orderId)->greaterThan(0, 'The $orderId has to be positive');
return (bool)$this->master->doRequest('DELETE', sprintf('/admin/WEBAPI/Endpoints/v1_0/OrderService/{KEY}/%d', $orderId));
} | Deletes an order
@param int $orderId
@return bool | https://github.com/loevgaard/dandomain-api/blob/cd420d5f92a78eece4201ab57a5f6356537ed371/src/Endpoint/Order.php#L77-L82 |
loevgaard/dandomain-api | src/Endpoint/Order.php | Order.copyOrder | public function copyOrder(int $orderId, array $orderLines = [], int $orderState = 0, bool $completeOrder = true) : array
{
Assert::that($orderId)->greaterThan(0, 'The $orderId has to be positive');
$order = $this->getOrder($orderId);
$data = [
'siteId' => $order['siteId'],
'altDeliveryInfo' => null,
'currencyCode' => $order['currencyCode'],
'customerId' => $order['customerInfo']['id'],
'paymentId' => $order['paymentInfo']['id'],
'shippingId' => $order['shippingInfo']['id'],
'orderLines' => $order['orderLines']
];
if (!empty($orderLines)) {
$data['orderLines'] = $orderLines;
}
$newOrder = $this->createOrder($data);
$newOrderId = (int)$newOrder['id'];
if ($completeOrder) {
$this->completeOrder($newOrderId);
}
if ($orderState) {
$this->setOrderState($newOrderId, $orderState);
}
return $newOrder;
} | php | public function copyOrder(int $orderId, array $orderLines = [], int $orderState = 0, bool $completeOrder = true) : array
{
Assert::that($orderId)->greaterThan(0, 'The $orderId has to be positive');
$order = $this->getOrder($orderId);
$data = [
'siteId' => $order['siteId'],
'altDeliveryInfo' => null,
'currencyCode' => $order['currencyCode'],
'customerId' => $order['customerInfo']['id'],
'paymentId' => $order['paymentInfo']['id'],
'shippingId' => $order['shippingInfo']['id'],
'orderLines' => $order['orderLines']
];
if (!empty($orderLines)) {
$data['orderLines'] = $orderLines;
}
$newOrder = $this->createOrder($data);
$newOrderId = (int)$newOrder['id'];
if ($completeOrder) {
$this->completeOrder($newOrderId);
}
if ($orderState) {
$this->setOrderState($newOrderId, $orderState);
}
return $newOrder;
} | Will copy an order based on the order id
If the $orderLines is empty, it will also copy the order lines
If the $orderState is > 0, the method will update the order state
If $completeOrder is true, the method will also complete the order, otherwise it will be marked as incomplete by default
Returns the new order
@param int $orderId
@param array $orderLines
@param int $orderState
@param boolean $completeOrder
@return array | https://github.com/loevgaard/dandomain-api/blob/cd420d5f92a78eece4201ab57a5f6356537ed371/src/Endpoint/Order.php#L222-L254 |
drakonli/php-imap | src/PhpImap/Mail/Attachment/File/Name/Decoder/Basic/BasicAttachmentFileNameDecoder.php | BasicAttachmentFileNameDecoder.decodeRFC2231 | private function decodeRFC2231(\SplString $string)
{
if (1 !== preg_match("/^(.*?)'.*?'(.*?)$/", $string, $matches)) {
return $string;
}
$encoding = $matches[1];
$data = $matches[2];
if (false === $this->urlHelper->isUrlEncoded($data)) {
return $string;
}
$string = $this->encodingConverter->convertStringEncoding(
urldecode($data),
$encoding,
$this->serverEncoding
);
return new \SplString($string);
} | php | private function decodeRFC2231(\SplString $string)
{
if (1 !== preg_match("/^(.*?)'.*?'(.*?)$/", $string, $matches)) {
return $string;
}
$encoding = $matches[1];
$data = $matches[2];
if (false === $this->urlHelper->isUrlEncoded($data)) {
return $string;
}
$string = $this->encodingConverter->convertStringEncoding(
urldecode($data),
$encoding,
$this->serverEncoding
);
return new \SplString($string);
} | @param \SplString $string
@return \SplString | https://github.com/drakonli/php-imap/blob/966dbb5d639897712d1570d62d3ce9bde3376089/src/PhpImap/Mail/Attachment/File/Name/Decoder/Basic/BasicAttachmentFileNameDecoder.php#L72-L92 |
wigedev/farm | src/Validator/Validator/Validator.php | Validator.quickValidate | public static function quickValidate(?string $value, array $constraints = [])
{
// Initialize the validator
$validator = new static('quickValidate function', InputFieldTypes::PASSED, [], $value, null);
// Add the constraints
if (is_array($constraints) && count($constraints) > 0) {
foreach ($constraints as $constraint) {
/** @var Constraint|array $constraint */
if (is_array($constraint) && count($constraint) > 0) {
$validator->addConstraint(Constraint::factory($constraint));
} elseif (!is_array($constraint)) {
$validator->addConstraint($constraint);
}
}
}
// Return the value or throw an exception
if ($validator->isValid()) {
return $validator->getValue();
} else {
throw new InvalidInputException('The value is not valid.');
}
} | php | public static function quickValidate(?string $value, array $constraints = [])
{
// Initialize the validator
$validator = new static('quickValidate function', InputFieldTypes::PASSED, [], $value, null);
// Add the constraints
if (is_array($constraints) && count($constraints) > 0) {
foreach ($constraints as $constraint) {
/** @var Constraint|array $constraint */
if (is_array($constraint) && count($constraint) > 0) {
$validator->addConstraint(Constraint::factory($constraint));
} elseif (!is_array($constraint)) {
$validator->addConstraint($constraint);
}
}
}
// Return the value or throw an exception
if ($validator->isValid()) {
return $validator->getValue();
} else {
throw new InvalidInputException('The value is not valid.');
}
} | Validates input as a one-off. Allows quick and dirty validation. Returns null if the value is not valid.
TODO: Decide should this just return true/false if the value is/not valid?
@param string $value The value to test
@param array $constraints The definition of the constraints
@return mixed The value if valid
@throws InvalidInputException If the value is not valid | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/Validator/Validator/Validator.php#L51-L73 |
wigedev/farm | src/Validator/Validator/Validator.php | Validator.addConstraint | public function addConstraint(Constraint $constraint) : void
{
$constraint->setValidator($this);
array_push($this->constraints, $constraint);
} | php | public function addConstraint(Constraint $constraint) : void
{
$constraint->setValidator($this);
array_push($this->constraints, $constraint);
} | Add a constraint to the validator
@param Constraint $constraint | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/Validator/Validator/Validator.php#L125-L129 |
wigedev/farm | src/Validator/Validator/Validator.php | Validator.reportError | public function reportError(string $error_message) : void
{
$error_message = sprintf($error_message, $this->field_name);
if (null != $this->validation_set) {
$this->validation_set->addValidationError(new ValidationError($this->field_name, $error_message));
}
} | php | public function reportError(string $error_message) : void
{
$error_message = sprintf($error_message, $this->field_name);
if (null != $this->validation_set) {
$this->validation_set->addValidationError(new ValidationError($this->field_name, $error_message));
}
} | Report the error message to validation set
@param string $error_message The error message to report | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/Validator/Validator/Validator.php#L164-L170 |
wigedev/farm | src/Validator/Validator/Validator.php | Validator.validate | public function validate() : void
{
$this->value = null;
$value = $this->filter($this->raw_value);
if (true === $this->checkValidity($value)) {
$this->is_valid = true;
} else {
$this->is_valid = false;
$this->reportError($this->error_message);
$error_message = sprintf($this->error_message, $this->field_name);
$this->the_message = $error_message;
}
// If no issues have been found, check the constraints.
if ($this->is_valid) {
foreach ($this->constraints as $constraint) {
if (false === $constraint->check($value)) {
$this->is_valid = false;
$this->the_message = sprintf($constraint->getErrorMessage(), $this->field_name);
}
}
}
// Set the value for retrieval
if ($this->is_valid) {
$this->value = $value;
}
} | php | public function validate() : void
{
$this->value = null;
$value = $this->filter($this->raw_value);
if (true === $this->checkValidity($value)) {
$this->is_valid = true;
} else {
$this->is_valid = false;
$this->reportError($this->error_message);
$error_message = sprintf($this->error_message, $this->field_name);
$this->the_message = $error_message;
}
// If no issues have been found, check the constraints.
if ($this->is_valid) {
foreach ($this->constraints as $constraint) {
if (false === $constraint->check($value)) {
$this->is_valid = false;
$this->the_message = sprintf($constraint->getErrorMessage(), $this->field_name);
}
}
}
// Set the value for retrieval
if ($this->is_valid) {
$this->value = $value;
}
} | Do the validation. This process starts by filtering the value, then checks the validity, and finally checks
the constraints. | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/Validator/Validator/Validator.php#L223-L248 |
wigedev/farm | src/Validator/Validator/Validator.php | Validator.checkValidity | protected function checkValidity($value) : bool
{
if (preg_match(static::$regex, $value)) {
return true;
} elseif ('' === $value) {
return true;
} else {
return false;
}
} | php | protected function checkValidity($value) : bool
{
if (preg_match(static::$regex, $value)) {
return true;
} elseif ('' === $value) {
return true;
} else {
return false;
}
} | This is the function that does the actual checking. This should allow either matches to the regex or empty
values.
@param mixed $value The value being checked
@return bool True if the value is valid | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/Validator/Validator/Validator.php#L275-L284 |
chilimatic/chilimatic-framework | lib/view/PHtml.php | PHtml.render | public function render($templateFile = '')
{
if ($templateFile) {
$this->setTemplateFile($templateFile);
}
$this->initRender();
if (!$this->getTemplateFile()) {
throw new \LogicException('no template given');
}
try {
ob_start();
include $this->getTemplateFile();
$this->content = ob_get_clean();
} catch (\Exception $e) {
ob_end_clean();
throw new \ErrorException($e->getMessage(), $e->getCode());
}
return $this->content;
} | php | public function render($templateFile = '')
{
if ($templateFile) {
$this->setTemplateFile($templateFile);
}
$this->initRender();
if (!$this->getTemplateFile()) {
throw new \LogicException('no template given');
}
try {
ob_start();
include $this->getTemplateFile();
$this->content = ob_get_clean();
} catch (\Exception $e) {
ob_end_clean();
throw new \ErrorException($e->getMessage(), $e->getCode());
}
return $this->content;
} | @param string $templateFile
@throws \LogicException
@throws \ErrorException
@return string | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/view/PHtml.php#L57-L80 |
peridot-php/peridot-dot-reporter | src/DotReporter.php | DotReporter.init | public function init()
{
$this->eventEmitter->on('test.passed', [$this, 'onTestPassed']);
$this->eventEmitter->on('test.failed', [$this, 'onTestFailed']);
$this->eventEmitter->on('test.pending', [$this, 'onTestPending']);
$this->eventEmitter->on('runner.end', [$this, 'onRunnerEnd']);
} | php | public function init()
{
$this->eventEmitter->on('test.passed', [$this, 'onTestPassed']);
$this->eventEmitter->on('test.failed', [$this, 'onTestFailed']);
$this->eventEmitter->on('test.pending', [$this, 'onTestPending']);
$this->eventEmitter->on('runner.end', [$this, 'onRunnerEnd']);
} | {@inheritdoc}
@return void | https://github.com/peridot-php/peridot-dot-reporter/blob/489f88000b8668487a2c1e5a872d4550af396899/src/DotReporter.php#L29-L35 |
yii2lab/yii2-rbac | src/domain/repositories/traits/AssignmentTrait.php | AssignmentTrait.getAssignments | public function getAssignments($userId) {
if(empty($userId)) {
return [];
}
$roles = $this->allRoleNamesByUserId($userId);
return AssignmentHelper::forge($userId, $roles);
} | php | public function getAssignments($userId) {
if(empty($userId)) {
return [];
}
$roles = $this->allRoleNamesByUserId($userId);
return AssignmentHelper::forge($userId, $roles);
} | Returns all role assignment information for the specified user.
@param string|int $userId the user ID (see [[\yii\web\User::id]])
@return Assignment[] the assignments indexed by role names. An empty array will be
returned if there is no role assigned to the user. | https://github.com/yii2lab/yii2-rbac/blob/e72ac0359af660690c161451f864208b2d20919d/src/domain/repositories/traits/AssignmentTrait.php#L114-L120 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.