repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
PenoaksDev/Milky-Framework
src/Milky/Database/Eloquent/Nested/SetBuilder.php
SetBuilder.rebuild
public function rebuild( $force = false ) { $alreadyValid = forward_static_call( [get_class( $this->model ), 'isValidNestedSet'] ); // Do not rebuild a valid Nested Set tree structure if ( !$force && $alreadyValid ) return true; // Rebuild lefts and rights for each root node and its children (recursively). // We go by setting left (and keep track of the current left bound), then // search for each children and recursively set the left index (while // incrementing that index). When going back up the recursive chain we start // setting the right indexes and saving the nodes... $self = $this; $this->model->getConnection()->transaction( function () use ( $self ) { foreach ( $self->roots() as $root ) $self->rebuildBounds( $root, 0 ); } ); return false; }
php
public function rebuild( $force = false ) { $alreadyValid = forward_static_call( [get_class( $this->model ), 'isValidNestedSet'] ); // Do not rebuild a valid Nested Set tree structure if ( !$force && $alreadyValid ) return true; // Rebuild lefts and rights for each root node and its children (recursively). // We go by setting left (and keep track of the current left bound), then // search for each children and recursively set the left index (while // incrementing that index). When going back up the recursive chain we start // setting the right indexes and saving the nodes... $self = $this; $this->model->getConnection()->transaction( function () use ( $self ) { foreach ( $self->roots() as $root ) $self->rebuildBounds( $root, 0 ); } ); return false; }
[ "public", "function", "rebuild", "(", "$", "force", "=", "false", ")", "{", "$", "alreadyValid", "=", "forward_static_call", "(", "[", "get_class", "(", "$", "this", "->", "model", ")", ",", "'isValidNestedSet'", "]", ")", ";", "// Do not rebuild a valid Nested Set tree structure", "if", "(", "!", "$", "force", "&&", "$", "alreadyValid", ")", "return", "true", ";", "// Rebuild lefts and rights for each root node and its children (recursively).", "// We go by setting left (and keep track of the current left bound), then", "// search for each children and recursively set the left index (while", "// incrementing that index). When going back up the recursive chain we start", "// setting the right indexes and saving the nodes...", "$", "self", "=", "$", "this", ";", "$", "this", "->", "model", "->", "getConnection", "(", ")", "->", "transaction", "(", "function", "(", ")", "use", "(", "$", "self", ")", "{", "foreach", "(", "$", "self", "->", "roots", "(", ")", "as", "$", "root", ")", "$", "self", "->", "rebuildBounds", "(", "$", "root", ",", "0", ")", ";", "}", ")", ";", "return", "false", ";", "}" ]
Perform the re-calculation of the left and right indexes of the whole nested set tree structure. @param bool $force @return bool
[ "Perform", "the", "re", "-", "calculation", "of", "the", "left", "and", "right", "indexes", "of", "the", "whole", "nested", "set", "tree", "structure", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Database/Eloquent/Nested/SetBuilder.php#L39-L61
train
PenoaksDev/Milky-Framework
src/Milky/Database/Eloquent/Nested/SetBuilder.php
SetBuilder.roots
public function roots() { return $this->model->newQuery()->whereNull( $this->model->getQualifiedParentColumnName() )->orderBy( $this->model->getQualifiedLeftColumnName() )->orderBy( $this->model->getQualifiedRightColumnName() )->orderBy( $this->model->getQualifiedKeyName() )->get(); }
php
public function roots() { return $this->model->newQuery()->whereNull( $this->model->getQualifiedParentColumnName() )->orderBy( $this->model->getQualifiedLeftColumnName() )->orderBy( $this->model->getQualifiedRightColumnName() )->orderBy( $this->model->getQualifiedKeyName() )->get(); }
[ "public", "function", "roots", "(", ")", "{", "return", "$", "this", "->", "model", "->", "newQuery", "(", ")", "->", "whereNull", "(", "$", "this", "->", "model", "->", "getQualifiedParentColumnName", "(", ")", ")", "->", "orderBy", "(", "$", "this", "->", "model", "->", "getQualifiedLeftColumnName", "(", ")", ")", "->", "orderBy", "(", "$", "this", "->", "model", "->", "getQualifiedRightColumnName", "(", ")", ")", "->", "orderBy", "(", "$", "this", "->", "model", "->", "getQualifiedKeyName", "(", ")", ")", "->", "get", "(", ")", ";", "}" ]
Return all root nodes for the current database table appropiately sorted. @return Collection
[ "Return", "all", "root", "nodes", "for", "the", "current", "database", "table", "appropiately", "sorted", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Database/Eloquent/Nested/SetBuilder.php#L68-L71
train
PenoaksDev/Milky-Framework
src/Milky/Database/Eloquent/Nested/SetBuilder.php
SetBuilder.children
public function children( $model ) { $query = $this->model->newQuery(); $query->where( $this->model->getQualifiedParentColumnName(), '=', $model->getKey() ); // We must also add the scoped column values to the query to compute valid // left and right indexes. foreach ( $this->scopedAttributes( $model ) as $fld => $value ) $query->where( $this->qualify( $fld ), '=', $value ); $query->orderBy( $this->model->getQualifiedLeftColumnName() ); $query->orderBy( $this->model->getQualifiedRightColumnName() ); $query->orderBy( $this->model->getQualifiedKeyName() ); return $query->get(); }
php
public function children( $model ) { $query = $this->model->newQuery(); $query->where( $this->model->getQualifiedParentColumnName(), '=', $model->getKey() ); // We must also add the scoped column values to the query to compute valid // left and right indexes. foreach ( $this->scopedAttributes( $model ) as $fld => $value ) $query->where( $this->qualify( $fld ), '=', $value ); $query->orderBy( $this->model->getQualifiedLeftColumnName() ); $query->orderBy( $this->model->getQualifiedRightColumnName() ); $query->orderBy( $this->model->getQualifiedKeyName() ); return $query->get(); }
[ "public", "function", "children", "(", "$", "model", ")", "{", "$", "query", "=", "$", "this", "->", "model", "->", "newQuery", "(", ")", ";", "$", "query", "->", "where", "(", "$", "this", "->", "model", "->", "getQualifiedParentColumnName", "(", ")", ",", "'='", ",", "$", "model", "->", "getKey", "(", ")", ")", ";", "// We must also add the scoped column values to the query to compute valid", "// left and right indexes.", "foreach", "(", "$", "this", "->", "scopedAttributes", "(", "$", "model", ")", "as", "$", "fld", "=>", "$", "value", ")", "$", "query", "->", "where", "(", "$", "this", "->", "qualify", "(", "$", "fld", ")", ",", "'='", ",", "$", "value", ")", ";", "$", "query", "->", "orderBy", "(", "$", "this", "->", "model", "->", "getQualifiedLeftColumnName", "(", ")", ")", ";", "$", "query", "->", "orderBy", "(", "$", "this", "->", "model", "->", "getQualifiedRightColumnName", "(", ")", ")", ";", "$", "query", "->", "orderBy", "(", "$", "this", "->", "model", "->", "getQualifiedKeyName", "(", ")", ")", ";", "return", "$", "query", "->", "get", "(", ")", ";", "}" ]
Return all children for the specified node. @param NestedModel $model @return Collection
[ "Return", "all", "children", "for", "the", "specified", "node", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Database/Eloquent/Nested/SetBuilder.php#L98-L114
train
PenoaksDev/Milky-Framework
src/Milky/Database/Eloquent/Nested/SetBuilder.php
SetBuilder.scopedAttributes
protected function scopedAttributes( $model ) { $keys = $this->model->getScopedColumns(); if ( count( $keys ) == 0 ) return []; $values = array_map( function ( $column ) use ( $model ) { return $model->getAttribute( $column ); }, $keys ); return array_combine( $keys, $values ); }
php
protected function scopedAttributes( $model ) { $keys = $this->model->getScopedColumns(); if ( count( $keys ) == 0 ) return []; $values = array_map( function ( $column ) use ( $model ) { return $model->getAttribute( $column ); }, $keys ); return array_combine( $keys, $values ); }
[ "protected", "function", "scopedAttributes", "(", "$", "model", ")", "{", "$", "keys", "=", "$", "this", "->", "model", "->", "getScopedColumns", "(", ")", ";", "if", "(", "count", "(", "$", "keys", ")", "==", "0", ")", "return", "[", "]", ";", "$", "values", "=", "array_map", "(", "function", "(", "$", "column", ")", "use", "(", "$", "model", ")", "{", "return", "$", "model", "->", "getAttribute", "(", "$", "column", ")", ";", "}", ",", "$", "keys", ")", ";", "return", "array_combine", "(", "$", "keys", ",", "$", "values", ")", ";", "}" ]
Return an array of the scoped attributes of the supplied node. @param NestedModel $model @return array
[ "Return", "an", "array", "of", "the", "scoped", "attributes", "of", "the", "supplied", "node", "." ]
8afd7156610a70371aa5b1df50b8a212bf7b142c
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Database/Eloquent/Nested/SetBuilder.php#L122-L135
train
jenskooij/cloudcontrol
src/storage/factories/UserFactory.php
UserFactory.createUserFromPostValues
public static function createUserFromPostValues($postValues) { if (isset($postValues['username'])) { $user = new \stdClass(); $user->username = $postValues['username']; $user->slug = StringUtil::slugify($postValues['username']); $user->rights = array(); if (isset($postValues['rights'])) { $user->rights = $postValues['rights']; } if (isset($postValues['password']) && empty($postValues['password']) === false) { $crypt = new Crypt(); $user->password = $crypt->encrypt($postValues['password'], 16); $user->salt = $crypt->getLastSalt(); } else { $user->password = $postValues['passHash']; $user->salt = $postValues['salt']; } return $user; } else { throw new \Exception('Trying to create user with invalid data.'); } }
php
public static function createUserFromPostValues($postValues) { if (isset($postValues['username'])) { $user = new \stdClass(); $user->username = $postValues['username']; $user->slug = StringUtil::slugify($postValues['username']); $user->rights = array(); if (isset($postValues['rights'])) { $user->rights = $postValues['rights']; } if (isset($postValues['password']) && empty($postValues['password']) === false) { $crypt = new Crypt(); $user->password = $crypt->encrypt($postValues['password'], 16); $user->salt = $crypt->getLastSalt(); } else { $user->password = $postValues['passHash']; $user->salt = $postValues['salt']; } return $user; } else { throw new \Exception('Trying to create user with invalid data.'); } }
[ "public", "static", "function", "createUserFromPostValues", "(", "$", "postValues", ")", "{", "if", "(", "isset", "(", "$", "postValues", "[", "'username'", "]", ")", ")", "{", "$", "user", "=", "new", "\\", "stdClass", "(", ")", ";", "$", "user", "->", "username", "=", "$", "postValues", "[", "'username'", "]", ";", "$", "user", "->", "slug", "=", "StringUtil", "::", "slugify", "(", "$", "postValues", "[", "'username'", "]", ")", ";", "$", "user", "->", "rights", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "postValues", "[", "'rights'", "]", ")", ")", "{", "$", "user", "->", "rights", "=", "$", "postValues", "[", "'rights'", "]", ";", "}", "if", "(", "isset", "(", "$", "postValues", "[", "'password'", "]", ")", "&&", "empty", "(", "$", "postValues", "[", "'password'", "]", ")", "===", "false", ")", "{", "$", "crypt", "=", "new", "Crypt", "(", ")", ";", "$", "user", "->", "password", "=", "$", "crypt", "->", "encrypt", "(", "$", "postValues", "[", "'password'", "]", ",", "16", ")", ";", "$", "user", "->", "salt", "=", "$", "crypt", "->", "getLastSalt", "(", ")", ";", "}", "else", "{", "$", "user", "->", "password", "=", "$", "postValues", "[", "'passHash'", "]", ";", "$", "user", "->", "salt", "=", "$", "postValues", "[", "'salt'", "]", ";", "}", "return", "$", "user", ";", "}", "else", "{", "throw", "new", "\\", "Exception", "(", "'Trying to create user with invalid data.'", ")", ";", "}", "}" ]
Create user from POST values @param $postValues @return \stdClass @throws \Exception
[ "Create", "user", "from", "POST", "values" ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/storage/factories/UserFactory.php#L24-L48
train
black-lamp/blcms-cart
backend/controllers/OrderStatusController.php
OrderStatusController.actionSave
public function actionSave($id = null, $languageId) { if (!empty($languageId)) { if (!empty($id)) { $model = $this->findModel($id); } else { $model = new OrderStatus(); } $modelTranslation = $this->findOrCreateModelTranslation($model->id, $languageId); if ($modelTranslation->load(Yii::$app->request->post()) && $model->load(Yii::$app->request->post())) { $model->save(); $modelTranslation->language_id = $languageId; $modelTranslation->order_status_id = $model->id; if ($modelTranslation->validate()) { $modelTranslation->save(); \Yii::$app->session->setFlash('success', \Yii::t('cart', 'The record was successfully saved.')); } else { \Yii::$app->session->setFlash('error', \Yii::t('cart', 'An error occurred when saving the record.')); } return $this->redirect(['save', 'id' => $model->id, 'languageId' => $languageId ]); } return $this->render('save', [ 'model' => $model, 'modelTranslation' => $modelTranslation, 'languages' => Language::find()->all(), 'selectedLanguage' => Language::findOne($languageId) ]); } else throw new Exception(\Yii::t('cart', 'Language id can not be empty')); }
php
public function actionSave($id = null, $languageId) { if (!empty($languageId)) { if (!empty($id)) { $model = $this->findModel($id); } else { $model = new OrderStatus(); } $modelTranslation = $this->findOrCreateModelTranslation($model->id, $languageId); if ($modelTranslation->load(Yii::$app->request->post()) && $model->load(Yii::$app->request->post())) { $model->save(); $modelTranslation->language_id = $languageId; $modelTranslation->order_status_id = $model->id; if ($modelTranslation->validate()) { $modelTranslation->save(); \Yii::$app->session->setFlash('success', \Yii::t('cart', 'The record was successfully saved.')); } else { \Yii::$app->session->setFlash('error', \Yii::t('cart', 'An error occurred when saving the record.')); } return $this->redirect(['save', 'id' => $model->id, 'languageId' => $languageId ]); } return $this->render('save', [ 'model' => $model, 'modelTranslation' => $modelTranslation, 'languages' => Language::find()->all(), 'selectedLanguage' => Language::findOne($languageId) ]); } else throw new Exception(\Yii::t('cart', 'Language id can not be empty')); }
[ "public", "function", "actionSave", "(", "$", "id", "=", "null", ",", "$", "languageId", ")", "{", "if", "(", "!", "empty", "(", "$", "languageId", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "id", ")", ")", "{", "$", "model", "=", "$", "this", "->", "findModel", "(", "$", "id", ")", ";", "}", "else", "{", "$", "model", "=", "new", "OrderStatus", "(", ")", ";", "}", "$", "modelTranslation", "=", "$", "this", "->", "findOrCreateModelTranslation", "(", "$", "model", "->", "id", ",", "$", "languageId", ")", ";", "if", "(", "$", "modelTranslation", "->", "load", "(", "Yii", "::", "$", "app", "->", "request", "->", "post", "(", ")", ")", "&&", "$", "model", "->", "load", "(", "Yii", "::", "$", "app", "->", "request", "->", "post", "(", ")", ")", ")", "{", "$", "model", "->", "save", "(", ")", ";", "$", "modelTranslation", "->", "language_id", "=", "$", "languageId", ";", "$", "modelTranslation", "->", "order_status_id", "=", "$", "model", "->", "id", ";", "if", "(", "$", "modelTranslation", "->", "validate", "(", ")", ")", "{", "$", "modelTranslation", "->", "save", "(", ")", ";", "\\", "Yii", "::", "$", "app", "->", "session", "->", "setFlash", "(", "'success'", ",", "\\", "Yii", "::", "t", "(", "'cart'", ",", "'The record was successfully saved.'", ")", ")", ";", "}", "else", "{", "\\", "Yii", "::", "$", "app", "->", "session", "->", "setFlash", "(", "'error'", ",", "\\", "Yii", "::", "t", "(", "'cart'", ",", "'An error occurred when saving the record.'", ")", ")", ";", "}", "return", "$", "this", "->", "redirect", "(", "[", "'save'", ",", "'id'", "=>", "$", "model", "->", "id", ",", "'languageId'", "=>", "$", "languageId", "]", ")", ";", "}", "return", "$", "this", "->", "render", "(", "'save'", ",", "[", "'model'", "=>", "$", "model", ",", "'modelTranslation'", "=>", "$", "modelTranslation", ",", "'languages'", "=>", "Language", "::", "find", "(", ")", "->", "all", "(", ")", ",", "'selectedLanguage'", "=>", "Language", "::", "findOne", "(", "$", "languageId", ")", "]", ")", ";", "}", "else", "throw", "new", "Exception", "(", "\\", "Yii", "::", "t", "(", "'cart'", ",", "'Language id can not be empty'", ")", ")", ";", "}" ]
Creates a new or updates existing OrderStatus and OrderStatusTranslation models. If creation is successful, the browser will be redirected to the 'view' page. @param integer $id @param integer $languageId @return mixed @throws Exception
[ "Creates", "a", "new", "or", "updates", "existing", "OrderStatus", "and", "OrderStatusTranslation", "models", ".", "If", "creation", "is", "successful", "the", "browser", "will", "be", "redirected", "to", "the", "view", "page", "." ]
314796eecae3ca4ed5fecfdc0231a738af50eba7
https://github.com/black-lamp/blcms-cart/blob/314796eecae3ca4ed5fecfdc0231a738af50eba7/backend/controllers/OrderStatusController.php#L73-L109
train
black-lamp/blcms-cart
backend/controllers/OrderStatusController.php
OrderStatusController.actionDelete
public function actionDelete($id) { if (!empty($id)) { if ($id != OrderStatus::STATUS_INCOMPLETE && $id != OrderStatus::STATUS_CONFIRMED) { $status = $this->findModel($id); if (!empty($status)) { \Yii::$app->session->setFlash('success', Yii::t('cart', 'The status was successfully deleted.')); $status->delete(); } } else { \Yii::$app->session->setFlash('success', Yii::t('cart', 'Removing this status will break cart functionality.')); } return $this->redirect(['index']); } throw new NotFoundHttpException(); }
php
public function actionDelete($id) { if (!empty($id)) { if ($id != OrderStatus::STATUS_INCOMPLETE && $id != OrderStatus::STATUS_CONFIRMED) { $status = $this->findModel($id); if (!empty($status)) { \Yii::$app->session->setFlash('success', Yii::t('cart', 'The status was successfully deleted.')); $status->delete(); } } else { \Yii::$app->session->setFlash('success', Yii::t('cart', 'Removing this status will break cart functionality.')); } return $this->redirect(['index']); } throw new NotFoundHttpException(); }
[ "public", "function", "actionDelete", "(", "$", "id", ")", "{", "if", "(", "!", "empty", "(", "$", "id", ")", ")", "{", "if", "(", "$", "id", "!=", "OrderStatus", "::", "STATUS_INCOMPLETE", "&&", "$", "id", "!=", "OrderStatus", "::", "STATUS_CONFIRMED", ")", "{", "$", "status", "=", "$", "this", "->", "findModel", "(", "$", "id", ")", ";", "if", "(", "!", "empty", "(", "$", "status", ")", ")", "{", "\\", "Yii", "::", "$", "app", "->", "session", "->", "setFlash", "(", "'success'", ",", "Yii", "::", "t", "(", "'cart'", ",", "'The status was successfully deleted.'", ")", ")", ";", "$", "status", "->", "delete", "(", ")", ";", "}", "}", "else", "{", "\\", "Yii", "::", "$", "app", "->", "session", "->", "setFlash", "(", "'success'", ",", "Yii", "::", "t", "(", "'cart'", ",", "'Removing this status will break cart functionality.'", ")", ")", ";", "}", "return", "$", "this", "->", "redirect", "(", "[", "'index'", "]", ")", ";", "}", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}" ]
Deletes an existing OrderStatus model. If deletion is successful, the browser will be redirected to the 'index' page. @param integer $id @return mixed @throws Exception if user try to delete default statuses. @throws NotFoundHttpException if there is not $id.
[ "Deletes", "an", "existing", "OrderStatus", "model", ".", "If", "deletion", "is", "successful", "the", "browser", "will", "be", "redirected", "to", "the", "index", "page", "." ]
314796eecae3ca4ed5fecfdc0231a738af50eba7
https://github.com/black-lamp/blcms-cart/blob/314796eecae3ca4ed5fecfdc0231a738af50eba7/backend/controllers/OrderStatusController.php#L119-L135
train
black-lamp/blcms-cart
backend/controllers/OrderStatusController.php
OrderStatusController.findOrCreateModelTranslation
protected function findOrCreateModelTranslation($id, $languageId) { $modelTranslations = OrderStatusTranslation::find() ->where(['order_status_id' => $id, 'language_id' => $languageId])->one(); return (!empty($modelTranslations)) ? $modelTranslations : new OrderStatusTranslation(); }
php
protected function findOrCreateModelTranslation($id, $languageId) { $modelTranslations = OrderStatusTranslation::find() ->where(['order_status_id' => $id, 'language_id' => $languageId])->one(); return (!empty($modelTranslations)) ? $modelTranslations : new OrderStatusTranslation(); }
[ "protected", "function", "findOrCreateModelTranslation", "(", "$", "id", ",", "$", "languageId", ")", "{", "$", "modelTranslations", "=", "OrderStatusTranslation", "::", "find", "(", ")", "->", "where", "(", "[", "'order_status_id'", "=>", "$", "id", ",", "'language_id'", "=>", "$", "languageId", "]", ")", "->", "one", "(", ")", ";", "return", "(", "!", "empty", "(", "$", "modelTranslations", ")", ")", "?", "$", "modelTranslations", ":", "new", "OrderStatusTranslation", "(", ")", ";", "}" ]
Finds the OrderStatusTranslation model based on 'order_status_id' property. If the model is not found, a new model will be created. @param integer $id @param integer $languageId @return OrderStatusTranslation|ActiveRecord the loaded model
[ "Finds", "the", "OrderStatusTranslation", "model", "based", "on", "order_status_id", "property", ".", "If", "the", "model", "is", "not", "found", "a", "new", "model", "will", "be", "created", "." ]
314796eecae3ca4ed5fecfdc0231a738af50eba7
https://github.com/black-lamp/blcms-cart/blob/314796eecae3ca4ed5fecfdc0231a738af50eba7/backend/controllers/OrderStatusController.php#L160-L165
train
eureka-framework/component-http
src/Http/Message/Request.php
Request.createFromServerRequest
public static function createFromServerRequest(ServerRequest $serverRequest) { return new Request( $serverRequest->getMethod(), $serverRequest->getUri(), $serverRequest->getHeaders(), $serverRequest->getBody(), $serverRequest->getProtocolVersion() ); }
php
public static function createFromServerRequest(ServerRequest $serverRequest) { return new Request( $serverRequest->getMethod(), $serverRequest->getUri(), $serverRequest->getHeaders(), $serverRequest->getBody(), $serverRequest->getProtocolVersion() ); }
[ "public", "static", "function", "createFromServerRequest", "(", "ServerRequest", "$", "serverRequest", ")", "{", "return", "new", "Request", "(", "$", "serverRequest", "->", "getMethod", "(", ")", ",", "$", "serverRequest", "->", "getUri", "(", ")", ",", "$", "serverRequest", "->", "getHeaders", "(", ")", ",", "$", "serverRequest", "->", "getBody", "(", ")", ",", "$", "serverRequest", "->", "getProtocolVersion", "(", ")", ")", ";", "}" ]
Build Request from a server Request. @param ServerRequest $serverRequest @return Request
[ "Build", "Request", "from", "a", "server", "Request", "." ]
698c3b73581a9703a9c932890c57e50f8774607a
https://github.com/eureka-framework/component-http/blob/698c3b73581a9703a9c932890c57e50f8774607a/src/Http/Message/Request.php#L148-L157
train
eureka-framework/component-http
src/Http/Message/Request.php
Request.replaceHostHeader
private function replaceHostHeader(UriInterface $uri) { $host = $uri->getHost(); if (!empty($host)) { $port = $uri->getPort(); if (!empty($port)) { $host .= ':' . $port; } //~ Ensure Host is the first header. See: http://tools.ietf.org/html/rfc7230#section-5.4 $this->headersOriginal = ['Host' => [$host]] + $this->headersOriginal; $this->headers = ['host' => [$host]] + $this->headers; } }
php
private function replaceHostHeader(UriInterface $uri) { $host = $uri->getHost(); if (!empty($host)) { $port = $uri->getPort(); if (!empty($port)) { $host .= ':' . $port; } //~ Ensure Host is the first header. See: http://tools.ietf.org/html/rfc7230#section-5.4 $this->headersOriginal = ['Host' => [$host]] + $this->headersOriginal; $this->headers = ['host' => [$host]] + $this->headers; } }
[ "private", "function", "replaceHostHeader", "(", "UriInterface", "$", "uri", ")", "{", "$", "host", "=", "$", "uri", "->", "getHost", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "host", ")", ")", "{", "$", "port", "=", "$", "uri", "->", "getPort", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "port", ")", ")", "{", "$", "host", ".=", "':'", ".", "$", "port", ";", "}", "//~ Ensure Host is the first header. See: http://tools.ietf.org/html/rfc7230#section-5.4", "$", "this", "->", "headersOriginal", "=", "[", "'Host'", "=>", "[", "$", "host", "]", "]", "+", "$", "this", "->", "headersOriginal", ";", "$", "this", "->", "headers", "=", "[", "'host'", "=>", "[", "$", "host", "]", "]", "+", "$", "this", "->", "headers", ";", "}", "}" ]
Update host header if host is not empty. @param UriInterface $uri @return void
[ "Update", "host", "header", "if", "host", "is", "not", "empty", "." ]
698c3b73581a9703a9c932890c57e50f8774607a
https://github.com/eureka-framework/component-http/blob/698c3b73581a9703a9c932890c57e50f8774607a/src/Http/Message/Request.php#L165-L180
train
brightnucleus/keys
src/UUID.php
UUID.unserialize
public function unserialize($serialized) { $string = unserialize($serialized, []); $this->data = RamseyUUID::fromString($string); }
php
public function unserialize($serialized) { $string = unserialize($serialized, []); $this->data = RamseyUUID::fromString($string); }
[ "public", "function", "unserialize", "(", "$", "serialized", ")", "{", "$", "string", "=", "unserialize", "(", "$", "serialized", ",", "[", "]", ")", ";", "$", "this", "->", "data", "=", "RamseyUUID", "::", "fromString", "(", "$", "string", ")", ";", "}" ]
Restore the object from serialized data. @since 0.1.0 @param string $serialized
[ "Restore", "the", "object", "from", "serialized", "data", "." ]
1eb8043fea7a61b7ef17a8a2496e3fba79723762
https://github.com/brightnucleus/keys/blob/1eb8043fea7a61b7ef17a8a2496e3fba79723762/src/UUID.php#L512-L516
train
sndsgd/sndsgd-field
src/field/rule/ClosureRule.php
ClosureRule.getClass
public function getClass() { if (is_string($this->fn)) { return $this->fn; } $hash = sha1(mt_rand().microtime(true)); return "sndsgd\\field\\rule\\Closure($hash)"; }
php
public function getClass() { if (is_string($this->fn)) { return $this->fn; } $hash = sha1(mt_rand().microtime(true)); return "sndsgd\\field\\rule\\Closure($hash)"; }
[ "public", "function", "getClass", "(", ")", "{", "if", "(", "is_string", "(", "$", "this", "->", "fn", ")", ")", "{", "return", "$", "this", "->", "fn", ";", "}", "$", "hash", "=", "sha1", "(", "mt_rand", "(", ")", ".", "microtime", "(", "true", ")", ")", ";", "return", "\"sndsgd\\\\field\\\\rule\\\\Closure($hash)\"", ";", "}" ]
Ensure that multiple Closure rules can be added to a field @return string
[ "Ensure", "that", "multiple", "Closure", "rules", "can", "be", "added", "to", "a", "field" ]
34ac3aabfe031bd9b259b3b93e84964b04031334
https://github.com/sndsgd/sndsgd-field/blob/34ac3aabfe031bd9b259b3b93e84964b04031334/src/field/rule/ClosureRule.php#L52-L59
train
symboo/BootstrapBundle
DependencyInjection/SymbooBootstrapExtension.php
SymbooBootstrapExtension.getAssets
protected function getAssets(array $config) { $bootstrapBasePath = $config['bootstrap']['dist_path']; // Add CSS and JS assets $assets = array( 'symboo_bootstrap_css' => array( 'inputs' => array($bootstrapBasePath . '/css/bootstrap.min.css'), 'filters' => array('cssrewrite'), 'output' => 'css/bootstrap.css' ), 'symboo_bootstrap_js' => array( 'inputs' => array($bootstrapBasePath . '/js/bootstrap.min.js'), 'output' => 'js/bootstrap.js' ) ); // Add bootstrap theme if desired if ($config['bootstrap']['use_theme']) { $assets['symboo_bootstrap_css']['inputs'][] = $bootstrapBasePath . '/css/bootstrap-theme.min.css'; } // Add glyphicon assets foreach (array('eot', 'svg', 'ttf', 'woff') as $fontType) { $assets['symboo_bootstrap_glyphicons_' . $fontType] = array( 'inputs' => array($bootstrapBasePath . '/fonts/glyphicons-halflings-regular.' . $fontType), 'output' => 'fonts/glyphicons-halflings-regular.' . $fontType ); } return $assets; }
php
protected function getAssets(array $config) { $bootstrapBasePath = $config['bootstrap']['dist_path']; // Add CSS and JS assets $assets = array( 'symboo_bootstrap_css' => array( 'inputs' => array($bootstrapBasePath . '/css/bootstrap.min.css'), 'filters' => array('cssrewrite'), 'output' => 'css/bootstrap.css' ), 'symboo_bootstrap_js' => array( 'inputs' => array($bootstrapBasePath . '/js/bootstrap.min.js'), 'output' => 'js/bootstrap.js' ) ); // Add bootstrap theme if desired if ($config['bootstrap']['use_theme']) { $assets['symboo_bootstrap_css']['inputs'][] = $bootstrapBasePath . '/css/bootstrap-theme.min.css'; } // Add glyphicon assets foreach (array('eot', 'svg', 'ttf', 'woff') as $fontType) { $assets['symboo_bootstrap_glyphicons_' . $fontType] = array( 'inputs' => array($bootstrapBasePath . '/fonts/glyphicons-halflings-regular.' . $fontType), 'output' => 'fonts/glyphicons-halflings-regular.' . $fontType ); } return $assets; }
[ "protected", "function", "getAssets", "(", "array", "$", "config", ")", "{", "$", "bootstrapBasePath", "=", "$", "config", "[", "'bootstrap'", "]", "[", "'dist_path'", "]", ";", "// Add CSS and JS assets", "$", "assets", "=", "array", "(", "'symboo_bootstrap_css'", "=>", "array", "(", "'inputs'", "=>", "array", "(", "$", "bootstrapBasePath", ".", "'/css/bootstrap.min.css'", ")", ",", "'filters'", "=>", "array", "(", "'cssrewrite'", ")", ",", "'output'", "=>", "'css/bootstrap.css'", ")", ",", "'symboo_bootstrap_js'", "=>", "array", "(", "'inputs'", "=>", "array", "(", "$", "bootstrapBasePath", ".", "'/js/bootstrap.min.js'", ")", ",", "'output'", "=>", "'js/bootstrap.js'", ")", ")", ";", "// Add bootstrap theme if desired", "if", "(", "$", "config", "[", "'bootstrap'", "]", "[", "'use_theme'", "]", ")", "{", "$", "assets", "[", "'symboo_bootstrap_css'", "]", "[", "'inputs'", "]", "[", "]", "=", "$", "bootstrapBasePath", ".", "'/css/bootstrap-theme.min.css'", ";", "}", "// Add glyphicon assets", "foreach", "(", "array", "(", "'eot'", ",", "'svg'", ",", "'ttf'", ",", "'woff'", ")", "as", "$", "fontType", ")", "{", "$", "assets", "[", "'symboo_bootstrap_glyphicons_'", ".", "$", "fontType", "]", "=", "array", "(", "'inputs'", "=>", "array", "(", "$", "bootstrapBasePath", ".", "'/fonts/glyphicons-halflings-regular.'", ".", "$", "fontType", ")", ",", "'output'", "=>", "'fonts/glyphicons-halflings-regular.'", ".", "$", "fontType", ")", ";", "}", "return", "$", "assets", ";", "}" ]
Returns the assets to be added @param array $config @return array
[ "Returns", "the", "assets", "to", "be", "added" ]
55a7a8732e3bbe99b2b9e52993c4469f816d3055
https://github.com/symboo/BootstrapBundle/blob/55a7a8732e3bbe99b2b9e52993c4469f816d3055/DependencyInjection/SymbooBootstrapExtension.php#L49-L80
train
CroudTech/laravel-repositories
src/Providers/RepositoryServiceProvider.php
RepositoryServiceProvider.boot
public function boot() { $this->publishes([ dirname(dirname(__DIR__)).'/config/repositories.php' => config_path('repositories.php'), ]); foreach (config('repositories.repositories', []) as $respository_contract => $repository) { $this->app->bind($respository_contract, $repository); } foreach (config('repositories.repository_transformers', []) as $transformer_contract => $transformer) { $this->app->bind($transformer, $transformer); } foreach (config('repositories.repository_transformers', []) as $repository_class => $transformer) { $this->app->when($repository_class) ->needs(TransformerContract::class) ->give(function () use ($transformer) { return $this->app->make($transformer); }); } foreach (config('repositories.contextual_repositories', []) as $controller => $repository) { $this->app->when($controller) ->needs(RepositoryContract::class) ->give($repository); } $this->commands([ \CroudTech\Repositories\Console\Commands\CreateRepository::class, ]); }
php
public function boot() { $this->publishes([ dirname(dirname(__DIR__)).'/config/repositories.php' => config_path('repositories.php'), ]); foreach (config('repositories.repositories', []) as $respository_contract => $repository) { $this->app->bind($respository_contract, $repository); } foreach (config('repositories.repository_transformers', []) as $transformer_contract => $transformer) { $this->app->bind($transformer, $transformer); } foreach (config('repositories.repository_transformers', []) as $repository_class => $transformer) { $this->app->when($repository_class) ->needs(TransformerContract::class) ->give(function () use ($transformer) { return $this->app->make($transformer); }); } foreach (config('repositories.contextual_repositories', []) as $controller => $repository) { $this->app->when($controller) ->needs(RepositoryContract::class) ->give($repository); } $this->commands([ \CroudTech\Repositories\Console\Commands\CreateRepository::class, ]); }
[ "public", "function", "boot", "(", ")", "{", "$", "this", "->", "publishes", "(", "[", "dirname", "(", "dirname", "(", "__DIR__", ")", ")", ".", "'/config/repositories.php'", "=>", "config_path", "(", "'repositories.php'", ")", ",", "]", ")", ";", "foreach", "(", "config", "(", "'repositories.repositories'", ",", "[", "]", ")", "as", "$", "respository_contract", "=>", "$", "repository", ")", "{", "$", "this", "->", "app", "->", "bind", "(", "$", "respository_contract", ",", "$", "repository", ")", ";", "}", "foreach", "(", "config", "(", "'repositories.repository_transformers'", ",", "[", "]", ")", "as", "$", "transformer_contract", "=>", "$", "transformer", ")", "{", "$", "this", "->", "app", "->", "bind", "(", "$", "transformer", ",", "$", "transformer", ")", ";", "}", "foreach", "(", "config", "(", "'repositories.repository_transformers'", ",", "[", "]", ")", "as", "$", "repository_class", "=>", "$", "transformer", ")", "{", "$", "this", "->", "app", "->", "when", "(", "$", "repository_class", ")", "->", "needs", "(", "TransformerContract", "::", "class", ")", "->", "give", "(", "function", "(", ")", "use", "(", "$", "transformer", ")", "{", "return", "$", "this", "->", "app", "->", "make", "(", "$", "transformer", ")", ";", "}", ")", ";", "}", "foreach", "(", "config", "(", "'repositories.contextual_repositories'", ",", "[", "]", ")", "as", "$", "controller", "=>", "$", "repository", ")", "{", "$", "this", "->", "app", "->", "when", "(", "$", "controller", ")", "->", "needs", "(", "RepositoryContract", "::", "class", ")", "->", "give", "(", "$", "repository", ")", ";", "}", "$", "this", "->", "commands", "(", "[", "\\", "CroudTech", "\\", "Repositories", "\\", "Console", "\\", "Commands", "\\", "CreateRepository", "::", "class", ",", "]", ")", ";", "}" ]
Register any repositories. @return void
[ "Register", "any", "repositories", "." ]
3146285be911728fe7b00cf27d2494ad22b773dc
https://github.com/CroudTech/laravel-repositories/blob/3146285be911728fe7b00cf27d2494ad22b773dc/src/Providers/RepositoryServiceProvider.php#L15-L46
train
RhubarbPHP/Scaffold.BackgroundTasks
src/BackgroundTask.php
BackgroundTask.executeInBackground
public static function executeInBackground(Task $task, $progressReportedCallback = null, BackgroundTaskStatus $persistentStatus = null) { if (!$persistentStatus){ $persistentStatus = new BackgroundTaskStatus(); $persistentStatus->TaskClass = get_class($task); $persistentStatus->save(); } $lastStatus = new TaskStatus(); $result = false; try { $result = $task->execute(function(TaskStatus $status) use ($progressReportedCallback, &$lastStatus, &$persistentStatus){ $lastStatus = $status; $persistentStatus->PercentageComplete = $status->percentageComplete; $persistentStatus->TaskStatus = $status->status; $persistentStatus->Message = $status->message; if ($progressReportedCallback){ $progressReportedCallback($status); } $persistentStatus->save(); }); $persistentStatus->TaskStatus = "Complete"; $persistentStatus->save(); if ($progressReportedCallback){ // Output a final status of complete. $lastStatus->percentageComplete = 100; $lastStatus->status = BackgroundTaskStatus::TASK_STATUS_COMPLETE; $progressReportedCallback($lastStatus); } } catch (Exception $er) { $persistentStatus->TaskStatus = "Failed"; $persistentStatus->ExceptionDetails = $er->getMessage() . "\r\n\r\n" . $er->getTraceAsString(); $persistentStatus->save(); if ($progressReportedCallback){ // Output a final status of complete. $lastStatus->status = BackgroundTaskStatus::TASK_STATUS_FAILED; if ($er instanceof RhubarbException) { $lastStatus->message = $er->getPublicMessage(); } $progressReportedCallback($lastStatus); } } return $result; }
php
public static function executeInBackground(Task $task, $progressReportedCallback = null, BackgroundTaskStatus $persistentStatus = null) { if (!$persistentStatus){ $persistentStatus = new BackgroundTaskStatus(); $persistentStatus->TaskClass = get_class($task); $persistentStatus->save(); } $lastStatus = new TaskStatus(); $result = false; try { $result = $task->execute(function(TaskStatus $status) use ($progressReportedCallback, &$lastStatus, &$persistentStatus){ $lastStatus = $status; $persistentStatus->PercentageComplete = $status->percentageComplete; $persistentStatus->TaskStatus = $status->status; $persistentStatus->Message = $status->message; if ($progressReportedCallback){ $progressReportedCallback($status); } $persistentStatus->save(); }); $persistentStatus->TaskStatus = "Complete"; $persistentStatus->save(); if ($progressReportedCallback){ // Output a final status of complete. $lastStatus->percentageComplete = 100; $lastStatus->status = BackgroundTaskStatus::TASK_STATUS_COMPLETE; $progressReportedCallback($lastStatus); } } catch (Exception $er) { $persistentStatus->TaskStatus = "Failed"; $persistentStatus->ExceptionDetails = $er->getMessage() . "\r\n\r\n" . $er->getTraceAsString(); $persistentStatus->save(); if ($progressReportedCallback){ // Output a final status of complete. $lastStatus->status = BackgroundTaskStatus::TASK_STATUS_FAILED; if ($er instanceof RhubarbException) { $lastStatus->message = $er->getPublicMessage(); } $progressReportedCallback($lastStatus); } } return $result; }
[ "public", "static", "function", "executeInBackground", "(", "Task", "$", "task", ",", "$", "progressReportedCallback", "=", "null", ",", "BackgroundTaskStatus", "$", "persistentStatus", "=", "null", ")", "{", "if", "(", "!", "$", "persistentStatus", ")", "{", "$", "persistentStatus", "=", "new", "BackgroundTaskStatus", "(", ")", ";", "$", "persistentStatus", "->", "TaskClass", "=", "get_class", "(", "$", "task", ")", ";", "$", "persistentStatus", "->", "save", "(", ")", ";", "}", "$", "lastStatus", "=", "new", "TaskStatus", "(", ")", ";", "$", "result", "=", "false", ";", "try", "{", "$", "result", "=", "$", "task", "->", "execute", "(", "function", "(", "TaskStatus", "$", "status", ")", "use", "(", "$", "progressReportedCallback", ",", "&", "$", "lastStatus", ",", "&", "$", "persistentStatus", ")", "{", "$", "lastStatus", "=", "$", "status", ";", "$", "persistentStatus", "->", "PercentageComplete", "=", "$", "status", "->", "percentageComplete", ";", "$", "persistentStatus", "->", "TaskStatus", "=", "$", "status", "->", "status", ";", "$", "persistentStatus", "->", "Message", "=", "$", "status", "->", "message", ";", "if", "(", "$", "progressReportedCallback", ")", "{", "$", "progressReportedCallback", "(", "$", "status", ")", ";", "}", "$", "persistentStatus", "->", "save", "(", ")", ";", "}", ")", ";", "$", "persistentStatus", "->", "TaskStatus", "=", "\"Complete\"", ";", "$", "persistentStatus", "->", "save", "(", ")", ";", "if", "(", "$", "progressReportedCallback", ")", "{", "// Output a final status of complete.", "$", "lastStatus", "->", "percentageComplete", "=", "100", ";", "$", "lastStatus", "->", "status", "=", "BackgroundTaskStatus", "::", "TASK_STATUS_COMPLETE", ";", "$", "progressReportedCallback", "(", "$", "lastStatus", ")", ";", "}", "}", "catch", "(", "Exception", "$", "er", ")", "{", "$", "persistentStatus", "->", "TaskStatus", "=", "\"Failed\"", ";", "$", "persistentStatus", "->", "ExceptionDetails", "=", "$", "er", "->", "getMessage", "(", ")", ".", "\"\\r\\n\\r\\n\"", ".", "$", "er", "->", "getTraceAsString", "(", ")", ";", "$", "persistentStatus", "->", "save", "(", ")", ";", "if", "(", "$", "progressReportedCallback", ")", "{", "// Output a final status of complete.", "$", "lastStatus", "->", "status", "=", "BackgroundTaskStatus", "::", "TASK_STATUS_FAILED", ";", "if", "(", "$", "er", "instanceof", "RhubarbException", ")", "{", "$", "lastStatus", "->", "message", "=", "$", "er", "->", "getPublicMessage", "(", ")", ";", "}", "$", "progressReportedCallback", "(", "$", "lastStatus", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Executes a task and provisions a BackgroundTaskStatus model to store a persistent record of the state. @param Task $task The task to execute @param callable|null $progressReportedCallback An optional call back to receive progress events @param BackgroundTaskStatus|null $persistentStatus If you have a pre-provisioned BackgroundTaskStatus model it can be updated instead.
[ "Executes", "a", "task", "and", "provisions", "a", "BackgroundTaskStatus", "model", "to", "store", "a", "persistent", "record", "of", "the", "state", "." ]
92a5feab27599288e8bf39deb522588115838904
https://github.com/RhubarbPHP/Scaffold.BackgroundTasks/blob/92a5feab27599288e8bf39deb522588115838904/src/BackgroundTask.php#L32-L88
train
squareproton/Bond
src/Bond/RecordManager/Task/Normality.php
Normality.buildQueryDelete
public static function buildQueryDelete( QuoteInterface $quoting, $table, array $data, array $returning = null ) { if( !count($data) === 0 ) { throw new NothingToDoException("Nothing to generate."); } $keys = self::keyTuple( $quoting, $data ); $tuples = self::dataTuples( $data ); return sprintf( "DELETE FROM %s WHERE (%s) IN (%s) %s;", $quoting->quoteIdent( $table ), $keys, $tuples, static::getReturningClause( $quoting, $returning ) ); }
php
public static function buildQueryDelete( QuoteInterface $quoting, $table, array $data, array $returning = null ) { if( !count($data) === 0 ) { throw new NothingToDoException("Nothing to generate."); } $keys = self::keyTuple( $quoting, $data ); $tuples = self::dataTuples( $data ); return sprintf( "DELETE FROM %s WHERE (%s) IN (%s) %s;", $quoting->quoteIdent( $table ), $keys, $tuples, static::getReturningClause( $quoting, $returning ) ); }
[ "public", "static", "function", "buildQueryDelete", "(", "QuoteInterface", "$", "quoting", ",", "$", "table", ",", "array", "$", "data", ",", "array", "$", "returning", "=", "null", ")", "{", "if", "(", "!", "count", "(", "$", "data", ")", "===", "0", ")", "{", "throw", "new", "NothingToDoException", "(", "\"Nothing to generate.\"", ")", ";", "}", "$", "keys", "=", "self", "::", "keyTuple", "(", "$", "quoting", ",", "$", "data", ")", ";", "$", "tuples", "=", "self", "::", "dataTuples", "(", "$", "data", ")", ";", "return", "sprintf", "(", "\"DELETE FROM %s WHERE (%s) IN (%s) %s;\"", ",", "$", "quoting", "->", "quoteIdent", "(", "$", "table", ")", ",", "$", "keys", ",", "$", "tuples", ",", "static", "::", "getReturningClause", "(", "$", "quoting", ",", "$", "returning", ")", ")", ";", "}" ]
Delete query for a data array @param string Table (unquoted) @param array of data
[ "Delete", "query", "for", "a", "data", "array" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/RecordManager/Task/Normality.php#L161-L179
train
squareproton/Bond
src/Bond/RecordManager/Task/Normality.php
Normality.buildQueryUpdate
public static function buildQueryUpdate( QuoteInterface $quoting, $table, array $primaryKeys, array $data, array $dataInitial, array $returning = null ) { if( !count($data) === 0 ) { throw new NothingToDoException("Nothing to generate."); } $columnNames = array_keys( $data[0] ); $columnNamesInitial = array_keys( $dataInitial[0] ); // select statement $dataAsSql = "VALUES " . ( $columnNamesInitial ? self::dataTuplesInitial( $data, $dataInitial ) : self::dataTuples( $data ) ); $columns = array(); $where = array(); // core data foreach( array_keys( $data[0] ) as $key => $column ) { $sqlFragment = sprintf( '%s = "uc"."%s"', $quoting->quoteIdent( $column ), $columnNames[$key] ); $columns[] = $sqlFragment; if( array_key_exists( $column, $primaryKeys ) ) { $where[$column] = '"t".'.$sqlFragment; } } // dataInitial // all dataInitial columns are primary keys, see self::extractColumnInfoFromDataTypes() foreach( array_keys( $dataInitial[0] ) as $key => $column ) { // overwrite existing where definition $where[$column] = sprintf( '"t".%s = "uc"."__initial_%s"', $quoting->quoteIdent( $column ), $columnNames[$key] ); $columnNames[] = "__initial_{$column}"; } if( !count($columns) ) { throw new NothingToDoException("Nothing to update for `{$table}`. Every column passed in the data array is a primary key column."); } return sprintf( <<<SQL UPDATE %s AS "t" SET %s FROM ( %s ) AS uc ( "%s" ) WHERE %s %s; SQL , $quoting->quoteIdent( $table ), implode( ', ', $columns ), $dataAsSql, implode( '", "', $columnNames ), implode( ' AND ', $where ), '' #static::getReturningClause( $returning, 't' ) ); }
php
public static function buildQueryUpdate( QuoteInterface $quoting, $table, array $primaryKeys, array $data, array $dataInitial, array $returning = null ) { if( !count($data) === 0 ) { throw new NothingToDoException("Nothing to generate."); } $columnNames = array_keys( $data[0] ); $columnNamesInitial = array_keys( $dataInitial[0] ); // select statement $dataAsSql = "VALUES " . ( $columnNamesInitial ? self::dataTuplesInitial( $data, $dataInitial ) : self::dataTuples( $data ) ); $columns = array(); $where = array(); // core data foreach( array_keys( $data[0] ) as $key => $column ) { $sqlFragment = sprintf( '%s = "uc"."%s"', $quoting->quoteIdent( $column ), $columnNames[$key] ); $columns[] = $sqlFragment; if( array_key_exists( $column, $primaryKeys ) ) { $where[$column] = '"t".'.$sqlFragment; } } // dataInitial // all dataInitial columns are primary keys, see self::extractColumnInfoFromDataTypes() foreach( array_keys( $dataInitial[0] ) as $key => $column ) { // overwrite existing where definition $where[$column] = sprintf( '"t".%s = "uc"."__initial_%s"', $quoting->quoteIdent( $column ), $columnNames[$key] ); $columnNames[] = "__initial_{$column}"; } if( !count($columns) ) { throw new NothingToDoException("Nothing to update for `{$table}`. Every column passed in the data array is a primary key column."); } return sprintf( <<<SQL UPDATE %s AS "t" SET %s FROM ( %s ) AS uc ( "%s" ) WHERE %s %s; SQL , $quoting->quoteIdent( $table ), implode( ', ', $columns ), $dataAsSql, implode( '", "', $columnNames ), implode( ' AND ', $where ), '' #static::getReturningClause( $returning, 't' ) ); }
[ "public", "static", "function", "buildQueryUpdate", "(", "QuoteInterface", "$", "quoting", ",", "$", "table", ",", "array", "$", "primaryKeys", ",", "array", "$", "data", ",", "array", "$", "dataInitial", ",", "array", "$", "returning", "=", "null", ")", "{", "if", "(", "!", "count", "(", "$", "data", ")", "===", "0", ")", "{", "throw", "new", "NothingToDoException", "(", "\"Nothing to generate.\"", ")", ";", "}", "$", "columnNames", "=", "array_keys", "(", "$", "data", "[", "0", "]", ")", ";", "$", "columnNamesInitial", "=", "array_keys", "(", "$", "dataInitial", "[", "0", "]", ")", ";", "// select statement", "$", "dataAsSql", "=", "\"VALUES \"", ".", "(", "$", "columnNamesInitial", "?", "self", "::", "dataTuplesInitial", "(", "$", "data", ",", "$", "dataInitial", ")", ":", "self", "::", "dataTuples", "(", "$", "data", ")", ")", ";", "$", "columns", "=", "array", "(", ")", ";", "$", "where", "=", "array", "(", ")", ";", "// core data", "foreach", "(", "array_keys", "(", "$", "data", "[", "0", "]", ")", "as", "$", "key", "=>", "$", "column", ")", "{", "$", "sqlFragment", "=", "sprintf", "(", "'%s = \"uc\".\"%s\"'", ",", "$", "quoting", "->", "quoteIdent", "(", "$", "column", ")", ",", "$", "columnNames", "[", "$", "key", "]", ")", ";", "$", "columns", "[", "]", "=", "$", "sqlFragment", ";", "if", "(", "array_key_exists", "(", "$", "column", ",", "$", "primaryKeys", ")", ")", "{", "$", "where", "[", "$", "column", "]", "=", "'\"t\".'", ".", "$", "sqlFragment", ";", "}", "}", "// dataInitial", "// all dataInitial columns are primary keys, see self::extractColumnInfoFromDataTypes()", "foreach", "(", "array_keys", "(", "$", "dataInitial", "[", "0", "]", ")", "as", "$", "key", "=>", "$", "column", ")", "{", "// overwrite existing where definition", "$", "where", "[", "$", "column", "]", "=", "sprintf", "(", "'\"t\".%s = \"uc\".\"__initial_%s\"'", ",", "$", "quoting", "->", "quoteIdent", "(", "$", "column", ")", ",", "$", "columnNames", "[", "$", "key", "]", ")", ";", "$", "columnNames", "[", "]", "=", "\"__initial_{$column}\"", ";", "}", "if", "(", "!", "count", "(", "$", "columns", ")", ")", "{", "throw", "new", "NothingToDoException", "(", "\"Nothing to update for `{$table}`. Every column passed in the data array is a primary key column.\"", ")", ";", "}", "return", "sprintf", "(", " <<<SQL\nUPDATE\n %s AS \"t\"\nSET\n %s\nFROM\n (\n %s\n ) AS uc ( \"%s\" )\nWHERE\n %s\n%s;\nSQL", ",", "$", "quoting", "->", "quoteIdent", "(", "$", "table", ")", ",", "implode", "(", "', '", ",", "$", "columns", ")", ",", "$", "dataAsSql", ",", "implode", "(", "'\", \"'", ",", "$", "columnNames", ")", ",", "implode", "(", "' AND '", ",", "$", "where", ")", ",", "''", "#static::getReturningClause( $returning, 't' )", ")", ";", "}" ]
Update query for a data array @param string $table @param array $primaryKeys @param array $data @return string SQL insert statement
[ "Update", "query", "for", "a", "data", "array" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/RecordManager/Task/Normality.php#L188-L266
train
squareproton/Bond
src/Bond/RecordManager/Task/Normality.php
Normality.getReturningClause
protected static function getReturningClause( QuoteInterface $quoting, array $returning = null, $table = '' ) { if( $returning === null ) { return 'RETURNING *'; } elseif ( $returning === array() ) { return ''; } elseif( !empty( $table ) ) { foreach( $returning as &$value ) { $value = "{$table}.{$value}"; } } return "RETURNING ". implode( ',', $returning = array_map( array( $quoting, 'quoteIdent' ), $returning ) ); }
php
protected static function getReturningClause( QuoteInterface $quoting, array $returning = null, $table = '' ) { if( $returning === null ) { return 'RETURNING *'; } elseif ( $returning === array() ) { return ''; } elseif( !empty( $table ) ) { foreach( $returning as &$value ) { $value = "{$table}.{$value}"; } } return "RETURNING ". implode( ',', $returning = array_map( array( $quoting, 'quoteIdent' ), $returning ) ); }
[ "protected", "static", "function", "getReturningClause", "(", "QuoteInterface", "$", "quoting", ",", "array", "$", "returning", "=", "null", ",", "$", "table", "=", "''", ")", "{", "if", "(", "$", "returning", "===", "null", ")", "{", "return", "'RETURNING *'", ";", "}", "elseif", "(", "$", "returning", "===", "array", "(", ")", ")", "{", "return", "''", ";", "}", "elseif", "(", "!", "empty", "(", "$", "table", ")", ")", "{", "foreach", "(", "$", "returning", "as", "&", "$", "value", ")", "{", "$", "value", "=", "\"{$table}.{$value}\"", ";", "}", "}", "return", "\"RETURNING \"", ".", "implode", "(", "','", ",", "$", "returning", "=", "array_map", "(", "array", "(", "$", "quoting", ",", "'quoteIdent'", ")", ",", "$", "returning", ")", ")", ";", "}" ]
Turn a array of columns into a comma separated identifier list suitable for being passed into a RETURNING @param array $returning @return string
[ "Turn", "a", "array", "of", "columns", "into", "a", "comma", "separated", "identifier", "list", "suitable", "for", "being", "passed", "into", "a", "RETURNING" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/RecordManager/Task/Normality.php#L299-L318
train
squareproton/Bond
src/Bond/RecordManager/Task/Normality.php
Normality.validateQueryDatas
protected static function validateQueryDatas( array &$datas, array $modifiers ) { foreach( $datas as $key => &$data ) { self::validateQueryData( $data, $modifiers ); } }
php
protected static function validateQueryDatas( array &$datas, array $modifiers ) { foreach( $datas as $key => &$data ) { self::validateQueryData( $data, $modifiers ); } }
[ "protected", "static", "function", "validateQueryDatas", "(", "array", "&", "$", "datas", ",", "array", "$", "modifiers", ")", "{", "foreach", "(", "$", "datas", "as", "$", "key", "=>", "&", "$", "data", ")", "{", "self", "::", "validateQueryData", "(", "$", "data", ",", "$", "modifiers", ")", ";", "}", "}" ]
Validate a array of query datas arrays @param array datas array of datas @param array validation callback
[ "Validate", "a", "array", "of", "query", "datas", "arrays" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/RecordManager/Task/Normality.php#L326-L331
train
squareproton/Bond
src/Bond/RecordManager/Task/Normality.php
Normality.validateQueryData
protected static function validateQueryData( array &$data, array $modifiers ) { foreach( $data as $column => &$value ) { $value = $modifiers[$column]->exec( $value ); } }
php
protected static function validateQueryData( array &$data, array $modifiers ) { foreach( $data as $column => &$value ) { $value = $modifiers[$column]->exec( $value ); } }
[ "protected", "static", "function", "validateQueryData", "(", "array", "&", "$", "data", ",", "array", "$", "modifiers", ")", "{", "foreach", "(", "$", "data", "as", "$", "column", "=>", "&", "$", "value", ")", "{", "$", "value", "=", "$", "modifiers", "[", "$", "column", "]", "->", "exec", "(", "$", "value", ")", ";", "}", "}" ]
Validate a query datas array @param array query datas array @param array validation callback
[ "Validate", "a", "query", "datas", "array" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/RecordManager/Task/Normality.php#L339-L344
train
squareproton/Bond
src/Bond/RecordManager/Task/Normality.php
Normality.buildChainTasks
protected static function buildChainTasks( \Bond\Entity\Base $entity, $columns ) { $tasks = array(); foreach( $columns as $column ) { $value = $entity->get($column); // chain saving if( is_object($value) and $value instanceof ChainSavingInterface ) { $value->chainSaving( $tasks, $column ); } } return $tasks; }
php
protected static function buildChainTasks( \Bond\Entity\Base $entity, $columns ) { $tasks = array(); foreach( $columns as $column ) { $value = $entity->get($column); // chain saving if( is_object($value) and $value instanceof ChainSavingInterface ) { $value->chainSaving( $tasks, $column ); } } return $tasks; }
[ "protected", "static", "function", "buildChainTasks", "(", "\\", "Bond", "\\", "Entity", "\\", "Base", "$", "entity", ",", "$", "columns", ")", "{", "$", "tasks", "=", "array", "(", ")", ";", "foreach", "(", "$", "columns", "as", "$", "column", ")", "{", "$", "value", "=", "$", "entity", "->", "get", "(", "$", "column", ")", ";", "// chain saving", "if", "(", "is_object", "(", "$", "value", ")", "and", "$", "value", "instanceof", "ChainSavingInterface", ")", "{", "$", "value", "->", "chainSaving", "(", "$", "tasks", ",", "$", "column", ")", ";", "}", "}", "return", "$", "tasks", ";", "}" ]
Get chain tasks @param Bond\Entity\Base $entity @param array $chainTasks @param array $columns @return null
[ "Get", "chain", "tasks" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/RecordManager/Task/Normality.php#L402-L420
train
bazzline/php_component_requirement
source/AbstractCondition.php
AbstractCondition.itemSupportsMethodCall
protected function itemSupportsMethodCall(IsMetInterface $item, $methodName) { $hash = spl_object_hash($item); if (empty($this->methodNamesPerItem) || !isset($this->methodNamesPerItem[$hash])) { $itemMethods = array_flip(get_class_methods($item)); $this->methodNamesPerItem[$hash] = $itemMethods; } return (isset($this->methodNamesPerItem[$hash][$methodName])); }
php
protected function itemSupportsMethodCall(IsMetInterface $item, $methodName) { $hash = spl_object_hash($item); if (empty($this->methodNamesPerItem) || !isset($this->methodNamesPerItem[$hash])) { $itemMethods = array_flip(get_class_methods($item)); $this->methodNamesPerItem[$hash] = $itemMethods; } return (isset($this->methodNamesPerItem[$hash][$methodName])); }
[ "protected", "function", "itemSupportsMethodCall", "(", "IsMetInterface", "$", "item", ",", "$", "methodName", ")", "{", "$", "hash", "=", "spl_object_hash", "(", "$", "item", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "methodNamesPerItem", ")", "||", "!", "isset", "(", "$", "this", "->", "methodNamesPerItem", "[", "$", "hash", "]", ")", ")", "{", "$", "itemMethods", "=", "array_flip", "(", "get_class_methods", "(", "$", "item", ")", ")", ";", "$", "this", "->", "methodNamesPerItem", "[", "$", "hash", "]", "=", "$", "itemMethods", ";", "}", "return", "(", "isset", "(", "$", "this", "->", "methodNamesPerItem", "[", "$", "hash", "]", "[", "$", "methodName", "]", ")", ")", ";", "}" ]
Checks if item implements method name @param IsMetInterface $item @param string $methodName @return bool @author stev leibelt <[email protected]> @since 2013-07-20
[ "Checks", "if", "item", "implements", "method", "name" ]
84ee943b6aa8df783e2cfa5897de3a4a70c39990
https://github.com/bazzline/php_component_requirement/blob/84ee943b6aa8df783e2cfa5897de3a4a70c39990/source/AbstractCondition.php#L143-L154
train
Linkvalue-Interne/MajoraOrientDBBundle
src/Majora/Component/Graph/Engine/OrientDbMetadata.php
OrientDbMetadata.registerVertex
public function registerVertex(Vertex $vertex) { $this->vertexes->set($vertex->getName(), $vertex); return $this; }
php
public function registerVertex(Vertex $vertex) { $this->vertexes->set($vertex->getName(), $vertex); return $this; }
[ "public", "function", "registerVertex", "(", "Vertex", "$", "vertex", ")", "{", "$", "this", "->", "vertexes", "->", "set", "(", "$", "vertex", "->", "getName", "(", ")", ",", "$", "vertex", ")", ";", "return", "$", "this", ";", "}" ]
register a new vertex into metadata @param Vertex $vertex @return OrientDbMetadata
[ "register", "a", "new", "vertex", "into", "metadata" ]
9fc9a409604472b558319c274442f75bbd055435
https://github.com/Linkvalue-Interne/MajoraOrientDBBundle/blob/9fc9a409604472b558319c274442f75bbd055435/src/Majora/Component/Graph/Engine/OrientDbMetadata.php#L179-L184
train
AthensFramework/CSRF
src/CSRF.php
CSRF.getSuppliedCSRF
protected static function getSuppliedCSRF() { $headers = function_exists('getallheaders') === true ? getallheaders() : []; $requestArguments = []; parse_str(file_get_contents('php://input'), $requestArguments); $requestArguments = array_merge($_POST, $requestArguments); if (array_key_exists(static::CSRF_TOKEN_HEADER, $headers) === true) { return $headers[static::CSRF_TOKEN_HEADER]; } elseif (array_key_exists("csrf_token", $requestArguments) === true) { return $requestArguments['csrf_token']; } else { return null; } }
php
protected static function getSuppliedCSRF() { $headers = function_exists('getallheaders') === true ? getallheaders() : []; $requestArguments = []; parse_str(file_get_contents('php://input'), $requestArguments); $requestArguments = array_merge($_POST, $requestArguments); if (array_key_exists(static::CSRF_TOKEN_HEADER, $headers) === true) { return $headers[static::CSRF_TOKEN_HEADER]; } elseif (array_key_exists("csrf_token", $requestArguments) === true) { return $requestArguments['csrf_token']; } else { return null; } }
[ "protected", "static", "function", "getSuppliedCSRF", "(", ")", "{", "$", "headers", "=", "function_exists", "(", "'getallheaders'", ")", "===", "true", "?", "getallheaders", "(", ")", ":", "[", "]", ";", "$", "requestArguments", "=", "[", "]", ";", "parse_str", "(", "file_get_contents", "(", "'php://input'", ")", ",", "$", "requestArguments", ")", ";", "$", "requestArguments", "=", "array_merge", "(", "$", "_POST", ",", "$", "requestArguments", ")", ";", "if", "(", "array_key_exists", "(", "static", "::", "CSRF_TOKEN_HEADER", ",", "$", "headers", ")", "===", "true", ")", "{", "return", "$", "headers", "[", "static", "::", "CSRF_TOKEN_HEADER", "]", ";", "}", "elseif", "(", "array_key_exists", "(", "\"csrf_token\"", ",", "$", "requestArguments", ")", "===", "true", ")", "{", "return", "$", "requestArguments", "[", "'csrf_token'", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Get the CSRF token, presented as a header, a PUT parameter, or a POST parameter. @return string|null
[ "Get", "the", "CSRF", "token", "presented", "as", "a", "header", "a", "PUT", "parameter", "or", "a", "POST", "parameter", "." ]
17cd1e330a9e47d1d41fec43a30ba8a6394acd94
https://github.com/AthensFramework/CSRF/blob/17cd1e330a9e47d1d41fec43a30ba8a6394acd94/src/CSRF.php#L100-L115
train
mtils/file-db
src/FileDB/Model/EloquentFileDBModel.php
EloquentFileDBModel.importFile
public function importFile($localPath, FileInterface $folder = null) { if(!$folder->isDir()){ throw new RuntimeException('Files can only be moved into directories'); } //$fileName = $uploadedFile->getClientOriginalName(); $fileName = basename($localPath); $targetPath = $folder ? $folder->getPath() . "$fileName" : $fileName; $this->files->move($localPath, $targetPath); $absPath = $this->mapper->absolutePath($targetPath); $file = $this->createFromPath($targetPath); if ($folder) { $file->setDir($folder); $folder->addChild($file); } $this->save($file); return $file; }
php
public function importFile($localPath, FileInterface $folder = null) { if(!$folder->isDir()){ throw new RuntimeException('Files can only be moved into directories'); } //$fileName = $uploadedFile->getClientOriginalName(); $fileName = basename($localPath); $targetPath = $folder ? $folder->getPath() . "$fileName" : $fileName; $this->files->move($localPath, $targetPath); $absPath = $this->mapper->absolutePath($targetPath); $file = $this->createFromPath($targetPath); if ($folder) { $file->setDir($folder); $folder->addChild($file); } $this->save($file); return $file; }
[ "public", "function", "importFile", "(", "$", "localPath", ",", "FileInterface", "$", "folder", "=", "null", ")", "{", "if", "(", "!", "$", "folder", "->", "isDir", "(", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'Files can only be moved into directories'", ")", ";", "}", "//$fileName = $uploadedFile->getClientOriginalName();", "$", "fileName", "=", "basename", "(", "$", "localPath", ")", ";", "$", "targetPath", "=", "$", "folder", "?", "$", "folder", "->", "getPath", "(", ")", ".", "\"$fileName\"", ":", "$", "fileName", ";", "$", "this", "->", "files", "->", "move", "(", "$", "localPath", ",", "$", "targetPath", ")", ";", "$", "absPath", "=", "$", "this", "->", "mapper", "->", "absolutePath", "(", "$", "targetPath", ")", ";", "$", "file", "=", "$", "this", "->", "createFromPath", "(", "$", "targetPath", ")", ";", "if", "(", "$", "folder", ")", "{", "$", "file", "->", "setDir", "(", "$", "folder", ")", ";", "$", "folder", "->", "addChild", "(", "$", "file", ")", ";", "}", "$", "this", "->", "save", "(", "$", "file", ")", ";", "return", "$", "file", ";", "}" ]
Import a local file into the FileDB @param string $localPath @param FileInterface $folder (optional) @return FileInterface The new file
[ "Import", "a", "local", "file", "into", "the", "FileDB" ]
270ebc26b0fa3d2c996ca8861507fa63d2db6814
https://github.com/mtils/file-db/blob/270ebc26b0fa3d2c996ca8861507fa63d2db6814/src/FileDB/Model/EloquentFileDBModel.php#L441-L466
train
Xsaven/laravel-intelect-admin
src/Addons/JWTAuth/Validators/PayloadValidator.php
PayloadValidator.validateTimestamps
protected function validateTimestamps(array $payload) { if (isset($payload['nbf']) && Utils::timestamp($payload['nbf'])->isFuture()) { throw new TokenInvalidException('Not Before (nbf) timestamp cannot be in the future', 400); } if (isset($payload['iat']) && Utils::timestamp($payload['iat'])->isFuture()) { throw new TokenInvalidException('Issued At (iat) timestamp cannot be in the future', 400); } if (Utils::timestamp($payload['exp'])->isPast()) { throw new TokenExpiredException('Token has expired'); } return true; }
php
protected function validateTimestamps(array $payload) { if (isset($payload['nbf']) && Utils::timestamp($payload['nbf'])->isFuture()) { throw new TokenInvalidException('Not Before (nbf) timestamp cannot be in the future', 400); } if (isset($payload['iat']) && Utils::timestamp($payload['iat'])->isFuture()) { throw new TokenInvalidException('Issued At (iat) timestamp cannot be in the future', 400); } if (Utils::timestamp($payload['exp'])->isPast()) { throw new TokenExpiredException('Token has expired'); } return true; }
[ "protected", "function", "validateTimestamps", "(", "array", "$", "payload", ")", "{", "if", "(", "isset", "(", "$", "payload", "[", "'nbf'", "]", ")", "&&", "Utils", "::", "timestamp", "(", "$", "payload", "[", "'nbf'", "]", ")", "->", "isFuture", "(", ")", ")", "{", "throw", "new", "TokenInvalidException", "(", "'Not Before (nbf) timestamp cannot be in the future'", ",", "400", ")", ";", "}", "if", "(", "isset", "(", "$", "payload", "[", "'iat'", "]", ")", "&&", "Utils", "::", "timestamp", "(", "$", "payload", "[", "'iat'", "]", ")", "->", "isFuture", "(", ")", ")", "{", "throw", "new", "TokenInvalidException", "(", "'Issued At (iat) timestamp cannot be in the future'", ",", "400", ")", ";", "}", "if", "(", "Utils", "::", "timestamp", "(", "$", "payload", "[", "'exp'", "]", ")", "->", "isPast", "(", ")", ")", "{", "throw", "new", "TokenExpiredException", "(", "'Token has expired'", ")", ";", "}", "return", "true", ";", "}" ]
Validate the payload timestamps. @param array $payload @throws \Lia\Addons\JWTAuth\Exceptions\TokenExpiredException @throws \Lia\Addons\JWTAuth\Exceptions\TokenInvalidException @return bool
[ "Validate", "the", "payload", "timestamps", "." ]
592574633d12c74cf25b43dd6694fee496abefcb
https://github.com/Xsaven/laravel-intelect-admin/blob/592574633d12c74cf25b43dd6694fee496abefcb/src/Addons/JWTAuth/Validators/PayloadValidator.php#L63-L78
train
praxigento/mobi_mod_pv
Observer/Z/PvRegister.php
PvRegister.accountPv
public function accountPv(\Magento\Sales\Api\Data\OrderInterface $order) { /* sale state validation should be performed before */ $orderId = $order->getEntityId(); /* update record state in the registry */ $this->updateDatePaid($orderId); /* ... then transfer PV to the customer account */ $req = new \Praxigento\Pv\Api\Service\Sale\Account\Pv\Request(); $req->setSaleOrderId($orderId); $this->srvPvAccount->exec($req); }
php
public function accountPv(\Magento\Sales\Api\Data\OrderInterface $order) { /* sale state validation should be performed before */ $orderId = $order->getEntityId(); /* update record state in the registry */ $this->updateDatePaid($orderId); /* ... then transfer PV to the customer account */ $req = new \Praxigento\Pv\Api\Service\Sale\Account\Pv\Request(); $req->setSaleOrderId($orderId); $this->srvPvAccount->exec($req); }
[ "public", "function", "accountPv", "(", "\\", "Magento", "\\", "Sales", "\\", "Api", "\\", "Data", "\\", "OrderInterface", "$", "order", ")", "{", "/* sale state validation should be performed before */", "$", "orderId", "=", "$", "order", "->", "getEntityId", "(", ")", ";", "/* update record state in the registry */", "$", "this", "->", "updateDatePaid", "(", "$", "orderId", ")", ";", "/* ... then transfer PV to the customer account */", "$", "req", "=", "new", "\\", "Praxigento", "\\", "Pv", "\\", "Api", "\\", "Service", "\\", "Sale", "\\", "Account", "\\", "Pv", "\\", "Request", "(", ")", ";", "$", "req", "->", "setSaleOrderId", "(", "$", "orderId", ")", ";", "$", "this", "->", "srvPvAccount", "->", "exec", "(", "$", "req", ")", ";", "}" ]
Collect order data and call service method to transfer PV to customer account. @param \Magento\Sales\Api\Data\OrderInterface $order @throws \Exception
[ "Collect", "order", "data", "and", "call", "service", "method", "to", "transfer", "PV", "to", "customer", "account", "." ]
d1540b7e94264527006e8b9fa68904a72a63928e
https://github.com/praxigento/mobi_mod_pv/blob/d1540b7e94264527006e8b9fa68904a72a63928e/Observer/Z/PvRegister.php#L51-L61
train
praxigento/mobi_mod_pv
Observer/Z/PvRegister.php
PvRegister.getServiceItemForMageItem
private function getServiceItemForMageItem(\Magento\Sales\Api\Data\OrderItemInterface $item, $stockId = null) { $result = new \Praxigento\Pv\Service\Sale\Data\Item(); $prodId = $item->getProductId(); $itemId = $item->getItemId(); /* qty of the product can be changed in invoice but we use ordered only */ $qty = $item->getQtyOrdered(); /* create data item for service */ $result->setItemId($itemId); $result->setProductId($prodId); $result->setQuantity($qty); $result->setStockId($stockId); return $result; }
php
private function getServiceItemForMageItem(\Magento\Sales\Api\Data\OrderItemInterface $item, $stockId = null) { $result = new \Praxigento\Pv\Service\Sale\Data\Item(); $prodId = $item->getProductId(); $itemId = $item->getItemId(); /* qty of the product can be changed in invoice but we use ordered only */ $qty = $item->getQtyOrdered(); /* create data item for service */ $result->setItemId($itemId); $result->setProductId($prodId); $result->setQuantity($qty); $result->setStockId($stockId); return $result; }
[ "private", "function", "getServiceItemForMageItem", "(", "\\", "Magento", "\\", "Sales", "\\", "Api", "\\", "Data", "\\", "OrderItemInterface", "$", "item", ",", "$", "stockId", "=", "null", ")", "{", "$", "result", "=", "new", "\\", "Praxigento", "\\", "Pv", "\\", "Service", "\\", "Sale", "\\", "Data", "\\", "Item", "(", ")", ";", "$", "prodId", "=", "$", "item", "->", "getProductId", "(", ")", ";", "$", "itemId", "=", "$", "item", "->", "getItemId", "(", ")", ";", "/* qty of the product can be changed in invoice but we use ordered only */", "$", "qty", "=", "$", "item", "->", "getQtyOrdered", "(", ")", ";", "/* create data item for service */", "$", "result", "->", "setItemId", "(", "$", "itemId", ")", ";", "$", "result", "->", "setProductId", "(", "$", "prodId", ")", ";", "$", "result", "->", "setQuantity", "(", "$", "qty", ")", ";", "$", "result", "->", "setStockId", "(", "$", "stockId", ")", ";", "return", "$", "result", ";", "}" ]
Convert Magento SaleOrderItem to service item. @param \Magento\Sales\Api\Data\OrderItemInterface $item @param int $stockId @return \Praxigento\Pv\Service\Sale\Data\Item @throws \Exception
[ "Convert", "Magento", "SaleOrderItem", "to", "service", "item", "." ]
d1540b7e94264527006e8b9fa68904a72a63928e
https://github.com/praxigento/mobi_mod_pv/blob/d1540b7e94264527006e8b9fa68904a72a63928e/Observer/Z/PvRegister.php#L71-L84
train
praxigento/mobi_mod_pv
Observer/Z/PvRegister.php
PvRegister.savePv
public function savePv(\Magento\Sales\Api\Data\OrderInterface $order) { $orderId = $order->getId(); $state = $order->getState(); $dateCreated = $order->getCreatedAt(); $itemsData = $this->getServiceItemsForMageSaleOrder($order); /* compose request data and request itself */ /** @var \Praxigento\Pv\Service\Sale\Save\Request $req */ $req = new \Praxigento\Pv\Service\Sale\Save\Request(); $req->setSaleOrderId($orderId); $req->setOrderItems($itemsData); if ($state == \Magento\Sales\Model\Order::STATE_PROCESSING) { $req->setSaleOrderDatePaid($dateCreated); } $this->srvPvSave->exec($req); }
php
public function savePv(\Magento\Sales\Api\Data\OrderInterface $order) { $orderId = $order->getId(); $state = $order->getState(); $dateCreated = $order->getCreatedAt(); $itemsData = $this->getServiceItemsForMageSaleOrder($order); /* compose request data and request itself */ /** @var \Praxigento\Pv\Service\Sale\Save\Request $req */ $req = new \Praxigento\Pv\Service\Sale\Save\Request(); $req->setSaleOrderId($orderId); $req->setOrderItems($itemsData); if ($state == \Magento\Sales\Model\Order::STATE_PROCESSING) { $req->setSaleOrderDatePaid($dateCreated); } $this->srvPvSave->exec($req); }
[ "public", "function", "savePv", "(", "\\", "Magento", "\\", "Sales", "\\", "Api", "\\", "Data", "\\", "OrderInterface", "$", "order", ")", "{", "$", "orderId", "=", "$", "order", "->", "getId", "(", ")", ";", "$", "state", "=", "$", "order", "->", "getState", "(", ")", ";", "$", "dateCreated", "=", "$", "order", "->", "getCreatedAt", "(", ")", ";", "$", "itemsData", "=", "$", "this", "->", "getServiceItemsForMageSaleOrder", "(", "$", "order", ")", ";", "/* compose request data and request itself */", "/** @var \\Praxigento\\Pv\\Service\\Sale\\Save\\Request $req */", "$", "req", "=", "new", "\\", "Praxigento", "\\", "Pv", "\\", "Service", "\\", "Sale", "\\", "Save", "\\", "Request", "(", ")", ";", "$", "req", "->", "setSaleOrderId", "(", "$", "orderId", ")", ";", "$", "req", "->", "setOrderItems", "(", "$", "itemsData", ")", ";", "if", "(", "$", "state", "==", "\\", "Magento", "\\", "Sales", "\\", "Model", "\\", "Order", "::", "STATE_PROCESSING", ")", "{", "$", "req", "->", "setSaleOrderDatePaid", "(", "$", "dateCreated", ")", ";", "}", "$", "this", "->", "srvPvSave", "->", "exec", "(", "$", "req", ")", ";", "}" ]
Collect orders data and call service method to register order PV. @param \Magento\Sales\Api\Data\OrderInterface $order @throws \Exception
[ "Collect", "orders", "data", "and", "call", "service", "method", "to", "register", "order", "PV", "." ]
d1540b7e94264527006e8b9fa68904a72a63928e
https://github.com/praxigento/mobi_mod_pv/blob/d1540b7e94264527006e8b9fa68904a72a63928e/Observer/Z/PvRegister.php#L113-L128
train
praxigento/mobi_mod_pv
Observer/Z/PvRegister.php
PvRegister.updateDatePaid
private function updateDatePaid($orderId) { $datePaid = $this->hlpDate->getUtcNowForDb(); $data = [ESale::A_DATE_PAID => $datePaid]; $this->daoSale->updateById($orderId, $data); $this->logger->info("Update paid date in PV registry when sale order (#$orderId) is paid."); }
php
private function updateDatePaid($orderId) { $datePaid = $this->hlpDate->getUtcNowForDb(); $data = [ESale::A_DATE_PAID => $datePaid]; $this->daoSale->updateById($orderId, $data); $this->logger->info("Update paid date in PV registry when sale order (#$orderId) is paid."); }
[ "private", "function", "updateDatePaid", "(", "$", "orderId", ")", "{", "$", "datePaid", "=", "$", "this", "->", "hlpDate", "->", "getUtcNowForDb", "(", ")", ";", "$", "data", "=", "[", "ESale", "::", "A_DATE_PAID", "=>", "$", "datePaid", "]", ";", "$", "this", "->", "daoSale", "->", "updateById", "(", "$", "orderId", ",", "$", "data", ")", ";", "$", "this", "->", "logger", "->", "info", "(", "\"Update paid date in PV registry when sale order (#$orderId) is paid.\"", ")", ";", "}" ]
Update paid date in sale order registry of PV module. @param int $orderId
[ "Update", "paid", "date", "in", "sale", "order", "registry", "of", "PV", "module", "." ]
d1540b7e94264527006e8b9fa68904a72a63928e
https://github.com/praxigento/mobi_mod_pv/blob/d1540b7e94264527006e8b9fa68904a72a63928e/Observer/Z/PvRegister.php#L135-L141
train
rabbitcms/forms
src/Controls/InputGroup.php
InputGroup.setForm
public function setForm(ControlCollection $form = null): Control { $this->control->setForm($form); return parent::setForm($form); }
php
public function setForm(ControlCollection $form = null): Control { $this->control->setForm($form); return parent::setForm($form); }
[ "public", "function", "setForm", "(", "ControlCollection", "$", "form", "=", "null", ")", ":", "Control", "{", "$", "this", "->", "control", "->", "setForm", "(", "$", "form", ")", ";", "return", "parent", "::", "setForm", "(", "$", "form", ")", ";", "}" ]
Set control form. @param ControlCollection|null $form @return static
[ "Set", "control", "form", "." ]
4dd657d1c8caeb0b87f25239fabf5fa064db29cd
https://github.com/rabbitcms/forms/blob/4dd657d1c8caeb0b87f25239fabf5fa064db29cd/src/Controls/InputGroup.php#L78-L83
train
libreworks/microformats
src/Geo.php
Geo.distance
public function distance(Geo $other) { if ($other === $this) { return 0.0; } else { return self::DEG_KM * rad2deg( acos( (sin(deg2rad($this->latitude)) * sin(deg2rad($other->latitude))) + (cos(deg2rad($this->latitude)) * cos(deg2rad($other->latitude)) * cos(deg2rad($this->longitude - $other->longitude))) ) ); } }
php
public function distance(Geo $other) { if ($other === $this) { return 0.0; } else { return self::DEG_KM * rad2deg( acos( (sin(deg2rad($this->latitude)) * sin(deg2rad($other->latitude))) + (cos(deg2rad($this->latitude)) * cos(deg2rad($other->latitude)) * cos(deg2rad($this->longitude - $other->longitude))) ) ); } }
[ "public", "function", "distance", "(", "Geo", "$", "other", ")", "{", "if", "(", "$", "other", "===", "$", "this", ")", "{", "return", "0.0", ";", "}", "else", "{", "return", "self", "::", "DEG_KM", "*", "rad2deg", "(", "acos", "(", "(", "sin", "(", "deg2rad", "(", "$", "this", "->", "latitude", ")", ")", "*", "sin", "(", "deg2rad", "(", "$", "other", "->", "latitude", ")", ")", ")", "+", "(", "cos", "(", "deg2rad", "(", "$", "this", "->", "latitude", ")", ")", "*", "cos", "(", "deg2rad", "(", "$", "other", "->", "latitude", ")", ")", "*", "cos", "(", "deg2rad", "(", "$", "this", "->", "longitude", "-", "$", "other", "->", "longitude", ")", ")", ")", ")", ")", ";", "}", "}" ]
Uses the Haversine formula to calculate kilometer point distance. @param \Libreworks\Microformats\Geo $other @return float The distance
[ "Uses", "the", "Haversine", "formula", "to", "calculate", "kilometer", "point", "distance", "." ]
f208650cb83e8711f5f35878cfa285b7cb505d3d
https://github.com/libreworks/microformats/blob/f208650cb83e8711f5f35878cfa285b7cb505d3d/src/Geo.php#L95-L107
train
jenskooij/cloudcontrol
src/search/Search.php
Search.getIndexedDocuments
public function getIndexedDocuments() { $db = $this->getSearchDbHandle(); $sql = ' SELECT count(DISTINCT documentPath) AS indexedDocuments FROM term_frequency '; if (!$stmt = $db->query($sql)) { $errorInfo = $db->errorInfo(); $errorMsg = $errorInfo[2]; throw new \RuntimeException('SQLite Exception: ' . $errorMsg . ' in SQL: <br /><pre>' . $sql . '</pre>'); } $result = $stmt->fetch(\PDO::FETCH_COLUMN); if (false === $result) { $errorInfo = $db->errorInfo(); $errorMsg = $errorInfo[2]; throw new \RuntimeException('SQLite Exception: ' . $errorMsg . ' in SQL: <br /><pre>' . $sql . '</pre>'); } return (int)$result; }
php
public function getIndexedDocuments() { $db = $this->getSearchDbHandle(); $sql = ' SELECT count(DISTINCT documentPath) AS indexedDocuments FROM term_frequency '; if (!$stmt = $db->query($sql)) { $errorInfo = $db->errorInfo(); $errorMsg = $errorInfo[2]; throw new \RuntimeException('SQLite Exception: ' . $errorMsg . ' in SQL: <br /><pre>' . $sql . '</pre>'); } $result = $stmt->fetch(\PDO::FETCH_COLUMN); if (false === $result) { $errorInfo = $db->errorInfo(); $errorMsg = $errorInfo[2]; throw new \RuntimeException('SQLite Exception: ' . $errorMsg . ' in SQL: <br /><pre>' . $sql . '</pre>'); } return (int)$result; }
[ "public", "function", "getIndexedDocuments", "(", ")", "{", "$", "db", "=", "$", "this", "->", "getSearchDbHandle", "(", ")", ";", "$", "sql", "=", "'\n\t\t\tSELECT count(DISTINCT documentPath) AS indexedDocuments\n\t\t\t FROM term_frequency\n\t\t'", ";", "if", "(", "!", "$", "stmt", "=", "$", "db", "->", "query", "(", "$", "sql", ")", ")", "{", "$", "errorInfo", "=", "$", "db", "->", "errorInfo", "(", ")", ";", "$", "errorMsg", "=", "$", "errorInfo", "[", "2", "]", ";", "throw", "new", "\\", "RuntimeException", "(", "'SQLite Exception: '", ".", "$", "errorMsg", ".", "' in SQL: <br /><pre>'", ".", "$", "sql", ".", "'</pre>'", ")", ";", "}", "$", "result", "=", "$", "stmt", "->", "fetch", "(", "\\", "PDO", "::", "FETCH_COLUMN", ")", ";", "if", "(", "false", "===", "$", "result", ")", "{", "$", "errorInfo", "=", "$", "db", "->", "errorInfo", "(", ")", ";", "$", "errorMsg", "=", "$", "errorInfo", "[", "2", "]", ";", "throw", "new", "\\", "RuntimeException", "(", "'SQLite Exception: '", ".", "$", "errorMsg", ".", "' in SQL: <br /><pre>'", ".", "$", "sql", ".", "'</pre>'", ")", ";", "}", "return", "(", "int", ")", "$", "result", ";", "}" ]
Returns the amount of distinct documents that are currently in the search index. @return int @throws \Exception
[ "Returns", "the", "amount", "of", "distinct", "documents", "that", "are", "currently", "in", "the", "search", "index", "." ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/search/Search.php#L74-L93
train
jenskooij/cloudcontrol
src/search/Search.php
Search.queryTokens
private function queryTokens() { $tokens = $this->getTokens(); $queryNorm = $this->getQueryNorm($tokens); $results = array(); foreach ($tokens as $token) { $results[$token] = $this->getResultsForToken($token, $queryNorm); } return $results; }
php
private function queryTokens() { $tokens = $this->getTokens(); $queryNorm = $this->getQueryNorm($tokens); $results = array(); foreach ($tokens as $token) { $results[$token] = $this->getResultsForToken($token, $queryNorm); } return $results; }
[ "private", "function", "queryTokens", "(", ")", "{", "$", "tokens", "=", "$", "this", "->", "getTokens", "(", ")", ";", "$", "queryNorm", "=", "$", "this", "->", "getQueryNorm", "(", "$", "tokens", ")", ";", "$", "results", "=", "array", "(", ")", ";", "foreach", "(", "$", "tokens", "as", "$", "token", ")", "{", "$", "results", "[", "$", "token", "]", "=", "$", "this", "->", "getResultsForToken", "(", "$", "token", ",", "$", "queryNorm", ")", ";", "}", "return", "$", "results", ";", "}" ]
Queries each token present in the Tokenizer and returns SearchResult objects for the found documents @return array @throws \Exception
[ "Queries", "each", "token", "present", "in", "the", "Tokenizer", "and", "returns", "SearchResult", "objects", "for", "the", "found", "documents" ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/search/Search.php#L102-L112
train
jenskooij/cloudcontrol
src/search/Search.php
Search.getSearchSuggestions
private function getSearchSuggestions() { $tokens = $this->getTokens(); $allResults = array(); foreach ($tokens as $token) { $allResults = $this->getSearchSuggestion($token, $allResults); } return $allResults; }
php
private function getSearchSuggestions() { $tokens = $this->getTokens(); $allResults = array(); foreach ($tokens as $token) { $allResults = $this->getSearchSuggestion($token, $allResults); } return $allResults; }
[ "private", "function", "getSearchSuggestions", "(", ")", "{", "$", "tokens", "=", "$", "this", "->", "getTokens", "(", ")", ";", "$", "allResults", "=", "array", "(", ")", ";", "foreach", "(", "$", "tokens", "as", "$", "token", ")", "{", "$", "allResults", "=", "$", "this", "->", "getSearchSuggestion", "(", "$", "token", ",", "$", "allResults", ")", ";", "}", "return", "$", "allResults", ";", "}" ]
Uses the levenshtein algorithm to determine the term that is closest to the token that was input for the search @return array @throws \Exception
[ "Uses", "the", "levenshtein", "algorithm", "to", "determine", "the", "term", "that", "is", "closest", "to", "the", "token", "that", "was", "input", "for", "the", "search" ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/search/Search.php#L276-L284
train
jenskooij/cloudcontrol
src/search/Search.php
Search.getTokens
private function getTokens() { $tokenVector = array( 'query' => array(), ); $tokenVector['query'] = $this->tokenizer->getTokenVector(); $tokens = $this->applyFilters($tokenVector); if (!empty($tokens)) { $tokens = array_keys($tokens['query']); } return $tokens; }
php
private function getTokens() { $tokenVector = array( 'query' => array(), ); $tokenVector['query'] = $this->tokenizer->getTokenVector(); $tokens = $this->applyFilters($tokenVector); if (!empty($tokens)) { $tokens = array_keys($tokens['query']); } return $tokens; }
[ "private", "function", "getTokens", "(", ")", "{", "$", "tokenVector", "=", "array", "(", "'query'", "=>", "array", "(", ")", ",", ")", ";", "$", "tokenVector", "[", "'query'", "]", "=", "$", "this", "->", "tokenizer", "->", "getTokenVector", "(", ")", ";", "$", "tokens", "=", "$", "this", "->", "applyFilters", "(", "$", "tokenVector", ")", ";", "if", "(", "!", "empty", "(", "$", "tokens", ")", ")", "{", "$", "tokens", "=", "array_keys", "(", "$", "tokens", "[", "'query'", "]", ")", ";", "}", "return", "$", "tokens", ";", "}" ]
Retrieves all tokens from the tokenizer @return array
[ "Retrieves", "all", "tokens", "from", "the", "tokenizer" ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/search/Search.php#L290-L302
train
nochso/ORM2
src/ResultSet.php
ResultSet.delete
public function delete() { if (count($this) == 0) { return; } $ids = $this->getPrimaryKeyList(); $hitman = new $this->className(); $hitman->in($hitman->getPrimaryKey(), $ids)->delete(); }
php
public function delete() { if (count($this) == 0) { return; } $ids = $this->getPrimaryKeyList(); $hitman = new $this->className(); $hitman->in($hitman->getPrimaryKey(), $ids)->delete(); }
[ "public", "function", "delete", "(", ")", "{", "if", "(", "count", "(", "$", "this", ")", "==", "0", ")", "{", "return", ";", "}", "$", "ids", "=", "$", "this", "->", "getPrimaryKeyList", "(", ")", ";", "$", "hitman", "=", "new", "$", "this", "->", "className", "(", ")", ";", "$", "hitman", "->", "in", "(", "$", "hitman", "->", "getPrimaryKey", "(", ")", ",", "$", "ids", ")", "->", "delete", "(", ")", ";", "}" ]
Functions to operate on all elements of the ResultSet at once
[ "Functions", "to", "operate", "on", "all", "elements", "of", "the", "ResultSet", "at", "once" ]
89f9a5c61ad5f575fbdd52990171b52d54f8bfbc
https://github.com/nochso/ORM2/blob/89f9a5c61ad5f575fbdd52990171b52d54f8bfbc/src/ResultSet.php#L27-L35
train
nochso/ORM2
src/ResultSet.php
ResultSet.update
public function update($data) { if (count($this) == 0) { return; } $ids = $this->getPrimaryKeyList(); $updater = new $this->className(); $updater->in($updater->getPrimaryKey(), $ids)->update($data); }
php
public function update($data) { if (count($this) == 0) { return; } $ids = $this->getPrimaryKeyList(); $updater = new $this->className(); $updater->in($updater->getPrimaryKey(), $ids)->update($data); }
[ "public", "function", "update", "(", "$", "data", ")", "{", "if", "(", "count", "(", "$", "this", ")", "==", "0", ")", "{", "return", ";", "}", "$", "ids", "=", "$", "this", "->", "getPrimaryKeyList", "(", ")", ";", "$", "updater", "=", "new", "$", "this", "->", "className", "(", ")", ";", "$", "updater", "->", "in", "(", "$", "updater", "->", "getPrimaryKey", "(", ")", ",", "$", "ids", ")", "->", "update", "(", "$", "data", ")", ";", "}" ]
Update all entries in this ResultSet with the same values
[ "Update", "all", "entries", "in", "this", "ResultSet", "with", "the", "same", "values" ]
89f9a5c61ad5f575fbdd52990171b52d54f8bfbc
https://github.com/nochso/ORM2/blob/89f9a5c61ad5f575fbdd52990171b52d54f8bfbc/src/ResultSet.php#L40-L48
train
nochso/ORM2
src/ResultSet.php
ResultSet.getPrimaryKeyList
public function getPrimaryKeyList() { $ids = []; if (count($this) > 0) { foreach ($this as $row) { $ids[] = $row->getPrimaryKeyValue(); } } return $ids; }
php
public function getPrimaryKeyList() { $ids = []; if (count($this) > 0) { foreach ($this as $row) { $ids[] = $row->getPrimaryKeyValue(); } } return $ids; }
[ "public", "function", "getPrimaryKeyList", "(", ")", "{", "$", "ids", "=", "[", "]", ";", "if", "(", "count", "(", "$", "this", ")", ">", "0", ")", "{", "foreach", "(", "$", "this", "as", "$", "row", ")", "{", "$", "ids", "[", "]", "=", "$", "row", "->", "getPrimaryKeyValue", "(", ")", ";", "}", "}", "return", "$", "ids", ";", "}" ]
Returns an array of all primary keys contained in the ResultSet @return array
[ "Returns", "an", "array", "of", "all", "primary", "keys", "contained", "in", "the", "ResultSet" ]
89f9a5c61ad5f575fbdd52990171b52d54f8bfbc
https://github.com/nochso/ORM2/blob/89f9a5c61ad5f575fbdd52990171b52d54f8bfbc/src/ResultSet.php#L74-L83
train
stubbles/stubbles-peer
src/main/php/HeaderList.php
HeaderList.parse
private static function parse(string $headers): array { $header = []; $matches = []; preg_match_all( '=^(.[^: ]+): ([^\r\n]*)=m', $headers, $matches, PREG_SET_ORDER ); foreach ($matches as $line) { $header[$line[1]] = $line[2]; } return $header; }
php
private static function parse(string $headers): array { $header = []; $matches = []; preg_match_all( '=^(.[^: ]+): ([^\r\n]*)=m', $headers, $matches, PREG_SET_ORDER ); foreach ($matches as $line) { $header[$line[1]] = $line[2]; } return $header; }
[ "private", "static", "function", "parse", "(", "string", "$", "headers", ")", ":", "array", "{", "$", "header", "=", "[", "]", ";", "$", "matches", "=", "[", "]", ";", "preg_match_all", "(", "'=^(.[^: ]+): ([^\\r\\n]*)=m'", ",", "$", "headers", ",", "$", "matches", ",", "PREG_SET_ORDER", ")", ";", "foreach", "(", "$", "matches", "as", "$", "line", ")", "{", "$", "header", "[", "$", "line", "[", "1", "]", "]", "=", "$", "line", "[", "2", "]", ";", "}", "return", "$", "header", ";", "}" ]
parses given header string and returns a list of headers @param string $headers @return array
[ "parses", "given", "header", "string", "and", "returns", "a", "list", "of", "headers" ]
dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc
https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/HeaderList.php#L54-L69
train
stubbles/stubbles-peer
src/main/php/HeaderList.php
HeaderList.append
public function append($headers): self { if (is_string($headers)) { $append = self::parse($headers); } elseif (is_array($headers)) { $append = $headers; } elseif ($headers instanceof self) { $append = $headers->headers; } else { throw new \InvalidArgumentException( 'Given headers must be a string, a list of headers' . ' or another instance of ' . __CLASS__ ); } $this->headers = array_merge($this->headers, $append); return $this; }
php
public function append($headers): self { if (is_string($headers)) { $append = self::parse($headers); } elseif (is_array($headers)) { $append = $headers; } elseif ($headers instanceof self) { $append = $headers->headers; } else { throw new \InvalidArgumentException( 'Given headers must be a string, a list of headers' . ' or another instance of ' . __CLASS__ ); } $this->headers = array_merge($this->headers, $append); return $this; }
[ "public", "function", "append", "(", "$", "headers", ")", ":", "self", "{", "if", "(", "is_string", "(", "$", "headers", ")", ")", "{", "$", "append", "=", "self", "::", "parse", "(", "$", "headers", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "headers", ")", ")", "{", "$", "append", "=", "$", "headers", ";", "}", "elseif", "(", "$", "headers", "instanceof", "self", ")", "{", "$", "append", "=", "$", "headers", "->", "headers", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Given headers must be a string, a list of headers'", ".", "' or another instance of '", ".", "__CLASS__", ")", ";", "}", "$", "this", "->", "headers", "=", "array_merge", "(", "$", "this", "->", "headers", ",", "$", "append", ")", ";", "return", "$", "this", ";", "}" ]
appends given headers If the header to append contain an already set header the existing header value will be overwritten by the new one. @param string|array|\stubbles\peer\HeaderList $headers @return \stubbles\peer\HeaderList @throws \InvalidArgumentException @since 2.0.0
[ "appends", "given", "headers" ]
dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc
https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/HeaderList.php#L82-L99
train
stubbles/stubbles-peer
src/main/php/HeaderList.php
HeaderList.put
public function put(string $key, $value): self { if (!is_scalar($value)) { throw new \InvalidArgumentException( 'Argument 2 passed to ' . __METHOD__ . ' must be an instance of a scalar value.' ); } $this->headers[$key] = (string) $value; return $this; }
php
public function put(string $key, $value): self { if (!is_scalar($value)) { throw new \InvalidArgumentException( 'Argument 2 passed to ' . __METHOD__ . ' must be an instance of a scalar value.' ); } $this->headers[$key] = (string) $value; return $this; }
[ "public", "function", "put", "(", "string", "$", "key", ",", "$", "value", ")", ":", "self", "{", "if", "(", "!", "is_scalar", "(", "$", "value", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Argument 2 passed to '", ".", "__METHOD__", ".", "' must be an instance of a scalar value.'", ")", ";", "}", "$", "this", "->", "headers", "[", "$", "key", "]", "=", "(", "string", ")", "$", "value", ";", "return", "$", "this", ";", "}" ]
creates header with value for key @param string $key name of header @param scalar $value value of header @return \stubbles\peer\HeaderList @throws \InvalidArgumentException
[ "creates", "header", "with", "value", "for", "key" ]
dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc
https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/HeaderList.php#L109-L120
train
stubbles/stubbles-peer
src/main/php/HeaderList.php
HeaderList.remove
public function remove(string $key): self { if (isset($this->headers[$key]) == true) { unset($this->headers[$key]); } return $this; }
php
public function remove(string $key): self { if (isset($this->headers[$key]) == true) { unset($this->headers[$key]); } return $this; }
[ "public", "function", "remove", "(", "string", "$", "key", ")", ":", "self", "{", "if", "(", "isset", "(", "$", "this", "->", "headers", "[", "$", "key", "]", ")", "==", "true", ")", "{", "unset", "(", "$", "this", "->", "headers", "[", "$", "key", "]", ")", ";", "}", "return", "$", "this", ";", "}" ]
removes header with given key @param string $key name of header @return \stubbles\peer\HeaderList
[ "removes", "header", "with", "given", "key" ]
dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc
https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/HeaderList.php#L128-L135
train
stubbles/stubbles-peer
src/main/php/HeaderList.php
HeaderList.putCookie
public function putCookie(array $cookieValues): self { $cookieValue = ''; foreach ($cookieValues as $key => $value) { $cookieValue .= $key . '=' . urlencode($value) . ';'; } $this->put('Cookie', $cookieValue); return $this; }
php
public function putCookie(array $cookieValues): self { $cookieValue = ''; foreach ($cookieValues as $key => $value) { $cookieValue .= $key . '=' . urlencode($value) . ';'; } $this->put('Cookie', $cookieValue); return $this; }
[ "public", "function", "putCookie", "(", "array", "$", "cookieValues", ")", ":", "self", "{", "$", "cookieValue", "=", "''", ";", "foreach", "(", "$", "cookieValues", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "cookieValue", ".=", "$", "key", ".", "'='", ".", "urlencode", "(", "$", "value", ")", ".", "';'", ";", "}", "$", "this", "->", "put", "(", "'Cookie'", ",", "$", "cookieValue", ")", ";", "return", "$", "this", ";", "}" ]
creates header for cookie @param array $cookieValues cookie values @return \stubbles\peer\HeaderList
[ "creates", "header", "for", "cookie" ]
dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc
https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/HeaderList.php#L167-L176
train
stubbles/stubbles-peer
src/main/php/HeaderList.php
HeaderList.putAuthorization
public function putAuthorization(string $user, string $password): self { $this->put('Authorization', 'BASIC ' . base64_encode($user . ':' . $password)); return $this; }
php
public function putAuthorization(string $user, string $password): self { $this->put('Authorization', 'BASIC ' . base64_encode($user . ':' . $password)); return $this; }
[ "public", "function", "putAuthorization", "(", "string", "$", "user", ",", "string", "$", "password", ")", ":", "self", "{", "$", "this", "->", "put", "(", "'Authorization'", ",", "'BASIC '", ".", "base64_encode", "(", "$", "user", ".", "':'", ".", "$", "password", ")", ")", ";", "return", "$", "this", ";", "}" ]
creates header for authorization @param string $user login name @param string $password login password @return \stubbles\peer\HeaderList
[ "creates", "header", "for", "authorization" ]
dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc
https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/HeaderList.php#L185-L189
train
stubbles/stubbles-peer
src/main/php/HeaderList.php
HeaderList.putDate
public function putDate(int $timestamp = null): self { if (null === $timestamp) { $date = gmdate('D, d M Y H:i:s'); } else { $date = gmdate('D, d M Y H:i:s', $timestamp); } $this->put('Date', $date . ' GMT'); return $this; }
php
public function putDate(int $timestamp = null): self { if (null === $timestamp) { $date = gmdate('D, d M Y H:i:s'); } else { $date = gmdate('D, d M Y H:i:s', $timestamp); } $this->put('Date', $date . ' GMT'); return $this; }
[ "public", "function", "putDate", "(", "int", "$", "timestamp", "=", "null", ")", ":", "self", "{", "if", "(", "null", "===", "$", "timestamp", ")", "{", "$", "date", "=", "gmdate", "(", "'D, d M Y H:i:s'", ")", ";", "}", "else", "{", "$", "date", "=", "gmdate", "(", "'D, d M Y H:i:s'", ",", "$", "timestamp", ")", ";", "}", "$", "this", "->", "put", "(", "'Date'", ",", "$", "date", ".", "' GMT'", ")", ";", "return", "$", "this", ";", "}" ]
adds a date header @param int $timestamp timestamp to use as date, defaults to current timestamp @return \stubbles\peer\HeaderList
[ "adds", "a", "date", "header" ]
dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc
https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/HeaderList.php#L197-L207
train
romm/configuration_object
Classes/TypeConverter/ConfigurationObjectConverter.php
ConfigurationObjectConverter.getTypeOfChildProperty
public function getTypeOfChildProperty($targetType, $propertyName, PropertyMappingConfigurationInterface $configuration) { $specificTargetType = $this->objectContainer->getImplementationClassName($targetType); if (Core::get()->classExists($specificTargetType)) { $propertyTags = $this->reflectionService->getPropertyTagValues($specificTargetType, $propertyName, 'var'); if (!empty($propertyTags)) { return current($propertyTags); } } return parent::getTypeOfChildProperty($targetType, $propertyName, $configuration); }
php
public function getTypeOfChildProperty($targetType, $propertyName, PropertyMappingConfigurationInterface $configuration) { $specificTargetType = $this->objectContainer->getImplementationClassName($targetType); if (Core::get()->classExists($specificTargetType)) { $propertyTags = $this->reflectionService->getPropertyTagValues($specificTargetType, $propertyName, 'var'); if (!empty($propertyTags)) { return current($propertyTags); } } return parent::getTypeOfChildProperty($targetType, $propertyName, $configuration); }
[ "public", "function", "getTypeOfChildProperty", "(", "$", "targetType", ",", "$", "propertyName", ",", "PropertyMappingConfigurationInterface", "$", "configuration", ")", "{", "$", "specificTargetType", "=", "$", "this", "->", "objectContainer", "->", "getImplementationClassName", "(", "$", "targetType", ")", ";", "if", "(", "Core", "::", "get", "(", ")", "->", "classExists", "(", "$", "specificTargetType", ")", ")", "{", "$", "propertyTags", "=", "$", "this", "->", "reflectionService", "->", "getPropertyTagValues", "(", "$", "specificTargetType", ",", "$", "propertyName", ",", "'var'", ")", ";", "if", "(", "!", "empty", "(", "$", "propertyTags", ")", ")", "{", "return", "current", "(", "$", "propertyTags", ")", ";", "}", "}", "return", "parent", "::", "getTypeOfChildProperty", "(", "$", "targetType", ",", "$", "propertyName", ",", "$", "configuration", ")", ";", "}" ]
Will check the type of the given class property, if reflection gives no result, the parent function is called. @inheritdoc
[ "Will", "check", "the", "type", "of", "the", "given", "class", "property", "if", "reflection", "gives", "no", "result", "the", "parent", "function", "is", "called", "." ]
d3a40903386c2e0766bd8279337fe6da45cf5ce3
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/TypeConverter/ConfigurationObjectConverter.php#L34-L47
train
cubicmushroom/exceptions
src/CubicMushroom/Exceptions/AbstractException.php
AbstractException.build
public static function build(array $constructorArguments = array(), $additionalProperties = array()) { $constructorDefaults = array('message' => null, 'code' => null, 'previous' => null); $constructorArguments = array_merge($constructorDefaults, $constructorArguments); $message = self::prepareMessage($constructorArguments['message'], $additionalProperties); $code = self::prepareCode($constructorArguments['code']); $previous = $constructorArguments['previous']; $e = new static($message, $code, $previous); $e = self::addAdditionalProperties($e, $additionalProperties); return $e; }
php
public static function build(array $constructorArguments = array(), $additionalProperties = array()) { $constructorDefaults = array('message' => null, 'code' => null, 'previous' => null); $constructorArguments = array_merge($constructorDefaults, $constructorArguments); $message = self::prepareMessage($constructorArguments['message'], $additionalProperties); $code = self::prepareCode($constructorArguments['code']); $previous = $constructorArguments['previous']; $e = new static($message, $code, $previous); $e = self::addAdditionalProperties($e, $additionalProperties); return $e; }
[ "public", "static", "function", "build", "(", "array", "$", "constructorArguments", "=", "array", "(", ")", ",", "$", "additionalProperties", "=", "array", "(", ")", ")", "{", "$", "constructorDefaults", "=", "array", "(", "'message'", "=>", "null", ",", "'code'", "=>", "null", ",", "'previous'", "=>", "null", ")", ";", "$", "constructorArguments", "=", "array_merge", "(", "$", "constructorDefaults", ",", "$", "constructorArguments", ")", ";", "$", "message", "=", "self", "::", "prepareMessage", "(", "$", "constructorArguments", "[", "'message'", "]", ",", "$", "additionalProperties", ")", ";", "$", "code", "=", "self", "::", "prepareCode", "(", "$", "constructorArguments", "[", "'code'", "]", ")", ";", "$", "previous", "=", "$", "constructorArguments", "[", "'previous'", "]", ";", "$", "e", "=", "new", "static", "(", "$", "message", ",", "$", "code", ",", "$", "previous", ")", ";", "$", "e", "=", "self", "::", "addAdditionalProperties", "(", "$", "e", ",", "$", "additionalProperties", ")", ";", "return", "$", "e", ";", "}" ]
Helper method to prepare all but the most complex exceptions Pass in an array containing any or all of the following keys - message (string) - code (int) - previous (\Exception) If you don't pass in a 'message' or a 'code' then the method will attempt to get these from the exception class getDefaultMessage or getDefaultCode methods, respectively. If no message is prepared, then we throw a \RuntimeException... There's no excuse for not including a useful message! If no code if prepared, then 500 is used @param array $constructorArguments [optional] Arguments to be passed to the constructor @param array $additionalProperties [optional] Additional p @return static @throws \RuntimeException if no message can be prepared... There's no excuse for not including a useful message!
[ "Helper", "method", "to", "prepare", "all", "but", "the", "most", "complex", "exceptions" ]
d6f48c92881b677d8c45527a7d6a1c687aa06227
https://github.com/cubicmushroom/exceptions/blob/d6f48c92881b677d8c45527a7d6a1c687aa06227/src/CubicMushroom/Exceptions/AbstractException.php#L47-L61
train
SagittariusX/Beluga.DynamicProperties
src/Beluga/DynamicProperties/ExplicitGetterSetter.php
ExplicitGetterSetter.__isset
public function __isset( string $name ) { if ( $this->hasWritableProperty( $name, $setterName ) ) { return true; } return parent::__isset( $name ); }
php
public function __isset( string $name ) { if ( $this->hasWritableProperty( $name, $setterName ) ) { return true; } return parent::__isset( $name ); }
[ "public", "function", "__isset", "(", "string", "$", "name", ")", "{", "if", "(", "$", "this", "->", "hasWritableProperty", "(", "$", "name", ",", "$", "setterName", ")", ")", "{", "return", "true", ";", "}", "return", "parent", "::", "__isset", "(", "$", "name", ")", ";", "}" ]
Magic isset implementation. @param string $name The name of the required property. @return boolean
[ "Magic", "isset", "implementation", "." ]
39a036030d768d64e5a9c5d715c4218bf06b1ce5
https://github.com/SagittariusX/Beluga.DynamicProperties/blob/39a036030d768d64e5a9c5d715c4218bf06b1ce5/src/Beluga/DynamicProperties/ExplicitGetterSetter.php#L73-L83
train
SagittariusX/Beluga.DynamicProperties
src/Beluga/DynamicProperties/ExplicitGetterSetter.php
ExplicitGetterSetter.hasWritableProperty
public function hasWritableProperty( string $name, &$setterName ) : bool { if ( \in_array( $name, $this->ignoreSetProperties ) ) { return false; } $setterName = 'set' . \ucfirst( $name ); return \method_exists( $this, $setterName ); }
php
public function hasWritableProperty( string $name, &$setterName ) : bool { if ( \in_array( $name, $this->ignoreSetProperties ) ) { return false; } $setterName = 'set' . \ucfirst( $name ); return \method_exists( $this, $setterName ); }
[ "public", "function", "hasWritableProperty", "(", "string", "$", "name", ",", "&", "$", "setterName", ")", ":", "bool", "{", "if", "(", "\\", "in_array", "(", "$", "name", ",", "$", "this", "->", "ignoreSetProperties", ")", ")", "{", "return", "false", ";", "}", "$", "setterName", "=", "'set'", ".", "\\", "ucfirst", "(", "$", "name", ")", ";", "return", "\\", "method_exists", "(", "$", "this", ",", "$", "setterName", ")", ";", "}" ]
Returns, if a property with the defined name exists for write access. @param string $name The name of the property. @param string $setterName Returns the name of the associated set method, if method returns TRUE. @return boolean
[ "Returns", "if", "a", "property", "with", "the", "defined", "name", "exists", "for", "write", "access", "." ]
39a036030d768d64e5a9c5d715c4218bf06b1ce5
https://github.com/SagittariusX/Beluga.DynamicProperties/blob/39a036030d768d64e5a9c5d715c4218bf06b1ce5/src/Beluga/DynamicProperties/ExplicitGetterSetter.php#L92-L104
train
randomhost/image
src/php/Image.php
Image.getInstanceByPath
public static function getInstanceByPath($path, $cacheDir = '') { $instance = new self(); $instance->pathFile = $path; if (!empty($cacheDir)) { $instance->setCacheDir($cacheDir); $instance->setCachePath(); } $instance->readImage(); return $instance; }
php
public static function getInstanceByPath($path, $cacheDir = '') { $instance = new self(); $instance->pathFile = $path; if (!empty($cacheDir)) { $instance->setCacheDir($cacheDir); $instance->setCachePath(); } $instance->readImage(); return $instance; }
[ "public", "static", "function", "getInstanceByPath", "(", "$", "path", ",", "$", "cacheDir", "=", "''", ")", "{", "$", "instance", "=", "new", "self", "(", ")", ";", "$", "instance", "->", "pathFile", "=", "$", "path", ";", "if", "(", "!", "empty", "(", "$", "cacheDir", ")", ")", "{", "$", "instance", "->", "setCacheDir", "(", "$", "cacheDir", ")", ";", "$", "instance", "->", "setCachePath", "(", ")", ";", "}", "$", "instance", "->", "readImage", "(", ")", ";", "return", "$", "instance", ";", "}" ]
Creates a new image from file or URL. @param string $path Path to the image. @param string $cacheDir Optional: Directory path for caching image files. @return $this
[ "Creates", "a", "new", "image", "from", "file", "or", "URL", "." ]
bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0
https://github.com/randomhost/image/blob/bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0/src/php/Image.php#L123-L137
train
randomhost/image
src/php/Image.php
Image.getInstanceByCreate
public static function getInstanceByCreate($width, $height) { $instance = new self(); // set image dimensions $instance->width = (int)$width; $instance->height = (int)$height; $instance->createImage(); return $instance; }
php
public static function getInstanceByCreate($width, $height) { $instance = new self(); // set image dimensions $instance->width = (int)$width; $instance->height = (int)$height; $instance->createImage(); return $instance; }
[ "public", "static", "function", "getInstanceByCreate", "(", "$", "width", ",", "$", "height", ")", "{", "$", "instance", "=", "new", "self", "(", ")", ";", "// set image dimensions", "$", "instance", "->", "width", "=", "(", "int", ")", "$", "width", ";", "$", "instance", "->", "height", "=", "(", "int", ")", "$", "height", ";", "$", "instance", "->", "createImage", "(", ")", ";", "return", "$", "instance", ";", "}" ]
Creates a new image in memory. @param int $width Image width. @param int $height Image height. @return $this
[ "Creates", "a", "new", "image", "in", "memory", "." ]
bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0
https://github.com/randomhost/image/blob/bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0/src/php/Image.php#L147-L158
train
randomhost/image
src/php/Image.php
Image.merge
public function merge( Image $srcImage, $dstX, $dstY, $strategy = self::MERGE_SCALE_SRC ) { if (!is_resource($this->image) || !is_resource($srcImage->image)) { throw new \RuntimeException( 'Attempt to merge image data using an invalid image resource.' ); } // determine re-sampling strategy switch ($strategy) { // merge using the destination image dimensions case self::MERGE_SCALE_DST: $dstWidth = $this->width; $dstHeight = $this->height; break; // merge using the destination image dimensions, do not upscale case self::MERGE_SCALE_DST_NO_UPSCALE: $dstWidth = $this->width; if ($dstWidth > $srcImage->width) { $dstWidth = $srcImage->width; } $dstHeight = $this->height; if ($dstHeight > $srcImage->height) { $dstHeight = $srcImage->height; } break; // merge using the source image dimensions case self::MERGE_SCALE_SRC: default: $dstWidth = $srcImage->width; $dstHeight = $srcImage->height; } // copy images around @imagecopyresampled( $this->image, $srcImage->image, (int)$dstX, (int)$dstY, 0, 0, (int)$dstWidth, (int)$dstHeight, $srcImage->width, $srcImage->height ); return $this; }
php
public function merge( Image $srcImage, $dstX, $dstY, $strategy = self::MERGE_SCALE_SRC ) { if (!is_resource($this->image) || !is_resource($srcImage->image)) { throw new \RuntimeException( 'Attempt to merge image data using an invalid image resource.' ); } // determine re-sampling strategy switch ($strategy) { // merge using the destination image dimensions case self::MERGE_SCALE_DST: $dstWidth = $this->width; $dstHeight = $this->height; break; // merge using the destination image dimensions, do not upscale case self::MERGE_SCALE_DST_NO_UPSCALE: $dstWidth = $this->width; if ($dstWidth > $srcImage->width) { $dstWidth = $srcImage->width; } $dstHeight = $this->height; if ($dstHeight > $srcImage->height) { $dstHeight = $srcImage->height; } break; // merge using the source image dimensions case self::MERGE_SCALE_SRC: default: $dstWidth = $srcImage->width; $dstHeight = $srcImage->height; } // copy images around @imagecopyresampled( $this->image, $srcImage->image, (int)$dstX, (int)$dstY, 0, 0, (int)$dstWidth, (int)$dstHeight, $srcImage->width, $srcImage->height ); return $this; }
[ "public", "function", "merge", "(", "Image", "$", "srcImage", ",", "$", "dstX", ",", "$", "dstY", ",", "$", "strategy", "=", "self", "::", "MERGE_SCALE_SRC", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "image", ")", "||", "!", "is_resource", "(", "$", "srcImage", "->", "image", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Attempt to merge image data using an invalid image resource.'", ")", ";", "}", "// determine re-sampling strategy", "switch", "(", "$", "strategy", ")", "{", "// merge using the destination image dimensions", "case", "self", "::", "MERGE_SCALE_DST", ":", "$", "dstWidth", "=", "$", "this", "->", "width", ";", "$", "dstHeight", "=", "$", "this", "->", "height", ";", "break", ";", "// merge using the destination image dimensions, do not upscale", "case", "self", "::", "MERGE_SCALE_DST_NO_UPSCALE", ":", "$", "dstWidth", "=", "$", "this", "->", "width", ";", "if", "(", "$", "dstWidth", ">", "$", "srcImage", "->", "width", ")", "{", "$", "dstWidth", "=", "$", "srcImage", "->", "width", ";", "}", "$", "dstHeight", "=", "$", "this", "->", "height", ";", "if", "(", "$", "dstHeight", ">", "$", "srcImage", "->", "height", ")", "{", "$", "dstHeight", "=", "$", "srcImage", "->", "height", ";", "}", "break", ";", "// merge using the source image dimensions", "case", "self", "::", "MERGE_SCALE_SRC", ":", "default", ":", "$", "dstWidth", "=", "$", "srcImage", "->", "width", ";", "$", "dstHeight", "=", "$", "srcImage", "->", "height", ";", "}", "// copy images around", "@", "imagecopyresampled", "(", "$", "this", "->", "image", ",", "$", "srcImage", "->", "image", ",", "(", "int", ")", "$", "dstX", ",", "(", "int", ")", "$", "dstY", ",", "0", ",", "0", ",", "(", "int", ")", "$", "dstWidth", ",", "(", "int", ")", "$", "dstHeight", ",", "$", "srcImage", "->", "width", ",", "$", "srcImage", "->", "height", ")", ";", "return", "$", "this", ";", "}" ]
Copies the given Image image stream into the image stream of the active instance using a scaling strategy. @param Image $srcImage The source image. @param int $dstX x-coordinate of destination point. @param int $dstY y-coordinate of destination point. @param int $strategy Scaling strategy. Default: self::MERGE_SCALE_SRC @return $this @throws \RuntimeException Thrown if $this->image or $srcImage->image is not a valid image resource.
[ "Copies", "the", "given", "Image", "image", "stream", "into", "the", "image", "stream", "of", "the", "active", "instance", "using", "a", "scaling", "strategy", "." ]
bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0
https://github.com/randomhost/image/blob/bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0/src/php/Image.php#L185-L242
train
randomhost/image
src/php/Image.php
Image.mergeAlpha
public function mergeAlpha( Image $srcImage, $dstX, $dstY, $alpha = 127 ) { if (!is_resource($this->image) || !is_resource($srcImage->image)) { throw new \RuntimeException( 'Attempt to merge image data using an invalid image resource.' ); } $percent = 100 - min(max(round(($alpha / 127 * 100)), 1), 100); // copy images around @imagecopymerge( $this->image, $srcImage->image, (int)$dstX, (int)$dstY, 0, 0, $srcImage->width, $srcImage->height, $percent ); return $this; }
php
public function mergeAlpha( Image $srcImage, $dstX, $dstY, $alpha = 127 ) { if (!is_resource($this->image) || !is_resource($srcImage->image)) { throw new \RuntimeException( 'Attempt to merge image data using an invalid image resource.' ); } $percent = 100 - min(max(round(($alpha / 127 * 100)), 1), 100); // copy images around @imagecopymerge( $this->image, $srcImage->image, (int)$dstX, (int)$dstY, 0, 0, $srcImage->width, $srcImage->height, $percent ); return $this; }
[ "public", "function", "mergeAlpha", "(", "Image", "$", "srcImage", ",", "$", "dstX", ",", "$", "dstY", ",", "$", "alpha", "=", "127", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "image", ")", "||", "!", "is_resource", "(", "$", "srcImage", "->", "image", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Attempt to merge image data using an invalid image resource.'", ")", ";", "}", "$", "percent", "=", "100", "-", "min", "(", "max", "(", "round", "(", "(", "$", "alpha", "/", "127", "*", "100", ")", ")", ",", "1", ")", ",", "100", ")", ";", "// copy images around", "@", "imagecopymerge", "(", "$", "this", "->", "image", ",", "$", "srcImage", "->", "image", ",", "(", "int", ")", "$", "dstX", ",", "(", "int", ")", "$", "dstY", ",", "0", ",", "0", ",", "$", "srcImage", "->", "width", ",", "$", "srcImage", "->", "height", ",", "$", "percent", ")", ";", "return", "$", "this", ";", "}" ]
Copies the given Image image stream into the image stream of the active instance while applying the given alpha transparency. This method does not support scaling. @param Image $srcImage The source image. @param int $dstX x-coordinate of destination point. @param int $dstY y-coordinate of destination point. @param int $alpha Alpha value (0-127) @return $this @throws \RuntimeException Thrown if $this->image or $srcImage->image is not a valid image resource.
[ "Copies", "the", "given", "Image", "image", "stream", "into", "the", "image", "stream", "of", "the", "active", "instance", "while", "applying", "the", "given", "alpha", "transparency", "." ]
bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0
https://github.com/randomhost/image/blob/bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0/src/php/Image.php#L260-L288
train
randomhost/image
src/php/Image.php
Image.render
public function render() { if (!is_resource($this->image)) { throw new \RuntimeException( 'Attempt to render invalid resource as image.' ); } header('Content-type: image/png'); imagepng($this->image, null, 9, PNG_ALL_FILTERS); return $this; }
php
public function render() { if (!is_resource($this->image)) { throw new \RuntimeException( 'Attempt to render invalid resource as image.' ); } header('Content-type: image/png'); imagepng($this->image, null, 9, PNG_ALL_FILTERS); return $this; }
[ "public", "function", "render", "(", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "image", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Attempt to render invalid resource as image.'", ")", ";", "}", "header", "(", "'Content-type: image/png'", ")", ";", "imagepng", "(", "$", "this", "->", "image", ",", "null", ",", "9", ",", "PNG_ALL_FILTERS", ")", ";", "return", "$", "this", ";", "}" ]
Outputs the image stream to the browser. @return $this @throws \RuntimeException Thrown if $this->image is not a valid image resource.
[ "Outputs", "the", "image", "stream", "to", "the", "browser", "." ]
bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0
https://github.com/randomhost/image/blob/bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0/src/php/Image.php#L298-L310
train
randomhost/image
src/php/Image.php
Image.setCacheDir
protected function setCacheDir($path) { if (!is_dir($path)) { throw new \InvalidArgumentException( sprintf( 'Cache directory at %s could not be found', $path ) ); } if (!is_readable($path)) { throw new \InvalidArgumentException( sprintf( 'Cache directory at %s is not readable', $path ) ); } if (!is_writable($path)) { throw new \InvalidArgumentException( sprintf( 'Cache directory at %s is not writable', $path ) ); } $this->cacheDir = realpath($path); }
php
protected function setCacheDir($path) { if (!is_dir($path)) { throw new \InvalidArgumentException( sprintf( 'Cache directory at %s could not be found', $path ) ); } if (!is_readable($path)) { throw new \InvalidArgumentException( sprintf( 'Cache directory at %s is not readable', $path ) ); } if (!is_writable($path)) { throw new \InvalidArgumentException( sprintf( 'Cache directory at %s is not writable', $path ) ); } $this->cacheDir = realpath($path); }
[ "protected", "function", "setCacheDir", "(", "$", "path", ")", "{", "if", "(", "!", "is_dir", "(", "$", "path", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Cache directory at %s could not be found'", ",", "$", "path", ")", ")", ";", "}", "if", "(", "!", "is_readable", "(", "$", "path", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Cache directory at %s is not readable'", ",", "$", "path", ")", ")", ";", "}", "if", "(", "!", "is_writable", "(", "$", "path", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Cache directory at %s is not writable'", ",", "$", "path", ")", ")", ";", "}", "$", "this", "->", "cacheDir", "=", "realpath", "(", "$", "path", ")", ";", "}" ]
Sets the path to the cache directory. @param string $path Path to cache directory @return void @throws \InvalidArgumentException
[ "Sets", "the", "path", "to", "the", "cache", "directory", "." ]
bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0
https://github.com/randomhost/image/blob/bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0/src/php/Image.php#L360-L388
train
randomhost/image
src/php/Image.php
Image.isCached
protected function isCached() { $cacheTime = self::CACHE_TIME * 60; if (!is_file($this->pathCache)) { return false; } $cachedTime = filemtime($this->pathCache); $cacheAge = $this->time - $cachedTime; return $cacheAge < $cacheTime; }
php
protected function isCached() { $cacheTime = self::CACHE_TIME * 60; if (!is_file($this->pathCache)) { return false; } $cachedTime = filemtime($this->pathCache); $cacheAge = $this->time - $cachedTime; return $cacheAge < $cacheTime; }
[ "protected", "function", "isCached", "(", ")", "{", "$", "cacheTime", "=", "self", "::", "CACHE_TIME", "*", "60", ";", "if", "(", "!", "is_file", "(", "$", "this", "->", "pathCache", ")", ")", "{", "return", "false", ";", "}", "$", "cachedTime", "=", "filemtime", "(", "$", "this", "->", "pathCache", ")", ";", "$", "cacheAge", "=", "$", "this", "->", "time", "-", "$", "cachedTime", ";", "return", "$", "cacheAge", "<", "$", "cacheTime", ";", "}" ]
Checks if the image file exists in the cache. @return bool
[ "Checks", "if", "the", "image", "file", "exists", "in", "the", "cache", "." ]
bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0
https://github.com/randomhost/image/blob/bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0/src/php/Image.php#L407-L419
train
randomhost/image
src/php/Image.php
Image.readImage
protected function readImage() { // set default path $path = $this->pathFile; // handle caching if (!empty($this->pathCache)) { // write / refresh cache file if necessary if (!$this->isCached()) { $this->writeCache(); } // replace path if file is cached if ($this->isCached()) { $path = $this->pathCache; } } // get image information $read = @getimagesize($path); if (false === $read) { throw new \RuntimeException( sprintf( "Couldn't read image at %s", $path ) ); } // detect image type switch ($read[2]) { case IMAGETYPE_GIF: $this->image = @imagecreatefromgif($path); break; case IMAGETYPE_JPEG: $this->image = @imagecreatefromjpeg($path); break; case IMAGETYPE_PNG: $this->image = @imagecreatefrompng($path); break; default: // image type not supported throw new \UnexpectedValueException( sprintf( 'Image type %s not supported', image_type_to_mime_type($read[2]) ) ); } if (false === $this->image) { throw new \RuntimeException( sprintf( "Couldn't read image at %s", $path ) ); } // set image dimensions $this->width = $read[0]; $this->height = $read[1]; // set mime type $this->mimeType = $read['mime']; // set modified date $this->modified = @filemtime($path); }
php
protected function readImage() { // set default path $path = $this->pathFile; // handle caching if (!empty($this->pathCache)) { // write / refresh cache file if necessary if (!$this->isCached()) { $this->writeCache(); } // replace path if file is cached if ($this->isCached()) { $path = $this->pathCache; } } // get image information $read = @getimagesize($path); if (false === $read) { throw new \RuntimeException( sprintf( "Couldn't read image at %s", $path ) ); } // detect image type switch ($read[2]) { case IMAGETYPE_GIF: $this->image = @imagecreatefromgif($path); break; case IMAGETYPE_JPEG: $this->image = @imagecreatefromjpeg($path); break; case IMAGETYPE_PNG: $this->image = @imagecreatefrompng($path); break; default: // image type not supported throw new \UnexpectedValueException( sprintf( 'Image type %s not supported', image_type_to_mime_type($read[2]) ) ); } if (false === $this->image) { throw new \RuntimeException( sprintf( "Couldn't read image at %s", $path ) ); } // set image dimensions $this->width = $read[0]; $this->height = $read[1]; // set mime type $this->mimeType = $read['mime']; // set modified date $this->modified = @filemtime($path); }
[ "protected", "function", "readImage", "(", ")", "{", "// set default path", "$", "path", "=", "$", "this", "->", "pathFile", ";", "// handle caching", "if", "(", "!", "empty", "(", "$", "this", "->", "pathCache", ")", ")", "{", "// write / refresh cache file if necessary", "if", "(", "!", "$", "this", "->", "isCached", "(", ")", ")", "{", "$", "this", "->", "writeCache", "(", ")", ";", "}", "// replace path if file is cached", "if", "(", "$", "this", "->", "isCached", "(", ")", ")", "{", "$", "path", "=", "$", "this", "->", "pathCache", ";", "}", "}", "// get image information", "$", "read", "=", "@", "getimagesize", "(", "$", "path", ")", ";", "if", "(", "false", "===", "$", "read", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "\"Couldn't read image at %s\"", ",", "$", "path", ")", ")", ";", "}", "// detect image type", "switch", "(", "$", "read", "[", "2", "]", ")", "{", "case", "IMAGETYPE_GIF", ":", "$", "this", "->", "image", "=", "@", "imagecreatefromgif", "(", "$", "path", ")", ";", "break", ";", "case", "IMAGETYPE_JPEG", ":", "$", "this", "->", "image", "=", "@", "imagecreatefromjpeg", "(", "$", "path", ")", ";", "break", ";", "case", "IMAGETYPE_PNG", ":", "$", "this", "->", "image", "=", "@", "imagecreatefrompng", "(", "$", "path", ")", ";", "break", ";", "default", ":", "// image type not supported", "throw", "new", "\\", "UnexpectedValueException", "(", "sprintf", "(", "'Image type %s not supported'", ",", "image_type_to_mime_type", "(", "$", "read", "[", "2", "]", ")", ")", ")", ";", "}", "if", "(", "false", "===", "$", "this", "->", "image", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "\"Couldn't read image at %s\"", ",", "$", "path", ")", ")", ";", "}", "// set image dimensions", "$", "this", "->", "width", "=", "$", "read", "[", "0", "]", ";", "$", "this", "->", "height", "=", "$", "read", "[", "1", "]", ";", "// set mime type", "$", "this", "->", "mimeType", "=", "$", "read", "[", "'mime'", "]", ";", "// set modified date", "$", "this", "->", "modified", "=", "@", "filemtime", "(", "$", "path", ")", ";", "}" ]
Reads the image file. @return void @throws \RuntimeException Thrown if the image could not be processed. @throws \UnexpectedValueException Thrown if the image type is not supported.
[ "Reads", "the", "image", "file", "." ]
bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0
https://github.com/randomhost/image/blob/bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0/src/php/Image.php#L491-L563
train
randomhost/image
src/php/Image.php
Image.createImage
protected function createImage() { // create image $this->image = @imagecreatetruecolor($this->width, $this->height); // set mime type $this->mimeType = 'image/png'; // set modified date $this->modified = time(); }
php
protected function createImage() { // create image $this->image = @imagecreatetruecolor($this->width, $this->height); // set mime type $this->mimeType = 'image/png'; // set modified date $this->modified = time(); }
[ "protected", "function", "createImage", "(", ")", "{", "// create image", "$", "this", "->", "image", "=", "@", "imagecreatetruecolor", "(", "$", "this", "->", "width", ",", "$", "this", "->", "height", ")", ";", "// set mime type", "$", "this", "->", "mimeType", "=", "'image/png'", ";", "// set modified date", "$", "this", "->", "modified", "=", "time", "(", ")", ";", "}" ]
Creates a new true color image. @return void
[ "Creates", "a", "new", "true", "color", "image", "." ]
bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0
https://github.com/randomhost/image/blob/bd669ba6b50fd2bbbe50c4ef06235b111a8a30b0/src/php/Image.php#L570-L580
train
agentmedia/phine-builtin
src/BuiltIn/Modules/Frontend/Repeater.php
Repeater.Init
protected function Init() { $this->repeater = ContentRepeater::Schema()->ByContent($this->content); $this->current = $this->tree->FirstChildOf($this->item); $this->isEmpty = !$this->current; return parent::Init(); }
php
protected function Init() { $this->repeater = ContentRepeater::Schema()->ByContent($this->content); $this->current = $this->tree->FirstChildOf($this->item); $this->isEmpty = !$this->current; return parent::Init(); }
[ "protected", "function", "Init", "(", ")", "{", "$", "this", "->", "repeater", "=", "ContentRepeater", "::", "Schema", "(", ")", "->", "ByContent", "(", "$", "this", "->", "content", ")", ";", "$", "this", "->", "current", "=", "$", "this", "->", "tree", "->", "FirstChildOf", "(", "$", "this", "->", "item", ")", ";", "$", "this", "->", "isEmpty", "=", "!", "$", "this", "->", "current", ";", "return", "parent", "::", "Init", "(", ")", ";", "}" ]
Initializes the repeater frontend module @return boolean Returns tru
[ "Initializes", "the", "repeater", "frontend", "module" ]
4dd05bc406a71e997bd4eaa16b12e23dbe62a456
https://github.com/agentmedia/phine-builtin/blob/4dd05bc406a71e997bd4eaa16b12e23dbe62a456/src/BuiltIn/Modules/Frontend/Repeater.php#L50-L56
train
agentmedia/phine-builtin
src/BuiltIn/Modules/Frontend/Repeater.php
Repeater.NextChild
protected function NextChild() { $item = $this->current; $this->current = $this->tree->NextOf($item); return $item; }
php
protected function NextChild() { $item = $this->current; $this->current = $this->tree->NextOf($item); return $item; }
[ "protected", "function", "NextChild", "(", ")", "{", "$", "item", "=", "$", "this", "->", "current", ";", "$", "this", "->", "current", "=", "$", "this", "->", "tree", "->", "NextOf", "(", "$", "item", ")", ";", "return", "$", "item", ";", "}" ]
Gets the next child @return mixed Returns the next tree item
[ "Gets", "the", "next", "child" ]
4dd05bc406a71e997bd4eaa16b12e23dbe62a456
https://github.com/agentmedia/phine-builtin/blob/4dd05bc406a71e997bd4eaa16b12e23dbe62a456/src/BuiltIn/Modules/Frontend/Repeater.php#L62-L67
train
t-kanstantsin/fileupload
src/config/Factory.php
Factory.prepareAliases
public static function prepareAliases(array $defaultAliasConfig, array $aliasArray): array { $factory = new static($defaultAliasConfig); foreach ($aliasArray as $name => $config) { $name = (string) $name; $aliasArray[$name] = $factory->createAlias($name, $config); } return $aliasArray; }
php
public static function prepareAliases(array $defaultAliasConfig, array $aliasArray): array { $factory = new static($defaultAliasConfig); foreach ($aliasArray as $name => $config) { $name = (string) $name; $aliasArray[$name] = $factory->createAlias($name, $config); } return $aliasArray; }
[ "public", "static", "function", "prepareAliases", "(", "array", "$", "defaultAliasConfig", ",", "array", "$", "aliasArray", ")", ":", "array", "{", "$", "factory", "=", "new", "static", "(", "$", "defaultAliasConfig", ")", ";", "foreach", "(", "$", "aliasArray", "as", "$", "name", "=>", "$", "config", ")", "{", "$", "name", "=", "(", "string", ")", "$", "name", ";", "$", "aliasArray", "[", "$", "name", "]", "=", "$", "factory", "->", "createAlias", "(", "$", "name", ",", "$", "config", ")", ";", "}", "return", "$", "aliasArray", ";", "}" ]
Prepares aliases config in proper view. @param array $defaultAliasConfig @param array $aliasArray @return array @throws InvalidConfigException
[ "Prepares", "aliases", "config", "in", "proper", "view", "." ]
d6317a9b9b36d992f09affe3900ef7d7ddfd855f
https://github.com/t-kanstantsin/fileupload/blob/d6317a9b9b36d992f09affe3900ef7d7ddfd855f/src/config/Factory.php#L29-L38
train
pluf/tenant
src/Tenant/SPA/Manager/Remote.php
Tenant_SPA_Manager_Remote.install
public static function install($request, $object) { $spa = Tenant_SpaService::installFromRepository($object->id); return Tenant_Shortcuts_SpaManager($spa)->apply($spa, 'create'); }
php
public static function install($request, $object) { $spa = Tenant_SpaService::installFromRepository($object->id); return Tenant_Shortcuts_SpaManager($spa)->apply($spa, 'create'); }
[ "public", "static", "function", "install", "(", "$", "request", ",", "$", "object", ")", "{", "$", "spa", "=", "Tenant_SpaService", "::", "installFromRepository", "(", "$", "object", "->", "id", ")", ";", "return", "Tenant_Shortcuts_SpaManager", "(", "$", "spa", ")", "->", "apply", "(", "$", "spa", ",", "'create'", ")", ";", "}" ]
Install an spa @param Pluf_HTTP_Request $request @param Tenant_SPA $object
[ "Install", "an", "spa" ]
a06359c52b9a257b5a0a186264e8770acfc54b73
https://github.com/pluf/tenant/blob/a06359c52b9a257b5a0a186264e8770acfc54b73/src/Tenant/SPA/Manager/Remote.php#L101-L105
train
drdplusinfo/drdplus-codes
DrdPlus/Codes/Partials/AbstractCode.php
AbstractCode.getPossibleValues
public static function getPossibleValues(): array { if ((static::$possibleValues[static::class] ?? null) === null) { static::$possibleValues[static::class] = []; try { $reflectionClass = new \ReflectionClass(static::class); } catch (\ReflectionException $reflectionException) { throw new Exceptions\CanNotDeterminePossibleValuesFromClassReflection($reflectionException->getMessage()); } foreach ($reflectionClass->getReflectionConstants() as $reflectionConstant) { if ($reflectionConstant->isPublic()) { static::$possibleValues[static::class][] = $reflectionConstant->getValue(); } } } return static::$possibleValues[static::class]; }
php
public static function getPossibleValues(): array { if ((static::$possibleValues[static::class] ?? null) === null) { static::$possibleValues[static::class] = []; try { $reflectionClass = new \ReflectionClass(static::class); } catch (\ReflectionException $reflectionException) { throw new Exceptions\CanNotDeterminePossibleValuesFromClassReflection($reflectionException->getMessage()); } foreach ($reflectionClass->getReflectionConstants() as $reflectionConstant) { if ($reflectionConstant->isPublic()) { static::$possibleValues[static::class][] = $reflectionConstant->getValue(); } } } return static::$possibleValues[static::class]; }
[ "public", "static", "function", "getPossibleValues", "(", ")", ":", "array", "{", "if", "(", "(", "static", "::", "$", "possibleValues", "[", "static", "::", "class", "]", "??", "null", ")", "===", "null", ")", "{", "static", "::", "$", "possibleValues", "[", "static", "::", "class", "]", "=", "[", "]", ";", "try", "{", "$", "reflectionClass", "=", "new", "\\", "ReflectionClass", "(", "static", "::", "class", ")", ";", "}", "catch", "(", "\\", "ReflectionException", "$", "reflectionException", ")", "{", "throw", "new", "Exceptions", "\\", "CanNotDeterminePossibleValuesFromClassReflection", "(", "$", "reflectionException", "->", "getMessage", "(", ")", ")", ";", "}", "foreach", "(", "$", "reflectionClass", "->", "getReflectionConstants", "(", ")", "as", "$", "reflectionConstant", ")", "{", "if", "(", "$", "reflectionConstant", "->", "isPublic", "(", ")", ")", "{", "static", "::", "$", "possibleValues", "[", "static", "::", "class", "]", "[", "]", "=", "$", "reflectionConstant", "->", "getValue", "(", ")", ";", "}", "}", "}", "return", "static", "::", "$", "possibleValues", "[", "static", "::", "class", "]", ";", "}" ]
Overload this by basic array with listed constants. Taking them via Reflection is not the fastest way. @return array|string[]
[ "Overload", "this", "by", "basic", "array", "with", "listed", "constants", ".", "Taking", "them", "via", "Reflection", "is", "not", "the", "fastest", "way", "." ]
b84db134f789e924f18ba471cf8e709a063e1807
https://github.com/drdplusinfo/drdplus-codes/blob/b84db134f789e924f18ba471cf8e709a063e1807/DrdPlus/Codes/Partials/AbstractCode.php#L23-L40
train
kdaviesnz/Molecule
src/FactoryClient.php
FactoryClient.getMolecule
public function getMolecule(string $canonicalSMILE) { $this->operations = new Operations(); $atoms = array(); // Recursive. $atoms is passed by reference. $this->operations->addBranches($canonicalSMILE, $atoms); $this->operations->addLoopBonds($atoms); $this->operations->atomsToCanonicalSMILE($atoms); $factoryType = ""; // Logic to determine what type of factory eg AlkeneFactory, AmineFactory, MoleculeFactory if (strpos($canonicalSMILE, "C=C")!==false) { $factoryType = "AlkeneFactory"; } switch($factoryType) { case "AlkeneFactory": $factory = new AlkeneFactory($atoms); break; default: $factory = new MoleculeFactory($atoms); break; } $molecule = $factory->getMolecule(); return $molecule; }
php
public function getMolecule(string $canonicalSMILE) { $this->operations = new Operations(); $atoms = array(); // Recursive. $atoms is passed by reference. $this->operations->addBranches($canonicalSMILE, $atoms); $this->operations->addLoopBonds($atoms); $this->operations->atomsToCanonicalSMILE($atoms); $factoryType = ""; // Logic to determine what type of factory eg AlkeneFactory, AmineFactory, MoleculeFactory if (strpos($canonicalSMILE, "C=C")!==false) { $factoryType = "AlkeneFactory"; } switch($factoryType) { case "AlkeneFactory": $factory = new AlkeneFactory($atoms); break; default: $factory = new MoleculeFactory($atoms); break; } $molecule = $factory->getMolecule(); return $molecule; }
[ "public", "function", "getMolecule", "(", "string", "$", "canonicalSMILE", ")", "{", "$", "this", "->", "operations", "=", "new", "Operations", "(", ")", ";", "$", "atoms", "=", "array", "(", ")", ";", "// Recursive. $atoms is passed by reference.", "$", "this", "->", "operations", "->", "addBranches", "(", "$", "canonicalSMILE", ",", "$", "atoms", ")", ";", "$", "this", "->", "operations", "->", "addLoopBonds", "(", "$", "atoms", ")", ";", "$", "this", "->", "operations", "->", "atomsToCanonicalSMILE", "(", "$", "atoms", ")", ";", "$", "factoryType", "=", "\"\"", ";", "// Logic to determine what type of factory eg AlkeneFactory, AmineFactory, MoleculeFactory", "if", "(", "strpos", "(", "$", "canonicalSMILE", ",", "\"C=C\"", ")", "!==", "false", ")", "{", "$", "factoryType", "=", "\"AlkeneFactory\"", ";", "}", "switch", "(", "$", "factoryType", ")", "{", "case", "\"AlkeneFactory\"", ":", "$", "factory", "=", "new", "AlkeneFactory", "(", "$", "atoms", ")", ";", "break", ";", "default", ":", "$", "factory", "=", "new", "MoleculeFactory", "(", "$", "atoms", ")", ";", "break", ";", "}", "$", "molecule", "=", "$", "factory", "->", "getMolecule", "(", ")", ";", "return", "$", "molecule", ";", "}" ]
FactoryClient constructor.
[ "FactoryClient", "constructor", "." ]
1e6897fb6c0c0012f4706f67ab2b644b7a7b1e8b
https://github.com/kdaviesnz/Molecule/blob/1e6897fb6c0c0012f4706f67ab2b644b7a7b1e8b/src/FactoryClient.php#L20-L52
train
PieterScheffers/arrr
src/Ar.php
Ar.sortBy
public static function sortBy($array, $sortByKeys, $sorters, $orders = []) { if( is_string($sortByKeys) ) { $sortByKeys = explode('.', $sortByKeys); } $sortByKeys = array_values((array)$sortByKeys); $sorters = array_values((array)$sorters); uasort($array, function($a, $b) use ($sortByKeys, $sorters, $orders) { $return = 0; foreach( $sortByKeys as $key => $sortBy ) { // call callback or get attribute if( is_callable($sortBy) ) { $aSort = call_user_func($sortBy, $a); $bSort = call_user_func($sortBy, $b); } else { $aSort = u\def($a, $sortBy); $bSort = u\def($b, $sortBy); } $method = isset($sorters[$key]) ? $sorters[$key] : $sorters[ ( count($sorters) - 1 ) ]; // make sure Sort class from pisc\arrr namespace is used if( is_string($method) && substr($method, 0, 4) === 'Sort' ) $method = __NAMESPACE__ .'\\' . $method; $order = u\def($orders, $key, 'desc'); // call compare function $return = call_user_func($method, $aSort, $bSort); // reverse return value if( $order !== 'desc' ) { $return *= -1; } // return if the items compared are not the same if( $return !== 0 ) { return $return; } } return 0; }); return $array; }
php
public static function sortBy($array, $sortByKeys, $sorters, $orders = []) { if( is_string($sortByKeys) ) { $sortByKeys = explode('.', $sortByKeys); } $sortByKeys = array_values((array)$sortByKeys); $sorters = array_values((array)$sorters); uasort($array, function($a, $b) use ($sortByKeys, $sorters, $orders) { $return = 0; foreach( $sortByKeys as $key => $sortBy ) { // call callback or get attribute if( is_callable($sortBy) ) { $aSort = call_user_func($sortBy, $a); $bSort = call_user_func($sortBy, $b); } else { $aSort = u\def($a, $sortBy); $bSort = u\def($b, $sortBy); } $method = isset($sorters[$key]) ? $sorters[$key] : $sorters[ ( count($sorters) - 1 ) ]; // make sure Sort class from pisc\arrr namespace is used if( is_string($method) && substr($method, 0, 4) === 'Sort' ) $method = __NAMESPACE__ .'\\' . $method; $order = u\def($orders, $key, 'desc'); // call compare function $return = call_user_func($method, $aSort, $bSort); // reverse return value if( $order !== 'desc' ) { $return *= -1; } // return if the items compared are not the same if( $return !== 0 ) { return $return; } } return 0; }); return $array; }
[ "public", "static", "function", "sortBy", "(", "$", "array", ",", "$", "sortByKeys", ",", "$", "sorters", ",", "$", "orders", "=", "[", "]", ")", "{", "if", "(", "is_string", "(", "$", "sortByKeys", ")", ")", "{", "$", "sortByKeys", "=", "explode", "(", "'.'", ",", "$", "sortByKeys", ")", ";", "}", "$", "sortByKeys", "=", "array_values", "(", "(", "array", ")", "$", "sortByKeys", ")", ";", "$", "sorters", "=", "array_values", "(", "(", "array", ")", "$", "sorters", ")", ";", "uasort", "(", "$", "array", ",", "function", "(", "$", "a", ",", "$", "b", ")", "use", "(", "$", "sortByKeys", ",", "$", "sorters", ",", "$", "orders", ")", "{", "$", "return", "=", "0", ";", "foreach", "(", "$", "sortByKeys", "as", "$", "key", "=>", "$", "sortBy", ")", "{", "// call callback or get attribute", "if", "(", "is_callable", "(", "$", "sortBy", ")", ")", "{", "$", "aSort", "=", "call_user_func", "(", "$", "sortBy", ",", "$", "a", ")", ";", "$", "bSort", "=", "call_user_func", "(", "$", "sortBy", ",", "$", "b", ")", ";", "}", "else", "{", "$", "aSort", "=", "u", "\\", "def", "(", "$", "a", ",", "$", "sortBy", ")", ";", "$", "bSort", "=", "u", "\\", "def", "(", "$", "b", ",", "$", "sortBy", ")", ";", "}", "$", "method", "=", "isset", "(", "$", "sorters", "[", "$", "key", "]", ")", "?", "$", "sorters", "[", "$", "key", "]", ":", "$", "sorters", "[", "(", "count", "(", "$", "sorters", ")", "-", "1", ")", "]", ";", "// make sure Sort class from pisc\\arrr namespace is used", "if", "(", "is_string", "(", "$", "method", ")", "&&", "substr", "(", "$", "method", ",", "0", ",", "4", ")", "===", "'Sort'", ")", "$", "method", "=", "__NAMESPACE__", ".", "'\\\\'", ".", "$", "method", ";", "$", "order", "=", "u", "\\", "def", "(", "$", "orders", ",", "$", "key", ",", "'desc'", ")", ";", "// call compare function", "$", "return", "=", "call_user_func", "(", "$", "method", ",", "$", "aSort", ",", "$", "bSort", ")", ";", "// reverse return value", "if", "(", "$", "order", "!==", "'desc'", ")", "{", "$", "return", "*=", "-", "1", ";", "}", "// return if the items compared are not the same", "if", "(", "$", "return", "!==", "0", ")", "{", "return", "$", "return", ";", "}", "}", "return", "0", ";", "}", ")", ";", "return", "$", "array", ";", "}" ]
Sort by multiple keys Usages: String of attributes Ar::sortBy($array, 'created_at.firstName', [ 'Sort::byDateTime', 'Sort::byString' ], [ 'asc', 'desc' ]); Array Ar::sortBy($array, [ 'created_at', function($i) { return strtolower($i->firstName); } ], [ 'Sort::byDateTime', 'Sort::byString' ], [ 'asc', 'desc' ]) @param array $array Array of values @param string/array $sortBy String with dots seperating keys or array of keys/functions @param array/callable $sorters Array of compare sorters or one method @param array $orders Array of order (desc/asc) @return array Sorted array
[ "Sort", "by", "multiple", "keys" ]
f920d911ae32641248131f1a510da287929cbd6e
https://github.com/PieterScheffers/arrr/blob/f920d911ae32641248131f1a510da287929cbd6e/src/Ar.php#L202-L257
train
PieterScheffers/arrr
src/Ar.php
Ar.groupBy
public static function groupBy($array, $groupBy = "id") { return static::reduce($array, function($arr, $item) use($groupBy) { // get value of attribute if( is_closure($groupBy) ) { // execute closure $value = $groupBy($item); } else { // get attribute of object $value = pisc\upperscore\def($item, $groupBy); } // build new array with value as keys if( isset($arr[$value]) ) { $arr[$value][] = $item; } else { $arr[$value] = [ $item ]; } return $arr; }, []); }
php
public static function groupBy($array, $groupBy = "id") { return static::reduce($array, function($arr, $item) use($groupBy) { // get value of attribute if( is_closure($groupBy) ) { // execute closure $value = $groupBy($item); } else { // get attribute of object $value = pisc\upperscore\def($item, $groupBy); } // build new array with value as keys if( isset($arr[$value]) ) { $arr[$value][] = $item; } else { $arr[$value] = [ $item ]; } return $arr; }, []); }
[ "public", "static", "function", "groupBy", "(", "$", "array", ",", "$", "groupBy", "=", "\"id\"", ")", "{", "return", "static", "::", "reduce", "(", "$", "array", ",", "function", "(", "$", "arr", ",", "$", "item", ")", "use", "(", "$", "groupBy", ")", "{", "// get value of attribute", "if", "(", "is_closure", "(", "$", "groupBy", ")", ")", "{", "// execute closure", "$", "value", "=", "$", "groupBy", "(", "$", "item", ")", ";", "}", "else", "{", "// get attribute of object", "$", "value", "=", "pisc", "\\", "upperscore", "\\", "def", "(", "$", "item", ",", "$", "groupBy", ")", ";", "}", "// build new array with value as keys", "if", "(", "isset", "(", "$", "arr", "[", "$", "value", "]", ")", ")", "{", "$", "arr", "[", "$", "value", "]", "[", "]", "=", "$", "item", ";", "}", "else", "{", "$", "arr", "[", "$", "value", "]", "=", "[", "$", "item", "]", ";", "}", "return", "$", "arr", ";", "}", ",", "[", "]", ")", ";", "}" ]
Group an array of objects by an attribute of an object or the result of a closure @param array $array Array of objects @param string/closure $groupBy Attribute of object or a closure. Closure gets object as parameter and should return a value that can be a key of the array @return array Array of arrays
[ "Group", "an", "array", "of", "objects", "by", "an", "attribute", "of", "an", "object", "or", "the", "result", "of", "a", "closure" ]
f920d911ae32641248131f1a510da287929cbd6e
https://github.com/PieterScheffers/arrr/blob/f920d911ae32641248131f1a510da287929cbd6e/src/Ar.php#L363-L392
train
PieterScheffers/arrr
src/Ar.php
Ar.type
public static function type($array) { $last_key = -1; $type = 'index'; foreach( $array as $key => $val ) { if( !is_int( $key ) || $key < 0 ) { return 'assoc'; } if( $type !== 'sparse' ) { if( $key !== $last_key + 1 ){ $type = 'sparse'; } $last_key = $key; } } return $type; }
php
public static function type($array) { $last_key = -1; $type = 'index'; foreach( $array as $key => $val ) { if( !is_int( $key ) || $key < 0 ) { return 'assoc'; } if( $type !== 'sparse' ) { if( $key !== $last_key + 1 ){ $type = 'sparse'; } $last_key = $key; } } return $type; }
[ "public", "static", "function", "type", "(", "$", "array", ")", "{", "$", "last_key", "=", "-", "1", ";", "$", "type", "=", "'index'", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "!", "is_int", "(", "$", "key", ")", "||", "$", "key", "<", "0", ")", "{", "return", "'assoc'", ";", "}", "if", "(", "$", "type", "!==", "'sparse'", ")", "{", "if", "(", "$", "key", "!==", "$", "last_key", "+", "1", ")", "{", "$", "type", "=", "'sparse'", ";", "}", "$", "last_key", "=", "$", "key", ";", "}", "}", "return", "$", "type", ";", "}" ]
Find whether the array is indexed or an associative array If it is indexed, find if its sparse or not @return string type of array (index, assoc, sparse)
[ "Find", "whether", "the", "array", "is", "indexed", "or", "an", "associative", "array", "If", "it", "is", "indexed", "find", "if", "its", "sparse", "or", "not" ]
f920d911ae32641248131f1a510da287929cbd6e
https://github.com/PieterScheffers/arrr/blob/f920d911ae32641248131f1a510da287929cbd6e/src/Ar.php#L400-L422
train
Vectrex/vxPHP
src/Session/NativeSessionStorage.php
NativeSessionStorage.start
public function start() { if(!$this->started) { // only non-CLI environments are supposed to provide sessions if(PHP_SAPI !== 'cli') { // avoid starting an already started session if ( (PHP_VERSION_ID >= 50400 && session_status() === PHP_SESSION_ACTIVE) || (PHP_VERSION_ID < 50400 && session_id()) ) { throw new \RuntimeException('Failed to start the session: Session already started.'); } // allow session only when no headers have been sent if (headers_sent($file, $line)) { throw new \RuntimeException(sprintf("Cannot start session. Headers have already been sent by file '%s' at line %d.", $file, $line)); } if(!session_start()) { throw new \RuntimeException('Session start failed.'); } } $this->loadSession(); } }
php
public function start() { if(!$this->started) { // only non-CLI environments are supposed to provide sessions if(PHP_SAPI !== 'cli') { // avoid starting an already started session if ( (PHP_VERSION_ID >= 50400 && session_status() === PHP_SESSION_ACTIVE) || (PHP_VERSION_ID < 50400 && session_id()) ) { throw new \RuntimeException('Failed to start the session: Session already started.'); } // allow session only when no headers have been sent if (headers_sent($file, $line)) { throw new \RuntimeException(sprintf("Cannot start session. Headers have already been sent by file '%s' at line %d.", $file, $line)); } if(!session_start()) { throw new \RuntimeException('Session start failed.'); } } $this->loadSession(); } }
[ "public", "function", "start", "(", ")", "{", "if", "(", "!", "$", "this", "->", "started", ")", "{", "// only non-CLI environments are supposed to provide sessions", "if", "(", "PHP_SAPI", "!==", "'cli'", ")", "{", "// avoid starting an already started session", "if", "(", "(", "PHP_VERSION_ID", ">=", "50400", "&&", "session_status", "(", ")", "===", "PHP_SESSION_ACTIVE", ")", "||", "(", "PHP_VERSION_ID", "<", "50400", "&&", "session_id", "(", ")", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Failed to start the session: Session already started.'", ")", ";", "}", "// allow session only when no headers have been sent", "if", "(", "headers_sent", "(", "$", "file", ",", "$", "line", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "\"Cannot start session. Headers have already been sent by file '%s' at line %d.\"", ",", "$", "file", ",", "$", "line", ")", ")", ";", "}", "if", "(", "!", "session_start", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Session start failed.'", ")", ";", "}", "}", "$", "this", "->", "loadSession", "(", ")", ";", "}", "}" ]
start session and load session data into SessionDataBag @throws \RuntimeException
[ "start", "session", "and", "load", "session", "data", "into", "SessionDataBag" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Session/NativeSessionStorage.php#L66-L97
train
Vectrex/vxPHP
src/Session/NativeSessionStorage.php
NativeSessionStorage.setSaveHandler
private function setSaveHandler() { if (PHP_VERSION_ID >= 50400) { $this->storageEngine = new NativeSessionWrapper(); if(!session_set_save_handler($this->storageEngine, FALSE)) { throw new \RuntimeException('Could not set session save handler.'); } } }
php
private function setSaveHandler() { if (PHP_VERSION_ID >= 50400) { $this->storageEngine = new NativeSessionWrapper(); if(!session_set_save_handler($this->storageEngine, FALSE)) { throw new \RuntimeException('Could not set session save handler.'); } } }
[ "private", "function", "setSaveHandler", "(", ")", "{", "if", "(", "PHP_VERSION_ID", ">=", "50400", ")", "{", "$", "this", "->", "storageEngine", "=", "new", "NativeSessionWrapper", "(", ")", ";", "if", "(", "!", "session_set_save_handler", "(", "$", "this", "->", "storageEngine", ",", "FALSE", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Could not set session save handler.'", ")", ";", "}", "}", "}" ]
set custom save handler for PHP 5.4+ @throws \RuntimeException
[ "set", "custom", "save", "handler", "for", "PHP", "5", ".", "4", "+" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Session/NativeSessionStorage.php#L119-L131
train
jenskooij/cloudcontrol
src/storage/storage/RedirectsStorage.php
RedirectsStorage.getRedirects
public function getRedirects() { $redirects = $this->repository->redirects; if ($redirects === null) { $redirects = array(); } usort($redirects, array($this, 'cmp')); return $redirects; }
php
public function getRedirects() { $redirects = $this->repository->redirects; if ($redirects === null) { $redirects = array(); } usort($redirects, array($this, 'cmp')); return $redirects; }
[ "public", "function", "getRedirects", "(", ")", "{", "$", "redirects", "=", "$", "this", "->", "repository", "->", "redirects", ";", "if", "(", "$", "redirects", "===", "null", ")", "{", "$", "redirects", "=", "array", "(", ")", ";", "}", "usort", "(", "$", "redirects", ",", "array", "(", "$", "this", ",", "'cmp'", ")", ")", ";", "return", "$", "redirects", ";", "}" ]
Get all redirects @return mixed
[ "Get", "all", "redirects" ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/storage/storage/RedirectsStorage.php#L18-L26
train
jenskooij/cloudcontrol
src/storage/storage/RedirectsStorage.php
RedirectsStorage.addRedirect
public function addRedirect($postValues) { $redirectObject = RedirectsFactory::createRedirectFromPostValues($postValues); $redirects = $this->repository->redirects; $redirects[] = $redirectObject; $this->repository->redirects = $redirects; $this->save(); }
php
public function addRedirect($postValues) { $redirectObject = RedirectsFactory::createRedirectFromPostValues($postValues); $redirects = $this->repository->redirects; $redirects[] = $redirectObject; $this->repository->redirects = $redirects; $this->save(); }
[ "public", "function", "addRedirect", "(", "$", "postValues", ")", "{", "$", "redirectObject", "=", "RedirectsFactory", "::", "createRedirectFromPostValues", "(", "$", "postValues", ")", ";", "$", "redirects", "=", "$", "this", "->", "repository", "->", "redirects", ";", "$", "redirects", "[", "]", "=", "$", "redirectObject", ";", "$", "this", "->", "repository", "->", "redirects", "=", "$", "redirects", ";", "$", "this", "->", "save", "(", ")", ";", "}" ]
Add a new redirect @param $postValues
[ "Add", "a", "new", "redirect" ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/storage/storage/RedirectsStorage.php#L32-L39
train
jenskooij/cloudcontrol
src/storage/storage/RedirectsStorage.php
RedirectsStorage.getRedirectBySlug
public function getRedirectBySlug($slug) { $redirects = $this->repository->redirects; foreach ($redirects as $redirect) { if ($redirect->slug == $slug) { return $redirect; } } return null; }
php
public function getRedirectBySlug($slug) { $redirects = $this->repository->redirects; foreach ($redirects as $redirect) { if ($redirect->slug == $slug) { return $redirect; } } return null; }
[ "public", "function", "getRedirectBySlug", "(", "$", "slug", ")", "{", "$", "redirects", "=", "$", "this", "->", "repository", "->", "redirects", ";", "foreach", "(", "$", "redirects", "as", "$", "redirect", ")", "{", "if", "(", "$", "redirect", "->", "slug", "==", "$", "slug", ")", "{", "return", "$", "redirect", ";", "}", "}", "return", "null", ";", "}" ]
Get a redirect by it's slug @param $slug @return \stdClass|null
[ "Get", "a", "redirect", "by", "it", "s", "slug" ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/storage/storage/RedirectsStorage.php#L47-L57
train
jenskooij/cloudcontrol
src/storage/storage/RedirectsStorage.php
RedirectsStorage.saveRedirect
public function saveRedirect($slug, $postValues) { $redirectObject = RedirectsFactory::createRedirectFromPostValues($postValues); $redirects = $this->repository->redirects; foreach ($redirects as $key => $redirect) { if ($redirect->slug == $slug) { $redirects[$key] = $redirectObject; } } $this->repository->redirects = $redirects; $this->save(); }
php
public function saveRedirect($slug, $postValues) { $redirectObject = RedirectsFactory::createRedirectFromPostValues($postValues); $redirects = $this->repository->redirects; foreach ($redirects as $key => $redirect) { if ($redirect->slug == $slug) { $redirects[$key] = $redirectObject; } } $this->repository->redirects = $redirects; $this->save(); }
[ "public", "function", "saveRedirect", "(", "$", "slug", ",", "$", "postValues", ")", "{", "$", "redirectObject", "=", "RedirectsFactory", "::", "createRedirectFromPostValues", "(", "$", "postValues", ")", ";", "$", "redirects", "=", "$", "this", "->", "repository", "->", "redirects", ";", "foreach", "(", "$", "redirects", "as", "$", "key", "=>", "$", "redirect", ")", "{", "if", "(", "$", "redirect", "->", "slug", "==", "$", "slug", ")", "{", "$", "redirects", "[", "$", "key", "]", "=", "$", "redirectObject", ";", "}", "}", "$", "this", "->", "repository", "->", "redirects", "=", "$", "redirects", ";", "$", "this", "->", "save", "(", ")", ";", "}" ]
Save a redirect by it's slug @param $slug @param $postValues
[ "Save", "a", "redirect", "by", "it", "s", "slug" ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/storage/storage/RedirectsStorage.php#L64-L76
train
jenskooij/cloudcontrol
src/storage/storage/RedirectsStorage.php
RedirectsStorage.deleteRedirectBySlug
public function deleteRedirectBySlug($slug) { $redirects = $this->repository->redirects; foreach ($redirects as $key => $redirect) { if ($redirect->slug == $slug) { unset($redirects[$key]); } } $redirects = array_values($redirects); $this->repository->redirects = $redirects; $this->save(); }
php
public function deleteRedirectBySlug($slug) { $redirects = $this->repository->redirects; foreach ($redirects as $key => $redirect) { if ($redirect->slug == $slug) { unset($redirects[$key]); } } $redirects = array_values($redirects); $this->repository->redirects = $redirects; $this->save(); }
[ "public", "function", "deleteRedirectBySlug", "(", "$", "slug", ")", "{", "$", "redirects", "=", "$", "this", "->", "repository", "->", "redirects", ";", "foreach", "(", "$", "redirects", "as", "$", "key", "=>", "$", "redirect", ")", "{", "if", "(", "$", "redirect", "->", "slug", "==", "$", "slug", ")", "{", "unset", "(", "$", "redirects", "[", "$", "key", "]", ")", ";", "}", "}", "$", "redirects", "=", "array_values", "(", "$", "redirects", ")", ";", "$", "this", "->", "repository", "->", "redirects", "=", "$", "redirects", ";", "$", "this", "->", "save", "(", ")", ";", "}" ]
Delete a redirect by it's slug @param $slug
[ "Delete", "a", "redirect", "by", "it", "s", "slug" ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/storage/storage/RedirectsStorage.php#L82-L93
train
Linkvalue-Interne/MajoraOAuthServerBundle
src/Majora/Bundle/OAuthServerBundle/DependencyInjection/Configuration.php
Configuration.createTokenNode
private function createTokenNode($tokenName, $defaultClass, $tokenInterface, $defaultTtl) { $builder = new TreeBuilder(); $node = $builder->root($tokenName); $node ->addDefaultsIfNotSet() ->children() ->integerNode('ttl') ->defaultValue($defaultTtl) ->end() ->scalarNode('class') ->cannotBeEmpty() ->defaultValue($defaultClass) ->validate() ->ifTrue(function ($accessTokenClass) use ($tokenInterface) { return !( class_exists($accessTokenClass, true) && (new \ReflectionClass($accessTokenClass)) ->implementsInterface($tokenInterface) ); }) ->thenInvalid(sprintf( 'Provided access_token configuration has to be a valid class which implements %s.', $tokenInterface )) ->end() ->end() ->append($this->createDriverStrategyNode('loader')) ->append($this->createDriverStrategyNode('repository')) ->end() ; return $node; }
php
private function createTokenNode($tokenName, $defaultClass, $tokenInterface, $defaultTtl) { $builder = new TreeBuilder(); $node = $builder->root($tokenName); $node ->addDefaultsIfNotSet() ->children() ->integerNode('ttl') ->defaultValue($defaultTtl) ->end() ->scalarNode('class') ->cannotBeEmpty() ->defaultValue($defaultClass) ->validate() ->ifTrue(function ($accessTokenClass) use ($tokenInterface) { return !( class_exists($accessTokenClass, true) && (new \ReflectionClass($accessTokenClass)) ->implementsInterface($tokenInterface) ); }) ->thenInvalid(sprintf( 'Provided access_token configuration has to be a valid class which implements %s.', $tokenInterface )) ->end() ->end() ->append($this->createDriverStrategyNode('loader')) ->append($this->createDriverStrategyNode('repository')) ->end() ; return $node; }
[ "private", "function", "createTokenNode", "(", "$", "tokenName", ",", "$", "defaultClass", ",", "$", "tokenInterface", ",", "$", "defaultTtl", ")", "{", "$", "builder", "=", "new", "TreeBuilder", "(", ")", ";", "$", "node", "=", "$", "builder", "->", "root", "(", "$", "tokenName", ")", ";", "$", "node", "->", "addDefaultsIfNotSet", "(", ")", "->", "children", "(", ")", "->", "integerNode", "(", "'ttl'", ")", "->", "defaultValue", "(", "$", "defaultTtl", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'class'", ")", "->", "cannotBeEmpty", "(", ")", "->", "defaultValue", "(", "$", "defaultClass", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "accessTokenClass", ")", "use", "(", "$", "tokenInterface", ")", "{", "return", "!", "(", "class_exists", "(", "$", "accessTokenClass", ",", "true", ")", "&&", "(", "new", "\\", "ReflectionClass", "(", "$", "accessTokenClass", ")", ")", "->", "implementsInterface", "(", "$", "tokenInterface", ")", ")", ";", "}", ")", "->", "thenInvalid", "(", "sprintf", "(", "'Provided access_token configuration has to be a valid class which implements %s.'", ",", "$", "tokenInterface", ")", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "append", "(", "$", "this", "->", "createDriverStrategyNode", "(", "'loader'", ")", ")", "->", "append", "(", "$", "this", "->", "createDriverStrategyNode", "(", "'repository'", ")", ")", "->", "end", "(", ")", ";", "return", "$", "node", ";", "}" ]
Create a token configuration node. @param string $tokenName @param string $defaultClass @param string $tokenInterface @param string $defaultTtl @return Node
[ "Create", "a", "token", "configuration", "node", "." ]
3e84e2494c947d1bd5d5c16221a3b9e343ebff92
https://github.com/Linkvalue-Interne/MajoraOAuthServerBundle/blob/3e84e2494c947d1bd5d5c16221a3b9e343ebff92/src/Majora/Bundle/OAuthServerBundle/DependencyInjection/Configuration.php#L73-L106
train
Gundars/HogLog
extra/PlanB.php
PlanB.isInsideJailDir
protected static function isInsideJailDir($path) { $jailDir = __DIR__ . '/' . self::$jailDir; return strpos(realpath($path), realpath($jailDir)) !== false; }
php
protected static function isInsideJailDir($path) { $jailDir = __DIR__ . '/' . self::$jailDir; return strpos(realpath($path), realpath($jailDir)) !== false; }
[ "protected", "static", "function", "isInsideJailDir", "(", "$", "path", ")", "{", "$", "jailDir", "=", "__DIR__", ".", "'/'", ".", "self", "::", "$", "jailDir", ";", "return", "strpos", "(", "realpath", "(", "$", "path", ")", ",", "realpath", "(", "$", "jailDir", ")", ")", "!==", "false", ";", "}" ]
Compare users selected path with jaildir path @param string $path @return bool
[ "Compare", "users", "selected", "path", "with", "jaildir", "path" ]
3349f6db3dd3c1f7d334d5e2e44a0f241c76f8a3
https://github.com/Gundars/HogLog/blob/3349f6db3dd3c1f7d334d5e2e44a0f241c76f8a3/extra/PlanB.php#L86-L90
train
Gundars/HogLog
extra/PlanB.php
PlanB.isWhitelisted
protected static function isWhitelisted($file) { if (!is_array(self::$whitelist) || count(self::$whitelist) === 0) { return true; } foreach (self::$whitelist as $fileName) { if (strpos($file, $fileName)) { return true; } } return false; }
php
protected static function isWhitelisted($file) { if (!is_array(self::$whitelist) || count(self::$whitelist) === 0) { return true; } foreach (self::$whitelist as $fileName) { if (strpos($file, $fileName)) { return true; } } return false; }
[ "protected", "static", "function", "isWhitelisted", "(", "$", "file", ")", "{", "if", "(", "!", "is_array", "(", "self", "::", "$", "whitelist", ")", "||", "count", "(", "self", "::", "$", "whitelist", ")", "===", "0", ")", "{", "return", "true", ";", "}", "foreach", "(", "self", "::", "$", "whitelist", "as", "$", "fileName", ")", "{", "if", "(", "strpos", "(", "$", "file", ",", "$", "fileName", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Compare users selected filename against whitelist @param string $file filename + extension @return bool
[ "Compare", "users", "selected", "filename", "against", "whitelist" ]
3349f6db3dd3c1f7d334d5e2e44a0f241c76f8a3
https://github.com/Gundars/HogLog/blob/3349f6db3dd3c1f7d334d5e2e44a0f241c76f8a3/extra/PlanB.php#L97-L108
train
Gundars/HogLog
extra/PlanB.php
PlanB.parseUrl
protected static function parseUrl($url) { $url = isset($url) ? $url : "//$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $url = parse_url($url); $url['browse'] = './'; if (array_key_exists('browse', self::$requestMethod) && !empty(self::$requestMethod['browse']) ) { $url['browse'] = self::$requestMethod['browse']; } return $url; }
php
protected static function parseUrl($url) { $url = isset($url) ? $url : "//$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $url = parse_url($url); $url['browse'] = './'; if (array_key_exists('browse', self::$requestMethod) && !empty(self::$requestMethod['browse']) ) { $url['browse'] = self::$requestMethod['browse']; } return $url; }
[ "protected", "static", "function", "parseUrl", "(", "$", "url", ")", "{", "$", "url", "=", "isset", "(", "$", "url", ")", "?", "$", "url", ":", "\"//$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]\"", ";", "$", "url", "=", "parse_url", "(", "$", "url", ")", ";", "$", "url", "[", "'browse'", "]", "=", "'./'", ";", "if", "(", "array_key_exists", "(", "'browse'", ",", "self", "::", "$", "requestMethod", ")", "&&", "!", "empty", "(", "self", "::", "$", "requestMethod", "[", "'browse'", "]", ")", ")", "{", "$", "url", "[", "'browse'", "]", "=", "self", "::", "$", "requestMethod", "[", "'browse'", "]", ";", "}", "return", "$", "url", ";", "}" ]
Pare URL into array @param $url string URL to parse, protocol is optional @return array $url ["host" => "www.example.com", "path" => "/path", "query" => "name=value", "browse" => "../app/storage/logs/"]
[ "Pare", "URL", "into", "array" ]
3349f6db3dd3c1f7d334d5e2e44a0f241c76f8a3
https://github.com/Gundars/HogLog/blob/3349f6db3dd3c1f7d334d5e2e44a0f241c76f8a3/extra/PlanB.php#L175-L186
train
wearenolte/wp-endpoints-static
src/StaticApi/Menus.php
Menus.get_all_locations
public static function get_all_locations() { $menus = []; $locations = get_nav_menu_locations(); foreach ( $locations as $location => $menu_id ) { $menus[ $location ] = []; $menu_items = wp_get_nav_menu_items( $menu_id ); $menu_items = is_array( $menu_items ) ? $menu_items : []; foreach ( $menu_items as $menu_item ) { if ( ! $menu_item->menu_item_parent ) { $items = [ 'title' => $menu_item->title, 'link' => str_replace( site_url(), '', $menu_item->url ), 'items' => self::get_sub_menu_items( $menu_items, $menu_item->ID ), ]; $menus[ $location ][] = apply_filters( "menu_$location", $items ); } } } return $menus; }
php
public static function get_all_locations() { $menus = []; $locations = get_nav_menu_locations(); foreach ( $locations as $location => $menu_id ) { $menus[ $location ] = []; $menu_items = wp_get_nav_menu_items( $menu_id ); $menu_items = is_array( $menu_items ) ? $menu_items : []; foreach ( $menu_items as $menu_item ) { if ( ! $menu_item->menu_item_parent ) { $items = [ 'title' => $menu_item->title, 'link' => str_replace( site_url(), '', $menu_item->url ), 'items' => self::get_sub_menu_items( $menu_items, $menu_item->ID ), ]; $menus[ $location ][] = apply_filters( "menu_$location", $items ); } } } return $menus; }
[ "public", "static", "function", "get_all_locations", "(", ")", "{", "$", "menus", "=", "[", "]", ";", "$", "locations", "=", "get_nav_menu_locations", "(", ")", ";", "foreach", "(", "$", "locations", "as", "$", "location", "=>", "$", "menu_id", ")", "{", "$", "menus", "[", "$", "location", "]", "=", "[", "]", ";", "$", "menu_items", "=", "wp_get_nav_menu_items", "(", "$", "menu_id", ")", ";", "$", "menu_items", "=", "is_array", "(", "$", "menu_items", ")", "?", "$", "menu_items", ":", "[", "]", ";", "foreach", "(", "$", "menu_items", "as", "$", "menu_item", ")", "{", "if", "(", "!", "$", "menu_item", "->", "menu_item_parent", ")", "{", "$", "items", "=", "[", "'title'", "=>", "$", "menu_item", "->", "title", ",", "'link'", "=>", "str_replace", "(", "site_url", "(", ")", ",", "''", ",", "$", "menu_item", "->", "url", ")", ",", "'items'", "=>", "self", "::", "get_sub_menu_items", "(", "$", "menu_items", ",", "$", "menu_item", "->", "ID", ")", ",", "]", ";", "$", "menus", "[", "$", "location", "]", "[", "]", "=", "apply_filters", "(", "\"menu_$location\"", ",", "$", "items", ")", ";", "}", "}", "}", "return", "$", "menus", ";", "}" ]
Returns an array of menu locations, with the assigned menu in each. @return array
[ "Returns", "an", "array", "of", "menu", "locations", "with", "the", "assigned", "menu", "in", "each", "." ]
23258bba9b65d55b78b3dc3edc123d75009b0825
https://github.com/wearenolte/wp-endpoints-static/blob/23258bba9b65d55b78b3dc3edc123d75009b0825/src/StaticApi/Menus.php#L14-L38
train
Xiphe/THEDEBUG
src/Xiphe/THEDEBUG.php
THEDEBUG.getFirePHP
public static function getFirePHP($options = null) { if (!isset(self::$_FirePHP) || !empty($options)) { if (!class_exists('\FirePHP')) { throw new THEDEBUGException("FirePHP not available"); } /* Start output buffer so we can debug after headers would be sent regular */ if (!isset(self::$_FirePHP)) { ob_start(); } if (!empty($options)) { \FB::setOptions($options); } self::$_FirePHP = \FirePHP::getInstance(true); } return self::$_FirePHP; }
php
public static function getFirePHP($options = null) { if (!isset(self::$_FirePHP) || !empty($options)) { if (!class_exists('\FirePHP')) { throw new THEDEBUGException("FirePHP not available"); } /* Start output buffer so we can debug after headers would be sent regular */ if (!isset(self::$_FirePHP)) { ob_start(); } if (!empty($options)) { \FB::setOptions($options); } self::$_FirePHP = \FirePHP::getInstance(true); } return self::$_FirePHP; }
[ "public", "static", "function", "getFirePHP", "(", "$", "options", "=", "null", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "_FirePHP", ")", "||", "!", "empty", "(", "$", "options", ")", ")", "{", "if", "(", "!", "class_exists", "(", "'\\FirePHP'", ")", ")", "{", "throw", "new", "THEDEBUGException", "(", "\"FirePHP not available\"", ")", ";", "}", "/* Start output buffer so we can debug after headers would be sent regular */", "if", "(", "!", "isset", "(", "self", "::", "$", "_FirePHP", ")", ")", "{", "ob_start", "(", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "options", ")", ")", "{", "\\", "FB", "::", "setOptions", "(", "$", "options", ")", ";", "}", "self", "::", "$", "_FirePHP", "=", "\\", "FirePHP", "::", "getInstance", "(", "true", ")", ";", "}", "return", "self", "::", "$", "_FirePHP", ";", "}" ]
Retrieve an instance of FirePHP @param array $options optional global options. @return FirePHP
[ "Retrieve", "an", "instance", "of", "FirePHP" ]
76983738a781cc495241672d57e7650aee57a2db
https://github.com/Xiphe/THEDEBUG/blob/76983738a781cc495241672d57e7650aee57a2db/src/Xiphe/THEDEBUG.php#L160-L179
train
Xiphe/THEDEBUG
src/Xiphe/THEDEBUG.php
THEDEBUG.getChromePHP
public static function getChromePHP() { if (!isset(self::$_ChromePHP)) { self::$_ChromePHP = X\THEDEBUG\ChromePhp::getInstance(); } return self::$_ChromePHP; }
php
public static function getChromePHP() { if (!isset(self::$_ChromePHP)) { self::$_ChromePHP = X\THEDEBUG\ChromePhp::getInstance(); } return self::$_ChromePHP; }
[ "public", "static", "function", "getChromePHP", "(", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "_ChromePHP", ")", ")", "{", "self", "::", "$", "_ChromePHP", "=", "X", "\\", "THEDEBUG", "\\", "ChromePhp", "::", "getInstance", "(", ")", ";", "}", "return", "self", "::", "$", "_ChromePHP", ";", "}" ]
Retrieve an instance of ChromePHP @return Xiphe\THEDEBUG\ChromePHP
[ "Retrieve", "an", "instance", "of", "ChromePHP" ]
76983738a781cc495241672d57e7650aee57a2db
https://github.com/Xiphe/THEDEBUG/blob/76983738a781cc495241672d57e7650aee57a2db/src/Xiphe/THEDEBUG.php#L186-L193
train
Xiphe/THEDEBUG
src/Xiphe/THEDEBUG.php
THEDEBUG.debug
public static function debug($variable) { if (!self::$_enabled) { return; } if (self::$ensureByGet && !isset($_GET['debug'])) { return; } $debug = new THEDEBUG\ADEBUG(func_get_args()); $debug->put(); return $variable; }
php
public static function debug($variable) { if (!self::$_enabled) { return; } if (self::$ensureByGet && !isset($_GET['debug'])) { return; } $debug = new THEDEBUG\ADEBUG(func_get_args()); $debug->put(); return $variable; }
[ "public", "static", "function", "debug", "(", "$", "variable", ")", "{", "if", "(", "!", "self", "::", "$", "_enabled", ")", "{", "return", ";", "}", "if", "(", "self", "::", "$", "ensureByGet", "&&", "!", "isset", "(", "$", "_GET", "[", "'debug'", "]", ")", ")", "{", "return", ";", "}", "$", "debug", "=", "new", "THEDEBUG", "\\", "ADEBUG", "(", "func_get_args", "(", ")", ")", ";", "$", "debug", "->", "put", "(", ")", ";", "return", "$", "variable", ";", "}" ]
Create an ADEBUG object and put it. @param mixed $variable the variable you want to debug. @param mixed optional string for name/message, integer for type or array containing options @param mixed optional same as above @param integer backTraceOffset @return mixed return the passed variable for later usage.
[ "Create", "an", "ADEBUG", "object", "and", "put", "it", "." ]
76983738a781cc495241672d57e7650aee57a2db
https://github.com/Xiphe/THEDEBUG/blob/76983738a781cc495241672d57e7650aee57a2db/src/Xiphe/THEDEBUG.php#L216-L230
train
Xiphe/THEDEBUG
src/Xiphe/THEDEBUG.php
THEDEBUG.diebug
public static function diebug() { if (!self::$_enabled) { return; } if (self::$ensureByGet && !isset($_GET['debug'])) { return; } $args = func_get_args(); $debug = new THEDEBUG\ADEBUG($args); /* don't debug if no arguments were passed */ if (!empty($args)) { $debug->put(); } /* Add a message so diebug can be called without arguments and still be found in the code */ $debug->variable = 'Script got murdered by diebug.'; $debug->variableType = 'string'; $debug->name = ''; $debug->type = 'Info'; $debug->put(); /* DIE! */ die(); }
php
public static function diebug() { if (!self::$_enabled) { return; } if (self::$ensureByGet && !isset($_GET['debug'])) { return; } $args = func_get_args(); $debug = new THEDEBUG\ADEBUG($args); /* don't debug if no arguments were passed */ if (!empty($args)) { $debug->put(); } /* Add a message so diebug can be called without arguments and still be found in the code */ $debug->variable = 'Script got murdered by diebug.'; $debug->variableType = 'string'; $debug->name = ''; $debug->type = 'Info'; $debug->put(); /* DIE! */ die(); }
[ "public", "static", "function", "diebug", "(", ")", "{", "if", "(", "!", "self", "::", "$", "_enabled", ")", "{", "return", ";", "}", "if", "(", "self", "::", "$", "ensureByGet", "&&", "!", "isset", "(", "$", "_GET", "[", "'debug'", "]", ")", ")", "{", "return", ";", "}", "$", "args", "=", "func_get_args", "(", ")", ";", "$", "debug", "=", "new", "THEDEBUG", "\\", "ADEBUG", "(", "$", "args", ")", ";", "/* don't debug if no arguments were passed */", "if", "(", "!", "empty", "(", "$", "args", ")", ")", "{", "$", "debug", "->", "put", "(", ")", ";", "}", "/* Add a message so diebug can be called without arguments and still be found in the code */", "$", "debug", "->", "variable", "=", "'Script got murdered by diebug.'", ";", "$", "debug", "->", "variableType", "=", "'string'", ";", "$", "debug", "->", "name", "=", "''", ";", "$", "debug", "->", "type", "=", "'Info'", ";", "$", "debug", "->", "put", "(", ")", ";", "/* DIE! */", "die", "(", ")", ";", "}" ]
The "Killer", debug the passed variable die! @param mixed $variable optional the variable you want to debug. @param mixed optional string for name/message, integer for type or array containing options @param mixed optional same as above @param integer backTraceOffset @return void
[ "The", "Killer", "debug", "the", "passed", "variable", "die!" ]
76983738a781cc495241672d57e7650aee57a2db
https://github.com/Xiphe/THEDEBUG/blob/76983738a781cc495241672d57e7650aee57a2db/src/Xiphe/THEDEBUG.php#L242-L270
train
Xiphe/THEDEBUG
src/Xiphe/THEDEBUG.php
THEDEBUG.getDebugObject
public static function getDebugObject($variable) { if (!self::$_enabled) { return; } if (self::$ensureByGet && !isset($_GET['debug'])) { return; } return new THEDEBUG\ADEBUG(func_get_args()); }
php
public static function getDebugObject($variable) { if (!self::$_enabled) { return; } if (self::$ensureByGet && !isset($_GET['debug'])) { return; } return new THEDEBUG\ADEBUG(func_get_args()); }
[ "public", "static", "function", "getDebugObject", "(", "$", "variable", ")", "{", "if", "(", "!", "self", "::", "$", "_enabled", ")", "{", "return", ";", "}", "if", "(", "self", "::", "$", "ensureByGet", "&&", "!", "isset", "(", "$", "_GET", "[", "'debug'", "]", ")", ")", "{", "return", ";", "}", "return", "new", "THEDEBUG", "\\", "ADEBUG", "(", "func_get_args", "(", ")", ")", ";", "}" ]
Just return the ADEBUG instance for later usage. @param mixed $variable @param mixed optional string for name/message, integer for type or array containing options @param mixed optional same as above @param integer backTraceOffset @return ADEBUG
[ "Just", "return", "the", "ADEBUG", "instance", "for", "later", "usage", "." ]
76983738a781cc495241672d57e7650aee57a2db
https://github.com/Xiphe/THEDEBUG/blob/76983738a781cc495241672d57e7650aee57a2db/src/Xiphe/THEDEBUG.php#L282-L293
train
Xiphe/THEDEBUG
src/Xiphe/THEDEBUG.php
THEDEBUG.deprecate
public static function deprecate($alternative = '', $continue = true) { if (!self::$_enabled) { return; } if (self::$ensureByGet && !isset($_GET['debug'])) { return; } $debug = new THEDEBUG\ADEBUG(); /* Get the deprecated method/function name */ $scope = $debug->getScope(); /* You can not deprecate the global namespace */ if ($scope->type === 'global') { return; } /* Write a nice message */ $message = sprintf( 'Deprecated usage of %s "%s".', $scope->type, $scope->name ); /* Add alternative hint if given */ if (!empty($alternative)) { $message .= sprintf( ' Please consider using "%s" instead.', $alternative ); } /* Manipulate the offset so the debug will point to the deprecated method call */ $debug->backTraceOffset++; $debug->setLineAndFile(); /* Set the message, type and put */ $debug->variable = $message; $debug->type = 'warning'; $debug->variableType = 'string'; $debug->put(); if ($debug->modus === 'FirePHP') { self::$_FirePHP->trace(''); } /* Die if continue is false */ if (!$continue) { die(); } }
php
public static function deprecate($alternative = '', $continue = true) { if (!self::$_enabled) { return; } if (self::$ensureByGet && !isset($_GET['debug'])) { return; } $debug = new THEDEBUG\ADEBUG(); /* Get the deprecated method/function name */ $scope = $debug->getScope(); /* You can not deprecate the global namespace */ if ($scope->type === 'global') { return; } /* Write a nice message */ $message = sprintf( 'Deprecated usage of %s "%s".', $scope->type, $scope->name ); /* Add alternative hint if given */ if (!empty($alternative)) { $message .= sprintf( ' Please consider using "%s" instead.', $alternative ); } /* Manipulate the offset so the debug will point to the deprecated method call */ $debug->backTraceOffset++; $debug->setLineAndFile(); /* Set the message, type and put */ $debug->variable = $message; $debug->type = 'warning'; $debug->variableType = 'string'; $debug->put(); if ($debug->modus === 'FirePHP') { self::$_FirePHP->trace(''); } /* Die if continue is false */ if (!$continue) { die(); } }
[ "public", "static", "function", "deprecate", "(", "$", "alternative", "=", "''", ",", "$", "continue", "=", "true", ")", "{", "if", "(", "!", "self", "::", "$", "_enabled", ")", "{", "return", ";", "}", "if", "(", "self", "::", "$", "ensureByGet", "&&", "!", "isset", "(", "$", "_GET", "[", "'debug'", "]", ")", ")", "{", "return", ";", "}", "$", "debug", "=", "new", "THEDEBUG", "\\", "ADEBUG", "(", ")", ";", "/* Get the deprecated method/function name */", "$", "scope", "=", "$", "debug", "->", "getScope", "(", ")", ";", "/* You can not deprecate the global namespace */", "if", "(", "$", "scope", "->", "type", "===", "'global'", ")", "{", "return", ";", "}", "/* Write a nice message */", "$", "message", "=", "sprintf", "(", "'Deprecated usage of %s \"%s\".'", ",", "$", "scope", "->", "type", ",", "$", "scope", "->", "name", ")", ";", "/* Add alternative hint if given */", "if", "(", "!", "empty", "(", "$", "alternative", ")", ")", "{", "$", "message", ".=", "sprintf", "(", "' Please consider using \"%s\" instead.'", ",", "$", "alternative", ")", ";", "}", "/* Manipulate the offset so the debug will point to the deprecated method call */", "$", "debug", "->", "backTraceOffset", "++", ";", "$", "debug", "->", "setLineAndFile", "(", ")", ";", "/* Set the message, type and put */", "$", "debug", "->", "variable", "=", "$", "message", ";", "$", "debug", "->", "type", "=", "'warning'", ";", "$", "debug", "->", "variableType", "=", "'string'", ";", "$", "debug", "->", "put", "(", ")", ";", "if", "(", "$", "debug", "->", "modus", "===", "'FirePHP'", ")", "{", "self", "::", "$", "_FirePHP", "->", "trace", "(", "''", ")", ";", "}", "/* Die if continue is false */", "if", "(", "!", "$", "continue", ")", "{", "die", "(", ")", ";", "}", "}" ]
Flag a function as deprecated by placing this method inside it. @param string $alternative an alternative function that should be used instead. @param boolean $continue true to die @return void
[ "Flag", "a", "function", "as", "deprecated", "by", "placing", "this", "method", "inside", "it", "." ]
76983738a781cc495241672d57e7650aee57a2db
https://github.com/Xiphe/THEDEBUG/blob/76983738a781cc495241672d57e7650aee57a2db/src/Xiphe/THEDEBUG.php#L303-L356
train
Xiphe/THEDEBUG
src/Xiphe/THEDEBUG.php
THEDEBUG.count
public static function count($message = '') { if (!self::$_enabled) { return; } if (self::$ensureByGet && !isset($_GET['debug'])) { return; } /* Get a new ADEBUG object */ $debug = new THEDEBUG\ADEBUG(array(1)); /* And its ID (calculated using file and line) */ $ID = $debug->getID(); /* * just increment the counter and return if this is * not the first time called from this file and line, */ if (isset(self::$counts[$ID])) { unset($debug); self::$counts[$ID]->variable++; return; } /* Register output on destruction */ $debug->putOnDestruction = true; /* Generate the message or insert the passed one */ if (empty($message)) { $debug->name = sprintf( 'File %s, Line %s was visited', $debug->file, $debug->line ); } else { $debug->name = $message; } /* Register callback to add time/s to the counter */ $debug->addCallback('beforePut', function (&$debug) { if ($debug->variable === 1) { $debug->variable .= ' time.'; } else { $debug->variable .= ' times.'; } }); /* Add the debug to the collection of counts */ self::$counts[$ID] = $debug; }
php
public static function count($message = '') { if (!self::$_enabled) { return; } if (self::$ensureByGet && !isset($_GET['debug'])) { return; } /* Get a new ADEBUG object */ $debug = new THEDEBUG\ADEBUG(array(1)); /* And its ID (calculated using file and line) */ $ID = $debug->getID(); /* * just increment the counter and return if this is * not the first time called from this file and line, */ if (isset(self::$counts[$ID])) { unset($debug); self::$counts[$ID]->variable++; return; } /* Register output on destruction */ $debug->putOnDestruction = true; /* Generate the message or insert the passed one */ if (empty($message)) { $debug->name = sprintf( 'File %s, Line %s was visited', $debug->file, $debug->line ); } else { $debug->name = $message; } /* Register callback to add time/s to the counter */ $debug->addCallback('beforePut', function (&$debug) { if ($debug->variable === 1) { $debug->variable .= ' time.'; } else { $debug->variable .= ' times.'; } }); /* Add the debug to the collection of counts */ self::$counts[$ID] = $debug; }
[ "public", "static", "function", "count", "(", "$", "message", "=", "''", ")", "{", "if", "(", "!", "self", "::", "$", "_enabled", ")", "{", "return", ";", "}", "if", "(", "self", "::", "$", "ensureByGet", "&&", "!", "isset", "(", "$", "_GET", "[", "'debug'", "]", ")", ")", "{", "return", ";", "}", "/* Get a new ADEBUG object */", "$", "debug", "=", "new", "THEDEBUG", "\\", "ADEBUG", "(", "array", "(", "1", ")", ")", ";", "/* And its ID (calculated using file and line) */", "$", "ID", "=", "$", "debug", "->", "getID", "(", ")", ";", "/*\n\t\t * just increment the counter and return if this is\t\t\n\t\t * not the first time called from this file and line,\n\t\t */", "if", "(", "isset", "(", "self", "::", "$", "counts", "[", "$", "ID", "]", ")", ")", "{", "unset", "(", "$", "debug", ")", ";", "self", "::", "$", "counts", "[", "$", "ID", "]", "->", "variable", "++", ";", "return", ";", "}", "/* Register output on destruction */", "$", "debug", "->", "putOnDestruction", "=", "true", ";", "/* Generate the message or insert the passed one */", "if", "(", "empty", "(", "$", "message", ")", ")", "{", "$", "debug", "->", "name", "=", "sprintf", "(", "'File %s, Line %s was visited'", ",", "$", "debug", "->", "file", ",", "$", "debug", "->", "line", ")", ";", "}", "else", "{", "$", "debug", "->", "name", "=", "$", "message", ";", "}", "/* Register callback to add time/s to the counter */", "$", "debug", "->", "addCallback", "(", "'beforePut'", ",", "function", "(", "&", "$", "debug", ")", "{", "if", "(", "$", "debug", "->", "variable", "===", "1", ")", "{", "$", "debug", "->", "variable", ".=", "' time.'", ";", "}", "else", "{", "$", "debug", "->", "variable", ".=", "' times.'", ";", "}", "}", ")", ";", "/* Add the debug to the collection of counts */", "self", "::", "$", "counts", "[", "$", "ID", "]", "=", "$", "debug", ";", "}" ]
Count how often this line is visited and put the debug at the end of the script. @param string $message optional message @return void
[ "Count", "how", "often", "this", "line", "is", "visited", "and", "put", "the", "debug", "at", "the", "end", "of", "the", "script", "." ]
76983738a781cc495241672d57e7650aee57a2db
https://github.com/Xiphe/THEDEBUG/blob/76983738a781cc495241672d57e7650aee57a2db/src/Xiphe/THEDEBUG.php#L365-L415
train
Wedeto/HTTP
src/FileUpload.php
FileUpload.traverse
private static function traverse($name, $type, $tmp_name, $error, $size, Dictionary $dict, $path) { if (is_array($name)) { $keys = array_keys($name); foreach ($keys as $key) { $new_path = $path; $new_path[] = $key; if ( !array_key_exists($key, $name) || !array_key_exists($key, $type) || !array_key_exists($key, $error) || !array_key_exists($key, $tmp_name) || !array_key_exists($key, $size) ) { throw new FileUploadException("Missing information for file upload " . implode(".", $new_path)); } self::traverse($name[$key], $type[$key], $tmp_name[$key], $error[$key], $size[$key], $dict, $new_path); } } else { $file = new FileUpload($path, $name, $type, $tmp_name, $error, $size); $path[] = $file; $dict->set($path, null); $dict->set('_files', $file->getFieldName(), $file); } }
php
private static function traverse($name, $type, $tmp_name, $error, $size, Dictionary $dict, $path) { if (is_array($name)) { $keys = array_keys($name); foreach ($keys as $key) { $new_path = $path; $new_path[] = $key; if ( !array_key_exists($key, $name) || !array_key_exists($key, $type) || !array_key_exists($key, $error) || !array_key_exists($key, $tmp_name) || !array_key_exists($key, $size) ) { throw new FileUploadException("Missing information for file upload " . implode(".", $new_path)); } self::traverse($name[$key], $type[$key], $tmp_name[$key], $error[$key], $size[$key], $dict, $new_path); } } else { $file = new FileUpload($path, $name, $type, $tmp_name, $error, $size); $path[] = $file; $dict->set($path, null); $dict->set('_files', $file->getFieldName(), $file); } }
[ "private", "static", "function", "traverse", "(", "$", "name", ",", "$", "type", ",", "$", "tmp_name", ",", "$", "error", ",", "$", "size", ",", "Dictionary", "$", "dict", ",", "$", "path", ")", "{", "if", "(", "is_array", "(", "$", "name", ")", ")", "{", "$", "keys", "=", "array_keys", "(", "$", "name", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "new_path", "=", "$", "path", ";", "$", "new_path", "[", "]", "=", "$", "key", ";", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "name", ")", "||", "!", "array_key_exists", "(", "$", "key", ",", "$", "type", ")", "||", "!", "array_key_exists", "(", "$", "key", ",", "$", "error", ")", "||", "!", "array_key_exists", "(", "$", "key", ",", "$", "tmp_name", ")", "||", "!", "array_key_exists", "(", "$", "key", ",", "$", "size", ")", ")", "{", "throw", "new", "FileUploadException", "(", "\"Missing information for file upload \"", ".", "implode", "(", "\".\"", ",", "$", "new_path", ")", ")", ";", "}", "self", "::", "traverse", "(", "$", "name", "[", "$", "key", "]", ",", "$", "type", "[", "$", "key", "]", ",", "$", "tmp_name", "[", "$", "key", "]", ",", "$", "error", "[", "$", "key", "]", ",", "$", "size", "[", "$", "key", "]", ",", "$", "dict", ",", "$", "new_path", ")", ";", "}", "}", "else", "{", "$", "file", "=", "new", "FileUpload", "(", "$", "path", ",", "$", "name", ",", "$", "type", ",", "$", "tmp_name", ",", "$", "error", ",", "$", "size", ")", ";", "$", "path", "[", "]", "=", "$", "file", ";", "$", "dict", "->", "set", "(", "$", "path", ",", "null", ")", ";", "$", "dict", "->", "set", "(", "'_files'", ",", "$", "file", "->", "getFieldName", "(", ")", ",", "$", "file", ")", ";", "}", "}" ]
Helper function to recursively traverse the uploaded files array. @param array|string $name The name @param array|string $type The content-type @param array|string $tmp_name The temporary file name @param array|int $size The file size @param Dictionary $dict The dictionary where to store the files @param array $path The path in the traversal
[ "Helper", "function", "to", "recursively", "traverse", "the", "uploaded", "files", "array", "." ]
7318eff1b81a3c103c4263466d09b7f3593b70b9
https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/FileUpload.php#L247-L277
train
zewadesign/framework
Zewa/Router.php
Router.baseURL
public function baseURL($path = '') { if (is_null($this->baseURL)) { $self = $_SERVER['PHP_SELF']; $server = $_SERVER['HTTP_HOST'] . rtrim(str_replace(strstr($self, 'index.php'), '', $self), '/'); if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) { $protocol = 'https://'; } else { $protocol = 'http://'; } $this->baseURL = $protocol . $server; } $url = $this->baseURL; if ($path !== '') { $url .= '/' . $path; } return $url; }
php
public function baseURL($path = '') { if (is_null($this->baseURL)) { $self = $_SERVER['PHP_SELF']; $server = $_SERVER['HTTP_HOST'] . rtrim(str_replace(strstr($self, 'index.php'), '', $self), '/'); if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) { $protocol = 'https://'; } else { $protocol = 'http://'; } $this->baseURL = $protocol . $server; } $url = $this->baseURL; if ($path !== '') { $url .= '/' . $path; } return $url; }
[ "public", "function", "baseURL", "(", "$", "path", "=", "''", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "baseURL", ")", ")", "{", "$", "self", "=", "$", "_SERVER", "[", "'PHP_SELF'", "]", ";", "$", "server", "=", "$", "_SERVER", "[", "'HTTP_HOST'", "]", ".", "rtrim", "(", "str_replace", "(", "strstr", "(", "$", "self", ",", "'index.php'", ")", ",", "''", ",", "$", "self", ")", ",", "'/'", ")", ";", "if", "(", "(", "!", "empty", "(", "$", "_SERVER", "[", "'HTTPS'", "]", ")", "&&", "$", "_SERVER", "[", "'HTTPS'", "]", "!=", "'off'", ")", "||", "!", "empty", "(", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_PROTO'", "]", ")", "&&", "$", "_SERVER", "[", "'HTTP_X_FORWARDED_PROTO'", "]", "===", "'https'", ")", "{", "$", "protocol", "=", "'https://'", ";", "}", "else", "{", "$", "protocol", "=", "'http://'", ";", "}", "$", "this", "->", "baseURL", "=", "$", "protocol", ".", "$", "server", ";", "}", "$", "url", "=", "$", "this", "->", "baseURL", ";", "if", "(", "$", "path", "!==", "''", ")", "{", "$", "url", ".=", "'/'", ".", "$", "path", ";", "}", "return", "$", "url", ";", "}" ]
Return the baseURL @access public @return string http://tld.com
[ "Return", "the", "baseURL" ]
be74e41c674ac2c2ef924752ed310cfbaafe33b8
https://github.com/zewadesign/framework/blob/be74e41c674ac2c2ef924752ed310cfbaafe33b8/Zewa/Router.php#L167-L193
train
SlabPHP/controllers
src/Redirect.php
Redirect.determineRedirectURL
protected function determineRedirectURL() { $this->redirectURL = trim($this->getRoutedParameter('url')); if (empty($this->redirectURL)) { $this->setNotReady("Invalid or missing redirect `url` parameter.", null, 404); } }
php
protected function determineRedirectURL() { $this->redirectURL = trim($this->getRoutedParameter('url')); if (empty($this->redirectURL)) { $this->setNotReady("Invalid or missing redirect `url` parameter.", null, 404); } }
[ "protected", "function", "determineRedirectURL", "(", ")", "{", "$", "this", "->", "redirectURL", "=", "trim", "(", "$", "this", "->", "getRoutedParameter", "(", "'url'", ")", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "redirectURL", ")", ")", "{", "$", "this", "->", "setNotReady", "(", "\"Invalid or missing redirect `url` parameter.\"", ",", "null", ",", "404", ")", ";", "}", "}" ]
Determine redirect url
[ "Determine", "redirect", "url" ]
a1c4fded0265100a85904dd664b972a7f8687652
https://github.com/SlabPHP/controllers/blob/a1c4fded0265100a85904dd664b972a7f8687652/src/Redirect.php#L49-L57
train
SlabPHP/controllers
src/Redirect.php
Redirect.determineRedirectType
protected function determineRedirectType() { $this->redirectType = intval($this->getRoutedParameter('type', $this->redirectType)); if (!in_array($this->redirectType, [301, 302])) { $this->setNotReady("Invalid redirect type specified.", null, 404); } }
php
protected function determineRedirectType() { $this->redirectType = intval($this->getRoutedParameter('type', $this->redirectType)); if (!in_array($this->redirectType, [301, 302])) { $this->setNotReady("Invalid redirect type specified.", null, 404); } }
[ "protected", "function", "determineRedirectType", "(", ")", "{", "$", "this", "->", "redirectType", "=", "intval", "(", "$", "this", "->", "getRoutedParameter", "(", "'type'", ",", "$", "this", "->", "redirectType", ")", ")", ";", "if", "(", "!", "in_array", "(", "$", "this", "->", "redirectType", ",", "[", "301", ",", "302", "]", ")", ")", "{", "$", "this", "->", "setNotReady", "(", "\"Invalid redirect type specified.\"", ",", "null", ",", "404", ")", ";", "}", "}" ]
Determine redirect type
[ "Determine", "redirect", "type" ]
a1c4fded0265100a85904dd664b972a7f8687652
https://github.com/SlabPHP/controllers/blob/a1c4fded0265100a85904dd664b972a7f8687652/src/Redirect.php#L70-L78
train
SlabPHP/controllers
src/Redirect.php
Redirect.validateRedirectURL
protected function validateRedirectURL() { if (!filter_var($this->redirectURL, FILTER_VALIDATE_URL)) { // Not a full URL if (!preg_match('#^/[a-zA-Z0-9_/.-]*#', $this->redirectURL)) { // Not a valid path either $this->setNotReady("Invalid redirect URL entered.", null, 404); return; } } }
php
protected function validateRedirectURL() { if (!filter_var($this->redirectURL, FILTER_VALIDATE_URL)) { // Not a full URL if (!preg_match('#^/[a-zA-Z0-9_/.-]*#', $this->redirectURL)) { // Not a valid path either $this->setNotReady("Invalid redirect URL entered.", null, 404); return; } } }
[ "protected", "function", "validateRedirectURL", "(", ")", "{", "if", "(", "!", "filter_var", "(", "$", "this", "->", "redirectURL", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "// Not a full URL", "if", "(", "!", "preg_match", "(", "'#^/[a-zA-Z0-9_/.-]*#'", ",", "$", "this", "->", "redirectURL", ")", ")", "{", "// Not a valid path either", "$", "this", "->", "setNotReady", "(", "\"Invalid redirect URL entered.\"", ",", "null", ",", "404", ")", ";", "return", ";", "}", "}", "}" ]
Validate redirect URL
[ "Validate", "redirect", "URL" ]
a1c4fded0265100a85904dd664b972a7f8687652
https://github.com/SlabPHP/controllers/blob/a1c4fded0265100a85904dd664b972a7f8687652/src/Redirect.php#L92-L102
train
SlabPHP/controllers
src/Redirect.php
Redirect.buildOutputObject
protected function buildOutputObject() { $output = new \Slab\Controllers\Response( static::DEFAULT_REDIRECT_RESOLVER, $this->data, $this->redirectType, $this->displayHeaders ); return $output; }
php
protected function buildOutputObject() { $output = new \Slab\Controllers\Response( static::DEFAULT_REDIRECT_RESOLVER, $this->data, $this->redirectType, $this->displayHeaders ); return $output; }
[ "protected", "function", "buildOutputObject", "(", ")", "{", "$", "output", "=", "new", "\\", "Slab", "\\", "Controllers", "\\", "Response", "(", "static", "::", "DEFAULT_REDIRECT_RESOLVER", ",", "$", "this", "->", "data", ",", "$", "this", "->", "redirectType", ",", "$", "this", "->", "displayHeaders", ")", ";", "return", "$", "output", ";", "}" ]
Build the output object @return \Slab\Components\Output\ControllerResponseInterface|Response
[ "Build", "the", "output", "object" ]
a1c4fded0265100a85904dd664b972a7f8687652
https://github.com/SlabPHP/controllers/blob/a1c4fded0265100a85904dd664b972a7f8687652/src/Redirect.php#L135-L145
train
hschletz/NADA
src/Factory.php
Factory.getDatabase
static function getDatabase($link) { // Determine the database abstraction layer if ($link instanceof \PDO) { $class = 'Pdo'; } elseif ($link instanceof \Zend\Db\Adapter\Adapter) { $class = 'ZendDb2'; } elseif ($link instanceof \Zend_Db_Adapter_Abstract) { $class = 'ZendDb'; } elseif ($link instanceof \MDB2_Driver_Common) { $class = 'Mdb2'; } else { throw new \InvalidArgumentException('Unsupported link type'); } // Create matching link object $class = "Nada\Link\\$class"; $link = new $class($link); // Create and return matching database object $class = 'Nada\Database\\' . $link->getDbmsSuffix(); return new $class($link); }
php
static function getDatabase($link) { // Determine the database abstraction layer if ($link instanceof \PDO) { $class = 'Pdo'; } elseif ($link instanceof \Zend\Db\Adapter\Adapter) { $class = 'ZendDb2'; } elseif ($link instanceof \Zend_Db_Adapter_Abstract) { $class = 'ZendDb'; } elseif ($link instanceof \MDB2_Driver_Common) { $class = 'Mdb2'; } else { throw new \InvalidArgumentException('Unsupported link type'); } // Create matching link object $class = "Nada\Link\\$class"; $link = new $class($link); // Create and return matching database object $class = 'Nada\Database\\' . $link->getDbmsSuffix(); return new $class($link); }
[ "static", "function", "getDatabase", "(", "$", "link", ")", "{", "// Determine the database abstraction layer", "if", "(", "$", "link", "instanceof", "\\", "PDO", ")", "{", "$", "class", "=", "'Pdo'", ";", "}", "elseif", "(", "$", "link", "instanceof", "\\", "Zend", "\\", "Db", "\\", "Adapter", "\\", "Adapter", ")", "{", "$", "class", "=", "'ZendDb2'", ";", "}", "elseif", "(", "$", "link", "instanceof", "\\", "Zend_Db_Adapter_Abstract", ")", "{", "$", "class", "=", "'ZendDb'", ";", "}", "elseif", "(", "$", "link", "instanceof", "\\", "MDB2_Driver_Common", ")", "{", "$", "class", "=", "'Mdb2'", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Unsupported link type'", ")", ";", "}", "// Create matching link object", "$", "class", "=", "\"Nada\\Link\\\\$class\"", ";", "$", "link", "=", "new", "$", "class", "(", "$", "link", ")", ";", "// Create and return matching database object", "$", "class", "=", "'Nada\\Database\\\\'", ".", "$", "link", "->", "getDbmsSuffix", "(", ")", ";", "return", "new", "$", "class", "(", "$", "link", ")", ";", "}" ]
Factory method to create database interface See class description for usage example. @param mixed $link Database link @return \Nada\Database\AbstractDatabase NADA interface @throws \InvalidArgumentException if no supported DBAL is detected
[ "Factory", "method", "to", "create", "database", "interface" ]
4ead798354089fd360f917ce64dd1432d5650df0
https://github.com/hschletz/NADA/blob/4ead798354089fd360f917ce64dd1432d5650df0/src/Factory.php#L55-L77
train
horntell/php-sdk
lib/guzzle/GuzzleHttp/Post/PostFile.php
PostFile.prepareContent
private function prepareContent($content) { $this->content = $content; if (!($this->content instanceof StreamInterface)) { $this->content = Stream::factory($this->content); } elseif ($this->content instanceof MultipartBody) { if (!$this->hasHeader('Content-Disposition')) { $disposition = 'form-data; name="' . $this->name .'"'; $this->headers['Content-Disposition'] = $disposition; } if (!$this->hasHeader('Content-Type')) { $this->headers['Content-Type'] = sprintf( "multipart/form-data; boundary=%s", $this->content->getBoundary() ); } } }
php
private function prepareContent($content) { $this->content = $content; if (!($this->content instanceof StreamInterface)) { $this->content = Stream::factory($this->content); } elseif ($this->content instanceof MultipartBody) { if (!$this->hasHeader('Content-Disposition')) { $disposition = 'form-data; name="' . $this->name .'"'; $this->headers['Content-Disposition'] = $disposition; } if (!$this->hasHeader('Content-Type')) { $this->headers['Content-Type'] = sprintf( "multipart/form-data; boundary=%s", $this->content->getBoundary() ); } } }
[ "private", "function", "prepareContent", "(", "$", "content", ")", "{", "$", "this", "->", "content", "=", "$", "content", ";", "if", "(", "!", "(", "$", "this", "->", "content", "instanceof", "StreamInterface", ")", ")", "{", "$", "this", "->", "content", "=", "Stream", "::", "factory", "(", "$", "this", "->", "content", ")", ";", "}", "elseif", "(", "$", "this", "->", "content", "instanceof", "MultipartBody", ")", "{", "if", "(", "!", "$", "this", "->", "hasHeader", "(", "'Content-Disposition'", ")", ")", "{", "$", "disposition", "=", "'form-data; name=\"'", ".", "$", "this", "->", "name", ".", "'\"'", ";", "$", "this", "->", "headers", "[", "'Content-Disposition'", "]", "=", "$", "disposition", ";", "}", "if", "(", "!", "$", "this", "->", "hasHeader", "(", "'Content-Type'", ")", ")", "{", "$", "this", "->", "headers", "[", "'Content-Type'", "]", "=", "sprintf", "(", "\"multipart/form-data; boundary=%s\"", ",", "$", "this", "->", "content", "->", "getBoundary", "(", ")", ")", ";", "}", "}", "}" ]
Prepares the contents of a POST file. @param mixed $content Content of the POST file
[ "Prepares", "the", "contents", "of", "a", "POST", "file", "." ]
e5205e9396a21b754d5651a8aa5898da5922a1b7
https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/Post/PostFile.php#L66-L85
train
horntell/php-sdk
lib/guzzle/GuzzleHttp/Post/PostFile.php
PostFile.prepareDefaultHeaders
private function prepareDefaultHeaders() { // Set a default content-disposition header if one was no provided if (!$this->hasHeader('Content-Disposition')) { $this->headers['Content-Disposition'] = sprintf( 'form-data; name="%s"; filename="%s"', $this->name, basename($this->filename) ); } // Set a default Content-Type if one was not supplied if (!$this->hasHeader('Content-Type')) { $this->headers['Content-Type'] = Mimetypes::getInstance() ->fromFilename($this->filename) ?: 'text/plain'; } }
php
private function prepareDefaultHeaders() { // Set a default content-disposition header if one was no provided if (!$this->hasHeader('Content-Disposition')) { $this->headers['Content-Disposition'] = sprintf( 'form-data; name="%s"; filename="%s"', $this->name, basename($this->filename) ); } // Set a default Content-Type if one was not supplied if (!$this->hasHeader('Content-Type')) { $this->headers['Content-Type'] = Mimetypes::getInstance() ->fromFilename($this->filename) ?: 'text/plain'; } }
[ "private", "function", "prepareDefaultHeaders", "(", ")", "{", "// Set a default content-disposition header if one was no provided", "if", "(", "!", "$", "this", "->", "hasHeader", "(", "'Content-Disposition'", ")", ")", "{", "$", "this", "->", "headers", "[", "'Content-Disposition'", "]", "=", "sprintf", "(", "'form-data; name=\"%s\"; filename=\"%s\"'", ",", "$", "this", "->", "name", ",", "basename", "(", "$", "this", "->", "filename", ")", ")", ";", "}", "// Set a default Content-Type if one was not supplied", "if", "(", "!", "$", "this", "->", "hasHeader", "(", "'Content-Type'", ")", ")", "{", "$", "this", "->", "headers", "[", "'Content-Type'", "]", "=", "Mimetypes", "::", "getInstance", "(", ")", "->", "fromFilename", "(", "$", "this", "->", "filename", ")", "?", ":", "'text/plain'", ";", "}", "}" ]
Applies default Content-Disposition and Content-Type headers if needed.
[ "Applies", "default", "Content", "-", "Disposition", "and", "Content", "-", "Type", "headers", "if", "needed", "." ]
e5205e9396a21b754d5651a8aa5898da5922a1b7
https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/Post/PostFile.php#L110-L126
train
hiqdev/hidev-license
src/components/License.php
License.getLicense
public function getLicense() { if ($this->_license === null) { $this->_license = $this->take('package')->getLicense(); } return $this->_license; }
php
public function getLicense() { if ($this->_license === null) { $this->_license = $this->take('package')->getLicense(); } return $this->_license; }
[ "public", "function", "getLicense", "(", ")", "{", "if", "(", "$", "this", "->", "_license", "===", "null", ")", "{", "$", "this", "->", "_license", "=", "$", "this", "->", "take", "(", "'package'", ")", "->", "getLicense", "(", ")", ";", "}", "return", "$", "this", "->", "_license", ";", "}" ]
Get license. @return string
[ "Get", "license", "." ]
99069ad17eb6d82a500ec2c2ecf1533a957c6a41
https://github.com/hiqdev/hidev-license/blob/99069ad17eb6d82a500ec2c2ecf1533a957c6a41/src/components/License.php#L39-L46
train
phossa/phossa-route
src/Phossa/Route/Route.php
Route.extractDefaultValues
protected function extractDefaultValues( /*# string */ $pattern )/*# : string */ { $regex = '~\{([a-zA-Z][a-zA-Z0-9_]*+)[^\}]*(=[a-zA-Z0-9._]++)\}~'; if (preg_match_all($regex, $pattern, $matches, \PREG_SET_ORDER)) { $srch = $repl = $vals = []; foreach ($matches as $m) { $srch[] = $m[0]; $repl[] = str_replace($m[2], '', $m[0]); $vals[$m[1]] = substr($m[2],1); } $this->setDefault($vals); return str_replace($srch, $repl, $pattern); } return $pattern; }
php
protected function extractDefaultValues( /*# string */ $pattern )/*# : string */ { $regex = '~\{([a-zA-Z][a-zA-Z0-9_]*+)[^\}]*(=[a-zA-Z0-9._]++)\}~'; if (preg_match_all($regex, $pattern, $matches, \PREG_SET_ORDER)) { $srch = $repl = $vals = []; foreach ($matches as $m) { $srch[] = $m[0]; $repl[] = str_replace($m[2], '', $m[0]); $vals[$m[1]] = substr($m[2],1); } $this->setDefault($vals); return str_replace($srch, $repl, $pattern); } return $pattern; }
[ "protected", "function", "extractDefaultValues", "(", "/*# string */", "$", "pattern", ")", "/*# : string */", "{", "$", "regex", "=", "'~\\{([a-zA-Z][a-zA-Z0-9_]*+)[^\\}]*(=[a-zA-Z0-9._]++)\\}~'", ";", "if", "(", "preg_match_all", "(", "$", "regex", ",", "$", "pattern", ",", "$", "matches", ",", "\\", "PREG_SET_ORDER", ")", ")", "{", "$", "srch", "=", "$", "repl", "=", "$", "vals", "=", "[", "]", ";", "foreach", "(", "$", "matches", "as", "$", "m", ")", "{", "$", "srch", "[", "]", "=", "$", "m", "[", "0", "]", ";", "$", "repl", "[", "]", "=", "str_replace", "(", "$", "m", "[", "2", "]", ",", "''", ",", "$", "m", "[", "0", "]", ")", ";", "$", "vals", "[", "$", "m", "[", "1", "]", "]", "=", "substr", "(", "$", "m", "[", "2", "]", ",", "1", ")", ";", "}", "$", "this", "->", "setDefault", "(", "$", "vals", ")", ";", "return", "str_replace", "(", "$", "srch", ",", "$", "repl", ",", "$", "pattern", ")", ";", "}", "return", "$", "pattern", ";", "}" ]
Extract default values from the pattern @param string $pattern @return string @access protected
[ "Extract", "default", "values", "from", "the", "pattern" ]
fdcc1c814b8b1692a60d433d3c085e6c7a923acc
https://github.com/phossa/phossa-route/blob/fdcc1c814b8b1692a60d433d3c085e6c7a923acc/src/Phossa/Route/Route.php#L195-L210
train
vukbgit/PHPCraft.Subject
src/Traits/Template.php
Template.setCommonTemplateParameters
private function setCommonTemplateParameters() { $this->setTemplateParameter('application', APPLICATION); $this->setTemplateParameter('area', AREA); $this->setTemplateParameter('subject', $this->name); $this->setTemplateParameter('language', LANGUAGE); $this->setTemplateParameter('configuration', $this->configuration); $this->setTemplateParameter('route', $this->route); $this->setTemplateParameter('translations', $this->translations); $this->setTemplateParameter('action', $this->action); $this->setTemplateParameter('ancestors', $this->ancestors); if($this->hasMessages && !empty($this->storedMessages)) { $this->setTemplateParameter('messages', $this->storedMessages); } }
php
private function setCommonTemplateParameters() { $this->setTemplateParameter('application', APPLICATION); $this->setTemplateParameter('area', AREA); $this->setTemplateParameter('subject', $this->name); $this->setTemplateParameter('language', LANGUAGE); $this->setTemplateParameter('configuration', $this->configuration); $this->setTemplateParameter('route', $this->route); $this->setTemplateParameter('translations', $this->translations); $this->setTemplateParameter('action', $this->action); $this->setTemplateParameter('ancestors', $this->ancestors); if($this->hasMessages && !empty($this->storedMessages)) { $this->setTemplateParameter('messages', $this->storedMessages); } }
[ "private", "function", "setCommonTemplateParameters", "(", ")", "{", "$", "this", "->", "setTemplateParameter", "(", "'application'", ",", "APPLICATION", ")", ";", "$", "this", "->", "setTemplateParameter", "(", "'area'", ",", "AREA", ")", ";", "$", "this", "->", "setTemplateParameter", "(", "'subject'", ",", "$", "this", "->", "name", ")", ";", "$", "this", "->", "setTemplateParameter", "(", "'language'", ",", "LANGUAGE", ")", ";", "$", "this", "->", "setTemplateParameter", "(", "'configuration'", ",", "$", "this", "->", "configuration", ")", ";", "$", "this", "->", "setTemplateParameter", "(", "'route'", ",", "$", "this", "->", "route", ")", ";", "$", "this", "->", "setTemplateParameter", "(", "'translations'", ",", "$", "this", "->", "translations", ")", ";", "$", "this", "->", "setTemplateParameter", "(", "'action'", ",", "$", "this", "->", "action", ")", ";", "$", "this", "->", "setTemplateParameter", "(", "'ancestors'", ",", "$", "this", "->", "ancestors", ")", ";", "if", "(", "$", "this", "->", "hasMessages", "&&", "!", "empty", "(", "$", "this", "->", "storedMessages", ")", ")", "{", "$", "this", "->", "setTemplateParameter", "(", "'messages'", ",", "$", "this", "->", "storedMessages", ")", ";", "}", "}" ]
Sets common template parameters
[ "Sets", "common", "template", "parameters" ]
a43ad7868098ff1e7bda6819547ea64f9a853732
https://github.com/vukbgit/PHPCraft.Subject/blob/a43ad7868098ff1e7bda6819547ea64f9a853732/src/Traits/Template.php#L72-L86
train
vukbgit/PHPCraft.Subject
src/Traits/Template.php
Template.buildTemplateFunctions
protected function buildTemplateFunctions() { //path to area $this->templateEngine->addFunction('pathToArea', function ($language = false) { return implode('/', $this->buildPathToArea($language)) . '/'; }); //path to subject $this->templateEngine->addFunction('pathToSubject', function ($language = false) { return implode('/', $this->buildPathToSubject($language)) . '/'; }); //path to action $this->templateEngine->addFunction('pathToAction', function ($action, $configurationUrl = false, $primaryKeyValue = false) { return $this->buildPathToAction($action, $configurationUrl, $primaryKeyValue); }); //path to ancestor $this->templateEngine->addFunction('pathToAncestor', function ($ancestor) { return implode('/', $this->buildPathToAncestor($ancestor)); }); }
php
protected function buildTemplateFunctions() { //path to area $this->templateEngine->addFunction('pathToArea', function ($language = false) { return implode('/', $this->buildPathToArea($language)) . '/'; }); //path to subject $this->templateEngine->addFunction('pathToSubject', function ($language = false) { return implode('/', $this->buildPathToSubject($language)) . '/'; }); //path to action $this->templateEngine->addFunction('pathToAction', function ($action, $configurationUrl = false, $primaryKeyValue = false) { return $this->buildPathToAction($action, $configurationUrl, $primaryKeyValue); }); //path to ancestor $this->templateEngine->addFunction('pathToAncestor', function ($ancestor) { return implode('/', $this->buildPathToAncestor($ancestor)); }); }
[ "protected", "function", "buildTemplateFunctions", "(", ")", "{", "//path to area", "$", "this", "->", "templateEngine", "->", "addFunction", "(", "'pathToArea'", ",", "function", "(", "$", "language", "=", "false", ")", "{", "return", "implode", "(", "'/'", ",", "$", "this", "->", "buildPathToArea", "(", "$", "language", ")", ")", ".", "'/'", ";", "}", ")", ";", "//path to subject", "$", "this", "->", "templateEngine", "->", "addFunction", "(", "'pathToSubject'", ",", "function", "(", "$", "language", "=", "false", ")", "{", "return", "implode", "(", "'/'", ",", "$", "this", "->", "buildPathToSubject", "(", "$", "language", ")", ")", ".", "'/'", ";", "}", ")", ";", "//path to action", "$", "this", "->", "templateEngine", "->", "addFunction", "(", "'pathToAction'", ",", "function", "(", "$", "action", ",", "$", "configurationUrl", "=", "false", ",", "$", "primaryKeyValue", "=", "false", ")", "{", "return", "$", "this", "->", "buildPathToAction", "(", "$", "action", ",", "$", "configurationUrl", ",", "$", "primaryKeyValue", ")", ";", "}", ")", ";", "//path to ancestor", "$", "this", "->", "templateEngine", "->", "addFunction", "(", "'pathToAncestor'", ",", "function", "(", "$", "ancestor", ")", "{", "return", "implode", "(", "'/'", ",", "$", "this", "->", "buildPathToAncestor", "(", "$", "ancestor", ")", ")", ";", "}", ")", ";", "}" ]
Builds functions used into templates
[ "Builds", "functions", "used", "into", "templates" ]
a43ad7868098ff1e7bda6819547ea64f9a853732
https://github.com/vukbgit/PHPCraft.Subject/blob/a43ad7868098ff1e7bda6819547ea64f9a853732/src/Traits/Template.php#L100-L118
train