id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
233,000
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.canView
public function canView($member = null) { if (!$member && $member !== false) { $member = Member::currentUser(); } if (!$member) { return false; } return Permission::checkMember($member, "CMS_ACCESS_AssetAdmin"); }
php
public function canView($member = null) { if (!$member && $member !== false) { $member = Member::currentUser(); } if (!$member) { return false; } return Permission::checkMember($member, "CMS_ACCESS_AssetAdmin"); }
[ "public", "function", "canView", "(", "$", "member", "=", "null", ")", "{", "if", "(", "!", "$", "member", "&&", "$", "member", "!==", "false", ")", "{", "$", "member", "=", "Member", "::", "currentUser", "(", ")", ";", "}", "if", "(", "!", "$", ...
Defines the canView permission @param Member $member @return bool
[ "Defines", "the", "canView", "permission" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L112-L123
233,001
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.init
public function init() { parent::init(); Requirements::clear(); Requirements::css(KICKASSETS_DIR . '/javascript/build/main.css'); Requirements::add_i18n_javascript(KICKASSETS_DIR . '/lang'); $js = $this->config()->js_file; Requirements::javascript(KICKASSETS_DIR . "/javascript/build/$js"); Requirements::clear_combined_files(); }
php
public function init() { parent::init(); Requirements::clear(); Requirements::css(KICKASSETS_DIR . '/javascript/build/main.css'); Requirements::add_i18n_javascript(KICKASSETS_DIR . '/lang'); $js = $this->config()->js_file; Requirements::javascript(KICKASSETS_DIR . "/javascript/build/$js"); Requirements::clear_combined_files(); }
[ "public", "function", "init", "(", ")", "{", "parent", "::", "init", "(", ")", ";", "Requirements", "::", "clear", "(", ")", ";", "Requirements", "::", "css", "(", "KICKASSETS_DIR", ".", "'/javascript/build/main.css'", ")", ";", "Requirements", "::", "add_i1...
Bootstraps the module, adds JavaScript
[ "Bootstraps", "the", "module", "adds", "JavaScript" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L128-L139
233,002
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.handleIndex
public function handleIndex($request) { if ($request->getVar('search') !== null) { return $this->handleSearch($request); } return $this->renderWith('KickAssets'); }
php
public function handleIndex($request) { if ($request->getVar('search') !== null) { return $this->handleSearch($request); } return $this->renderWith('KickAssets'); }
[ "public", "function", "handleIndex", "(", "$", "request", ")", "{", "if", "(", "$", "request", "->", "getVar", "(", "'search'", ")", "!==", "null", ")", "{", "return", "$", "this", "->", "handleSearch", "(", "$", "request", ")", ";", "}", "return", "...
Index action, renders the main template @param SS_HTTPRequest $request @return HTMLText|SS_HTTPResponse
[ "Index", "action", "renders", "the", "main", "template" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L147-L154
233,003
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.handleFolderContents
public function handleFolderContents(SS_HTTPRequest $request) { if (!$request->param('FolderID')) { $folder = Injector::inst()->get('Folder'); $folder->Filename = ASSETS_DIR; } else { $folder = Folder::get()->byID($request->param('FolderID')); } if (!$folder) { return $this->httpError(404, 'That folder does not exist'); } $cursor = (int)$request->getVar('cursor'); $result = array( 'folder' => $this->createFolderJson($folder), 'breadcrumbs' => $this->createBreadcrumbJson($folder), 'children' => array() ); $files = File::get() ->filter(array( 'ParentID' => $folder->ID )) ->sort($this->getSortClause($request->getVar('sort'))); $totalFiles = (int)$files->count(); $files = $files->limit($this->config()->folder_items_limit, $cursor); foreach ($files as $file) { if (!$file->canView()) { continue; } $result['children'][] = ($file instanceof Folder) ? $this->createFolderJson($file) : $this->createFileJson($file, $folder); } $cursor += $files->count(); $result['cursor'] = $cursor; $result['has_more'] = ($cursor < $totalFiles); $result['total_items'] = $totalFiles; $response = new SS_HTTPResponse( Convert::array2json($result), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
php
public function handleFolderContents(SS_HTTPRequest $request) { if (!$request->param('FolderID')) { $folder = Injector::inst()->get('Folder'); $folder->Filename = ASSETS_DIR; } else { $folder = Folder::get()->byID($request->param('FolderID')); } if (!$folder) { return $this->httpError(404, 'That folder does not exist'); } $cursor = (int)$request->getVar('cursor'); $result = array( 'folder' => $this->createFolderJson($folder), 'breadcrumbs' => $this->createBreadcrumbJson($folder), 'children' => array() ); $files = File::get() ->filter(array( 'ParentID' => $folder->ID )) ->sort($this->getSortClause($request->getVar('sort'))); $totalFiles = (int)$files->count(); $files = $files->limit($this->config()->folder_items_limit, $cursor); foreach ($files as $file) { if (!$file->canView()) { continue; } $result['children'][] = ($file instanceof Folder) ? $this->createFolderJson($file) : $this->createFileJson($file, $folder); } $cursor += $files->count(); $result['cursor'] = $cursor; $result['has_more'] = ($cursor < $totalFiles); $result['total_items'] = $totalFiles; $response = new SS_HTTPResponse( Convert::array2json($result), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
[ "public", "function", "handleFolderContents", "(", "SS_HTTPRequest", "$", "request", ")", "{", "if", "(", "!", "$", "request", "->", "param", "(", "'FolderID'", ")", ")", "{", "$", "folder", "=", "Injector", "::", "inst", "(", ")", "->", "get", "(", "'...
Gets the contents of a folder, and applies a sort. Splits the response into folder metadata and folder children @param SS_HTTPRequest $request @return SS_HTTPResponse
[ "Gets", "the", "contents", "of", "a", "folder", "and", "applies", "a", "sort", ".", "Splits", "the", "response", "into", "folder", "metadata", "and", "folder", "children" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L163-L212
233,004
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.handleRecentItems
public function handleRecentItems(SS_HTTPRequest $request) { $result = array(); $fileIDs = File::get() ->sort('LastEdited', 'DESC') ->limit($this->config()->recent_items_limit) ->column('ID'); if (!empty($fileIDs)) { $files = File::get() ->sort($this->getSortClause($request->getVar('sort'))) ->byIDs($fileIDs); foreach ($files as $file) { if (!$file->canView()) { continue; } $result[] = ($file instanceof Folder) ? $this->createFolderJson($file) : $this->createFileJson($file); } } $response = new SS_HTTPResponse( Convert::array2json($result), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
php
public function handleRecentItems(SS_HTTPRequest $request) { $result = array(); $fileIDs = File::get() ->sort('LastEdited', 'DESC') ->limit($this->config()->recent_items_limit) ->column('ID'); if (!empty($fileIDs)) { $files = File::get() ->sort($this->getSortClause($request->getVar('sort'))) ->byIDs($fileIDs); foreach ($files as $file) { if (!$file->canView()) { continue; } $result[] = ($file instanceof Folder) ? $this->createFolderJson($file) : $this->createFileJson($file); } } $response = new SS_HTTPResponse( Convert::array2json($result), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
[ "public", "function", "handleRecentItems", "(", "SS_HTTPRequest", "$", "request", ")", "{", "$", "result", "=", "array", "(", ")", ";", "$", "fileIDs", "=", "File", "::", "get", "(", ")", "->", "sort", "(", "'LastEdited'", ",", "'DESC'", ")", "->", "li...
Gets recently updated items @param SS_HTTPRequest $request @return SS_HTTPResponse
[ "Gets", "recently", "updated", "items" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L220-L251
233,005
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.handleCreateFolder
public function handleCreateFolder(SS_HTTPRequest $request) { if (!Injector::inst()->get('Folder')->canCreate()) { return $this->httpError(403); } $parentID = (int)$request->postVar('parentID'); /** @var Folder $parentRecord */ $parentRecord = Folder::get()->byID($parentID); $name = $request->postVar('title') ? $request->postVar('title') : _t('AssetAdmin.NEWFOLDER', "NewFolder"); if ($parentRecord && $parentRecord->ID) { $filename = Controller::join_links($parentRecord->FullPath, $name); } else { $filename = Controller::join_links(ASSETS_PATH, $name); } /** @var Folder $record */ $record = Folder::create(array( 'ParentID' => $parentID, 'Name' => basename($filename), 'Title' => basename($filename), 'Filename' => $filename )); // Ensure uniqueness $i = 2; if (substr($record->Filename, -1) == "/") { $baseFilename = substr($record->Filename, 0, -1); } else { $baseFilename = $record->Filename; } $baseFilename .= "-"; while (file_exists($record->FullPath)) { $record->Filename = $baseFilename . $i . '/'; $i++; } $record->Name = $record->Title = basename($record->Filename); mkdir($record->FullPath); @chmod($record->FullPath, (int)Config::inst()->get('Filesystem', 'file_create_mask')); $record->write(); $response = new SS_HTTPResponse( Convert::array2json($this->createFolderJson($record)), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
php
public function handleCreateFolder(SS_HTTPRequest $request) { if (!Injector::inst()->get('Folder')->canCreate()) { return $this->httpError(403); } $parentID = (int)$request->postVar('parentID'); /** @var Folder $parentRecord */ $parentRecord = Folder::get()->byID($parentID); $name = $request->postVar('title') ? $request->postVar('title') : _t('AssetAdmin.NEWFOLDER', "NewFolder"); if ($parentRecord && $parentRecord->ID) { $filename = Controller::join_links($parentRecord->FullPath, $name); } else { $filename = Controller::join_links(ASSETS_PATH, $name); } /** @var Folder $record */ $record = Folder::create(array( 'ParentID' => $parentID, 'Name' => basename($filename), 'Title' => basename($filename), 'Filename' => $filename )); // Ensure uniqueness $i = 2; if (substr($record->Filename, -1) == "/") { $baseFilename = substr($record->Filename, 0, -1); } else { $baseFilename = $record->Filename; } $baseFilename .= "-"; while (file_exists($record->FullPath)) { $record->Filename = $baseFilename . $i . '/'; $i++; } $record->Name = $record->Title = basename($record->Filename); mkdir($record->FullPath); @chmod($record->FullPath, (int)Config::inst()->get('Filesystem', 'file_create_mask')); $record->write(); $response = new SS_HTTPResponse( Convert::array2json($this->createFolderJson($record)), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
[ "public", "function", "handleCreateFolder", "(", "SS_HTTPRequest", "$", "request", ")", "{", "if", "(", "!", "Injector", "::", "inst", "(", ")", "->", "get", "(", "'Folder'", ")", "->", "canCreate", "(", ")", ")", "{", "return", "$", "this", "->", "htt...
Creates a folder, ensures uniqueness @param SS_HTTPRequest $request @return SS_HTTPResponse
[ "Creates", "a", "folder", "ensures", "uniqueness" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L259-L311
233,006
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.handleFile
public function handleFile(SS_HTTPRequest $request) { /** @var File $file */ $file = File::get()->byID($request->param('FileID')); if ($file) { $fileRequest = new KickAssetsFileRequest($this, $file); return $fileRequest->handlerequest($request, DataModel::inst()); } return $this->httpError(404, 'File does not exist'); }
php
public function handleFile(SS_HTTPRequest $request) { /** @var File $file */ $file = File::get()->byID($request->param('FileID')); if ($file) { $fileRequest = new KickAssetsFileRequest($this, $file); return $fileRequest->handlerequest($request, DataModel::inst()); } return $this->httpError(404, 'File does not exist'); }
[ "public", "function", "handleFile", "(", "SS_HTTPRequest", "$", "request", ")", "{", "/** @var File $file */", "$", "file", "=", "File", "::", "get", "(", ")", "->", "byID", "(", "$", "request", "->", "param", "(", "'FileID'", ")", ")", ";", "if", "(", ...
Handles a specific file request @param SS_HTTPRequest $request @return KickAssetsFileRequest|SS_HTTPResponse
[ "Handles", "a", "specific", "file", "request" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L319-L331
233,007
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.handleFolders
public function handleFolders(SS_HTTPRequest $request) { $result = array(); foreach (Folder::get() as $folder) { $result[] = array( 'id' => $folder->ID, 'filename' => $folder->Filename ); } $response = new SS_HTTPResponse( Convert::array2json($result), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
php
public function handleFolders(SS_HTTPRequest $request) { $result = array(); foreach (Folder::get() as $folder) { $result[] = array( 'id' => $folder->ID, 'filename' => $folder->Filename ); } $response = new SS_HTTPResponse( Convert::array2json($result), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
[ "public", "function", "handleFolders", "(", "SS_HTTPRequest", "$", "request", ")", "{", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "Folder", "::", "get", "(", ")", "as", "$", "folder", ")", "{", "$", "result", "[", "]", "=", "array",...
Gets a list of all the folders in the system @param SS_HTTPRequest $request @return SS_HTTPResponse
[ "Gets", "a", "list", "of", "all", "the", "folders", "in", "the", "system" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L339-L355
233,008
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.handleUpload
public function handleUpload(SS_HTTPRequest $request) { $request->setUrl('upload'); /** @var Folder $folder */ $folder = Folder::get()->byID($request->param('FolderID')); /** @var FileAttachmentField $uploader */ $uploader = FileAttachmentField::create('dummy'); if ($folder) { $uploader->setFolderName(self::remove_assets_dir($folder->Filename)); } else { $uploader->setFolderName('/'); } /** @var SS_HTTPResponse $httpResponse */ $httpResponse = $uploader->handleRequest($request, DataModel::inst()); if ($httpResponse->getStatusCode() !== 200) { return $httpResponse; } $ids = $httpResponse->getBody(); $files = File::get()->byIDs(explode(',', $ids)); $result = array(); foreach ($files as $f) { $result[] = $this->createFileJson($f, $folder); } $response = new SS_HTTPResponse( Convert::array2json($result), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
php
public function handleUpload(SS_HTTPRequest $request) { $request->setUrl('upload'); /** @var Folder $folder */ $folder = Folder::get()->byID($request->param('FolderID')); /** @var FileAttachmentField $uploader */ $uploader = FileAttachmentField::create('dummy'); if ($folder) { $uploader->setFolderName(self::remove_assets_dir($folder->Filename)); } else { $uploader->setFolderName('/'); } /** @var SS_HTTPResponse $httpResponse */ $httpResponse = $uploader->handleRequest($request, DataModel::inst()); if ($httpResponse->getStatusCode() !== 200) { return $httpResponse; } $ids = $httpResponse->getBody(); $files = File::get()->byIDs(explode(',', $ids)); $result = array(); foreach ($files as $f) { $result[] = $this->createFileJson($f, $folder); } $response = new SS_HTTPResponse( Convert::array2json($result), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
[ "public", "function", "handleUpload", "(", "SS_HTTPRequest", "$", "request", ")", "{", "$", "request", "->", "setUrl", "(", "'upload'", ")", ";", "/** @var Folder $folder */", "$", "folder", "=", "Folder", "::", "get", "(", ")", "->", "byID", "(", "$", "re...
The endpoint for file uploads. Hands off to Dropzone module @param SS_HTTPRequest $request @return SS_HTTPResponse
[ "The", "endpoint", "for", "file", "uploads", ".", "Hands", "off", "to", "Dropzone", "module" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L363-L399
233,009
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.handleDelete
public function handleDelete(SS_HTTPRequest $request) { parse_str($request->getBody(), $vars); $count = 0; if ($vars['ids']) { foreach (explode(',', $vars['ids']) as $id) { if ($file = File::get()->byID($id)) { if ($file->canDelete()) { $file->delete(); $count++; } } } } $result = array( 'deleted' => $count ); $response = new SS_HTTPResponse( Convert::array2json($result), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
php
public function handleDelete(SS_HTTPRequest $request) { parse_str($request->getBody(), $vars); $count = 0; if ($vars['ids']) { foreach (explode(',', $vars['ids']) as $id) { if ($file = File::get()->byID($id)) { if ($file->canDelete()) { $file->delete(); $count++; } } } } $result = array( 'deleted' => $count ); $response = new SS_HTTPResponse( Convert::array2json($result), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
[ "public", "function", "handleDelete", "(", "SS_HTTPRequest", "$", "request", ")", "{", "parse_str", "(", "$", "request", "->", "getBody", "(", ")", ",", "$", "vars", ")", ";", "$", "count", "=", "0", ";", "if", "(", "$", "vars", "[", "'ids'", "]", ...
Deletes a list of files @param SS_HTTPRequest $request @return SS_HTTPResponse
[ "Deletes", "a", "list", "of", "files" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L407-L431
233,010
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.handleSearch
public function handleSearch(SS_HTTPRequest $request) { if ($request->getVar('search') === null) { return null; } $result = array(); $searchTerm = $request->getVar('search'); $list = File::get()->filterAny(array( 'Title:PartialMatch' => $searchTerm, 'Filename:PartialMatch' => $searchTerm ))->limit(100); $this->extend('beforeHandleSearch', $list, $searchTerm); foreach ($list as $item) { if (!$item->canView()) { continue; } $result[] = $item instanceof Folder ? $this->createFolderJson($item) : $this->createFileJson($item); } $response = new SS_HTTPResponse( Convert::array2json($result), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
php
public function handleSearch(SS_HTTPRequest $request) { if ($request->getVar('search') === null) { return null; } $result = array(); $searchTerm = $request->getVar('search'); $list = File::get()->filterAny(array( 'Title:PartialMatch' => $searchTerm, 'Filename:PartialMatch' => $searchTerm ))->limit(100); $this->extend('beforeHandleSearch', $list, $searchTerm); foreach ($list as $item) { if (!$item->canView()) { continue; } $result[] = $item instanceof Folder ? $this->createFolderJson($item) : $this->createFileJson($item); } $response = new SS_HTTPResponse( Convert::array2json($result), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
[ "public", "function", "handleSearch", "(", "SS_HTTPRequest", "$", "request", ")", "{", "if", "(", "$", "request", "->", "getVar", "(", "'search'", ")", "===", "null", ")", "{", "return", "null", ";", "}", "$", "result", "=", "array", "(", ")", ";", "...
Searches for files by PartialMatch @param SS_HTTPRequest $request @return SS_HTTPResponse
[ "Searches", "for", "files", "by", "PartialMatch" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L439-L467
233,011
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.jsonConfig
public function jsonConfig() { $request = $this->request; // Remove null values and normalise leading dot $allExts = $request->getVar('allowedExtensions') ? explode(',', $request->getVar('allowedExtensions')) : File::config()->allowed_extensions; $exts = array_map(function ($item) { return $item[0] == '.' ? $item : '.' . $item; }, array_filter( $allExts, 'strlen' )); $currentLinkParts = parse_url(Controller::join_links(Director::baseURL(), $this->Link())); $types = explode(',', $request->getVar('allowedTypes')); return Convert::array2json(array( 'baseRoute' => $currentLinkParts['path'], 'maxFilesize' => FileAttachmentField::get_filesize_from_ini(), 'allowedExtensions' => implode(',', $exts), 'thumbnailsDir' => DROPZONE_DIR . '/images/file-icons', 'langNewFolder' => _t('AssetAdmin.NEWFOLDER', 'NewFolder'), 'iconSize' => self::ICON_SIZE, 'thumbnailWidth' => self::IMAGE_WIDTH, 'thumbnailHeight' => self::IMAGE_HEIGHT, 'defaultSort' => $this->config()->default_sort, 'defaultView' => $this->config()->default_view, 'maxCacheSize' => $this->config()->max_cache_size, 'folderExtension' => self::FOLDER_EXTENSION, 'allowSelection' => (boolean)$request->getVar('allowSelection'), 'maxSelection' => (int)$request->getVar('maxSelection'), 'canUpload' => (boolean)$request->getVar('canUpload'), 'canDelete' => (boolean)$request->getVar('canDelete'), 'canEdit' => (boolean)$request->getVar('canEdit'), 'canCreateFolder' => (boolean)$request->getVar('canCreateFolder'), 'allowedTypes' => !empty($types) ? $types : null )); }
php
public function jsonConfig() { $request = $this->request; // Remove null values and normalise leading dot $allExts = $request->getVar('allowedExtensions') ? explode(',', $request->getVar('allowedExtensions')) : File::config()->allowed_extensions; $exts = array_map(function ($item) { return $item[0] == '.' ? $item : '.' . $item; }, array_filter( $allExts, 'strlen' )); $currentLinkParts = parse_url(Controller::join_links(Director::baseURL(), $this->Link())); $types = explode(',', $request->getVar('allowedTypes')); return Convert::array2json(array( 'baseRoute' => $currentLinkParts['path'], 'maxFilesize' => FileAttachmentField::get_filesize_from_ini(), 'allowedExtensions' => implode(',', $exts), 'thumbnailsDir' => DROPZONE_DIR . '/images/file-icons', 'langNewFolder' => _t('AssetAdmin.NEWFOLDER', 'NewFolder'), 'iconSize' => self::ICON_SIZE, 'thumbnailWidth' => self::IMAGE_WIDTH, 'thumbnailHeight' => self::IMAGE_HEIGHT, 'defaultSort' => $this->config()->default_sort, 'defaultView' => $this->config()->default_view, 'maxCacheSize' => $this->config()->max_cache_size, 'folderExtension' => self::FOLDER_EXTENSION, 'allowSelection' => (boolean)$request->getVar('allowSelection'), 'maxSelection' => (int)$request->getVar('maxSelection'), 'canUpload' => (boolean)$request->getVar('canUpload'), 'canDelete' => (boolean)$request->getVar('canDelete'), 'canEdit' => (boolean)$request->getVar('canEdit'), 'canCreateFolder' => (boolean)$request->getVar('canCreateFolder'), 'allowedTypes' => !empty($types) ? $types : null )); }
[ "public", "function", "jsonConfig", "(", ")", "{", "$", "request", "=", "$", "this", "->", "request", ";", "// Remove null values and normalise leading dot", "$", "allExts", "=", "$", "request", "->", "getVar", "(", "'allowedExtensions'", ")", "?", "explode", "(...
Creates a JSON string of all the variables that can be set in the Config @return string
[ "Creates", "a", "JSON", "string", "of", "all", "the", "variables", "that", "can", "be", "set", "in", "the", "Config" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L474-L515
233,012
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.createFolderJson
public function createFolderJson(Folder $folder) { $size = self::ICON_SIZE; $file = Injector::inst()->get('File'); return array( 'id' => $folder->ID, 'parentID' => $folder->ParentID, 'title' => $folder->Title, 'filename' => $folder->Filename, 'type' => 'folder', 'extension' => self::FOLDER_EXTENSION, 'created' => $folder->Created, 'iconURL' => $folder->getPreviewThumbnail($size, $size)->URL, 'canEdit' => $folder->canEdit(), 'canCreate' => $folder->canCreate(), 'canDelete' => $folder->canDelete(), 'canUpload' => $folder->canEdit() && $file->canCreate() ); }
php
public function createFolderJson(Folder $folder) { $size = self::ICON_SIZE; $file = Injector::inst()->get('File'); return array( 'id' => $folder->ID, 'parentID' => $folder->ParentID, 'title' => $folder->Title, 'filename' => $folder->Filename, 'type' => 'folder', 'extension' => self::FOLDER_EXTENSION, 'created' => $folder->Created, 'iconURL' => $folder->getPreviewThumbnail($size, $size)->URL, 'canEdit' => $folder->canEdit(), 'canCreate' => $folder->canCreate(), 'canDelete' => $folder->canDelete(), 'canUpload' => $folder->canEdit() && $file->canCreate() ); }
[ "public", "function", "createFolderJson", "(", "Folder", "$", "folder", ")", "{", "$", "size", "=", "self", "::", "ICON_SIZE", ";", "$", "file", "=", "Injector", "::", "inst", "(", ")", "->", "get", "(", "'File'", ")", ";", "return", "array", "(", "'...
Given a Folder object, create an array of its properties and values ready to be transformed to JSON @param Folder $folder @return array
[ "Given", "a", "Folder", "object", "create", "an", "array", "of", "its", "properties", "and", "values", "ready", "to", "be", "transformed", "to", "JSON" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L568-L587
233,013
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.createFileJson
public function createFileJson(File $file, $folder = null) { $isImage = $file instanceof Image; $w = $isImage ? self::IMAGE_WIDTH : self::ICON_SIZE; $h = $isImage ? self::IMAGE_HEIGHT : self::ICON_SIZE; $folder = $folder ?: $file->Parent(); return array( 'id' => $file->ID, 'parentID' => $file->ParentID, 'title' => ($file->Title) ? $file->Title : basename($file->Filename), 'filename' => basename($file->Filename), 'path' => $file->Filename, 'filesize' => $file->getAbsoluteSize(), 'folderName' => $folder->Filename, 'type' => $isImage ? 'image' : 'file', 'extension' => $file->getExtension(), 'created' => $file->Created, 'updated' => $file->LastEdited, 'iconURL' => $file->getPreviewThumbnail($w, $h)->URL, 'canEdit' => $file->canEdit(), 'canCreate' => $file->canCreate(), 'canDelete' => $file->canDelete() ); }
php
public function createFileJson(File $file, $folder = null) { $isImage = $file instanceof Image; $w = $isImage ? self::IMAGE_WIDTH : self::ICON_SIZE; $h = $isImage ? self::IMAGE_HEIGHT : self::ICON_SIZE; $folder = $folder ?: $file->Parent(); return array( 'id' => $file->ID, 'parentID' => $file->ParentID, 'title' => ($file->Title) ? $file->Title : basename($file->Filename), 'filename' => basename($file->Filename), 'path' => $file->Filename, 'filesize' => $file->getAbsoluteSize(), 'folderName' => $folder->Filename, 'type' => $isImage ? 'image' : 'file', 'extension' => $file->getExtension(), 'created' => $file->Created, 'updated' => $file->LastEdited, 'iconURL' => $file->getPreviewThumbnail($w, $h)->URL, 'canEdit' => $file->canEdit(), 'canCreate' => $file->canCreate(), 'canDelete' => $file->canDelete() ); }
[ "public", "function", "createFileJson", "(", "File", "$", "file", ",", "$", "folder", "=", "null", ")", "{", "$", "isImage", "=", "$", "file", "instanceof", "Image", ";", "$", "w", "=", "$", "isImage", "?", "self", "::", "IMAGE_WIDTH", ":", "self", "...
Given a File object, create an array of its properties and values ready to be transformed to JSON @param File $file @param Folder $folder @return array
[ "Given", "a", "File", "object", "create", "an", "array", "of", "its", "properties", "and", "values", "ready", "to", "be", "transformed", "to", "JSON" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L597-L621
233,014
unclecheese/silverstripe-kickassets
code/KickAssets.php
KickAssets.createBreadcrumbJson
protected function createBreadcrumbJson(Folder $folder) { $breadcrumbs = array(); while ($folder->exists()) { $breadcrumbs[] = array( 'title' => $folder->Title, 'id' => $folder->ID ); $folder = $folder->Parent(); } $breadcrumbs[] = array( 'title' => ASSETS_DIR, 'id' => 0 ); return array_reverse($breadcrumbs); }
php
protected function createBreadcrumbJson(Folder $folder) { $breadcrumbs = array(); while ($folder->exists()) { $breadcrumbs[] = array( 'title' => $folder->Title, 'id' => $folder->ID ); $folder = $folder->Parent(); } $breadcrumbs[] = array( 'title' => ASSETS_DIR, 'id' => 0 ); return array_reverse($breadcrumbs); }
[ "protected", "function", "createBreadcrumbJson", "(", "Folder", "$", "folder", ")", "{", "$", "breadcrumbs", "=", "array", "(", ")", ";", "while", "(", "$", "folder", "->", "exists", "(", ")", ")", "{", "$", "breadcrumbs", "[", "]", "=", "array", "(", ...
Creates an array of breadcrumbs for a given Folder, ready to be transformed to JSON @param Folder $folder @return array
[ "Creates", "an", "array", "of", "breadcrumbs", "for", "a", "given", "Folder", "ready", "to", "be", "transformed", "to", "JSON" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssets.php#L630-L647
233,015
asinfotrack/yii2-toolbox
behaviors/ArchiveQueryBehavior.php
ArchiveQueryBehavior.isArchived
public function isArchived($isArchived) { if ($this->modelInstance === null) { $this->modelInstance = new $this->owner->modelClass(); } $column = sprintf('%s.%s', $this->modelInstance->tableName(), $this->modelInstance->archiveAttribute); $value = $isArchived ? $this->modelInstance->archivedValue : $this->modelInstance->unarchivedValue; $this->owner->andWhere([$column=>$value]); return $this->owner; }
php
public function isArchived($isArchived) { if ($this->modelInstance === null) { $this->modelInstance = new $this->owner->modelClass(); } $column = sprintf('%s.%s', $this->modelInstance->tableName(), $this->modelInstance->archiveAttribute); $value = $isArchived ? $this->modelInstance->archivedValue : $this->modelInstance->unarchivedValue; $this->owner->andWhere([$column=>$value]); return $this->owner; }
[ "public", "function", "isArchived", "(", "$", "isArchived", ")", "{", "if", "(", "$", "this", "->", "modelInstance", "===", "null", ")", "{", "$", "this", "->", "modelInstance", "=", "new", "$", "this", "->", "owner", "->", "modelClass", "(", ")", ";",...
Named scope to filter either archived or unarchived records @param boolean $isArchived if set to true, only archived records will be returned. other wise only unarchived records. @return \yii\db\ActiveQuery
[ "Named", "scope", "to", "filter", "either", "archived", "or", "unarchived", "records" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/behaviors/ArchiveQueryBehavior.php#L29-L41
233,016
yongtiger/yii2-tree-manager
src/actions/MoveAction.php
MoveAction.run
public function run($id) { if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; $model = $this->findModel($id); if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); $parentId = isset($post['parent_id']) ? $post['parent_id'] : 0; $prevId = isset($post['prev_id']) ? $post['prev_id'] : 0; $nextId = isset($post['next_id']) ? $post['next_id'] : 0; try { if (empty($parentId)) { if ($this->isMultipleTree) { ///[isMultipleTree] if (!$model->isRoot()) { $result = $model->makeRoot(); } ///?????root sorting logic } else { return [ 'status' => 'error', 'error' => 'Tree root operations are protected when "isMultipleTree" is false!', ]; } } elseif (!empty($prevId)) { $prevModel = $this->findModel($prevId); $result = $model->insertAfter($prevModel); } elseif (!empty($nextId)) { $nextModel = $this->findModel($nextId); $result = $model->insertBefore($nextModel); } else { $parentModel = $this->findModel($parentId); $result = $model->appendTo($parentModel); } } catch (\Exception $e) { return [ 'status' => 'error', 'error' => $e->getMessage(), ]; } ///Note: remove `save()` when using `creocoder/yii2-nested-sets`! return is_bool($result) ? $result : $result->save(); } } ///Redirect to this controller's default action return $this->controller->redirect([$this->controller->defaultAction]); }
php
public function run($id) { if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; $model = $this->findModel($id); if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); $parentId = isset($post['parent_id']) ? $post['parent_id'] : 0; $prevId = isset($post['prev_id']) ? $post['prev_id'] : 0; $nextId = isset($post['next_id']) ? $post['next_id'] : 0; try { if (empty($parentId)) { if ($this->isMultipleTree) { ///[isMultipleTree] if (!$model->isRoot()) { $result = $model->makeRoot(); } ///?????root sorting logic } else { return [ 'status' => 'error', 'error' => 'Tree root operations are protected when "isMultipleTree" is false!', ]; } } elseif (!empty($prevId)) { $prevModel = $this->findModel($prevId); $result = $model->insertAfter($prevModel); } elseif (!empty($nextId)) { $nextModel = $this->findModel($nextId); $result = $model->insertBefore($nextModel); } else { $parentModel = $this->findModel($parentId); $result = $model->appendTo($parentModel); } } catch (\Exception $e) { return [ 'status' => 'error', 'error' => $e->getMessage(), ]; } ///Note: remove `save()` when using `creocoder/yii2-nested-sets`! return is_bool($result) ? $result : $result->save(); } } ///Redirect to this controller's default action return $this->controller->redirect([$this->controller->defaultAction]); }
[ "public", "function", "run", "(", "$", "id", ")", "{", "if", "(", "Yii", "::", "$", "app", "->", "request", "->", "isAjax", ")", "{", "Yii", "::", "$", "app", "->", "response", "->", "format", "=", "Response", "::", "FORMAT_JSON", ";", "$", "model"...
Moves a node by given nodes with `parent_id`, `prev_id` and `next_id`. @param integer $id the primary key of the moved node @return array
[ "Moves", "a", "node", "by", "given", "nodes", "with", "parent_id", "prev_id", "and", "next_id", "." ]
e3a6f8bca42f9a941847538200a9cdb234d3ed14
https://github.com/yongtiger/yii2-tree-manager/blob/e3a6f8bca42f9a941847538200a9cdb234d3ed14/src/actions/MoveAction.php#L31-L83
233,017
DuckThom/laravel-importer
src/Importer.php
Importer.runner
public function runner($runner) { if ($runner instanceof Runner) { $this->runner = $runner; } else { $this->runner = $this->getRunner($runner); } return $this; }
php
public function runner($runner) { if ($runner instanceof Runner) { $this->runner = $runner; } else { $this->runner = $this->getRunner($runner); } return $this; }
[ "public", "function", "runner", "(", "$", "runner", ")", "{", "if", "(", "$", "runner", "instanceof", "Runner", ")", "{", "$", "this", "->", "runner", "=", "$", "runner", ";", "}", "else", "{", "$", "this", "->", "runner", "=", "$", "this", "->", ...
Set the runner @param Runner|string $runner @return $this
[ "Set", "the", "runner" ]
64bad083a7af35396199f342b57c3e619f2968c6
https://github.com/DuckThom/laravel-importer/blob/64bad083a7af35396199f342b57c3e619f2968c6/src/Importer.php#L65-L74
233,018
DuckThom/laravel-importer
src/Importer.php
Importer.importer
public function importer($importer) { if ($importer instanceof ImporterContract) { $this->importer = $importer; } else { $this->importer = $this->getImporter($importer); } return $this; }
php
public function importer($importer) { if ($importer instanceof ImporterContract) { $this->importer = $importer; } else { $this->importer = $this->getImporter($importer); } return $this; }
[ "public", "function", "importer", "(", "$", "importer", ")", "{", "if", "(", "$", "importer", "instanceof", "ImporterContract", ")", "{", "$", "this", "->", "importer", "=", "$", "importer", ";", "}", "else", "{", "$", "this", "->", "importer", "=", "$...
Set the importer @param ImporterContract|string $importer @return $this
[ "Set", "the", "importer" ]
64bad083a7af35396199f342b57c3e619f2968c6
https://github.com/DuckThom/laravel-importer/blob/64bad083a7af35396199f342b57c3e619f2968c6/src/Importer.php#L82-L91
233,019
unclecheese/silverstripe-kickassets
code/KickAssetsFileRequest.php
KickAssetsFileRequest.handleRead
public function handleRead(SS_HTTPRequest $request) { if (!$this->file->canView()) { return $this->httpError(403); } return $this->jsonResponse($this->buildJSON()); }
php
public function handleRead(SS_HTTPRequest $request) { if (!$this->file->canView()) { return $this->httpError(403); } return $this->jsonResponse($this->buildJSON()); }
[ "public", "function", "handleRead", "(", "SS_HTTPRequest", "$", "request", ")", "{", "if", "(", "!", "$", "this", "->", "file", "->", "canView", "(", ")", ")", "{", "return", "$", "this", "->", "httpError", "(", "403", ")", ";", "}", "return", "$", ...
Serves up the details for the file bound to this controller @param SS_HTTPRequest $request @return SS_HTTPResponse
[ "Serves", "up", "the", "details", "for", "the", "file", "bound", "to", "this", "controller" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssetsFileRequest.php#L66-L73
233,020
unclecheese/silverstripe-kickassets
code/KickAssetsFileRequest.php
KickAssetsFileRequest.handleUpdate
public function handleUpdate(SS_HTTPRequest $request) { if (!$this->file->canEdit()) { return $this->httpError(403); } parse_str($request->getBody(), $vars); if (isset($vars['parentID'])) { $this->file->ParentID = $vars['parentID']; $this->file->write(); } $this->file->Title = $vars['title']; if (isset($vars['filename']) && !empty($vars['filename'])) { $this->file->Filename = $this->file->Parent()->Filename . '/' . $vars['filename']; } $this->file->write(); return $this->jsonResponse($this->buildJSON()); }
php
public function handleUpdate(SS_HTTPRequest $request) { if (!$this->file->canEdit()) { return $this->httpError(403); } parse_str($request->getBody(), $vars); if (isset($vars['parentID'])) { $this->file->ParentID = $vars['parentID']; $this->file->write(); } $this->file->Title = $vars['title']; if (isset($vars['filename']) && !empty($vars['filename'])) { $this->file->Filename = $this->file->Parent()->Filename . '/' . $vars['filename']; } $this->file->write(); return $this->jsonResponse($this->buildJSON()); }
[ "public", "function", "handleUpdate", "(", "SS_HTTPRequest", "$", "request", ")", "{", "if", "(", "!", "$", "this", "->", "file", "->", "canEdit", "(", ")", ")", "{", "return", "$", "this", "->", "httpError", "(", "403", ")", ";", "}", "parse_str", "...
Applies edits to the file bound to this controller @param SS_HTTPRequest $request @return SS_HTTPResponse
[ "Applies", "edits", "to", "the", "file", "bound", "to", "this", "controller" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssetsFileRequest.php#L81-L100
233,021
unclecheese/silverstripe-kickassets
code/KickAssetsFileRequest.php
KickAssetsFileRequest.handleDelete
public function handleDelete(SS_HTTPRequest $request) { if (!$this->file->canDelete()) { return $this->httpError(403); } $this->file->delete(); return new SS_HTTPResponse('OK'); }
php
public function handleDelete(SS_HTTPRequest $request) { if (!$this->file->canDelete()) { return $this->httpError(403); } $this->file->delete(); return new SS_HTTPResponse('OK'); }
[ "public", "function", "handleDelete", "(", "SS_HTTPRequest", "$", "request", ")", "{", "if", "(", "!", "$", "this", "->", "file", "->", "canDelete", "(", ")", ")", "{", "return", "$", "this", "->", "httpError", "(", "403", ")", ";", "}", "$", "this",...
Deletes the file bound to this controller @param SS_HTTPRequest $request @return SS_HTTPResponse
[ "Deletes", "the", "file", "bound", "to", "this", "controller" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssetsFileRequest.php#L108-L117
233,022
unclecheese/silverstripe-kickassets
code/KickAssetsFileRequest.php
KickAssetsFileRequest.jsonResponse
protected function jsonResponse($json = null) { if (!$json) { $json = $this->file instanceof Folder ? $this->parent->createFolderJson($this->file) : $this->parent->createFileJson($this->file); } $response = new SS_HTTPResponse( Convert::array2json($json), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
php
protected function jsonResponse($json = null) { if (!$json) { $json = $this->file instanceof Folder ? $this->parent->createFolderJson($this->file) : $this->parent->createFileJson($this->file); } $response = new SS_HTTPResponse( Convert::array2json($json), 200 ); return $response->addHeader('Content-Type', 'application/json'); }
[ "protected", "function", "jsonResponse", "(", "$", "json", "=", "null", ")", "{", "if", "(", "!", "$", "json", ")", "{", "$", "json", "=", "$", "this", "->", "file", "instanceof", "Folder", "?", "$", "this", "->", "parent", "->", "createFolderJson", ...
Helper method for generating an HTTPResponse based on given JSON @param array $json @return SS_HTTPResponse
[ "Helper", "method", "for", "generating", "an", "HTTPResponse", "based", "on", "given", "JSON" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssetsFileRequest.php#L150-L162
233,023
DuckThom/laravel-importer
src/Runners/CsvRunner.php
CsvRunner.import
public function import() { DB::beginTransaction(); try { $iteration = 0; while (! feof($this->file)) { $iteration++; $csvLine = str_getcsv(fgets($this->file), ';'); $columnCount = count($csvLine); if ($columnCount === 1 && !$this->importer->validateLine($csvLine)) { continue; } elseif ($this->importer->validateLine($csvLine)) { $this->handleLine($csvLine); } else { throw new InvalidCsvLineException($iteration); } } $this->lines = $this->importer->getModelInstance()->count(); $this->removeStale(); if (!$this->dryRun) { DB::commit(); } event(new ImportSuccess($this, $this->importer)); } catch (\Exception $e) { DB::rollBack(); event(new ImportFailed($this, $this->importer, $e)); // Re-throw the exception to catch it from outside throw $e; } }
php
public function import() { DB::beginTransaction(); try { $iteration = 0; while (! feof($this->file)) { $iteration++; $csvLine = str_getcsv(fgets($this->file), ';'); $columnCount = count($csvLine); if ($columnCount === 1 && !$this->importer->validateLine($csvLine)) { continue; } elseif ($this->importer->validateLine($csvLine)) { $this->handleLine($csvLine); } else { throw new InvalidCsvLineException($iteration); } } $this->lines = $this->importer->getModelInstance()->count(); $this->removeStale(); if (!$this->dryRun) { DB::commit(); } event(new ImportSuccess($this, $this->importer)); } catch (\Exception $e) { DB::rollBack(); event(new ImportFailed($this, $this->importer, $e)); // Re-throw the exception to catch it from outside throw $e; } }
[ "public", "function", "import", "(", ")", "{", "DB", "::", "beginTransaction", "(", ")", ";", "try", "{", "$", "iteration", "=", "0", ";", "while", "(", "!", "feof", "(", "$", "this", "->", "file", ")", ")", "{", "$", "iteration", "++", ";", "$",...
Run the import @return void @throws \Luna\Importer\Exceptions\InvalidCsvLineException @throws \Exception
[ "Run", "the", "import" ]
64bad083a7af35396199f342b57c3e619f2968c6
https://github.com/DuckThom/laravel-importer/blob/64bad083a7af35396199f342b57c3e619f2968c6/src/Runners/CsvRunner.php#L28-L67
233,024
DuckThom/laravel-importer
src/Runners/CsvRunner.php
CsvRunner.handleLine
public function handleLine(array $csvLine) { $fields = $this->importer->parseLine($csvLine); $hash = $this->makeHash($fields); $item = $this->importer->getModelInstance() ->where($this->importer->getUniqueKey(), $fields[$this->importer->getUniqueKey()]) ->lockForUpdate() ->first(); if ($item === null) { // Create a new item and fill it with the fields $item = $this->importer->getModelInstance(); $item->fill($fields); $this->added++; } elseif ($hash !== $item->hash) { // Update the fields if there is a hash mismatch $item->fill($fields); $this->updated++; } elseif ($hash === $item->hash) { $this->unchanged++; } $item->hash = $hash; if (!$this->dryRun) { $item->save(); } }
php
public function handleLine(array $csvLine) { $fields = $this->importer->parseLine($csvLine); $hash = $this->makeHash($fields); $item = $this->importer->getModelInstance() ->where($this->importer->getUniqueKey(), $fields[$this->importer->getUniqueKey()]) ->lockForUpdate() ->first(); if ($item === null) { // Create a new item and fill it with the fields $item = $this->importer->getModelInstance(); $item->fill($fields); $this->added++; } elseif ($hash !== $item->hash) { // Update the fields if there is a hash mismatch $item->fill($fields); $this->updated++; } elseif ($hash === $item->hash) { $this->unchanged++; } $item->hash = $hash; if (!$this->dryRun) { $item->save(); } }
[ "public", "function", "handleLine", "(", "array", "$", "csvLine", ")", "{", "$", "fields", "=", "$", "this", "->", "importer", "->", "parseLine", "(", "$", "csvLine", ")", ";", "$", "hash", "=", "$", "this", "->", "makeHash", "(", "$", "fields", ")",...
Handle a csv line @param array $csvLine @return void @throws InvalidCsvLineException
[ "Handle", "a", "csv", "line" ]
64bad083a7af35396199f342b57c3e619f2968c6
https://github.com/DuckThom/laravel-importer/blob/64bad083a7af35396199f342b57c3e619f2968c6/src/Runners/CsvRunner.php#L76-L105
233,025
DuckThom/laravel-importer
src/Runners/CsvRunner.php
CsvRunner.validateFile
public function validateFile(): bool { return Validator::make( ['fileType' => finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this->importer->getFilePath())], ['fileType' => 'required|string:text/plain|string:text/csv'] )->passes(); }
php
public function validateFile(): bool { return Validator::make( ['fileType' => finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this->importer->getFilePath())], ['fileType' => 'required|string:text/plain|string:text/csv'] )->passes(); }
[ "public", "function", "validateFile", "(", ")", ":", "bool", "{", "return", "Validator", "::", "make", "(", "[", "'fileType'", "=>", "finfo_file", "(", "finfo_open", "(", "FILEINFO_MIME_TYPE", ")", ",", "$", "this", "->", "importer", "->", "getFilePath", "("...
Check if the csv file is valid @return bool
[ "Check", "if", "the", "csv", "file", "is", "valid" ]
64bad083a7af35396199f342b57c3e619f2968c6
https://github.com/DuckThom/laravel-importer/blob/64bad083a7af35396199f342b57c3e619f2968c6/src/Runners/CsvRunner.php#L112-L118
233,026
CottaCush/phalcon-user-auth
src/Models/User.php
User.validation
public function validation() { $validator = new Validation(); $validator->add('email', new Email([ 'message' => 'Invalid email supplied' ])); $validator->add('email', new Uniqueness(array( 'message' => 'Sorry, The email has been used by another user' ))); return $this->validate($validator); }
php
public function validation() { $validator = new Validation(); $validator->add('email', new Email([ 'message' => 'Invalid email supplied' ])); $validator->add('email', new Uniqueness(array( 'message' => 'Sorry, The email has been used by another user' ))); return $this->validate($validator); }
[ "public", "function", "validation", "(", ")", "{", "$", "validator", "=", "new", "Validation", "(", ")", ";", "$", "validator", "->", "add", "(", "'email'", ",", "new", "Email", "(", "[", "'message'", "=>", "'Invalid email supplied'", "]", ")", ")", ";",...
Validate user's email @return bool
[ "Validate", "user", "s", "email" ]
89c8a1ae5e6f712591ba66bc2dd5e8a9f73b9d54
https://github.com/CottaCush/phalcon-user-auth/blob/89c8a1ae5e6f712591ba66bc2dd5e8a9f73b9d54/src/Models/User.php#L68-L81
233,027
CottaCush/phalcon-user-auth
src/Models/User.php
User.changeUserStatus
public function changeUserStatus($email, $newStatus) { /* @var \UserAuth\Models\User */ $user = $this->getUserByEmail($email); if (empty($user)) { throw new StatusChangeException(ErrorMessages::EMAIL_DOES_NOT_EXIST); } if (!array_key_exists($newStatus, self::$statusMap)) { throw new StatusChangeException(ErrorMessages::INVALID_STATUS); } if ($user->status == $newStatus) { throw new StatusChangeException("User status is already set to " . self::getStatusDescriptionFromCode($newStatus)); } //all is fine $user->status = (int)$newStatus; if (!$user->save()) { throw new StatusChangeException(ErrorMessages::STATUS_UPDATE_FAILED); } return true; }
php
public function changeUserStatus($email, $newStatus) { /* @var \UserAuth\Models\User */ $user = $this->getUserByEmail($email); if (empty($user)) { throw new StatusChangeException(ErrorMessages::EMAIL_DOES_NOT_EXIST); } if (!array_key_exists($newStatus, self::$statusMap)) { throw new StatusChangeException(ErrorMessages::INVALID_STATUS); } if ($user->status == $newStatus) { throw new StatusChangeException("User status is already set to " . self::getStatusDescriptionFromCode($newStatus)); } //all is fine $user->status = (int)$newStatus; if (!$user->save()) { throw new StatusChangeException(ErrorMessages::STATUS_UPDATE_FAILED); } return true; }
[ "public", "function", "changeUserStatus", "(", "$", "email", ",", "$", "newStatus", ")", "{", "/* @var \\UserAuth\\Models\\User */", "$", "user", "=", "$", "this", "->", "getUserByEmail", "(", "$", "email", ")", ";", "if", "(", "empty", "(", "$", "user", "...
Change a user's status @param string $email @param int $newStatus @return bool @throws StatusChangeException
[ "Change", "a", "user", "s", "status" ]
89c8a1ae5e6f712591ba66bc2dd5e8a9f73b9d54
https://github.com/CottaCush/phalcon-user-auth/blob/89c8a1ae5e6f712591ba66bc2dd5e8a9f73b9d54/src/Models/User.php#L327-L350
233,028
CottaCush/phalcon-user-auth
src/Models/User.php
User.getUserIdByResetPasswordToken
public function getUserIdByResetPasswordToken($token) { $tokenData = (new UserPasswordReset())->getTokenData($token); return $tokenData == false ? null : $tokenData->user_id; }
php
public function getUserIdByResetPasswordToken($token) { $tokenData = (new UserPasswordReset())->getTokenData($token); return $tokenData == false ? null : $tokenData->user_id; }
[ "public", "function", "getUserIdByResetPasswordToken", "(", "$", "token", ")", "{", "$", "tokenData", "=", "(", "new", "UserPasswordReset", "(", ")", ")", "->", "getTokenData", "(", "$", "token", ")", ";", "return", "$", "tokenData", "==", "false", "?", "n...
Returns the User ID associated with a reset password token @param $token @return null|int
[ "Returns", "the", "User", "ID", "associated", "with", "a", "reset", "password", "token" ]
89c8a1ae5e6f712591ba66bc2dd5e8a9f73b9d54
https://github.com/CottaCush/phalcon-user-auth/blob/89c8a1ae5e6f712591ba66bc2dd5e8a9f73b9d54/src/Models/User.php#L426-L430
233,029
jlorente/yii2-widget-remainingcharacters
RemainingCharacters.php
RemainingCharacters.renderJs
protected function renderJs() { $id = $this->options['id']; $options = $this->getOptionsObject(); $this->getView()->registerJs("$('#$id').remainingCharacters($options);"); }
php
protected function renderJs() { $id = $this->options['id']; $options = $this->getOptionsObject(); $this->getView()->registerJs("$('#$id').remainingCharacters($options);"); }
[ "protected", "function", "renderJs", "(", ")", "{", "$", "id", "=", "$", "this", "->", "options", "[", "'id'", "]", ";", "$", "options", "=", "$", "this", "->", "getOptionsObject", "(", ")", ";", "$", "this", "->", "getView", "(", ")", "->", "regis...
Renders the js necessary to init the plugin.
[ "Renders", "the", "js", "necessary", "to", "init", "the", "plugin", "." ]
e8c37b57793f79daab561c94077316c4658fd320
https://github.com/jlorente/yii2-widget-remainingcharacters/blob/e8c37b57793f79daab561c94077316c4658fd320/RemainingCharacters.php#L90-L95
233,030
laravel-notification-channels/hipchat
src/HipChatMessage.php
HipChatMessage.card
public function card($card) { if ($card instanceof Card) { $this->card = $card; return $this; } if ($card instanceof Closure) { $card($new = new Card()); $this->card = $new; return $this; } throw new InvalidArgumentException( 'Invalid Card type. Expected '.Card::class.' or '.Closure::class.'.' ); }
php
public function card($card) { if ($card instanceof Card) { $this->card = $card; return $this; } if ($card instanceof Closure) { $card($new = new Card()); $this->card = $new; return $this; } throw new InvalidArgumentException( 'Invalid Card type. Expected '.Card::class.' or '.Closure::class.'.' ); }
[ "public", "function", "card", "(", "$", "card", ")", "{", "if", "(", "$", "card", "instanceof", "Card", ")", "{", "$", "this", "->", "card", "=", "$", "card", ";", "return", "$", "this", ";", "}", "if", "(", "$", "card", "instanceof", "Closure", ...
Sets the Card. @param Card|Closure|null $card @return $this
[ "Sets", "the", "Card", "." ]
c24bca85f7cf9f6804635aa206c961783e22e888
https://github.com/laravel-notification-channels/hipchat/blob/c24bca85f7cf9f6804635aa206c961783e22e888/src/HipChatMessage.php#L244-L262
233,031
laravel-notification-channels/hipchat
src/HipChatMessage.php
HipChatMessage.toArray
public function toArray() { $message = str_array_filter([ 'from' => $this->from, 'message_format' => $this->format, 'color' => $this->color, 'notify' => $this->notify, 'message' => $this->content, 'attach_to' => $this->attachTo, ]); if (! is_null($this->card)) { $message['card'] = $this->card->toArray(); } return $message; }
php
public function toArray() { $message = str_array_filter([ 'from' => $this->from, 'message_format' => $this->format, 'color' => $this->color, 'notify' => $this->notify, 'message' => $this->content, 'attach_to' => $this->attachTo, ]); if (! is_null($this->card)) { $message['card'] = $this->card->toArray(); } return $message; }
[ "public", "function", "toArray", "(", ")", "{", "$", "message", "=", "str_array_filter", "(", "[", "'from'", "=>", "$", "this", "->", "from", ",", "'message_format'", "=>", "$", "this", "->", "format", ",", "'color'", "=>", "$", "this", "->", "color", ...
Get an array representation of the HipChatMessage. @return array
[ "Get", "an", "array", "representation", "of", "the", "HipChatMessage", "." ]
c24bca85f7cf9f6804635aa206c961783e22e888
https://github.com/laravel-notification-channels/hipchat/blob/c24bca85f7cf9f6804635aa206c961783e22e888/src/HipChatMessage.php#L282-L298
233,032
bav-php/bav
classes/util/FileUtil.php
FileUtil.safeRename
public function safeRename($source, $destination) { $isRenamed = @rename($source, $destination); if ($isRenamed) { return; } // copy to the target filesystem $tempFileOnSameFS = "$destination.tmp"; $isCopied = copy($source, $tempFileOnSameFS); if (! $isCopied) { throw new FileException( "failed to copy $source to $tempFileOnSameFS." ); } $isUnlinked = unlink($source); if (! $isUnlinked) { trigger_error("Failed to unlink $source."); } $isRenamed = rename($tempFileOnSameFS, $destination); if (! $isRenamed) { throw new FileException( "failed to rename $tempFileOnSameFS to $destination." ); } }
php
public function safeRename($source, $destination) { $isRenamed = @rename($source, $destination); if ($isRenamed) { return; } // copy to the target filesystem $tempFileOnSameFS = "$destination.tmp"; $isCopied = copy($source, $tempFileOnSameFS); if (! $isCopied) { throw new FileException( "failed to copy $source to $tempFileOnSameFS." ); } $isUnlinked = unlink($source); if (! $isUnlinked) { trigger_error("Failed to unlink $source."); } $isRenamed = rename($tempFileOnSameFS, $destination); if (! $isRenamed) { throw new FileException( "failed to rename $tempFileOnSameFS to $destination." ); } }
[ "public", "function", "safeRename", "(", "$", "source", ",", "$", "destination", ")", "{", "$", "isRenamed", "=", "@", "rename", "(", "$", "source", ",", "$", "destination", ")", ";", "if", "(", "$", "isRenamed", ")", "{", "return", ";", "}", "// cop...
Renames a file atomically between different filesystems. @param String $source path of the source @param String $destination path of the destination @throws FileException
[ "Renames", "a", "file", "atomically", "between", "different", "filesystems", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/util/FileUtil.php#L44-L76
233,033
bav-php/bav
classes/util/FileUtil.php
FileUtil.getTempDirectory
public function getTempDirectory() { if (! is_null($this->configuration->getTempDirectory())) { return $this->configuration->getTempDirectory(); } if (is_null($this->cachedTempDirectory)) { $this->cachedTempDirectory = $this->findTempDirectory(); } return $this->cachedTempDirectory; }
php
public function getTempDirectory() { if (! is_null($this->configuration->getTempDirectory())) { return $this->configuration->getTempDirectory(); } if (is_null($this->cachedTempDirectory)) { $this->cachedTempDirectory = $this->findTempDirectory(); } return $this->cachedTempDirectory; }
[ "public", "function", "getTempDirectory", "(", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "configuration", "->", "getTempDirectory", "(", ")", ")", ")", "{", "return", "$", "this", "->", "configuration", "->", "getTempDirectory", "(", ")"...
Returns a writable directory for temporary files @return String @see Configuration::setTempDirectory() @throws NoTempDirectoryException
[ "Returns", "a", "writable", "directory", "for", "temporary", "files" ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/util/FileUtil.php#L85-L97
233,034
unclecheese/silverstripe-kickassets
code/KickAssetsImage.php
KickAssetsImage.getKickAssetsDetailImage
public function getKickAssetsDetailImage() { if ($this->owner->getOrientation() === Image::ORIENTATION_PORTRAIT) { return $this->owner->SetHeight(400); } return $this->owner->SetWidth(600); }
php
public function getKickAssetsDetailImage() { if ($this->owner->getOrientation() === Image::ORIENTATION_PORTRAIT) { return $this->owner->SetHeight(400); } return $this->owner->SetWidth(600); }
[ "public", "function", "getKickAssetsDetailImage", "(", ")", "{", "if", "(", "$", "this", "->", "owner", "->", "getOrientation", "(", ")", "===", "Image", "::", "ORIENTATION_PORTRAIT", ")", "{", "return", "$", "this", "->", "owner", "->", "SetHeight", "(", ...
Returns an image properly formatted for the detail panel @return Image_Cached
[ "Returns", "an", "image", "properly", "formatted", "for", "the", "detail", "panel" ]
1c3cc9655479677ad6628a48071e5a933619b4e7
https://github.com/unclecheese/silverstripe-kickassets/blob/1c3cc9655479677ad6628a48071e5a933619b4e7/code/KickAssetsImage.php#L15-L22
233,035
silverstripe-archive/deploynaut
code/model/DNDataArchive.php
DNDataArchive.canMoveTo
public function canMoveTo($targetEnv, $member = null) { if ($this->Environment()->Project()->ID!=$targetEnv->Project()->ID) { // We don't permit moving snapshots between projects at this stage. return false; } if(!$member) $member = Member::currentUser(); if(!$member) return false; // Must be logged in to check permissions // Admin can always move. if(Permission::checkMember($member, 'ADMIN')) return true; // Checks if the user can actually access the archive. if (!$this->canDownload($member)) return false; // Hooks into ArchiveUploaders permission to prevent proliferation of permission checkboxes. // Bypasses the quota check - we don't need to check for it as long as we move the snapshot within the project. return $targetEnv->ArchiveUploaders()->byID($member->ID) || $member->inGroups($targetEnv->ArchiveUploaderGroups()); }
php
public function canMoveTo($targetEnv, $member = null) { if ($this->Environment()->Project()->ID!=$targetEnv->Project()->ID) { // We don't permit moving snapshots between projects at this stage. return false; } if(!$member) $member = Member::currentUser(); if(!$member) return false; // Must be logged in to check permissions // Admin can always move. if(Permission::checkMember($member, 'ADMIN')) return true; // Checks if the user can actually access the archive. if (!$this->canDownload($member)) return false; // Hooks into ArchiveUploaders permission to prevent proliferation of permission checkboxes. // Bypasses the quota check - we don't need to check for it as long as we move the snapshot within the project. return $targetEnv->ArchiveUploaders()->byID($member->ID) || $member->inGroups($targetEnv->ArchiveUploaderGroups()); }
[ "public", "function", "canMoveTo", "(", "$", "targetEnv", ",", "$", "member", "=", "null", ")", "{", "if", "(", "$", "this", "->", "Environment", "(", ")", "->", "Project", "(", ")", "->", "ID", "!=", "$", "targetEnv", "->", "Project", "(", ")", "-...
Check if this member can move archive into the environment. @param DNEnvironment $targetEnv Environment to check. @param Member|null $member The {@link Member} object to test against. If null, uses Member::currentMember(); @return boolean true if $member can upload archives linked to this environment, false if they can't.
[ "Check", "if", "this", "member", "can", "move", "archive", "into", "the", "environment", "." ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/DNDataArchive.php#L255-L274
233,036
silverstripe-archive/deploynaut
code/model/DNDataArchive.php
DNDataArchive.validTargetEnvironments
public function validTargetEnvironments() { $archive = $this; $envs = $this->Environment()->Project()->DNEnvironmentList() ->filterByCallback(function($item) use ($archive) { return $archive->EnvironmentID!=$item->ID && $archive->canMoveTo($item); }); return $envs; }
php
public function validTargetEnvironments() { $archive = $this; $envs = $this->Environment()->Project()->DNEnvironmentList() ->filterByCallback(function($item) use ($archive) { return $archive->EnvironmentID!=$item->ID && $archive->canMoveTo($item); }); return $envs; }
[ "public", "function", "validTargetEnvironments", "(", ")", "{", "$", "archive", "=", "$", "this", ";", "$", "envs", "=", "$", "this", "->", "Environment", "(", ")", "->", "Project", "(", ")", "->", "DNEnvironmentList", "(", ")", "->", "filterByCallback", ...
Finds all environments within this project where the archive can be moved to. Excludes current environment automatically. @return ArrayList List of valid environments.
[ "Finds", "all", "environments", "within", "this", "project", "where", "the", "archive", "can", "be", "moved", "to", ".", "Excludes", "current", "environment", "automatically", "." ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/DNDataArchive.php#L282-L290
233,037
silverstripe-archive/deploynaut
code/model/DNDataArchive.php
DNDataArchive.validateArchiveContents
public function validateArchiveContents($mode = null) { $mode = $mode ?: $this->Mode; $result = new ValidationResult(); $file = $this->ArchiveFile()->FullPath; if(!is_readable($file)) { $result->error(sprintf('SSPak file "%s" cannot be read.', $file)); return $result; } $process = new Process(sprintf('tar -tf %s', escapeshellarg($file))); $process->setTimeout(120); $process->run(); if(!$process->isSuccessful()) { throw new RuntimeException(sprintf('Could not list files in archive: %s', $process->getErrorOutput())); } $output = explode(PHP_EOL, $process->getOutput()); $files = array_filter($output); if(in_array($mode, array('all', 'db')) && !in_array('database.sql.gz', $files)) { $result->error('The snapshot is missing the database.'); return $result; } if(in_array($mode, array('all', 'assets')) && !in_array('assets.tar.gz', $files)) { $result->error('The snapshot is missing assets.'); return $result; } return $result; }
php
public function validateArchiveContents($mode = null) { $mode = $mode ?: $this->Mode; $result = new ValidationResult(); $file = $this->ArchiveFile()->FullPath; if(!is_readable($file)) { $result->error(sprintf('SSPak file "%s" cannot be read.', $file)); return $result; } $process = new Process(sprintf('tar -tf %s', escapeshellarg($file))); $process->setTimeout(120); $process->run(); if(!$process->isSuccessful()) { throw new RuntimeException(sprintf('Could not list files in archive: %s', $process->getErrorOutput())); } $output = explode(PHP_EOL, $process->getOutput()); $files = array_filter($output); if(in_array($mode, array('all', 'db')) && !in_array('database.sql.gz', $files)) { $result->error('The snapshot is missing the database.'); return $result; } if(in_array($mode, array('all', 'assets')) && !in_array('assets.tar.gz', $files)) { $result->error('The snapshot is missing assets.'); return $result; } return $result; }
[ "public", "function", "validateArchiveContents", "(", "$", "mode", "=", "null", ")", "{", "$", "mode", "=", "$", "mode", "?", ":", "$", "this", "->", "Mode", ";", "$", "result", "=", "new", "ValidationResult", "(", ")", ";", "$", "file", "=", "$", ...
Validate that an sspak contains the correct content. For example, if the user uploaded an sspak containing just the db, but declared in the form that it contained db+assets, then the archive is not valid. @param string $mode "db", "assets", or "all". This is the content we're checking for. Default to the archive setting @return ValidationResult
[ "Validate", "that", "an", "sspak", "contains", "the", "correct", "content", "." ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/DNDataArchive.php#L433-L465
233,038
silverstripe-archive/deploynaut
code/model/DNDataArchive.php
DNDataArchive.fixArchivePermissions
public function fixArchivePermissions($workingDir) { $fixCmds = array( // The directories need to have permissions changed one by one (hence the ; instead of +), // otherwise we might end up having no +x access to a directory deeper down. sprintf('find %s -type d -exec chmod 755 {} \;', escapeshellarg($workingDir)), sprintf('find %s -type f -exec chmod 644 {} +', escapeshellarg($workingDir)) ); foreach($fixCmds as $cmd) { $process = new Process($cmd); $process->setTimeout(3600); $process->run(); if(!$process->isSuccessful()) { throw new RuntimeException($process->getErrorOutput()); } } return true; }
php
public function fixArchivePermissions($workingDir) { $fixCmds = array( // The directories need to have permissions changed one by one (hence the ; instead of +), // otherwise we might end up having no +x access to a directory deeper down. sprintf('find %s -type d -exec chmod 755 {} \;', escapeshellarg($workingDir)), sprintf('find %s -type f -exec chmod 644 {} +', escapeshellarg($workingDir)) ); foreach($fixCmds as $cmd) { $process = new Process($cmd); $process->setTimeout(3600); $process->run(); if(!$process->isSuccessful()) { throw new RuntimeException($process->getErrorOutput()); } } return true; }
[ "public", "function", "fixArchivePermissions", "(", "$", "workingDir", ")", "{", "$", "fixCmds", "=", "array", "(", "// The directories need to have permissions changed one by one (hence the ; instead of +),", "// otherwise we might end up having no +x access to a directory deeper down."...
Given a path that already exists and contains an extracted sspak, including the assets, fix all of the file permissions so they're in a state ready to be pushed to remote servers. Normally, command line tar will use permissions found in the archive, but will substract the user's umask from them. This has a potential to create unreadable files, e.g. cygwin on Windows will pack files with mode 000, hence why this fix is necessary. @param string|null $workingDir The path of where the sspak has been extracted to @throws RuntimeException @return bool
[ "Given", "a", "path", "that", "already", "exists", "and", "contains", "an", "extracted", "sspak", "including", "the", "assets", "fix", "all", "of", "the", "file", "permissions", "so", "they", "re", "in", "a", "state", "ready", "to", "be", "pushed", "to", ...
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/DNDataArchive.php#L481-L499
233,039
silverstripe-archive/deploynaut
code/model/DNDataArchive.php
DNDataArchive.setArchiveFromFiles
public function setArchiveFromFiles($workingDir) { $commands = array(); if($this->Mode == 'db') { if (file_exists($workingDir . '/database.sql')) { $commands[] = 'gzip database.sql'; } $commands[] = sprintf('tar -cf %s database.sql.gz', $this->ArchiveFile()->FullPath); $commands[] = 'rm -f database.sql.gz'; } elseif($this->Mode == 'assets') { $commands[] = 'GZIP=-1 tar --dereference -czf assets.tar.gz assets'; $commands[] = sprintf('tar -cf %s assets.tar.gz', $this->ArchiveFile()->FullPath); $commands[] = 'rm -f assets.tar.gz'; } else { if (file_exists($workingDir . '/database.sql')) { $commands[] = 'gzip database.sql'; } $commands[] = 'GZIP=-1 tar --dereference -czf assets.tar.gz assets'; $commands[] = sprintf('tar -cf %s database.sql.gz assets.tar.gz', $this->ArchiveFile()->FullPath); $commands[] = 'rm -f database.sql.gz assets.tar.gz'; } $process = new Process(implode(' && ', $commands), $workingDir); $process->setTimeout(3600); $process->run(); if(!$process->isSuccessful()) { throw new RuntimeException($process->getErrorOutput()); } $this->write(); return true; }
php
public function setArchiveFromFiles($workingDir) { $commands = array(); if($this->Mode == 'db') { if (file_exists($workingDir . '/database.sql')) { $commands[] = 'gzip database.sql'; } $commands[] = sprintf('tar -cf %s database.sql.gz', $this->ArchiveFile()->FullPath); $commands[] = 'rm -f database.sql.gz'; } elseif($this->Mode == 'assets') { $commands[] = 'GZIP=-1 tar --dereference -czf assets.tar.gz assets'; $commands[] = sprintf('tar -cf %s assets.tar.gz', $this->ArchiveFile()->FullPath); $commands[] = 'rm -f assets.tar.gz'; } else { if (file_exists($workingDir . '/database.sql')) { $commands[] = 'gzip database.sql'; } $commands[] = 'GZIP=-1 tar --dereference -czf assets.tar.gz assets'; $commands[] = sprintf('tar -cf %s database.sql.gz assets.tar.gz', $this->ArchiveFile()->FullPath); $commands[] = 'rm -f database.sql.gz assets.tar.gz'; } $process = new Process(implode(' && ', $commands), $workingDir); $process->setTimeout(3600); $process->run(); if(!$process->isSuccessful()) { throw new RuntimeException($process->getErrorOutput()); } $this->write(); return true; }
[ "public", "function", "setArchiveFromFiles", "(", "$", "workingDir", ")", "{", "$", "commands", "=", "array", "(", ")", ";", "if", "(", "$", "this", "->", "Mode", "==", "'db'", ")", "{", "if", "(", "file_exists", "(", "$", "workingDir", ".", "'/databas...
Given extracted sspak contents, create an sspak from it and overwrite the current ArchiveFile with it's contents. Use GZIP=-1 for less compression on assets, which are already heavily compressed to begin with. @param string|null $workingDir The path of where the sspak has been extracted to @return bool
[ "Given", "extracted", "sspak", "contents", "create", "an", "sspak", "from", "it", "and", "overwrite", "the", "current", "ArchiveFile", "with", "it", "s", "contents", ".", "Use", "GZIP", "=", "-", "1", "for", "less", "compression", "on", "assets", "which", ...
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/DNDataArchive.php#L510-L541
233,040
silverstripe-archive/deploynaut
code/model/DNBranch.php
DNBranch.DNBuildList
public function DNBuildList() { $blockBranch = $this->branch->getName() == 'master' ? null : 'master'; return DNReferenceList::create($this->project, $this->data, $this->branch, $blockBranch); }
php
public function DNBuildList() { $blockBranch = $this->branch->getName() == 'master' ? null : 'master'; return DNReferenceList::create($this->project, $this->data, $this->branch, $blockBranch); }
[ "public", "function", "DNBuildList", "(", ")", "{", "$", "blockBranch", "=", "$", "this", "->", "branch", "->", "getName", "(", ")", "==", "'master'", "?", "null", ":", "'master'", ";", "return", "DNReferenceList", "::", "create", "(", "$", "this", "->",...
Provides a DNBuildList of builds found in this project.
[ "Provides", "a", "DNBuildList", "of", "builds", "found", "in", "this", "project", "." ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/DNBranch.php#L68-L71
233,041
asinfotrack/yii2-toolbox
actions/AjaxAttributeAction.php
AjaxAttributeAction.findModel
protected function findModel($data) { //fetch pk data $pk = []; foreach ($this->modelInstance->primaryKey() as $pkCol) { if (!isset($data[$pkCol])) { throw new InvalidConfigException(Yii::t('app', 'Missing PK-param {param}', ['param' => $pkCol])); } $pk[$pkCol] = $data[$pkCol]; } //find model and act according to result $model = $this->modelInstance->findOne($pk); if ($model === null) throw new NotFoundHttpException(); return $model; }
php
protected function findModel($data) { //fetch pk data $pk = []; foreach ($this->modelInstance->primaryKey() as $pkCol) { if (!isset($data[$pkCol])) { throw new InvalidConfigException(Yii::t('app', 'Missing PK-param {param}', ['param' => $pkCol])); } $pk[$pkCol] = $data[$pkCol]; } //find model and act according to result $model = $this->modelInstance->findOne($pk); if ($model === null) throw new NotFoundHttpException(); return $model; }
[ "protected", "function", "findModel", "(", "$", "data", ")", "{", "//fetch pk data", "$", "pk", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "modelInstance", "->", "primaryKey", "(", ")", "as", "$", "pkCol", ")", "{", "if", "(", "!", "isset...
Finds a model with the provided post data @param array $data the data to read the pk values from @return \yii\db\ActiveRecord the found model @throws \yii\base\InvalidConfigException if pk parts are missing in post-data @throws \yii\web\NotFoundHttpException
[ "Finds", "a", "model", "with", "the", "provided", "post", "data" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/actions/AjaxAttributeAction.php#L126-L141
233,042
asinfotrack/yii2-toolbox
helpers/Html.php
Html.htmlClass
public static function htmlClass($glue='-') { $parts = [ $parts[] = Yii::$app->controller->id, $parts[] = Yii::$app->controller->action->id, ]; if (Yii::$app->module !== null) { array_unshift($parts, Yii::$app->module->id); } return implode($glue, $parts); }
php
public static function htmlClass($glue='-') { $parts = [ $parts[] = Yii::$app->controller->id, $parts[] = Yii::$app->controller->action->id, ]; if (Yii::$app->module !== null) { array_unshift($parts, Yii::$app->module->id); } return implode($glue, $parts); }
[ "public", "static", "function", "htmlClass", "(", "$", "glue", "=", "'-'", ")", "{", "$", "parts", "=", "[", "$", "parts", "[", "]", "=", "Yii", "::", "$", "app", "->", "controller", "->", "id", ",", "$", "parts", "[", "]", "=", "Yii", "::", "$...
Creates a css-class to identify the html-tag by the current controller-, action- and module-ids. On in the index-action of the SiteController this method would return site-index. In module cms, within the article controllers index-action it would return cms-article-index. @param string $glue the glue to join the parts (defaults to '-') @return string the css-class
[ "Creates", "a", "css", "-", "class", "to", "identify", "the", "html", "-", "tag", "by", "the", "current", "controller", "-", "action", "-", "and", "module", "-", "ids", "." ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/Html.php#L43-L55
233,043
asinfotrack/yii2-toolbox
helpers/Html.php
Html.bsLabel
public static function bsLabel($content, $type=self::BS_DEFAULT, $encode=true) { return static::tag('span', $encode ? static::encode($content) : $content, [ 'class'=>'label label-' . $type, ]); }
php
public static function bsLabel($content, $type=self::BS_DEFAULT, $encode=true) { return static::tag('span', $encode ? static::encode($content) : $content, [ 'class'=>'label label-' . $type, ]); }
[ "public", "static", "function", "bsLabel", "(", "$", "content", ",", "$", "type", "=", "self", "::", "BS_DEFAULT", ",", "$", "encode", "=", "true", ")", "{", "return", "static", "::", "tag", "(", "'span'", ",", "$", "encode", "?", "static", "::", "en...
Creates a bootstrap label @param string $content the content of the label @param string $type the bootstrap type (eg alert, danger, etc.) which can be set via constants of this class @param boolean $encode whether or not to encode the content (defaults to true) @return string generated html-code
[ "Creates", "a", "bootstrap", "label" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/Html.php#L94-L99
233,044
asinfotrack/yii2-toolbox
helpers/Html.php
Html.bsListGroup
public function bsListGroup($items, $listOptions=[], $defaultItemOptions=[], $listTagName='ul') { //prepare vars static::addCssClass($defaultItemOptions, 'list-group-item'); $ret = ''; //iterate over items foreach ($items as $i) { if (is_array($i)) { //validate content if (!isset($i['content'])) { throw new InvalidParamException('the index \'content\' is mandatory for each list element'); } //prepare options $itemOptions = $defaultItemOptions; if (isset($i['options'])) { $itemOptions = ArrayHelper::merge($itemOptions, $i['options']); static::addCssClass($itemOptions, 'list-group-item'); } //prepare url if necessary $isLink = isset($i['url']); if ($isLink) { $itemOptions['href'] = is_array($i['url']) ? UrlOriginal::to($i['url']) : $i['url']; } //bs type if (isset($i['type'])) { static::addCssClass($itemOptions, 'list-group-item-' . $i['type']); } //active if (isset($i['active'])) { $isActive = $i['active'] instanceof \Closure ? call_user_func($i['active']) : $i['active']; if ($isActive) static::addCssClass($itemOptions, 'active'); } //badge if (isset($i['badgeVal'])) $i['content'] = static::bsBadge($i['badgeVal']) . $i['content']; //render item $ret .= static::tag($isLink ? 'a' : 'li', $i['content'], $itemOptions) . "\n"; } else { $ret .= static::tag('li', $i, $defaultItemOptions); } } //enclose and return static::addCssClass($listOptions, 'list-group'); return static::tag($listTagName, $ret, $listOptions); }
php
public function bsListGroup($items, $listOptions=[], $defaultItemOptions=[], $listTagName='ul') { //prepare vars static::addCssClass($defaultItemOptions, 'list-group-item'); $ret = ''; //iterate over items foreach ($items as $i) { if (is_array($i)) { //validate content if (!isset($i['content'])) { throw new InvalidParamException('the index \'content\' is mandatory for each list element'); } //prepare options $itemOptions = $defaultItemOptions; if (isset($i['options'])) { $itemOptions = ArrayHelper::merge($itemOptions, $i['options']); static::addCssClass($itemOptions, 'list-group-item'); } //prepare url if necessary $isLink = isset($i['url']); if ($isLink) { $itemOptions['href'] = is_array($i['url']) ? UrlOriginal::to($i['url']) : $i['url']; } //bs type if (isset($i['type'])) { static::addCssClass($itemOptions, 'list-group-item-' . $i['type']); } //active if (isset($i['active'])) { $isActive = $i['active'] instanceof \Closure ? call_user_func($i['active']) : $i['active']; if ($isActive) static::addCssClass($itemOptions, 'active'); } //badge if (isset($i['badgeVal'])) $i['content'] = static::bsBadge($i['badgeVal']) . $i['content']; //render item $ret .= static::tag($isLink ? 'a' : 'li', $i['content'], $itemOptions) . "\n"; } else { $ret .= static::tag('li', $i, $defaultItemOptions); } } //enclose and return static::addCssClass($listOptions, 'list-group'); return static::tag($listTagName, $ret, $listOptions); }
[ "public", "function", "bsListGroup", "(", "$", "items", ",", "$", "listOptions", "=", "[", "]", ",", "$", "defaultItemOptions", "=", "[", "]", ",", "$", "listTagName", "=", "'ul'", ")", "{", "//prepare vars", "static", "::", "addCssClass", "(", "$", "def...
Creates a bootstrap list group. Each item can be specified as a simple string or an array. Subsequent are all valid indices of which \'content\' is mandatory. - content: string contains the content of the item (mandatory!) - options: mixed[] individual item options beeing merged with default item options - url: string|array either a raw url in string format or an array as needed by yiis url-helper (@see \yii\helpers\Url::to()) - type: string the bootstrap type (eg alert, danger, etc.) which can be set via constants of this class - active boolean|\Closure either a boolean value or an anonymous function returning a boolean value - badgeVal string content of an optional badge rendered inside the item @param string[]|mixed[] $items collection of items (each can be string or array) @param mixed[] $listOptions options for the list tag @param mixed[] $defaultItemOptions default options for list items (can be overriden in items individual options) @param string $listTagName tag name for the list (defaults to <code>ul</code>) @throws InvalidParamException if an item is specified in array-form and index \'content\' is not set @return string the code of the list group
[ "Creates", "a", "bootstrap", "list", "group", ".", "Each", "item", "can", "be", "specified", "as", "a", "simple", "string", "or", "an", "array", ".", "Subsequent", "are", "all", "valid", "indices", "of", "which", "\\", "content", "\\", "is", "mandatory", ...
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/Html.php#L125-L170
233,045
asinfotrack/yii2-toolbox
helpers/Html.php
Html.mailtoDisguised
public static function mailtoDisguised($text, $email=null, $options=[]) { //register asset EmailDisguiseAsset::register(Yii::$app->getView()); //get email-address and disguise everything if ($email === null) { $hiddenTag = Html::tag('span', Yii::$app->security->generateRandomString(8), ['style'=>'display: none']); $address = $text; $clear = str_replace('@', $hiddenTag . Html::tag('span', '@') . $hiddenTag, $address); $clear = str_replace('.', $hiddenTag . Html::tag('span', '.') . $hiddenTag, $clear); } else { $address = $email; $clear = $text; } $href = 'mailto:' . strrev(str_replace('@', '[at]', $address)); //prepare options $options['href'] = $href; static::addCssClass($options, 'email-disguised'); //return tag return static::tag('a', $clear, $options); }
php
public static function mailtoDisguised($text, $email=null, $options=[]) { //register asset EmailDisguiseAsset::register(Yii::$app->getView()); //get email-address and disguise everything if ($email === null) { $hiddenTag = Html::tag('span', Yii::$app->security->generateRandomString(8), ['style'=>'display: none']); $address = $text; $clear = str_replace('@', $hiddenTag . Html::tag('span', '@') . $hiddenTag, $address); $clear = str_replace('.', $hiddenTag . Html::tag('span', '.') . $hiddenTag, $clear); } else { $address = $email; $clear = $text; } $href = 'mailto:' . strrev(str_replace('@', '[at]', $address)); //prepare options $options['href'] = $href; static::addCssClass($options, 'email-disguised'); //return tag return static::tag('a', $clear, $options); }
[ "public", "static", "function", "mailtoDisguised", "(", "$", "text", ",", "$", "email", "=", "null", ",", "$", "options", "=", "[", "]", ")", "{", "//register asset", "EmailDisguiseAsset", "::", "register", "(", "Yii", "::", "$", "app", "->", "getView", ...
Generates a mailto hyperlink and disguises the email-address. The address is translated when link gets clicked. @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag. If this is coming from end users, you should consider [[encode()]] it to prevent XSS attacks. @param string $email email address. If this is null, the first parameter (link body) will be treated as the email address and used. @param array $options the tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered. See [[renderTagAttributes()]] for details on how attributes are being rendered. @return string the generated mailto link
[ "Generates", "a", "mailto", "hyperlink", "and", "disguises", "the", "email", "-", "address", ".", "The", "address", "is", "translated", "when", "link", "gets", "clicked", "." ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/Html.php#L224-L248
233,046
sebastiansulinski/dotenv
src/DotEnv/Validator.php
Validator.assertCallback
private function assertCallback(callable $callback, string $message = 'failed callback assertion'): Validator { $variablesFailingAssertion = []; foreach ($this->variables as $variableName) { $variableValue = $this->loader->getVariable($variableName); if (call_user_func($callback, $variableValue) === false) { $variablesFailingAssertion[] = $variableName." $message"; } } if (count($variablesFailingAssertion) > 0) { throw new RuntimeException(sprintf( 'One or more environment variables failed validation: %s', implode(', ', $variablesFailingAssertion) )); } return $this; }
php
private function assertCallback(callable $callback, string $message = 'failed callback assertion'): Validator { $variablesFailingAssertion = []; foreach ($this->variables as $variableName) { $variableValue = $this->loader->getVariable($variableName); if (call_user_func($callback, $variableValue) === false) { $variablesFailingAssertion[] = $variableName." $message"; } } if (count($variablesFailingAssertion) > 0) { throw new RuntimeException(sprintf( 'One or more environment variables failed validation: %s', implode(', ', $variablesFailingAssertion) )); } return $this; }
[ "private", "function", "assertCallback", "(", "callable", "$", "callback", ",", "string", "$", "message", "=", "'failed callback assertion'", ")", ":", "Validator", "{", "$", "variablesFailingAssertion", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "...
Assert that the callback returns true for each variable. @param callable $callback @param string $message @return \SSD\DotEnv\Validator
[ "Assert", "that", "the", "callback", "returns", "true", "for", "each", "variable", "." ]
a298fa533e641aa7ea4cbf89061613226de87bd4
https://github.com/sebastiansulinski/dotenv/blob/a298fa533e641aa7ea4cbf89061613226de87bd4/src/DotEnv/Validator.php#L40-L62
233,047
sebastiansulinski/dotenv
src/DotEnv/Validator.php
Validator.allowedValues
public function allowedValues(array $choices): Validator { return $this->assertCallback( function ($value) use ($choices) { return in_array($value, $choices); }, 'is not an allowed value' ); }
php
public function allowedValues(array $choices): Validator { return $this->assertCallback( function ($value) use ($choices) { return in_array($value, $choices); }, 'is not an allowed value' ); }
[ "public", "function", "allowedValues", "(", "array", "$", "choices", ")", ":", "Validator", "{", "return", "$", "this", "->", "assertCallback", "(", "function", "(", "$", "value", ")", "use", "(", "$", "choices", ")", "{", "return", "in_array", "(", "$",...
Assert that each variable's value matches one from the given collection. @param array $choices @return \SSD\DotEnv\Validator
[ "Assert", "that", "each", "variable", "s", "value", "matches", "one", "from", "the", "given", "collection", "." ]
a298fa533e641aa7ea4cbf89061613226de87bd4
https://github.com/sebastiansulinski/dotenv/blob/a298fa533e641aa7ea4cbf89061613226de87bd4/src/DotEnv/Validator.php#L101-L109
233,048
swoft-cloud/swoft-http-message
src/Server/Request.php
Request.loadFromSwooleRequest
public static function loadFromSwooleRequest(\Swoole\Http\Request $swooleRequest) { $server = $swooleRequest->server; $method = $server['request_method'] ?? 'GET'; $headers = $swooleRequest->header ?? []; $uri = self::getUriFromGlobals($swooleRequest); $body = new SwooleStream($swooleRequest->rawContent()); $protocol = isset($server['server_protocol']) ? str_replace('HTTP/', '', $server['server_protocol']) : '1.1'; $request = new static($method, $uri, $headers, $body, $protocol); $request->cookieParams = ($swooleRequest->cookie ?? []); $request->queryParams = ($swooleRequest->get ?? []); $request->serverParams = ($server ?? []); $request->parsedBody = ($swooleRequest->post ?? []); $request->uploadedFiles = self::normalizeFiles($swooleRequest->files ?? []); $request->swooleRequest = $swooleRequest; return $request; }
php
public static function loadFromSwooleRequest(\Swoole\Http\Request $swooleRequest) { $server = $swooleRequest->server; $method = $server['request_method'] ?? 'GET'; $headers = $swooleRequest->header ?? []; $uri = self::getUriFromGlobals($swooleRequest); $body = new SwooleStream($swooleRequest->rawContent()); $protocol = isset($server['server_protocol']) ? str_replace('HTTP/', '', $server['server_protocol']) : '1.1'; $request = new static($method, $uri, $headers, $body, $protocol); $request->cookieParams = ($swooleRequest->cookie ?? []); $request->queryParams = ($swooleRequest->get ?? []); $request->serverParams = ($server ?? []); $request->parsedBody = ($swooleRequest->post ?? []); $request->uploadedFiles = self::normalizeFiles($swooleRequest->files ?? []); $request->swooleRequest = $swooleRequest; return $request; }
[ "public", "static", "function", "loadFromSwooleRequest", "(", "\\", "Swoole", "\\", "Http", "\\", "Request", "$", "swooleRequest", ")", "{", "$", "server", "=", "$", "swooleRequest", "->", "server", ";", "$", "method", "=", "$", "server", "[", "'request_meth...
Load a swoole request, and transfer to a swoft request object @param \Swoole\Http\Request $swooleRequest @return \Swoft\Http\Message\Server\Request
[ "Load", "a", "swoole", "request", "and", "transfer", "to", "a", "swoft", "request", "object" ]
5cc36c68b24d8ff9bc75cd0f6c8492bcc452f73a
https://github.com/swoft-cloud/swoft-http-message/blob/5cc36c68b24d8ff9bc75cd0f6c8492bcc452f73a/src/Server/Request.php#L71-L87
233,049
swoft-cloud/swoft-http-message
src/Server/Request.php
Request.addParserBody
public function addParserBody(string $name, $value) { if (is_array($this->parsedBody)) { $clone = clone $this; $clone->parsedBody[$name] = $value; return $clone; } return $this; }
php
public function addParserBody(string $name, $value) { if (is_array($this->parsedBody)) { $clone = clone $this; $clone->parsedBody[$name] = $value; return $clone; } return $this; }
[ "public", "function", "addParserBody", "(", "string", "$", "name", ",", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "parsedBody", ")", ")", "{", "$", "clone", "=", "clone", "$", "this", ";", "$", "clone", "->", "parsedBody"...
add parser body @param string $name the name of param @param mixed $value the value of param @return static
[ "add", "parser", "body" ]
5cc36c68b24d8ff9bc75cd0f6c8492bcc452f73a
https://github.com/swoft-cloud/swoft-http-message/blob/5cc36c68b24d8ff9bc75cd0f6c8492bcc452f73a/src/Server/Request.php#L395-L404
233,050
webfactorybulgaria/laravel-shop
src/LaravelShop.php
LaravelShop.format
public static function format($value) { $formatFunction = Config::get('shop.display_price_number_format') ?: function($price) { return number_format($price, 2); }; return preg_replace( [ '/:symbol/', '/:price/', '/:currency/' ], [ Config::get('shop.currency_symbol'), $formatFunction($value), Config::get('shop.currency') ], Config::get('shop.display_price_format') ); }
php
public static function format($value) { $formatFunction = Config::get('shop.display_price_number_format') ?: function($price) { return number_format($price, 2); }; return preg_replace( [ '/:symbol/', '/:price/', '/:currency/' ], [ Config::get('shop.currency_symbol'), $formatFunction($value), Config::get('shop.currency') ], Config::get('shop.display_price_format') ); }
[ "public", "static", "function", "format", "(", "$", "value", ")", "{", "$", "formatFunction", "=", "Config", "::", "get", "(", "'shop.display_price_number_format'", ")", "?", ":", "function", "(", "$", "price", ")", "{", "return", "number_format", "(", "$", ...
Formats any value to price format set in config. @param mixed $value Value to format. @return string
[ "Formats", "any", "value", "to", "price", "format", "set", "in", "config", "." ]
9d191b7d17395bd875505bfbc0b1077dc6c87869
https://github.com/webfactorybulgaria/laravel-shop/blob/9d191b7d17395bd875505bfbc0b1077dc6c87869/src/LaravelShop.php#L268-L284
233,051
ameliaikeda/backblaze
src/Adapter.php
Adapter.getUrl
public function getUrl($path) { if (! $this->host) { throw new BadMethodCallException("The 'host' key must be set in the b2 storage adapter to fetch URLs."); } return 'https://' . $this->host . '/file/' . $this->bucketName . '/' . $path; }
php
public function getUrl($path) { if (! $this->host) { throw new BadMethodCallException("The 'host' key must be set in the b2 storage adapter to fetch URLs."); } return 'https://' . $this->host . '/file/' . $this->bucketName . '/' . $path; }
[ "public", "function", "getUrl", "(", "$", "path", ")", "{", "if", "(", "!", "$", "this", "->", "host", ")", "{", "throw", "new", "BadMethodCallException", "(", "\"The 'host' key must be set in the b2 storage adapter to fetch URLs.\"", ")", ";", "}", "return", "'ht...
Get the URL to the given path. @param $path @return string
[ "Get", "the", "URL", "to", "the", "given", "path", "." ]
72dd26a55549e3bfd7a551e019b9eefad7e50f5e
https://github.com/ameliaikeda/backblaze/blob/72dd26a55549e3bfd7a551e019b9eefad7e50f5e/src/Adapter.php#L38-L45
233,052
networkteam/Networkteam.SentryClient
Classes/Handler/DebugExceptionHandler.php
DebugExceptionHandler.sendExceptionToSentry
protected function sendExceptionToSentry($exception) { if (!Bootstrap::$staticObjectManager instanceof ObjectManagerInterface) { return; } $options = $this->resolveCustomRenderingOptions($exception); $logException = $options['logException'] ?? false; $sentryClientIgnoreException = $options['sentryClientIgnoreException'] ?? false; if ($logException && !$sentryClientIgnoreException) { try { $errorHandler = Bootstrap::$staticObjectManager->get(ErrorHandler::class); if ($errorHandler !== null) { $errorHandler->handleException($exception); } } catch (\Exception $exception) { // Quick'n dirty workaround to catch exception with the error handler is called during compile time } } }
php
protected function sendExceptionToSentry($exception) { if (!Bootstrap::$staticObjectManager instanceof ObjectManagerInterface) { return; } $options = $this->resolveCustomRenderingOptions($exception); $logException = $options['logException'] ?? false; $sentryClientIgnoreException = $options['sentryClientIgnoreException'] ?? false; if ($logException && !$sentryClientIgnoreException) { try { $errorHandler = Bootstrap::$staticObjectManager->get(ErrorHandler::class); if ($errorHandler !== null) { $errorHandler->handleException($exception); } } catch (\Exception $exception) { // Quick'n dirty workaround to catch exception with the error handler is called during compile time } } }
[ "protected", "function", "sendExceptionToSentry", "(", "$", "exception", ")", "{", "if", "(", "!", "Bootstrap", "::", "$", "staticObjectManager", "instanceof", "ObjectManagerInterface", ")", "{", "return", ";", "}", "$", "options", "=", "$", "this", "->", "res...
Send an exception to Sentry, but only if the "logException" rendering option is true During compiletime there might be missing dependencies, so we need additional safeguards to not cause errors. @param \Throwable $exception The throwable
[ "Send", "an", "exception", "to", "Sentry", "but", "only", "if", "the", "logException", "rendering", "option", "is", "true" ]
ad5f7e0e32b0fd11da21b3e37a1ae8dc5e6c2cbc
https://github.com/networkteam/Networkteam.SentryClient/blob/ad5f7e0e32b0fd11da21b3e37a1ae8dc5e6c2cbc/Classes/Handler/DebugExceptionHandler.php#L38-L57
233,053
silverstripe-archive/deploynaut
code/model/steps/PipelineStep.php
PipelineStep.markFailed
public function markFailed($notify = true) { $this->Status = 'Failed'; $this->log('Marking pipeline step as failed. See earlier log messages to determine cause.'); $this->write(); $this->Pipeline()->markFailed($notify); }
php
public function markFailed($notify = true) { $this->Status = 'Failed'; $this->log('Marking pipeline step as failed. See earlier log messages to determine cause.'); $this->write(); $this->Pipeline()->markFailed($notify); }
[ "public", "function", "markFailed", "(", "$", "notify", "=", "true", ")", "{", "$", "this", "->", "Status", "=", "'Failed'", ";", "$", "this", "->", "log", "(", "'Marking pipeline step as failed. See earlier log messages to determine cause.'", ")", ";", "$", "this...
Fail this pipeline step @param bool $notify Set to false to disable notifications for this failure
[ "Fail", "this", "pipeline", "step" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/PipelineStep.php#L145-L150
233,054
silverstripe-archive/deploynaut
code/model/steps/PipelineStep.php
PipelineStep.abort
public function abort() { if ($this->isQueued() || $this->isRunning()) { $this->Status = 'Aborted'; $this->log('Step aborted'); $this->write(); } return true; }
php
public function abort() { if ($this->isQueued() || $this->isRunning()) { $this->Status = 'Aborted'; $this->log('Step aborted'); $this->write(); } return true; }
[ "public", "function", "abort", "(", ")", "{", "if", "(", "$", "this", "->", "isQueued", "(", ")", "||", "$", "this", "->", "isRunning", "(", ")", ")", "{", "$", "this", "->", "Status", "=", "'Aborted'", ";", "$", "this", "->", "log", "(", "'Step ...
Abort the step immediately, regardless of its current state, performing any cleanup necessary. If a step is aborted, all subsequent states will also be aborted by the Pipeline, so it is possible for a Queued step to skip straight to Aborted state. No further state transitions may occur. If aborting fails return false but remain in Aborted state. @return boolean True if successfully aborted, false if error
[ "Abort", "the", "step", "immediately", "regardless", "of", "its", "current", "state", "performing", "any", "cleanup", "necessary", ".", "If", "a", "step", "is", "aborted", "all", "subsequent", "states", "will", "also", "be", "aborted", "by", "the", "Pipeline",...
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/PipelineStep.php#L252-L261
233,055
bav-php/bav
classes/bank/Bank.php
Bank.getAgencies
public function getAgencies() { if (is_null($this->agencies)) { $this->agencies = $this->dataBackend->getAgenciesForBank($this); } return $this->agencies; }
php
public function getAgencies() { if (is_null($this->agencies)) { $this->agencies = $this->dataBackend->getAgenciesForBank($this); } return $this->agencies; }
[ "public", "function", "getAgencies", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "agencies", ")", ")", "{", "$", "this", "->", "agencies", "=", "$", "this", "->", "dataBackend", "->", "getAgenciesForBank", "(", "$", "this", ")", ";", ...
A bank may have more agencies. @throws DataBackendException @return Agency[]
[ "A", "bank", "may", "have", "more", "agencies", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/bank/Bank.php#L122-L129
233,056
OzanKurt/google-analytics
src/Traits/Filters/CustomCommonFilters.php
CustomCommonFilters.getVisitsByDate
public function getVisitsByDate($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:visits', 'dimensions' => 'ga:date', ]); return $this->execute($parameters, $parseResult); }
php
public function getVisitsByDate($parameters = [], $parseResult = true) { $this->setParams([ 'metrics' => 'ga:visits', 'dimensions' => 'ga:date', ]); return $this->execute($parameters, $parseResult); }
[ "public", "function", "getVisitsByDate", "(", "$", "parameters", "=", "[", "]", ",", "$", "parseResult", "=", "true", ")", "{", "$", "this", "->", "setParams", "(", "[", "'metrics'", "=>", "'ga:visits'", ",", "'dimensions'", "=>", "'ga:date'", ",", "]", ...
Visit by date. @param array $parameters Parameters you may want to overwrite. @return array
[ "Visit", "by", "date", "." ]
da5fecb6d9267f2fc5015a918c3aebda2c2f70a5
https://github.com/OzanKurt/google-analytics/blob/da5fecb6d9267f2fc5015a918c3aebda2c2f70a5/src/Traits/Filters/CustomCommonFilters.php#L14-L22
233,057
QuickenLoans/uri-template
src/Expander.php
Expander.expandExplodeMod
private function expandExplodeMod($op, $varname, array $varvalue) { $result = ''; $first = true; $isList = $this->isNumericArray($varvalue); if (self::$behavior[$op]['named']) { foreach ($varvalue as $name => $value) { if ($first) { $first = false; } else { $result .= self::$behavior[$op]['sep']; } if ($isList) { $result .= $varname; } else { $result .= $name; } if (!$value) { $result .= self::$behavior[$op]['ifemp']; } else { $result .= '=' . rawurlencode($value); } } } else { if ($isList) { if (self::$behavior[$op]['allow'] === 'U') { $varvalue = array_map('rawurlencode', $varvalue); } else { $varvalue = array_map([$this, 'encodeNonReservedCharacters'], $varvalue); } $result .= implode(self::$behavior[$op]['sep'], $varvalue); } else { $newvals = []; foreach ($varvalue as $name => $value) { if (self::$behavior[$op]['allow'] === 'U') { $newvals[] .= rawurlencode($name) . '=' . rawurlencode($value); } else { $newvals[] .= $this->encodeNonReservedCharacters($name) . '=' . $this->encodeNonReservedCharacters($value); } } $result .= implode(self::$behavior[$op]['sep'], $newvals); } } return $result; }
php
private function expandExplodeMod($op, $varname, array $varvalue) { $result = ''; $first = true; $isList = $this->isNumericArray($varvalue); if (self::$behavior[$op]['named']) { foreach ($varvalue as $name => $value) { if ($first) { $first = false; } else { $result .= self::$behavior[$op]['sep']; } if ($isList) { $result .= $varname; } else { $result .= $name; } if (!$value) { $result .= self::$behavior[$op]['ifemp']; } else { $result .= '=' . rawurlencode($value); } } } else { if ($isList) { if (self::$behavior[$op]['allow'] === 'U') { $varvalue = array_map('rawurlencode', $varvalue); } else { $varvalue = array_map([$this, 'encodeNonReservedCharacters'], $varvalue); } $result .= implode(self::$behavior[$op]['sep'], $varvalue); } else { $newvals = []; foreach ($varvalue as $name => $value) { if (self::$behavior[$op]['allow'] === 'U') { $newvals[] .= rawurlencode($name) . '=' . rawurlencode($value); } else { $newvals[] .= $this->encodeNonReservedCharacters($name) . '=' . $this->encodeNonReservedCharacters($value); } } $result .= implode(self::$behavior[$op]['sep'], $newvals); } } return $result; }
[ "private", "function", "expandExplodeMod", "(", "$", "op", ",", "$", "varname", ",", "array", "$", "varvalue", ")", "{", "$", "result", "=", "''", ";", "$", "first", "=", "true", ";", "$", "isList", "=", "$", "this", "->", "isNumericArray", "(", "$",...
Does the work of the explode modifier @param string|null $op @param string $varname @param array $varvalue @return string
[ "Does", "the", "work", "of", "the", "explode", "modifier" ]
948f14d8e288641b72bd0c1de6647d2c9ccae616
https://github.com/QuickenLoans/uri-template/blob/948f14d8e288641b72bd0c1de6647d2c9ccae616/src/Expander.php#L280-L325
233,058
QuickenLoans/uri-template
src/Expander.php
Expander.isNumericArray
private function isNumericArray(array $arr) { $numeric = true; $i = 0; foreach ($arr as $k => $v) { if ($i !== $k) { $numeric = false; return $numeric; } $i++; } return $numeric; }
php
private function isNumericArray(array $arr) { $numeric = true; $i = 0; foreach ($arr as $k => $v) { if ($i !== $k) { $numeric = false; return $numeric; } $i++; } return $numeric; }
[ "private", "function", "isNumericArray", "(", "array", "$", "arr", ")", "{", "$", "numeric", "=", "true", ";", "$", "i", "=", "0", ";", "foreach", "(", "$", "arr", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "$", "i", "!==", "$", "k"...
This method decides if the given array is a 'list' or an 'associative array' The RFC defines variable data to be either a string, a list or an associative array of name, value pairs. Since PHP's array construct can be either a list OR an associative array, this method does the differentiation. @param array $arr @return boolean
[ "This", "method", "decides", "if", "the", "given", "array", "is", "a", "list", "or", "an", "associative", "array" ]
948f14d8e288641b72bd0c1de6647d2c9ccae616
https://github.com/QuickenLoans/uri-template/blob/948f14d8e288641b72bd0c1de6647d2c9ccae616/src/Expander.php#L338-L350
233,059
sebastiansulinski/dotenv
src/DotEnv/Loader.php
Loader.toArray
public function toArray(string $loadingMethod = null): array { if (in_array($loadingMethod, [DotEnv::LOAD, DotEnv::OVERLOAD])) { $this->immutable = $loadingMethod === DotEnv::LOAD; $this->setter = true; } else { $this->setter = false; } $this->getContent(); $this->processEntries(); return $this->attributes; }
php
public function toArray(string $loadingMethod = null): array { if (in_array($loadingMethod, [DotEnv::LOAD, DotEnv::OVERLOAD])) { $this->immutable = $loadingMethod === DotEnv::LOAD; $this->setter = true; } else { $this->setter = false; } $this->getContent(); $this->processEntries(); return $this->attributes; }
[ "public", "function", "toArray", "(", "string", "$", "loadingMethod", "=", "null", ")", ":", "array", "{", "if", "(", "in_array", "(", "$", "loadingMethod", ",", "[", "DotEnv", "::", "LOAD", ",", "DotEnv", "::", "OVERLOAD", "]", ")", ")", "{", "$", "...
Load the files and return all variables as array without setting environment variables. @param string|null $loadingMethod @return array
[ "Load", "the", "files", "and", "return", "all", "variables", "as", "array", "without", "setting", "environment", "variables", "." ]
a298fa533e641aa7ea4cbf89061613226de87bd4
https://github.com/sebastiansulinski/dotenv/blob/a298fa533e641aa7ea4cbf89061613226de87bd4/src/DotEnv/Loader.php#L54-L73
233,060
sebastiansulinski/dotenv
src/DotEnv/Loader.php
Loader.readFileContent
private function readFileContent(string $file): void { $autodetect = ini_get('auto_detect_line_endings'); ini_set('auto_detect_line_endings', '1'); $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); ini_set('auto_detect_line_endings', $autodetect); $this->lines = array_merge($this->lines, $lines); }
php
private function readFileContent(string $file): void { $autodetect = ini_get('auto_detect_line_endings'); ini_set('auto_detect_line_endings', '1'); $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); ini_set('auto_detect_line_endings', $autodetect); $this->lines = array_merge($this->lines, $lines); }
[ "private", "function", "readFileContent", "(", "string", "$", "file", ")", ":", "void", "{", "$", "autodetect", "=", "ini_get", "(", "'auto_detect_line_endings'", ")", ";", "ini_set", "(", "'auto_detect_line_endings'", ",", "'1'", ")", ";", "$", "lines", "=", ...
Read content of a file and add its lines to the collection. @param string $file @return void
[ "Read", "content", "of", "a", "file", "and", "add", "its", "lines", "to", "the", "collection", "." ]
a298fa533e641aa7ea4cbf89061613226de87bd4
https://github.com/sebastiansulinski/dotenv/blob/a298fa533e641aa7ea4cbf89061613226de87bd4/src/DotEnv/Loader.php#L115-L123
233,061
sebastiansulinski/dotenv
src/DotEnv/Loader.php
Loader.readDirectoryContent
private function readDirectoryContent(string $directory): void { $items = new DirectoryIterator($directory); foreach ($items as $item) { if ($item->isFile() && $this->isFile($item->getFilename())) { $this->readFileContent($item->getPathname()); } } }
php
private function readDirectoryContent(string $directory): void { $items = new DirectoryIterator($directory); foreach ($items as $item) { if ($item->isFile() && $this->isFile($item->getFilename())) { $this->readFileContent($item->getPathname()); } } }
[ "private", "function", "readDirectoryContent", "(", "string", "$", "directory", ")", ":", "void", "{", "$", "items", "=", "new", "DirectoryIterator", "(", "$", "directory", ")", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "if", "(", ...
Read content of a directory and add each qualifying file's content lines to the collection. @param string $directory @return void
[ "Read", "content", "of", "a", "directory", "and", "add", "each", "qualifying", "file", "s", "content", "lines", "to", "the", "collection", "." ]
a298fa533e641aa7ea4cbf89061613226de87bd4
https://github.com/sebastiansulinski/dotenv/blob/a298fa533e641aa7ea4cbf89061613226de87bd4/src/DotEnv/Loader.php#L133-L143
233,062
sebastiansulinski/dotenv
src/DotEnv/Loader.php
Loader.processEntries
private function processEntries(): void { if (empty($this->lines)) { return; } foreach ($this->lines as $line) { if ($this->isLineComment($line) || !$this->isLineSetter($line)) { continue; } $this->setVariable($line); } }
php
private function processEntries(): void { if (empty($this->lines)) { return; } foreach ($this->lines as $line) { if ($this->isLineComment($line) || !$this->isLineSetter($line)) { continue; } $this->setVariable($line); } }
[ "private", "function", "processEntries", "(", ")", ":", "void", "{", "if", "(", "empty", "(", "$", "this", "->", "lines", ")", ")", "{", "return", ";", "}", "foreach", "(", "$", "this", "->", "lines", "as", "$", "line", ")", "{", "if", "(", "$", ...
Validate lines fetch from the files and set variables accordingly. @return void
[ "Validate", "lines", "fetch", "from", "the", "files", "and", "set", "variables", "accordingly", "." ]
a298fa533e641aa7ea4cbf89061613226de87bd4
https://github.com/sebastiansulinski/dotenv/blob/a298fa533e641aa7ea4cbf89061613226de87bd4/src/DotEnv/Loader.php#L163-L177
233,063
sebastiansulinski/dotenv
src/DotEnv/Loader.php
Loader.normaliseVariable
private function normaliseVariable(string $name, $value): array { [$name, $value] = $this->sanitiseVariableValue( ...$this->sanitiseVariableName( ...$this->splitStringIntoParts($name, $value) ) ); $value = $this->resolveNestedVariables($value); return [$name, $value]; }
php
private function normaliseVariable(string $name, $value): array { [$name, $value] = $this->sanitiseVariableValue( ...$this->sanitiseVariableName( ...$this->splitStringIntoParts($name, $value) ) ); $value = $this->resolveNestedVariables($value); return [$name, $value]; }
[ "private", "function", "normaliseVariable", "(", "string", "$", "name", ",", "$", "value", ")", ":", "array", "{", "[", "$", "name", ",", "$", "value", "]", "=", "$", "this", "->", "sanitiseVariableValue", "(", "...", "$", "this", "->", "sanitiseVariable...
Normalise given name and value. - Splits the string using "=" symbol - Strips the quotes from name and value - Resolves nested variables @param string $name @param mixed $value @return array
[ "Normalise", "given", "name", "and", "value", "." ]
a298fa533e641aa7ea4cbf89061613226de87bd4
https://github.com/sebastiansulinski/dotenv/blob/a298fa533e641aa7ea4cbf89061613226de87bd4/src/DotEnv/Loader.php#L242-L253
233,064
sebastiansulinski/dotenv
src/DotEnv/Loader.php
Loader.splitStringIntoParts
private function splitStringIntoParts(string $name, $value): array { if (strpos($name, '=') !== false) { [$name, $value] = array_map('trim', explode('=', $name, 2)); } return [$name, $value]; }
php
private function splitStringIntoParts(string $name, $value): array { if (strpos($name, '=') !== false) { [$name, $value] = array_map('trim', explode('=', $name, 2)); } return [$name, $value]; }
[ "private", "function", "splitStringIntoParts", "(", "string", "$", "name", ",", "$", "value", ")", ":", "array", "{", "if", "(", "strpos", "(", "$", "name", ",", "'='", ")", "!==", "false", ")", "{", "[", "$", "name", ",", "$", "value", "]", "=", ...
Split name into parts. If the "$name" contains a "=" symbol we split it into "$name" and "$value" disregarding "$value" argument of the method. @param string $name @param mixed $value @return array
[ "Split", "name", "into", "parts", "." ]
a298fa533e641aa7ea4cbf89061613226de87bd4
https://github.com/sebastiansulinski/dotenv/blob/a298fa533e641aa7ea4cbf89061613226de87bd4/src/DotEnv/Loader.php#L266-L273
233,065
sebastiansulinski/dotenv
src/DotEnv/Loader.php
Loader.sanitiseVariableName
private function sanitiseVariableName(string $name, $value): array { $name = trim(str_replace(['export ', '\'', '"'], '', $name)); return [$name, $value]; }
php
private function sanitiseVariableName(string $name, $value): array { $name = trim(str_replace(['export ', '\'', '"'], '', $name)); return [$name, $value]; }
[ "private", "function", "sanitiseVariableName", "(", "string", "$", "name", ",", "$", "value", ")", ":", "array", "{", "$", "name", "=", "trim", "(", "str_replace", "(", "[", "'export '", ",", "'\\''", ",", "'\"'", "]", ",", "''", ",", "$", "name", ")...
Strip quotes and the optional leading "export" from the name. @param string $name @param mixed $value @return array
[ "Strip", "quotes", "and", "the", "optional", "leading", "export", "from", "the", "name", "." ]
a298fa533e641aa7ea4cbf89061613226de87bd4
https://github.com/sebastiansulinski/dotenv/blob/a298fa533e641aa7ea4cbf89061613226de87bd4/src/DotEnv/Loader.php#L283-L288
233,066
sebastiansulinski/dotenv
src/DotEnv/Loader.php
Loader.sanitiseVariableValue
private function sanitiseVariableValue(string $name, $value): array { $value = trim($value); if (!$value) { return [$name, $value]; } $value = $this->getSanitisedValue($value); return [$name, trim($value)]; }
php
private function sanitiseVariableValue(string $name, $value): array { $value = trim($value); if (!$value) { return [$name, $value]; } $value = $this->getSanitisedValue($value); return [$name, trim($value)]; }
[ "private", "function", "sanitiseVariableValue", "(", "string", "$", "name", ",", "$", "value", ")", ":", "array", "{", "$", "value", "=", "trim", "(", "$", "value", ")", ";", "if", "(", "!", "$", "value", ")", "{", "return", "[", "$", "name", ",", ...
Strip quotes from the value. @param string $name @param mixed $value @return array
[ "Strip", "quotes", "from", "the", "value", "." ]
a298fa533e641aa7ea4cbf89061613226de87bd4
https://github.com/sebastiansulinski/dotenv/blob/a298fa533e641aa7ea4cbf89061613226de87bd4/src/DotEnv/Loader.php#L297-L308
233,067
sebastiansulinski/dotenv
src/DotEnv/Loader.php
Loader.getSanitisedValue
private function getSanitisedValue($value) { if ($this->beginsWithQuote($value)) { $quote = $value[0]; $regexPattern = sprintf( '/^ %1$s # match a quote at the start of the value ( # capturing sub-pattern used (?: # we do not need to capture this [^%1$s\\\\] # any character other than a quote or backslash |\\\\\\\\ # or two backslashes together |\\\\%1$s # or an escaped quote e.g \" )* # as many characters that match the previous rules ) # end of the capturing sub-pattern %1$s # and the closing quote .*$ # and discard any string after the closing quote /mx', $quote ); $value = preg_replace($regexPattern, '$1', $value); $value = str_replace("\\$quote", $quote, $value); $value = str_replace('\\\\', '\\', $value); return $value; } $parts = explode(' #', $value, 2); $value = trim($parts[0]); if (preg_match('/\s+/', $value) > 0) { throw new InvalidArgumentException('DotEnv values containing spaces must be surrounded by quotes.'); } return $value; }
php
private function getSanitisedValue($value) { if ($this->beginsWithQuote($value)) { $quote = $value[0]; $regexPattern = sprintf( '/^ %1$s # match a quote at the start of the value ( # capturing sub-pattern used (?: # we do not need to capture this [^%1$s\\\\] # any character other than a quote or backslash |\\\\\\\\ # or two backslashes together |\\\\%1$s # or an escaped quote e.g \" )* # as many characters that match the previous rules ) # end of the capturing sub-pattern %1$s # and the closing quote .*$ # and discard any string after the closing quote /mx', $quote ); $value = preg_replace($regexPattern, '$1', $value); $value = str_replace("\\$quote", $quote, $value); $value = str_replace('\\\\', '\\', $value); return $value; } $parts = explode(' #', $value, 2); $value = trim($parts[0]); if (preg_match('/\s+/', $value) > 0) { throw new InvalidArgumentException('DotEnv values containing spaces must be surrounded by quotes.'); } return $value; }
[ "private", "function", "getSanitisedValue", "(", "$", "value", ")", "{", "if", "(", "$", "this", "->", "beginsWithQuote", "(", "$", "value", ")", ")", "{", "$", "quote", "=", "$", "value", "[", "0", "]", ";", "$", "regexPattern", "=", "sprintf", "(",...
Return value without the quotes. @param mixed $value @return mixed @throws InvalidArgumentException
[ "Return", "value", "without", "the", "quotes", "." ]
a298fa533e641aa7ea4cbf89061613226de87bd4
https://github.com/sebastiansulinski/dotenv/blob/a298fa533e641aa7ea4cbf89061613226de87bd4/src/DotEnv/Loader.php#L317-L354
233,068
sebastiansulinski/dotenv
src/DotEnv/Loader.php
Loader.clearVariable
public function clearVariable(string $name) { if ($this->immutable) { return; } putenv($name); unset($_ENV[$name]); unset($_SERVER[$name]); }
php
public function clearVariable(string $name) { if ($this->immutable) { return; } putenv($name); unset($_ENV[$name]); unset($_SERVER[$name]); }
[ "public", "function", "clearVariable", "(", "string", "$", "name", ")", "{", "if", "(", "$", "this", "->", "immutable", ")", "{", "return", ";", "}", "putenv", "(", "$", "name", ")", ";", "unset", "(", "$", "_ENV", "[", "$", "name", "]", ")", ";"...
Clear environment variable by name. @param string $name
[ "Clear", "environment", "variable", "by", "name", "." ]
a298fa533e641aa7ea4cbf89061613226de87bd4
https://github.com/sebastiansulinski/dotenv/blob/a298fa533e641aa7ea4cbf89061613226de87bd4/src/DotEnv/Loader.php#L424-L433
233,069
CottaCush/phalcon-user-auth
src/Models/UserPasswordReset.php
UserPasswordReset.tokenExists
private function tokenExists($token) { $tokenData = $this->getTokenData($token); if ($tokenData == false) { return false; } return $tokenData == false ? true : false; }
php
private function tokenExists($token) { $tokenData = $this->getTokenData($token); if ($tokenData == false) { return false; } return $tokenData == false ? true : false; }
[ "private", "function", "tokenExists", "(", "$", "token", ")", "{", "$", "tokenData", "=", "$", "this", "->", "getTokenData", "(", "$", "token", ")", ";", "if", "(", "$", "tokenData", "==", "false", ")", "{", "return", "false", ";", "}", "return", "$"...
Check if a token already exists @param string $token @return bool
[ "Check", "if", "a", "token", "already", "exists" ]
89c8a1ae5e6f712591ba66bc2dd5e8a9f73b9d54
https://github.com/CottaCush/phalcon-user-auth/blob/89c8a1ae5e6f712591ba66bc2dd5e8a9f73b9d54/src/Models/UserPasswordReset.php#L246-L254
233,070
CottaCush/phalcon-user-auth
src/Models/UserPasswordReset.php
UserPasswordReset.expireToken
public function expireToken($token) { $tokenData = $this->getTokenData($token); if ($tokenData == false) { return false; } $tokenData->date_of_expiry = time() - 1; return $tokenData->save(); }
php
public function expireToken($token) { $tokenData = $this->getTokenData($token); if ($tokenData == false) { return false; } $tokenData->date_of_expiry = time() - 1; return $tokenData->save(); }
[ "public", "function", "expireToken", "(", "$", "token", ")", "{", "$", "tokenData", "=", "$", "this", "->", "getTokenData", "(", "$", "token", ")", ";", "if", "(", "$", "tokenData", "==", "false", ")", "{", "return", "false", ";", "}", "$", "tokenDat...
Expire a token @param string $token @return bool
[ "Expire", "a", "token" ]
89c8a1ae5e6f712591ba66bc2dd5e8a9f73b9d54
https://github.com/CottaCush/phalcon-user-auth/blob/89c8a1ae5e6f712591ba66bc2dd5e8a9f73b9d54/src/Models/UserPasswordReset.php#L261-L270
233,071
bav-php/bav
classes/configuration/ConfigurationRegistry.php
ConfigurationRegistry.classConstructor
public static function classConstructor() { $locator = new ConfigurationLocator(array( __DIR__ . self::BAV_PATH, self::INCLUDE_PATH )); $configuration = $locator->locate(); if ($configuration == null) { $configuration = new DefaultConfiguration(); } self::setConfiguration($configuration); }
php
public static function classConstructor() { $locator = new ConfigurationLocator(array( __DIR__ . self::BAV_PATH, self::INCLUDE_PATH )); $configuration = $locator->locate(); if ($configuration == null) { $configuration = new DefaultConfiguration(); } self::setConfiguration($configuration); }
[ "public", "static", "function", "classConstructor", "(", ")", "{", "$", "locator", "=", "new", "ConfigurationLocator", "(", "array", "(", "__DIR__", ".", "self", "::", "BAV_PATH", ",", "self", "::", "INCLUDE_PATH", ")", ")", ";", "$", "configuration", "=", ...
locate a configuration or register the default configuration. You may define the file bav/configuration.php. This file should return a Configuration object. @see DefaultConfiguration @throws ConfigurationException
[ "locate", "a", "configuration", "or", "register", "the", "default", "configuration", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/configuration/ConfigurationRegistry.php#L56-L68
233,072
silverstripe-archive/deploynaut
code/jobs/PingJob.php
PingJob.perform
public function perform() { echo "[-] PingJob starting" . PHP_EOL; $log = new DeploynautLogFile($this->args['logfile']); $DNProject = $this->DNData()->DNProjectList()->filter('Name', $this->args['projectName'])->First(); $DNEnvironment = $DNProject->Environments()->filter('Name', $this->args['environmentName'])->First(); $DNEnvironment->Backend()->ping($DNEnvironment, $log, $DNProject); }
php
public function perform() { echo "[-] PingJob starting" . PHP_EOL; $log = new DeploynautLogFile($this->args['logfile']); $DNProject = $this->DNData()->DNProjectList()->filter('Name', $this->args['projectName'])->First(); $DNEnvironment = $DNProject->Environments()->filter('Name', $this->args['environmentName'])->First(); $DNEnvironment->Backend()->ping($DNEnvironment, $log, $DNProject); }
[ "public", "function", "perform", "(", ")", "{", "echo", "\"[-] PingJob starting\"", ".", "PHP_EOL", ";", "$", "log", "=", "new", "DeploynautLogFile", "(", "$", "this", "->", "args", "[", "'logfile'", "]", ")", ";", "$", "DNProject", "=", "$", "this", "->...
Do the actual job by calling the appropiate backend
[ "Do", "the", "actual", "job", "by", "calling", "the", "appropiate", "backend" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/jobs/PingJob.php#L36-L42
233,073
ameliaikeda/backblaze
src/Client.php
Client.auth
protected function auth() { return Cache::remember('b2', 1320, function () { return $this->client->request('GET', 'https://api.backblaze.com/b2api/v1/b2_authorize_account', [ 'auth' => [$this->accountId, $this->applicationKey] ]); }); }
php
protected function auth() { return Cache::remember('b2', 1320, function () { return $this->client->request('GET', 'https://api.backblaze.com/b2api/v1/b2_authorize_account', [ 'auth' => [$this->accountId, $this->applicationKey] ]); }); }
[ "protected", "function", "auth", "(", ")", "{", "return", "Cache", "::", "remember", "(", "'b2'", ",", "1320", ",", "function", "(", ")", "{", "return", "$", "this", "->", "client", "->", "request", "(", "'GET'", ",", "'https://api.backblaze.com/b2api/v1/b2_...
Get an authorization token back from b2. @return array
[ "Get", "an", "authorization", "token", "back", "from", "b2", "." ]
72dd26a55549e3bfd7a551e019b9eefad7e50f5e
https://github.com/ameliaikeda/backblaze/blob/72dd26a55549e3bfd7a551e019b9eefad7e50f5e/src/Client.php#L39-L46
233,074
asinfotrack/yii2-toolbox
helpers/ImageFactory.php
ImageFactory.createInstance
public static function createInstance($path, $driver=self::DRIVER_GD) { //validate driver if (!in_array($driver, static::$ALL_DRIVERS)) { $msg = Yii::t('app', 'Invalid driver \'{driver}\'! Allowed drivers are: {drivers}', [ 'driver'=>$driver, 'drivers'=>implode(', ', static::$ALL_DRIVERS) ]); throw new InvalidCallException($msg); } //try to create instance if ($driver === self::DRIVER_GD && ServerConfig::extGdLoaded()) { return new ProgressiveImageGd($path); } else if ($driver === self::DRIVER_IMAGICK && ServerConfig::extImagickLoaded()) { return new ProgressiveImageImagick($path); } else { $msg = Yii::t('app', 'The requested driver is \'{driver}\' but the corresponding extension is not loaded', [ 'driver'=>$driver, ]); throw new InvalidConfigException($msg); } }
php
public static function createInstance($path, $driver=self::DRIVER_GD) { //validate driver if (!in_array($driver, static::$ALL_DRIVERS)) { $msg = Yii::t('app', 'Invalid driver \'{driver}\'! Allowed drivers are: {drivers}', [ 'driver'=>$driver, 'drivers'=>implode(', ', static::$ALL_DRIVERS) ]); throw new InvalidCallException($msg); } //try to create instance if ($driver === self::DRIVER_GD && ServerConfig::extGdLoaded()) { return new ProgressiveImageGd($path); } else if ($driver === self::DRIVER_IMAGICK && ServerConfig::extImagickLoaded()) { return new ProgressiveImageImagick($path); } else { $msg = Yii::t('app', 'The requested driver is \'{driver}\' but the corresponding extension is not loaded', [ 'driver'=>$driver, ]); throw new InvalidConfigException($msg); } }
[ "public", "static", "function", "createInstance", "(", "$", "path", ",", "$", "driver", "=", "self", "::", "DRIVER_GD", ")", "{", "//validate driver", "if", "(", "!", "in_array", "(", "$", "driver", ",", "static", "::", "$", "ALL_DRIVERS", ")", ")", "{",...
Creates an instance of the progressively encoded image driver desired @param string $path the path to the image @param string $driver the driver (defaults to GD, use class-constants) @return \asinfotrack\yii2\toolbox\components\image\ProgressiveImageGd|\asinfotrack\yii2\toolbox\components\image\ProgressiveImageImagick the instance created @throws \yii\base\InvalidCallException when called with an invalid driver @throws \yii\base\InvalidConfigException when necessary extension is not loaded
[ "Creates", "an", "instance", "of", "the", "progressively", "encoded", "image", "driver", "desired" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/ImageFactory.php#L44-L66
233,075
contao-community-alliance/event-dispatcher
src/EventDispatcherPopulator.php
EventDispatcherPopulator.populate
public function populate() { if ($this->configurator) { call_user_func($this->configurator); } $this->populateListeners(); $this->populateSubscribers(); }
php
public function populate() { if ($this->configurator) { call_user_func($this->configurator); } $this->populateListeners(); $this->populateSubscribers(); }
[ "public", "function", "populate", "(", ")", "{", "if", "(", "$", "this", "->", "configurator", ")", "{", "call_user_func", "(", "$", "this", "->", "configurator", ")", ";", "}", "$", "this", "->", "populateListeners", "(", ")", ";", "$", "this", "->", ...
Populate the event dispatcher. @return void
[ "Populate", "the", "event", "dispatcher", "." ]
1282b22fdbec4e458fc6204530ed36c3eebbe6c6
https://github.com/contao-community-alliance/event-dispatcher/blob/1282b22fdbec4e458fc6204530ed36c3eebbe6c6/src/EventDispatcherPopulator.php#L90-L98
233,076
contao-community-alliance/event-dispatcher
src/EventDispatcherPopulator.php
EventDispatcherPopulator.addListeners
private function addListeners(array $events) { foreach ($events as $eventName => $listeners) { foreach ($listeners as $listener) { if (is_array($listener) && count($listener) === 2 && is_int($listener[1])) { list($listener, $priority) = $listener; } else { $priority = 0; } $this->dispatcher->addListener($eventName, $listener, $priority); } } return $this; }
php
private function addListeners(array $events) { foreach ($events as $eventName => $listeners) { foreach ($listeners as $listener) { if (is_array($listener) && count($listener) === 2 && is_int($listener[1])) { list($listener, $priority) = $listener; } else { $priority = 0; } $this->dispatcher->addListener($eventName, $listener, $priority); } } return $this; }
[ "private", "function", "addListeners", "(", "array", "$", "events", ")", "{", "foreach", "(", "$", "events", "as", "$", "eventName", "=>", "$", "listeners", ")", "{", "foreach", "(", "$", "listeners", "as", "$", "listener", ")", "{", "if", "(", "is_arr...
Add listeners to the event dispatcher. @param array $events A collection of event names as keys and an array of listeners as values. @return static
[ "Add", "listeners", "to", "the", "event", "dispatcher", "." ]
1282b22fdbec4e458fc6204530ed36c3eebbe6c6
https://github.com/contao-community-alliance/event-dispatcher/blob/1282b22fdbec4e458fc6204530ed36c3eebbe6c6/src/EventDispatcherPopulator.php#L129-L143
233,077
contao-community-alliance/event-dispatcher
src/EventDispatcherPopulator.php
EventDispatcherPopulator.addSubscribers
private function addSubscribers(array $eventSubscribers) { foreach ($eventSubscribers as $eventSubscriber) { if (is_string($eventSubscriber)) { $eventSubscriber = new $eventSubscriber(); } elseif (is_callable($eventSubscriber)) { $eventSubscriber = call_user_func($eventSubscriber, $this->dispatcher); } $this->dispatcher->addSubscriber($eventSubscriber); } return $this; }
php
private function addSubscribers(array $eventSubscribers) { foreach ($eventSubscribers as $eventSubscriber) { if (is_string($eventSubscriber)) { $eventSubscriber = new $eventSubscriber(); } elseif (is_callable($eventSubscriber)) { $eventSubscriber = call_user_func($eventSubscriber, $this->dispatcher); } $this->dispatcher->addSubscriber($eventSubscriber); } return $this; }
[ "private", "function", "addSubscribers", "(", "array", "$", "eventSubscribers", ")", "{", "foreach", "(", "$", "eventSubscribers", "as", "$", "eventSubscriber", ")", "{", "if", "(", "is_string", "(", "$", "eventSubscriber", ")", ")", "{", "$", "eventSubscriber...
Add subscribers to the event dispatcher. @param array|string[]|\Closure[]|EventSubscriberInterface[] $eventSubscribers A collection of subscriber class names, factory functions or subscriber objects. @return static
[ "Add", "subscribers", "to", "the", "event", "dispatcher", "." ]
1282b22fdbec4e458fc6204530ed36c3eebbe6c6
https://github.com/contao-community-alliance/event-dispatcher/blob/1282b22fdbec4e458fc6204530ed36c3eebbe6c6/src/EventDispatcherPopulator.php#L176-L189
233,078
kuria/error
src/ErrorHandler.php
ErrorHandler.onError
function onError(int $code, string $message, ?string $file = null, ?int $line = null): bool { $this->lastError = error_get_last(); $this->currentErrorException = new ErrorException( $message, $code, ($code & error_reporting()) === 0, $file ?? __FILE__, $line ?? __LINE__ ); try { try { $this->emit(ErrorHandlerEvents::ERROR, $this->currentErrorException, $this->debug); } catch (\Throwable $e) { throw new ChainedException( 'Additional exception was thrown from an [error] event listener. See previous exceptions.', 0, Exception::joinChains($this->currentErrorException, $e) ); } // check suppression state if (!$this->currentErrorException->isSuppressed()) { throw $this->currentErrorException; } // suppressed error return true; } finally { $this->currentErrorException = null; } }
php
function onError(int $code, string $message, ?string $file = null, ?int $line = null): bool { $this->lastError = error_get_last(); $this->currentErrorException = new ErrorException( $message, $code, ($code & error_reporting()) === 0, $file ?? __FILE__, $line ?? __LINE__ ); try { try { $this->emit(ErrorHandlerEvents::ERROR, $this->currentErrorException, $this->debug); } catch (\Throwable $e) { throw new ChainedException( 'Additional exception was thrown from an [error] event listener. See previous exceptions.', 0, Exception::joinChains($this->currentErrorException, $e) ); } // check suppression state if (!$this->currentErrorException->isSuppressed()) { throw $this->currentErrorException; } // suppressed error return true; } finally { $this->currentErrorException = null; } }
[ "function", "onError", "(", "int", "$", "code", ",", "string", "$", "message", ",", "?", "string", "$", "file", "=", "null", ",", "?", "int", "$", "line", "=", "null", ")", ":", "bool", "{", "$", "this", "->", "lastError", "=", "error_get_last", "(...
Handle a PHP error @throws ErrorException if the error isn't suppressed @throws ChainedException if an event listener throws an exception
[ "Handle", "a", "PHP", "error" ]
e1426256569e9e9253a940a3cec854d550b257eb
https://github.com/kuria/error/blob/e1426256569e9e9253a940a3cec854d550b257eb/src/ErrorHandler.php#L152-L184
233,079
kuria/error
src/ErrorHandler.php
ErrorHandler.onUncaughtException
function onUncaughtException(\Throwable $exception): void { try { // handle the exception try { $this->emit(ErrorHandlerEvents::EXCEPTION, $exception, $this->debug); } catch (\Throwable $e) { $exception = new ChainedException( 'Additional exception was thrown from an [exception] event listener. See previous exceptions.', 0, Exception::joinChains($exception, $e) ); } $this->invokeErrorScreen($exception); return; } catch (\Throwable $e) { $exception = new ChainedException( sprintf('Additional exception was thrown while trying to invoke %s. See previous exceptions.', get_class($this->errorScreen)), 0, Exception::joinChains($exception, $e) ); $this->emit(ErrorHandlerEvents::FAILURE, $exception, $this->debug); } // unhandled exception if ($this->debug && $this->printUnhandledExceptionInDebug) { echo Exception::render($exception, true, true); } }
php
function onUncaughtException(\Throwable $exception): void { try { // handle the exception try { $this->emit(ErrorHandlerEvents::EXCEPTION, $exception, $this->debug); } catch (\Throwable $e) { $exception = new ChainedException( 'Additional exception was thrown from an [exception] event listener. See previous exceptions.', 0, Exception::joinChains($exception, $e) ); } $this->invokeErrorScreen($exception); return; } catch (\Throwable $e) { $exception = new ChainedException( sprintf('Additional exception was thrown while trying to invoke %s. See previous exceptions.', get_class($this->errorScreen)), 0, Exception::joinChains($exception, $e) ); $this->emit(ErrorHandlerEvents::FAILURE, $exception, $this->debug); } // unhandled exception if ($this->debug && $this->printUnhandledExceptionInDebug) { echo Exception::render($exception, true, true); } }
[ "function", "onUncaughtException", "(", "\\", "Throwable", "$", "exception", ")", ":", "void", "{", "try", "{", "// handle the exception", "try", "{", "$", "this", "->", "emit", "(", "ErrorHandlerEvents", "::", "EXCEPTION", ",", "$", "exception", ",", "$", "...
Handle an uncaught exception
[ "Handle", "an", "uncaught", "exception" ]
e1426256569e9e9253a940a3cec854d550b257eb
https://github.com/kuria/error/blob/e1426256569e9e9253a940a3cec854d550b257eb/src/ErrorHandler.php#L189-L220
233,080
kuria/error
src/ErrorHandler.php
ErrorHandler.onShutdown
function onShutdown(): void { // free the reserved memory $this->reservedMemory = null; if ( $this->isActive() && ($error = error_get_last()) !== null && $error !== $this->lastError ) { $this->lastError = null; // fix working directory if ($this->workingDirectory !== null) { chdir($this->workingDirectory); } // determine exception class if ($this->isOutOfMemoryError($error)) { gc_collect_cycles(); $exceptionClass = OutOfMemoryException::class; } else { $exceptionClass = FatalErrorException::class; } // handle $this->onUncaughtException( new $exceptionClass( $error['message'], 0, $error['type'], $error['file'], $error['line'], $this->currentErrorException // use current error exception if a fatal error happens during onError() ) ); } }
php
function onShutdown(): void { // free the reserved memory $this->reservedMemory = null; if ( $this->isActive() && ($error = error_get_last()) !== null && $error !== $this->lastError ) { $this->lastError = null; // fix working directory if ($this->workingDirectory !== null) { chdir($this->workingDirectory); } // determine exception class if ($this->isOutOfMemoryError($error)) { gc_collect_cycles(); $exceptionClass = OutOfMemoryException::class; } else { $exceptionClass = FatalErrorException::class; } // handle $this->onUncaughtException( new $exceptionClass( $error['message'], 0, $error['type'], $error['file'], $error['line'], $this->currentErrorException // use current error exception if a fatal error happens during onError() ) ); } }
[ "function", "onShutdown", "(", ")", ":", "void", "{", "// free the reserved memory", "$", "this", "->", "reservedMemory", "=", "null", ";", "if", "(", "$", "this", "->", "isActive", "(", ")", "&&", "(", "$", "error", "=", "error_get_last", "(", ")", ")",...
Check for a fatal error on shutdown @internal
[ "Check", "for", "a", "fatal", "error", "on", "shutdown" ]
e1426256569e9e9253a940a3cec854d550b257eb
https://github.com/kuria/error/blob/e1426256569e9e9253a940a3cec854d550b257eb/src/ErrorHandler.php#L227-L264
233,081
kuria/error
src/ErrorHandler.php
ErrorHandler.isActive
protected function isActive(): bool { if ($this->currentErrorException !== null) { return true; } // ugly, but there is no get_error_handler() $currentErrorHandler = set_error_handler(function () {}); restore_error_handler(); return is_array($currentErrorHandler) && $currentErrorHandler[0] === $this; }
php
protected function isActive(): bool { if ($this->currentErrorException !== null) { return true; } // ugly, but there is no get_error_handler() $currentErrorHandler = set_error_handler(function () {}); restore_error_handler(); return is_array($currentErrorHandler) && $currentErrorHandler[0] === $this; }
[ "protected", "function", "isActive", "(", ")", ":", "bool", "{", "if", "(", "$", "this", "->", "currentErrorException", "!==", "null", ")", "{", "return", "true", ";", "}", "// ugly, but there is no get_error_handler()", "$", "currentErrorHandler", "=", "set_error...
See if this is the current error handler
[ "See", "if", "this", "is", "the", "current", "error", "handler" ]
e1426256569e9e9253a940a3cec854d550b257eb
https://github.com/kuria/error/blob/e1426256569e9e9253a940a3cec854d550b257eb/src/ErrorHandler.php#L310-L321
233,082
asinfotrack/yii2-toolbox
helpers/ColorHelper.php
ColorHelper.calculateLuminance
public static function calculateLuminance($color) { $rgb = static::getMixedColorAsRgb($color); if ($rgb === false) return false; return 0.2126 * $rgb[0] + 0.7152 * $rgb[1] + 0.0722 * $rgb[2]; }
php
public static function calculateLuminance($color) { $rgb = static::getMixedColorAsRgb($color); if ($rgb === false) return false; return 0.2126 * $rgb[0] + 0.7152 * $rgb[1] + 0.0722 * $rgb[2]; }
[ "public", "static", "function", "calculateLuminance", "(", "$", "color", ")", "{", "$", "rgb", "=", "static", "::", "getMixedColorAsRgb", "(", "$", "color", ")", ";", "if", "(", "$", "rgb", "===", "false", ")", "return", "false", ";", "return", "0.2126",...
Calculate the luminance for a color @param integer[]|string $color either a hex-string or a rgb-array @return float the luminance value
[ "Calculate", "the", "luminance", "for", "a", "color" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/ColorHelper.php#L31-L37
233,083
asinfotrack/yii2-toolbox
helpers/ColorHelper.php
ColorHelper.darken
public static function darken($color, $percent) { $rgb = static::getMixedColorAsRgb($color); if ($rgb === false) return false; if (!static::validatePercent($percent)) return false; if (is_array($percent)) { foreach ($percent as &$p) $p = abs($p) * -1; } else { $percent = abs($percent) * -1; } return static::makeSameAsInput(static::modifyColor($rgb, $percent), $color); }
php
public static function darken($color, $percent) { $rgb = static::getMixedColorAsRgb($color); if ($rgb === false) return false; if (!static::validatePercent($percent)) return false; if (is_array($percent)) { foreach ($percent as &$p) $p = abs($p) * -1; } else { $percent = abs($percent) * -1; } return static::makeSameAsInput(static::modifyColor($rgb, $percent), $color); }
[ "public", "static", "function", "darken", "(", "$", "color", ",", "$", "percent", ")", "{", "$", "rgb", "=", "static", "::", "getMixedColorAsRgb", "(", "$", "color", ")", ";", "if", "(", "$", "rgb", "===", "false", ")", "return", "false", ";", "if", ...
Darkens a color by a certain amount of percent. The input can be both a hex-string or a rgb-array. The output will be in the exact same format @param integer[]|string $color either a hex-string or a rgb-array @param float|float[] $percent percentage to lighten the color, either one value or three individual values @return integer[]|string|boolean false if invalid color, otherwise darkened color in the same format as the input was
[ "Darkens", "a", "color", "by", "a", "certain", "amount", "of", "percent", ".", "The", "input", "can", "be", "both", "a", "hex", "-", "string", "or", "a", "rgb", "-", "array", ".", "The", "output", "will", "be", "in", "the", "exact", "same", "format" ...
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/ColorHelper.php#L105-L118
233,084
asinfotrack/yii2-toolbox
helpers/ColorHelper.php
ColorHelper.decToHex
public static function decToHex($rgbArr, $withHash=true, $preferThreeChars=true) { if (!static::validateRgbColor($rgbArr)) return false; //get parts $hex = ''; foreach ($rgbArr as $color) { $hex .= str_pad(dechex($color), 2, 0, STR_PAD_LEFT); } //three chars if desired and possible if ($preferThreeChars && $hex[0] == $hex[1] && $hex[2] == $hex[3] && $hex[4] == $hex[5]) { $hex = $hex[0] . $hex[2] . $hex[4]; } return ($withHash ? '#' : '') . $hex; }
php
public static function decToHex($rgbArr, $withHash=true, $preferThreeChars=true) { if (!static::validateRgbColor($rgbArr)) return false; //get parts $hex = ''; foreach ($rgbArr as $color) { $hex .= str_pad(dechex($color), 2, 0, STR_PAD_LEFT); } //three chars if desired and possible if ($preferThreeChars && $hex[0] == $hex[1] && $hex[2] == $hex[3] && $hex[4] == $hex[5]) { $hex = $hex[0] . $hex[2] . $hex[4]; } return ($withHash ? '#' : '') . $hex; }
[ "public", "static", "function", "decToHex", "(", "$", "rgbArr", ",", "$", "withHash", "=", "true", ",", "$", "preferThreeChars", "=", "true", ")", "{", "if", "(", "!", "static", "::", "validateRgbColor", "(", "$", "rgbArr", ")", ")", "return", "false", ...
Converts an array containing rgb-color-codes into its hex-representation. The array needs to consist of three integers containing the three color values. @param integer[] $rgbArr array containing r, g and b as integers between 0 and 255 @param boolean $withHash if set to true, the hex-value will be preceded by a hash ('#') @param boolean $preferThreeChars if set to true the three char representation is returned if possible @return boolean|string hex-string or false if the provided rgb-array was invalid
[ "Converts", "an", "array", "containing", "rgb", "-", "color", "-", "codes", "into", "its", "hex", "-", "representation", ".", "The", "array", "needs", "to", "consist", "of", "three", "integers", "containing", "the", "three", "color", "values", "." ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/ColorHelper.php#L158-L174
233,085
asinfotrack/yii2-toolbox
helpers/ColorHelper.php
ColorHelper.hexToRgb
public static function hexToRgb($hexStr) { if (!static::validateHexString($hexStr)) return false; $hexStr = ltrim(trim($hexStr), '#'); //create parts and make it six digit if it isnt already $parts = str_split($hexStr, strlen($hexStr) == 3 ? 1 : 2); if (strlen($hexStr) == 3) { foreach ($parts as $i=>$p) { $parts[$i] = str_repeat($p, 2); } } return [hexdec($parts[0]), hexdec($parts[1]), hexdec($parts[2])]; }
php
public static function hexToRgb($hexStr) { if (!static::validateHexString($hexStr)) return false; $hexStr = ltrim(trim($hexStr), '#'); //create parts and make it six digit if it isnt already $parts = str_split($hexStr, strlen($hexStr) == 3 ? 1 : 2); if (strlen($hexStr) == 3) { foreach ($parts as $i=>$p) { $parts[$i] = str_repeat($p, 2); } } return [hexdec($parts[0]), hexdec($parts[1]), hexdec($parts[2])]; }
[ "public", "static", "function", "hexToRgb", "(", "$", "hexStr", ")", "{", "if", "(", "!", "static", "::", "validateHexString", "(", "$", "hexStr", ")", ")", "return", "false", ";", "$", "hexStr", "=", "ltrim", "(", "trim", "(", "$", "hexStr", ")", ",...
Converts a hex-color into an array containing the three decimal representation values of r, g, and b @param string $hexStr hex-color with either three or six chars, hash is optional @return boolean|integer[] array containing dec values for rgb or false if string is invalid
[ "Converts", "a", "hex", "-", "color", "into", "an", "array", "containing", "the", "three", "decimal", "representation", "values", "of", "r", "g", "and", "b" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/ColorHelper.php#L184-L198
233,086
asinfotrack/yii2-toolbox
helpers/ColorHelper.php
ColorHelper.validateRgbColor
public static function validateRgbColor($rgbArr) { if (count($rgbArr) != 3) return false; foreach ($rgbArr as $val) { if ($val < 0 || $val > 255) return false; } return true; }
php
public static function validateRgbColor($rgbArr) { if (count($rgbArr) != 3) return false; foreach ($rgbArr as $val) { if ($val < 0 || $val > 255) return false; } return true; }
[ "public", "static", "function", "validateRgbColor", "(", "$", "rgbArr", ")", "{", "if", "(", "count", "(", "$", "rgbArr", ")", "!=", "3", ")", "return", "false", ";", "foreach", "(", "$", "rgbArr", "as", "$", "val", ")", "{", "if", "(", "$", "val",...
Validates an array containing rgb-colors. The array needs to contain three integer-values, each between 0 and 255 to be valid @param integer[] $rgbArr the rgb-values @return boolean true if ok, otherwise false
[ "Validates", "an", "array", "containing", "rgb", "-", "colors", ".", "The", "array", "needs", "to", "contain", "three", "integer", "-", "values", "each", "between", "0", "and", "255", "to", "be", "valid" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/ColorHelper.php#L220-L227
233,087
asinfotrack/yii2-toolbox
helpers/ColorHelper.php
ColorHelper.modifyColor
protected static function modifyColor($rgbArr, $percent) { if (is_array($percent)) { foreach ($rgbArr as $i=>&$c) { $multiplier = $percent[$i] > 0 ? 1 + $percent[$i] / 100 : 1 - $percent[$i] / 100; $c = intval(round($c * $multiplier)); if ($c > 255) $c = 255; if ($c < 0) $c = 0; } } else { $multiplier = $percent > 0 ? 1 + $percent / 100 : 1 - $percent / 100; foreach ($rgbArr as &$c) { $c = intval(round($c * $multiplier)); if ($c > 255) $c = 255; if ($c < 0) $c = 0; } } return $rgbArr; }
php
protected static function modifyColor($rgbArr, $percent) { if (is_array($percent)) { foreach ($rgbArr as $i=>&$c) { $multiplier = $percent[$i] > 0 ? 1 + $percent[$i] / 100 : 1 - $percent[$i] / 100; $c = intval(round($c * $multiplier)); if ($c > 255) $c = 255; if ($c < 0) $c = 0; } } else { $multiplier = $percent > 0 ? 1 + $percent / 100 : 1 - $percent / 100; foreach ($rgbArr as &$c) { $c = intval(round($c * $multiplier)); if ($c > 255) $c = 255; if ($c < 0) $c = 0; } } return $rgbArr; }
[ "protected", "static", "function", "modifyColor", "(", "$", "rgbArr", ",", "$", "percent", ")", "{", "if", "(", "is_array", "(", "$", "percent", ")", ")", "{", "foreach", "(", "$", "rgbArr", "as", "$", "i", "=>", "&", "$", "c", ")", "{", "$", "mu...
Internal modification function for colors.This method DOES NOT validate the input so make sure this happened before @param integer[] $rgbArr array containing rgb-values @param float|float[] $percent @return integer[] modified color as rgb-array
[ "Internal", "modification", "function", "for", "colors", ".", "This", "method", "DOES", "NOT", "validate", "the", "input", "so", "make", "sure", "this", "happened", "before" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/ColorHelper.php#L248-L267
233,088
asinfotrack/yii2-toolbox
helpers/ColorHelper.php
ColorHelper.areSameColors
protected function areSameColors($colorOne, $colorTwo) { $rgbOne = static::getMixedColorAsRgb($colorOne); $rgbTwo = static::getMixedColorAsRgb($colorTwo); for ($i=0; $i<3; $i++) { if ($rgbOne[$i] != $rgbTwo[$i]) return false; } return true; }
php
protected function areSameColors($colorOne, $colorTwo) { $rgbOne = static::getMixedColorAsRgb($colorOne); $rgbTwo = static::getMixedColorAsRgb($colorTwo); for ($i=0; $i<3; $i++) { if ($rgbOne[$i] != $rgbTwo[$i]) return false; } return true; }
[ "protected", "function", "areSameColors", "(", "$", "colorOne", ",", "$", "colorTwo", ")", "{", "$", "rgbOne", "=", "static", "::", "getMixedColorAsRgb", "(", "$", "colorOne", ")", ";", "$", "rgbTwo", "=", "static", "::", "getMixedColorAsRgb", "(", "$", "c...
Compares two colors if they are the same. This method DOES NOT validate the input so make sure this happened before @param integer[]|string $colorOne either a hex-string or a rgb-array @param integer[]|string $colorTwo either a hex-string or a rgb-array @return boolean true if they are the same
[ "Compares", "two", "colors", "if", "they", "are", "the", "same", ".", "This", "method", "DOES", "NOT", "validate", "the", "input", "so", "make", "sure", "this", "happened", "before" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/ColorHelper.php#L277-L286
233,089
asinfotrack/yii2-toolbox
helpers/ColorHelper.php
ColorHelper.makeSameAsInput
protected function makeSameAsInput($rgbArr, $input) { if (is_array($input)) { return $rgbArr; } else { return static::decToHex($rgbArr, $input[0]=='#', strlen($input) == ($input[0]=='#' ? 4 : 3)); } }
php
protected function makeSameAsInput($rgbArr, $input) { if (is_array($input)) { return $rgbArr; } else { return static::decToHex($rgbArr, $input[0]=='#', strlen($input) == ($input[0]=='#' ? 4 : 3)); } }
[ "protected", "function", "makeSameAsInput", "(", "$", "rgbArr", ",", "$", "input", ")", "{", "if", "(", "is_array", "(", "$", "input", ")", ")", "{", "return", "$", "rgbArr", ";", "}", "else", "{", "return", "static", "::", "decToHex", "(", "$", "rgb...
Converts an rgb-array into the same format as the input was. @param integer[] $rgbArr array containing rgb-values @param integer[]|string $input either rgb-array or hex-string @return integer[]|string color in the same format as the input was
[ "Converts", "an", "rgb", "-", "array", "into", "the", "same", "format", "as", "the", "input", "was", "." ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/ColorHelper.php#L295-L302
233,090
asinfotrack/yii2-toolbox
helpers/ColorHelper.php
ColorHelper.getMixedColorAsRgb
protected static function getMixedColorAsRgb($color) { if (is_array($color)) { if (!static::validateRgbColor($color)) return false; return $color; } else { return static::hexToRgb($color); } }
php
protected static function getMixedColorAsRgb($color) { if (is_array($color)) { if (!static::validateRgbColor($color)) return false; return $color; } else { return static::hexToRgb($color); } }
[ "protected", "static", "function", "getMixedColorAsRgb", "(", "$", "color", ")", "{", "if", "(", "is_array", "(", "$", "color", ")", ")", "{", "if", "(", "!", "static", "::", "validateRgbColor", "(", "$", "color", ")", ")", "return", "false", ";", "ret...
Takes either an rgb-array or a hex-string as its input and validates it and returns an rgb-array @param string|integer[] $color either hex-string or rgb-array @return boolean|integer[] either an rgb-array or false if color is invalid
[ "Takes", "either", "an", "rgb", "-", "array", "or", "a", "hex", "-", "string", "as", "its", "input", "and", "validates", "it", "and", "returns", "an", "rgb", "-", "array" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/ColorHelper.php#L311-L319
233,091
tedslittlerobot/html-table-builder
src/TableRenderer.php
TableRenderer.getAttributesForElement
public function getAttributesForElement(Element $element) : string { $attributes = []; if ($this->usesTrait($element, Classable::class)) { $attributes[] = $element->renderClassAttribute(); } if ($this->usesTrait($element, Spannable::class)) { $attributes[] = $element->renderSpanAttribute(); } if ($this->usesTrait($element, Attributable::class)) { $attributes[] = $element->renderAttributes(); } $attributes = array_filter($attributes); return $attributes ? ' ' . implode(' ', $attributes) : ''; }
php
public function getAttributesForElement(Element $element) : string { $attributes = []; if ($this->usesTrait($element, Classable::class)) { $attributes[] = $element->renderClassAttribute(); } if ($this->usesTrait($element, Spannable::class)) { $attributes[] = $element->renderSpanAttribute(); } if ($this->usesTrait($element, Attributable::class)) { $attributes[] = $element->renderAttributes(); } $attributes = array_filter($attributes); return $attributes ? ' ' . implode(' ', $attributes) : ''; }
[ "public", "function", "getAttributesForElement", "(", "Element", "$", "element", ")", ":", "string", "{", "$", "attributes", "=", "[", "]", ";", "if", "(", "$", "this", "->", "usesTrait", "(", "$", "element", ",", "Classable", "::", "class", ")", ")", ...
Get the attribute string for the element @param Element $element @return string
[ "Get", "the", "attribute", "string", "for", "the", "element" ]
12597f8c44dde9f002c74b0aeadefec2bdb2eafa
https://github.com/tedslittlerobot/html-table-builder/blob/12597f8c44dde9f002c74b0aeadefec2bdb2eafa/src/TableRenderer.php#L61-L80
233,092
tedslittlerobot/html-table-builder
src/TableRenderer.php
TableRenderer.getContentForElement
public function getContentForElement(Element $element) : string { if ($element instanceof HasChildren && $element instanceof HasContent) { throw new InvalidArgumentException('An element can only implement one of HasChildren and HasContent'); } if ($element instanceof HasChildren) { $renderedChildren = array_map(function(Element $element) { return $this->renderElement($element); }, $element->getChildren()); return implode('', $renderedChildren); } if ($element instanceof HasContent) { return $element->getContent(); } return ''; }
php
public function getContentForElement(Element $element) : string { if ($element instanceof HasChildren && $element instanceof HasContent) { throw new InvalidArgumentException('An element can only implement one of HasChildren and HasContent'); } if ($element instanceof HasChildren) { $renderedChildren = array_map(function(Element $element) { return $this->renderElement($element); }, $element->getChildren()); return implode('', $renderedChildren); } if ($element instanceof HasContent) { return $element->getContent(); } return ''; }
[ "public", "function", "getContentForElement", "(", "Element", "$", "element", ")", ":", "string", "{", "if", "(", "$", "element", "instanceof", "HasChildren", "&&", "$", "element", "instanceof", "HasContent", ")", "{", "throw", "new", "InvalidArgumentException", ...
Get the content for the element @param Element $element @return string
[ "Get", "the", "content", "for", "the", "element" ]
12597f8c44dde9f002c74b0aeadefec2bdb2eafa
https://github.com/tedslittlerobot/html-table-builder/blob/12597f8c44dde9f002c74b0aeadefec2bdb2eafa/src/TableRenderer.php#L88-L107
233,093
tedslittlerobot/html-table-builder
src/TableRenderer.php
TableRenderer.indent
public function indent(int $depth, string $content) : string { if (!$this->pretty) { return $content; } return PHP_EOL . str_repeat(' ', $this->depth) . $content; }
php
public function indent(int $depth, string $content) : string { if (!$this->pretty) { return $content; } return PHP_EOL . str_repeat(' ', $this->depth) . $content; }
[ "public", "function", "indent", "(", "int", "$", "depth", ",", "string", "$", "content", ")", ":", "string", "{", "if", "(", "!", "$", "this", "->", "pretty", ")", "{", "return", "$", "content", ";", "}", "return", "PHP_EOL", ".", "str_repeat", "(", ...
Get the indentation for the current level @return string
[ "Get", "the", "indentation", "for", "the", "current", "level" ]
12597f8c44dde9f002c74b0aeadefec2bdb2eafa
https://github.com/tedslittlerobot/html-table-builder/blob/12597f8c44dde9f002c74b0aeadefec2bdb2eafa/src/TableRenderer.php#L114-L121
233,094
dmitriybelyy/yii2-cassandra-cql
phpcassa/Batch/AbstractMutator.php
AbstractMutator.send
public function send($consistency_level=null) { if ($consistency_level === null) $wcl = $this->cl; else $wcl = $consistency_level; $mutations = array(); foreach ($this->buffer as $mut_set) { list($key, $cf, $cols) = $mut_set; if (isset($mutations[$key])) { $key_muts = $mutations[$key]; } else { $key_muts = array(); } if (isset($key_muts[$cf])) { $cf_muts = $key_muts[$cf]; } else { $cf_muts = array(); } $cf_muts = array_merge($cf_muts, $cols); $key_muts[$cf] = $cf_muts; $mutations[$key] = $key_muts; } if (!empty($mutations)) { $this->pool->call('batch_mutate', $mutations, $wcl); } $this->buffer = array(); }
php
public function send($consistency_level=null) { if ($consistency_level === null) $wcl = $this->cl; else $wcl = $consistency_level; $mutations = array(); foreach ($this->buffer as $mut_set) { list($key, $cf, $cols) = $mut_set; if (isset($mutations[$key])) { $key_muts = $mutations[$key]; } else { $key_muts = array(); } if (isset($key_muts[$cf])) { $cf_muts = $key_muts[$cf]; } else { $cf_muts = array(); } $cf_muts = array_merge($cf_muts, $cols); $key_muts[$cf] = $cf_muts; $mutations[$key] = $key_muts; } if (!empty($mutations)) { $this->pool->call('batch_mutate', $mutations, $wcl); } $this->buffer = array(); }
[ "public", "function", "send", "(", "$", "consistency_level", "=", "null", ")", "{", "if", "(", "$", "consistency_level", "===", "null", ")", "$", "wcl", "=", "$", "this", "->", "cl", ";", "else", "$", "wcl", "=", "$", "consistency_level", ";", "$", "...
Send all buffered mutations. If an error occurs, the buffer will be preserverd, allowing you to attempt to call send() again later or take other recovery actions. @param cassandra\ConsistencyLevel $consistency_level optional override for the mutator's default consistency level
[ "Send", "all", "buffered", "mutations", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/Batch/AbstractMutator.php#L28-L59
233,095
laravel-notification-channels/hipchat
src/Exceptions/CouldNotSendNotification.php
CouldNotSendNotification.hipChatRespondedWithAnError
public static function hipChatRespondedWithAnError(ClientException $exception) { return new static(sprintf( 'HipChat responded with an error %s - %s', $exception->getResponse()->getStatusCode(), $exception->getResponse()->getBody() )); }
php
public static function hipChatRespondedWithAnError(ClientException $exception) { return new static(sprintf( 'HipChat responded with an error %s - %s', $exception->getResponse()->getStatusCode(), $exception->getResponse()->getBody() )); }
[ "public", "static", "function", "hipChatRespondedWithAnError", "(", "ClientException", "$", "exception", ")", "{", "return", "new", "static", "(", "sprintf", "(", "'HipChat responded with an error %s - %s'", ",", "$", "exception", "->", "getResponse", "(", ")", "->", ...
Thrown when there's a bad request from the HttpClient. @param \GuzzleHttp\Exception\ClientException $exception @return static
[ "Thrown", "when", "there", "s", "a", "bad", "request", "from", "the", "HttpClient", "." ]
c24bca85f7cf9f6804635aa206c961783e22e888
https://github.com/laravel-notification-channels/hipchat/blob/c24bca85f7cf9f6804635aa206c961783e22e888/src/Exceptions/CouldNotSendNotification.php#L17-L24
233,096
laravel-notification-channels/hipchat
src/HipChat.php
HipChat.shareFile
public function shareFile($to, $file) { $parts[] = [ 'headers' => [ 'Content-Type' => $file['file_type'] ?: 'application/octet-stream', ], 'name' => 'file', 'contents' => stream_for($file['content']), 'filename' => $file['filename'] ?: 'untitled', ]; if (! str_empty($file['message'])) { $parts[] = [ 'headers' => [ 'Content-Type' => 'application/json', ], 'name' => 'metadata', 'contents' => json_encode(['message' => $file['message']]), ]; } $url = $this->url.'/v2/room/'.urlencode($to).'/share/file'; return $this->postMultipartRelated($url, [ 'headers' => $this->getHeaders(), 'multipart' => $parts, ]); }
php
public function shareFile($to, $file) { $parts[] = [ 'headers' => [ 'Content-Type' => $file['file_type'] ?: 'application/octet-stream', ], 'name' => 'file', 'contents' => stream_for($file['content']), 'filename' => $file['filename'] ?: 'untitled', ]; if (! str_empty($file['message'])) { $parts[] = [ 'headers' => [ 'Content-Type' => 'application/json', ], 'name' => 'metadata', 'contents' => json_encode(['message' => $file['message']]), ]; } $url = $this->url.'/v2/room/'.urlencode($to).'/share/file'; return $this->postMultipartRelated($url, [ 'headers' => $this->getHeaders(), 'multipart' => $parts, ]); }
[ "public", "function", "shareFile", "(", "$", "to", ",", "$", "file", ")", "{", "$", "parts", "[", "]", "=", "[", "'headers'", "=>", "[", "'Content-Type'", "=>", "$", "file", "[", "'file_type'", "]", "?", ":", "'application/octet-stream'", ",", "]", ","...
Share a file. @param string|int $to @param array $file @return \Psr\Http\Message\ResponseInterface
[ "Share", "a", "file", "." ]
c24bca85f7cf9f6804635aa206c961783e22e888
https://github.com/laravel-notification-channels/hipchat/blob/c24bca85f7cf9f6804635aa206c961783e22e888/src/HipChat.php#L92-L119
233,097
mcustiel/php-simple-request
src/Strategies/Properties/SimplePropertyParser.php
SimplePropertyParser.validate
protected function validate($value) { foreach ($this->validators as $validator) { if (!$validator->validate($value)) { throw new InvalidValueException( "Field {$this->name}, was set with invalid value: " . var_export($value, true) ); } } }
php
protected function validate($value) { foreach ($this->validators as $validator) { if (!$validator->validate($value)) { throw new InvalidValueException( "Field {$this->name}, was set with invalid value: " . var_export($value, true) ); } } }
[ "protected", "function", "validate", "(", "$", "value", ")", "{", "foreach", "(", "$", "this", "->", "validators", "as", "$", "validator", ")", "{", "if", "(", "!", "$", "validator", "->", "validate", "(", "$", "value", ")", ")", "{", "throw", "new",...
Checks the value against all validators. @param mixed $value @throws \Mcustiel\SimpleRequest\Exception\InvalidValueException
[ "Checks", "the", "value", "against", "all", "validators", "." ]
4d0fc06092ccdff3ea488c67b394225c7243428f
https://github.com/mcustiel/php-simple-request/blob/4d0fc06092ccdff3ea488c67b394225c7243428f/src/Strategies/Properties/SimplePropertyParser.php#L87-L96
233,098
bav-php/bav
classes/validator/validators/ValidatorA4.php
ValidatorA4.useValidator
protected function useValidator(Validator $validator) { if (substr($this->account, 2, 2) == '99') { return $validator === $this->validators[2] || $validator === $this->validators[3]; } else { return $validator !== $this->validators[2]; } }
php
protected function useValidator(Validator $validator) { if (substr($this->account, 2, 2) == '99') { return $validator === $this->validators[2] || $validator === $this->validators[3]; } else { return $validator !== $this->validators[2]; } }
[ "protected", "function", "useValidator", "(", "Validator", "$", "validator", ")", "{", "if", "(", "substr", "(", "$", "this", "->", "account", ",", "2", ",", "2", ")", "==", "'99'", ")", "{", "return", "$", "validator", "===", "$", "this", "->", "val...
Decide if you really want to use this validator @return bool
[ "Decide", "if", "you", "really", "want", "to", "use", "this", "validator" ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/validator/validators/ValidatorA4.php#L49-L59
233,099
bav-php/bav
classes/configuration/ConfigurationLocator.php
ConfigurationLocator.locate
public function locate() { foreach ($this->paths as $path) { $resolvedPath = stream_resolve_include_path($path); if (! $resolvedPath) { continue; } $configuration = require $resolvedPath; if (! $configuration instanceof Configuration) { throw new ConfigurationException( "$resolvedPath must return a malkusch\\bav\\Configuration object." ); } return $configuration; } return null; }
php
public function locate() { foreach ($this->paths as $path) { $resolvedPath = stream_resolve_include_path($path); if (! $resolvedPath) { continue; } $configuration = require $resolvedPath; if (! $configuration instanceof Configuration) { throw new ConfigurationException( "$resolvedPath must return a malkusch\\bav\\Configuration object." ); } return $configuration; } return null; }
[ "public", "function", "locate", "(", ")", "{", "foreach", "(", "$", "this", "->", "paths", "as", "$", "path", ")", "{", "$", "resolvedPath", "=", "stream_resolve_include_path", "(", "$", "path", ")", ";", "if", "(", "!", "$", "resolvedPath", ")", "{", ...
Locates a configuration. @return Configuration|null @throws ConfigurationException
[ "Locates", "a", "configuration", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/configuration/ConfigurationLocator.php#L39-L58