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
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
DoSomething/mb-toolbox
src/MB_Toolbox.php
MB_Toolbox.createNorthstarUser
public function createNorthstarUser($user) { $northstarAPIConfig = $this->mbConfig->getProperty('northstar_config'); if (empty($northstarAPIConfig['host'])) { throw new Exception('MB_Toolbox->createNorthstarUser() northstar_config missing host setting.'); } // Required - at least one of email or mobile must be set. $requiredSet = false; if (!empty($user->email)) { $post['email'] = $user->email; $requiredSet = true; } if (!empty($user->mobile)) { $post['mobile'] = $user->mobile; $requiredSet = true; } if (!$requiredSet) { throw new Exception('MB_Toolbox->createNorthstarUser() Neither email or mobile value available. Failed to create user.'); } // Optional fields that can be a part of a Northstar user document // List of supported fields: // https://github.com/DoSomething/northstar/blob/dev/documentation/endpoints/users.md#create-a-user $supportedFields = [ 'password', 'first_name', 'last_name', 'addr_street1', 'addr_street2', 'addr_city', 'addr_state', 'addr_zip', 'country', // two character country code 'language', 'source', 'race', 'religion', 'college_name', 'degree_type', 'major_name', 'hs_gradyear', 'hs_name', 'sat_math', 'sat_verbal', 'sat_writing', ]; foreach ($supportedFields as $field) { if (isset($user->$field)) { $post[$field] = $user->$field; } } // Optional fields that require formatting if (isset($user->birthdate) && strtotime($user->birthdate)) { $post['birthdate'] = date('Y-m-d', strtotime($user->birthdate)); } elseif (isset($user->birthdate) && is_int($user->birthdate)) { $post['birthdate'] = date('Y-m-d', $user->birthdate); } elseif (isset($user->birthdate_timestamp) && is_int($user->birthdate_timestamp)) { $post['birthdate'] = date('Y-m-d', $user->birthdate_timestamp); } $northstarUrl = $northstarAPIConfig['host']; // Append port if exists. if (!empty($northstarAPIConfig['port'])) { $port = (int) $northstarAPIConfig['port']; // Port is within allowed range: // https://en.wikipedia.org/wiki/Port_(computer_networking)#Details if ($port > 0 && $port < 65536) { $northstarUrl .= ':' . $port; } } $northstarUrl .= '/' . self::NORTHSTAR_API_VERSION . '/users?create_drupal_user=true'; $result = $this->mbToolboxcURL->curlPOST($northstarUrl, $post); return $this->parseNorthstarUserResponse($result); }
php
public function createNorthstarUser($user) { $northstarAPIConfig = $this->mbConfig->getProperty('northstar_config'); if (empty($northstarAPIConfig['host'])) { throw new Exception('MB_Toolbox->createNorthstarUser() northstar_config missing host setting.'); } // Required - at least one of email or mobile must be set. $requiredSet = false; if (!empty($user->email)) { $post['email'] = $user->email; $requiredSet = true; } if (!empty($user->mobile)) { $post['mobile'] = $user->mobile; $requiredSet = true; } if (!$requiredSet) { throw new Exception('MB_Toolbox->createNorthstarUser() Neither email or mobile value available. Failed to create user.'); } // Optional fields that can be a part of a Northstar user document // List of supported fields: // https://github.com/DoSomething/northstar/blob/dev/documentation/endpoints/users.md#create-a-user $supportedFields = [ 'password', 'first_name', 'last_name', 'addr_street1', 'addr_street2', 'addr_city', 'addr_state', 'addr_zip', 'country', // two character country code 'language', 'source', 'race', 'religion', 'college_name', 'degree_type', 'major_name', 'hs_gradyear', 'hs_name', 'sat_math', 'sat_verbal', 'sat_writing', ]; foreach ($supportedFields as $field) { if (isset($user->$field)) { $post[$field] = $user->$field; } } // Optional fields that require formatting if (isset($user->birthdate) && strtotime($user->birthdate)) { $post['birthdate'] = date('Y-m-d', strtotime($user->birthdate)); } elseif (isset($user->birthdate) && is_int($user->birthdate)) { $post['birthdate'] = date('Y-m-d', $user->birthdate); } elseif (isset($user->birthdate_timestamp) && is_int($user->birthdate_timestamp)) { $post['birthdate'] = date('Y-m-d', $user->birthdate_timestamp); } $northstarUrl = $northstarAPIConfig['host']; // Append port if exists. if (!empty($northstarAPIConfig['port'])) { $port = (int) $northstarAPIConfig['port']; // Port is within allowed range: // https://en.wikipedia.org/wiki/Port_(computer_networking)#Details if ($port > 0 && $port < 65536) { $northstarUrl .= ':' . $port; } } $northstarUrl .= '/' . self::NORTHSTAR_API_VERSION . '/users?create_drupal_user=true'; $result = $this->mbToolboxcURL->curlPOST($northstarUrl, $post); return $this->parseNorthstarUserResponse($result); }
[ "public", "function", "createNorthstarUser", "(", "$", "user", ")", "{", "$", "northstarAPIConfig", "=", "$", "this", "->", "mbConfig", "->", "getProperty", "(", "'northstar_config'", ")", ";", "if", "(", "empty", "(", "$", "northstarAPIConfig", "[", "'host'", "]", ")", ")", "{", "throw", "new", "Exception", "(", "'MB_Toolbox->createNorthstarUser() northstar_config missing host setting.'", ")", ";", "}", "// Required - at least one of email or mobile must be set.", "$", "requiredSet", "=", "false", ";", "if", "(", "!", "empty", "(", "$", "user", "->", "email", ")", ")", "{", "$", "post", "[", "'email'", "]", "=", "$", "user", "->", "email", ";", "$", "requiredSet", "=", "true", ";", "}", "if", "(", "!", "empty", "(", "$", "user", "->", "mobile", ")", ")", "{", "$", "post", "[", "'mobile'", "]", "=", "$", "user", "->", "mobile", ";", "$", "requiredSet", "=", "true", ";", "}", "if", "(", "!", "$", "requiredSet", ")", "{", "throw", "new", "Exception", "(", "'MB_Toolbox->createNorthstarUser() Neither email or mobile value available. Failed to create user.'", ")", ";", "}", "// Optional fields that can be a part of a Northstar user document", "// List of supported fields:", "// https://github.com/DoSomething/northstar/blob/dev/documentation/endpoints/users.md#create-a-user", "$", "supportedFields", "=", "[", "'password'", ",", "'first_name'", ",", "'last_name'", ",", "'addr_street1'", ",", "'addr_street2'", ",", "'addr_city'", ",", "'addr_state'", ",", "'addr_zip'", ",", "'country'", ",", "// two character country code", "'language'", ",", "'source'", ",", "'race'", ",", "'religion'", ",", "'college_name'", ",", "'degree_type'", ",", "'major_name'", ",", "'hs_gradyear'", ",", "'hs_name'", ",", "'sat_math'", ",", "'sat_verbal'", ",", "'sat_writing'", ",", "]", ";", "foreach", "(", "$", "supportedFields", "as", "$", "field", ")", "{", "if", "(", "isset", "(", "$", "user", "->", "$", "field", ")", ")", "{", "$", "post", "[", "$", "field", "]", "=", "$", "user", "->", "$", "field", ";", "}", "}", "// Optional fields that require formatting", "if", "(", "isset", "(", "$", "user", "->", "birthdate", ")", "&&", "strtotime", "(", "$", "user", "->", "birthdate", ")", ")", "{", "$", "post", "[", "'birthdate'", "]", "=", "date", "(", "'Y-m-d'", ",", "strtotime", "(", "$", "user", "->", "birthdate", ")", ")", ";", "}", "elseif", "(", "isset", "(", "$", "user", "->", "birthdate", ")", "&&", "is_int", "(", "$", "user", "->", "birthdate", ")", ")", "{", "$", "post", "[", "'birthdate'", "]", "=", "date", "(", "'Y-m-d'", ",", "$", "user", "->", "birthdate", ")", ";", "}", "elseif", "(", "isset", "(", "$", "user", "->", "birthdate_timestamp", ")", "&&", "is_int", "(", "$", "user", "->", "birthdate_timestamp", ")", ")", "{", "$", "post", "[", "'birthdate'", "]", "=", "date", "(", "'Y-m-d'", ",", "$", "user", "->", "birthdate_timestamp", ")", ";", "}", "$", "northstarUrl", "=", "$", "northstarAPIConfig", "[", "'host'", "]", ";", "// Append port if exists.", "if", "(", "!", "empty", "(", "$", "northstarAPIConfig", "[", "'port'", "]", ")", ")", "{", "$", "port", "=", "(", "int", ")", "$", "northstarAPIConfig", "[", "'port'", "]", ";", "// Port is within allowed range:", "// https://en.wikipedia.org/wiki/Port_(computer_networking)#Details", "if", "(", "$", "port", ">", "0", "&&", "$", "port", "<", "65536", ")", "{", "$", "northstarUrl", ".=", "':'", ".", "$", "port", ";", "}", "}", "$", "northstarUrl", ".=", "'/'", ".", "self", "::", "NORTHSTAR_API_VERSION", ".", "'/users?create_drupal_user=true'", ";", "$", "result", "=", "$", "this", "->", "mbToolboxcURL", "->", "curlPOST", "(", "$", "northstarUrl", ",", "$", "post", ")", ";", "return", "$", "this", "->", "parseNorthstarUserResponse", "(", "$", "result", ")", ";", "}" ]
Create a user entry in Northstar, the DoSomething User API. @param object $user Values used to define the user created in Northstar. @return object The values returned from Northstar as a result of user creation.
[ "Create", "a", "user", "entry", "in", "Northstar", "the", "DoSomething", "User", "API", "." ]
ceec5fc594bae137d1ab1f447344800343b62ac6
https://github.com/DoSomething/mb-toolbox/blob/ceec5fc594bae137d1ab1f447344800343b62ac6/src/MB_Toolbox.php#L212-L293
train
DoSomething/mb-toolbox
src/MB_Toolbox.php
MB_Toolbox.lookupNorthstarUser
public function lookupNorthstarUser($user) { $northstarAPIConfig = $this->mbConfig->getProperty('northstar_config'); if (empty($northstarAPIConfig['host'])) { throw new Exception('MB_Toolbox->lookupNorthstarUser() northstar_config missing host setting.'); } $northstarUrl = $northstarAPIConfig['host']; // Append port if exists. if (!empty($northstarAPIConfig['port'])) { $port = (int) $northstarAPIConfig['port']; // Port is within allowed range: // https://en.wikipedia.org/wiki/Port_(computer_networking)#Details if ($port > 0 && $port < 65536) { $northstarUrl .= ':' . $port; } } // Api version. $northstarUrl .= '/' . self::NORTHSTAR_API_VERSION . '/'; // Lookup by email. if (!empty($user->email)) { $endpoint = $northstarUrl . 'users/email/' . $user->email; $result = $this->mbToolboxcURL->curlGet($endpoint); try { $northstarUser = $this->parseNorthstarUserResponse($result); echo '- User loaded from Northstar by email: ' . $user->email . PHP_EOL; return $northstarUser; } catch (Exception $e) { echo '- Coundn\'t load user from Northstar by email: ' . $user->email . PHP_EOL; } } // Lookup by phone. if (!empty($user->mobile)) { $endpoint = $northstarUrl . 'users/mobile/' . $user->mobile; $result = $this->mbToolboxcURL->curlGet($endpoint); try { $northstarUser = $this->parseNorthstarUserResponse($result); echo '- User loaded from Northstar by mobile: ' . $user->mobile . PHP_EOL; return $northstarUser; } catch (Exception $e) { echo '- Coundn\'t load user from Northstar by mobile: ' . $user->mobile . PHP_EOL; } } return false; }
php
public function lookupNorthstarUser($user) { $northstarAPIConfig = $this->mbConfig->getProperty('northstar_config'); if (empty($northstarAPIConfig['host'])) { throw new Exception('MB_Toolbox->lookupNorthstarUser() northstar_config missing host setting.'); } $northstarUrl = $northstarAPIConfig['host']; // Append port if exists. if (!empty($northstarAPIConfig['port'])) { $port = (int) $northstarAPIConfig['port']; // Port is within allowed range: // https://en.wikipedia.org/wiki/Port_(computer_networking)#Details if ($port > 0 && $port < 65536) { $northstarUrl .= ':' . $port; } } // Api version. $northstarUrl .= '/' . self::NORTHSTAR_API_VERSION . '/'; // Lookup by email. if (!empty($user->email)) { $endpoint = $northstarUrl . 'users/email/' . $user->email; $result = $this->mbToolboxcURL->curlGet($endpoint); try { $northstarUser = $this->parseNorthstarUserResponse($result); echo '- User loaded from Northstar by email: ' . $user->email . PHP_EOL; return $northstarUser; } catch (Exception $e) { echo '- Coundn\'t load user from Northstar by email: ' . $user->email . PHP_EOL; } } // Lookup by phone. if (!empty($user->mobile)) { $endpoint = $northstarUrl . 'users/mobile/' . $user->mobile; $result = $this->mbToolboxcURL->curlGet($endpoint); try { $northstarUser = $this->parseNorthstarUserResponse($result); echo '- User loaded from Northstar by mobile: ' . $user->mobile . PHP_EOL; return $northstarUser; } catch (Exception $e) { echo '- Coundn\'t load user from Northstar by mobile: ' . $user->mobile . PHP_EOL; } } return false; }
[ "public", "function", "lookupNorthstarUser", "(", "$", "user", ")", "{", "$", "northstarAPIConfig", "=", "$", "this", "->", "mbConfig", "->", "getProperty", "(", "'northstar_config'", ")", ";", "if", "(", "empty", "(", "$", "northstarAPIConfig", "[", "'host'", "]", ")", ")", "{", "throw", "new", "Exception", "(", "'MB_Toolbox->lookupNorthstarUser() northstar_config missing host setting.'", ")", ";", "}", "$", "northstarUrl", "=", "$", "northstarAPIConfig", "[", "'host'", "]", ";", "// Append port if exists.", "if", "(", "!", "empty", "(", "$", "northstarAPIConfig", "[", "'port'", "]", ")", ")", "{", "$", "port", "=", "(", "int", ")", "$", "northstarAPIConfig", "[", "'port'", "]", ";", "// Port is within allowed range:", "// https://en.wikipedia.org/wiki/Port_(computer_networking)#Details", "if", "(", "$", "port", ">", "0", "&&", "$", "port", "<", "65536", ")", "{", "$", "northstarUrl", ".=", "':'", ".", "$", "port", ";", "}", "}", "// Api version.", "$", "northstarUrl", ".=", "'/'", ".", "self", "::", "NORTHSTAR_API_VERSION", ".", "'/'", ";", "// Lookup by email.", "if", "(", "!", "empty", "(", "$", "user", "->", "email", ")", ")", "{", "$", "endpoint", "=", "$", "northstarUrl", ".", "'users/email/'", ".", "$", "user", "->", "email", ";", "$", "result", "=", "$", "this", "->", "mbToolboxcURL", "->", "curlGet", "(", "$", "endpoint", ")", ";", "try", "{", "$", "northstarUser", "=", "$", "this", "->", "parseNorthstarUserResponse", "(", "$", "result", ")", ";", "echo", "'- User loaded from Northstar by email: '", ".", "$", "user", "->", "email", ".", "PHP_EOL", ";", "return", "$", "northstarUser", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "echo", "'- Coundn\\'t load user from Northstar by email: '", ".", "$", "user", "->", "email", ".", "PHP_EOL", ";", "}", "}", "// Lookup by phone.", "if", "(", "!", "empty", "(", "$", "user", "->", "mobile", ")", ")", "{", "$", "endpoint", "=", "$", "northstarUrl", ".", "'users/mobile/'", ".", "$", "user", "->", "mobile", ";", "$", "result", "=", "$", "this", "->", "mbToolboxcURL", "->", "curlGet", "(", "$", "endpoint", ")", ";", "try", "{", "$", "northstarUser", "=", "$", "this", "->", "parseNorthstarUserResponse", "(", "$", "result", ")", ";", "echo", "'- User loaded from Northstar by mobile: '", ".", "$", "user", "->", "mobile", ".", "PHP_EOL", ";", "return", "$", "northstarUser", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "echo", "'- Coundn\\'t load user from Northstar by mobile: '", ".", "$", "user", "->", "mobile", ".", "PHP_EOL", ";", "}", "}", "return", "false", ";", "}" ]
Lookup user on Northstar.
[ "Lookup", "user", "on", "Northstar", "." ]
ceec5fc594bae137d1ab1f447344800343b62ac6
https://github.com/DoSomething/mb-toolbox/blob/ceec5fc594bae137d1ab1f447344800343b62ac6/src/MB_Toolbox.php#L298-L353
train
DoSomething/mb-toolbox
src/MB_Toolbox.php
MB_Toolbox.parseNorthstarUserResponse
public function parseNorthstarUserResponse($response) { // Check response contains correct data. if (!is_array($response) || empty($response[0]) || empty($response[1])) { throw new Exception( '- Unexpected Northstar response:' . var_export($response, true) ); } // Check HTTP code. list($user, $httpCode) = $response; if ($httpCode === 201) { echo '- Northstar user created.' . PHP_EOL; } elseif ($httpCode === 200) { echo '- Northstar user loaded or updated.' . PHP_EOL; } else { throw new Exception( '- Unexpected Northstar http code:' . $httpCode . 'user: ' . var_export($user, true) ); } // Check user user. if (empty($user->data) || empty($user->data->id)) { throw new Exception( '- Unexpected user user:'. var_export($user->data, true) ); } return $user->data; }
php
public function parseNorthstarUserResponse($response) { // Check response contains correct data. if (!is_array($response) || empty($response[0]) || empty($response[1])) { throw new Exception( '- Unexpected Northstar response:' . var_export($response, true) ); } // Check HTTP code. list($user, $httpCode) = $response; if ($httpCode === 201) { echo '- Northstar user created.' . PHP_EOL; } elseif ($httpCode === 200) { echo '- Northstar user loaded or updated.' . PHP_EOL; } else { throw new Exception( '- Unexpected Northstar http code:' . $httpCode . 'user: ' . var_export($user, true) ); } // Check user user. if (empty($user->data) || empty($user->data->id)) { throw new Exception( '- Unexpected user user:'. var_export($user->data, true) ); } return $user->data; }
[ "public", "function", "parseNorthstarUserResponse", "(", "$", "response", ")", "{", "// Check response contains correct data.", "if", "(", "!", "is_array", "(", "$", "response", ")", "||", "empty", "(", "$", "response", "[", "0", "]", ")", "||", "empty", "(", "$", "response", "[", "1", "]", ")", ")", "{", "throw", "new", "Exception", "(", "'- Unexpected Northstar response:'", ".", "var_export", "(", "$", "response", ",", "true", ")", ")", ";", "}", "// Check HTTP code.", "list", "(", "$", "user", ",", "$", "httpCode", ")", "=", "$", "response", ";", "if", "(", "$", "httpCode", "===", "201", ")", "{", "echo", "'- Northstar user created.'", ".", "PHP_EOL", ";", "}", "elseif", "(", "$", "httpCode", "===", "200", ")", "{", "echo", "'- Northstar user loaded or updated.'", ".", "PHP_EOL", ";", "}", "else", "{", "throw", "new", "Exception", "(", "'- Unexpected Northstar http code:'", ".", "$", "httpCode", ".", "'user: '", ".", "var_export", "(", "$", "user", ",", "true", ")", ")", ";", "}", "// Check user user.", "if", "(", "empty", "(", "$", "user", "->", "data", ")", "||", "empty", "(", "$", "user", "->", "data", "->", "id", ")", ")", "{", "throw", "new", "Exception", "(", "'- Unexpected user user:'", ".", "var_export", "(", "$", "user", "->", "data", ",", "true", ")", ")", ";", "}", "return", "$", "user", "->", "data", ";", "}" ]
Parse Northstar user response, throw exception on failure.
[ "Parse", "Northstar", "user", "response", "throw", "exception", "on", "failure", "." ]
ceec5fc594bae137d1ab1f447344800343b62ac6
https://github.com/DoSomething/mb-toolbox/blob/ceec5fc594bae137d1ab1f447344800343b62ac6/src/MB_Toolbox.php#L358-L387
train
gplcart/cli
controllers/commands/User.php
User.cmdGetUser
public function cmdGetUser() { $result = $this->getListUser(); $this->outputFormat($result); $this->outputFormatTableUser($result); $this->output(); }
php
public function cmdGetUser() { $result = $this->getListUser(); $this->outputFormat($result); $this->outputFormatTableUser($result); $this->output(); }
[ "public", "function", "cmdGetUser", "(", ")", "{", "$", "result", "=", "$", "this", "->", "getListUser", "(", ")", ";", "$", "this", "->", "outputFormat", "(", "$", "result", ")", ";", "$", "this", "->", "outputFormatTableUser", "(", "$", "result", ")", ";", "$", "this", "->", "output", "(", ")", ";", "}" ]
Callback for "user-get" command
[ "Callback", "for", "user", "-", "get", "command" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/User.php#L41-L47
train
gplcart/cli
controllers/commands/User.php
User.cmdUpdateUser
public function cmdUpdateUser() { $params = $this->getParam(); if (empty($params[0]) || count($params) < 2) { $this->errorAndExit($this->text('Invalid command')); } if (!is_numeric($params[0])) { $this->errorAndExit($this->text('Invalid argument')); } $this->setSubmitted(null, $params); $this->setSubmitted('update', $params[0]); $this->setSubmittedJson('data'); $this->validateComponent('user', array('admin' => true)); $this->updateUser($params[0]); $this->output(); }
php
public function cmdUpdateUser() { $params = $this->getParam(); if (empty($params[0]) || count($params) < 2) { $this->errorAndExit($this->text('Invalid command')); } if (!is_numeric($params[0])) { $this->errorAndExit($this->text('Invalid argument')); } $this->setSubmitted(null, $params); $this->setSubmitted('update', $params[0]); $this->setSubmittedJson('data'); $this->validateComponent('user', array('admin' => true)); $this->updateUser($params[0]); $this->output(); }
[ "public", "function", "cmdUpdateUser", "(", ")", "{", "$", "params", "=", "$", "this", "->", "getParam", "(", ")", ";", "if", "(", "empty", "(", "$", "params", "[", "0", "]", ")", "||", "count", "(", "$", "params", ")", "<", "2", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Invalid command'", ")", ")", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "params", "[", "0", "]", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Invalid argument'", ")", ")", ";", "}", "$", "this", "->", "setSubmitted", "(", "null", ",", "$", "params", ")", ";", "$", "this", "->", "setSubmitted", "(", "'update'", ",", "$", "params", "[", "0", "]", ")", ";", "$", "this", "->", "setSubmittedJson", "(", "'data'", ")", ";", "$", "this", "->", "validateComponent", "(", "'user'", ",", "array", "(", "'admin'", "=>", "true", ")", ")", ";", "$", "this", "->", "updateUser", "(", "$", "params", "[", "0", "]", ")", ";", "$", "this", "->", "output", "(", ")", ";", "}" ]
Callback for "user-update" command
[ "Callback", "for", "user", "-", "update", "command" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/User.php#L106-L126
train
gplcart/cli
controllers/commands/User.php
User.submitAddUser
protected function submitAddUser() { $this->setSubmitted(null, $this->getParam()); $this->setSubmittedJson('data'); $this->validateComponent('user'); $this->addUser(); }
php
protected function submitAddUser() { $this->setSubmitted(null, $this->getParam()); $this->setSubmittedJson('data'); $this->validateComponent('user'); $this->addUser(); }
[ "protected", "function", "submitAddUser", "(", ")", "{", "$", "this", "->", "setSubmitted", "(", "null", ",", "$", "this", "->", "getParam", "(", ")", ")", ";", "$", "this", "->", "setSubmittedJson", "(", "'data'", ")", ";", "$", "this", "->", "validateComponent", "(", "'user'", ")", ";", "$", "this", "->", "addUser", "(", ")", ";", "}" ]
Add a new user at once
[ "Add", "a", "new", "user", "at", "once" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/User.php#L208-L215
train
gplcart/cli
controllers/commands/User.php
User.addUser
protected function addUser() { if (!$this->isError()) { $id = $this->user->add($this->getSubmitted()); if (empty($id)) { $this->errorAndExit($this->text('Unexpected result')); } $this->line($id); } }
php
protected function addUser() { if (!$this->isError()) { $id = $this->user->add($this->getSubmitted()); if (empty($id)) { $this->errorAndExit($this->text('Unexpected result')); } $this->line($id); } }
[ "protected", "function", "addUser", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isError", "(", ")", ")", "{", "$", "id", "=", "$", "this", "->", "user", "->", "add", "(", "$", "this", "->", "getSubmitted", "(", ")", ")", ";", "if", "(", "empty", "(", "$", "id", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Unexpected result'", ")", ")", ";", "}", "$", "this", "->", "line", "(", "$", "id", ")", ";", "}", "}" ]
Add a new user
[ "Add", "a", "new", "user" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/User.php#L220-L229
train
gplcart/cli
controllers/commands/User.php
User.wizardAddUser
protected function wizardAddUser() { // Required $this->validatePrompt('email', $this->text('E-mail'), 'user'); $this->validatePrompt('password', $this->text('Password'), 'user'); $this->validatePrompt('name', $this->text('Name'), 'user'); // Optional $this->validatePrompt('role_id', $this->text('Role ID'), 'user', 0); $this->validatePrompt('store_id', $this->text('Store ID'), 'user', $this->config->get('store', 1)); $this->validatePrompt('timezone', $this->text('Timezone'), 'user', $this->config->get('timezone', 'Europe/London')); $this->validatePrompt('status', $this->text('Status'), 'user', 0); $this->validatePrompt('data', $this->text('Data'), 'user'); $this->setSubmittedJson('data'); $this->validateComponent('user'); $this->addUser(); }
php
protected function wizardAddUser() { // Required $this->validatePrompt('email', $this->text('E-mail'), 'user'); $this->validatePrompt('password', $this->text('Password'), 'user'); $this->validatePrompt('name', $this->text('Name'), 'user'); // Optional $this->validatePrompt('role_id', $this->text('Role ID'), 'user', 0); $this->validatePrompt('store_id', $this->text('Store ID'), 'user', $this->config->get('store', 1)); $this->validatePrompt('timezone', $this->text('Timezone'), 'user', $this->config->get('timezone', 'Europe/London')); $this->validatePrompt('status', $this->text('Status'), 'user', 0); $this->validatePrompt('data', $this->text('Data'), 'user'); $this->setSubmittedJson('data'); $this->validateComponent('user'); $this->addUser(); }
[ "protected", "function", "wizardAddUser", "(", ")", "{", "// Required", "$", "this", "->", "validatePrompt", "(", "'email'", ",", "$", "this", "->", "text", "(", "'E-mail'", ")", ",", "'user'", ")", ";", "$", "this", "->", "validatePrompt", "(", "'password'", ",", "$", "this", "->", "text", "(", "'Password'", ")", ",", "'user'", ")", ";", "$", "this", "->", "validatePrompt", "(", "'name'", ",", "$", "this", "->", "text", "(", "'Name'", ")", ",", "'user'", ")", ";", "// Optional", "$", "this", "->", "validatePrompt", "(", "'role_id'", ",", "$", "this", "->", "text", "(", "'Role ID'", ")", ",", "'user'", ",", "0", ")", ";", "$", "this", "->", "validatePrompt", "(", "'store_id'", ",", "$", "this", "->", "text", "(", "'Store ID'", ")", ",", "'user'", ",", "$", "this", "->", "config", "->", "get", "(", "'store'", ",", "1", ")", ")", ";", "$", "this", "->", "validatePrompt", "(", "'timezone'", ",", "$", "this", "->", "text", "(", "'Timezone'", ")", ",", "'user'", ",", "$", "this", "->", "config", "->", "get", "(", "'timezone'", ",", "'Europe/London'", ")", ")", ";", "$", "this", "->", "validatePrompt", "(", "'status'", ",", "$", "this", "->", "text", "(", "'Status'", ")", ",", "'user'", ",", "0", ")", ";", "$", "this", "->", "validatePrompt", "(", "'data'", ",", "$", "this", "->", "text", "(", "'Data'", ")", ",", "'user'", ")", ";", "$", "this", "->", "setSubmittedJson", "(", "'data'", ")", ";", "$", "this", "->", "validateComponent", "(", "'user'", ")", ";", "$", "this", "->", "addUser", "(", ")", ";", "}" ]
Add a new user step by step
[ "Add", "a", "new", "user", "step", "by", "step" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/User.php#L234-L251
train
gplcart/cli
controllers/commands/User.php
User.setStatusUser
public function setStatusUser($status) { $options = $id = $result = null; if ($this->getParam('all')) { $options = array(); } else { $id = $this->getParam(0); if (!is_numeric($id)) { // Allow 0 for roleless users $this->errorAndExit($this->text('Invalid argument')); } if ($this->getParam('role')) { $options = array('role_id' => $id); } else if ($this->getParam('store')) { $options = array('store_id' => $id); } } if (isset($options)) { $updated = $count = 0; foreach ($this->user->getList($options) as $item) { $count++; $updated += (int) $this->user->update($item['user_id'], array('status' => (bool) $status)); } $result = $count && $count == $updated; } else if (isset($id)) { $result = $this->user->update($id, array('status' => (bool) $status)); } if (empty($result)) { $this->errorAndExit($this->text('Unexpected result')); } }
php
public function setStatusUser($status) { $options = $id = $result = null; if ($this->getParam('all')) { $options = array(); } else { $id = $this->getParam(0); if (!is_numeric($id)) { // Allow 0 for roleless users $this->errorAndExit($this->text('Invalid argument')); } if ($this->getParam('role')) { $options = array('role_id' => $id); } else if ($this->getParam('store')) { $options = array('store_id' => $id); } } if (isset($options)) { $updated = $count = 0; foreach ($this->user->getList($options) as $item) { $count++; $updated += (int) $this->user->update($item['user_id'], array('status' => (bool) $status)); } $result = $count && $count == $updated; } else if (isset($id)) { $result = $this->user->update($id, array('status' => (bool) $status)); } if (empty($result)) { $this->errorAndExit($this->text('Unexpected result')); } }
[ "public", "function", "setStatusUser", "(", "$", "status", ")", "{", "$", "options", "=", "$", "id", "=", "$", "result", "=", "null", ";", "if", "(", "$", "this", "->", "getParam", "(", "'all'", ")", ")", "{", "$", "options", "=", "array", "(", ")", ";", "}", "else", "{", "$", "id", "=", "$", "this", "->", "getParam", "(", "0", ")", ";", "if", "(", "!", "is_numeric", "(", "$", "id", ")", ")", "{", "// Allow 0 for roleless users", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Invalid argument'", ")", ")", ";", "}", "if", "(", "$", "this", "->", "getParam", "(", "'role'", ")", ")", "{", "$", "options", "=", "array", "(", "'role_id'", "=>", "$", "id", ")", ";", "}", "else", "if", "(", "$", "this", "->", "getParam", "(", "'store'", ")", ")", "{", "$", "options", "=", "array", "(", "'store_id'", "=>", "$", "id", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "options", ")", ")", "{", "$", "updated", "=", "$", "count", "=", "0", ";", "foreach", "(", "$", "this", "->", "user", "->", "getList", "(", "$", "options", ")", "as", "$", "item", ")", "{", "$", "count", "++", ";", "$", "updated", "+=", "(", "int", ")", "$", "this", "->", "user", "->", "update", "(", "$", "item", "[", "'user_id'", "]", ",", "array", "(", "'status'", "=>", "(", "bool", ")", "$", "status", ")", ")", ";", "}", "$", "result", "=", "$", "count", "&&", "$", "count", "==", "$", "updated", ";", "}", "else", "if", "(", "isset", "(", "$", "id", ")", ")", "{", "$", "result", "=", "$", "this", "->", "user", "->", "update", "(", "$", "id", ",", "array", "(", "'status'", "=>", "(", "bool", ")", "$", "status", ")", ")", ";", "}", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Unexpected result'", ")", ")", ";", "}", "}" ]
Sets a user status @param $status
[ "Sets", "a", "user", "status" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/User.php#L257-L295
train
locomotivemtl/charcoal-queue
src/Charcoal/Queue/QueueableTrait.php
QueueableTrait.setQueueId
public function setQueueId($id) { if ($id === null) { $this->queueId = null; return $this; } if (!is_string($id)) { throw new InvalidArgumentException( 'Queue ID must be a string' ); } $this->queueId = $id; return $this; }
php
public function setQueueId($id) { if ($id === null) { $this->queueId = null; return $this; } if (!is_string($id)) { throw new InvalidArgumentException( 'Queue ID must be a string' ); } $this->queueId = $id; return $this; }
[ "public", "function", "setQueueId", "(", "$", "id", ")", "{", "if", "(", "$", "id", "===", "null", ")", "{", "$", "this", "->", "queueId", "=", "null", ";", "return", "$", "this", ";", "}", "if", "(", "!", "is_string", "(", "$", "id", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Queue ID must be a string'", ")", ";", "}", "$", "this", "->", "queueId", "=", "$", "id", ";", "return", "$", "this", ";", "}" ]
Set the queue's ID. @param string|null $id The unique queue identifier. @throws InvalidArgumentException If the ID isn't a string. @return self
[ "Set", "the", "queue", "s", "ID", "." ]
90c47581cd35fbb554eca513f909171a70325b44
https://github.com/locomotivemtl/charcoal-queue/blob/90c47581cd35fbb554eca513f909171a70325b44/src/Charcoal/Queue/QueueableTrait.php#L26-L42
train
zewadesign/framework
Zewa/App.php
App.initialize
public function initialize() { $request = $this->router->getAction(); $isRouteCallback = $this->processRequestParameters($request); $this->start($isRouteCallback); return $this; }
php
public function initialize() { $request = $this->router->getAction(); $isRouteCallback = $this->processRequestParameters($request); $this->start($isRouteCallback); return $this; }
[ "public", "function", "initialize", "(", ")", "{", "$", "request", "=", "$", "this", "->", "router", "->", "getAction", "(", ")", ";", "$", "isRouteCallback", "=", "$", "this", "->", "processRequestParameters", "(", "$", "request", ")", ";", "$", "this", "->", "start", "(", "$", "isRouteCallback", ")", ";", "return", "$", "this", ";", "}" ]
Calls the proper shell for app execution @access private
[ "Calls", "the", "proper", "shell", "for", "app", "execution" ]
be74e41c674ac2c2ef924752ed310cfbaafe33b8
https://github.com/zewadesign/framework/blob/be74e41c674ac2c2ef924752ed310cfbaafe33b8/Zewa/App.php#L71-L80
train
19ft/NFHtmlToText
HtmlToText.php
HtmlToText.processNode
protected function processNode($node) { if ($node instanceof DOMDocumentType) { return ''; } if ($node instanceof DOMText) { // return the plain text return preg_replace("/\\s+/im", " ", $node->wholeText); } $tag = strtolower($node->nodeName); if (in_array($tag, $this->ignoredBlockTags)) { return ''; } $lastTag = $this->lastTagName($node); $nextTag = $this->nextTagName($node); $output = ''; if ($tag == 'ol') { // ordered lists start from one $this->liCharacter = 1; } if ($tag == 'ul') { // unsigned lists start with a bullet point $this->liCharacter = $this->bulletSymbol; } if ($tag == 'li') { if ($lastTag == 'li') { // add a new line, but not for the first item $output .= "\n"; } // add the list character and increment if an OL $output .= $this->liCharacter . ' '; if (is_int($this->liCharacter)) { $this->liCharacter++; } } // processes child nodes: if ($node->childNodes) { $numberOfNodes = $node->childNodes->length; for ($i = 0; $i < $numberOfNodes; $i++) { $childNode = $node->childNodes->item($i); $output .= $this->processNode($childNode); } } // add new lines if (in_array($tag, $this->doubleNewLineTags)){ $output = trim($output); $output .= "\n\n"; } if (in_array($tag, $this->newLineTags)) { $output = trim($output); $output .= "\n"; } return $output; }
php
protected function processNode($node) { if ($node instanceof DOMDocumentType) { return ''; } if ($node instanceof DOMText) { // return the plain text return preg_replace("/\\s+/im", " ", $node->wholeText); } $tag = strtolower($node->nodeName); if (in_array($tag, $this->ignoredBlockTags)) { return ''; } $lastTag = $this->lastTagName($node); $nextTag = $this->nextTagName($node); $output = ''; if ($tag == 'ol') { // ordered lists start from one $this->liCharacter = 1; } if ($tag == 'ul') { // unsigned lists start with a bullet point $this->liCharacter = $this->bulletSymbol; } if ($tag == 'li') { if ($lastTag == 'li') { // add a new line, but not for the first item $output .= "\n"; } // add the list character and increment if an OL $output .= $this->liCharacter . ' '; if (is_int($this->liCharacter)) { $this->liCharacter++; } } // processes child nodes: if ($node->childNodes) { $numberOfNodes = $node->childNodes->length; for ($i = 0; $i < $numberOfNodes; $i++) { $childNode = $node->childNodes->item($i); $output .= $this->processNode($childNode); } } // add new lines if (in_array($tag, $this->doubleNewLineTags)){ $output = trim($output); $output .= "\n\n"; } if (in_array($tag, $this->newLineTags)) { $output = trim($output); $output .= "\n"; } return $output; }
[ "protected", "function", "processNode", "(", "$", "node", ")", "{", "if", "(", "$", "node", "instanceof", "DOMDocumentType", ")", "{", "return", "''", ";", "}", "if", "(", "$", "node", "instanceof", "DOMText", ")", "{", "// return the plain text", "return", "preg_replace", "(", "\"/\\\\s+/im\"", ",", "\" \"", ",", "$", "node", "->", "wholeText", ")", ";", "}", "$", "tag", "=", "strtolower", "(", "$", "node", "->", "nodeName", ")", ";", "if", "(", "in_array", "(", "$", "tag", ",", "$", "this", "->", "ignoredBlockTags", ")", ")", "{", "return", "''", ";", "}", "$", "lastTag", "=", "$", "this", "->", "lastTagName", "(", "$", "node", ")", ";", "$", "nextTag", "=", "$", "this", "->", "nextTagName", "(", "$", "node", ")", ";", "$", "output", "=", "''", ";", "if", "(", "$", "tag", "==", "'ol'", ")", "{", "// ordered lists start from one", "$", "this", "->", "liCharacter", "=", "1", ";", "}", "if", "(", "$", "tag", "==", "'ul'", ")", "{", "// unsigned lists start with a bullet point", "$", "this", "->", "liCharacter", "=", "$", "this", "->", "bulletSymbol", ";", "}", "if", "(", "$", "tag", "==", "'li'", ")", "{", "if", "(", "$", "lastTag", "==", "'li'", ")", "{", "// add a new line, but not for the first item", "$", "output", ".=", "\"\\n\"", ";", "}", "// add the list character and increment if an OL", "$", "output", ".=", "$", "this", "->", "liCharacter", ".", "' '", ";", "if", "(", "is_int", "(", "$", "this", "->", "liCharacter", ")", ")", "{", "$", "this", "->", "liCharacter", "++", ";", "}", "}", "// processes child nodes:", "if", "(", "$", "node", "->", "childNodes", ")", "{", "$", "numberOfNodes", "=", "$", "node", "->", "childNodes", "->", "length", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "numberOfNodes", ";", "$", "i", "++", ")", "{", "$", "childNode", "=", "$", "node", "->", "childNodes", "->", "item", "(", "$", "i", ")", ";", "$", "output", ".=", "$", "this", "->", "processNode", "(", "$", "childNode", ")", ";", "}", "}", "// add new lines", "if", "(", "in_array", "(", "$", "tag", ",", "$", "this", "->", "doubleNewLineTags", ")", ")", "{", "$", "output", "=", "trim", "(", "$", "output", ")", ";", "$", "output", ".=", "\"\\n\\n\"", ";", "}", "if", "(", "in_array", "(", "$", "tag", ",", "$", "this", "->", "newLineTags", ")", ")", "{", "$", "output", "=", "trim", "(", "$", "output", ")", ";", "$", "output", ".=", "\"\\n\"", ";", "}", "return", "$", "output", ";", "}" ]
Recursively called method that creates the plain text required for a give tag. NOTE: This is rather simplistic and only handles reasonably well structured block tags along with OL and UL lists. All inline tags are ignored. @param DOMNode $node DOM node to process @return string plain text representation of the node
[ "Recursively", "called", "method", "that", "creates", "the", "plain", "text", "required", "for", "a", "give", "tag", "." ]
d7be8382d23c1ba5960b22f487c9915d4f4ebb3c
https://github.com/19ft/NFHtmlToText/blob/d7be8382d23c1ba5960b22f487c9915d4f4ebb3c/HtmlToText.php#L102-L165
train
19ft/NFHtmlToText
HtmlToText.php
HtmlToText.lastTagName
protected function lastTagName($node) { $lastNode = $node->previousSibling; while ($lastNode != null) { if ($lastNode instanceof DOMElement) { break; } $lastNode = $lastNode->previousSibling; } $lastTag = ''; if ($lastNode instanceof DOMElement && $lastNode != null) { $lastTag = strtolower($lastNode->nodeName); } return $lastTag; }
php
protected function lastTagName($node) { $lastNode = $node->previousSibling; while ($lastNode != null) { if ($lastNode instanceof DOMElement) { break; } $lastNode = $lastNode->previousSibling; } $lastTag = ''; if ($lastNode instanceof DOMElement && $lastNode != null) { $lastTag = strtolower($lastNode->nodeName); } return $lastTag; }
[ "protected", "function", "lastTagName", "(", "$", "node", ")", "{", "$", "lastNode", "=", "$", "node", "->", "previousSibling", ";", "while", "(", "$", "lastNode", "!=", "null", ")", "{", "if", "(", "$", "lastNode", "instanceof", "DOMElement", ")", "{", "break", ";", "}", "$", "lastNode", "=", "$", "lastNode", "->", "previousSibling", ";", "}", "$", "lastTag", "=", "''", ";", "if", "(", "$", "lastNode", "instanceof", "DOMElement", "&&", "$", "lastNode", "!=", "null", ")", "{", "$", "lastTag", "=", "strtolower", "(", "$", "lastNode", "->", "nodeName", ")", ";", "}", "return", "$", "lastTag", ";", "}" ]
Find the previous sibling tag name for this node @param DOMNode $node DOM node @return string tag name
[ "Find", "the", "previous", "sibling", "tag", "name", "for", "this", "node" ]
d7be8382d23c1ba5960b22f487c9915d4f4ebb3c
https://github.com/19ft/NFHtmlToText/blob/d7be8382d23c1ba5960b22f487c9915d4f4ebb3c/HtmlToText.php#L173-L188
train
19ft/NFHtmlToText
HtmlToText.php
HtmlToText.nextTagName
protected function nextTagName($node) { $nextNode = $node->nextSibling; while ($nextNode != null) { if ($nextNode instanceof DOMElement) { break; } $nextNode = $nextNode->nextSibling; } $nextTag = ''; if ($nextNode instanceof DOMElement && $nextNode != null) { $nextTag = strtolower($nextNode->nodeName); } return $nextTag; }
php
protected function nextTagName($node) { $nextNode = $node->nextSibling; while ($nextNode != null) { if ($nextNode instanceof DOMElement) { break; } $nextNode = $nextNode->nextSibling; } $nextTag = ''; if ($nextNode instanceof DOMElement && $nextNode != null) { $nextTag = strtolower($nextNode->nodeName); } return $nextTag; }
[ "protected", "function", "nextTagName", "(", "$", "node", ")", "{", "$", "nextNode", "=", "$", "node", "->", "nextSibling", ";", "while", "(", "$", "nextNode", "!=", "null", ")", "{", "if", "(", "$", "nextNode", "instanceof", "DOMElement", ")", "{", "break", ";", "}", "$", "nextNode", "=", "$", "nextNode", "->", "nextSibling", ";", "}", "$", "nextTag", "=", "''", ";", "if", "(", "$", "nextNode", "instanceof", "DOMElement", "&&", "$", "nextNode", "!=", "null", ")", "{", "$", "nextTag", "=", "strtolower", "(", "$", "nextNode", "->", "nodeName", ")", ";", "}", "return", "$", "nextTag", ";", "}" ]
Find the next sibling tag name for this node @param DOMNode $node DOM node @return string tag name
[ "Find", "the", "next", "sibling", "tag", "name", "for", "this", "node" ]
d7be8382d23c1ba5960b22f487c9915d4f4ebb3c
https://github.com/19ft/NFHtmlToText/blob/d7be8382d23c1ba5960b22f487c9915d4f4ebb3c/HtmlToText.php#L196-L211
train
Vectrex/vxPHP
src/Security/Csrf/CsrfTokenSessionStorage.php
CsrfTokenSessionStorage.getToken
public function getToken($tokenId) { $sessionToken = $this->sessionDataBag->get($this->namespace . '/' . $tokenId); if(!$sessionToken) { throw new CsrfTokenException(sprintf("CSRF token with id '%s' not found.", $tokenId)); } return $sessionToken; }
php
public function getToken($tokenId) { $sessionToken = $this->sessionDataBag->get($this->namespace . '/' . $tokenId); if(!$sessionToken) { throw new CsrfTokenException(sprintf("CSRF token with id '%s' not found.", $tokenId)); } return $sessionToken; }
[ "public", "function", "getToken", "(", "$", "tokenId", ")", "{", "$", "sessionToken", "=", "$", "this", "->", "sessionDataBag", "->", "get", "(", "$", "this", "->", "namespace", ".", "'/'", ".", "$", "tokenId", ")", ";", "if", "(", "!", "$", "sessionToken", ")", "{", "throw", "new", "CsrfTokenException", "(", "sprintf", "(", "\"CSRF token with id '%s' not found.\"", ",", "$", "tokenId", ")", ")", ";", "}", "return", "$", "sessionToken", ";", "}" ]
retrieves token stored in session under namespaced token id @param string $tokenId @return string @throws CsrfTokenException
[ "retrieves", "token", "stored", "in", "session", "under", "namespaced", "token", "id" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Security/Csrf/CsrfTokenSessionStorage.php#L69-L78
train
Vectrex/vxPHP
src/Security/Csrf/CsrfTokenSessionStorage.php
CsrfTokenSessionStorage.setToken
public function setToken($tokenId, CsrfToken $token) { if(!trim((string) $tokenId)) { throw new \InvalidArgumentException('Invalid token id.'); } $this->sessionDataBag->set( $this->namespace . '/' . $tokenId, $token ); }
php
public function setToken($tokenId, CsrfToken $token) { if(!trim((string) $tokenId)) { throw new \InvalidArgumentException('Invalid token id.'); } $this->sessionDataBag->set( $this->namespace . '/' . $tokenId, $token ); }
[ "public", "function", "setToken", "(", "$", "tokenId", ",", "CsrfToken", "$", "token", ")", "{", "if", "(", "!", "trim", "(", "(", "string", ")", "$", "tokenId", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid token id.'", ")", ";", "}", "$", "this", "->", "sessionDataBag", "->", "set", "(", "$", "this", "->", "namespace", ".", "'/'", ".", "$", "tokenId", ",", "$", "token", ")", ";", "}" ]
store token under namespaced token id in session @param string $tokenId @param CsrfToken $token @throws \InvalidArgumentException
[ "store", "token", "under", "namespaced", "token", "id", "in", "session" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Security/Csrf/CsrfTokenSessionStorage.php#L88-L98
train
MinyFramework/Miny-Core
src/Shutdown/ShutdownService.php
ShutdownService.register
public function register(callable $callback, $priority = null) { $priority = $this->getPriority($priority); if (!isset($this->callbacks[$priority])) { $this->callbacks[$priority] = []; } $this->callbacks[$priority][] = $callback; $this->lowestPriority = max($priority, $this->lowestPriority); }
php
public function register(callable $callback, $priority = null) { $priority = $this->getPriority($priority); if (!isset($this->callbacks[$priority])) { $this->callbacks[$priority] = []; } $this->callbacks[$priority][] = $callback; $this->lowestPriority = max($priority, $this->lowestPriority); }
[ "public", "function", "register", "(", "callable", "$", "callback", ",", "$", "priority", "=", "null", ")", "{", "$", "priority", "=", "$", "this", "->", "getPriority", "(", "$", "priority", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "callbacks", "[", "$", "priority", "]", ")", ")", "{", "$", "this", "->", "callbacks", "[", "$", "priority", "]", "=", "[", "]", ";", "}", "$", "this", "->", "callbacks", "[", "$", "priority", "]", "[", "]", "=", "$", "callback", ";", "$", "this", "->", "lowestPriority", "=", "max", "(", "$", "priority", ",", "$", "this", "->", "lowestPriority", ")", ";", "}" ]
Registers a callback to be called on shutdown. @param callable $callback @param null|int $priority The priority of the callback. Lowest number means higher priority. @throws \InvalidArgumentException
[ "Registers", "a", "callback", "to", "be", "called", "on", "shutdown", "." ]
a1bfe801a44a49cf01f16411cb4663473e9c827c
https://github.com/MinyFramework/Miny-Core/blob/a1bfe801a44a49cf01f16411cb4663473e9c827c/src/Shutdown/ShutdownService.php#L33-L41
train
Wedeto/HTTP
src/ProcessChain.php
ProcessChain.addProcessor
public function addProcessor(Processor $processor, int $precedence = ProcessChain::RUN_DEFAULT) { return $this->appendProcessor($processor, static::STAGE_PROCESS, $precedence); }
php
public function addProcessor(Processor $processor, int $precedence = ProcessChain::RUN_DEFAULT) { return $this->appendProcessor($processor, static::STAGE_PROCESS, $precedence); }
[ "public", "function", "addProcessor", "(", "Processor", "$", "processor", ",", "int", "$", "precedence", "=", "ProcessChain", "::", "RUN_DEFAULT", ")", "{", "return", "$", "this", "->", "appendProcessor", "(", "$", "processor", ",", "static", "::", "STAGE_PROCESS", ",", "$", "precedence", ")", ";", "}" ]
Add a processor to the chain in the PROCESS stage. Any operator in this stage is expected to produce a response. @param Processor $processor The processor to add @param int $precedence The precedence - the lower this value, the higher it will be put in the chain @return $this Provides fluent interface.
[ "Add", "a", "processor", "to", "the", "chain", "in", "the", "PROCESS", "stage", ".", "Any", "operator", "in", "this", "stage", "is", "expected", "to", "produce", "a", "response", "." ]
7318eff1b81a3c103c4263466d09b7f3593b70b9
https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/ProcessChain.php#L88-L91
train
Wedeto/HTTP
src/ProcessChain.php
ProcessChain.addPostProcessor
public function addPostProcessor(Processor $processor, int $precedence = ProcessChain::RUN_DEFAULT) { return $this->appendProcessor($processor, static::STAGE_POSTPROCESS, $precedence); }
php
public function addPostProcessor(Processor $processor, int $precedence = ProcessChain::RUN_DEFAULT) { return $this->appendProcessor($processor, static::STAGE_POSTPROCESS, $precedence); }
[ "public", "function", "addPostProcessor", "(", "Processor", "$", "processor", ",", "int", "$", "precedence", "=", "ProcessChain", "::", "RUN_DEFAULT", ")", "{", "return", "$", "this", "->", "appendProcessor", "(", "$", "processor", ",", "static", "::", "STAGE_POSTPROCESS", ",", "$", "precedence", ")", ";", "}" ]
Adds a post processor to the pipeline. A postprocessor is a filter that operates on the response rather than producing it. @param Processor $processor The Processor to add @param int $precedence The precedence - the lower this value, the higher it will be put in the chain @return $this Provides fluent interface
[ "Adds", "a", "post", "processor", "to", "the", "pipeline", ".", "A", "postprocessor", "is", "a", "filter", "that", "operates", "on", "the", "response", "rather", "than", "producing", "it", "." ]
7318eff1b81a3c103c4263466d09b7f3593b70b9
https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/ProcessChain.php#L101-L104
train
Wedeto/HTTP
src/ProcessChain.php
ProcessChain.appendProcessor
protected function appendProcessor(Processor $processor, int $stage, int $precedence = ProcessChain::RUN_DEFAULT) { $stage = WF::clamp($stage, static::STAGE_FILTER, static::STAGE_POSTPROCESS); $precedence = WF::clamp($precedence, static::RUN_FIRST, static::RUN_LAST); $this->processors[] = [ 'precedence' => $precedence, 'stage' => $stage, 'seq' => ++$this->seq, 'processor' => $processor ]; // Sort the processors, first on stage, then on precedence, finally on order of appending usort($this->processors, function ($l, $r) { if ($l['stage'] != $r['stage']) return $l['stage'] - $r['stage']; if ($l['precedence'] != $r['precedence']) return $l['precedence'] - $r['precedence']; return $l['seq'] - $r['seq']; }); return $this; }
php
protected function appendProcessor(Processor $processor, int $stage, int $precedence = ProcessChain::RUN_DEFAULT) { $stage = WF::clamp($stage, static::STAGE_FILTER, static::STAGE_POSTPROCESS); $precedence = WF::clamp($precedence, static::RUN_FIRST, static::RUN_LAST); $this->processors[] = [ 'precedence' => $precedence, 'stage' => $stage, 'seq' => ++$this->seq, 'processor' => $processor ]; // Sort the processors, first on stage, then on precedence, finally on order of appending usort($this->processors, function ($l, $r) { if ($l['stage'] != $r['stage']) return $l['stage'] - $r['stage']; if ($l['precedence'] != $r['precedence']) return $l['precedence'] - $r['precedence']; return $l['seq'] - $r['seq']; }); return $this; }
[ "protected", "function", "appendProcessor", "(", "Processor", "$", "processor", ",", "int", "$", "stage", ",", "int", "$", "precedence", "=", "ProcessChain", "::", "RUN_DEFAULT", ")", "{", "$", "stage", "=", "WF", "::", "clamp", "(", "$", "stage", ",", "static", "::", "STAGE_FILTER", ",", "static", "::", "STAGE_POSTPROCESS", ")", ";", "$", "precedence", "=", "WF", "::", "clamp", "(", "$", "precedence", ",", "static", "::", "RUN_FIRST", ",", "static", "::", "RUN_LAST", ")", ";", "$", "this", "->", "processors", "[", "]", "=", "[", "'precedence'", "=>", "$", "precedence", ",", "'stage'", "=>", "$", "stage", ",", "'seq'", "=>", "++", "$", "this", "->", "seq", ",", "'processor'", "=>", "$", "processor", "]", ";", "// Sort the processors, first on stage, then on precedence, finally on order of appending", "usort", "(", "$", "this", "->", "processors", ",", "function", "(", "$", "l", ",", "$", "r", ")", "{", "if", "(", "$", "l", "[", "'stage'", "]", "!=", "$", "r", "[", "'stage'", "]", ")", "return", "$", "l", "[", "'stage'", "]", "-", "$", "r", "[", "'stage'", "]", ";", "if", "(", "$", "l", "[", "'precedence'", "]", "!=", "$", "r", "[", "'precedence'", "]", ")", "return", "$", "l", "[", "'precedence'", "]", "-", "$", "r", "[", "'precedence'", "]", ";", "return", "$", "l", "[", "'seq'", "]", "-", "$", "r", "[", "'seq'", "]", ";", "}", ")", ";", "return", "$", "this", ";", "}" ]
Helper to add a processor to the pipeline @param Wedeto\HTTP\Processor $processor The processor to add @param int $stage The stage - STAGE_PREPROCESS, STAGE_PROCESS or STAGE_POSTPROCESS @param int $precedence The precedence of the processor - the lower, the sooner it will be placed in its stage. @return $this Provides fluent interface
[ "Helper", "to", "add", "a", "processor", "to", "the", "pipeline" ]
7318eff1b81a3c103c4263466d09b7f3593b70b9
https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/ProcessChain.php#L115-L135
train
Wedeto/HTTP
src/ProcessChain.php
ProcessChain.getProcessors
public function getProcessors(int $stage) { $list = []; foreach ($this->processors as $proc) { if ($proc['stage'] === $stage) $list[] = $proc['processor']; } return $list; }
php
public function getProcessors(int $stage) { $list = []; foreach ($this->processors as $proc) { if ($proc['stage'] === $stage) $list[] = $proc['processor']; } return $list; }
[ "public", "function", "getProcessors", "(", "int", "$", "stage", ")", "{", "$", "list", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "processors", "as", "$", "proc", ")", "{", "if", "(", "$", "proc", "[", "'stage'", "]", "===", "$", "stage", ")", "$", "list", "[", "]", "=", "$", "proc", "[", "'processor'", "]", ";", "}", "return", "$", "list", ";", "}" ]
Get a list of processor for a stage @param int $stage The stage for which to get a list of processor @return array The list of processor for the stage
[ "Get", "a", "list", "of", "processor", "for", "a", "stage" ]
7318eff1b81a3c103c4263466d09b7f3593b70b9
https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/ProcessChain.php#L142-L151
train
Wedeto/HTTP
src/ProcessChain.php
ProcessChain.process
public function process(Request $request) { $result = new Result; $stage = static::STAGE_FILTER; foreach ($this->processors as $processor) { if ($processor['stage'] < $stage) continue; $stage = $processor['stage']; $processor = $processor['processor']; try { $processor->process($request, $result); } catch (Response\Response $response) { $result->setResponse($response); $stage = static::STAGE_POSTPROCESS; } } return $result; }
php
public function process(Request $request) { $result = new Result; $stage = static::STAGE_FILTER; foreach ($this->processors as $processor) { if ($processor['stage'] < $stage) continue; $stage = $processor['stage']; $processor = $processor['processor']; try { $processor->process($request, $result); } catch (Response\Response $response) { $result->setResponse($response); $stage = static::STAGE_POSTPROCESS; } } return $result; }
[ "public", "function", "process", "(", "Request", "$", "request", ")", "{", "$", "result", "=", "new", "Result", ";", "$", "stage", "=", "static", "::", "STAGE_FILTER", ";", "foreach", "(", "$", "this", "->", "processors", "as", "$", "processor", ")", "{", "if", "(", "$", "processor", "[", "'stage'", "]", "<", "$", "stage", ")", "continue", ";", "$", "stage", "=", "$", "processor", "[", "'stage'", "]", ";", "$", "processor", "=", "$", "processor", "[", "'processor'", "]", ";", "try", "{", "$", "processor", "->", "process", "(", "$", "request", ",", "$", "result", ")", ";", "}", "catch", "(", "Response", "\\", "Response", "$", "response", ")", "{", "$", "result", "->", "setResponse", "(", "$", "response", ")", ";", "$", "stage", "=", "static", "::", "STAGE_POSTPROCESS", ";", "}", "}", "return", "$", "result", ";", "}" ]
Process a request - put it through the pipeline and return the response. The request will be routed through each processor until one throws an exception at which point the stage is advanced to the post processing stage. @param Request $request The request to process @return Result The produced response
[ "Process", "a", "request", "-", "put", "it", "through", "the", "pipeline", "and", "return", "the", "response", ".", "The", "request", "will", "be", "routed", "through", "each", "processor", "until", "one", "throws", "an", "exception", "at", "which", "point", "the", "stage", "is", "advanced", "to", "the", "post", "processing", "stage", "." ]
7318eff1b81a3c103c4263466d09b7f3593b70b9
https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/ProcessChain.php#L161-L186
train
judus/minimal-http
src/Request.php
Request.fetchRequestMethod
public function fetchRequestMethod($server = null) { $server || $server = $this->_SERVER; if (isset($_POST['_method'])) { if ( strtoupper($_POST['_method']) == 'PUT' || strtoupper($_POST['_method']) == 'PATCH' || strtoupper($_POST['_method']) == 'DELETE' ) { return strtoupper($_POST['_method']); } } if (php_sapi_name() == 'cli' || defined('STDIN')) { return 'CLI'; } return $server['REQUEST_METHOD']; }
php
public function fetchRequestMethod($server = null) { $server || $server = $this->_SERVER; if (isset($_POST['_method'])) { if ( strtoupper($_POST['_method']) == 'PUT' || strtoupper($_POST['_method']) == 'PATCH' || strtoupper($_POST['_method']) == 'DELETE' ) { return strtoupper($_POST['_method']); } } if (php_sapi_name() == 'cli' || defined('STDIN')) { return 'CLI'; } return $server['REQUEST_METHOD']; }
[ "public", "function", "fetchRequestMethod", "(", "$", "server", "=", "null", ")", "{", "$", "server", "||", "$", "server", "=", "$", "this", "->", "_SERVER", ";", "if", "(", "isset", "(", "$", "_POST", "[", "'_method'", "]", ")", ")", "{", "if", "(", "strtoupper", "(", "$", "_POST", "[", "'_method'", "]", ")", "==", "'PUT'", "||", "strtoupper", "(", "$", "_POST", "[", "'_method'", "]", ")", "==", "'PATCH'", "||", "strtoupper", "(", "$", "_POST", "[", "'_method'", "]", ")", "==", "'DELETE'", ")", "{", "return", "strtoupper", "(", "$", "_POST", "[", "'_method'", "]", ")", ";", "}", "}", "if", "(", "php_sapi_name", "(", ")", "==", "'cli'", "||", "defined", "(", "'STDIN'", ")", ")", "{", "return", "'CLI'", ";", "}", "return", "$", "server", "[", "'REQUEST_METHOD'", "]", ";", "}" ]
Fetch the http method
[ "Fetch", "the", "http", "method" ]
13c49e1350488acea8acf44ab5ed7796a39a9f1a
https://github.com/judus/minimal-http/blob/13c49e1350488acea8acf44ab5ed7796a39a9f1a/src/Request.php#L496-L515
train
judus/minimal-http
src/Request.php
Request.parseCliArgs
public function parseCliArgs($server = null) { $server || $server = $this->_SERVER; if (!isset($server['argv'])) { throw new \Exception('$_SERVER["argv"] is not available'); } $args = array_slice($server['argv'], 1); return $args ? '/' . implode('/', $args) : ''; }
php
public function parseCliArgs($server = null) { $server || $server = $this->_SERVER; if (!isset($server['argv'])) { throw new \Exception('$_SERVER["argv"] is not available'); } $args = array_slice($server['argv'], 1); return $args ? '/' . implode('/', $args) : ''; }
[ "public", "function", "parseCliArgs", "(", "$", "server", "=", "null", ")", "{", "$", "server", "||", "$", "server", "=", "$", "this", "->", "_SERVER", ";", "if", "(", "!", "isset", "(", "$", "server", "[", "'argv'", "]", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'$_SERVER[\"argv\"] is not available'", ")", ";", "}", "$", "args", "=", "array_slice", "(", "$", "server", "[", "'argv'", "]", ",", "1", ")", ";", "return", "$", "args", "?", "'/'", ".", "implode", "(", "'/'", ",", "$", "args", ")", ":", "''", ";", "}" ]
Formats cli args like a uri @return string @throws \Exception
[ "Formats", "cli", "args", "like", "a", "uri" ]
13c49e1350488acea8acf44ab5ed7796a39a9f1a
https://github.com/judus/minimal-http/blob/13c49e1350488acea8acf44ab5ed7796a39a9f1a/src/Request.php#L552-L563
train
judus/minimal-http
src/Request.php
Request.explodeSegments
public function explodeSegments($uri) { $segments = []; $pattern = "|/*(.+?)/*$|"; $elements = explode("/", preg_replace($pattern, "\\1", $uri)); foreach ($elements as $val) { $val = trim($this->filterUri($val)); empty($val) || $segments[] = $val; } return $segments; }
php
public function explodeSegments($uri) { $segments = []; $pattern = "|/*(.+?)/*$|"; $elements = explode("/", preg_replace($pattern, "\\1", $uri)); foreach ($elements as $val) { $val = trim($this->filterUri($val)); empty($val) || $segments[] = $val; } return $segments; }
[ "public", "function", "explodeSegments", "(", "$", "uri", ")", "{", "$", "segments", "=", "[", "]", ";", "$", "pattern", "=", "\"|/*(.+?)/*$|\"", ";", "$", "elements", "=", "explode", "(", "\"/\"", ",", "preg_replace", "(", "$", "pattern", ",", "\"\\\\1\"", ",", "$", "uri", ")", ")", ";", "foreach", "(", "$", "elements", "as", "$", "val", ")", "{", "$", "val", "=", "trim", "(", "$", "this", "->", "filterUri", "(", "$", "val", ")", ")", ";", "empty", "(", "$", "val", ")", "||", "$", "segments", "[", "]", "=", "$", "val", ";", "}", "return", "$", "segments", ";", "}" ]
Explodes the uri string
[ "Explodes", "the", "uri", "string" ]
13c49e1350488acea8acf44ab5ed7796a39a9f1a
https://github.com/judus/minimal-http/blob/13c49e1350488acea8acf44ab5ed7796a39a9f1a/src/Request.php#L583-L596
train
jabernardo/lollipop-php
Library/System/File.php
File.write
static function write($filename, $contents, $overwriteExisting = true) { if (file_exists($filename) && self::isWritable($filename)) { if ($overwriteExisting) unlink($filename); } file_put_contents($filename, $contents); }
php
static function write($filename, $contents, $overwriteExisting = true) { if (file_exists($filename) && self::isWritable($filename)) { if ($overwriteExisting) unlink($filename); } file_put_contents($filename, $contents); }
[ "static", "function", "write", "(", "$", "filename", ",", "$", "contents", ",", "$", "overwriteExisting", "=", "true", ")", "{", "if", "(", "file_exists", "(", "$", "filename", ")", "&&", "self", "::", "isWritable", "(", "$", "filename", ")", ")", "{", "if", "(", "$", "overwriteExisting", ")", "unlink", "(", "$", "filename", ")", ";", "}", "file_put_contents", "(", "$", "filename", ",", "$", "contents", ")", ";", "}" ]
Create or updates file @param string $filename File to create or update @param string $contents Contents to write into file @param bool $overwriteExisting Overwrite existing file
[ "Create", "or", "updates", "file" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/System/File.php#L47-L53
train
jabernardo/lollipop-php
Library/System/File.php
File.read
static function read($filename) { if (file_exists($filename) && self::isReadable($filename)) { return file_get_contents($filename); } return NULL; }
php
static function read($filename) { if (file_exists($filename) && self::isReadable($filename)) { return file_get_contents($filename); } return NULL; }
[ "static", "function", "read", "(", "$", "filename", ")", "{", "if", "(", "file_exists", "(", "$", "filename", ")", "&&", "self", "::", "isReadable", "(", "$", "filename", ")", ")", "{", "return", "file_get_contents", "(", "$", "filename", ")", ";", "}", "return", "NULL", ";", "}" ]
Gets the contents of a file @param string $filename File to be read @return string
[ "Gets", "the", "contents", "of", "a", "file" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/System/File.php#L62-L68
train
jabernardo/lollipop-php
Library/System/File.php
File.rename
static function rename($src, $dest) { if (self::exists($dest)) { throw new \Lollipop\Exception\Runtime('File already exists: ' . $dest); } if (is_uploaded_file($src)) { return \move_uploaded_file($src, $dest); } return \rename($src, $dest); }
php
static function rename($src, $dest) { if (self::exists($dest)) { throw new \Lollipop\Exception\Runtime('File already exists: ' . $dest); } if (is_uploaded_file($src)) { return \move_uploaded_file($src, $dest); } return \rename($src, $dest); }
[ "static", "function", "rename", "(", "$", "src", ",", "$", "dest", ")", "{", "if", "(", "self", "::", "exists", "(", "$", "dest", ")", ")", "{", "throw", "new", "\\", "Lollipop", "\\", "Exception", "\\", "Runtime", "(", "'File already exists: '", ".", "$", "dest", ")", ";", "}", "if", "(", "is_uploaded_file", "(", "$", "src", ")", ")", "{", "return", "\\", "move_uploaded_file", "(", "$", "src", ",", "$", "dest", ")", ";", "}", "return", "\\", "rename", "(", "$", "src", ",", "$", "dest", ")", ";", "}" ]
Alias rename file @param string $src Source file @param string $dest Destination file @return int
[ "Alias", "rename", "file" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/System/File.php#L116-L126
train
ValkSystems/bootbuilder
src/bootbuilder/Controls/Control.php
Control.isValid
public function isValid() { if($this->isRequired()) { if($this->getValue() == null) return false; if($this->getValue() == "") return false; } return true; }
php
public function isValid() { if($this->isRequired()) { if($this->getValue() == null) return false; if($this->getValue() == "") return false; } return true; }
[ "public", "function", "isValid", "(", ")", "{", "if", "(", "$", "this", "->", "isRequired", "(", ")", ")", "{", "if", "(", "$", "this", "->", "getValue", "(", ")", "==", "null", ")", "return", "false", ";", "if", "(", "$", "this", "->", "getValue", "(", ")", "==", "\"\"", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Validate value of control @return boolean validation successfully?
[ "Validate", "value", "of", "control" ]
7601a403f42eba47ce4cf02a3c852d5196b1d860
https://github.com/ValkSystems/bootbuilder/blob/7601a403f42eba47ce4cf02a3c852d5196b1d860/src/bootbuilder/Controls/Control.php#L227-L233
train
ValkSystems/bootbuilder
src/bootbuilder/Controls/Control.php
Control.getCompiledAttributes
protected function getCompiledAttributes($prependClass = "", $skipValue = false) { $attrs = ""; if($this->id) $attrs .= " id='$this->id'"; $attrs .= " class='$prependClass $this->class'"; if($this->name) $attrs .= " name='$this->name'"; if($this->placeholder) $attrs .= " placeholder='$this->placeholder'"; if($this->value && !$skipValue) $attrs .= " value='$this->value'"; if($this->disabled === true) $attrs .= " disabled"; if($this->readonly === true) $attrs .= " readonly"; if($this->required === true) $attrs .= " required"; // Trim and return the compiled attributes return rtrim(ltrim($attrs)); }
php
protected function getCompiledAttributes($prependClass = "", $skipValue = false) { $attrs = ""; if($this->id) $attrs .= " id='$this->id'"; $attrs .= " class='$prependClass $this->class'"; if($this->name) $attrs .= " name='$this->name'"; if($this->placeholder) $attrs .= " placeholder='$this->placeholder'"; if($this->value && !$skipValue) $attrs .= " value='$this->value'"; if($this->disabled === true) $attrs .= " disabled"; if($this->readonly === true) $attrs .= " readonly"; if($this->required === true) $attrs .= " required"; // Trim and return the compiled attributes return rtrim(ltrim($attrs)); }
[ "protected", "function", "getCompiledAttributes", "(", "$", "prependClass", "=", "\"\"", ",", "$", "skipValue", "=", "false", ")", "{", "$", "attrs", "=", "\"\"", ";", "if", "(", "$", "this", "->", "id", ")", "$", "attrs", ".=", "\" id='$this->id'\"", ";", "$", "attrs", ".=", "\" class='$prependClass $this->class'\"", ";", "if", "(", "$", "this", "->", "name", ")", "$", "attrs", ".=", "\" name='$this->name'\"", ";", "if", "(", "$", "this", "->", "placeholder", ")", "$", "attrs", ".=", "\" placeholder='$this->placeholder'\"", ";", "if", "(", "$", "this", "->", "value", "&&", "!", "$", "skipValue", ")", "$", "attrs", ".=", "\" value='$this->value'\"", ";", "if", "(", "$", "this", "->", "disabled", "===", "true", ")", "$", "attrs", ".=", "\" disabled\"", ";", "if", "(", "$", "this", "->", "readonly", "===", "true", ")", "$", "attrs", ".=", "\" readonly\"", ";", "if", "(", "$", "this", "->", "required", "===", "true", ")", "$", "attrs", ".=", "\" required\"", ";", "// Trim and return the compiled attributes", "return", "rtrim", "(", "ltrim", "(", "$", "attrs", ")", ")", ";", "}" ]
Compile the HTML attributes for using in the controls tag @param string $prependClass @param boolean $skipValue @return string Compiled attributes
[ "Compile", "the", "HTML", "attributes", "for", "using", "in", "the", "controls", "tag" ]
7601a403f42eba47ce4cf02a3c852d5196b1d860
https://github.com/ValkSystems/bootbuilder/blob/7601a403f42eba47ce4cf02a3c852d5196b1d860/src/bootbuilder/Controls/Control.php#L241-L254
train
anime-db/catalog-bundle
src/Controller/HomeController.php
HomeController.searchSimpleFormAction
public function searchSimpleFormAction() { $form = new SearchSimple($this->generateUrl('home_autocomplete_name')); return $this->render('AnimeDbCatalogBundle:Home:searchSimpleForm.html.twig', [ 'form' => $this->createForm($form)->createView(), ]); }
php
public function searchSimpleFormAction() { $form = new SearchSimple($this->generateUrl('home_autocomplete_name')); return $this->render('AnimeDbCatalogBundle:Home:searchSimpleForm.html.twig', [ 'form' => $this->createForm($form)->createView(), ]); }
[ "public", "function", "searchSimpleFormAction", "(", ")", "{", "$", "form", "=", "new", "SearchSimple", "(", "$", "this", "->", "generateUrl", "(", "'home_autocomplete_name'", ")", ")", ";", "return", "$", "this", "->", "render", "(", "'AnimeDbCatalogBundle:Home:searchSimpleForm.html.twig'", ",", "[", "'form'", "=>", "$", "this", "->", "createForm", "(", "$", "form", ")", "->", "createView", "(", ")", ",", "]", ")", ";", "}" ]
Search simple form. @return Response
[ "Search", "simple", "form", "." ]
631b6f92a654e91bee84f46218c52cf42bdb8606
https://github.com/anime-db/catalog-bundle/blob/631b6f92a654e91bee84f46218c52cf42bdb8606/src/Controller/HomeController.php#L110-L117
train
anime-db/catalog-bundle
src/Controller/HomeController.php
HomeController.autocompleteNameAction
public function autocompleteNameAction(Request $request) { /* @var $response JsonResponse */ $response = $this->getCacheTimeKeeper() ->getResponse('AnimeDbCatalogBundle:Item', -1, new JsonResponse()); // response was not modified for this request if ($response->isNotModified($request)) { return $response; } $term = mb_strtolower($request->get('term'), 'UTF8'); /* @var $service Manager */ $service = $this->get('anime_db.item.search'); $result = $service->searchByName($term, self::AUTOCOMPLETE_LIMIT); $list = []; /* @var $item Item */ foreach ($result as $item) { if (strpos(mb_strtolower($item->getName(), 'UTF8'), $term) === 0) { $list[] = $item->getName(); } else { /* @var $name Name */ foreach ($item->getNames() as $name) { if (strpos(mb_strtolower($name->getName(), 'UTF8'), $term) === 0) { $list[] = $name->getName(); break; } } } } return $response->setData($list); }
php
public function autocompleteNameAction(Request $request) { /* @var $response JsonResponse */ $response = $this->getCacheTimeKeeper() ->getResponse('AnimeDbCatalogBundle:Item', -1, new JsonResponse()); // response was not modified for this request if ($response->isNotModified($request)) { return $response; } $term = mb_strtolower($request->get('term'), 'UTF8'); /* @var $service Manager */ $service = $this->get('anime_db.item.search'); $result = $service->searchByName($term, self::AUTOCOMPLETE_LIMIT); $list = []; /* @var $item Item */ foreach ($result as $item) { if (strpos(mb_strtolower($item->getName(), 'UTF8'), $term) === 0) { $list[] = $item->getName(); } else { /* @var $name Name */ foreach ($item->getNames() as $name) { if (strpos(mb_strtolower($name->getName(), 'UTF8'), $term) === 0) { $list[] = $name->getName(); break; } } } } return $response->setData($list); }
[ "public", "function", "autocompleteNameAction", "(", "Request", "$", "request", ")", "{", "/* @var $response JsonResponse */", "$", "response", "=", "$", "this", "->", "getCacheTimeKeeper", "(", ")", "->", "getResponse", "(", "'AnimeDbCatalogBundle:Item'", ",", "-", "1", ",", "new", "JsonResponse", "(", ")", ")", ";", "// response was not modified for this request", "if", "(", "$", "response", "->", "isNotModified", "(", "$", "request", ")", ")", "{", "return", "$", "response", ";", "}", "$", "term", "=", "mb_strtolower", "(", "$", "request", "->", "get", "(", "'term'", ")", ",", "'UTF8'", ")", ";", "/* @var $service Manager */", "$", "service", "=", "$", "this", "->", "get", "(", "'anime_db.item.search'", ")", ";", "$", "result", "=", "$", "service", "->", "searchByName", "(", "$", "term", ",", "self", "::", "AUTOCOMPLETE_LIMIT", ")", ";", "$", "list", "=", "[", "]", ";", "/* @var $item Item */", "foreach", "(", "$", "result", "as", "$", "item", ")", "{", "if", "(", "strpos", "(", "mb_strtolower", "(", "$", "item", "->", "getName", "(", ")", ",", "'UTF8'", ")", ",", "$", "term", ")", "===", "0", ")", "{", "$", "list", "[", "]", "=", "$", "item", "->", "getName", "(", ")", ";", "}", "else", "{", "/* @var $name Name */", "foreach", "(", "$", "item", "->", "getNames", "(", ")", "as", "$", "name", ")", "{", "if", "(", "strpos", "(", "mb_strtolower", "(", "$", "name", "->", "getName", "(", ")", ",", "'UTF8'", ")", ",", "$", "term", ")", "===", "0", ")", "{", "$", "list", "[", "]", "=", "$", "name", "->", "getName", "(", ")", ";", "break", ";", "}", "}", "}", "}", "return", "$", "response", "->", "setData", "(", "$", "list", ")", ";", "}" ]
Autocomplete name. @param Request $request @return Response
[ "Autocomplete", "name", "." ]
631b6f92a654e91bee84f46218c52cf42bdb8606
https://github.com/anime-db/catalog-bundle/blob/631b6f92a654e91bee84f46218c52cf42bdb8606/src/Controller/HomeController.php#L126-L158
train
anime-db/catalog-bundle
src/Controller/HomeController.php
HomeController.searchAction
public function searchAction(Request $request) { $response = $this->getCacheTimeKeeper() ->getResponse(['AnimeDbCatalogBundle:Item', 'AnimeDbCatalogBundle:Storage']); // response was not modified for this request if ($response->isNotModified($request)) { return $response; } /* @var $form Form */ $form = $this->createForm('animedb_catalog_search', new SearchEntity())->handleRequest($request); $pagination = null; $result = ['list' => [], 'total' => 0]; if ($form->isValid()) { /* @var $controls ListControls */ $controls = $this->get('anime_db.item.list_controls'); // current page for paging $current_page = $request->get('page', 1); $current_page = $current_page > 1 ? $current_page : 1; // get items limit $limit = $controls->getLimit($request->query->all()); // do search $result = $this->get('anime_db.item.search')->search( $form->getData(), $limit, ($current_page - 1) * $limit, $controls->getSortColumn($request->query->all()), $controls->getSortDirection($request->query->all()) ); if ($limit) { // build pagination $that = $this; $query = $request->query->all(); unset($query['page']); $pagination = $this->get('anime_db.pagination') ->create(ceil($result['total'] / $limit), $current_page) ->setPageLink(function ($page) use ($that, $query) { return $that->generateUrl('home_search', array_merge($query, ['page' => $page])); }) ->setFirstPageLink($this->generateUrl('home_search', $query)) ->getView(); } } return $this->render('AnimeDbCatalogBundle:Home:search.html.twig', [ 'form' => $form->createView(), 'items' => $result['list'], 'total' => $result['total'], 'pagination' => $pagination, 'searched' => (bool) $request->query->count(), ], $response); }
php
public function searchAction(Request $request) { $response = $this->getCacheTimeKeeper() ->getResponse(['AnimeDbCatalogBundle:Item', 'AnimeDbCatalogBundle:Storage']); // response was not modified for this request if ($response->isNotModified($request)) { return $response; } /* @var $form Form */ $form = $this->createForm('animedb_catalog_search', new SearchEntity())->handleRequest($request); $pagination = null; $result = ['list' => [], 'total' => 0]; if ($form->isValid()) { /* @var $controls ListControls */ $controls = $this->get('anime_db.item.list_controls'); // current page for paging $current_page = $request->get('page', 1); $current_page = $current_page > 1 ? $current_page : 1; // get items limit $limit = $controls->getLimit($request->query->all()); // do search $result = $this->get('anime_db.item.search')->search( $form->getData(), $limit, ($current_page - 1) * $limit, $controls->getSortColumn($request->query->all()), $controls->getSortDirection($request->query->all()) ); if ($limit) { // build pagination $that = $this; $query = $request->query->all(); unset($query['page']); $pagination = $this->get('anime_db.pagination') ->create(ceil($result['total'] / $limit), $current_page) ->setPageLink(function ($page) use ($that, $query) { return $that->generateUrl('home_search', array_merge($query, ['page' => $page])); }) ->setFirstPageLink($this->generateUrl('home_search', $query)) ->getView(); } } return $this->render('AnimeDbCatalogBundle:Home:search.html.twig', [ 'form' => $form->createView(), 'items' => $result['list'], 'total' => $result['total'], 'pagination' => $pagination, 'searched' => (bool) $request->query->count(), ], $response); }
[ "public", "function", "searchAction", "(", "Request", "$", "request", ")", "{", "$", "response", "=", "$", "this", "->", "getCacheTimeKeeper", "(", ")", "->", "getResponse", "(", "[", "'AnimeDbCatalogBundle:Item'", ",", "'AnimeDbCatalogBundle:Storage'", "]", ")", ";", "// response was not modified for this request", "if", "(", "$", "response", "->", "isNotModified", "(", "$", "request", ")", ")", "{", "return", "$", "response", ";", "}", "/* @var $form Form */", "$", "form", "=", "$", "this", "->", "createForm", "(", "'animedb_catalog_search'", ",", "new", "SearchEntity", "(", ")", ")", "->", "handleRequest", "(", "$", "request", ")", ";", "$", "pagination", "=", "null", ";", "$", "result", "=", "[", "'list'", "=>", "[", "]", ",", "'total'", "=>", "0", "]", ";", "if", "(", "$", "form", "->", "isValid", "(", ")", ")", "{", "/* @var $controls ListControls */", "$", "controls", "=", "$", "this", "->", "get", "(", "'anime_db.item.list_controls'", ")", ";", "// current page for paging", "$", "current_page", "=", "$", "request", "->", "get", "(", "'page'", ",", "1", ")", ";", "$", "current_page", "=", "$", "current_page", ">", "1", "?", "$", "current_page", ":", "1", ";", "// get items limit", "$", "limit", "=", "$", "controls", "->", "getLimit", "(", "$", "request", "->", "query", "->", "all", "(", ")", ")", ";", "// do search", "$", "result", "=", "$", "this", "->", "get", "(", "'anime_db.item.search'", ")", "->", "search", "(", "$", "form", "->", "getData", "(", ")", ",", "$", "limit", ",", "(", "$", "current_page", "-", "1", ")", "*", "$", "limit", ",", "$", "controls", "->", "getSortColumn", "(", "$", "request", "->", "query", "->", "all", "(", ")", ")", ",", "$", "controls", "->", "getSortDirection", "(", "$", "request", "->", "query", "->", "all", "(", ")", ")", ")", ";", "if", "(", "$", "limit", ")", "{", "// build pagination", "$", "that", "=", "$", "this", ";", "$", "query", "=", "$", "request", "->", "query", "->", "all", "(", ")", ";", "unset", "(", "$", "query", "[", "'page'", "]", ")", ";", "$", "pagination", "=", "$", "this", "->", "get", "(", "'anime_db.pagination'", ")", "->", "create", "(", "ceil", "(", "$", "result", "[", "'total'", "]", "/", "$", "limit", ")", ",", "$", "current_page", ")", "->", "setPageLink", "(", "function", "(", "$", "page", ")", "use", "(", "$", "that", ",", "$", "query", ")", "{", "return", "$", "that", "->", "generateUrl", "(", "'home_search'", ",", "array_merge", "(", "$", "query", ",", "[", "'page'", "=>", "$", "page", "]", ")", ")", ";", "}", ")", "->", "setFirstPageLink", "(", "$", "this", "->", "generateUrl", "(", "'home_search'", ",", "$", "query", ")", ")", "->", "getView", "(", ")", ";", "}", "}", "return", "$", "this", "->", "render", "(", "'AnimeDbCatalogBundle:Home:search.html.twig'", ",", "[", "'form'", "=>", "$", "form", "->", "createView", "(", ")", ",", "'items'", "=>", "$", "result", "[", "'list'", "]", ",", "'total'", "=>", "$", "result", "[", "'total'", "]", ",", "'pagination'", "=>", "$", "pagination", ",", "'searched'", "=>", "(", "bool", ")", "$", "request", "->", "query", "->", "count", "(", ")", ",", "]", ",", "$", "response", ")", ";", "}" ]
Search item. @param Request $request @return Response
[ "Search", "item", "." ]
631b6f92a654e91bee84f46218c52cf42bdb8606
https://github.com/anime-db/catalog-bundle/blob/631b6f92a654e91bee84f46218c52cf42bdb8606/src/Controller/HomeController.php#L167-L223
train
anime-db/catalog-bundle
src/Controller/HomeController.php
HomeController.settingsAction
public function settingsAction(Request $request) { $response = $this->getCacheTimeKeeper()->getResponse(); // response was not modified for this request if ($response->isNotModified($request)) { return $response; } $entity = (new GeneralEntity()) ->setTaskScheduler($this->container->getParameter('task_scheduler.enabled')) ->setDefaultSearch($this->container->getParameter('anime_db.catalog.default_search')) ->setLocale($request->getLocale()); /* @var $chain ChainSearch */ $chain = $this->get('anime_db.plugin.search_fill'); /* @var $form Form */ $form = $this->createForm(new GeneralForm($chain), $entity) ->handleRequest($request); if ($form->isValid()) { // update params $this->get('anime_db.manipulator.parameters') ->set('task_scheduler.enabled', $entity->getTaskScheduler()); $this->get('anime_db.manipulator.parameters') ->set('anime_db.catalog.default_search', $entity->getDefaultSearch()); $this->get('anime_db.manipulator.parameters') ->set('locale', $entity->getLocale()); $this->get('anime_db.app.listener.request')->setLocale($request, $entity->getLocale()); $this->get('anime_db.cache_clearer')->clear(); return $this->redirect($this->generateUrl('home_settings')); } return $this->render('AnimeDbCatalogBundle:Home:settings.html.twig', [ 'form' => $form->createView(), ], $response); }
php
public function settingsAction(Request $request) { $response = $this->getCacheTimeKeeper()->getResponse(); // response was not modified for this request if ($response->isNotModified($request)) { return $response; } $entity = (new GeneralEntity()) ->setTaskScheduler($this->container->getParameter('task_scheduler.enabled')) ->setDefaultSearch($this->container->getParameter('anime_db.catalog.default_search')) ->setLocale($request->getLocale()); /* @var $chain ChainSearch */ $chain = $this->get('anime_db.plugin.search_fill'); /* @var $form Form */ $form = $this->createForm(new GeneralForm($chain), $entity) ->handleRequest($request); if ($form->isValid()) { // update params $this->get('anime_db.manipulator.parameters') ->set('task_scheduler.enabled', $entity->getTaskScheduler()); $this->get('anime_db.manipulator.parameters') ->set('anime_db.catalog.default_search', $entity->getDefaultSearch()); $this->get('anime_db.manipulator.parameters') ->set('locale', $entity->getLocale()); $this->get('anime_db.app.listener.request')->setLocale($request, $entity->getLocale()); $this->get('anime_db.cache_clearer')->clear(); return $this->redirect($this->generateUrl('home_settings')); } return $this->render('AnimeDbCatalogBundle:Home:settings.html.twig', [ 'form' => $form->createView(), ], $response); }
[ "public", "function", "settingsAction", "(", "Request", "$", "request", ")", "{", "$", "response", "=", "$", "this", "->", "getCacheTimeKeeper", "(", ")", "->", "getResponse", "(", ")", ";", "// response was not modified for this request", "if", "(", "$", "response", "->", "isNotModified", "(", "$", "request", ")", ")", "{", "return", "$", "response", ";", "}", "$", "entity", "=", "(", "new", "GeneralEntity", "(", ")", ")", "->", "setTaskScheduler", "(", "$", "this", "->", "container", "->", "getParameter", "(", "'task_scheduler.enabled'", ")", ")", "->", "setDefaultSearch", "(", "$", "this", "->", "container", "->", "getParameter", "(", "'anime_db.catalog.default_search'", ")", ")", "->", "setLocale", "(", "$", "request", "->", "getLocale", "(", ")", ")", ";", "/* @var $chain ChainSearch */", "$", "chain", "=", "$", "this", "->", "get", "(", "'anime_db.plugin.search_fill'", ")", ";", "/* @var $form Form */", "$", "form", "=", "$", "this", "->", "createForm", "(", "new", "GeneralForm", "(", "$", "chain", ")", ",", "$", "entity", ")", "->", "handleRequest", "(", "$", "request", ")", ";", "if", "(", "$", "form", "->", "isValid", "(", ")", ")", "{", "// update params", "$", "this", "->", "get", "(", "'anime_db.manipulator.parameters'", ")", "->", "set", "(", "'task_scheduler.enabled'", ",", "$", "entity", "->", "getTaskScheduler", "(", ")", ")", ";", "$", "this", "->", "get", "(", "'anime_db.manipulator.parameters'", ")", "->", "set", "(", "'anime_db.catalog.default_search'", ",", "$", "entity", "->", "getDefaultSearch", "(", ")", ")", ";", "$", "this", "->", "get", "(", "'anime_db.manipulator.parameters'", ")", "->", "set", "(", "'locale'", ",", "$", "entity", "->", "getLocale", "(", ")", ")", ";", "$", "this", "->", "get", "(", "'anime_db.app.listener.request'", ")", "->", "setLocale", "(", "$", "request", ",", "$", "entity", "->", "getLocale", "(", ")", ")", ";", "$", "this", "->", "get", "(", "'anime_db.cache_clearer'", ")", "->", "clear", "(", ")", ";", "return", "$", "this", "->", "redirect", "(", "$", "this", "->", "generateUrl", "(", "'home_settings'", ")", ")", ";", "}", "return", "$", "this", "->", "render", "(", "'AnimeDbCatalogBundle:Home:settings.html.twig'", ",", "[", "'form'", "=>", "$", "form", "->", "createView", "(", ")", ",", "]", ",", "$", "response", ")", ";", "}" ]
General settings. @param Request $request @return Response
[ "General", "settings", "." ]
631b6f92a654e91bee84f46218c52cf42bdb8606
https://github.com/anime-db/catalog-bundle/blob/631b6f92a654e91bee84f46218c52cf42bdb8606/src/Controller/HomeController.php#L232-L268
train
FusePump/cli.php
lib/FusePump/Cli/Logger.php
Logger.log
public static function log($message, $options = array()) { if (array_key_exists('inputs', $options)) { $inputs = $options['inputs']; } else { $inputs = array( self::getTimestamp(), 'LOG', self::getFilename(), self::getLineNumber() ); } if (!array_key_exists('output', $options)) { $options['output'] = 'STDOUT'; } if (array_key_exists('format', $options)) { array_unshift($inputs, $options['format']); } else { array_unshift($inputs, self::$format); } $inputs[] = $message; $logMessage = self::getLogMessage($inputs); if (array_key_exists('colour', $options) && !empty($options['colour'])) { self::out($logMessage, $options['colour'], $options['output']); } else { self::out($logMessage, false, $options['output']); } }
php
public static function log($message, $options = array()) { if (array_key_exists('inputs', $options)) { $inputs = $options['inputs']; } else { $inputs = array( self::getTimestamp(), 'LOG', self::getFilename(), self::getLineNumber() ); } if (!array_key_exists('output', $options)) { $options['output'] = 'STDOUT'; } if (array_key_exists('format', $options)) { array_unshift($inputs, $options['format']); } else { array_unshift($inputs, self::$format); } $inputs[] = $message; $logMessage = self::getLogMessage($inputs); if (array_key_exists('colour', $options) && !empty($options['colour'])) { self::out($logMessage, $options['colour'], $options['output']); } else { self::out($logMessage, false, $options['output']); } }
[ "public", "static", "function", "log", "(", "$", "message", ",", "$", "options", "=", "array", "(", ")", ")", "{", "if", "(", "array_key_exists", "(", "'inputs'", ",", "$", "options", ")", ")", "{", "$", "inputs", "=", "$", "options", "[", "'inputs'", "]", ";", "}", "else", "{", "$", "inputs", "=", "array", "(", "self", "::", "getTimestamp", "(", ")", ",", "'LOG'", ",", "self", "::", "getFilename", "(", ")", ",", "self", "::", "getLineNumber", "(", ")", ")", ";", "}", "if", "(", "!", "array_key_exists", "(", "'output'", ",", "$", "options", ")", ")", "{", "$", "options", "[", "'output'", "]", "=", "'STDOUT'", ";", "}", "if", "(", "array_key_exists", "(", "'format'", ",", "$", "options", ")", ")", "{", "array_unshift", "(", "$", "inputs", ",", "$", "options", "[", "'format'", "]", ")", ";", "}", "else", "{", "array_unshift", "(", "$", "inputs", ",", "self", "::", "$", "format", ")", ";", "}", "$", "inputs", "[", "]", "=", "$", "message", ";", "$", "logMessage", "=", "self", "::", "getLogMessage", "(", "$", "inputs", ")", ";", "if", "(", "array_key_exists", "(", "'colour'", ",", "$", "options", ")", "&&", "!", "empty", "(", "$", "options", "[", "'colour'", "]", ")", ")", "{", "self", "::", "out", "(", "$", "logMessage", ",", "$", "options", "[", "'colour'", "]", ",", "$", "options", "[", "'output'", "]", ")", ";", "}", "else", "{", "self", "::", "out", "(", "$", "logMessage", ",", "false", ",", "$", "options", "[", "'output'", "]", ")", ";", "}", "}" ]
Output log message @param string $message @param array $options @static
[ "Output", "log", "message" ]
2cc92f09ce7b2f73d5cbc09f5ae4f31f3f9ae3b4
https://github.com/FusePump/cli.php/blob/2cc92f09ce7b2f73d5cbc09f5ae4f31f3f9ae3b4/lib/FusePump/Cli/Logger.php#L33-L64
train
FusePump/cli.php
lib/FusePump/Cli/Logger.php
Logger.warn
public static function warn($message, $options = array()) { $options['inputs'] = array( self::getTimestamp(), 'WARN', self::getFilename(), self::getLineNumber() ); self::log($message, $options); }
php
public static function warn($message, $options = array()) { $options['inputs'] = array( self::getTimestamp(), 'WARN', self::getFilename(), self::getLineNumber() ); self::log($message, $options); }
[ "public", "static", "function", "warn", "(", "$", "message", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "options", "[", "'inputs'", "]", "=", "array", "(", "self", "::", "getTimestamp", "(", ")", ",", "'WARN'", ",", "self", "::", "getFilename", "(", ")", ",", "self", "::", "getLineNumber", "(", ")", ")", ";", "self", "::", "log", "(", "$", "message", ",", "$", "options", ")", ";", "}" ]
Output warn message @param string $message @param array $options @static
[ "Output", "warn", "message" ]
2cc92f09ce7b2f73d5cbc09f5ae4f31f3f9ae3b4
https://github.com/FusePump/cli.php/blob/2cc92f09ce7b2f73d5cbc09f5ae4f31f3f9ae3b4/lib/FusePump/Cli/Logger.php#L95-L104
train
wobblecode/WobbleCodeUserBundle
Manager/UserManager.php
UserManager.createUserFromOAuth
public function createUserFromOAuth($data) { $user = $this->createUser(); $user->setAuthDataByProvider($data['provider'], ['id' => $data['id'], 'token' => $data['token']]); $user->setAuthProvider($data['provider']); $user->setFirstAuthProvider($data['provider']); $user->setUsername($data['email']); $user->setEmail($data['email']); $user->setPassword('none'); $user->setEnabled(true); $user->setContact(new Contact); return $user; }
php
public function createUserFromOAuth($data) { $user = $this->createUser(); $user->setAuthDataByProvider($data['provider'], ['id' => $data['id'], 'token' => $data['token']]); $user->setAuthProvider($data['provider']); $user->setFirstAuthProvider($data['provider']); $user->setUsername($data['email']); $user->setEmail($data['email']); $user->setPassword('none'); $user->setEnabled(true); $user->setContact(new Contact); return $user; }
[ "public", "function", "createUserFromOAuth", "(", "$", "data", ")", "{", "$", "user", "=", "$", "this", "->", "createUser", "(", ")", ";", "$", "user", "->", "setAuthDataByProvider", "(", "$", "data", "[", "'provider'", "]", ",", "[", "'id'", "=>", "$", "data", "[", "'id'", "]", ",", "'token'", "=>", "$", "data", "[", "'token'", "]", "]", ")", ";", "$", "user", "->", "setAuthProvider", "(", "$", "data", "[", "'provider'", "]", ")", ";", "$", "user", "->", "setFirstAuthProvider", "(", "$", "data", "[", "'provider'", "]", ")", ";", "$", "user", "->", "setUsername", "(", "$", "data", "[", "'email'", "]", ")", ";", "$", "user", "->", "setEmail", "(", "$", "data", "[", "'email'", "]", ")", ";", "$", "user", "->", "setPassword", "(", "'none'", ")", ";", "$", "user", "->", "setEnabled", "(", "true", ")", ";", "$", "user", "->", "setContact", "(", "new", "Contact", ")", ";", "return", "$", "user", ";", "}" ]
Creates a new User from oAuth data @param array $data Normalized oAuth data @return User
[ "Creates", "a", "new", "User", "from", "oAuth", "data" ]
7b8206f8b4a50fbc61f7bfe4f83eb466cad96440
https://github.com/wobblecode/WobbleCodeUserBundle/blob/7b8206f8b4a50fbc61f7bfe4f83eb466cad96440/Manager/UserManager.php#L67-L80
train
wobblecode/WobbleCodeUserBundle
Manager/UserManager.php
UserManager.updateFromGeoIp
public function updateFromGeoIp(User $user, array $ipInfo) { $contact = $user->getContact(); $country = $contact->getCountry(); $city = $contact->getCity(); $region = $contact->getRegion(); if (!$country) { $contact->setCountry($ipInfo['country']); } if (!$city) { $contact->setCountry($ipInfo['country']); } if (!$region) { $contact->setCountry($ipInfo['country']); } $this->dm->persist($user); return $this; }
php
public function updateFromGeoIp(User $user, array $ipInfo) { $contact = $user->getContact(); $country = $contact->getCountry(); $city = $contact->getCity(); $region = $contact->getRegion(); if (!$country) { $contact->setCountry($ipInfo['country']); } if (!$city) { $contact->setCountry($ipInfo['country']); } if (!$region) { $contact->setCountry($ipInfo['country']); } $this->dm->persist($user); return $this; }
[ "public", "function", "updateFromGeoIp", "(", "User", "$", "user", ",", "array", "$", "ipInfo", ")", "{", "$", "contact", "=", "$", "user", "->", "getContact", "(", ")", ";", "$", "country", "=", "$", "contact", "->", "getCountry", "(", ")", ";", "$", "city", "=", "$", "contact", "->", "getCity", "(", ")", ";", "$", "region", "=", "$", "contact", "->", "getRegion", "(", ")", ";", "if", "(", "!", "$", "country", ")", "{", "$", "contact", "->", "setCountry", "(", "$", "ipInfo", "[", "'country'", "]", ")", ";", "}", "if", "(", "!", "$", "city", ")", "{", "$", "contact", "->", "setCountry", "(", "$", "ipInfo", "[", "'country'", "]", ")", ";", "}", "if", "(", "!", "$", "region", ")", "{", "$", "contact", "->", "setCountry", "(", "$", "ipInfo", "[", "'country'", "]", ")", ";", "}", "$", "this", "->", "dm", "->", "persist", "(", "$", "user", ")", ";", "return", "$", "this", ";", "}" ]
Update User contact data from geoIp @param User $user @param array $ipInfo @return self
[ "Update", "User", "contact", "data", "from", "geoIp" ]
7b8206f8b4a50fbc61f7bfe4f83eb466cad96440
https://github.com/wobblecode/WobbleCodeUserBundle/blob/7b8206f8b4a50fbc61f7bfe4f83eb466cad96440/Manager/UserManager.php#L90-L112
train
wobblecode/WobbleCodeUserBundle
Manager/UserManager.php
UserManager.signupLog
public function signupLog(User $user, array $ipInfo) { $user->setAttribute('signupIp', $ipInfo); $this->dm->persist($user); $this->dm->flush(); return $this; }
php
public function signupLog(User $user, array $ipInfo) { $user->setAttribute('signupIp', $ipInfo); $this->dm->persist($user); $this->dm->flush(); return $this; }
[ "public", "function", "signupLog", "(", "User", "$", "user", ",", "array", "$", "ipInfo", ")", "{", "$", "user", "->", "setAttribute", "(", "'signupIp'", ",", "$", "ipInfo", ")", ";", "$", "this", "->", "dm", "->", "persist", "(", "$", "user", ")", ";", "$", "this", "->", "dm", "->", "flush", "(", ")", ";", "return", "$", "this", ";", "}" ]
Set signup attributes for geoIp on signup @param User $user @param array $geoIp @return self
[ "Set", "signup", "attributes", "for", "geoIp", "on", "signup" ]
7b8206f8b4a50fbc61f7bfe4f83eb466cad96440
https://github.com/wobblecode/WobbleCodeUserBundle/blob/7b8206f8b4a50fbc61f7bfe4f83eb466cad96440/Manager/UserManager.php#L122-L129
train
wobblecode/WobbleCodeUserBundle
Manager/UserManager.php
UserManager.loginLog
public function loginLog(User $user, array $geoIp) { $geoIp['date'] = date('Y-m-d H:i:s'); $loginIps = $user->getAttribute('lastLoginIps'); if (!$loginIps) { $loginIps = []; } array_unshift($loginIps, $geoIp); $loginIps = array_slice($loginIps, 0, 3); $user->setAttribute('lastLoginIps', $loginIps); $this->dm->persist($user); $this->dm->flush(); return $this; }
php
public function loginLog(User $user, array $geoIp) { $geoIp['date'] = date('Y-m-d H:i:s'); $loginIps = $user->getAttribute('lastLoginIps'); if (!$loginIps) { $loginIps = []; } array_unshift($loginIps, $geoIp); $loginIps = array_slice($loginIps, 0, 3); $user->setAttribute('lastLoginIps', $loginIps); $this->dm->persist($user); $this->dm->flush(); return $this; }
[ "public", "function", "loginLog", "(", "User", "$", "user", ",", "array", "$", "geoIp", ")", "{", "$", "geoIp", "[", "'date'", "]", "=", "date", "(", "'Y-m-d H:i:s'", ")", ";", "$", "loginIps", "=", "$", "user", "->", "getAttribute", "(", "'lastLoginIps'", ")", ";", "if", "(", "!", "$", "loginIps", ")", "{", "$", "loginIps", "=", "[", "]", ";", "}", "array_unshift", "(", "$", "loginIps", ",", "$", "geoIp", ")", ";", "$", "loginIps", "=", "array_slice", "(", "$", "loginIps", ",", "0", ",", "3", ")", ";", "$", "user", "->", "setAttribute", "(", "'lastLoginIps'", ",", "$", "loginIps", ")", ";", "$", "this", "->", "dm", "->", "persist", "(", "$", "user", ")", ";", "$", "this", "->", "dm", "->", "flush", "(", ")", ";", "return", "$", "this", ";", "}" ]
Save login geoIp last 20 events @param User $user @param array $geoIp @return self
[ "Save", "login", "geoIp", "last", "20", "events" ]
7b8206f8b4a50fbc61f7bfe4f83eb466cad96440
https://github.com/wobblecode/WobbleCodeUserBundle/blob/7b8206f8b4a50fbc61f7bfe4f83eb466cad96440/Manager/UserManager.php#L139-L156
train
wobblecode/WobbleCodeUserBundle
Manager/UserManager.php
UserManager.setLocale
public function setLocale(User $user, $locale) { $user->getContact()->setLocale($locale); $this->dm->persist($user); $this->dm->flush(); return $this; }
php
public function setLocale(User $user, $locale) { $user->getContact()->setLocale($locale); $this->dm->persist($user); $this->dm->flush(); return $this; }
[ "public", "function", "setLocale", "(", "User", "$", "user", ",", "$", "locale", ")", "{", "$", "user", "->", "getContact", "(", ")", "->", "setLocale", "(", "$", "locale", ")", ";", "$", "this", "->", "dm", "->", "persist", "(", "$", "user", ")", ";", "$", "this", "->", "dm", "->", "flush", "(", ")", ";", "return", "$", "this", ";", "}" ]
Set locale for an user @param User $user @param $locale @return $this
[ "Set", "locale", "for", "an", "user" ]
7b8206f8b4a50fbc61f7bfe4f83eb466cad96440
https://github.com/wobblecode/WobbleCodeUserBundle/blob/7b8206f8b4a50fbc61f7bfe4f83eb466cad96440/Manager/UserManager.php#L166-L174
train
wobblecode/WobbleCodeUserBundle
Manager/UserManager.php
UserManager.enableRememberMe
public function enableRememberMe($user) { $rememberMeValue = $this->generateRememberMeCookie($user->getUsername()); $this->session->set('REMEMBER_ME', $rememberMeValue); }
php
public function enableRememberMe($user) { $rememberMeValue = $this->generateRememberMeCookie($user->getUsername()); $this->session->set('REMEMBER_ME', $rememberMeValue); }
[ "public", "function", "enableRememberMe", "(", "$", "user", ")", "{", "$", "rememberMeValue", "=", "$", "this", "->", "generateRememberMeCookie", "(", "$", "user", "->", "getUsername", "(", ")", ")", ";", "$", "this", "->", "session", "->", "set", "(", "'REMEMBER_ME'", ",", "$", "rememberMeValue", ")", ";", "}" ]
Enable Remember Me feature @param User
[ "Enable", "Remember", "Me", "feature" ]
7b8206f8b4a50fbc61f7bfe4f83eb466cad96440
https://github.com/wobblecode/WobbleCodeUserBundle/blob/7b8206f8b4a50fbc61f7bfe4f83eb466cad96440/Manager/UserManager.php#L198-L202
train
wobblecode/WobbleCodeUserBundle
Manager/UserManager.php
UserManager.generateRememberMeCookie
protected function generateRememberMeCookie($username) { $key = 'ThisTokenIsNotSoSecretChangeIt'; $class = 'WobbleCode\UserBundle\Document\User'; $password = 'none'; $expires = time()+2592000; $hash = hash('sha256', $class.$username.$expires.$password.$key); return $this->encodeCookie([$class, base64_encode($username), $expires, $hash]); }
php
protected function generateRememberMeCookie($username) { $key = 'ThisTokenIsNotSoSecretChangeIt'; $class = 'WobbleCode\UserBundle\Document\User'; $password = 'none'; $expires = time()+2592000; $hash = hash('sha256', $class.$username.$expires.$password.$key); return $this->encodeCookie([$class, base64_encode($username), $expires, $hash]); }
[ "protected", "function", "generateRememberMeCookie", "(", "$", "username", ")", "{", "$", "key", "=", "'ThisTokenIsNotSoSecretChangeIt'", ";", "$", "class", "=", "'WobbleCode\\UserBundle\\Document\\User'", ";", "$", "password", "=", "'none'", ";", "$", "expires", "=", "time", "(", ")", "+", "2592000", ";", "$", "hash", "=", "hash", "(", "'sha256'", ",", "$", "class", ".", "$", "username", ".", "$", "expires", ".", "$", "password", ".", "$", "key", ")", ";", "return", "$", "this", "->", "encodeCookie", "(", "[", "$", "class", ",", "base64_encode", "(", "$", "username", ")", ",", "$", "expires", ",", "$", "hash", "]", ")", ";", "}" ]
Generate remember me cookie final value @todo Add bundle option to define the class name @todo Add bundle option to get the expire time @todo Add functionality to get the secret key from service @param string $username Username to remember @return string Cookie final value
[ "Generate", "remember", "me", "cookie", "final", "value" ]
7b8206f8b4a50fbc61f7bfe4f83eb466cad96440
https://github.com/wobblecode/WobbleCodeUserBundle/blob/7b8206f8b4a50fbc61f7bfe4f83eb466cad96440/Manager/UserManager.php#L215-L225
train
modulusphp/http
Request.php
Request.ip
public function ip($return_type = null, $ip_addresses = []) { $ip_elements = array( 'HTTP_X_FORWARDED_FOR', 'HTTP_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_CLUSTER_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR' ); foreach ( $ip_elements as $element ) { if(isset($_SERVER[$element])) { if ( !is_string($_SERVER[$element]) ) { // Log the value somehow, to improve the script! continue; } $address_list = explode(',', $_SERVER[$element]); $address_list = array_map('trim', $address_list); // Not using array_merge in order to preserve order foreach ( $address_list as $x ) { $ip_addresses[] = $x; } } } if (count($ip_addresses) == 0) { return false; } elseif ($return_type === 'array') { return $ip_addresses; } elseif ($return_type === 'single' || $return_type === null) { return $ip_addresses[0]; } }
php
public function ip($return_type = null, $ip_addresses = []) { $ip_elements = array( 'HTTP_X_FORWARDED_FOR', 'HTTP_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_CLUSTER_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR' ); foreach ( $ip_elements as $element ) { if(isset($_SERVER[$element])) { if ( !is_string($_SERVER[$element]) ) { // Log the value somehow, to improve the script! continue; } $address_list = explode(',', $_SERVER[$element]); $address_list = array_map('trim', $address_list); // Not using array_merge in order to preserve order foreach ( $address_list as $x ) { $ip_addresses[] = $x; } } } if (count($ip_addresses) == 0) { return false; } elseif ($return_type === 'array') { return $ip_addresses; } elseif ($return_type === 'single' || $return_type === null) { return $ip_addresses[0]; } }
[ "public", "function", "ip", "(", "$", "return_type", "=", "null", ",", "$", "ip_addresses", "=", "[", "]", ")", "{", "$", "ip_elements", "=", "array", "(", "'HTTP_X_FORWARDED_FOR'", ",", "'HTTP_FORWARDED_FOR'", ",", "'HTTP_X_FORWARDED'", ",", "'HTTP_FORWARDED'", ",", "'HTTP_X_CLUSTER_CLIENT_IP'", ",", "'HTTP_CLUSTER_CLIENT_IP'", ",", "'HTTP_X_CLIENT_IP'", ",", "'HTTP_CLIENT_IP'", ",", "'REMOTE_ADDR'", ")", ";", "foreach", "(", "$", "ip_elements", "as", "$", "element", ")", "{", "if", "(", "isset", "(", "$", "_SERVER", "[", "$", "element", "]", ")", ")", "{", "if", "(", "!", "is_string", "(", "$", "_SERVER", "[", "$", "element", "]", ")", ")", "{", "// Log the value somehow, to improve the script!", "continue", ";", "}", "$", "address_list", "=", "explode", "(", "','", ",", "$", "_SERVER", "[", "$", "element", "]", ")", ";", "$", "address_list", "=", "array_map", "(", "'trim'", ",", "$", "address_list", ")", ";", "// Not using array_merge in order to preserve order", "foreach", "(", "$", "address_list", "as", "$", "x", ")", "{", "$", "ip_addresses", "[", "]", "=", "$", "x", ";", "}", "}", "}", "if", "(", "count", "(", "$", "ip_addresses", ")", "==", "0", ")", "{", "return", "false", ";", "}", "elseif", "(", "$", "return_type", "===", "'array'", ")", "{", "return", "$", "ip_addresses", ";", "}", "elseif", "(", "$", "return_type", "===", "'single'", "||", "$", "return_type", "===", "null", ")", "{", "return", "$", "ip_addresses", "[", "0", "]", ";", "}", "}" ]
Get client ip address @return void
[ "Get", "client", "ip", "address" ]
fc5c0f2b582a04de1685578d3fb790686a0a240c
https://github.com/modulusphp/http/blob/fc5c0f2b582a04de1685578d3fb790686a0a240c/Request.php#L80-L111
train
Hnto/nuki
src/Handlers/Database/PDO.php
PDO.insert
public function insert($query, array $data){ $this->conn->prepare($query)->execute($data); return $this->conn->lastInsertId(); }
php
public function insert($query, array $data){ $this->conn->prepare($query)->execute($data); return $this->conn->lastInsertId(); }
[ "public", "function", "insert", "(", "$", "query", ",", "array", "$", "data", ")", "{", "$", "this", "->", "conn", "->", "prepare", "(", "$", "query", ")", "->", "execute", "(", "$", "data", ")", ";", "return", "$", "this", "->", "conn", "->", "lastInsertId", "(", ")", ";", "}" ]
Insert a record in the storage @param string $query @param array $data @return string the last inserted id
[ "Insert", "a", "record", "in", "the", "storage" ]
c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c
https://github.com/Hnto/nuki/blob/c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c/src/Handlers/Database/PDO.php#L40-L44
train
Hnto/nuki
src/Handlers/Database/PDO.php
PDO.update
public function update($query, array $data) { $stmt = $this->executeQuery($query, $data); return $stmt->rowCount(); }
php
public function update($query, array $data) { $stmt = $this->executeQuery($query, $data); return $stmt->rowCount(); }
[ "public", "function", "update", "(", "$", "query", ",", "array", "$", "data", ")", "{", "$", "stmt", "=", "$", "this", "->", "executeQuery", "(", "$", "query", ",", "$", "data", ")", ";", "return", "$", "stmt", "->", "rowCount", "(", ")", ";", "}" ]
Update an existing record in the storage @param string $query @param array $data @return int the number of rows
[ "Update", "an", "existing", "record", "in", "the", "storage" ]
c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c
https://github.com/Hnto/nuki/blob/c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c/src/Handlers/Database/PDO.php#L53-L57
train
Hnto/nuki
src/Handlers/Database/PDO.php
PDO.delete
public function delete($query, array $data) { $stmt = $this->executeQuery($query, $data); return $stmt->rowCount(); }
php
public function delete($query, array $data) { $stmt = $this->executeQuery($query, $data); return $stmt->rowCount(); }
[ "public", "function", "delete", "(", "$", "query", ",", "array", "$", "data", ")", "{", "$", "stmt", "=", "$", "this", "->", "executeQuery", "(", "$", "query", ",", "$", "data", ")", ";", "return", "$", "stmt", "->", "rowCount", "(", ")", ";", "}" ]
Delete a record in the storage @param string $query @param array $data @return int the number of rows
[ "Delete", "a", "record", "in", "the", "storage" ]
c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c
https://github.com/Hnto/nuki/blob/c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c/src/Handlers/Database/PDO.php#L66-L70
train
Hnto/nuki
src/Handlers/Database/PDO.php
PDO.findOne
public function findOne($query, array $data = null) { $stmt = $this->executeQuery($query, $data); return $stmt->fetch(\PDO::FETCH_ASSOC); }
php
public function findOne($query, array $data = null) { $stmt = $this->executeQuery($query, $data); return $stmt->fetch(\PDO::FETCH_ASSOC); }
[ "public", "function", "findOne", "(", "$", "query", ",", "array", "$", "data", "=", "null", ")", "{", "$", "stmt", "=", "$", "this", "->", "executeQuery", "(", "$", "query", ",", "$", "data", ")", ";", "return", "$", "stmt", "->", "fetch", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "}" ]
Fetch a record from the storage @param string $query @param array $data @return object data as object
[ "Fetch", "a", "record", "from", "the", "storage" ]
c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c
https://github.com/Hnto/nuki/blob/c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c/src/Handlers/Database/PDO.php#L79-L83
train
Hnto/nuki
src/Handlers/Database/PDO.php
PDO.findMany
public function findMany($query, array $data = null){ $stmt = $this->executeQuery($query, $data); return($stmt->fetchAll(\PDO::FETCH_ASSOC)); }
php
public function findMany($query, array $data = null){ $stmt = $this->executeQuery($query, $data); return($stmt->fetchAll(\PDO::FETCH_ASSOC)); }
[ "public", "function", "findMany", "(", "$", "query", ",", "array", "$", "data", "=", "null", ")", "{", "$", "stmt", "=", "$", "this", "->", "executeQuery", "(", "$", "query", ",", "$", "data", ")", ";", "return", "(", "$", "stmt", "->", "fetchAll", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ")", ";", "}" ]
Fetch all records from a certain location in the storage @param string $query @param array $data @return object as object
[ "Fetch", "all", "records", "from", "a", "certain", "location", "in", "the", "storage" ]
c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c
https://github.com/Hnto/nuki/blob/c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c/src/Handlers/Database/PDO.php#L92-L96
train
Hnto/nuki
src/Handlers/Database/PDO.php
PDO.executeQuery
private function executeQuery($query, $data = null) { $stmt = $this->conn->prepare($query); $stmt->execute($data); return $stmt; }
php
private function executeQuery($query, $data = null) { $stmt = $this->conn->prepare($query); $stmt->execute($data); return $stmt; }
[ "private", "function", "executeQuery", "(", "$", "query", ",", "$", "data", "=", "null", ")", "{", "$", "stmt", "=", "$", "this", "->", "conn", "->", "prepare", "(", "$", "query", ")", ";", "$", "stmt", "->", "execute", "(", "$", "data", ")", ";", "return", "$", "stmt", ";", "}" ]
Execute a raw query @param string $query @param array $data @return object statement object
[ "Execute", "a", "raw", "query" ]
c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c
https://github.com/Hnto/nuki/blob/c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c/src/Handlers/Database/PDO.php#L105-L110
train
vpg/titon.utility
src/Titon/Utility/Hash.php
Hash.each
public static function each(array $set, Closure $callback, $recursive = true) { foreach ($set as $key => $value) { if (is_array($value) && $recursive) { $set[$key] = static::each($value, $callback, $recursive); } else { $set[$key] = $callback($value, $key); } } return $set; }
php
public static function each(array $set, Closure $callback, $recursive = true) { foreach ($set as $key => $value) { if (is_array($value) && $recursive) { $set[$key] = static::each($value, $callback, $recursive); } else { $set[$key] = $callback($value, $key); } } return $set; }
[ "public", "static", "function", "each", "(", "array", "$", "set", ",", "Closure", "$", "callback", ",", "$", "recursive", "=", "true", ")", "{", "foreach", "(", "$", "set", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "&&", "$", "recursive", ")", "{", "$", "set", "[", "$", "key", "]", "=", "static", "::", "each", "(", "$", "value", ",", "$", "callback", ",", "$", "recursive", ")", ";", "}", "else", "{", "$", "set", "[", "$", "key", "]", "=", "$", "callback", "(", "$", "value", ",", "$", "key", ")", ";", "}", "}", "return", "$", "set", ";", "}" ]
Calls a function for each key-value pair in the set. If recursive is true, will apply the callback to nested arrays as well. @param array $set @param \Closure $callback @param bool $recursive @return array
[ "Calls", "a", "function", "for", "each", "key", "-", "value", "pair", "in", "the", "set", ".", "If", "recursive", "is", "true", "will", "apply", "the", "callback", "to", "nested", "arrays", "as", "well", "." ]
8a77eb9e7b8baacf41cc25487289779d8319cd3a
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Hash.php#L66-L76
train
vpg/titon.utility
src/Titon/Utility/Hash.php
Hash.every
public static function every(array $set, Closure $callback) { foreach ($set as $key => $value) { if (!$callback($value, $key)) { return false; } } return true; }
php
public static function every(array $set, Closure $callback) { foreach ($set as $key => $value) { if (!$callback($value, $key)) { return false; } } return true; }
[ "public", "static", "function", "every", "(", "array", "$", "set", ",", "Closure", "$", "callback", ")", "{", "foreach", "(", "$", "set", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "$", "callback", "(", "$", "value", ",", "$", "key", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Returns true if every element in the array satisfies the provided testing function. @param array $set @param \Closure $callback @return bool
[ "Returns", "true", "if", "every", "element", "in", "the", "array", "satisfies", "the", "provided", "testing", "function", "." ]
8a77eb9e7b8baacf41cc25487289779d8319cd3a
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Hash.php#L85-L93
train
vpg/titon.utility
src/Titon/Utility/Hash.php
Hash.expand
public static function expand(array $set) { $data = array(); foreach ($set as $key => $value) { $data = static::insert($data, $key, $value); } return $data; }
php
public static function expand(array $set) { $data = array(); foreach ($set as $key => $value) { $data = static::insert($data, $key, $value); } return $data; }
[ "public", "static", "function", "expand", "(", "array", "$", "set", ")", "{", "$", "data", "=", "array", "(", ")", ";", "foreach", "(", "$", "set", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "data", "=", "static", "::", "insert", "(", "$", "data", ",", "$", "key", ",", "$", "value", ")", ";", "}", "return", "$", "data", ";", "}" ]
Expand an array to a fully workable multi-dimensional array, where the values key is a dot notated path. @param array $set @return array
[ "Expand", "an", "array", "to", "a", "fully", "workable", "multi", "-", "dimensional", "array", "where", "the", "values", "key", "is", "a", "dot", "notated", "path", "." ]
8a77eb9e7b8baacf41cc25487289779d8319cd3a
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Hash.php#L116-L124
train
vpg/titon.utility
src/Titon/Utility/Hash.php
Hash.extract
public static function extract(array $set, $path) { if (!$set) { return null; } // Exit early for faster processing if (strpos($path, '.') === false) { return isset($set[$path]) ? $set[$path] : null; } $search =& $set; $paths = explode('.', (string) $path); $total = count($paths); while ($total > 0) { $key = $paths[0]; // Within the last path if ($total === 1) { return array_key_exists($key, $search) ? $search[$key] : null; // Break out of non-existent paths early } else if (!array_key_exists($key, $search) || !is_array($search[$key])) { return null; } $search =& $search[$key]; array_shift($paths); $total--; } return null; }
php
public static function extract(array $set, $path) { if (!$set) { return null; } // Exit early for faster processing if (strpos($path, '.') === false) { return isset($set[$path]) ? $set[$path] : null; } $search =& $set; $paths = explode('.', (string) $path); $total = count($paths); while ($total > 0) { $key = $paths[0]; // Within the last path if ($total === 1) { return array_key_exists($key, $search) ? $search[$key] : null; // Break out of non-existent paths early } else if (!array_key_exists($key, $search) || !is_array($search[$key])) { return null; } $search =& $search[$key]; array_shift($paths); $total--; } return null; }
[ "public", "static", "function", "extract", "(", "array", "$", "set", ",", "$", "path", ")", "{", "if", "(", "!", "$", "set", ")", "{", "return", "null", ";", "}", "// Exit early for faster processing", "if", "(", "strpos", "(", "$", "path", ",", "'.'", ")", "===", "false", ")", "{", "return", "isset", "(", "$", "set", "[", "$", "path", "]", ")", "?", "$", "set", "[", "$", "path", "]", ":", "null", ";", "}", "$", "search", "=", "&", "$", "set", ";", "$", "paths", "=", "explode", "(", "'.'", ",", "(", "string", ")", "$", "path", ")", ";", "$", "total", "=", "count", "(", "$", "paths", ")", ";", "while", "(", "$", "total", ">", "0", ")", "{", "$", "key", "=", "$", "paths", "[", "0", "]", ";", "// Within the last path", "if", "(", "$", "total", "===", "1", ")", "{", "return", "array_key_exists", "(", "$", "key", ",", "$", "search", ")", "?", "$", "search", "[", "$", "key", "]", ":", "null", ";", "// Break out of non-existent paths early", "}", "else", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "search", ")", "||", "!", "is_array", "(", "$", "search", "[", "$", "key", "]", ")", ")", "{", "return", "null", ";", "}", "$", "search", "=", "&", "$", "search", "[", "$", "key", "]", ";", "array_shift", "(", "$", "paths", ")", ";", "$", "total", "--", ";", "}", "return", "null", ";", "}" ]
Extract the value of an array, depending on the paths given, represented by key.key.key notation. @param array $set @param string $path @return mixed
[ "Extract", "the", "value", "of", "an", "array", "depending", "on", "the", "paths", "given", "represented", "by", "key", ".", "key", ".", "key", "notation", "." ]
8a77eb9e7b8baacf41cc25487289779d8319cd3a
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Hash.php#L133-L165
train
vpg/titon.utility
src/Titon/Utility/Hash.php
Hash.flatten
public static function flatten(array $set, $path = null) { if ($path) { $path = $path . '.'; } $data = array(); foreach ($set as $key => $value) { if (is_array($value)) { if ($value) { $data += static::flatten($value, $path . $key); } else { $data[$path . $key] = null; } } else { $data[$path . $key] = $value; } } return $data; }
php
public static function flatten(array $set, $path = null) { if ($path) { $path = $path . '.'; } $data = array(); foreach ($set as $key => $value) { if (is_array($value)) { if ($value) { $data += static::flatten($value, $path . $key); } else { $data[$path . $key] = null; } } else { $data[$path . $key] = $value; } } return $data; }
[ "public", "static", "function", "flatten", "(", "array", "$", "set", ",", "$", "path", "=", "null", ")", "{", "if", "(", "$", "path", ")", "{", "$", "path", "=", "$", "path", ".", "'.'", ";", "}", "$", "data", "=", "array", "(", ")", ";", "foreach", "(", "$", "set", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "if", "(", "$", "value", ")", "{", "$", "data", "+=", "static", "::", "flatten", "(", "$", "value", ",", "$", "path", ".", "$", "key", ")", ";", "}", "else", "{", "$", "data", "[", "$", "path", ".", "$", "key", "]", "=", "null", ";", "}", "}", "else", "{", "$", "data", "[", "$", "path", ".", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "data", ";", "}" ]
Flatten a multi-dimensional array by returning the values with their keys representing their previous pathing. @param array $set @param string $path @return array
[ "Flatten", "a", "multi", "-", "dimensional", "array", "by", "returning", "the", "values", "with", "their", "keys", "representing", "their", "previous", "pathing", "." ]
8a77eb9e7b8baacf41cc25487289779d8319cd3a
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Hash.php#L201-L221
train
vpg/titon.utility
src/Titon/Utility/Hash.php
Hash.inject
public static function inject(array $set, $path, $value) { if (static::has($set, $path)) { return $set; } return static::insert($set, $path, $value); }
php
public static function inject(array $set, $path, $value) { if (static::has($set, $path)) { return $set; } return static::insert($set, $path, $value); }
[ "public", "static", "function", "inject", "(", "array", "$", "set", ",", "$", "path", ",", "$", "value", ")", "{", "if", "(", "static", "::", "has", "(", "$", "set", ",", "$", "path", ")", ")", "{", "return", "$", "set", ";", "}", "return", "static", "::", "insert", "(", "$", "set", ",", "$", "path", ",", "$", "value", ")", ";", "}" ]
Includes the specified key-value pair in the set if the key doesn't already exist. @param array $set @param string $path @param mixed $value @return array
[ "Includes", "the", "specified", "key", "-", "value", "pair", "in", "the", "set", "if", "the", "key", "doesn", "t", "already", "exist", "." ]
8a77eb9e7b8baacf41cc25487289779d8319cd3a
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Hash.php#L320-L326
train
vpg/titon.utility
src/Titon/Utility/Hash.php
Hash.insert
public static function insert(array $set, $path, $value) { if (!$path) { return $set; } // Exit early for faster processing if (strpos($path, '.') === false) { $set[$path] = $value; return $set; } $search =& $set; $paths = explode('.', $path); $total = count($paths); while ($total > 0) { $key = $paths[0]; // Within the last path if ($total === 1) { $search[$key] = $value; // Break out of non-existent paths early } else if (!array_key_exists($key, $search) || !is_array($search[$key])) { $search[$key] = array(); } $search =& $search[$key]; array_shift($paths); $total--; } unset($search); return $set; }
php
public static function insert(array $set, $path, $value) { if (!$path) { return $set; } // Exit early for faster processing if (strpos($path, '.') === false) { $set[$path] = $value; return $set; } $search =& $set; $paths = explode('.', $path); $total = count($paths); while ($total > 0) { $key = $paths[0]; // Within the last path if ($total === 1) { $search[$key] = $value; // Break out of non-existent paths early } else if (!array_key_exists($key, $search) || !is_array($search[$key])) { $search[$key] = array(); } $search =& $search[$key]; array_shift($paths); $total--; } unset($search); return $set; }
[ "public", "static", "function", "insert", "(", "array", "$", "set", ",", "$", "path", ",", "$", "value", ")", "{", "if", "(", "!", "$", "path", ")", "{", "return", "$", "set", ";", "}", "// Exit early for faster processing", "if", "(", "strpos", "(", "$", "path", ",", "'.'", ")", "===", "false", ")", "{", "$", "set", "[", "$", "path", "]", "=", "$", "value", ";", "return", "$", "set", ";", "}", "$", "search", "=", "&", "$", "set", ";", "$", "paths", "=", "explode", "(", "'.'", ",", "$", "path", ")", ";", "$", "total", "=", "count", "(", "$", "paths", ")", ";", "while", "(", "$", "total", ">", "0", ")", "{", "$", "key", "=", "$", "paths", "[", "0", "]", ";", "// Within the last path", "if", "(", "$", "total", "===", "1", ")", "{", "$", "search", "[", "$", "key", "]", "=", "$", "value", ";", "// Break out of non-existent paths early", "}", "else", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "search", ")", "||", "!", "is_array", "(", "$", "search", "[", "$", "key", "]", ")", ")", "{", "$", "search", "[", "$", "key", "]", "=", "array", "(", ")", ";", "}", "$", "search", "=", "&", "$", "search", "[", "$", "key", "]", ";", "array_shift", "(", "$", "paths", ")", ";", "$", "total", "--", ";", "}", "unset", "(", "$", "search", ")", ";", "return", "$", "set", ";", "}" ]
Inserts a value into the array set based on the given path. @param array $set @param string $path @param mixed $value @return array
[ "Inserts", "a", "value", "into", "the", "array", "set", "based", "on", "the", "given", "path", "." ]
8a77eb9e7b8baacf41cc25487289779d8319cd3a
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Hash.php#L336-L372
train
vpg/titon.utility
src/Titon/Utility/Hash.php
Hash.keyOf
public static function keyOf(array $set, $match) { $return = null; $isArray = array(); foreach ($set as $key => $value) { if ($value === $match) { $return = $key; } if (is_array($value)) { $isArray[] = $key; } } if (!$return && $isArray) { foreach ($isArray as $key) { if ($value = static::keyOf($set[$key], $match)) { $return = $key . '.' . $value; } } } return $return; }
php
public static function keyOf(array $set, $match) { $return = null; $isArray = array(); foreach ($set as $key => $value) { if ($value === $match) { $return = $key; } if (is_array($value)) { $isArray[] = $key; } } if (!$return && $isArray) { foreach ($isArray as $key) { if ($value = static::keyOf($set[$key], $match)) { $return = $key . '.' . $value; } } } return $return; }
[ "public", "static", "function", "keyOf", "(", "array", "$", "set", ",", "$", "match", ")", "{", "$", "return", "=", "null", ";", "$", "isArray", "=", "array", "(", ")", ";", "foreach", "(", "$", "set", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "===", "$", "match", ")", "{", "$", "return", "=", "$", "key", ";", "}", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "isArray", "[", "]", "=", "$", "key", ";", "}", "}", "if", "(", "!", "$", "return", "&&", "$", "isArray", ")", "{", "foreach", "(", "$", "isArray", "as", "$", "key", ")", "{", "if", "(", "$", "value", "=", "static", "::", "keyOf", "(", "$", "set", "[", "$", "key", "]", ",", "$", "match", ")", ")", "{", "$", "return", "=", "$", "key", ".", "'.'", ".", "$", "value", ";", "}", "}", "}", "return", "$", "return", ";", "}" ]
Returns the key of the specified value. Will recursively search if the first pass doesn't match. @param array $set @param mixed $match @return mixed
[ "Returns", "the", "key", "of", "the", "specified", "value", ".", "Will", "recursively", "search", "if", "the", "first", "pass", "doesn", "t", "match", "." ]
8a77eb9e7b8baacf41cc25487289779d8319cd3a
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Hash.php#L417-L440
train
vpg/titon.utility
src/Titon/Utility/Hash.php
Hash.pluck
public static function pluck(array $set, $path) { $data = array(); foreach ($set as $array) { if ($value = static::extract($array, $path)) { $data[] = $value; } } return $data; }
php
public static function pluck(array $set, $path) { $data = array(); foreach ($set as $array) { if ($value = static::extract($array, $path)) { $data[] = $value; } } return $data; }
[ "public", "static", "function", "pluck", "(", "array", "$", "set", ",", "$", "path", ")", "{", "$", "data", "=", "array", "(", ")", ";", "foreach", "(", "$", "set", "as", "$", "array", ")", "{", "if", "(", "$", "value", "=", "static", "::", "extract", "(", "$", "array", ",", "$", "path", ")", ")", "{", "$", "data", "[", "]", "=", "$", "value", ";", "}", "}", "return", "$", "data", ";", "}" ]
Pluck a value out of each child-array and return an array of the plucked values. @param array $set @param string $path @return array
[ "Pluck", "a", "value", "out", "of", "each", "child", "-", "array", "and", "return", "an", "array", "of", "the", "plucked", "values", "." ]
8a77eb9e7b8baacf41cc25487289779d8319cd3a
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Hash.php#L541-L551
train
vpg/titon.utility
src/Titon/Utility/Hash.php
Hash.reduce
public static function reduce(array $set, array $keys) { $array = array(); foreach ($set as $key => $value) { if (in_array($key, $keys)) { $array[$key] = $value; } } return $array; }
php
public static function reduce(array $set, array $keys) { $array = array(); foreach ($set as $key => $value) { if (in_array($key, $keys)) { $array[$key] = $value; } } return $array; }
[ "public", "static", "function", "reduce", "(", "array", "$", "set", ",", "array", "$", "keys", ")", "{", "$", "array", "=", "array", "(", ")", ";", "foreach", "(", "$", "set", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "in_array", "(", "$", "key", ",", "$", "keys", ")", ")", "{", "$", "array", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "array", ";", "}" ]
Reduce an array by removing all keys that have not been defined for persistence. @param array $set @param array $keys @return array
[ "Reduce", "an", "array", "by", "removing", "all", "keys", "that", "have", "not", "been", "defined", "for", "persistence", "." ]
8a77eb9e7b8baacf41cc25487289779d8319cd3a
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Hash.php#L594-L604
train
vpg/titon.utility
src/Titon/Utility/Hash.php
Hash.set
public static function set(array $set, $path, $value = null) { if (is_array($path)) { foreach ($path as $key => $value) { $set = static::insert($set, $key, $value); } } else { $set = static::insert($set, $path, $value); } return $set; }
php
public static function set(array $set, $path, $value = null) { if (is_array($path)) { foreach ($path as $key => $value) { $set = static::insert($set, $key, $value); } } else { $set = static::insert($set, $path, $value); } return $set; }
[ "public", "static", "function", "set", "(", "array", "$", "set", ",", "$", "path", ",", "$", "value", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "path", ")", ")", "{", "foreach", "(", "$", "path", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "set", "=", "static", "::", "insert", "(", "$", "set", ",", "$", "key", ",", "$", "value", ")", ";", "}", "}", "else", "{", "$", "set", "=", "static", "::", "insert", "(", "$", "set", ",", "$", "path", ",", "$", "value", ")", ";", "}", "return", "$", "set", ";", "}" ]
Set a value into the result set. If the paths is an array, loop over each one and insert the value. @param array $set @param array|string $path @param mixed $value @return array
[ "Set", "a", "value", "into", "the", "result", "set", ".", "If", "the", "paths", "is", "an", "array", "loop", "over", "each", "one", "and", "insert", "the", "value", "." ]
8a77eb9e7b8baacf41cc25487289779d8319cd3a
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Hash.php#L658-L668
train
vpg/titon.utility
src/Titon/Utility/Hash.php
Hash.some
public static function some(array $set, Closure $callback) { foreach ($set as $value) { if ($callback($value, $value)) { return true; } } return false; }
php
public static function some(array $set, Closure $callback) { foreach ($set as $value) { if ($callback($value, $value)) { return true; } } return false; }
[ "public", "static", "function", "some", "(", "array", "$", "set", ",", "Closure", "$", "callback", ")", "{", "foreach", "(", "$", "set", "as", "$", "value", ")", "{", "if", "(", "$", "callback", "(", "$", "value", ",", "$", "value", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if at least one element in the array satisfies the provided testing function. @param array $set @param \Closure $callback @return bool
[ "Returns", "true", "if", "at", "least", "one", "element", "in", "the", "array", "satisfies", "the", "provided", "testing", "function", "." ]
8a77eb9e7b8baacf41cc25487289779d8319cd3a
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Hash.php#L677-L685
train
erenmustafaozdal/laravel-modules-base
src/Repositories/FileRepository.php
FileRepository.moveFile
public function moveFile($file, $model) { $path = $this->getUploadPath($model, $this->options); $this->makeDirectoryBeforeUpload($path, true); if ( ! is_null($this->elfinderFilePath) ) { $this->copy($this->elfinderFilePath, $path . '/' . $this->fileName); } else { $this->move($file, $path . '/' . $this->fileName); } return [ 'fileName' => $this->fileName, 'fileSize' => $this->fileSize ]; }
php
public function moveFile($file, $model) { $path = $this->getUploadPath($model, $this->options); $this->makeDirectoryBeforeUpload($path, true); if ( ! is_null($this->elfinderFilePath) ) { $this->copy($this->elfinderFilePath, $path . '/' . $this->fileName); } else { $this->move($file, $path . '/' . $this->fileName); } return [ 'fileName' => $this->fileName, 'fileSize' => $this->fileSize ]; }
[ "public", "function", "moveFile", "(", "$", "file", ",", "$", "model", ")", "{", "$", "path", "=", "$", "this", "->", "getUploadPath", "(", "$", "model", ",", "$", "this", "->", "options", ")", ";", "$", "this", "->", "makeDirectoryBeforeUpload", "(", "$", "path", ",", "true", ")", ";", "if", "(", "!", "is_null", "(", "$", "this", "->", "elfinderFilePath", ")", ")", "{", "$", "this", "->", "copy", "(", "$", "this", "->", "elfinderFilePath", ",", "$", "path", ".", "'/'", ".", "$", "this", "->", "fileName", ")", ";", "}", "else", "{", "$", "this", "->", "move", "(", "$", "file", ",", "$", "path", ".", "'/'", ".", "$", "this", "->", "fileName", ")", ";", "}", "return", "[", "'fileName'", "=>", "$", "this", "->", "fileName", ",", "'fileSize'", "=>", "$", "this", "->", "fileSize", "]", ";", "}" ]
move upload file @param $file @param \Illuminate\Database\Eloquent\Model $model @return string
[ "move", "upload", "file" ]
c26600543817642926bcf16ada84009e00d784e0
https://github.com/erenmustafaozdal/laravel-modules-base/blob/c26600543817642926bcf16ada84009e00d784e0/src/Repositories/FileRepository.php#L86-L101
train
erenmustafaozdal/laravel-modules-base
src/Repositories/FileRepository.php
FileRepository.setFileName
protected function setFileName($file) { if (isset($this->options['thumbnails'])) { $thumbs = isset($this->options['changeThumb']) ? $this->options['thumbnails'][$this->options['changeThumb']] : $this->options['thumbnails']; $thumbs = array_values($thumbs); $firstThumb = array_shift($thumbs); if (isset($firstThumb['name'])) { $this->fileName = str_replace(':time',time(),$firstThumb['name']); return; } } $this->fileName = $this->createFileName($file); }
php
protected function setFileName($file) { if (isset($this->options['thumbnails'])) { $thumbs = isset($this->options['changeThumb']) ? $this->options['thumbnails'][$this->options['changeThumb']] : $this->options['thumbnails']; $thumbs = array_values($thumbs); $firstThumb = array_shift($thumbs); if (isset($firstThumb['name'])) { $this->fileName = str_replace(':time',time(),$firstThumb['name']); return; } } $this->fileName = $this->createFileName($file); }
[ "protected", "function", "setFileName", "(", "$", "file", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "options", "[", "'thumbnails'", "]", ")", ")", "{", "$", "thumbs", "=", "isset", "(", "$", "this", "->", "options", "[", "'changeThumb'", "]", ")", "?", "$", "this", "->", "options", "[", "'thumbnails'", "]", "[", "$", "this", "->", "options", "[", "'changeThumb'", "]", "]", ":", "$", "this", "->", "options", "[", "'thumbnails'", "]", ";", "$", "thumbs", "=", "array_values", "(", "$", "thumbs", ")", ";", "$", "firstThumb", "=", "array_shift", "(", "$", "thumbs", ")", ";", "if", "(", "isset", "(", "$", "firstThumb", "[", "'name'", "]", ")", ")", "{", "$", "this", "->", "fileName", "=", "str_replace", "(", "':time'", ",", "time", "(", ")", ",", "$", "firstThumb", "[", "'name'", "]", ")", ";", "return", ";", "}", "}", "$", "this", "->", "fileName", "=", "$", "this", "->", "createFileName", "(", "$", "file", ")", ";", "}" ]
set file name @param \Symfony\Component\HttpFoundation\File\UploadedFile|string $file @return void
[ "set", "file", "name" ]
c26600543817642926bcf16ada84009e00d784e0
https://github.com/erenmustafaozdal/laravel-modules-base/blob/c26600543817642926bcf16ada84009e00d784e0/src/Repositories/FileRepository.php#L109-L123
train
erenmustafaozdal/laravel-modules-base
src/Repositories/FileRepository.php
FileRepository.setFileSize
protected function setFileSize($file) { $this->fileSize = ! is_null($this->elfinderFilePath) ? $this->getFileSize() : (is_string($file) ? $this->size($file) : $file->getClientSize()); }
php
protected function setFileSize($file) { $this->fileSize = ! is_null($this->elfinderFilePath) ? $this->getFileSize() : (is_string($file) ? $this->size($file) : $file->getClientSize()); }
[ "protected", "function", "setFileSize", "(", "$", "file", ")", "{", "$", "this", "->", "fileSize", "=", "!", "is_null", "(", "$", "this", "->", "elfinderFilePath", ")", "?", "$", "this", "->", "getFileSize", "(", ")", ":", "(", "is_string", "(", "$", "file", ")", "?", "$", "this", "->", "size", "(", "$", "file", ")", ":", "$", "file", "->", "getClientSize", "(", ")", ")", ";", "}" ]
set file size @param \Symfony\Component\HttpFoundation\File\UploadedFile|string $file @return void
[ "set", "file", "size" ]
c26600543817642926bcf16ada84009e00d784e0
https://github.com/erenmustafaozdal/laravel-modules-base/blob/c26600543817642926bcf16ada84009e00d784e0/src/Repositories/FileRepository.php#L131-L134
train
erenmustafaozdal/laravel-modules-base
src/Repositories/FileRepository.php
FileRepository.createFileName
public function createFileName($file) { if ( ! is_null($this->elfinderFilePath) ) { return $this->getFileName(); } if ( is_string($file) ) { return substr( strrchr( $file, '/' ), 1 ); } $filename = $file->getClientOriginalName(); $mime = $file->getClientOriginalExtension(); $parts = explode('.',$filename); array_pop($parts); return str_slug( implode(' ', $parts), '-' ) . '_' . time() . '.' . $mime; }
php
public function createFileName($file) { if ( ! is_null($this->elfinderFilePath) ) { return $this->getFileName(); } if ( is_string($file) ) { return substr( strrchr( $file, '/' ), 1 ); } $filename = $file->getClientOriginalName(); $mime = $file->getClientOriginalExtension(); $parts = explode('.',$filename); array_pop($parts); return str_slug( implode(' ', $parts), '-' ) . '_' . time() . '.' . $mime; }
[ "public", "function", "createFileName", "(", "$", "file", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "elfinderFilePath", ")", ")", "{", "return", "$", "this", "->", "getFileName", "(", ")", ";", "}", "if", "(", "is_string", "(", "$", "file", ")", ")", "{", "return", "substr", "(", "strrchr", "(", "$", "file", ",", "'/'", ")", ",", "1", ")", ";", "}", "$", "filename", "=", "$", "file", "->", "getClientOriginalName", "(", ")", ";", "$", "mime", "=", "$", "file", "->", "getClientOriginalExtension", "(", ")", ";", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "filename", ")", ";", "array_pop", "(", "$", "parts", ")", ";", "return", "str_slug", "(", "implode", "(", "' '", ",", "$", "parts", ")", ",", "'-'", ")", ".", "'_'", ".", "time", "(", ")", ".", "'.'", ".", "$", "mime", ";", "}" ]
create file name @param $file @return string
[ "create", "file", "name" ]
c26600543817642926bcf16ada84009e00d784e0
https://github.com/erenmustafaozdal/laravel-modules-base/blob/c26600543817642926bcf16ada84009e00d784e0/src/Repositories/FileRepository.php#L142-L156
train
erenmustafaozdal/laravel-modules-base
src/Repositories/FileRepository.php
FileRepository.getFile
protected function getFile($request) { $columns = explode('.',$this->options['column']); $column = count($columns) > 1 ? $columns[1] : $columns[0]; $inputName = isset($this->options['group']) ? "{$this->options['group']}.{$this->options['index']}.{$column}" : $column; $inputName = isset($this->options['inputPrefix']) && $this->options['inputPrefix'] ? $this->options['inputPrefix'] . $inputName : $inputName; if ( isset($this->options['isElfinder']) && $this->options['isElfinder'] ) { $file = $request->input($inputName); $this->elfinderFilePath = public_path($file); } else { $file = $request->file($inputName); // eğer dosya yoksa init var mı bakılır if (! $file || (is_array($file) && array_search(null,$file) !== false) ) { $column = 'init_'; $column .= count($columns) > 1 ? $columns[1] : $columns[0]; $file = $request->get($column); } } return is_array($file) ? $file : [$file]; }
php
protected function getFile($request) { $columns = explode('.',$this->options['column']); $column = count($columns) > 1 ? $columns[1] : $columns[0]; $inputName = isset($this->options['group']) ? "{$this->options['group']}.{$this->options['index']}.{$column}" : $column; $inputName = isset($this->options['inputPrefix']) && $this->options['inputPrefix'] ? $this->options['inputPrefix'] . $inputName : $inputName; if ( isset($this->options['isElfinder']) && $this->options['isElfinder'] ) { $file = $request->input($inputName); $this->elfinderFilePath = public_path($file); } else { $file = $request->file($inputName); // eğer dosya yoksa init var mı bakılır if (! $file || (is_array($file) && array_search(null,$file) !== false) ) { $column = 'init_'; $column .= count($columns) > 1 ? $columns[1] : $columns[0]; $file = $request->get($column); } } return is_array($file) ? $file : [$file]; }
[ "protected", "function", "getFile", "(", "$", "request", ")", "{", "$", "columns", "=", "explode", "(", "'.'", ",", "$", "this", "->", "options", "[", "'column'", "]", ")", ";", "$", "column", "=", "count", "(", "$", "columns", ")", ">", "1", "?", "$", "columns", "[", "1", "]", ":", "$", "columns", "[", "0", "]", ";", "$", "inputName", "=", "isset", "(", "$", "this", "->", "options", "[", "'group'", "]", ")", "?", "\"{$this->options['group']}.{$this->options['index']}.{$column}\"", ":", "$", "column", ";", "$", "inputName", "=", "isset", "(", "$", "this", "->", "options", "[", "'inputPrefix'", "]", ")", "&&", "$", "this", "->", "options", "[", "'inputPrefix'", "]", "?", "$", "this", "->", "options", "[", "'inputPrefix'", "]", ".", "$", "inputName", ":", "$", "inputName", ";", "if", "(", "isset", "(", "$", "this", "->", "options", "[", "'isElfinder'", "]", ")", "&&", "$", "this", "->", "options", "[", "'isElfinder'", "]", ")", "{", "$", "file", "=", "$", "request", "->", "input", "(", "$", "inputName", ")", ";", "$", "this", "->", "elfinderFilePath", "=", "public_path", "(", "$", "file", ")", ";", "}", "else", "{", "$", "file", "=", "$", "request", "->", "file", "(", "$", "inputName", ")", ";", "// eğer dosya yoksa init var mı bakılır\r", "if", "(", "!", "$", "file", "||", "(", "is_array", "(", "$", "file", ")", "&&", "array_search", "(", "null", ",", "$", "file", ")", "!==", "false", ")", ")", "{", "$", "column", "=", "'init_'", ";", "$", "column", ".=", "count", "(", "$", "columns", ")", ">", "1", "?", "$", "columns", "[", "1", "]", ":", "$", "columns", "[", "0", "]", ";", "$", "file", "=", "$", "request", "->", "get", "(", "$", "column", ")", ";", "}", "}", "return", "is_array", "(", "$", "file", ")", "?", "$", "file", ":", "[", "$", "file", "]", ";", "}" ]
get file or string path @param \Illuminate\Http\Request $request @return \Symfony\Component\HttpFoundation\File\UploadedFile|string
[ "get", "file", "or", "string", "path" ]
c26600543817642926bcf16ada84009e00d784e0
https://github.com/erenmustafaozdal/laravel-modules-base/blob/c26600543817642926bcf16ada84009e00d784e0/src/Repositories/FileRepository.php#L164-L185
train
erenmustafaozdal/laravel-modules-base
src/Repositories/FileRepository.php
FileRepository.getFileName
public function getFileName() { $filename = substr( strrchr( $this->elfinderFilePath, '/' ), 1 ); $parts = explode('.',$filename); $last = array_pop($parts); $filename = str_slug(implode('_',$parts)) . '_' . time(); return $filename . '.' . $last; }
php
public function getFileName() { $filename = substr( strrchr( $this->elfinderFilePath, '/' ), 1 ); $parts = explode('.',$filename); $last = array_pop($parts); $filename = str_slug(implode('_',$parts)) . '_' . time(); return $filename . '.' . $last; }
[ "public", "function", "getFileName", "(", ")", "{", "$", "filename", "=", "substr", "(", "strrchr", "(", "$", "this", "->", "elfinderFilePath", ",", "'/'", ")", ",", "1", ")", ";", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "filename", ")", ";", "$", "last", "=", "array_pop", "(", "$", "parts", ")", ";", "$", "filename", "=", "str_slug", "(", "implode", "(", "'_'", ",", "$", "parts", ")", ")", ".", "'_'", ".", "time", "(", ")", ";", "return", "$", "filename", ".", "'.'", ".", "$", "last", ";", "}" ]
get file name of the elfinder file @return string
[ "get", "file", "name", "of", "the", "elfinder", "file" ]
c26600543817642926bcf16ada84009e00d784e0
https://github.com/erenmustafaozdal/laravel-modules-base/blob/c26600543817642926bcf16ada84009e00d784e0/src/Repositories/FileRepository.php#L202-L209
train
erenmustafaozdal/laravel-modules-base
src/Repositories/FileRepository.php
FileRepository.getDatas
public function getDatas($request) { $relation = $this->options['relation']; $columnParams = explode('.',$this->options['column']); if ( ! $relation ) { return [ 'relation_type' => 'not', 'datas' => [ $columnParams[0] => $this->fileName, 'size' => $this->fileSize ] ]; } $datas = []; foreach ($this->files as $file) { $data = [ $columnParams[1] => $file['fileName'], 'size' => $file['fileSize'] ]; if ((isset($this->options['group']) && isset($this->options['add_column'])) || isset($this->options['add_column'])) { foreach($this->options['add_column'] as $column) { $columnData = isset($this->options['group']) ? "{$this->options['group']}.{$this->options['index']}.{$column}" : (isset($this->options['inputPrefix']) ? $this->options['inputPrefix'] . $column : $column); $columnData = $request->input($columnData); if ($columnData) { $data[$column] = $columnData; } } } $datas[] = $data; } return [ 'relation_type' => $relation, 'relation' => $columnParams[0], 'relation_model' => $this->options['relation_model'], 'is_reset' => isset($this->options['is_reset']) && $this->options['is_reset'] ? true : false, 'changeToHasOne' => isset($this->options['changeToHasOne']) ? $this->options['changeToHasOne'] : false, 'datas' => $relation === 'hasOne' ? $datas[0] : $datas ]; }
php
public function getDatas($request) { $relation = $this->options['relation']; $columnParams = explode('.',$this->options['column']); if ( ! $relation ) { return [ 'relation_type' => 'not', 'datas' => [ $columnParams[0] => $this->fileName, 'size' => $this->fileSize ] ]; } $datas = []; foreach ($this->files as $file) { $data = [ $columnParams[1] => $file['fileName'], 'size' => $file['fileSize'] ]; if ((isset($this->options['group']) && isset($this->options['add_column'])) || isset($this->options['add_column'])) { foreach($this->options['add_column'] as $column) { $columnData = isset($this->options['group']) ? "{$this->options['group']}.{$this->options['index']}.{$column}" : (isset($this->options['inputPrefix']) ? $this->options['inputPrefix'] . $column : $column); $columnData = $request->input($columnData); if ($columnData) { $data[$column] = $columnData; } } } $datas[] = $data; } return [ 'relation_type' => $relation, 'relation' => $columnParams[0], 'relation_model' => $this->options['relation_model'], 'is_reset' => isset($this->options['is_reset']) && $this->options['is_reset'] ? true : false, 'changeToHasOne' => isset($this->options['changeToHasOne']) ? $this->options['changeToHasOne'] : false, 'datas' => $relation === 'hasOne' ? $datas[0] : $datas ]; }
[ "public", "function", "getDatas", "(", "$", "request", ")", "{", "$", "relation", "=", "$", "this", "->", "options", "[", "'relation'", "]", ";", "$", "columnParams", "=", "explode", "(", "'.'", ",", "$", "this", "->", "options", "[", "'column'", "]", ")", ";", "if", "(", "!", "$", "relation", ")", "{", "return", "[", "'relation_type'", "=>", "'not'", ",", "'datas'", "=>", "[", "$", "columnParams", "[", "0", "]", "=>", "$", "this", "->", "fileName", ",", "'size'", "=>", "$", "this", "->", "fileSize", "]", "]", ";", "}", "$", "datas", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "files", "as", "$", "file", ")", "{", "$", "data", "=", "[", "$", "columnParams", "[", "1", "]", "=>", "$", "file", "[", "'fileName'", "]", ",", "'size'", "=>", "$", "file", "[", "'fileSize'", "]", "]", ";", "if", "(", "(", "isset", "(", "$", "this", "->", "options", "[", "'group'", "]", ")", "&&", "isset", "(", "$", "this", "->", "options", "[", "'add_column'", "]", ")", ")", "||", "isset", "(", "$", "this", "->", "options", "[", "'add_column'", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "options", "[", "'add_column'", "]", "as", "$", "column", ")", "{", "$", "columnData", "=", "isset", "(", "$", "this", "->", "options", "[", "'group'", "]", ")", "?", "\"{$this->options['group']}.{$this->options['index']}.{$column}\"", ":", "(", "isset", "(", "$", "this", "->", "options", "[", "'inputPrefix'", "]", ")", "?", "$", "this", "->", "options", "[", "'inputPrefix'", "]", ".", "$", "column", ":", "$", "column", ")", ";", "$", "columnData", "=", "$", "request", "->", "input", "(", "$", "columnData", ")", ";", "if", "(", "$", "columnData", ")", "{", "$", "data", "[", "$", "column", "]", "=", "$", "columnData", ";", "}", "}", "}", "$", "datas", "[", "]", "=", "$", "data", ";", "}", "return", "[", "'relation_type'", "=>", "$", "relation", ",", "'relation'", "=>", "$", "columnParams", "[", "0", "]", ",", "'relation_model'", "=>", "$", "this", "->", "options", "[", "'relation_model'", "]", ",", "'is_reset'", "=>", "isset", "(", "$", "this", "->", "options", "[", "'is_reset'", "]", ")", "&&", "$", "this", "->", "options", "[", "'is_reset'", "]", "?", "true", ":", "false", ",", "'changeToHasOne'", "=>", "isset", "(", "$", "this", "->", "options", "[", "'changeToHasOne'", "]", ")", "?", "$", "this", "->", "options", "[", "'changeToHasOne'", "]", ":", "false", ",", "'datas'", "=>", "$", "relation", "===", "'hasOne'", "?", "$", "datas", "[", "0", "]", ":", "$", "datas", "]", ";", "}" ]
get datas for save the database @param $request @return array
[ "get", "datas", "for", "save", "the", "database" ]
c26600543817642926bcf16ada84009e00d784e0
https://github.com/erenmustafaozdal/laravel-modules-base/blob/c26600543817642926bcf16ada84009e00d784e0/src/Repositories/FileRepository.php#L228-L269
train
erenmustafaozdal/laravel-modules-base
src/Repositories/FileRepository.php
FileRepository.deletePhoto
public function deletePhoto($model, $parentRelation = null) { $thumbs = $this->options['photo']['thumbnails']; $id = is_null($parentRelation) ? $model->id : $model->$parentRelation->id; $path = $this->options['photo']['path'] . "/{$id}"; // delete original $this->delete($path . "/original/{$model->photo}"); // thumbnails delete foreach($thumbs as $thumb => $size){ $this->delete($path . "/thumbnails/{$thumb}_{$model->photo}"); } }
php
public function deletePhoto($model, $parentRelation = null) { $thumbs = $this->options['photo']['thumbnails']; $id = is_null($parentRelation) ? $model->id : $model->$parentRelation->id; $path = $this->options['photo']['path'] . "/{$id}"; // delete original $this->delete($path . "/original/{$model->photo}"); // thumbnails delete foreach($thumbs as $thumb => $size){ $this->delete($path . "/thumbnails/{$thumb}_{$model->photo}"); } }
[ "public", "function", "deletePhoto", "(", "$", "model", ",", "$", "parentRelation", "=", "null", ")", "{", "$", "thumbs", "=", "$", "this", "->", "options", "[", "'photo'", "]", "[", "'thumbnails'", "]", ";", "$", "id", "=", "is_null", "(", "$", "parentRelation", ")", "?", "$", "model", "->", "id", ":", "$", "model", "->", "$", "parentRelation", "->", "id", ";", "$", "path", "=", "$", "this", "->", "options", "[", "'photo'", "]", "[", "'path'", "]", ".", "\"/{$id}\"", ";", "// delete original\r", "$", "this", "->", "delete", "(", "$", "path", ".", "\"/original/{$model->photo}\"", ")", ";", "// thumbnails delete\r", "foreach", "(", "$", "thumbs", "as", "$", "thumb", "=>", "$", "size", ")", "{", "$", "this", "->", "delete", "(", "$", "path", ".", "\"/thumbnails/{$thumb}_{$model->photo}\"", ")", ";", "}", "}" ]
delete file with model path @param \Illuminate\Database\Eloquent\Model $model @param string|null $parentRelation
[ "delete", "file", "with", "model", "path" ]
c26600543817642926bcf16ada84009e00d784e0
https://github.com/erenmustafaozdal/laravel-modules-base/blob/c26600543817642926bcf16ada84009e00d784e0/src/Repositories/FileRepository.php#L287-L298
train
erenmustafaozdal/laravel-modules-base
src/Repositories/FileRepository.php
FileRepository.deleteDirectories
public function deleteDirectories($model, $parentRelation = null) { $id = is_null($parentRelation) ? $model->id : $model->$parentRelation->id; foreach($this->options as $option){ $this->deleteDirectory($option['path'] . "/{$id}"); } }
php
public function deleteDirectories($model, $parentRelation = null) { $id = is_null($parentRelation) ? $model->id : $model->$parentRelation->id; foreach($this->options as $option){ $this->deleteDirectory($option['path'] . "/{$id}"); } }
[ "public", "function", "deleteDirectories", "(", "$", "model", ",", "$", "parentRelation", "=", "null", ")", "{", "$", "id", "=", "is_null", "(", "$", "parentRelation", ")", "?", "$", "model", "->", "id", ":", "$", "model", "->", "$", "parentRelation", "->", "id", ";", "foreach", "(", "$", "this", "->", "options", "as", "$", "option", ")", "{", "$", "this", "->", "deleteDirectory", "(", "$", "option", "[", "'path'", "]", ".", "\"/{$id}\"", ")", ";", "}", "}" ]
delete multiple directories with model path @param \Illuminate\Database\Eloquent\Model $model @param string|null $parentRelation
[ "delete", "multiple", "directories", "with", "model", "path" ]
c26600543817642926bcf16ada84009e00d784e0
https://github.com/erenmustafaozdal/laravel-modules-base/blob/c26600543817642926bcf16ada84009e00d784e0/src/Repositories/FileRepository.php#L316-L322
train
erenmustafaozdal/laravel-modules-base
src/Repositories/FileRepository.php
FileRepository.makeDirectoryBeforeUpload
public function makeDirectoryBeforeUpload($path, $cleanDirectory = false) { if (! $this->exists($path)) { $this->makeDirectory($path, 0775, true); return true; } // tamamen silip oluşturmak istendi ise if (($this->exists($path) && $cleanDirectory) || (isset($this->options['is_reset']) && $this->options['is_reset'])) { $this->deleteDirectory($path, true); $this->makeDirectory($path, 0775, true, true); return true; } if ($this->options['relation'] !== 'hasMany' && ( ! isset($this->options['is_reset']) || $this->options['is_reset']) ) { $this->cleanDirectory($path); } return true; }
php
public function makeDirectoryBeforeUpload($path, $cleanDirectory = false) { if (! $this->exists($path)) { $this->makeDirectory($path, 0775, true); return true; } // tamamen silip oluşturmak istendi ise if (($this->exists($path) && $cleanDirectory) || (isset($this->options['is_reset']) && $this->options['is_reset'])) { $this->deleteDirectory($path, true); $this->makeDirectory($path, 0775, true, true); return true; } if ($this->options['relation'] !== 'hasMany' && ( ! isset($this->options['is_reset']) || $this->options['is_reset']) ) { $this->cleanDirectory($path); } return true; }
[ "public", "function", "makeDirectoryBeforeUpload", "(", "$", "path", ",", "$", "cleanDirectory", "=", "false", ")", "{", "if", "(", "!", "$", "this", "->", "exists", "(", "$", "path", ")", ")", "{", "$", "this", "->", "makeDirectory", "(", "$", "path", ",", "0775", ",", "true", ")", ";", "return", "true", ";", "}", "// tamamen silip oluşturmak istendi ise\r", "if", "(", "(", "$", "this", "->", "exists", "(", "$", "path", ")", "&&", "$", "cleanDirectory", ")", "||", "(", "isset", "(", "$", "this", "->", "options", "[", "'is_reset'", "]", ")", "&&", "$", "this", "->", "options", "[", "'is_reset'", "]", ")", ")", "{", "$", "this", "->", "deleteDirectory", "(", "$", "path", ",", "true", ")", ";", "$", "this", "->", "makeDirectory", "(", "$", "path", ",", "0775", ",", "true", ",", "true", ")", ";", "return", "true", ";", "}", "if", "(", "$", "this", "->", "options", "[", "'relation'", "]", "!==", "'hasMany'", "&&", "(", "!", "isset", "(", "$", "this", "->", "options", "[", "'is_reset'", "]", ")", "||", "$", "this", "->", "options", "[", "'is_reset'", "]", ")", ")", "{", "$", "this", "->", "cleanDirectory", "(", "$", "path", ")", ";", "}", "return", "true", ";", "}" ]
if not exists make directory or clean directory @param string $path @param boolean $cleanDirectory @return boolean
[ "if", "not", "exists", "make", "directory", "or", "clean", "directory" ]
c26600543817642926bcf16ada84009e00d784e0
https://github.com/erenmustafaozdal/laravel-modules-base/blob/c26600543817642926bcf16ada84009e00d784e0/src/Repositories/FileRepository.php#L332-L350
train
Stinger-Soft/TwigExtensions
src/StingerSoft/TwigExtensions/StaticExtensions.php
StaticExtensions.staticProperty
public function staticProperty($class, $property, $args = array()) { if(!class_exists($class)) return null; if(!property_exists($class, $property)) return null; $vars = get_class_vars($class); return $vars[$property]; }
php
public function staticProperty($class, $property, $args = array()) { if(!class_exists($class)) return null; if(!property_exists($class, $property)) return null; $vars = get_class_vars($class); return $vars[$property]; }
[ "public", "function", "staticProperty", "(", "$", "class", ",", "$", "property", ",", "$", "args", "=", "array", "(", ")", ")", "{", "if", "(", "!", "class_exists", "(", "$", "class", ")", ")", "return", "null", ";", "if", "(", "!", "property_exists", "(", "$", "class", ",", "$", "property", ")", ")", "return", "null", ";", "$", "vars", "=", "get_class_vars", "(", "$", "class", ")", ";", "return", "$", "vars", "[", "$", "property", "]", ";", "}" ]
Calls a static method on the given class @param string $class Full name of the class to execute a method on @param string $function The name of the static method @param array $args The arguments to pass to the method @return NULL|mixed
[ "Calls", "a", "static", "method", "on", "the", "given", "class" ]
7bfce337b0dd33106e22f80b221338451a02d7c5
https://github.com/Stinger-Soft/TwigExtensions/blob/7bfce337b0dd33106e22f80b221338451a02d7c5/src/StingerSoft/TwigExtensions/StaticExtensions.php#L69-L77
train
spiral/console
src/Console.php
Console.start
public function start(InputInterface $input = null, OutputInterface $output = null): int { return ContainerScope::runScope($this->container, function () use ($input, $output) { return $this->getApplication()->run($input, $output); }); }
php
public function start(InputInterface $input = null, OutputInterface $output = null): int { return ContainerScope::runScope($this->container, function () use ($input, $output) { return $this->getApplication()->run($input, $output); }); }
[ "public", "function", "start", "(", "InputInterface", "$", "input", "=", "null", ",", "OutputInterface", "$", "output", "=", "null", ")", ":", "int", "{", "return", "ContainerScope", "::", "runScope", "(", "$", "this", "->", "container", ",", "function", "(", ")", "use", "(", "$", "input", ",", "$", "output", ")", "{", "return", "$", "this", "->", "getApplication", "(", ")", "->", "run", "(", "$", "input", ",", "$", "output", ")", ";", "}", ")", ";", "}" ]
Run console application. @param InputInterface|null $input @param OutputInterface|null $output @return int @throws \Throwable
[ "Run", "console", "application", "." ]
c3d99450ddd32bcc6f87e2b2ed40821054a93da3
https://github.com/spiral/console/blob/c3d99450ddd32bcc6f87e2b2ed40821054a93da3/src/Console.php#L64-L69
train
spiral/console
src/Console.php
Console.run
public function run( ?string $command, $input = [], OutputInterface $output = null ): CommandOutput { if (is_array($input)) { $input = new ArrayInput($input + compact('command')); } $output = $output ?? new BufferedOutput(); $command = $this->getApplication()->find($command); $code = ContainerScope::runScope($this->container, function () use ( $command, $input, $output ) { return $command->run($input, $output); }); return new CommandOutput($code ?? self::CODE_NONE, $output); }
php
public function run( ?string $command, $input = [], OutputInterface $output = null ): CommandOutput { if (is_array($input)) { $input = new ArrayInput($input + compact('command')); } $output = $output ?? new BufferedOutput(); $command = $this->getApplication()->find($command); $code = ContainerScope::runScope($this->container, function () use ( $command, $input, $output ) { return $command->run($input, $output); }); return new CommandOutput($code ?? self::CODE_NONE, $output); }
[ "public", "function", "run", "(", "?", "string", "$", "command", ",", "$", "input", "=", "[", "]", ",", "OutputInterface", "$", "output", "=", "null", ")", ":", "CommandOutput", "{", "if", "(", "is_array", "(", "$", "input", ")", ")", "{", "$", "input", "=", "new", "ArrayInput", "(", "$", "input", "+", "compact", "(", "'command'", ")", ")", ";", "}", "$", "output", "=", "$", "output", "??", "new", "BufferedOutput", "(", ")", ";", "$", "command", "=", "$", "this", "->", "getApplication", "(", ")", "->", "find", "(", "$", "command", ")", ";", "$", "code", "=", "ContainerScope", "::", "runScope", "(", "$", "this", "->", "container", ",", "function", "(", ")", "use", "(", "$", "command", ",", "$", "input", ",", "$", "output", ")", "{", "return", "$", "command", "->", "run", "(", "$", "input", ",", "$", "output", ")", ";", "}", ")", ";", "return", "new", "CommandOutput", "(", "$", "code", "??", "self", "::", "CODE_NONE", ",", "$", "output", ")", ";", "}" ]
Run selected command. @param string $command @param InputInterface|array $input @param OutputInterface|null $output @return CommandOutput @throws \Throwable @throws CommandNotFoundException
[ "Run", "selected", "command", "." ]
c3d99450ddd32bcc6f87e2b2ed40821054a93da3
https://github.com/spiral/console/blob/c3d99450ddd32bcc6f87e2b2ed40821054a93da3/src/Console.php#L82-L102
train
spiral/console
src/Console.php
Console.getApplication
public function getApplication(): Application { if (!empty($this->application)) { return $this->application; } $this->application = new Application($this->config->getName(), $this->config->getVersion()); $this->application->setCatchExceptions(false); $this->application->setAutoExit(false); if (!is_null($this->locator)) { foreach ($this->locator->locateCommands() as $command) { $this->application->add($command); } } // Register user defined commands $static = new StaticLocator($this->config->getCommands(), $this->container); foreach ($static->locateCommands() as $command) { $this->application->add($command); } return $this->application; }
php
public function getApplication(): Application { if (!empty($this->application)) { return $this->application; } $this->application = new Application($this->config->getName(), $this->config->getVersion()); $this->application->setCatchExceptions(false); $this->application->setAutoExit(false); if (!is_null($this->locator)) { foreach ($this->locator->locateCommands() as $command) { $this->application->add($command); } } // Register user defined commands $static = new StaticLocator($this->config->getCommands(), $this->container); foreach ($static->locateCommands() as $command) { $this->application->add($command); } return $this->application; }
[ "public", "function", "getApplication", "(", ")", ":", "Application", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "application", ")", ")", "{", "return", "$", "this", "->", "application", ";", "}", "$", "this", "->", "application", "=", "new", "Application", "(", "$", "this", "->", "config", "->", "getName", "(", ")", ",", "$", "this", "->", "config", "->", "getVersion", "(", ")", ")", ";", "$", "this", "->", "application", "->", "setCatchExceptions", "(", "false", ")", ";", "$", "this", "->", "application", "->", "setAutoExit", "(", "false", ")", ";", "if", "(", "!", "is_null", "(", "$", "this", "->", "locator", ")", ")", "{", "foreach", "(", "$", "this", "->", "locator", "->", "locateCommands", "(", ")", "as", "$", "command", ")", "{", "$", "this", "->", "application", "->", "add", "(", "$", "command", ")", ";", "}", "}", "// Register user defined commands", "$", "static", "=", "new", "StaticLocator", "(", "$", "this", "->", "config", "->", "getCommands", "(", ")", ",", "$", "this", "->", "container", ")", ";", "foreach", "(", "$", "static", "->", "locateCommands", "(", ")", "as", "$", "command", ")", "{", "$", "this", "->", "application", "->", "add", "(", "$", "command", ")", ";", "}", "return", "$", "this", "->", "application", ";", "}" ]
Get associated Symfony Console Application. @return Application @throws \Spiral\Console\Exception\LocatorException
[ "Get", "associated", "Symfony", "Console", "Application", "." ]
c3d99450ddd32bcc6f87e2b2ed40821054a93da3
https://github.com/spiral/console/blob/c3d99450ddd32bcc6f87e2b2ed40821054a93da3/src/Console.php#L111-L134
train
wb-crowdfusion/crowdfusion
system/core/classes/mvc/filters/NumberFilterer.php
NumberFilterer.format
protected function format() { $number = $this->getParameter('number'); if($number instanceof Meta) { $number = $number->getValue(); } if(empty($number) || !is_numeric($number)) { return 0; } $decimals = $this->getParameter('decimals'); $decimal_sep = $this->getParameter('decimal_separator'); $thousands_sep = $this->getParameter('thousands_separator'); return number_format((double)$number, $decimals, $decimal_sep, $thousands_sep); }
php
protected function format() { $number = $this->getParameter('number'); if($number instanceof Meta) { $number = $number->getValue(); } if(empty($number) || !is_numeric($number)) { return 0; } $decimals = $this->getParameter('decimals'); $decimal_sep = $this->getParameter('decimal_separator'); $thousands_sep = $this->getParameter('thousands_separator'); return number_format((double)$number, $decimals, $decimal_sep, $thousands_sep); }
[ "protected", "function", "format", "(", ")", "{", "$", "number", "=", "$", "this", "->", "getParameter", "(", "'number'", ")", ";", "if", "(", "$", "number", "instanceof", "Meta", ")", "{", "$", "number", "=", "$", "number", "->", "getValue", "(", ")", ";", "}", "if", "(", "empty", "(", "$", "number", ")", "||", "!", "is_numeric", "(", "$", "number", ")", ")", "{", "return", "0", ";", "}", "$", "decimals", "=", "$", "this", "->", "getParameter", "(", "'decimals'", ")", ";", "$", "decimal_sep", "=", "$", "this", "->", "getParameter", "(", "'decimal_separator'", ")", ";", "$", "thousands_sep", "=", "$", "this", "->", "getParameter", "(", "'thousands_separator'", ")", ";", "return", "number_format", "(", "(", "double", ")", "$", "number", ",", "$", "decimals", ",", "$", "decimal_sep", ",", "$", "thousands_sep", ")", ";", "}" ]
wrapper for number_format @return int|string
[ "wrapper", "for", "number_format" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/filters/NumberFilterer.php#L26-L42
train
wb-crowdfusion/crowdfusion
system/core/classes/mvc/filters/NumberFilterer.php
NumberFilterer.bound
protected function bound() { $number = $this->getParameter('number'); $min = $this->getParameter('min'); $max = $this->getParameter('max'); if ($number instanceof Meta) { $number = $number->getValue(); } return NumberUtils::bound($number, $min, $max); }
php
protected function bound() { $number = $this->getParameter('number'); $min = $this->getParameter('min'); $max = $this->getParameter('max'); if ($number instanceof Meta) { $number = $number->getValue(); } return NumberUtils::bound($number, $min, $max); }
[ "protected", "function", "bound", "(", ")", "{", "$", "number", "=", "$", "this", "->", "getParameter", "(", "'number'", ")", ";", "$", "min", "=", "$", "this", "->", "getParameter", "(", "'min'", ")", ";", "$", "max", "=", "$", "this", "->", "getParameter", "(", "'max'", ")", ";", "if", "(", "$", "number", "instanceof", "Meta", ")", "{", "$", "number", "=", "$", "number", "->", "getValue", "(", ")", ";", "}", "return", "NumberUtils", "::", "bound", "(", "$", "number", ",", "$", "min", ",", "$", "max", ")", ";", "}" ]
Return a number within a range. @return integer
[ "Return", "a", "number", "within", "a", "range", "." ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/filters/NumberFilterer.php#L49-L60
train
pharmonic/container
src/Factory.php
Factory.create
public function create($id, ContainerInterface $container) { if (isset($this->registeredList['services'][$id])) { $data = $this->createService($id, $container); } elseif (isset($this->registeredList['params'][$id])) { $data = $this->registeredList['params'][$id]; } else { $data = null; } return $data; }
php
public function create($id, ContainerInterface $container) { if (isset($this->registeredList['services'][$id])) { $data = $this->createService($id, $container); } elseif (isset($this->registeredList['params'][$id])) { $data = $this->registeredList['params'][$id]; } else { $data = null; } return $data; }
[ "public", "function", "create", "(", "$", "id", ",", "ContainerInterface", "$", "container", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "registeredList", "[", "'services'", "]", "[", "$", "id", "]", ")", ")", "{", "$", "data", "=", "$", "this", "->", "createService", "(", "$", "id", ",", "$", "container", ")", ";", "}", "elseif", "(", "isset", "(", "$", "this", "->", "registeredList", "[", "'params'", "]", "[", "$", "id", "]", ")", ")", "{", "$", "data", "=", "$", "this", "->", "registeredList", "[", "'params'", "]", "[", "$", "id", "]", ";", "}", "else", "{", "$", "data", "=", "null", ";", "}", "return", "$", "data", ";", "}" ]
Create service or parameter based on configured dependencies. @param int $id @param ContainerInterface $container @return mixed
[ "Create", "service", "or", "parameter", "based", "on", "configured", "dependencies", "." ]
100e6e1ab34d111da559fa50f40d5fef6dbb1ec3
https://github.com/pharmonic/container/blob/100e6e1ab34d111da559fa50f40d5fef6dbb1ec3/src/Factory.php#L38-L49
train
pharmonic/container
src/Factory.php
Factory.createResolver
public function createResolver($namespace, $resolution, $newInstance = false) { if (!$this->hasResolution($namespace)) { if ($newInstance) { $resolution = [$resolution, true]; } $this->registeredList['resolves'][$namespace] = $resolution; } }
php
public function createResolver($namespace, $resolution, $newInstance = false) { if (!$this->hasResolution($namespace)) { if ($newInstance) { $resolution = [$resolution, true]; } $this->registeredList['resolves'][$namespace] = $resolution; } }
[ "public", "function", "createResolver", "(", "$", "namespace", ",", "$", "resolution", ",", "$", "newInstance", "=", "false", ")", "{", "if", "(", "!", "$", "this", "->", "hasResolution", "(", "$", "namespace", ")", ")", "{", "if", "(", "$", "newInstance", ")", "{", "$", "resolution", "=", "[", "$", "resolution", ",", "true", "]", ";", "}", "$", "this", "->", "registeredList", "[", "'resolves'", "]", "[", "$", "namespace", "]", "=", "$", "resolution", ";", "}", "}" ]
Resolve a given namespace to given resolution. Will check whether it need new instance or pointed into already defined service according to $newInstance value (default to false) @param string $namespace @param string $resolution @param bool $newInstance
[ "Resolve", "a", "given", "namespace", "to", "given", "resolution", "." ]
100e6e1ab34d111da559fa50f40d5fef6dbb1ec3
https://github.com/pharmonic/container/blob/100e6e1ab34d111da559fa50f40d5fef6dbb1ec3/src/Factory.php#L61-L69
train
pharmonic/container
src/Factory.php
Factory.resolveAndCreate
public function resolveAndCreate($namespace, ContainerInterface $container) { $class = new \ReflectionClass($namespace); $arguments = $this->resolveReflectionArguments($class, $container); return $class->newInstanceArgs($arguments); }
php
public function resolveAndCreate($namespace, ContainerInterface $container) { $class = new \ReflectionClass($namespace); $arguments = $this->resolveReflectionArguments($class, $container); return $class->newInstanceArgs($arguments); }
[ "public", "function", "resolveAndCreate", "(", "$", "namespace", ",", "ContainerInterface", "$", "container", ")", "{", "$", "class", "=", "new", "\\", "ReflectionClass", "(", "$", "namespace", ")", ";", "$", "arguments", "=", "$", "this", "->", "resolveReflectionArguments", "(", "$", "class", ",", "$", "container", ")", ";", "return", "$", "class", "->", "newInstanceArgs", "(", "$", "arguments", ")", ";", "}" ]
Instantiate a new object using constructor injection. @param string $namespace @param ContainerInterface $container @return mixed
[ "Instantiate", "a", "new", "object", "using", "constructor", "injection", "." ]
100e6e1ab34d111da559fa50f40d5fef6dbb1ec3
https://github.com/pharmonic/container/blob/100e6e1ab34d111da559fa50f40d5fef6dbb1ec3/src/Factory.php#L79-L85
train
field-interactive/cito-bundle
Cito/Navigation.php
Navigation.processNodes
public function processNodes(DOMNode $node) { // get all link nodes $allLinkNodes = $this->xp->query('.//a', $node); $allLinkNodesSortedByLength = []; foreach ($allLinkNodes as $linkNode) { $allLinkNodesSortedByLength[] = [ 'href' => $linkNode->getAttribute('href'), 'node' => $linkNode, ]; } // sort by link-length usort( $allLinkNodesSortedByLength, function ($a, $b) { $lengthA = strlen($a['href']); $lengthB = strlen($b['href']); if ($lengthA == $lengthB) { return 0; } return ($lengthA < $lengthB) ? 1 : -1; } ); // set best matching link node to active, all ancestors to open $requestedUri = $this->requestedUri; while (DIRECTORY_SEPARATOR !== $requestedUri) { foreach ($allLinkNodesSortedByLength as $currentLinkNode) { if ($currentLinkNode['href'] === $requestedUri) { $currentLinkNode['node']->setAttribute('class', trim($currentLinkNode['node']->getAttribute('class').' '.self::CLASS_ACTIVE)); // set nearest li ancestor to active $ancestorListNode = $this->xp->query('./ancestor::li', $currentLinkNode['node'])->item( $this->xp->query('./ancestor::li', $currentLinkNode['node'])->length - 1 ); $ancestorListNode->setAttribute('class', trim($ancestorListNode->getAttribute('class').' '.self::CLASS_ACTIVE)); // set all other li ancestors to open and all links inside them to open $remainingAncestorListNodes = $this->xp->query('ancestor::li', $ancestorListNode); foreach ($remainingAncestorListNodes as $remainingAncestorListNode) { $remainingAncestorListNode->setAttribute('class', trim($remainingAncestorListNode->getAttribute('class').' '.self::CLASS_OPEN)); $descendantAnchorNode = $this->xp->query('descendant::a', $remainingAncestorListNode)->item(0); $descendantAnchorNode->setAttribute('class', trim($descendantAnchorNode->getAttribute('class').' '.self::CLASS_OPEN)); } return; } } $requestedUri = dirname($requestedUri); } return false; }
php
public function processNodes(DOMNode $node) { // get all link nodes $allLinkNodes = $this->xp->query('.//a', $node); $allLinkNodesSortedByLength = []; foreach ($allLinkNodes as $linkNode) { $allLinkNodesSortedByLength[] = [ 'href' => $linkNode->getAttribute('href'), 'node' => $linkNode, ]; } // sort by link-length usort( $allLinkNodesSortedByLength, function ($a, $b) { $lengthA = strlen($a['href']); $lengthB = strlen($b['href']); if ($lengthA == $lengthB) { return 0; } return ($lengthA < $lengthB) ? 1 : -1; } ); // set best matching link node to active, all ancestors to open $requestedUri = $this->requestedUri; while (DIRECTORY_SEPARATOR !== $requestedUri) { foreach ($allLinkNodesSortedByLength as $currentLinkNode) { if ($currentLinkNode['href'] === $requestedUri) { $currentLinkNode['node']->setAttribute('class', trim($currentLinkNode['node']->getAttribute('class').' '.self::CLASS_ACTIVE)); // set nearest li ancestor to active $ancestorListNode = $this->xp->query('./ancestor::li', $currentLinkNode['node'])->item( $this->xp->query('./ancestor::li', $currentLinkNode['node'])->length - 1 ); $ancestorListNode->setAttribute('class', trim($ancestorListNode->getAttribute('class').' '.self::CLASS_ACTIVE)); // set all other li ancestors to open and all links inside them to open $remainingAncestorListNodes = $this->xp->query('ancestor::li', $ancestorListNode); foreach ($remainingAncestorListNodes as $remainingAncestorListNode) { $remainingAncestorListNode->setAttribute('class', trim($remainingAncestorListNode->getAttribute('class').' '.self::CLASS_OPEN)); $descendantAnchorNode = $this->xp->query('descendant::a', $remainingAncestorListNode)->item(0); $descendantAnchorNode->setAttribute('class', trim($descendantAnchorNode->getAttribute('class').' '.self::CLASS_OPEN)); } return; } } $requestedUri = dirname($requestedUri); } return false; }
[ "public", "function", "processNodes", "(", "DOMNode", "$", "node", ")", "{", "// get all link nodes", "$", "allLinkNodes", "=", "$", "this", "->", "xp", "->", "query", "(", "'.//a'", ",", "$", "node", ")", ";", "$", "allLinkNodesSortedByLength", "=", "[", "]", ";", "foreach", "(", "$", "allLinkNodes", "as", "$", "linkNode", ")", "{", "$", "allLinkNodesSortedByLength", "[", "]", "=", "[", "'href'", "=>", "$", "linkNode", "->", "getAttribute", "(", "'href'", ")", ",", "'node'", "=>", "$", "linkNode", ",", "]", ";", "}", "// sort by link-length", "usort", "(", "$", "allLinkNodesSortedByLength", ",", "function", "(", "$", "a", ",", "$", "b", ")", "{", "$", "lengthA", "=", "strlen", "(", "$", "a", "[", "'href'", "]", ")", ";", "$", "lengthB", "=", "strlen", "(", "$", "b", "[", "'href'", "]", ")", ";", "if", "(", "$", "lengthA", "==", "$", "lengthB", ")", "{", "return", "0", ";", "}", "return", "(", "$", "lengthA", "<", "$", "lengthB", ")", "?", "1", ":", "-", "1", ";", "}", ")", ";", "// set best matching link node to active, all ancestors to open", "$", "requestedUri", "=", "$", "this", "->", "requestedUri", ";", "while", "(", "DIRECTORY_SEPARATOR", "!==", "$", "requestedUri", ")", "{", "foreach", "(", "$", "allLinkNodesSortedByLength", "as", "$", "currentLinkNode", ")", "{", "if", "(", "$", "currentLinkNode", "[", "'href'", "]", "===", "$", "requestedUri", ")", "{", "$", "currentLinkNode", "[", "'node'", "]", "->", "setAttribute", "(", "'class'", ",", "trim", "(", "$", "currentLinkNode", "[", "'node'", "]", "->", "getAttribute", "(", "'class'", ")", ".", "' '", ".", "self", "::", "CLASS_ACTIVE", ")", ")", ";", "// set nearest li ancestor to active", "$", "ancestorListNode", "=", "$", "this", "->", "xp", "->", "query", "(", "'./ancestor::li'", ",", "$", "currentLinkNode", "[", "'node'", "]", ")", "->", "item", "(", "$", "this", "->", "xp", "->", "query", "(", "'./ancestor::li'", ",", "$", "currentLinkNode", "[", "'node'", "]", ")", "->", "length", "-", "1", ")", ";", "$", "ancestorListNode", "->", "setAttribute", "(", "'class'", ",", "trim", "(", "$", "ancestorListNode", "->", "getAttribute", "(", "'class'", ")", ".", "' '", ".", "self", "::", "CLASS_ACTIVE", ")", ")", ";", "// set all other li ancestors to open and all links inside them to open", "$", "remainingAncestorListNodes", "=", "$", "this", "->", "xp", "->", "query", "(", "'ancestor::li'", ",", "$", "ancestorListNode", ")", ";", "foreach", "(", "$", "remainingAncestorListNodes", "as", "$", "remainingAncestorListNode", ")", "{", "$", "remainingAncestorListNode", "->", "setAttribute", "(", "'class'", ",", "trim", "(", "$", "remainingAncestorListNode", "->", "getAttribute", "(", "'class'", ")", ".", "' '", ".", "self", "::", "CLASS_OPEN", ")", ")", ";", "$", "descendantAnchorNode", "=", "$", "this", "->", "xp", "->", "query", "(", "'descendant::a'", ",", "$", "remainingAncestorListNode", ")", "->", "item", "(", "0", ")", ";", "$", "descendantAnchorNode", "->", "setAttribute", "(", "'class'", ",", "trim", "(", "$", "descendantAnchorNode", "->", "getAttribute", "(", "'class'", ")", ".", "' '", ".", "self", "::", "CLASS_OPEN", ")", ")", ";", "}", "return", ";", "}", "}", "$", "requestedUri", "=", "dirname", "(", "$", "requestedUri", ")", ";", "}", "return", "false", ";", "}" ]
Process node. @param DOMNode $node @return bool|void
[ "Process", "node", "." ]
41cab570f960d964916e278c616720b17de258c1
https://github.com/field-interactive/cito-bundle/blob/41cab570f960d964916e278c616720b17de258c1/Cito/Navigation.php#L87-L141
train
field-interactive/cito-bundle
Cito/Navigation.php
Navigation.filterRange
public function filterRange($range) { if (is_int($range)) { $level = $range; $depth = 0; } else { reset($range); $level = key($range); $depth = current($range); } if (1 === $level) { $nodeList = $this->xp->query('/descendant-or-self::*[ name() = "ul" and count( ancestor-or-self::ul ) >= '.$level.' ]')->item(0); } else { $nodeList = $this->xp->query('/descendant-or-self::*[ name() = "ul" and count( ancestor-or-self::ul ) >= '.$level.' and ( descendant-or-self::*[ contains(@class, "open") or contains(@class, "active") ] or ancestor-or-self::*[ contains(@class, "open") or contains(@class, "active") ] ) ]')->item(0); } if (!$nodeList) { return false; } if (false === $depth) { return $nodeList; } $depthNodelist = $this->xp->query('./descendant::*[ name() = "ul" and count( ancestor-or-self::ul ) > '.($level + $depth).' ]', $nodeList); foreach ($depthNodelist as $node) { $node->parentNode->removeChild($node); } if ($nodeList) { return $nodeList; } else { return false; } }
php
public function filterRange($range) { if (is_int($range)) { $level = $range; $depth = 0; } else { reset($range); $level = key($range); $depth = current($range); } if (1 === $level) { $nodeList = $this->xp->query('/descendant-or-self::*[ name() = "ul" and count( ancestor-or-self::ul ) >= '.$level.' ]')->item(0); } else { $nodeList = $this->xp->query('/descendant-or-self::*[ name() = "ul" and count( ancestor-or-self::ul ) >= '.$level.' and ( descendant-or-self::*[ contains(@class, "open") or contains(@class, "active") ] or ancestor-or-self::*[ contains(@class, "open") or contains(@class, "active") ] ) ]')->item(0); } if (!$nodeList) { return false; } if (false === $depth) { return $nodeList; } $depthNodelist = $this->xp->query('./descendant::*[ name() = "ul" and count( ancestor-or-self::ul ) > '.($level + $depth).' ]', $nodeList); foreach ($depthNodelist as $node) { $node->parentNode->removeChild($node); } if ($nodeList) { return $nodeList; } else { return false; } }
[ "public", "function", "filterRange", "(", "$", "range", ")", "{", "if", "(", "is_int", "(", "$", "range", ")", ")", "{", "$", "level", "=", "$", "range", ";", "$", "depth", "=", "0", ";", "}", "else", "{", "reset", "(", "$", "range", ")", ";", "$", "level", "=", "key", "(", "$", "range", ")", ";", "$", "depth", "=", "current", "(", "$", "range", ")", ";", "}", "if", "(", "1", "===", "$", "level", ")", "{", "$", "nodeList", "=", "$", "this", "->", "xp", "->", "query", "(", "'/descendant-or-self::*[ name() = \"ul\" and count( ancestor-or-self::ul ) >= '", ".", "$", "level", ".", "' ]'", ")", "->", "item", "(", "0", ")", ";", "}", "else", "{", "$", "nodeList", "=", "$", "this", "->", "xp", "->", "query", "(", "'/descendant-or-self::*[ name() = \"ul\" and count( ancestor-or-self::ul ) >= '", ".", "$", "level", ".", "' and ( descendant-or-self::*[ contains(@class, \"open\") or contains(@class, \"active\") ] or ancestor-or-self::*[ contains(@class, \"open\") or contains(@class, \"active\") ] ) ]'", ")", "->", "item", "(", "0", ")", ";", "}", "if", "(", "!", "$", "nodeList", ")", "{", "return", "false", ";", "}", "if", "(", "false", "===", "$", "depth", ")", "{", "return", "$", "nodeList", ";", "}", "$", "depthNodelist", "=", "$", "this", "->", "xp", "->", "query", "(", "'./descendant::*[ name() = \"ul\" and count( ancestor-or-self::ul ) > '", ".", "(", "$", "level", "+", "$", "depth", ")", ".", "' ]'", ",", "$", "nodeList", ")", ";", "foreach", "(", "$", "depthNodelist", "as", "$", "node", ")", "{", "$", "node", "->", "parentNode", "->", "removeChild", "(", "$", "node", ")", ";", "}", "if", "(", "$", "nodeList", ")", "{", "return", "$", "nodeList", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Restrict navigation to given range. Examples: $range = 3, only show level 3 $range = array( 1 => 0 ), only show level 1 and 0 nested levels @param array $range @return DOMNode $nodeList
[ "Restrict", "navigation", "to", "given", "range", "." ]
41cab570f960d964916e278c616720b17de258c1
https://github.com/field-interactive/cito-bundle/blob/41cab570f960d964916e278c616720b17de258c1/Cito/Navigation.php#L154-L190
train
field-interactive/cito-bundle
Cito/Navigation.php
Navigation.filterBreadcrumb
public function filterBreadcrumb() { $nodeList = $this->xp->query('//li[ contains(@class, "open") or contains(@class, "active")]'); if (0 !== $nodeList->length) { $ul = $this->dom->createElement('ul'); foreach ($nodeList as $node) { $li = $this->dom->createElement('li'); $li->appendChild($node->firstChild); $ul->appendChild($li); } return $ul; } }
php
public function filterBreadcrumb() { $nodeList = $this->xp->query('//li[ contains(@class, "open") or contains(@class, "active")]'); if (0 !== $nodeList->length) { $ul = $this->dom->createElement('ul'); foreach ($nodeList as $node) { $li = $this->dom->createElement('li'); $li->appendChild($node->firstChild); $ul->appendChild($li); } return $ul; } }
[ "public", "function", "filterBreadcrumb", "(", ")", "{", "$", "nodeList", "=", "$", "this", "->", "xp", "->", "query", "(", "'//li[ contains(@class, \"open\") or contains(@class, \"active\")]'", ")", ";", "if", "(", "0", "!==", "$", "nodeList", "->", "length", ")", "{", "$", "ul", "=", "$", "this", "->", "dom", "->", "createElement", "(", "'ul'", ")", ";", "foreach", "(", "$", "nodeList", "as", "$", "node", ")", "{", "$", "li", "=", "$", "this", "->", "dom", "->", "createElement", "(", "'li'", ")", ";", "$", "li", "->", "appendChild", "(", "$", "node", "->", "firstChild", ")", ";", "$", "ul", "->", "appendChild", "(", "$", "li", ")", ";", "}", "return", "$", "ul", ";", "}", "}" ]
Create breadcrumb for current page. @return DOMNode $nodeList
[ "Create", "breadcrumb", "for", "current", "page", "." ]
41cab570f960d964916e278c616720b17de258c1
https://github.com/field-interactive/cito-bundle/blob/41cab570f960d964916e278c616720b17de258c1/Cito/Navigation.php#L197-L210
train
field-interactive/cito-bundle
Cito/Navigation.php
Navigation.render
public static function render($navigationFile, $requestedUri = false, $options = null) { $instance = new Navigation($navigationFile, $requestedUri); if ($options) { if (isset($options['breadcrumb'])) { $temp = $instance->filterBreadcrumb(); if ($temp) { return $instance->dom->saveXML($temp); } } if (isset($options['range']) && $temp = $instance->filterRange($options['range'])) { return $instance->dom->saveXML($temp); } } else { return $instance->dom->saveXML($instance->dom->documentElement); } }
php
public static function render($navigationFile, $requestedUri = false, $options = null) { $instance = new Navigation($navigationFile, $requestedUri); if ($options) { if (isset($options['breadcrumb'])) { $temp = $instance->filterBreadcrumb(); if ($temp) { return $instance->dom->saveXML($temp); } } if (isset($options['range']) && $temp = $instance->filterRange($options['range'])) { return $instance->dom->saveXML($temp); } } else { return $instance->dom->saveXML($instance->dom->documentElement); } }
[ "public", "static", "function", "render", "(", "$", "navigationFile", ",", "$", "requestedUri", "=", "false", ",", "$", "options", "=", "null", ")", "{", "$", "instance", "=", "new", "Navigation", "(", "$", "navigationFile", ",", "$", "requestedUri", ")", ";", "if", "(", "$", "options", ")", "{", "if", "(", "isset", "(", "$", "options", "[", "'breadcrumb'", "]", ")", ")", "{", "$", "temp", "=", "$", "instance", "->", "filterBreadcrumb", "(", ")", ";", "if", "(", "$", "temp", ")", "{", "return", "$", "instance", "->", "dom", "->", "saveXML", "(", "$", "temp", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "options", "[", "'range'", "]", ")", "&&", "$", "temp", "=", "$", "instance", "->", "filterRange", "(", "$", "options", "[", "'range'", "]", ")", ")", "{", "return", "$", "instance", "->", "dom", "->", "saveXML", "(", "$", "temp", ")", ";", "}", "}", "else", "{", "return", "$", "instance", "->", "dom", "->", "saveXML", "(", "$", "instance", "->", "dom", "->", "documentElement", ")", ";", "}", "}" ]
Static helper function to render Navigation. @param string $navigationSource XML/HTML source, unordered list @param string $requestedUri requested URI @param string $options Navigation options @return string
[ "Static", "helper", "function", "to", "render", "Navigation", "." ]
41cab570f960d964916e278c616720b17de258c1
https://github.com/field-interactive/cito-bundle/blob/41cab570f960d964916e278c616720b17de258c1/Cito/Navigation.php#L221-L237
train
vainproject/vain-user
src/User/Entities/User.php
User.sites
public function sites() { if (!class_exists(\Modules\Site\Entities\Page::class, false)) { throw new \Exception('in order to use User::sites() you have to install the \'vain-sites\' module'); } return $this->hasMany(\Modules\Site\Entities\Page::class); }
php
public function sites() { if (!class_exists(\Modules\Site\Entities\Page::class, false)) { throw new \Exception('in order to use User::sites() you have to install the \'vain-sites\' module'); } return $this->hasMany(\Modules\Site\Entities\Page::class); }
[ "public", "function", "sites", "(", ")", "{", "if", "(", "!", "class_exists", "(", "\\", "Modules", "\\", "Site", "\\", "Entities", "\\", "Page", "::", "class", ",", "false", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'in order to use User::sites() you have to install the \\'vain-sites\\' module'", ")", ";", "}", "return", "$", "this", "->", "hasMany", "(", "\\", "Modules", "\\", "Site", "\\", "Entities", "\\", "Page", "::", "class", ")", ";", "}" ]
created static pages. todo make site module trait to include in user entity @throws \Exception @return mixed
[ "created", "static", "pages", "." ]
1c059faa61ebf289fcaea39a90b4523cfc9d6efc
https://github.com/vainproject/vain-user/blob/1c059faa61ebf289fcaea39a90b4523cfc9d6efc/src/User/Entities/User.php#L87-L94
train
vainproject/vain-user
src/User/Entities/User.php
User.scopeOnline
public function scopeOnline($query) { $expiryDate = Carbon::now() ->subMinutes(config('session.lifetime')); return $query->where('last_active_at', '>', $expiryDate) ->andWhere('logged_out', false); }
php
public function scopeOnline($query) { $expiryDate = Carbon::now() ->subMinutes(config('session.lifetime')); return $query->where('last_active_at', '>', $expiryDate) ->andWhere('logged_out', false); }
[ "public", "function", "scopeOnline", "(", "$", "query", ")", "{", "$", "expiryDate", "=", "Carbon", "::", "now", "(", ")", "->", "subMinutes", "(", "config", "(", "'session.lifetime'", ")", ")", ";", "return", "$", "query", "->", "where", "(", "'last_active_at'", ",", "'>'", ",", "$", "expiryDate", ")", "->", "andWhere", "(", "'logged_out'", ",", "false", ")", ";", "}" ]
queries all possible online users. @param $query @return \Illuminate\Database\Eloquent\Builder|static
[ "queries", "all", "possible", "online", "users", "." ]
1c059faa61ebf289fcaea39a90b4523cfc9d6efc
https://github.com/vainproject/vain-user/blob/1c059faa61ebf289fcaea39a90b4523cfc9d6efc/src/User/Entities/User.php#L135-L142
train
vainproject/vain-user
src/User/Entities/User.php
User.getOnlineAttribute
public function getOnlineAttribute($value) { $expiryDate = Carbon::now() ->subMinutes(config('session.lifetime')); return (!$this->logged_out) && $expiryDate->lt($this->last_active_at); }
php
public function getOnlineAttribute($value) { $expiryDate = Carbon::now() ->subMinutes(config('session.lifetime')); return (!$this->logged_out) && $expiryDate->lt($this->last_active_at); }
[ "public", "function", "getOnlineAttribute", "(", "$", "value", ")", "{", "$", "expiryDate", "=", "Carbon", "::", "now", "(", ")", "->", "subMinutes", "(", "config", "(", "'session.lifetime'", ")", ")", ";", "return", "(", "!", "$", "this", "->", "logged_out", ")", "&&", "$", "expiryDate", "->", "lt", "(", "$", "this", "->", "last_active_at", ")", ";", "}" ]
accessor for current online state. @param $value @return \Illuminate\Database\Eloquent\Model
[ "accessor", "for", "current", "online", "state", "." ]
1c059faa61ebf289fcaea39a90b4523cfc9d6efc
https://github.com/vainproject/vain-user/blob/1c059faa61ebf289fcaea39a90b4523cfc9d6efc/src/User/Entities/User.php#L151-L158
train
vainproject/vain-user
src/User/Entities/User.php
User.saveWithoutTimestamps
public function saveWithoutTimestamps(array $options = []) { $this->timestamps = false; // don't update updated_at $this->save($options); $this->timestamps = true; // forgetting this may result in unexpected behavior }
php
public function saveWithoutTimestamps(array $options = []) { $this->timestamps = false; // don't update updated_at $this->save($options); $this->timestamps = true; // forgetting this may result in unexpected behavior }
[ "public", "function", "saveWithoutTimestamps", "(", "array", "$", "options", "=", "[", "]", ")", "{", "$", "this", "->", "timestamps", "=", "false", ";", "// don't update updated_at", "$", "this", "->", "save", "(", "$", "options", ")", ";", "$", "this", "->", "timestamps", "=", "true", ";", "// forgetting this may result in unexpected behavior", "}" ]
Save the model to the database without updating the timestamps. @param array $options @return bool
[ "Save", "the", "model", "to", "the", "database", "without", "updating", "the", "timestamps", "." ]
1c059faa61ebf289fcaea39a90b4523cfc9d6efc
https://github.com/vainproject/vain-user/blob/1c059faa61ebf289fcaea39a90b4523cfc9d6efc/src/User/Entities/User.php#L191-L197
train
praxigento/mobi_mod_downline
Observer/CustomerSaveAfterDataObject/A/SaveNew.php
SaveNew.getCountryCode
private function getCountryCode() { $posted = $this->appRequest->getPostValue(); if (isset($posted['customer'][ABlock::TMPL_FLDGRP][ABlock::TMPL_FIELD_COUNTRY_CODE])) { $result = $posted['customer'][ABlock::TMPL_FLDGRP][ABlock::TMPL_FIELD_COUNTRY_CODE]; } else { $result = $this->hlpRegistry->getCustomerCountry(); } return $result; }
php
private function getCountryCode() { $posted = $this->appRequest->getPostValue(); if (isset($posted['customer'][ABlock::TMPL_FLDGRP][ABlock::TMPL_FIELD_COUNTRY_CODE])) { $result = $posted['customer'][ABlock::TMPL_FLDGRP][ABlock::TMPL_FIELD_COUNTRY_CODE]; } else { $result = $this->hlpRegistry->getCustomerCountry(); } return $result; }
[ "private", "function", "getCountryCode", "(", ")", "{", "$", "posted", "=", "$", "this", "->", "appRequest", "->", "getPostValue", "(", ")", ";", "if", "(", "isset", "(", "$", "posted", "[", "'customer'", "]", "[", "ABlock", "::", "TMPL_FLDGRP", "]", "[", "ABlock", "::", "TMPL_FIELD_COUNTRY_CODE", "]", ")", ")", "{", "$", "result", "=", "$", "posted", "[", "'customer'", "]", "[", "ABlock", "::", "TMPL_FLDGRP", "]", "[", "ABlock", "::", "TMPL_FIELD_COUNTRY_CODE", "]", ";", "}", "else", "{", "$", "result", "=", "$", "this", "->", "hlpRegistry", "->", "getCustomerCountry", "(", ")", ";", "}", "return", "$", "result", ";", "}" ]
Extract code for customer's registration country from posted data. @return string
[ "Extract", "code", "for", "customer", "s", "registration", "country", "from", "posted", "data", "." ]
0f3c276dfff1aa029f9fd205ccfc56f207a2e75b
https://github.com/praxigento/mobi_mod_downline/blob/0f3c276dfff1aa029f9fd205ccfc56f207a2e75b/Observer/CustomerSaveAfterDataObject/A/SaveNew.php#L62-L71
train
praxigento/mobi_mod_downline
Observer/CustomerSaveAfterDataObject/A/SaveNew.php
SaveNew.getMlmId
private function getMlmId($customer) { $posted = $this->appRequest->getPostValue(); if ( isset($posted['customer'][ABlock::TMPL_FLDGRP][ABlock::TMPL_FIELD_OWN_MLM_ID]) && !empty($posted['customer'][ABlock::TMPL_FLDGRP][ABlock::TMPL_FIELD_OWN_MLM_ID]) ) { $result = $posted['customer'][ABlock::TMPL_FLDGRP][ABlock::TMPL_FIELD_OWN_MLM_ID]; } else { $result = $this->hlpCodeGen->generateMlmId($customer); } return $result; }
php
private function getMlmId($customer) { $posted = $this->appRequest->getPostValue(); if ( isset($posted['customer'][ABlock::TMPL_FLDGRP][ABlock::TMPL_FIELD_OWN_MLM_ID]) && !empty($posted['customer'][ABlock::TMPL_FLDGRP][ABlock::TMPL_FIELD_OWN_MLM_ID]) ) { $result = $posted['customer'][ABlock::TMPL_FLDGRP][ABlock::TMPL_FIELD_OWN_MLM_ID]; } else { $result = $this->hlpCodeGen->generateMlmId($customer); } return $result; }
[ "private", "function", "getMlmId", "(", "$", "customer", ")", "{", "$", "posted", "=", "$", "this", "->", "appRequest", "->", "getPostValue", "(", ")", ";", "if", "(", "isset", "(", "$", "posted", "[", "'customer'", "]", "[", "ABlock", "::", "TMPL_FLDGRP", "]", "[", "ABlock", "::", "TMPL_FIELD_OWN_MLM_ID", "]", ")", "&&", "!", "empty", "(", "$", "posted", "[", "'customer'", "]", "[", "ABlock", "::", "TMPL_FLDGRP", "]", "[", "ABlock", "::", "TMPL_FIELD_OWN_MLM_ID", "]", ")", ")", "{", "$", "result", "=", "$", "posted", "[", "'customer'", "]", "[", "ABlock", "::", "TMPL_FLDGRP", "]", "[", "ABlock", "::", "TMPL_FIELD_OWN_MLM_ID", "]", ";", "}", "else", "{", "$", "result", "=", "$", "this", "->", "hlpCodeGen", "->", "generateMlmId", "(", "$", "customer", ")", ";", "}", "return", "$", "result", ";", "}" ]
Extract customer's MLM ID from posted data or generate new one. @param \Magento\Customer\Model\Data\Customer $customer @return string
[ "Extract", "customer", "s", "MLM", "ID", "from", "posted", "data", "or", "generate", "new", "one", "." ]
0f3c276dfff1aa029f9fd205ccfc56f207a2e75b
https://github.com/praxigento/mobi_mod_downline/blob/0f3c276dfff1aa029f9fd205ccfc56f207a2e75b/Observer/CustomerSaveAfterDataObject/A/SaveNew.php#L79-L91
train
praxigento/mobi_mod_downline
Observer/CustomerSaveAfterDataObject/A/SaveNew.php
SaveNew.getParentId
private function getParentId() { $posted = $this->appRequest->getPostValue(); if (isset($posted['customer'][ABlock::TMPL_FLDGRP][ABlock::TMPL_FIELD_PARENT_MLM_ID])) { $mlmId = $posted['customer'][ABlock::TMPL_FLDGRP][ABlock::TMPL_FIELD_PARENT_MLM_ID]; $found = $this->daoDwnlCust->getByMlmId($mlmId); if ($found) { $result = $found->getCustomerRef(); } } else { $result = null; } return $result; }
php
private function getParentId() { $posted = $this->appRequest->getPostValue(); if (isset($posted['customer'][ABlock::TMPL_FLDGRP][ABlock::TMPL_FIELD_PARENT_MLM_ID])) { $mlmId = $posted['customer'][ABlock::TMPL_FLDGRP][ABlock::TMPL_FIELD_PARENT_MLM_ID]; $found = $this->daoDwnlCust->getByMlmId($mlmId); if ($found) { $result = $found->getCustomerRef(); } } else { $result = null; } return $result; }
[ "private", "function", "getParentId", "(", ")", "{", "$", "posted", "=", "$", "this", "->", "appRequest", "->", "getPostValue", "(", ")", ";", "if", "(", "isset", "(", "$", "posted", "[", "'customer'", "]", "[", "ABlock", "::", "TMPL_FLDGRP", "]", "[", "ABlock", "::", "TMPL_FIELD_PARENT_MLM_ID", "]", ")", ")", "{", "$", "mlmId", "=", "$", "posted", "[", "'customer'", "]", "[", "ABlock", "::", "TMPL_FLDGRP", "]", "[", "ABlock", "::", "TMPL_FIELD_PARENT_MLM_ID", "]", ";", "$", "found", "=", "$", "this", "->", "daoDwnlCust", "->", "getByMlmId", "(", "$", "mlmId", ")", ";", "if", "(", "$", "found", ")", "{", "$", "result", "=", "$", "found", "->", "getCustomerRef", "(", ")", ";", "}", "}", "else", "{", "$", "result", "=", "null", ";", "}", "return", "$", "result", ";", "}" ]
Extract customer's parent ID from posted data or set null to extract it in service later from referral code. @return int|null
[ "Extract", "customer", "s", "parent", "ID", "from", "posted", "data", "or", "set", "null", "to", "extract", "it", "in", "service", "later", "from", "referral", "code", "." ]
0f3c276dfff1aa029f9fd205ccfc56f207a2e75b
https://github.com/praxigento/mobi_mod_downline/blob/0f3c276dfff1aa029f9fd205ccfc56f207a2e75b/Observer/CustomerSaveAfterDataObject/A/SaveNew.php#L98-L111
train
NukaCode/core
src/NukaCode/Core/Models/BaseModel.php
BaseModel.findExistingReferences
public static function findExistingReferences($model, $field) { $invalid = true; $uniqueString = null; while ($invalid == true) { // Create a new random string. $uniqueString = Str::random($model::$uniqueStringLimit); // Look for any instances of that string on the model. $existingReferences = $model::where($field, $uniqueString)->count(); // If none exist, this is a valid unique string. if ($existingReferences == 0) { $invalid = false; } } return $uniqueString; }
php
public static function findExistingReferences($model, $field) { $invalid = true; $uniqueString = null; while ($invalid == true) { // Create a new random string. $uniqueString = Str::random($model::$uniqueStringLimit); // Look for any instances of that string on the model. $existingReferences = $model::where($field, $uniqueString)->count(); // If none exist, this is a valid unique string. if ($existingReferences == 0) { $invalid = false; } } return $uniqueString; }
[ "public", "static", "function", "findExistingReferences", "(", "$", "model", ",", "$", "field", ")", "{", "$", "invalid", "=", "true", ";", "$", "uniqueString", "=", "null", ";", "while", "(", "$", "invalid", "==", "true", ")", "{", "// Create a new random string.", "$", "uniqueString", "=", "Str", "::", "random", "(", "$", "model", "::", "$", "uniqueStringLimit", ")", ";", "// Look for any instances of that string on the model.", "$", "existingReferences", "=", "$", "model", "::", "where", "(", "$", "field", ",", "$", "uniqueString", ")", "->", "count", "(", ")", ";", "// If none exist, this is a valid unique string.", "if", "(", "$", "existingReferences", "==", "0", ")", "{", "$", "invalid", "=", "false", ";", "}", "}", "return", "$", "uniqueString", ";", "}" ]
Make sure the uniqueId is always unique. @param string $model The model to search on. @param $field The field to search on. @return string
[ "Make", "sure", "the", "uniqueId", "is", "always", "unique", "." ]
75b20903fb068a7df22cdec34ae729279fbaab3c
https://github.com/NukaCode/core/blob/75b20903fb068a7df22cdec34ae729279fbaab3c/src/NukaCode/Core/Models/BaseModel.php#L180-L199
train
FuzeWorks/Core
src/FuzeWorks/TemplateEngine/LatteEngine.php
LatteEngine.setDirectory
public function setDirectory($directory) { if (class_exists('\Latte\Engine', true)) { // If possible, load Latte\Engine $this->latte = new Latte; $this->latte->setTempDirectory(realpath(Core::$tempDir . DS . 'Latte')); } else { throw new LayoutException("Could not load LatteEngine. Is it installed or Composer not loaded?", 1); } }
php
public function setDirectory($directory) { if (class_exists('\Latte\Engine', true)) { // If possible, load Latte\Engine $this->latte = new Latte; $this->latte->setTempDirectory(realpath(Core::$tempDir . DS . 'Latte')); } else { throw new LayoutException("Could not load LatteEngine. Is it installed or Composer not loaded?", 1); } }
[ "public", "function", "setDirectory", "(", "$", "directory", ")", "{", "if", "(", "class_exists", "(", "'\\Latte\\Engine'", ",", "true", ")", ")", "{", "// If possible, load Latte\\Engine", "$", "this", "->", "latte", "=", "new", "Latte", ";", "$", "this", "->", "latte", "->", "setTempDirectory", "(", "realpath", "(", "Core", "::", "$", "tempDir", ".", "DS", ".", "'Latte'", ")", ")", ";", "}", "else", "{", "throw", "new", "LayoutException", "(", "\"Could not load LatteEngine. Is it installed or Composer not loaded?\"", ",", "1", ")", ";", "}", "}" ]
Set the directory of the current template. @param string $directory Template Directory
[ "Set", "the", "directory", "of", "the", "current", "template", "." ]
051c64fdaa3a648174cbd54557d05ad553dd826b
https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/FuzeWorks/TemplateEngine/LatteEngine.php#L60-L72
train
jitesoft/php-container
src/Container.php
Container.set
public function set(string $abstract, $concrete, $singleton = false) { if ($this->has($abstract)) { throw new ContainerException( sprintf('An entry with the id "%s" already exists.', $abstract) ); } $this->bindings[$abstract] = new ContainerEntry($abstract, $concrete, $singleton); return true; }
php
public function set(string $abstract, $concrete, $singleton = false) { if ($this->has($abstract)) { throw new ContainerException( sprintf('An entry with the id "%s" already exists.', $abstract) ); } $this->bindings[$abstract] = new ContainerEntry($abstract, $concrete, $singleton); return true; }
[ "public", "function", "set", "(", "string", "$", "abstract", ",", "$", "concrete", ",", "$", "singleton", "=", "false", ")", "{", "if", "(", "$", "this", "->", "has", "(", "$", "abstract", ")", ")", "{", "throw", "new", "ContainerException", "(", "sprintf", "(", "'An entry with the id \"%s\" already exists.'", ",", "$", "abstract", ")", ")", ";", "}", "$", "this", "->", "bindings", "[", "$", "abstract", "]", "=", "new", "ContainerEntry", "(", "$", "abstract", ",", "$", "concrete", ",", "$", "singleton", ")", ";", "return", "true", ";", "}" ]
Bind a abstract to a concrete. If the concrete is a object and not a string, it will be stored as it is. @param string $abstract @param object|string $concrete @param bool $singleton If the created object is intended to be treated as a single instance on creation. @return bool @throws ContainerException
[ "Bind", "a", "abstract", "to", "a", "concrete", ".", "If", "the", "concrete", "is", "a", "object", "and", "not", "a", "string", "it", "will", "be", "stored", "as", "it", "is", "." ]
e24af8e089f5b46219316f9a9c0e0b2193c256b7
https://github.com/jitesoft/php-container/blob/e24af8e089f5b46219316f9a9c0e0b2193c256b7/src/Container.php#L61-L70
train
phpffcms/ffcms-core
src/Helper/Text.php
Text.snippet
public static function snippet(string $text, int $length = 150) { $breakerPos = mb_strpos($text, self::WYSIWYG_BREAK_HTML, null, 'UTF-8'); // offset is founded, try to split preview from full text if ($breakerPos !== false) { $text = Str::sub($text, 0, $breakerPos); } else { // page breaker is not founded, lets get a fun ;D // find first paragraph ending $breakerPos = mb_strpos($text, '</p>', null, 'UTF-8'); // no paragraph's ? lets try to get <br[\/|*]> if ($breakerPos === false) { $breakerPos = mb_strpos($text, '<br', null, 'UTF-8'); } else { // add length('</p>') $breakerPos+= 4; } // cut text from position caret before </p> (+4 symbols to save item as valid) if ($breakerPos !== false) { $text = Str::sub($text, 0, $breakerPos); } } // if breaker position is still undefined - lets make 'text cut' for defined length and remove all html tags if ($breakerPos === false) { $text = strip_tags($text); $text = self::cut($text, 0, $length); } return $text; }
php
public static function snippet(string $text, int $length = 150) { $breakerPos = mb_strpos($text, self::WYSIWYG_BREAK_HTML, null, 'UTF-8'); // offset is founded, try to split preview from full text if ($breakerPos !== false) { $text = Str::sub($text, 0, $breakerPos); } else { // page breaker is not founded, lets get a fun ;D // find first paragraph ending $breakerPos = mb_strpos($text, '</p>', null, 'UTF-8'); // no paragraph's ? lets try to get <br[\/|*]> if ($breakerPos === false) { $breakerPos = mb_strpos($text, '<br', null, 'UTF-8'); } else { // add length('</p>') $breakerPos+= 4; } // cut text from position caret before </p> (+4 symbols to save item as valid) if ($breakerPos !== false) { $text = Str::sub($text, 0, $breakerPos); } } // if breaker position is still undefined - lets make 'text cut' for defined length and remove all html tags if ($breakerPos === false) { $text = strip_tags($text); $text = self::cut($text, 0, $length); } return $text; }
[ "public", "static", "function", "snippet", "(", "string", "$", "text", ",", "int", "$", "length", "=", "150", ")", "{", "$", "breakerPos", "=", "mb_strpos", "(", "$", "text", ",", "self", "::", "WYSIWYG_BREAK_HTML", ",", "null", ",", "'UTF-8'", ")", ";", "// offset is founded, try to split preview from full text", "if", "(", "$", "breakerPos", "!==", "false", ")", "{", "$", "text", "=", "Str", "::", "sub", "(", "$", "text", ",", "0", ",", "$", "breakerPos", ")", ";", "}", "else", "{", "// page breaker is not founded, lets get a fun ;D", "// find first paragraph ending", "$", "breakerPos", "=", "mb_strpos", "(", "$", "text", ",", "'</p>'", ",", "null", ",", "'UTF-8'", ")", ";", "// no paragraph's ? lets try to get <br[\\/|*]>", "if", "(", "$", "breakerPos", "===", "false", ")", "{", "$", "breakerPos", "=", "mb_strpos", "(", "$", "text", ",", "'<br'", ",", "null", ",", "'UTF-8'", ")", ";", "}", "else", "{", "// add length('</p>')", "$", "breakerPos", "+=", "4", ";", "}", "// cut text from position caret before </p> (+4 symbols to save item as valid)", "if", "(", "$", "breakerPos", "!==", "false", ")", "{", "$", "text", "=", "Str", "::", "sub", "(", "$", "text", ",", "0", ",", "$", "breakerPos", ")", ";", "}", "}", "// if breaker position is still undefined - lets make 'text cut' for defined length and remove all html tags", "if", "(", "$", "breakerPos", "===", "false", ")", "{", "$", "text", "=", "strip_tags", "(", "$", "text", ")", ";", "$", "text", "=", "self", "::", "cut", "(", "$", "text", ",", "0", ",", "$", "length", ")", ";", "}", "return", "$", "text", ";", "}" ]
Make snippet from text or html-text content. @param string $text @param int $length @return string
[ "Make", "snippet", "from", "text", "or", "html", "-", "text", "content", "." ]
44a309553ef9f115ccfcfd71f2ac6e381c612082
https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Helper/Text.php#L17-L46
train
mossphp/moss-storage
Moss/Storage/Query/AbstractEntityQuery.php
AbstractEntityQuery.assignEntity
protected function assignEntity($entity) { $entityClass = $this->model->entity(); if ($entity === null) { throw new QueryException(sprintf('Missing required entity of class "%s"', $entityClass)); } if (!is_array($entity) && !$entity instanceof $entityClass) { throw new QueryException(sprintf('Entity must be an instance of "%s" or array got "%s"', $entityClass, $this->getType($entity))); } $this->instance = $entity; }
php
protected function assignEntity($entity) { $entityClass = $this->model->entity(); if ($entity === null) { throw new QueryException(sprintf('Missing required entity of class "%s"', $entityClass)); } if (!is_array($entity) && !$entity instanceof $entityClass) { throw new QueryException(sprintf('Entity must be an instance of "%s" or array got "%s"', $entityClass, $this->getType($entity))); } $this->instance = $entity; }
[ "protected", "function", "assignEntity", "(", "$", "entity", ")", "{", "$", "entityClass", "=", "$", "this", "->", "model", "->", "entity", "(", ")", ";", "if", "(", "$", "entity", "===", "null", ")", "{", "throw", "new", "QueryException", "(", "sprintf", "(", "'Missing required entity of class \"%s\"'", ",", "$", "entityClass", ")", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "entity", ")", "&&", "!", "$", "entity", "instanceof", "$", "entityClass", ")", "{", "throw", "new", "QueryException", "(", "sprintf", "(", "'Entity must be an instance of \"%s\" or array got \"%s\"'", ",", "$", "entityClass", ",", "$", "this", "->", "getType", "(", "$", "entity", ")", ")", ")", ";", "}", "$", "this", "->", "instance", "=", "$", "entity", ";", "}" ]
Assigns entity instance Asserts if entity instance is of expected type @param array|object $entity @throws QueryException
[ "Assigns", "entity", "instance", "Asserts", "if", "entity", "instance", "is", "of", "expected", "type" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/AbstractEntityQuery.php#L55-L68
train
mossphp/moss-storage
Moss/Storage/Query/AbstractEntityQuery.php
AbstractEntityQuery.setPrimaryKeyConditions
protected function setPrimaryKeyConditions() { foreach ($this->model->primaryFields() as $field) { $value = $this->accessor->getPropertyValue($this->instance, $field->name()); $this->builder->andWhere( sprintf( '%s = %s', $this->connection->quoteIdentifier($field->mappedName()), $this->builder->createNamedParameter($value, $field->type()) ) ); } }
php
protected function setPrimaryKeyConditions() { foreach ($this->model->primaryFields() as $field) { $value = $this->accessor->getPropertyValue($this->instance, $field->name()); $this->builder->andWhere( sprintf( '%s = %s', $this->connection->quoteIdentifier($field->mappedName()), $this->builder->createNamedParameter($value, $field->type()) ) ); } }
[ "protected", "function", "setPrimaryKeyConditions", "(", ")", "{", "foreach", "(", "$", "this", "->", "model", "->", "primaryFields", "(", ")", "as", "$", "field", ")", "{", "$", "value", "=", "$", "this", "->", "accessor", "->", "getPropertyValue", "(", "$", "this", "->", "instance", ",", "$", "field", "->", "name", "(", ")", ")", ";", "$", "this", "->", "builder", "->", "andWhere", "(", "sprintf", "(", "'%s = %s'", ",", "$", "this", "->", "connection", "->", "quoteIdentifier", "(", "$", "field", "->", "mappedName", "(", ")", ")", ",", "$", "this", "->", "builder", "->", "createNamedParameter", "(", "$", "value", ",", "$", "field", "->", "type", "(", ")", ")", ")", ")", ";", "}", "}" ]
Assigns primary condition @throws QueryException
[ "Assigns", "primary", "condition" ]
0d123e7ae6bbfce1e2a18e73bf70997277b430c1
https://github.com/mossphp/moss-storage/blob/0d123e7ae6bbfce1e2a18e73bf70997277b430c1/Moss/Storage/Query/AbstractEntityQuery.php#L75-L87
train
vegas-cmf/oauth
src/OAuth/Storage/Session.php
Session.clearToken
public function clearToken($service) { $service = $this->normalizeServiceName($service); $tokens = $this->sessionScope->get(self::SESSION_TOKEN); if (array_key_exists($service, $tokens)) { unset($tokens, $service); } $this->sessionScope->set(self::SESSION_TOKEN, $tokens); return $this; }
php
public function clearToken($service) { $service = $this->normalizeServiceName($service); $tokens = $this->sessionScope->get(self::SESSION_TOKEN); if (array_key_exists($service, $tokens)) { unset($tokens, $service); } $this->sessionScope->set(self::SESSION_TOKEN, $tokens); return $this; }
[ "public", "function", "clearToken", "(", "$", "service", ")", "{", "$", "service", "=", "$", "this", "->", "normalizeServiceName", "(", "$", "service", ")", ";", "$", "tokens", "=", "$", "this", "->", "sessionScope", "->", "get", "(", "self", "::", "SESSION_TOKEN", ")", ";", "if", "(", "array_key_exists", "(", "$", "service", ",", "$", "tokens", ")", ")", "{", "unset", "(", "$", "tokens", ",", "$", "service", ")", ";", "}", "$", "this", "->", "sessionScope", "->", "set", "(", "self", "::", "SESSION_TOKEN", ",", "$", "tokens", ")", ";", "return", "$", "this", ";", "}" ]
Delete the users token. Aka, log out. @param string $service @return TokenStorageInterface
[ "Delete", "the", "users", "token", ".", "Aka", "log", "out", "." ]
5183a60d02cdf3b7db9f3168be1c0bbe1306cddf
https://github.com/vegas-cmf/oauth/blob/5183a60d02cdf3b7db9f3168be1c0bbe1306cddf/src/OAuth/Storage/Session.php#L115-L126
train
vegas-cmf/oauth
src/OAuth/Storage/Session.php
Session.hasAuthorizationState
public function hasAuthorizationState($service) { $service = $this->normalizeServiceName($service); $states = $this->sessionScope->get(self::SESSION_STATE); return isset($states[$service]); }
php
public function hasAuthorizationState($service) { $service = $this->normalizeServiceName($service); $states = $this->sessionScope->get(self::SESSION_STATE); return isset($states[$service]); }
[ "public", "function", "hasAuthorizationState", "(", "$", "service", ")", "{", "$", "service", "=", "$", "this", "->", "normalizeServiceName", "(", "$", "service", ")", ";", "$", "states", "=", "$", "this", "->", "sessionScope", "->", "get", "(", "self", "::", "SESSION_STATE", ")", ";", "return", "isset", "(", "$", "states", "[", "$", "service", "]", ")", ";", "}" ]
Check if an authorization state for a given service exists @param string $service @return bool
[ "Check", "if", "an", "authorization", "state", "for", "a", "given", "service", "exists" ]
5183a60d02cdf3b7db9f3168be1c0bbe1306cddf
https://github.com/vegas-cmf/oauth/blob/5183a60d02cdf3b7db9f3168be1c0bbe1306cddf/src/OAuth/Storage/Session.php#L167-L173
train