repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.init | public function init()
{
parent::init();
Requirements::add_i18n_javascript('silverstripe/asset-admin:client/lang', false, true);
Requirements::javascript('silverstripe/asset-admin:client/dist/js/bundle.js');
Requirements::css('silverstripe/asset-admin:client/dist/styles/bundle.css');
CMSBatchActionHandler::register('delete', DeleteAssets::class, Folder::class);
} | php | public function init()
{
parent::init();
Requirements::add_i18n_javascript('silverstripe/asset-admin:client/lang', false, true);
Requirements::javascript('silverstripe/asset-admin:client/dist/js/bundle.js');
Requirements::css('silverstripe/asset-admin:client/dist/styles/bundle.css');
CMSBatchActionHandler::register('delete', DeleteAssets::class, Folder::class);
} | [
"public",
"function",
"init",
"(",
")",
"{",
"parent",
"::",
"init",
"(",
")",
";",
"Requirements",
"::",
"add_i18n_javascript",
"(",
"'silverstripe/asset-admin:client/lang'",
",",
"false",
",",
"true",
")",
";",
"Requirements",
"::",
"javascript",
"(",
"'silver... | Set up the controller | [
"Set",
"up",
"the",
"controller"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L183-L192 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.apiUploadFile | public function apiUploadFile(HTTPRequest $request)
{
$data = $request->postVars();
// When updating files, replace on conflict
$upload = $this->getUpload();
$upload->setReplaceFile(true);
// CSRF check
$token = SecurityToken::inst();
if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) {
$this->jsonError(400);
return null;
}
$tmpFile = $data['Upload'];
if (empty($data['ID']) || empty($tmpFile['name']) || !array_key_exists('Name', $data)) {
$this->jsonError(400, _t(__CLASS__.'.INVALID_REQUEST', 'Invalid request'));
return null;
}
// Check parent record
/** @var File $file */
$file = File::get()->byID($data['ID']);
if (!$file) {
$this->jsonError(404, _t(__CLASS__.'.FILE_NOT_FOUND', 'File not found'));
return null;
}
$folder = $file->ParentID ? $file->Parent()->getFilename() : '/';
// If extension is the same, attempt to re-use existing name
if (File::get_file_extension($tmpFile['name']) === File::get_file_extension($data['Name'])) {
$tmpFile['name'] = $data['Name'];
} else {
// If we are allowing this upload to rename the underlying record,
// do a uniqueness check.
$renamer = $this->getNameGenerator($tmpFile['name']);
foreach ($renamer as $name) {
$filename = File::join_paths($folder, $name);
if (!File::find($filename)) {
$tmpFile['name'] = $name;
break;
}
}
}
if (!$upload->validate($tmpFile)) {
$errors = $upload->getErrors();
$message = array_shift($errors);
$this->jsonError(400, $message);
return null;
}
try {
$tuple = $upload->load($tmpFile, $folder);
} catch (Exception $e) {
$this->jsonError(400, $e->getMessage());
return null;
}
if ($upload->isError()) {
$errors = implode(' ' . PHP_EOL, $upload->getErrors());
$this->jsonError(400, $errors);
return null;
}
$tuple['Name'] = basename($tuple['Filename']);
return (new HTTPResponse(json_encode($tuple)))
->addHeader('Content-Type', 'application/json');
} | php | public function apiUploadFile(HTTPRequest $request)
{
$data = $request->postVars();
// When updating files, replace on conflict
$upload = $this->getUpload();
$upload->setReplaceFile(true);
// CSRF check
$token = SecurityToken::inst();
if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) {
$this->jsonError(400);
return null;
}
$tmpFile = $data['Upload'];
if (empty($data['ID']) || empty($tmpFile['name']) || !array_key_exists('Name', $data)) {
$this->jsonError(400, _t(__CLASS__.'.INVALID_REQUEST', 'Invalid request'));
return null;
}
// Check parent record
/** @var File $file */
$file = File::get()->byID($data['ID']);
if (!$file) {
$this->jsonError(404, _t(__CLASS__.'.FILE_NOT_FOUND', 'File not found'));
return null;
}
$folder = $file->ParentID ? $file->Parent()->getFilename() : '/';
// If extension is the same, attempt to re-use existing name
if (File::get_file_extension($tmpFile['name']) === File::get_file_extension($data['Name'])) {
$tmpFile['name'] = $data['Name'];
} else {
// If we are allowing this upload to rename the underlying record,
// do a uniqueness check.
$renamer = $this->getNameGenerator($tmpFile['name']);
foreach ($renamer as $name) {
$filename = File::join_paths($folder, $name);
if (!File::find($filename)) {
$tmpFile['name'] = $name;
break;
}
}
}
if (!$upload->validate($tmpFile)) {
$errors = $upload->getErrors();
$message = array_shift($errors);
$this->jsonError(400, $message);
return null;
}
try {
$tuple = $upload->load($tmpFile, $folder);
} catch (Exception $e) {
$this->jsonError(400, $e->getMessage());
return null;
}
if ($upload->isError()) {
$errors = implode(' ' . PHP_EOL, $upload->getErrors());
$this->jsonError(400, $errors);
return null;
}
$tuple['Name'] = basename($tuple['Filename']);
return (new HTTPResponse(json_encode($tuple)))
->addHeader('Content-Type', 'application/json');
} | [
"public",
"function",
"apiUploadFile",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"$",
"data",
"=",
"$",
"request",
"->",
"postVars",
"(",
")",
";",
"// When updating files, replace on conflict",
"$",
"upload",
"=",
"$",
"this",
"->",
"getUpload",
"(",
")",... | Upload a new asset for a pre-existing record. Returns the asset tuple.
Note that conflict resolution is as follows:
- If uploading a file with the same extension, we simply keep the same filename,
and overwrite any existing files (same name + sha = don't duplicate).
- If uploading a new file with a different extension, then the filename will
be replaced, and will be checked for uniqueness against other File dataobjects.
@param HTTPRequest $request Request containing vars 'ID' of parent record ID,
and 'Name' as form filename value
@return HTTPRequest|HTTPResponse | [
"Upload",
"a",
"new",
"asset",
"for",
"a",
"pre",
"-",
"existing",
"record",
".",
"Returns",
"the",
"asset",
"tuple",
"."
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L356-L424 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.legacyRedirectForEditView | public function legacyRedirectForEditView($request)
{
$fileID = $request->param('FileID');
/** @var File $file */
$file = File::get()->byID($fileID);
$link = $this->getFileEditLink($file) ?: $this->Link();
$this->redirect($link);
} | php | public function legacyRedirectForEditView($request)
{
$fileID = $request->param('FileID');
/** @var File $file */
$file = File::get()->byID($fileID);
$link = $this->getFileEditLink($file) ?: $this->Link();
$this->redirect($link);
} | [
"public",
"function",
"legacyRedirectForEditView",
"(",
"$",
"request",
")",
"{",
"$",
"fileID",
"=",
"$",
"request",
"->",
"param",
"(",
"'FileID'",
")",
";",
"/** @var File $file */",
"$",
"file",
"=",
"File",
"::",
"get",
"(",
")",
"->",
"byID",
"(",
... | Redirects 3.x style detail links to new 4.x style routing.
@param HTTPRequest $request | [
"Redirects",
"3",
".",
"x",
"style",
"detail",
"links",
"to",
"new",
"4",
".",
"x",
"style",
"routing",
"."
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L529-L536 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.getFileEditLink | public function getFileEditLink($file)
{
if (!$file || !$file->isInDB()) {
return null;
}
return Controller::join_links(
$this->Link('show'),
$file->ParentID,
'edit',
$file->ID
);
} | php | public function getFileEditLink($file)
{
if (!$file || !$file->isInDB()) {
return null;
}
return Controller::join_links(
$this->Link('show'),
$file->ParentID,
'edit',
$file->ID
);
} | [
"public",
"function",
"getFileEditLink",
"(",
"$",
"file",
")",
"{",
"if",
"(",
"!",
"$",
"file",
"||",
"!",
"$",
"file",
"->",
"isInDB",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"Controller",
"::",
"join_links",
"(",
"$",
"this",
... | Given a file return the CMS link to edit it
@param File $file
@return string | [
"Given",
"a",
"file",
"return",
"the",
"CMS",
"link",
"to",
"edit",
"it"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L544-L556 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.getFormFactory | public function getFormFactory(File $file)
{
// Get service name based on file class
$name = null;
if ($file instanceof Folder) {
$name = FolderFormFactory::class;
} elseif ($file instanceof Image) {
$name = ImageFormFactory::class;
} else {
$name = FileFormFactory::class;
}
return Injector::inst()->get($name);
} | php | public function getFormFactory(File $file)
{
// Get service name based on file class
$name = null;
if ($file instanceof Folder) {
$name = FolderFormFactory::class;
} elseif ($file instanceof Image) {
$name = ImageFormFactory::class;
} else {
$name = FileFormFactory::class;
}
return Injector::inst()->get($name);
} | [
"public",
"function",
"getFormFactory",
"(",
"File",
"$",
"file",
")",
"{",
"// Get service name based on file class",
"$",
"name",
"=",
"null",
";",
"if",
"(",
"$",
"file",
"instanceof",
"Folder",
")",
"{",
"$",
"name",
"=",
"FolderFormFactory",
"::",
"class"... | Build a form scaffolder for this model
NOTE: Volatile api. May be moved to {@see LeftAndMain}
@param File $file
@return FormFactory | [
"Build",
"a",
"form",
"scaffolder",
"for",
"this",
"model"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L610-L622 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.fileEditForm | public function fileEditForm($request = null)
{
// Get ID either from posted back value, or url parameter
if (!$request) {
$this->jsonError(400);
return null;
}
$id = $request->param('ID');
if (!$id) {
$this->jsonError(400);
return null;
}
return $this->getFileEditForm($id);
} | php | public function fileEditForm($request = null)
{
// Get ID either from posted back value, or url parameter
if (!$request) {
$this->jsonError(400);
return null;
}
$id = $request->param('ID');
if (!$id) {
$this->jsonError(400);
return null;
}
return $this->getFileEditForm($id);
} | [
"public",
"function",
"fileEditForm",
"(",
"$",
"request",
"=",
"null",
")",
"{",
"// Get ID either from posted back value, or url parameter",
"if",
"(",
"!",
"$",
"request",
")",
"{",
"$",
"this",
"->",
"jsonError",
"(",
"400",
")",
";",
"return",
"null",
";"... | Get file edit form
@param HTTPRequest $request
@return Form|HTTPResponse | [
"Get",
"file",
"edit",
"form"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L649-L662 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.fileInsertForm | public function fileInsertForm($request = null)
{
// Get ID either from posted back value, or url parameter
if (!$request) {
$this->jsonError(400);
return null;
}
$id = $request->param('ID');
if (!$id) {
$this->jsonError(400);
return null;
}
return $this->getFileInsertForm($id);
} | php | public function fileInsertForm($request = null)
{
// Get ID either from posted back value, or url parameter
if (!$request) {
$this->jsonError(400);
return null;
}
$id = $request->param('ID');
if (!$id) {
$this->jsonError(400);
return null;
}
return $this->getFileInsertForm($id);
} | [
"public",
"function",
"fileInsertForm",
"(",
"$",
"request",
"=",
"null",
")",
"{",
"// Get ID either from posted back value, or url parameter",
"if",
"(",
"!",
"$",
"request",
")",
"{",
"$",
"this",
"->",
"jsonError",
"(",
"400",
")",
";",
"return",
"null",
"... | Get file insert media form
@param HTTPRequest $request
@return Form|HTTPResponse | [
"Get",
"file",
"insert",
"media",
"form"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L684-L697 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.fileEditorLinkForm | public function fileEditorLinkForm($request = null)
{
// Get ID either from posted back value, or url parameter
if (!$request) {
$this->jsonError(400);
return null;
}
$id = $request->param('ID');
if (!$id) {
$this->jsonError(400);
return null;
}
return $this->getFileInsertForm($id);
} | php | public function fileEditorLinkForm($request = null)
{
// Get ID either from posted back value, or url parameter
if (!$request) {
$this->jsonError(400);
return null;
}
$id = $request->param('ID');
if (!$id) {
$this->jsonError(400);
return null;
}
return $this->getFileInsertForm($id);
} | [
"public",
"function",
"fileEditorLinkForm",
"(",
"$",
"request",
"=",
"null",
")",
"{",
"// Get ID either from posted back value, or url parameter",
"if",
"(",
"!",
"$",
"request",
")",
"{",
"$",
"this",
"->",
"jsonError",
"(",
"400",
")",
";",
"return",
"null",... | Get the file insert link form
@param HTTPRequest $request
@return Form|HTTPResponse | [
"Get",
"the",
"file",
"insert",
"link",
"form"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L717-L730 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.getAbstractFileForm | protected function getAbstractFileForm($id, $name, $context = [])
{
/** @var File $file */
$file = File::get()->byID($id);
if (!$file) {
$this->jsonError(404);
return null;
}
if (!$file->canView()) {
$this->jsonError(403, _t(
__CLASS__.'.ErrorItemPermissionDenied',
"You don't have the necessary permissions to modify {ObjectTitle}",
[ 'ObjectTitle' => $file->i18n_singular_name() ]
));
return null;
}
// Pass to form factory
$showLinkText = $this->getRequest()->getVar('requireLinkText');
$augmentedContext = array_merge(
$context,
[ 'Record' => $file, 'RequireLinkText' => isset($showLinkText) ]
);
$scaffolder = $this->getFormFactory($file);
$form = $scaffolder->getForm($this, $name, $augmentedContext);
// Set form action handler with ID included
$form->setRequestHandler(
LeftAndMainFormRequestHandler::create($form, [ $id ])
);
// Configure form to respond to validation errors with form schema
// if requested via react.
$form->setValidationResponseCallback(function (ValidationResult $error) use ($form, $id, $name) {
$schemaId = Controller::join_links($this->Link('schema'), $name, $id);
return $this->getSchemaResponse($schemaId, $form, $error);
});
return $form;
} | php | protected function getAbstractFileForm($id, $name, $context = [])
{
/** @var File $file */
$file = File::get()->byID($id);
if (!$file) {
$this->jsonError(404);
return null;
}
if (!$file->canView()) {
$this->jsonError(403, _t(
__CLASS__.'.ErrorItemPermissionDenied',
"You don't have the necessary permissions to modify {ObjectTitle}",
[ 'ObjectTitle' => $file->i18n_singular_name() ]
));
return null;
}
// Pass to form factory
$showLinkText = $this->getRequest()->getVar('requireLinkText');
$augmentedContext = array_merge(
$context,
[ 'Record' => $file, 'RequireLinkText' => isset($showLinkText) ]
);
$scaffolder = $this->getFormFactory($file);
$form = $scaffolder->getForm($this, $name, $augmentedContext);
// Set form action handler with ID included
$form->setRequestHandler(
LeftAndMainFormRequestHandler::create($form, [ $id ])
);
// Configure form to respond to validation errors with form schema
// if requested via react.
$form->setValidationResponseCallback(function (ValidationResult $error) use ($form, $id, $name) {
$schemaId = Controller::join_links($this->Link('schema'), $name, $id);
return $this->getSchemaResponse($schemaId, $form, $error);
});
return $form;
} | [
"protected",
"function",
"getAbstractFileForm",
"(",
"$",
"id",
",",
"$",
"name",
",",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"/** @var File $file */",
"$",
"file",
"=",
"File",
"::",
"get",
"(",
")",
"->",
"byID",
"(",
"$",
"id",
")",
";",
"if",
... | Abstract method for generating a form for a file
@param int $id Record ID
@param string $name Form name
@param array $context Form context
@return Form|HTTPResponse | [
"Abstract",
"method",
"for",
"generating",
"a",
"form",
"for",
"a",
"file"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L740-L781 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.fileSelectForm | public function fileSelectForm()
{
// Get ID either from posted back value, or url parameter
$request = $this->getRequest();
$id = $request->param('ID') ?: $request->postVar('ID');
return $this->getFileSelectForm($id);
} | php | public function fileSelectForm()
{
// Get ID either from posted back value, or url parameter
$request = $this->getRequest();
$id = $request->param('ID') ?: $request->postVar('ID');
return $this->getFileSelectForm($id);
} | [
"public",
"function",
"fileSelectForm",
"(",
")",
"{",
"// Get ID either from posted back value, or url parameter",
"$",
"request",
"=",
"$",
"this",
"->",
"getRequest",
"(",
")",
";",
"$",
"id",
"=",
"$",
"request",
"->",
"param",
"(",
"'ID'",
")",
"?",
":",
... | Get form for selecting a file
@return Form | [
"Get",
"form",
"for",
"selecting",
"a",
"file"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L788-L794 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.fileHistoryForm | public function fileHistoryForm($request = null)
{
// Get ID either from posted back value, or url parameter
if (!$request) {
$this->jsonError(400);
return null;
}
$id = $request->param('ID');
if (!$id) {
$this->jsonError(400);
return null;
}
$versionID = $request->param('VersionID');
if (!$versionID) {
$this->jsonError(400);
return null;
}
$form = $this->getFileHistoryForm([
'RecordID' => $id,
'RecordVersion' => $versionID,
]);
return $form;
} | php | public function fileHistoryForm($request = null)
{
// Get ID either from posted back value, or url parameter
if (!$request) {
$this->jsonError(400);
return null;
}
$id = $request->param('ID');
if (!$id) {
$this->jsonError(400);
return null;
}
$versionID = $request->param('VersionID');
if (!$versionID) {
$this->jsonError(400);
return null;
}
$form = $this->getFileHistoryForm([
'RecordID' => $id,
'RecordVersion' => $versionID,
]);
return $form;
} | [
"public",
"function",
"fileHistoryForm",
"(",
"$",
"request",
"=",
"null",
")",
"{",
"// Get ID either from posted back value, or url parameter",
"if",
"(",
"!",
"$",
"request",
")",
"{",
"$",
"this",
"->",
"jsonError",
"(",
"400",
")",
";",
"return",
"null",
... | Get file history form
@param HTTPRequest $request
@return Form|HTTPResponse | [
"Get",
"file",
"history",
"form"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L926-L948 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.getObjectFromData | public function getObjectFromData(File $file, $thumbnailLinks = true)
{
$object = $this->getMinimalistObjectFromData($file, $thumbnailLinks);
// Slightly more accurate than graphql bulk-usage lookup, but more expensive
$object['inUseCount'] = ($file->hasMethod('findOwners')) ? $file->findOwners()->count() : 0;
$object['created'] = $file->Created;
$object['lastUpdated'] = $file->LastEdited;
$object['owner'] = null;
$object['type'] = $file instanceof Folder ? 'folder' : $file->FileType;
$object['name'] = $file->Name;
$object['filename'] = $file->Filename;
$object['url'] = $file->AbsoluteURL;
$object['canEdit'] = $file->canEdit();
$object['canDelete'] = ($file->hasMethod('canArchive')) ? $file->canArchive() : $file->canDelete();
/** @var Member $owner */
$owner = $file->Owner();
if ($owner) {
$object['owner'] = array(
'id' => $owner->ID,
'title' => $owner->Name,
);
}
return $object;
} | php | public function getObjectFromData(File $file, $thumbnailLinks = true)
{
$object = $this->getMinimalistObjectFromData($file, $thumbnailLinks);
// Slightly more accurate than graphql bulk-usage lookup, but more expensive
$object['inUseCount'] = ($file->hasMethod('findOwners')) ? $file->findOwners()->count() : 0;
$object['created'] = $file->Created;
$object['lastUpdated'] = $file->LastEdited;
$object['owner'] = null;
$object['type'] = $file instanceof Folder ? 'folder' : $file->FileType;
$object['name'] = $file->Name;
$object['filename'] = $file->Filename;
$object['url'] = $file->AbsoluteURL;
$object['canEdit'] = $file->canEdit();
$object['canDelete'] = ($file->hasMethod('canArchive')) ? $file->canArchive() : $file->canDelete();
/** @var Member $owner */
$owner = $file->Owner();
if ($owner) {
$object['owner'] = array(
'id' => $owner->ID,
'title' => $owner->Name,
);
}
return $object;
} | [
"public",
"function",
"getObjectFromData",
"(",
"File",
"$",
"file",
",",
"$",
"thumbnailLinks",
"=",
"true",
")",
"{",
"$",
"object",
"=",
"$",
"this",
"->",
"getMinimalistObjectFromData",
"(",
"$",
"file",
",",
"$",
"thumbnailLinks",
")",
";",
"// Slightly... | Build the array containing the all attributes the AssetAdmin client interact with.
@param File $file
@param bool $thumbnailLinks Set to true if thumbnail links should be included.
Set to false to skip thumbnail link generation.
Note: Thumbnail content is always generated to pre-optimise for future use, even if
links are not generated.
@return array | [
"Build",
"the",
"array",
"containing",
"the",
"all",
"attributes",
"the",
"AssetAdmin",
"client",
"interact",
"with",
"."
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L1113-L1140 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.getMinimalistObjectFromData | public function getMinimalistObjectFromData(File $file, $thumbnailLinks = true)
{
$object = array(
'id' => (int) $file->ID,
'parent' => null,
'title' => $file->Title,
'exists' => $file->exists(), // Broken file check
'category' => $file instanceof Folder ? 'folder' : $file->appCategory(),
'extension' => $file->Extension,
'size' => $file->AbsoluteSize,
'published' => ($file->hasMethod('isPublished')) ? $file->isPublished() : true,
'modified' => ($file->hasMethod('isModifiedOnDraft')) ? $file->isModifiedOnDraft() : false,
'draft' => ($file->hasMethod('isOnDraftOnly')) ? $file->isOnDraftOnly() : false,
);
/** @var Folder $parent */
$parent = $file->Parent();
if ($parent) {
$object['parent'] = array(
'id' => $parent->ID,
'title' => $parent->Title,
'filename' => $parent->Filename,
);
}
/** @var File $file */
if ($file->getIsImage()) {
$thumbnails = $this->generateThumbnails($file, $thumbnailLinks);
if ($thumbnailLinks) {
$object = array_merge($object, $thumbnails);
}
// Save dimensions
$object['width'] = $file->getWidth();
$object['height'] = $file->getHeight();
} else {
$object['thumbnail'] = $file->PreviewLink();
}
return $object;
} | php | public function getMinimalistObjectFromData(File $file, $thumbnailLinks = true)
{
$object = array(
'id' => (int) $file->ID,
'parent' => null,
'title' => $file->Title,
'exists' => $file->exists(), // Broken file check
'category' => $file instanceof Folder ? 'folder' : $file->appCategory(),
'extension' => $file->Extension,
'size' => $file->AbsoluteSize,
'published' => ($file->hasMethod('isPublished')) ? $file->isPublished() : true,
'modified' => ($file->hasMethod('isModifiedOnDraft')) ? $file->isModifiedOnDraft() : false,
'draft' => ($file->hasMethod('isOnDraftOnly')) ? $file->isOnDraftOnly() : false,
);
/** @var Folder $parent */
$parent = $file->Parent();
if ($parent) {
$object['parent'] = array(
'id' => $parent->ID,
'title' => $parent->Title,
'filename' => $parent->Filename,
);
}
/** @var File $file */
if ($file->getIsImage()) {
$thumbnails = $this->generateThumbnails($file, $thumbnailLinks);
if ($thumbnailLinks) {
$object = array_merge($object, $thumbnails);
}
// Save dimensions
$object['width'] = $file->getWidth();
$object['height'] = $file->getHeight();
} else {
$object['thumbnail'] = $file->PreviewLink();
}
return $object;
} | [
"public",
"function",
"getMinimalistObjectFromData",
"(",
"File",
"$",
"file",
",",
"$",
"thumbnailLinks",
"=",
"true",
")",
"{",
"$",
"object",
"=",
"array",
"(",
"'id'",
"=>",
"(",
"int",
")",
"$",
"file",
"->",
"ID",
",",
"'parent'",
"=>",
"null",
"... | Build the array containing the minimal attributes needed to render an UploadFieldItem.
@param File $file
@param bool $thumbnailLinks Set to true if thumbnail links should be included.
Set to false to skip thumbnail link generation.
Note: Thumbnail content is always generated to pre-optimise for future use, even if
links are not generated.
@return array | [
"Build",
"the",
"array",
"containing",
"the",
"minimal",
"attributes",
"needed",
"to",
"render",
"an",
"UploadFieldItem",
"."
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L1152-L1193 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.generateThumbnails | public function generateThumbnails(File $file, $thumbnailLinks = false)
{
$links = [];
if (!$file->getIsImage()) {
return $links;
}
$generator = $this->getThumbnailGenerator();
// Small thumbnail
$smallWidth = UploadField::config()->uninherited('thumbnail_width');
$smallHeight = UploadField::config()->uninherited('thumbnail_height');
// Large thumbnail
$width = $this->config()->get('thumbnail_width');
$height = $this->config()->get('thumbnail_height');
// Generate links if client requests them
// Note: Thumbnails should always be generated even if links are not
if ($thumbnailLinks) {
$links['smallThumbnail'] = $generator->generateThumbnailLink($file, $smallWidth, $smallHeight);
$links['thumbnail'] = $generator->generateThumbnailLink($file, $width, $height);
} else {
$generator->generateThumbnail($file, $smallWidth, $smallHeight);
$generator->generateThumbnail($file, $width, $height);
}
$this->extend('updateGeneratedThumbnails', $file, $links, $generator);
return $links;
} | php | public function generateThumbnails(File $file, $thumbnailLinks = false)
{
$links = [];
if (!$file->getIsImage()) {
return $links;
}
$generator = $this->getThumbnailGenerator();
// Small thumbnail
$smallWidth = UploadField::config()->uninherited('thumbnail_width');
$smallHeight = UploadField::config()->uninherited('thumbnail_height');
// Large thumbnail
$width = $this->config()->get('thumbnail_width');
$height = $this->config()->get('thumbnail_height');
// Generate links if client requests them
// Note: Thumbnails should always be generated even if links are not
if ($thumbnailLinks) {
$links['smallThumbnail'] = $generator->generateThumbnailLink($file, $smallWidth, $smallHeight);
$links['thumbnail'] = $generator->generateThumbnailLink($file, $width, $height);
} else {
$generator->generateThumbnail($file, $smallWidth, $smallHeight);
$generator->generateThumbnail($file, $width, $height);
}
$this->extend('updateGeneratedThumbnails', $file, $links, $generator);
return $links;
} | [
"public",
"function",
"generateThumbnails",
"(",
"File",
"$",
"file",
",",
"$",
"thumbnailLinks",
"=",
"false",
")",
"{",
"$",
"links",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"$",
"file",
"->",
"getIsImage",
"(",
")",
")",
"{",
"return",
"$",
"links",
... | Generate thumbnails and provide links for a given file
@param File $file
@param bool $thumbnailLinks
@return array | [
"Generate",
"thumbnails",
"and",
"provide",
"links",
"for",
"a",
"given",
"file"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L1202-L1230 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.getRecordUpdatedResponse | protected function getRecordUpdatedResponse($record, $form)
{
// Return the record data in the same response as the schema to save a postback
$schemaData = ['record' => $this->getObjectFromData($record)];
$schemaId = Controller::join_links($this->Link('schema/fileEditForm'), $record->ID);
return $this->getSchemaResponse($schemaId, $form, null, $schemaData);
} | php | protected function getRecordUpdatedResponse($record, $form)
{
// Return the record data in the same response as the schema to save a postback
$schemaData = ['record' => $this->getObjectFromData($record)];
$schemaId = Controller::join_links($this->Link('schema/fileEditForm'), $record->ID);
return $this->getSchemaResponse($schemaId, $form, null, $schemaData);
} | [
"protected",
"function",
"getRecordUpdatedResponse",
"(",
"$",
"record",
",",
"$",
"form",
")",
"{",
"// Return the record data in the same response as the schema to save a postback",
"$",
"schemaData",
"=",
"[",
"'record'",
"=>",
"$",
"this",
"->",
"getObjectFromData",
"... | Get response for successfully updated record
@param File $record
@param Form $form
@return HTTPResponse | [
"Get",
"response",
"for",
"successfully",
"updated",
"record"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L1330-L1336 | train |
silverstripe/silverstripe-asset-admin | code/Controller/AssetAdmin.php | AssetAdmin.getFolderCreateForm | public function getFolderCreateForm($parentId = 0)
{
/** @var FolderCreateFormFactory $factory */
$factory = Injector::inst()->get(FolderCreateFormFactory::class);
$form = $factory->getForm($this, 'folderCreateForm', [ 'ParentID' => $parentId ]);
// Set form action handler with ParentID included
$form->setRequestHandler(
LeftAndMainFormRequestHandler::create($form, [ $parentId ])
);
return $form;
} | php | public function getFolderCreateForm($parentId = 0)
{
/** @var FolderCreateFormFactory $factory */
$factory = Injector::inst()->get(FolderCreateFormFactory::class);
$form = $factory->getForm($this, 'folderCreateForm', [ 'ParentID' => $parentId ]);
// Set form action handler with ParentID included
$form->setRequestHandler(
LeftAndMainFormRequestHandler::create($form, [ $parentId ])
);
return $form;
} | [
"public",
"function",
"getFolderCreateForm",
"(",
"$",
"parentId",
"=",
"0",
")",
"{",
"/** @var FolderCreateFormFactory $factory */",
"$",
"factory",
"=",
"Injector",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"FolderCreateFormFactory",
"::",
"class",
")",
";",
... | Returns the form to be used for creating a new folder
@param $parentId
@return Form | [
"Returns",
"the",
"form",
"to",
"be",
"used",
"for",
"creating",
"a",
"new",
"folder"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/Controller/AssetAdmin.php#L1363-L1375 | train |
silverstripe/silverstripe-asset-admin | code/GraphQL/UnpublishFileMutationCreator.php | UnpublishFileMutationCreator.countLiveOwners | protected function countLiveOwners(File $file)
{
// In case no versioning
if (!$file->hasExtension(RecursivePublishable::class)) {
return 0;
}
// Query live record
/** @var Versioned|RecursivePublishable $liveRecord */
$liveRecord = Versioned::get_by_stage(File::class, Versioned::LIVE)->byID($file->ID);
if ($liveRecord) {
return $liveRecord
->findOwners(false)
->count();
}
// No live record, no live owners
return 0;
} | php | protected function countLiveOwners(File $file)
{
// In case no versioning
if (!$file->hasExtension(RecursivePublishable::class)) {
return 0;
}
// Query live record
/** @var Versioned|RecursivePublishable $liveRecord */
$liveRecord = Versioned::get_by_stage(File::class, Versioned::LIVE)->byID($file->ID);
if ($liveRecord) {
return $liveRecord
->findOwners(false)
->count();
}
// No live record, no live owners
return 0;
} | [
"protected",
"function",
"countLiveOwners",
"(",
"File",
"$",
"file",
")",
"{",
"// In case no versioning",
"if",
"(",
"!",
"$",
"file",
"->",
"hasExtension",
"(",
"RecursivePublishable",
"::",
"class",
")",
")",
"{",
"return",
"0",
";",
"}",
"// Query live re... | Count number of live owners this file uses
@param File $file
@return int Number of live owners | [
"Count",
"number",
"of",
"live",
"owners",
"this",
"file",
"uses"
] | cfa36b7c61b79b81a035e1c2845e58340cd03b2e | https://github.com/silverstripe/silverstripe-asset-admin/blob/cfa36b7c61b79b81a035e1c2845e58340cd03b2e/code/GraphQL/UnpublishFileMutationCreator.php#L87-L105 | train |
symbiote/silverstripe-gridfieldextensions | src/GridFieldEditableColumns.php | GridFieldEditableColumns.getFields | public function getFields(GridField $grid, DataObjectInterface $record)
{
$cols = $this->getDisplayFields($grid);
$fields = new FieldList();
/** @var DataList $list */
$list = $grid->getList();
$class = $list ? $list->dataClass() : null;
foreach ($cols as $col => $info) {
$field = null;
if ($info instanceof Closure) {
$field = call_user_func($info, $record, $col, $grid);
} elseif (is_array($info)) {
if (isset($info['callback'])) {
$field = call_user_func($info['callback'], $record, $col, $grid);
} elseif (isset($info['field'])) {
if ($info['field'] == LiteralField::class) {
$field = new $info['field']($col, null);
} else {
$field = new $info['field']($col);
}
}
if (!$field instanceof FormField) {
throw new Exception(sprintf(
'The field for column "%s" is not a valid form field',
$col
));
}
}
if (!$field && $list instanceof ManyManyList) {
$extra = $list->getExtraFields();
if ($extra && array_key_exists($col, $extra)) {
$field = Injector::inst()->create($extra[$col], $col)->scaffoldFormField();
}
}
if (!$field) {
if (!$this->displayFields) {
// If setDisplayFields() not used, utilize $summary_fields
// in a way similar to base class
//
// Allows use of 'MyBool.Nice' and 'MyHTML.NoHTML' so that
// GridFields not using inline editing still look good or
// revert to looking good in cases where the field isn't
// available or is readonly
//
$colRelation = explode('.', $col);
if ($class && $obj = DataObject::singleton($class)->dbObject($colRelation[0])) {
$field = $obj->scaffoldFormField();
} else {
$field = new ReadonlyField($colRelation[0]);
}
} elseif ($class && $obj = DataObject::singleton($class)->dbObject($col)) {
$field = $obj->scaffoldFormField();
} else {
$field = new ReadonlyField($col);
}
}
if (!$field instanceof FormField) {
throw new Exception(sprintf(
'Invalid form field instance for column "%s"',
$col
));
}
// Add CSS class for interactive fields
if (!($field->isReadOnly() || $field instanceof LiteralField)) {
$field->addExtraClass('editable-column-field');
}
$fields->push($field);
}
return $fields;
} | php | public function getFields(GridField $grid, DataObjectInterface $record)
{
$cols = $this->getDisplayFields($grid);
$fields = new FieldList();
/** @var DataList $list */
$list = $grid->getList();
$class = $list ? $list->dataClass() : null;
foreach ($cols as $col => $info) {
$field = null;
if ($info instanceof Closure) {
$field = call_user_func($info, $record, $col, $grid);
} elseif (is_array($info)) {
if (isset($info['callback'])) {
$field = call_user_func($info['callback'], $record, $col, $grid);
} elseif (isset($info['field'])) {
if ($info['field'] == LiteralField::class) {
$field = new $info['field']($col, null);
} else {
$field = new $info['field']($col);
}
}
if (!$field instanceof FormField) {
throw new Exception(sprintf(
'The field for column "%s" is not a valid form field',
$col
));
}
}
if (!$field && $list instanceof ManyManyList) {
$extra = $list->getExtraFields();
if ($extra && array_key_exists($col, $extra)) {
$field = Injector::inst()->create($extra[$col], $col)->scaffoldFormField();
}
}
if (!$field) {
if (!$this->displayFields) {
// If setDisplayFields() not used, utilize $summary_fields
// in a way similar to base class
//
// Allows use of 'MyBool.Nice' and 'MyHTML.NoHTML' so that
// GridFields not using inline editing still look good or
// revert to looking good in cases where the field isn't
// available or is readonly
//
$colRelation = explode('.', $col);
if ($class && $obj = DataObject::singleton($class)->dbObject($colRelation[0])) {
$field = $obj->scaffoldFormField();
} else {
$field = new ReadonlyField($colRelation[0]);
}
} elseif ($class && $obj = DataObject::singleton($class)->dbObject($col)) {
$field = $obj->scaffoldFormField();
} else {
$field = new ReadonlyField($col);
}
}
if (!$field instanceof FormField) {
throw new Exception(sprintf(
'Invalid form field instance for column "%s"',
$col
));
}
// Add CSS class for interactive fields
if (!($field->isReadOnly() || $field instanceof LiteralField)) {
$field->addExtraClass('editable-column-field');
}
$fields->push($field);
}
return $fields;
} | [
"public",
"function",
"getFields",
"(",
"GridField",
"$",
"grid",
",",
"DataObjectInterface",
"$",
"record",
")",
"{",
"$",
"cols",
"=",
"$",
"this",
"->",
"getDisplayFields",
"(",
"$",
"grid",
")",
";",
"$",
"fields",
"=",
"new",
"FieldList",
"(",
")",
... | Gets the field list for a record.
@param GridField $grid
@param DataObjectInterface $record
@return FieldList
@throws Exception | [
"Gets",
"the",
"field",
"list",
"for",
"a",
"record",
"."
] | 176922303e8fa27b9b52b68b635b58d09e0a0ec3 | https://github.com/symbiote/silverstripe-gridfieldextensions/blob/176922303e8fa27b9b52b68b635b58d09e0a0ec3/src/GridFieldEditableColumns.php#L205-L285 | train |
symbiote/silverstripe-gridfieldextensions | src/GridFieldEditableColumns.php | GridFieldEditableColumns.getForm | public function getForm(GridField $grid, DataObjectInterface $record)
{
$fields = $this->getFields($grid, $record);
$form = new Form($grid, null, $fields, new FieldList());
$form->loadDataFrom($record);
$form->setFormAction(Controller::join_links(
$grid->Link(),
'editable/form',
$record->ID
));
return $form;
} | php | public function getForm(GridField $grid, DataObjectInterface $record)
{
$fields = $this->getFields($grid, $record);
$form = new Form($grid, null, $fields, new FieldList());
$form->loadDataFrom($record);
$form->setFormAction(Controller::join_links(
$grid->Link(),
'editable/form',
$record->ID
));
return $form;
} | [
"public",
"function",
"getForm",
"(",
"GridField",
"$",
"grid",
",",
"DataObjectInterface",
"$",
"record",
")",
"{",
"$",
"fields",
"=",
"$",
"this",
"->",
"getFields",
"(",
"$",
"grid",
",",
"$",
"record",
")",
";",
"$",
"form",
"=",
"new",
"Form",
... | Gets the form instance for a record.
@param GridField $grid
@param DataObjectInterface $record
@return Form | [
"Gets",
"the",
"form",
"instance",
"for",
"a",
"record",
"."
] | 176922303e8fa27b9b52b68b635b58d09e0a0ec3 | https://github.com/symbiote/silverstripe-gridfieldextensions/blob/176922303e8fa27b9b52b68b635b58d09e0a0ec3/src/GridFieldEditableColumns.php#L294-L308 | train |
symbiote/silverstripe-gridfieldextensions | src/GridFieldRequestHandler.php | GridFieldRequestHandler.Form | public function Form()
{
$form = new Form(
$this,
'SilverStripe\\Forms\\Form',
new FieldList($root = new TabSet('Root', new Tab('Main'))),
new FieldList()
);
if ($this->getTopLevelController() instanceof LeftAndMain) {
$form->setTemplate('LeftAndMain_EditForm');
$form->addExtraClass('cms-content cms-edit-form cms-tabset center');
$form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
$root->setTemplate('CMSTabSet');
$form->Backlink = $this->getBackLink();
}
return $form;
} | php | public function Form()
{
$form = new Form(
$this,
'SilverStripe\\Forms\\Form',
new FieldList($root = new TabSet('Root', new Tab('Main'))),
new FieldList()
);
if ($this->getTopLevelController() instanceof LeftAndMain) {
$form->setTemplate('LeftAndMain_EditForm');
$form->addExtraClass('cms-content cms-edit-form cms-tabset center');
$form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
$root->setTemplate('CMSTabSet');
$form->Backlink = $this->getBackLink();
}
return $form;
} | [
"public",
"function",
"Form",
"(",
")",
"{",
"$",
"form",
"=",
"new",
"Form",
"(",
"$",
"this",
",",
"'SilverStripe\\\\Forms\\\\Form'",
",",
"new",
"FieldList",
"(",
"$",
"root",
"=",
"new",
"TabSet",
"(",
"'Root'",
",",
"new",
"Tab",
"(",
"'Main'",
")... | This method should be overloaded to build out the detail form.
@return Form | [
"This",
"method",
"should",
"be",
"overloaded",
"to",
"build",
"out",
"the",
"detail",
"form",
"."
] | 176922303e8fa27b9b52b68b635b58d09e0a0ec3 | https://github.com/symbiote/silverstripe-gridfieldextensions/blob/176922303e8fa27b9b52b68b635b58d09e0a0ec3/src/GridFieldRequestHandler.php#L84-L103 | train |
symbiote/silverstripe-gridfieldextensions | src/GridFieldOrderableRows.php | GridFieldOrderableRows.validateSortField | public function validateSortField(SS_List $list)
{
$field = $this->getSortField();
// Check extra fields on many many relation types
if ($list instanceof ManyManyList) {
$extra = $list->getExtraFields();
if ($extra && array_key_exists($field, $extra)) {
return;
}
} elseif ($list instanceof ManyManyThroughList) {
$manipulator = $this->getManyManyInspector($list);
$fieldTable = DataObject::getSchema()->tableForField($manipulator->getJoinClass(), $field);
if ($fieldTable) {
return;
}
}
$classes = ClassInfo::dataClassesFor($list->dataClass());
foreach ($classes as $class) {
if (singleton($class)->hasDataBaseField($field)) {
return;
}
}
throw new Exception("Couldn't find the sort field '" . $field . "'");
} | php | public function validateSortField(SS_List $list)
{
$field = $this->getSortField();
// Check extra fields on many many relation types
if ($list instanceof ManyManyList) {
$extra = $list->getExtraFields();
if ($extra && array_key_exists($field, $extra)) {
return;
}
} elseif ($list instanceof ManyManyThroughList) {
$manipulator = $this->getManyManyInspector($list);
$fieldTable = DataObject::getSchema()->tableForField($manipulator->getJoinClass(), $field);
if ($fieldTable) {
return;
}
}
$classes = ClassInfo::dataClassesFor($list->dataClass());
foreach ($classes as $class) {
if (singleton($class)->hasDataBaseField($field)) {
return;
}
}
throw new Exception("Couldn't find the sort field '" . $field . "'");
} | [
"public",
"function",
"validateSortField",
"(",
"SS_List",
"$",
"list",
")",
"{",
"$",
"field",
"=",
"$",
"this",
"->",
"getSortField",
"(",
")",
";",
"// Check extra fields on many many relation types",
"if",
"(",
"$",
"list",
"instanceof",
"ManyManyList",
")",
... | Validates sortable list
@param SS_List $list
@throws Exception | [
"Validates",
"sortable",
"list"
] | 176922303e8fa27b9b52b68b635b58d09e0a0ec3 | https://github.com/symbiote/silverstripe-gridfieldextensions/blob/176922303e8fa27b9b52b68b635b58d09e0a0ec3/src/GridFieldOrderableRows.php#L231-L259 | train |
symbiote/silverstripe-gridfieldextensions | src/GridFieldOrderableRows.php | GridFieldOrderableRows.handleSave | public function handleSave(GridField $grid, DataObjectInterface $record)
{
if (!$this->immediateUpdate) {
$value = $grid->Value();
$sortedIDs = $this->getSortedIDs($value);
if ($sortedIDs) {
$this->executeReorder($grid, $sortedIDs);
}
}
} | php | public function handleSave(GridField $grid, DataObjectInterface $record)
{
if (!$this->immediateUpdate) {
$value = $grid->Value();
$sortedIDs = $this->getSortedIDs($value);
if ($sortedIDs) {
$this->executeReorder($grid, $sortedIDs);
}
}
} | [
"public",
"function",
"handleSave",
"(",
"GridField",
"$",
"grid",
",",
"DataObjectInterface",
"$",
"record",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"immediateUpdate",
")",
"{",
"$",
"value",
"=",
"$",
"grid",
"->",
"Value",
"(",
")",
";",
"$",
... | Handle saving when 'immediateUpdate' is disabled, otherwise this isn't
necessary for the default sort mode. | [
"Handle",
"saving",
"when",
"immediateUpdate",
"is",
"disabled",
"otherwise",
"this",
"isn",
"t",
"necessary",
"for",
"the",
"default",
"sort",
"mode",
"."
] | 176922303e8fa27b9b52b68b635b58d09e0a0ec3 | https://github.com/symbiote/silverstripe-gridfieldextensions/blob/176922303e8fa27b9b52b68b635b58d09e0a0ec3/src/GridFieldOrderableRows.php#L530-L539 | train |
symbiote/silverstripe-gridfieldextensions | src/GridFieldOrderableRows.php | GridFieldOrderableRows.getManyManyInspector | protected function getManyManyInspector($list)
{
$inspector = $list;
if ($list instanceof ManyManyThroughList) {
foreach ($list->dataQuery()->getDataQueryManipulators() as $manipulator) {
if ($manipulator instanceof ManyManyThroughQueryManipulator) {
$inspector = $manipulator;
break;
}
}
}
return $inspector;
} | php | protected function getManyManyInspector($list)
{
$inspector = $list;
if ($list instanceof ManyManyThroughList) {
foreach ($list->dataQuery()->getDataQueryManipulators() as $manipulator) {
if ($manipulator instanceof ManyManyThroughQueryManipulator) {
$inspector = $manipulator;
break;
}
}
}
return $inspector;
} | [
"protected",
"function",
"getManyManyInspector",
"(",
"$",
"list",
")",
"{",
"$",
"inspector",
"=",
"$",
"list",
";",
"if",
"(",
"$",
"list",
"instanceof",
"ManyManyThroughList",
")",
"{",
"foreach",
"(",
"$",
"list",
"->",
"dataQuery",
"(",
")",
"->",
"... | A ManyManyList defines functions such as getLocalKey, however on ManyManyThroughList
these functions are moved to ManyManyThroughQueryManipulator, but otherwise retain
the same signature.
@param ManyManyList|ManyManyThroughList $list
@return ManyManyList|ManyManyThroughQueryManipulator | [
"A",
"ManyManyList",
"defines",
"functions",
"such",
"as",
"getLocalKey",
"however",
"on",
"ManyManyThroughList",
"these",
"functions",
"are",
"moved",
"to",
"ManyManyThroughQueryManipulator",
"but",
"otherwise",
"retain",
"the",
"same",
"signature",
"."
] | 176922303e8fa27b9b52b68b635b58d09e0a0ec3 | https://github.com/symbiote/silverstripe-gridfieldextensions/blob/176922303e8fa27b9b52b68b635b58d09e0a0ec3/src/GridFieldOrderableRows.php#L798-L810 | train |
symbiote/silverstripe-gridfieldextensions | src/GridFieldOrderableRows.php | GridFieldOrderableRows.getSortValuesFromManyManyThroughList | protected function getSortValuesFromManyManyThroughList($list, $sortField)
{
$manipulator = $this->getManyManyInspector($list);
// Find the foreign key name, ID and class to look up
$joinClass = $manipulator->getJoinClass();
$fromRelationName = $manipulator->getForeignKey();
$toRelationName = $manipulator->getLocalKey();
// Create a list of the MMTL relations
$sortlist = DataList::create($joinClass)->filter([
$toRelationName => $list->column('ID'),
// first() is safe as there are earlier checks to ensure our list to sort is valid
$fromRelationName => $list->first()->getJoin()->$fromRelationName,
]);
return $sortlist->map($toRelationName, $sortField)->toArray();
} | php | protected function getSortValuesFromManyManyThroughList($list, $sortField)
{
$manipulator = $this->getManyManyInspector($list);
// Find the foreign key name, ID and class to look up
$joinClass = $manipulator->getJoinClass();
$fromRelationName = $manipulator->getForeignKey();
$toRelationName = $manipulator->getLocalKey();
// Create a list of the MMTL relations
$sortlist = DataList::create($joinClass)->filter([
$toRelationName => $list->column('ID'),
// first() is safe as there are earlier checks to ensure our list to sort is valid
$fromRelationName => $list->first()->getJoin()->$fromRelationName,
]);
return $sortlist->map($toRelationName, $sortField)->toArray();
} | [
"protected",
"function",
"getSortValuesFromManyManyThroughList",
"(",
"$",
"list",
",",
"$",
"sortField",
")",
"{",
"$",
"manipulator",
"=",
"$",
"this",
"->",
"getManyManyInspector",
"(",
"$",
"list",
")",
";",
"// Find the foreign key name, ID and class to look up",
... | Used to get sort orders from a many many through list relationship record, rather than the current
record itself.
@param ManyManyList|ManyManyThroughList $list
@return int[] Sort orders for the | [
"Used",
"to",
"get",
"sort",
"orders",
"from",
"a",
"many",
"many",
"through",
"list",
"relationship",
"record",
"rather",
"than",
"the",
"current",
"record",
"itself",
"."
] | 176922303e8fa27b9b52b68b635b58d09e0a0ec3 | https://github.com/symbiote/silverstripe-gridfieldextensions/blob/176922303e8fa27b9b52b68b635b58d09e0a0ec3/src/GridFieldOrderableRows.php#L819-L836 | train |
symbiote/silverstripe-gridfieldextensions | src/GridFieldAddNewMultiClass.php | GridFieldAddNewMultiClass.getClasses | public function getClasses(GridField $grid)
{
$result = array();
if (is_null($this->classes)) {
$classes = array_values(ClassInfo::subclassesFor($grid->getModelClass()));
sort($classes);
} else {
$classes = $this->classes;
}
$kill_ancestors = array();
foreach ($classes as $class => $title) {
if (!is_string($class)) {
$class = $title;
}
if (!class_exists($class)) {
continue;
}
$is_abstract = (($reflection = new ReflectionClass($class)) && $reflection->isAbstract());
if (!$is_abstract && $class === $title) {
$title = singleton($class)->i18n_singular_name();
}
if ($ancestor_to_hide = Config::inst()->get($class, 'hide_ancestor')) {
$kill_ancestors[$ancestor_to_hide] = true;
}
if ($is_abstract || !singleton($class)->canCreate()) {
continue;
}
$result[$class] = $title;
}
if ($kill_ancestors) {
foreach ($kill_ancestors as $class => $bool) {
unset($result[$class]);
}
}
$sanitised = array();
foreach ($result as $class => $title) {
$sanitised[$this->sanitiseClassName($class)] = $title;
}
return $sanitised;
} | php | public function getClasses(GridField $grid)
{
$result = array();
if (is_null($this->classes)) {
$classes = array_values(ClassInfo::subclassesFor($grid->getModelClass()));
sort($classes);
} else {
$classes = $this->classes;
}
$kill_ancestors = array();
foreach ($classes as $class => $title) {
if (!is_string($class)) {
$class = $title;
}
if (!class_exists($class)) {
continue;
}
$is_abstract = (($reflection = new ReflectionClass($class)) && $reflection->isAbstract());
if (!$is_abstract && $class === $title) {
$title = singleton($class)->i18n_singular_name();
}
if ($ancestor_to_hide = Config::inst()->get($class, 'hide_ancestor')) {
$kill_ancestors[$ancestor_to_hide] = true;
}
if ($is_abstract || !singleton($class)->canCreate()) {
continue;
}
$result[$class] = $title;
}
if ($kill_ancestors) {
foreach ($kill_ancestors as $class => $bool) {
unset($result[$class]);
}
}
$sanitised = array();
foreach ($result as $class => $title) {
$sanitised[$this->sanitiseClassName($class)] = $title;
}
return $sanitised;
} | [
"public",
"function",
"getClasses",
"(",
"GridField",
"$",
"grid",
")",
"{",
"$",
"result",
"=",
"array",
"(",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"classes",
")",
")",
"{",
"$",
"classes",
"=",
"array_values",
"(",
"ClassInfo",
":... | Gets the classes that can be created using this button, defaulting to the model class and
its subclasses.
@param GridField $grid
@return array a map of class name to title | [
"Gets",
"the",
"classes",
"that",
"can",
"be",
"created",
"using",
"this",
"button",
"defaulting",
"to",
"the",
"model",
"class",
"and",
"its",
"subclasses",
"."
] | 176922303e8fa27b9b52b68b635b58d09e0a0ec3 | https://github.com/symbiote/silverstripe-gridfieldextensions/blob/176922303e8fa27b9b52b68b635b58d09e0a0ec3/src/GridFieldAddNewMultiClass.php#L119-L166 | train |
symbiote/silverstripe-gridfieldextensions | src/GridFieldConfigurablePaginator.php | GridFieldConfigurablePaginator.getFirstShown | public function getFirstShown()
{
$firstShown = $this->getGridPagerState()->firstShown ?: 1;
// Prevent visiting a page with an offset higher than the total number of items
if ($firstShown > $this->getTotalRecords()) {
$this->getGridPagerState()->firstShown = $firstShown = 1;
}
return $firstShown;
} | php | public function getFirstShown()
{
$firstShown = $this->getGridPagerState()->firstShown ?: 1;
// Prevent visiting a page with an offset higher than the total number of items
if ($firstShown > $this->getTotalRecords()) {
$this->getGridPagerState()->firstShown = $firstShown = 1;
}
return $firstShown;
} | [
"public",
"function",
"getFirstShown",
"(",
")",
"{",
"$",
"firstShown",
"=",
"$",
"this",
"->",
"getGridPagerState",
"(",
")",
"->",
"firstShown",
"?",
":",
"1",
";",
"// Prevent visiting a page with an offset higher than the total number of items",
"if",
"(",
"$",
... | Get the first shown record number
@return int | [
"Get",
"the",
"first",
"shown",
"record",
"number"
] | 176922303e8fa27b9b52b68b635b58d09e0a0ec3 | https://github.com/symbiote/silverstripe-gridfieldextensions/blob/176922303e8fa27b9b52b68b635b58d09e0a0ec3/src/GridFieldConfigurablePaginator.php#L78-L86 | train |
symbiote/silverstripe-gridfieldextensions | src/GridFieldConfigurablePaginator.php | GridFieldConfigurablePaginator.setPageSizes | public function setPageSizes(array $pageSizes)
{
$this->pageSizes = $pageSizes;
// Reset items per page
$this->setItemsPerPage(current($pageSizes));
return $this;
} | php | public function setPageSizes(array $pageSizes)
{
$this->pageSizes = $pageSizes;
// Reset items per page
$this->setItemsPerPage(current($pageSizes));
return $this;
} | [
"public",
"function",
"setPageSizes",
"(",
"array",
"$",
"pageSizes",
")",
"{",
"$",
"this",
"->",
"pageSizes",
"=",
"$",
"pageSizes",
";",
"// Reset items per page",
"$",
"this",
"->",
"setItemsPerPage",
"(",
"current",
"(",
"$",
"pageSizes",
")",
")",
";",... | Set the page sizes to use in the "Show x" dropdown
@param array $pageSizes
@return $this | [
"Set",
"the",
"page",
"sizes",
"to",
"use",
"in",
"the",
"Show",
"x",
"dropdown"
] | 176922303e8fa27b9b52b68b635b58d09e0a0ec3 | https://github.com/symbiote/silverstripe-gridfieldextensions/blob/176922303e8fa27b9b52b68b635b58d09e0a0ec3/src/GridFieldConfigurablePaginator.php#L169-L177 | train |
symbiote/silverstripe-gridfieldextensions | src/GridFieldConfigurablePaginator.php | GridFieldConfigurablePaginator.getPageSizesAsList | public function getPageSizesAsList()
{
$pageSizes = ArrayList::create();
$perPage = $this->getItemsPerPage();
foreach ($this->getPageSizes() as $pageSize) {
$pageSizes->push(array(
'Size' => $pageSize,
'Selected' => $pageSize == $perPage
));
}
return $pageSizes;
} | php | public function getPageSizesAsList()
{
$pageSizes = ArrayList::create();
$perPage = $this->getItemsPerPage();
foreach ($this->getPageSizes() as $pageSize) {
$pageSizes->push(array(
'Size' => $pageSize,
'Selected' => $pageSize == $perPage
));
}
return $pageSizes;
} | [
"public",
"function",
"getPageSizesAsList",
"(",
")",
"{",
"$",
"pageSizes",
"=",
"ArrayList",
"::",
"create",
"(",
")",
";",
"$",
"perPage",
"=",
"$",
"this",
"->",
"getItemsPerPage",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getPageSizes",
"("... | Gets a list of page sizes for use in templates as a dropdown
@return ArrayList | [
"Gets",
"a",
"list",
"of",
"page",
"sizes",
"for",
"use",
"in",
"templates",
"as",
"a",
"dropdown"
] | 176922303e8fa27b9b52b68b635b58d09e0a0ec3 | https://github.com/symbiote/silverstripe-gridfieldextensions/blob/176922303e8fa27b9b52b68b635b58d09e0a0ec3/src/GridFieldConfigurablePaginator.php#L194-L205 | train |
symbiote/silverstripe-gridfieldextensions | src/GridFieldConfigurablePaginator.php | GridFieldConfigurablePaginator.getTemplateParameters | public function getTemplateParameters(GridField $gridField)
{
$state = $this->getGridPagerState();
if (is_numeric($state->pageSize)) {
$this->setItemsPerPage($state->pageSize);
}
$arguments = $this->getPagerArguments();
// Figure out which page and record range we're on
if (!$arguments['total-rows']) {
return null;
}
// Define a list of the FormActions that should be generated for pager controls (see getPagerActions())
$controls = array(
'first' => array(
'title' => 'First',
'args' => array('first-shown' => 1),
'extra-class' => 'btn btn-secondary btn--hide-text btn-sm font-icon-angle-double-left '
. 'ss-gridfield-pagination-action ss-gridfield-firstpage',
'disable-previous' => ($this->getCurrentPage() == 1)
),
'prev' => array(
'title' => 'Previous',
'args' => array('first-shown' => $arguments['first-shown'] - $this->getItemsPerPage()),
'extra-class' => 'btn btn-secondary btn--hide-text btn-sm font-icon-angle-left '
. 'ss-gridfield-pagination-action ss-gridfield-previouspage',
'disable-previous' => ($this->getCurrentPage() == 1)
),
'next' => array(
'title' => 'Next',
'args' => array('first-shown' => $arguments['first-shown'] + $this->getItemsPerPage()),
'extra-class' => 'btn btn-secondary btn--hide-text btn-sm font-icon-angle-right '
.'ss-gridfield-pagination-action ss-gridfield-nextpage',
'disable-next' => ($this->getCurrentPage() == $arguments['total-pages'])
),
'last' => array(
'title' => 'Last',
'args' => array('first-shown' => ($this->getTotalPages() - 1) * $this->getItemsPerPage() + 1),
'extra-class' => 'btn btn-secondary btn--hide-text btn-sm font-icon-angle-double-right '
. 'ss-gridfield-pagination-action ss-gridfield-lastpage',
'disable-next' => ($this->getCurrentPage() == $arguments['total-pages'])
),
'pagesize' => array(
'title' => 'Page Size',
'args' => array('first-shown' => $arguments['first-shown']),
'extra-class' => 'ss-gridfield-pagination-action ss-gridfield-pagesize-submit'
),
);
if ($controls['prev']['args']['first-shown'] < 1) {
$controls['prev']['args']['first-shown'] = 1;
}
$actions = $this->getPagerActions($controls, $gridField);
// Render in template
return ArrayData::create(array(
'OnlyOnePage' => ($arguments['total-pages'] == 1),
'FirstPage' => $actions['first'],
'PreviousPage' => $actions['prev'],
'NextPage' => $actions['next'],
'LastPage' => $actions['last'],
'PageSizesSubmit' => $actions['pagesize'],
'CurrentPageNum' => $this->getCurrentPage(),
'NumPages' => $arguments['total-pages'],
'FirstShownRecord' => $arguments['first-shown'],
'LastShownRecord' => $arguments['last-shown'],
'NumRecords' => $arguments['total-rows'],
'PageSizes' => $this->getPageSizesAsList(),
'PageSizesName' => $gridField->getName() . '[page-sizes]',
));
} | php | public function getTemplateParameters(GridField $gridField)
{
$state = $this->getGridPagerState();
if (is_numeric($state->pageSize)) {
$this->setItemsPerPage($state->pageSize);
}
$arguments = $this->getPagerArguments();
// Figure out which page and record range we're on
if (!$arguments['total-rows']) {
return null;
}
// Define a list of the FormActions that should be generated for pager controls (see getPagerActions())
$controls = array(
'first' => array(
'title' => 'First',
'args' => array('first-shown' => 1),
'extra-class' => 'btn btn-secondary btn--hide-text btn-sm font-icon-angle-double-left '
. 'ss-gridfield-pagination-action ss-gridfield-firstpage',
'disable-previous' => ($this->getCurrentPage() == 1)
),
'prev' => array(
'title' => 'Previous',
'args' => array('first-shown' => $arguments['first-shown'] - $this->getItemsPerPage()),
'extra-class' => 'btn btn-secondary btn--hide-text btn-sm font-icon-angle-left '
. 'ss-gridfield-pagination-action ss-gridfield-previouspage',
'disable-previous' => ($this->getCurrentPage() == 1)
),
'next' => array(
'title' => 'Next',
'args' => array('first-shown' => $arguments['first-shown'] + $this->getItemsPerPage()),
'extra-class' => 'btn btn-secondary btn--hide-text btn-sm font-icon-angle-right '
.'ss-gridfield-pagination-action ss-gridfield-nextpage',
'disable-next' => ($this->getCurrentPage() == $arguments['total-pages'])
),
'last' => array(
'title' => 'Last',
'args' => array('first-shown' => ($this->getTotalPages() - 1) * $this->getItemsPerPage() + 1),
'extra-class' => 'btn btn-secondary btn--hide-text btn-sm font-icon-angle-double-right '
. 'ss-gridfield-pagination-action ss-gridfield-lastpage',
'disable-next' => ($this->getCurrentPage() == $arguments['total-pages'])
),
'pagesize' => array(
'title' => 'Page Size',
'args' => array('first-shown' => $arguments['first-shown']),
'extra-class' => 'ss-gridfield-pagination-action ss-gridfield-pagesize-submit'
),
);
if ($controls['prev']['args']['first-shown'] < 1) {
$controls['prev']['args']['first-shown'] = 1;
}
$actions = $this->getPagerActions($controls, $gridField);
// Render in template
return ArrayData::create(array(
'OnlyOnePage' => ($arguments['total-pages'] == 1),
'FirstPage' => $actions['first'],
'PreviousPage' => $actions['prev'],
'NextPage' => $actions['next'],
'LastPage' => $actions['last'],
'PageSizesSubmit' => $actions['pagesize'],
'CurrentPageNum' => $this->getCurrentPage(),
'NumPages' => $arguments['total-pages'],
'FirstShownRecord' => $arguments['first-shown'],
'LastShownRecord' => $arguments['last-shown'],
'NumRecords' => $arguments['total-rows'],
'PageSizes' => $this->getPageSizesAsList(),
'PageSizesName' => $gridField->getName() . '[page-sizes]',
));
} | [
"public",
"function",
"getTemplateParameters",
"(",
"GridField",
"$",
"gridField",
")",
"{",
"$",
"state",
"=",
"$",
"this",
"->",
"getGridPagerState",
"(",
")",
";",
"if",
"(",
"is_numeric",
"(",
"$",
"state",
"->",
"pageSize",
")",
")",
"{",
"$",
"this... | Add the configurable page size options to the template data
{@inheritDoc}
@param GridField $gridField
@return ArrayData|null | [
"Add",
"the",
"configurable",
"page",
"size",
"options",
"to",
"the",
"template",
"data"
] | 176922303e8fa27b9b52b68b635b58d09e0a0ec3 | https://github.com/symbiote/silverstripe-gridfieldextensions/blob/176922303e8fa27b9b52b68b635b58d09e0a0ec3/src/GridFieldConfigurablePaginator.php#L274-L346 | train |
symbiote/silverstripe-gridfieldextensions | src/GridFieldConfigurablePaginator.php | GridFieldConfigurablePaginator.getPagerActions | public function getPagerActions(array $controls, GridField $gridField)
{
$actions = array();
foreach ($controls as $key => $arguments) {
$action = GridField_FormAction::create(
$gridField,
'pagination_' . $key,
$arguments['title'],
'paginate',
$arguments['args']
);
if (isset($arguments['extra-class'])) {
$action->addExtraClass($arguments['extra-class']);
}
if (isset($arguments['disable-previous']) && $arguments['disable-previous']) {
$action = $action->performDisabledTransformation();
} elseif (isset($arguments['disable-next']) && $arguments['disable-next']) {
$action = $action->performDisabledTransformation();
}
$actions[$key] = $action;
}
return $actions;
} | php | public function getPagerActions(array $controls, GridField $gridField)
{
$actions = array();
foreach ($controls as $key => $arguments) {
$action = GridField_FormAction::create(
$gridField,
'pagination_' . $key,
$arguments['title'],
'paginate',
$arguments['args']
);
if (isset($arguments['extra-class'])) {
$action->addExtraClass($arguments['extra-class']);
}
if (isset($arguments['disable-previous']) && $arguments['disable-previous']) {
$action = $action->performDisabledTransformation();
} elseif (isset($arguments['disable-next']) && $arguments['disable-next']) {
$action = $action->performDisabledTransformation();
}
$actions[$key] = $action;
}
return $actions;
} | [
"public",
"function",
"getPagerActions",
"(",
"array",
"$",
"controls",
",",
"GridField",
"$",
"gridField",
")",
"{",
"$",
"actions",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"controls",
"as",
"$",
"key",
"=>",
"$",
"arguments",
")",
"{",
"$",... | Returns FormActions for each of the pagination actions, in an array
@param array $controls
@param GridField $gridField
@return GridField_FormAction[] | [
"Returns",
"FormActions",
"for",
"each",
"of",
"the",
"pagination",
"actions",
"in",
"an",
"array"
] | 176922303e8fa27b9b52b68b635b58d09e0a0ec3 | https://github.com/symbiote/silverstripe-gridfieldextensions/blob/176922303e8fa27b9b52b68b635b58d09e0a0ec3/src/GridFieldConfigurablePaginator.php#L388-L415 | train |
symbiote/silverstripe-gridfieldextensions | src/GridFieldConfigurablePaginator.php | GridFieldConfigurablePaginator.getGridPagerState | protected function getGridPagerState(GridField $gridField = null)
{
if (!$this->gridFieldState) {
$state = $this->getGridField()->State->GridFieldConfigurablePaginator;
// SS 3.1 compatibility (missing __call)
if (is_object($state->firstShown)) {
$state->firstShown = 1;
}
if (is_object($state->pageSize)) {
$state->pageSize = $this->getItemsPerPage();
}
// Handle free input in the page number field
$parentState = $this->getGridField()->State->GridFieldPaginator;
if (is_object($parentState->currentPage)) {
$parentState->currentPage = 0;
}
if ($parentState->currentPage >= 1) {
$state->firstShown = ($parentState->currentPage - 1) * $this->getItemsPerPage() + 1;
$parentState->currentPage = null;
}
$this->gridFieldState = $state;
}
return $this->gridFieldState;
} | php | protected function getGridPagerState(GridField $gridField = null)
{
if (!$this->gridFieldState) {
$state = $this->getGridField()->State->GridFieldConfigurablePaginator;
// SS 3.1 compatibility (missing __call)
if (is_object($state->firstShown)) {
$state->firstShown = 1;
}
if (is_object($state->pageSize)) {
$state->pageSize = $this->getItemsPerPage();
}
// Handle free input in the page number field
$parentState = $this->getGridField()->State->GridFieldPaginator;
if (is_object($parentState->currentPage)) {
$parentState->currentPage = 0;
}
if ($parentState->currentPage >= 1) {
$state->firstShown = ($parentState->currentPage - 1) * $this->getItemsPerPage() + 1;
$parentState->currentPage = null;
}
$this->gridFieldState = $state;
}
return $this->gridFieldState;
} | [
"protected",
"function",
"getGridPagerState",
"(",
"GridField",
"$",
"gridField",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"gridFieldState",
")",
"{",
"$",
"state",
"=",
"$",
"this",
"->",
"getGridField",
"(",
")",
"->",
"State",
"->",
... | Gets the state from the current request's GridField and sets some default values on it
@param GridField $gridField Not used, but present for parent method compatibility
@return GridState_Data | [
"Gets",
"the",
"state",
"from",
"the",
"current",
"request",
"s",
"GridField",
"and",
"sets",
"some",
"default",
"values",
"on",
"it"
] | 176922303e8fa27b9b52b68b635b58d09e0a0ec3 | https://github.com/symbiote/silverstripe-gridfieldextensions/blob/176922303e8fa27b9b52b68b635b58d09e0a0ec3/src/GridFieldConfigurablePaginator.php#L428-L456 | train |
auth0/jwt-auth-bundle | src/Security/Auth0Service.php | Auth0Service.decodeJWT | public function decodeJWT($encToken)
{
$config = [
// The api_identifier setting could come through as an array or a string.
'valid_audiences' => is_array($this->api_identifier) ? $this->api_identifier : [$this->api_identifier],
'client_secret' => $this->api_secret,
'authorized_iss' => [$this->authorized_issuer],
'supported_algs' => $this->supported_algs,
'secret_base64_encoded' => $this->secret_base64_encoded
];
if (null !== $this->cache) {
$config['cache'] = $this->cache;
}
$verifier = new JWTVerifier($config);
return $verifier->verifyAndDecode($encToken);
} | php | public function decodeJWT($encToken)
{
$config = [
// The api_identifier setting could come through as an array or a string.
'valid_audiences' => is_array($this->api_identifier) ? $this->api_identifier : [$this->api_identifier],
'client_secret' => $this->api_secret,
'authorized_iss' => [$this->authorized_issuer],
'supported_algs' => $this->supported_algs,
'secret_base64_encoded' => $this->secret_base64_encoded
];
if (null !== $this->cache) {
$config['cache'] = $this->cache;
}
$verifier = new JWTVerifier($config);
return $verifier->verifyAndDecode($encToken);
} | [
"public",
"function",
"decodeJWT",
"(",
"$",
"encToken",
")",
"{",
"$",
"config",
"=",
"[",
"// The api_identifier setting could come through as an array or a string.",
"'valid_audiences'",
"=>",
"is_array",
"(",
"$",
"this",
"->",
"api_identifier",
")",
"?",
"$",
"th... | Decodes the JWT and validate it
@return \stdClass | [
"Decodes",
"the",
"JWT",
"and",
"validate",
"it"
] | 7969686f06fc61d1858f217085813d769bf85894 | https://github.com/auth0/jwt-auth-bundle/blob/7969686f06fc61d1858f217085813d769bf85894/src/Security/Auth0Service.php#L70-L88 | train |
TYPO3/styleguide | Classes/Controller/StyleguideController.php | StyleguideController.initializeView | protected function initializeView(ViewInterface $view)
{
parent::initializeView($view);
// Early return for actions without valid view like tcaCreateAction or tcaDeleteAction
if (!($this->view instanceof BackendTemplateView)) {
return;
}
// Hand over flash message queue to module template
$this->view->getModuleTemplate()->setFlashMessageQueue($this->controllerContext->getFlashMessageQueue());
$this->view->assign('actions', ['index', 'typography', 'tca', 'trees', 'tab', 'tables', 'avatar', 'buttons',
'infobox', 'flashMessages', 'icons', 'debug', 'helpers', 'modal']);
$this->view->assign('currentAction', $this->request->getControllerActionName());
// Shortcut button
$buttonBar = $this->view->getModuleTemplate()->getDocHeaderComponent()->getButtonBar();
$getVars = $this->request->getArguments();
$extensionName = $this->request->getControllerExtensionName();
$moduleName = $this->request->getPluginName();
if (count($getVars) === 0) {
$modulePrefix = strtolower('tx_' . $extensionName . '_' . $moduleName);
$getVars = array('id', 'M', $modulePrefix);
}
$shortcutButton = $buttonBar->makeShortcutButton()
->setModuleName($moduleName)
->setGetVariables($getVars);
$buttonBar->addButton($shortcutButton);
} | php | protected function initializeView(ViewInterface $view)
{
parent::initializeView($view);
// Early return for actions without valid view like tcaCreateAction or tcaDeleteAction
if (!($this->view instanceof BackendTemplateView)) {
return;
}
// Hand over flash message queue to module template
$this->view->getModuleTemplate()->setFlashMessageQueue($this->controllerContext->getFlashMessageQueue());
$this->view->assign('actions', ['index', 'typography', 'tca', 'trees', 'tab', 'tables', 'avatar', 'buttons',
'infobox', 'flashMessages', 'icons', 'debug', 'helpers', 'modal']);
$this->view->assign('currentAction', $this->request->getControllerActionName());
// Shortcut button
$buttonBar = $this->view->getModuleTemplate()->getDocHeaderComponent()->getButtonBar();
$getVars = $this->request->getArguments();
$extensionName = $this->request->getControllerExtensionName();
$moduleName = $this->request->getPluginName();
if (count($getVars) === 0) {
$modulePrefix = strtolower('tx_' . $extensionName . '_' . $moduleName);
$getVars = array('id', 'M', $modulePrefix);
}
$shortcutButton = $buttonBar->makeShortcutButton()
->setModuleName($moduleName)
->setGetVariables($getVars);
$buttonBar->addButton($shortcutButton);
} | [
"protected",
"function",
"initializeView",
"(",
"ViewInterface",
"$",
"view",
")",
"{",
"parent",
"::",
"initializeView",
"(",
"$",
"view",
")",
";",
"// Early return for actions without valid view like tcaCreateAction or tcaDeleteAction",
"if",
"(",
"!",
"(",
"$",
"thi... | Method is called before each action and sets up the doc header.
@param ViewInterface $view | [
"Method",
"is",
"called",
"before",
"each",
"action",
"and",
"sets",
"up",
"the",
"doc",
"header",
"."
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/Controller/StyleguideController.php#L60-L88 | train |
TYPO3/styleguide | Classes/Controller/StyleguideController.php | StyleguideController.tcaCreateAction | public function tcaCreateAction()
{
/** @var Generator $generator */
$generator = GeneralUtility::makeInstance(Generator::class);
$generator->create();
// Tell something was done here
$this->addFlashMessage(
LocalizationUtility::translate($this->languageFilePrefix . 'tcaCreateActionOkBody', 'styleguide'),
LocalizationUtility::translate($this->languageFilePrefix . 'tcaCreateActionOkTitle', 'styleguide')
);
// And redirect to display action
$this->forward('tca');
} | php | public function tcaCreateAction()
{
/** @var Generator $generator */
$generator = GeneralUtility::makeInstance(Generator::class);
$generator->create();
// Tell something was done here
$this->addFlashMessage(
LocalizationUtility::translate($this->languageFilePrefix . 'tcaCreateActionOkBody', 'styleguide'),
LocalizationUtility::translate($this->languageFilePrefix . 'tcaCreateActionOkTitle', 'styleguide')
);
// And redirect to display action
$this->forward('tca');
} | [
"public",
"function",
"tcaCreateAction",
"(",
")",
"{",
"/** @var Generator $generator */",
"$",
"generator",
"=",
"GeneralUtility",
"::",
"makeInstance",
"(",
"Generator",
"::",
"class",
")",
";",
"$",
"generator",
"->",
"create",
"(",
")",
";",
"// Tell somethin... | TCA create default data action | [
"TCA",
"create",
"default",
"data",
"action"
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/Controller/StyleguideController.php#L135-L147 | train |
TYPO3/styleguide | Classes/Controller/StyleguideController.php | StyleguideController.tcaDeleteAction | public function tcaDeleteAction()
{
/** @var Generator $generator */
$generator = GeneralUtility::makeInstance(Generator::class);
$generator->delete();
// Tell something was done here
$this->addFlashMessage(
LocalizationUtility::translate($this->languageFilePrefix . 'tcaDeleteActionOkBody', 'styleguide'),
LocalizationUtility::translate($this->languageFilePrefix . 'tcaDeleteActionOkTitle', 'styleguide')
);
// And redirect to display action
$this->forward('tca');
} | php | public function tcaDeleteAction()
{
/** @var Generator $generator */
$generator = GeneralUtility::makeInstance(Generator::class);
$generator->delete();
// Tell something was done here
$this->addFlashMessage(
LocalizationUtility::translate($this->languageFilePrefix . 'tcaDeleteActionOkBody', 'styleguide'),
LocalizationUtility::translate($this->languageFilePrefix . 'tcaDeleteActionOkTitle', 'styleguide')
);
// And redirect to display action
$this->forward('tca');
} | [
"public",
"function",
"tcaDeleteAction",
"(",
")",
"{",
"/** @var Generator $generator */",
"$",
"generator",
"=",
"GeneralUtility",
"::",
"makeInstance",
"(",
"Generator",
"::",
"class",
")",
";",
"$",
"generator",
"->",
"delete",
"(",
")",
";",
"// Tell somethin... | TCA delete default data action | [
"TCA",
"delete",
"default",
"data",
"action"
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/Controller/StyleguideController.php#L152-L164 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/FieldGenerator/TypeInlineExpandsingle.php | TypeInlineExpandsingle.generate | public function generate(array $data): string
{
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
$connection = $connectionPool->getConnectionForTable('tx_styleguide_inline_expandsingle_child');
$childRowsToCreate = 3;
for ($i = 0; $i < $childRowsToCreate; $i++) {
// Insert an empty row again to have the uid already. This is useful for
// possible further inline that may be attached to this child.
$childFieldValues = [
'pid' => $data['fieldValues']['pid'],
'parentid' => $data['fieldValues']['uid'],
'parenttable' => $data['tableName'],
];
$connection->insert(
'tx_styleguide_inline_expandsingle_child',
$childFieldValues
);
$childFieldValues['uid'] = $connection->lastInsertId('tx_styleguide_inline_expandsingle_child');
$recordData = GeneralUtility::makeInstance(RecordData::class);
$childFieldValues = $recordData->generate('tx_styleguide_inline_expandsingle_child', $childFieldValues);
$connection->update(
'tx_styleguide_inline_expandsingle_child',
$childFieldValues,
[ 'uid' => $childFieldValues['uid'] ]
);
}
return (string)$childRowsToCreate;
} | php | public function generate(array $data): string
{
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
$connection = $connectionPool->getConnectionForTable('tx_styleguide_inline_expandsingle_child');
$childRowsToCreate = 3;
for ($i = 0; $i < $childRowsToCreate; $i++) {
// Insert an empty row again to have the uid already. This is useful for
// possible further inline that may be attached to this child.
$childFieldValues = [
'pid' => $data['fieldValues']['pid'],
'parentid' => $data['fieldValues']['uid'],
'parenttable' => $data['tableName'],
];
$connection->insert(
'tx_styleguide_inline_expandsingle_child',
$childFieldValues
);
$childFieldValues['uid'] = $connection->lastInsertId('tx_styleguide_inline_expandsingle_child');
$recordData = GeneralUtility::makeInstance(RecordData::class);
$childFieldValues = $recordData->generate('tx_styleguide_inline_expandsingle_child', $childFieldValues);
$connection->update(
'tx_styleguide_inline_expandsingle_child',
$childFieldValues,
[ 'uid' => $childFieldValues['uid'] ]
);
}
return (string)$childRowsToCreate;
} | [
"public",
"function",
"generate",
"(",
"array",
"$",
"data",
")",
":",
"string",
"{",
"$",
"connectionPool",
"=",
"GeneralUtility",
"::",
"makeInstance",
"(",
"ConnectionPool",
"::",
"class",
")",
";",
"$",
"connection",
"=",
"$",
"connectionPool",
"->",
"ge... | Generate 3 child rows
@param array $data
@return string | [
"Generate",
"3",
"child",
"rows"
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/FieldGenerator/TypeInlineExpandsingle.php#L62-L89 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/TableHandler/InlineMnSymmetric.php | InlineMnSymmetric.handle | public function handle(string $tableName)
{
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
$recordFinder = GeneralUtility::makeInstance(RecordFinder::class);
$pidOfMainTable = $recordFinder->findPidOfMainTableRecord($tableName);
$recordData = GeneralUtility::makeInstance(RecordData::class);
$isFirst = true;
$numberOfRelationsForFirstRecord = 2;
$relationUids = [];
$uidOfFirstRecord = null;
for ($i = 0; $i < 4; $i++) {
$fieldValues = [
'pid' => $pidOfMainTable,
];
$connection = $connectionPool->getConnectionForTable($tableName);
$connection->insert($tableName, $fieldValues);
$fieldValues['uid'] = $connection->lastInsertId($tableName);
if ($isFirst) {
$fieldValues['branches'] = $numberOfRelationsForFirstRecord;
$uidOfFirstRecord = $fieldValues['uid'];
}
$fieldValues = $recordData->generate($tableName, $fieldValues);
$connection->update(
$tableName,
$fieldValues,
[ 'uid' => $fieldValues['uid'] ]
);
$this->generateTranslatedRecords($tableName, $fieldValues);
if (!$isFirst && count($relationUids) < $numberOfRelationsForFirstRecord) {
$relationUids[] = $fieldValues['uid'];
}
$isFirst = false;
}
foreach ($relationUids as $uid) {
$mmFieldValues = [
'pid' => $pidOfMainTable,
'hotelid' => $uidOfFirstRecord,
'branchid' => $uid,
];
$connection = $connectionPool->getConnectionForTable('tx_styleguide_inline_mnsymmetric_mm');
$connection->insert(
'tx_styleguide_inline_mnsymmetric_mm',
$mmFieldValues
);
}
} | php | public function handle(string $tableName)
{
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
$recordFinder = GeneralUtility::makeInstance(RecordFinder::class);
$pidOfMainTable = $recordFinder->findPidOfMainTableRecord($tableName);
$recordData = GeneralUtility::makeInstance(RecordData::class);
$isFirst = true;
$numberOfRelationsForFirstRecord = 2;
$relationUids = [];
$uidOfFirstRecord = null;
for ($i = 0; $i < 4; $i++) {
$fieldValues = [
'pid' => $pidOfMainTable,
];
$connection = $connectionPool->getConnectionForTable($tableName);
$connection->insert($tableName, $fieldValues);
$fieldValues['uid'] = $connection->lastInsertId($tableName);
if ($isFirst) {
$fieldValues['branches'] = $numberOfRelationsForFirstRecord;
$uidOfFirstRecord = $fieldValues['uid'];
}
$fieldValues = $recordData->generate($tableName, $fieldValues);
$connection->update(
$tableName,
$fieldValues,
[ 'uid' => $fieldValues['uid'] ]
);
$this->generateTranslatedRecords($tableName, $fieldValues);
if (!$isFirst && count($relationUids) < $numberOfRelationsForFirstRecord) {
$relationUids[] = $fieldValues['uid'];
}
$isFirst = false;
}
foreach ($relationUids as $uid) {
$mmFieldValues = [
'pid' => $pidOfMainTable,
'hotelid' => $uidOfFirstRecord,
'branchid' => $uid,
];
$connection = $connectionPool->getConnectionForTable('tx_styleguide_inline_mnsymmetric_mm');
$connection->insert(
'tx_styleguide_inline_mnsymmetric_mm',
$mmFieldValues
);
}
} | [
"public",
"function",
"handle",
"(",
"string",
"$",
"tableName",
")",
"{",
"$",
"connectionPool",
"=",
"GeneralUtility",
"::",
"makeInstance",
"(",
"ConnectionPool",
"::",
"class",
")",
";",
"$",
"recordFinder",
"=",
"GeneralUtility",
"::",
"makeInstance",
"(",
... | Create 4 rows, add row 2 and 3 as branch to row 1
@param string $tableName
@return string | [
"Create",
"4",
"rows",
"add",
"row",
"2",
"and",
"3",
"as",
"branch",
"to",
"row",
"1"
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/TableHandler/InlineMnSymmetric.php#L40-L91 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/TableHandler/InlineMn.php | InlineMn.handle | public function handle(string $tableName)
{
$recordFinder = GeneralUtility::makeInstance(RecordFinder::class);
$pidOfMainTable = $recordFinder->findPidOfMainTableRecord($tableName);
$recordData = GeneralUtility::makeInstance(RecordData::class);
$childRelationUids = [];
$numberOfChildRelationsToCreate = 2;
$numberOfChildRows = 4;
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
for ($i = 0; $i < $numberOfChildRows; $i ++) {
$fieldValues = [
'pid' => $pidOfMainTable,
];
$connection = $connectionPool->getConnectionForTable('tx_styleguide_inline_mn_child');
$connection->insert('tx_styleguide_inline_mn_child', $fieldValues);
$fieldValues['uid'] = $connection->lastInsertId('tx_styleguide_inline_mn_child');
if (count($childRelationUids) < $numberOfChildRelationsToCreate) {
$childRelationUids[] = $fieldValues['uid'];
}
$fieldValues = $recordData->generate('tx_styleguide_inline_mn_child', $fieldValues);
$connection->update(
'tx_styleguide_inline_mn_child',
$fieldValues,
[ 'uid' => (int)$fieldValues['uid'] ]
);
}
$fieldValues = [
'pid' => $pidOfMainTable,
'inline_1' => $numberOfChildRelationsToCreate,
];
$connection = $connectionPool->getConnectionForTable($tableName);
$connection->insert($tableName, $fieldValues);
$parentid = $fieldValues['uid'] = $connection->lastInsertId($tableName);
$fieldValues = $recordData->generate($tableName, $fieldValues);
$connection->update(
$tableName,
$fieldValues,
[ 'uid' => (int)$fieldValues['uid'] ]
);
$this->generateTranslatedRecords($tableName, $fieldValues);
foreach ($childRelationUids as $uid) {
$mmFieldValues = [
'pid' => $pidOfMainTable,
'parentid' => $parentid,
'childid' => $uid,
];
$connection = $connectionPool->getConnectionForTable('tx_styleguide_inline_mn_mm');
$connection->insert('tx_styleguide_inline_mn_mm', $mmFieldValues);
}
} | php | public function handle(string $tableName)
{
$recordFinder = GeneralUtility::makeInstance(RecordFinder::class);
$pidOfMainTable = $recordFinder->findPidOfMainTableRecord($tableName);
$recordData = GeneralUtility::makeInstance(RecordData::class);
$childRelationUids = [];
$numberOfChildRelationsToCreate = 2;
$numberOfChildRows = 4;
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
for ($i = 0; $i < $numberOfChildRows; $i ++) {
$fieldValues = [
'pid' => $pidOfMainTable,
];
$connection = $connectionPool->getConnectionForTable('tx_styleguide_inline_mn_child');
$connection->insert('tx_styleguide_inline_mn_child', $fieldValues);
$fieldValues['uid'] = $connection->lastInsertId('tx_styleguide_inline_mn_child');
if (count($childRelationUids) < $numberOfChildRelationsToCreate) {
$childRelationUids[] = $fieldValues['uid'];
}
$fieldValues = $recordData->generate('tx_styleguide_inline_mn_child', $fieldValues);
$connection->update(
'tx_styleguide_inline_mn_child',
$fieldValues,
[ 'uid' => (int)$fieldValues['uid'] ]
);
}
$fieldValues = [
'pid' => $pidOfMainTable,
'inline_1' => $numberOfChildRelationsToCreate,
];
$connection = $connectionPool->getConnectionForTable($tableName);
$connection->insert($tableName, $fieldValues);
$parentid = $fieldValues['uid'] = $connection->lastInsertId($tableName);
$fieldValues = $recordData->generate($tableName, $fieldValues);
$connection->update(
$tableName,
$fieldValues,
[ 'uid' => (int)$fieldValues['uid'] ]
);
$this->generateTranslatedRecords($tableName, $fieldValues);
foreach ($childRelationUids as $uid) {
$mmFieldValues = [
'pid' => $pidOfMainTable,
'parentid' => $parentid,
'childid' => $uid,
];
$connection = $connectionPool->getConnectionForTable('tx_styleguide_inline_mn_mm');
$connection->insert('tx_styleguide_inline_mn_mm', $mmFieldValues);
}
} | [
"public",
"function",
"handle",
"(",
"string",
"$",
"tableName",
")",
"{",
"$",
"recordFinder",
"=",
"GeneralUtility",
"::",
"makeInstance",
"(",
"RecordFinder",
"::",
"class",
")",
";",
"$",
"pidOfMainTable",
"=",
"$",
"recordFinder",
"->",
"findPidOfMainTableR... | Create 1 main row, 4 child child rows, add 2 child child rows in mn
@param string $tableName
@return string | [
"Create",
"1",
"main",
"row",
"4",
"child",
"child",
"rows",
"add",
"2",
"child",
"child",
"rows",
"in",
"mn"
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/TableHandler/InlineMn.php#L40-L93 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/FieldGenerator/TypeSelect.php | TypeSelect.generate | public function generate(array $data): string
{
$result = [];
if (isset($data['fieldConfig']['config']['items']) && count($data['fieldConfig']['config']['items']) > 1) {
$numberOfItemsToSelect = 1;
if (isset($data['fieldConfig']['config']['minitems'])) {
$numberOfItemsToSelect = $data['fieldConfig']['config']['minitems'];
}
$isFirst = true;
foreach ($data['fieldConfig']['config']['items'] as $item) {
if ($isFirst) {
// Ignore first item
$isFirst = false;
continue;
}
// Ignore divider
if (isset($item[1]) && $item[1] !== '--div--') {
if (count($result) <= $numberOfItemsToSelect) {
$result[] = $item[1];
}
if (count($result) === $numberOfItemsToSelect) {
break;
}
}
}
}
return implode(',', $result);
} | php | public function generate(array $data): string
{
$result = [];
if (isset($data['fieldConfig']['config']['items']) && count($data['fieldConfig']['config']['items']) > 1) {
$numberOfItemsToSelect = 1;
if (isset($data['fieldConfig']['config']['minitems'])) {
$numberOfItemsToSelect = $data['fieldConfig']['config']['minitems'];
}
$isFirst = true;
foreach ($data['fieldConfig']['config']['items'] as $item) {
if ($isFirst) {
// Ignore first item
$isFirst = false;
continue;
}
// Ignore divider
if (isset($item[1]) && $item[1] !== '--div--') {
if (count($result) <= $numberOfItemsToSelect) {
$result[] = $item[1];
}
if (count($result) === $numberOfItemsToSelect) {
break;
}
}
}
}
return implode(',', $result);
} | [
"public",
"function",
"generate",
"(",
"array",
"$",
"data",
")",
":",
"string",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"data",
"[",
"'fieldConfig'",
"]",
"[",
"'config'",
"]",
"[",
"'items'",
"]",
")",
"&&",
"count",... | Selects the second item from a static item list if there are
at least two items.
@param array $data
@return string | [
"Selects",
"the",
"second",
"item",
"from",
"a",
"static",
"item",
"list",
"if",
"there",
"are",
"at",
"least",
"two",
"items",
"."
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/FieldGenerator/TypeSelect.php#L45-L72 | train |
TYPO3/styleguide | Classes/UserFunctions/ExtensionConfiguration/User1.php | User1.user_1 | public function user_1(&$params, &$tsObj)
{
$out = '';
// Params;
$out .= '<pre>';
ob_start();
var_dump($params);
$out .= ob_get_contents();
ob_end_clean();
$out .= '</pre>';
return $out;
} | php | public function user_1(&$params, &$tsObj)
{
$out = '';
// Params;
$out .= '<pre>';
ob_start();
var_dump($params);
$out .= ob_get_contents();
ob_end_clean();
$out .= '</pre>';
return $out;
} | [
"public",
"function",
"user_1",
"(",
"&",
"$",
"params",
",",
"&",
"$",
"tsObj",
")",
"{",
"$",
"out",
"=",
"''",
";",
"// Params;",
"$",
"out",
".=",
"'<pre>'",
";",
"ob_start",
"(",
")",
";",
"var_dump",
"(",
"$",
"params",
")",
";",
"$",
"out"... | Simple user function returning a var_dump of input parameters
@param array $params
@param mixed $tsObj
@return string | [
"Simple",
"user",
"function",
"returning",
"a",
"var_dump",
"of",
"input",
"parameters"
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/UserFunctions/ExtensionConfiguration/User1.php#L29-L42 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/FieldGeneratorResolver.php | FieldGeneratorResolver.resolve | public function resolve(array $data): FieldGeneratorInterface
{
$generator = NULL;
foreach ($this->fieldValueGenerators as $fieldValueGenerator) {
$generator = GeneralUtility::makeInstance($fieldValueGenerator);
if (!$generator instanceof FieldGeneratorInterface) {
throw new Exception(
'Field value generator ' . $fieldValueGenerator . ' must implement FieldGeneratorInterface',
1457693564
);
}
if ($generator->match($data)) {
break;
} else {
$generator = null;
}
}
if (is_null($generator)) {
throw new GeneratorNotFoundException(
'No generator found',
1457873493
);
}
return $generator;
} | php | public function resolve(array $data): FieldGeneratorInterface
{
$generator = NULL;
foreach ($this->fieldValueGenerators as $fieldValueGenerator) {
$generator = GeneralUtility::makeInstance($fieldValueGenerator);
if (!$generator instanceof FieldGeneratorInterface) {
throw new Exception(
'Field value generator ' . $fieldValueGenerator . ' must implement FieldGeneratorInterface',
1457693564
);
}
if ($generator->match($data)) {
break;
} else {
$generator = null;
}
}
if (is_null($generator)) {
throw new GeneratorNotFoundException(
'No generator found',
1457873493
);
}
return $generator;
} | [
"public",
"function",
"resolve",
"(",
"array",
"$",
"data",
")",
":",
"FieldGeneratorInterface",
"{",
"$",
"generator",
"=",
"NULL",
";",
"foreach",
"(",
"$",
"this",
"->",
"fieldValueGenerators",
"as",
"$",
"fieldValueGenerator",
")",
"{",
"$",
"generator",
... | Resolve a generator class and return its instance.
Either returns an instance of FieldGeneratorInterface or throws exception
@param array $data Criteria data
@return FieldGeneratorInterface
@throws GeneratorNotFoundException|Exception | [
"Resolve",
"a",
"generator",
"class",
"and",
"return",
"its",
"instance",
".",
"Either",
"returns",
"an",
"instance",
"of",
"FieldGeneratorInterface",
"or",
"throws",
"exception"
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/FieldGeneratorResolver.php#L119-L143 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/FieldGenerator/TypeInlineUsecombination.php | TypeInlineUsecombination.match | public function match(array $data): bool
{
$match = parent::match($data);
if ($match) {
if ($data['fieldConfig']['config']['foreign_table'] !== 'tx_styleguide_inline_usecombination_mm'
&& $data['fieldConfig']['config']['foreign_table'] !== 'tx_styleguide_inline_usecombinationbox_mm'
) {
$match = false;
}
}
return $match;
} | php | public function match(array $data): bool
{
$match = parent::match($data);
if ($match) {
if ($data['fieldConfig']['config']['foreign_table'] !== 'tx_styleguide_inline_usecombination_mm'
&& $data['fieldConfig']['config']['foreign_table'] !== 'tx_styleguide_inline_usecombinationbox_mm'
) {
$match = false;
}
}
return $match;
} | [
"public",
"function",
"match",
"(",
"array",
"$",
"data",
")",
":",
"bool",
"{",
"$",
"match",
"=",
"parent",
"::",
"match",
"(",
"$",
"data",
")",
";",
"if",
"(",
"$",
"match",
")",
"{",
"if",
"(",
"$",
"data",
"[",
"'fieldConfig'",
"]",
"[",
... | Check for tx_styleguide_inline_usecombination and
tx_styleguide_inline_usecombinationbox table
@param array $data
@return bool | [
"Check",
"for",
"tx_styleguide_inline_usecombination",
"and",
"tx_styleguide_inline_usecombinationbox",
"table"
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/FieldGenerator/TypeInlineUsecombination.php#L52-L63 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/FieldGenerator/TypeInlineUsecombination.php | TypeInlineUsecombination.generate | public function generate(array $data): string
{
if (!isset($GLOBALS['TCA'][$data['fieldConfig']['config']['foreign_table']]['columns']['select_child']['config']['foreign_table'])) {
throw new \RuntimeException(
'mm child table name not found',
1459941569
);
}
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
$childChildTableName = $GLOBALS['TCA'][$data['fieldConfig']['config']['foreign_table']]['columns']['select_child']['config']['foreign_table'];
$numberOfChildChildRowsToCreate = 4;
$uidsOfChildrenToConnect = [];
for ($i = 0; $i < $numberOfChildChildRowsToCreate; $i++) {
// Insert an empty row again to have the uid already. This is useful for
// possible further inline that may be attached to this child.
$childFieldValues = [
'pid' => $data['fieldValues']['pid'],
];
$connection = $connectionPool->getConnectionForTable($childChildTableName);
$connection->insert($childChildTableName, $childFieldValues);
$childFieldValues['uid'] = $connection->lastInsertId($childChildTableName);
if (count($uidsOfChildrenToConnect) < 2) {
$uidsOfChildrenToConnect[] = $childFieldValues['uid'];
}
$recordData = GeneralUtility::makeInstance(RecordData::class);
$childFieldValues = $recordData->generate($childChildTableName, $childFieldValues);
$connection->update(
$childChildTableName,
$childFieldValues,
[ 'uid' => (int)$childFieldValues['uid'] ]
);
}
foreach ($uidsOfChildrenToConnect as $uid) {
$mmFieldValues = [
'pid' => $data['fieldValues']['pid'],
'select_parent' => $data['fieldValues']['uid'],
'select_child' => $uid,
];
$tableName = $data['fieldConfig']['config']['foreign_table'];
$connection = $connectionPool->getConnectionForTable($tableName);
$connection->insert($tableName, $mmFieldValues);
}
return (string)count($uidsOfChildrenToConnect);
} | php | public function generate(array $data): string
{
if (!isset($GLOBALS['TCA'][$data['fieldConfig']['config']['foreign_table']]['columns']['select_child']['config']['foreign_table'])) {
throw new \RuntimeException(
'mm child table name not found',
1459941569
);
}
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
$childChildTableName = $GLOBALS['TCA'][$data['fieldConfig']['config']['foreign_table']]['columns']['select_child']['config']['foreign_table'];
$numberOfChildChildRowsToCreate = 4;
$uidsOfChildrenToConnect = [];
for ($i = 0; $i < $numberOfChildChildRowsToCreate; $i++) {
// Insert an empty row again to have the uid already. This is useful for
// possible further inline that may be attached to this child.
$childFieldValues = [
'pid' => $data['fieldValues']['pid'],
];
$connection = $connectionPool->getConnectionForTable($childChildTableName);
$connection->insert($childChildTableName, $childFieldValues);
$childFieldValues['uid'] = $connection->lastInsertId($childChildTableName);
if (count($uidsOfChildrenToConnect) < 2) {
$uidsOfChildrenToConnect[] = $childFieldValues['uid'];
}
$recordData = GeneralUtility::makeInstance(RecordData::class);
$childFieldValues = $recordData->generate($childChildTableName, $childFieldValues);
$connection->update(
$childChildTableName,
$childFieldValues,
[ 'uid' => (int)$childFieldValues['uid'] ]
);
}
foreach ($uidsOfChildrenToConnect as $uid) {
$mmFieldValues = [
'pid' => $data['fieldValues']['pid'],
'select_parent' => $data['fieldValues']['uid'],
'select_child' => $uid,
];
$tableName = $data['fieldConfig']['config']['foreign_table'];
$connection = $connectionPool->getConnectionForTable($tableName);
$connection->insert($tableName, $mmFieldValues);
}
return (string)count($uidsOfChildrenToConnect);
} | [
"public",
"function",
"generate",
"(",
"array",
"$",
"data",
")",
":",
"string",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"GLOBALS",
"[",
"'TCA'",
"]",
"[",
"$",
"data",
"[",
"'fieldConfig'",
"]",
"[",
"'config'",
"]",
"[",
"'foreign_table'",
"]",
"]"... | Generate 4 child child rows, connect 2 of them in mm table
@param array $data
@return string | [
"Generate",
"4",
"child",
"child",
"rows",
"connect",
"2",
"of",
"them",
"in",
"mm",
"table"
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/FieldGenerator/TypeInlineUsecombination.php#L71-L114 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/FieldGenerator/TypeInline1n.php | TypeInline1n.match | public function match(array $data): bool
{
$result = $this->checkMatchArray($data, $this->matchArray);
if ($result && isset($data['fieldConfig']['config']['foreign_table'])) {
$result = true;
} else {
$result = false;
}
return $result;
} | php | public function match(array $data): bool
{
$result = $this->checkMatchArray($data, $this->matchArray);
if ($result && isset($data['fieldConfig']['config']['foreign_table'])) {
$result = true;
} else {
$result = false;
}
return $result;
} | [
"public",
"function",
"match",
"(",
"array",
"$",
"data",
")",
":",
"bool",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"checkMatchArray",
"(",
"$",
"data",
",",
"$",
"this",
"->",
"matchArray",
")",
";",
"if",
"(",
"$",
"result",
"&&",
"isset",
"(... | Additionally check that "foreign_table" is set to something.
@param array $data
@return bool | [
"Additionally",
"check",
"that",
"foreign_table",
"is",
"set",
"to",
"something",
"."
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/FieldGenerator/TypeInline1n.php#L47-L56 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/Generator.php | Generator.create | public function create()
{
// Add entry page on top level
$newIdOfEntryPage = StringUtility::getUniqueId('NEW');
$data = [
'pages' => [
$newIdOfEntryPage => [
'title' => 'styleguide TCA demo',
'pid' => 0 - $this->getUidOfLastTopLevelPage(),
// Mark this page as entry point
'tx_styleguide_containsdemo' => 'tx_styleguide',
// Have the "globus" icon for this page
'is_siteroot' => 1,
],
],
];
// Add rows of third party tables like be_users and fal records
$this->populateRowsOfThirdPartyTables();
$recordFinder = GeneralUtility::makeInstance(RecordFinder::class);
$sysLanguageStyleguideDemoUids = $recordFinder->findUidsOfDemoLanguages();
// Add a page for each main table below entry page
$mainTables = $this->getListOfStyleguideMainTables();
// Have the first main table inside entry page
$neighborPage = $newIdOfEntryPage;
foreach ($mainTables as $mainTable) {
$newIdOfPage = StringUtility::getUniqueId('NEW');
$data['pages'][$newIdOfPage] = [
'title' => str_replace('_', ' ', substr($mainTable, strlen('tx_styleguide_'))),
'tx_styleguide_containsdemo' => $mainTable,
'hidden' => 0,
'pid' => $neighborPage,
];
if (!empty($sysLanguageStyleguideDemoUids)) {
foreach ($sysLanguageStyleguideDemoUids as $languageUid) {
$newIdOfLocalizedPage = StringUtility::getUniqueId('NEW');
$data['pages'][$newIdOfLocalizedPage] = [
'title' => str_replace('_', ' ', substr($mainTable . " - language " . $languageUid, strlen('tx_styleguide_'))),
'tx_styleguide_containsdemo' => $mainTable,
'hidden' => 0,
'pid' => $neighborPage,
'sys_language_uid' => $languageUid,
'l10n_parent' => $newIdOfPage,
'l10n_source' => $newIdOfPage,
];
}
}
// Have next page after this page
$neighborPage = '-' . $newIdOfPage;
}
// Populate page tree via DataHandler
$dataHandler = GeneralUtility::makeInstance(DataHandler::class);
$dataHandler->start($data, []);
$dataHandler->process_datamap();
BackendUtility::setUpdateSignal('updatePageTree');
// Create data for each main table
foreach ($mainTables as $mainTable) {
$generator = NULL;
foreach ($this->tableHandler as $handlerName) {
$generator = GeneralUtility::makeInstance($handlerName);
if (!$generator instanceof TableHandlerInterface) {
throw new Exception(
'Table handler ' . $handlerName . ' must implement TableHandlerInterface',
1458302830
);
}
if ($generator->match($mainTable)) {
break;
} else {
$generator = null;
}
}
if (is_null($generator)) {
throw new GeneratorNotFoundException(
'No table handler found',
1458302901
);
}
$generator->handle($mainTable);
}
} | php | public function create()
{
// Add entry page on top level
$newIdOfEntryPage = StringUtility::getUniqueId('NEW');
$data = [
'pages' => [
$newIdOfEntryPage => [
'title' => 'styleguide TCA demo',
'pid' => 0 - $this->getUidOfLastTopLevelPage(),
// Mark this page as entry point
'tx_styleguide_containsdemo' => 'tx_styleguide',
// Have the "globus" icon for this page
'is_siteroot' => 1,
],
],
];
// Add rows of third party tables like be_users and fal records
$this->populateRowsOfThirdPartyTables();
$recordFinder = GeneralUtility::makeInstance(RecordFinder::class);
$sysLanguageStyleguideDemoUids = $recordFinder->findUidsOfDemoLanguages();
// Add a page for each main table below entry page
$mainTables = $this->getListOfStyleguideMainTables();
// Have the first main table inside entry page
$neighborPage = $newIdOfEntryPage;
foreach ($mainTables as $mainTable) {
$newIdOfPage = StringUtility::getUniqueId('NEW');
$data['pages'][$newIdOfPage] = [
'title' => str_replace('_', ' ', substr($mainTable, strlen('tx_styleguide_'))),
'tx_styleguide_containsdemo' => $mainTable,
'hidden' => 0,
'pid' => $neighborPage,
];
if (!empty($sysLanguageStyleguideDemoUids)) {
foreach ($sysLanguageStyleguideDemoUids as $languageUid) {
$newIdOfLocalizedPage = StringUtility::getUniqueId('NEW');
$data['pages'][$newIdOfLocalizedPage] = [
'title' => str_replace('_', ' ', substr($mainTable . " - language " . $languageUid, strlen('tx_styleguide_'))),
'tx_styleguide_containsdemo' => $mainTable,
'hidden' => 0,
'pid' => $neighborPage,
'sys_language_uid' => $languageUid,
'l10n_parent' => $newIdOfPage,
'l10n_source' => $newIdOfPage,
];
}
}
// Have next page after this page
$neighborPage = '-' . $newIdOfPage;
}
// Populate page tree via DataHandler
$dataHandler = GeneralUtility::makeInstance(DataHandler::class);
$dataHandler->start($data, []);
$dataHandler->process_datamap();
BackendUtility::setUpdateSignal('updatePageTree');
// Create data for each main table
foreach ($mainTables as $mainTable) {
$generator = NULL;
foreach ($this->tableHandler as $handlerName) {
$generator = GeneralUtility::makeInstance($handlerName);
if (!$generator instanceof TableHandlerInterface) {
throw new Exception(
'Table handler ' . $handlerName . ' must implement TableHandlerInterface',
1458302830
);
}
if ($generator->match($mainTable)) {
break;
} else {
$generator = null;
}
}
if (is_null($generator)) {
throw new GeneratorNotFoundException(
'No table handler found',
1458302901
);
}
$generator->handle($mainTable);
}
} | [
"public",
"function",
"create",
"(",
")",
"{",
"// Add entry page on top level",
"$",
"newIdOfEntryPage",
"=",
"StringUtility",
"::",
"getUniqueId",
"(",
"'NEW'",
")",
";",
"$",
"data",
"=",
"[",
"'pages'",
"=>",
"[",
"$",
"newIdOfEntryPage",
"=>",
"[",
"'titl... | Create a page tree for styleguide records and add records on them.
@throws Exception
@throws GeneratorNotFoundException | [
"Create",
"a",
"page",
"tree",
"for",
"styleguide",
"records",
"and",
"add",
"records",
"on",
"them",
"."
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/Generator.php#L59-L144 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/Generator.php | Generator.delete | public function delete()
{
$recordFinder = GeneralUtility::makeInstance(RecordFinder::class);
$commands = [];
// Delete page tree and all their records on this tree
$topUids = $recordFinder->findUidsOfStyleguideEntryPages();
if (!empty($topUids)) {
foreach ($topUids as $topUid) {
$commands['pages'][(int)$topUid]['delete'] = 1;
}
}
// Delete all the sys_language demo records
$languageUids = $recordFinder->findUidsOfDemoLanguages();
if (!empty($languageUids)) {
foreach ($languageUids as $languageUid) {
$commands['sys_language'][(int)$languageUid]['delete'] = 1;
}
}
// Delete demo users
$demoUserUids = $recordFinder->findUidsOfDemoBeUsers();
if (!empty($demoUserUids)) {
foreach ($demoUserUids as $demoUserUid) {
$commands['be_users'][(int)$demoUserUid]['delete'] = 1;
}
}
// Delete demo groups
$demoGroupUids = $recordFinder->findUidsOfDemoBeGroups();
if (!empty($demoGroupUids)) {
foreach ($demoGroupUids as $demoUserGroup) {
$commands['be_groups'][(int)$demoUserGroup]['delete'] = 1;
}
}
// Do the thing
if (!empty($commands)) {
$dataHandler = GeneralUtility::makeInstance(DataHandler::class);
$dataHandler->deleteTree = true;
$dataHandler->start([], $commands);
$dataHandler->process_cmdmap();
BackendUtility::setUpdateSignal('updatePageTree');
}
// Delete demo images in fileadmin again
$storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
$storage = $storageRepository->findByUid(1);
$folder = $storage->getRootLevelFolder();
try {
$folder = $folder->getSubfolder('styleguide');
$folder->delete(true);
} catch (\InvalidArgumentException $e) {
// No op if folder does not exist
}
} | php | public function delete()
{
$recordFinder = GeneralUtility::makeInstance(RecordFinder::class);
$commands = [];
// Delete page tree and all their records on this tree
$topUids = $recordFinder->findUidsOfStyleguideEntryPages();
if (!empty($topUids)) {
foreach ($topUids as $topUid) {
$commands['pages'][(int)$topUid]['delete'] = 1;
}
}
// Delete all the sys_language demo records
$languageUids = $recordFinder->findUidsOfDemoLanguages();
if (!empty($languageUids)) {
foreach ($languageUids as $languageUid) {
$commands['sys_language'][(int)$languageUid]['delete'] = 1;
}
}
// Delete demo users
$demoUserUids = $recordFinder->findUidsOfDemoBeUsers();
if (!empty($demoUserUids)) {
foreach ($demoUserUids as $demoUserUid) {
$commands['be_users'][(int)$demoUserUid]['delete'] = 1;
}
}
// Delete demo groups
$demoGroupUids = $recordFinder->findUidsOfDemoBeGroups();
if (!empty($demoGroupUids)) {
foreach ($demoGroupUids as $demoUserGroup) {
$commands['be_groups'][(int)$demoUserGroup]['delete'] = 1;
}
}
// Do the thing
if (!empty($commands)) {
$dataHandler = GeneralUtility::makeInstance(DataHandler::class);
$dataHandler->deleteTree = true;
$dataHandler->start([], $commands);
$dataHandler->process_cmdmap();
BackendUtility::setUpdateSignal('updatePageTree');
}
// Delete demo images in fileadmin again
$storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
$storage = $storageRepository->findByUid(1);
$folder = $storage->getRootLevelFolder();
try {
$folder = $folder->getSubfolder('styleguide');
$folder->delete(true);
} catch (\InvalidArgumentException $e) {
// No op if folder does not exist
}
} | [
"public",
"function",
"delete",
"(",
")",
"{",
"$",
"recordFinder",
"=",
"GeneralUtility",
"::",
"makeInstance",
"(",
"RecordFinder",
"::",
"class",
")",
";",
"$",
"commands",
"=",
"[",
"]",
";",
"// Delete page tree and all their records on this tree",
"$",
"topU... | Delete all pages and their records that belong to the
tx_styleguide demo pages
@return void | [
"Delete",
"all",
"pages",
"and",
"their",
"records",
"that",
"belong",
"to",
"the",
"tx_styleguide",
"demo",
"pages"
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/Generator.php#L152-L209 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/Generator.php | Generator.getListOfStyleguideMainTables | protected function getListOfStyleguideMainTables(): array
{
$prefixes = [
'tx_styleguide_',
'tx_styleguide_elements_',
'tx_styleguide_inline_',
];
$result = [];
foreach ($GLOBALS['TCA'] as $tablename => $_) {
if ($tablename === 'tx_styleguide_staticdata') {
continue;
}
foreach ($prefixes as $prefix) {
if (!StringUtility::beginsWith($tablename, $prefix)) {
continue;
}
// See if string after $prefix is only one _ separated segment
$suffix = substr($tablename, strlen($prefix));
$suffixArray = explode('_', $suffix);
if (count($suffixArray) !== 1) {
continue;
}
// Found a main table
$result[] = $tablename;
// No need to scan other prefixes
break;
}
}
// Manual resorting - the "staticdata" table is used by other tables later.
// We resort this on top so it is handled first and other tables can rely on
// created data already. This is a bit hacky but a quick workaround.
array_unshift($result, 'tx_styleguide_staticdata');
return $result;
} | php | protected function getListOfStyleguideMainTables(): array
{
$prefixes = [
'tx_styleguide_',
'tx_styleguide_elements_',
'tx_styleguide_inline_',
];
$result = [];
foreach ($GLOBALS['TCA'] as $tablename => $_) {
if ($tablename === 'tx_styleguide_staticdata') {
continue;
}
foreach ($prefixes as $prefix) {
if (!StringUtility::beginsWith($tablename, $prefix)) {
continue;
}
// See if string after $prefix is only one _ separated segment
$suffix = substr($tablename, strlen($prefix));
$suffixArray = explode('_', $suffix);
if (count($suffixArray) !== 1) {
continue;
}
// Found a main table
$result[] = $tablename;
// No need to scan other prefixes
break;
}
}
// Manual resorting - the "staticdata" table is used by other tables later.
// We resort this on top so it is handled first and other tables can rely on
// created data already. This is a bit hacky but a quick workaround.
array_unshift($result, 'tx_styleguide_staticdata');
return $result;
} | [
"protected",
"function",
"getListOfStyleguideMainTables",
"(",
")",
":",
"array",
"{",
"$",
"prefixes",
"=",
"[",
"'tx_styleguide_'",
",",
"'tx_styleguide_elements_'",
",",
"'tx_styleguide_inline_'",
",",
"]",
";",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"... | List of styleguide "main" pages.
A styleguide table is either a "main" entry table or a "child" table that
belongs to a main table. Each "main" table is located at an own page with all its children.
The difference is a naming thing, styleguide tables have a
"prefix"_"identifier"_"childidentifier" structure.
Example:
prefix = tx_styleguide_inline, identifier = 1n
-> "tx_styleguide_inline_1n" is a "main" table
-> "tx_styleguide_inline_1n1n" is a "child" table
In general the list of prefixes is hard coded. If a specific table name is a concatenation
of a prefix plus a single word, then the table is considered a "main" table, if there are more
than one words after prefix, it is a "child" table.
This method return the list of "main" tables.
@return array | [
"List",
"of",
"styleguide",
"main",
"pages",
"."
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/Generator.php#L331-L367 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/RecordFinder.php | RecordFinder.findUidsOfStyleguideEntryPages | public function findUidsOfStyleguideEntryPages(): array
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
$queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
$rows = $queryBuilder->select('uid')
->from('pages')
->where(
$queryBuilder->expr()->eq(
'pid',
$queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
),
$queryBuilder->expr()->eq(
'tx_styleguide_containsdemo',
$queryBuilder->createNamedParameter('tx_styleguide', \PDO::PARAM_STR)
)
)
->execute()
->fetchAll();
$uids = [];
if (is_array($rows)) {
foreach ($rows as $row) {
$uids[] = (int)$row['uid'];
}
}
return $uids;
} | php | public function findUidsOfStyleguideEntryPages(): array
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
$queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
$rows = $queryBuilder->select('uid')
->from('pages')
->where(
$queryBuilder->expr()->eq(
'pid',
$queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
),
$queryBuilder->expr()->eq(
'tx_styleguide_containsdemo',
$queryBuilder->createNamedParameter('tx_styleguide', \PDO::PARAM_STR)
)
)
->execute()
->fetchAll();
$uids = [];
if (is_array($rows)) {
foreach ($rows as $row) {
$uids[] = (int)$row['uid'];
}
}
return $uids;
} | [
"public",
"function",
"findUidsOfStyleguideEntryPages",
"(",
")",
":",
"array",
"{",
"$",
"queryBuilder",
"=",
"GeneralUtility",
"::",
"makeInstance",
"(",
"ConnectionPool",
"::",
"class",
")",
"->",
"getQueryBuilderForTable",
"(",
"'pages'",
")",
";",
"$",
"query... | Returns a uid list of existing styleguide demo top level pages.
These are pages with pid=0 and tx_styleguide_containsdemo set to 'tx_styleguide'.
This can be multiple pages if "create" button was clicked multiple times without "delete" in between.
@return array | [
"Returns",
"a",
"uid",
"list",
"of",
"existing",
"styleguide",
"demo",
"top",
"level",
"pages",
".",
"These",
"are",
"pages",
"with",
"pid",
"=",
"0",
"and",
"tx_styleguide_containsdemo",
"set",
"to",
"tx_styleguide",
".",
"This",
"can",
"be",
"multiple",
"p... | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/RecordFinder.php#L37-L62 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/RecordFinder.php | RecordFinder.findPidOfMainTableRecord | public function findPidOfMainTableRecord(string $tableName): int
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
$queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
$row = $queryBuilder->select('uid')
->from('pages')
->where(
$queryBuilder->expr()->eq(
'tx_styleguide_containsdemo',
$queryBuilder->createNamedParameter($tableName, \PDO::PARAM_STR)
)
)
->orderBy('pid', 'DESC')
->execute()
->fetch();
if (count($row) !== 1) {
throw new Exception(
'Found no page for main table ' . $tableName,
1457690656
);
}
return (int)$row['uid'];
} | php | public function findPidOfMainTableRecord(string $tableName): int
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
$queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
$row = $queryBuilder->select('uid')
->from('pages')
->where(
$queryBuilder->expr()->eq(
'tx_styleguide_containsdemo',
$queryBuilder->createNamedParameter($tableName, \PDO::PARAM_STR)
)
)
->orderBy('pid', 'DESC')
->execute()
->fetch();
if (count($row) !== 1) {
throw new Exception(
'Found no page for main table ' . $tableName,
1457690656
);
}
return (int)$row['uid'];
} | [
"public",
"function",
"findPidOfMainTableRecord",
"(",
"string",
"$",
"tableName",
")",
":",
"int",
"{",
"$",
"queryBuilder",
"=",
"GeneralUtility",
"::",
"makeInstance",
"(",
"ConnectionPool",
"::",
"class",
")",
"->",
"getQueryBuilderForTable",
"(",
"'pages'",
"... | "Main" tables have a single page they are located on with their possible children.
The methods find this page by getting the highest uid of a page where field
tx_styleguide_containsdemo is set to given table name.
@param string $tableName
@return int
@throws Exception | [
"Main",
"tables",
"have",
"a",
"single",
"page",
"they",
"are",
"located",
"on",
"with",
"their",
"possible",
"children",
".",
"The",
"methods",
"find",
"this",
"page",
"by",
"getting",
"the",
"highest",
"uid",
"of",
"a",
"page",
"where",
"field",
"tx_styl... | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/RecordFinder.php#L73-L95 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/RecordFinder.php | RecordFinder.findUidsOfDemoLanguages | public function findUidsOfDemoLanguages(): array
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_language');
$queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
$rows = $queryBuilder->select('uid')
->from('sys_language')
->where(
$queryBuilder->expr()->eq(
'tx_styleguide_isdemorecord',
$queryBuilder->createNamedParameter(1, \PDO::PARAM_INT)
)
)
->execute()
->fetchAll();
$result = [];
if (is_array($rows)) {
foreach ($rows as $row) {
$result[] = $row['uid'];
}
}
return $result;
} | php | public function findUidsOfDemoLanguages(): array
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_language');
$queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
$rows = $queryBuilder->select('uid')
->from('sys_language')
->where(
$queryBuilder->expr()->eq(
'tx_styleguide_isdemorecord',
$queryBuilder->createNamedParameter(1, \PDO::PARAM_INT)
)
)
->execute()
->fetchAll();
$result = [];
if (is_array($rows)) {
foreach ($rows as $row) {
$result[] = $row['uid'];
}
}
return $result;
} | [
"public",
"function",
"findUidsOfDemoLanguages",
"(",
")",
":",
"array",
"{",
"$",
"queryBuilder",
"=",
"GeneralUtility",
"::",
"makeInstance",
"(",
"ConnectionPool",
"::",
"class",
")",
"->",
"getQueryBuilderForTable",
"(",
"'sys_language'",
")",
";",
"$",
"query... | Find uids of styleguide demo sys_language`s
@return array List of uids | [
"Find",
"uids",
"of",
"styleguide",
"demo",
"sys_language",
"s"
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/RecordFinder.php#L102-L123 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/RecordFinder.php | RecordFinder.findDemoFolderObject | public function findDemoFolderObject(): Folder
{
/** @var StorageRepository $storageRepository */
$storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
$storage = $storageRepository->findByUid(1);
$folder = $storage->getRootLevelFolder();
return $folder->getSubfolder('styleguide');
} | php | public function findDemoFolderObject(): Folder
{
/** @var StorageRepository $storageRepository */
$storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
$storage = $storageRepository->findByUid(1);
$folder = $storage->getRootLevelFolder();
return $folder->getSubfolder('styleguide');
} | [
"public",
"function",
"findDemoFolderObject",
"(",
")",
":",
"Folder",
"{",
"/** @var StorageRepository $storageRepository */",
"$",
"storageRepository",
"=",
"GeneralUtility",
"::",
"makeInstance",
"(",
"StorageRepository",
"::",
"class",
")",
";",
"$",
"storage",
"=",... | Find the demo folder
@return Folder | [
"Find",
"the",
"demo",
"folder"
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/RecordFinder.php#L230-L237 | train |
TYPO3/styleguide | Classes/TcaDataGenerator/RecordData.php | RecordData.generate | public function generate(string $tableName, array $fieldValues): array
{
$tca = $GLOBALS['TCA'][$tableName];
/** @var FieldGeneratorResolver $resolver */
$resolver = GeneralUtility::makeInstance(FieldGeneratorResolver::class);
foreach ($tca['columns'] as $fieldName => $fieldConfig) {
// Generate only if there is no value set, yet
if (isset($fieldValues[$fieldName])) {
continue;
}
$data = [
'tableName' => $tableName,
'fieldName' => $fieldName,
'fieldConfig' => $fieldConfig,
'fieldValues' => $fieldValues,
];
try {
$generator = $resolver->resolve($data);
$fieldValues[$fieldName] = $generator->generate($data);
} catch (GeneratorNotFoundException $e) {
// No op if no matching generator was found
}
}
return $fieldValues;
} | php | public function generate(string $tableName, array $fieldValues): array
{
$tca = $GLOBALS['TCA'][$tableName];
/** @var FieldGeneratorResolver $resolver */
$resolver = GeneralUtility::makeInstance(FieldGeneratorResolver::class);
foreach ($tca['columns'] as $fieldName => $fieldConfig) {
// Generate only if there is no value set, yet
if (isset($fieldValues[$fieldName])) {
continue;
}
$data = [
'tableName' => $tableName,
'fieldName' => $fieldName,
'fieldConfig' => $fieldConfig,
'fieldValues' => $fieldValues,
];
try {
$generator = $resolver->resolve($data);
$fieldValues[$fieldName] = $generator->generate($data);
} catch (GeneratorNotFoundException $e) {
// No op if no matching generator was found
}
}
return $fieldValues;
} | [
"public",
"function",
"generate",
"(",
"string",
"$",
"tableName",
",",
"array",
"$",
"fieldValues",
")",
":",
"array",
"{",
"$",
"tca",
"=",
"$",
"GLOBALS",
"[",
"'TCA'",
"]",
"[",
"$",
"tableName",
"]",
";",
"/** @var FieldGeneratorResolver $resolver */",
... | Generate data for a given table and insert into database
@param string $tableName The tablename to create data for
@param array $fieldValues Incoming list of field values, Typically uid and pid are set already
@return array
@throws Exception | [
"Generate",
"data",
"for",
"a",
"given",
"table",
"and",
"insert",
"into",
"database"
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/TcaDataGenerator/RecordData.php#L33-L57 | train |
TYPO3/styleguide | Classes/Command/KauderwelschCommand.php | KauderwelschCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln(GeneralUtility::makeInstance(KauderwelschService::class)->getLoremIpsum());
return 0;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln(GeneralUtility::makeInstance(KauderwelschService::class)->getLoremIpsum());
return 0;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"GeneralUtility",
"::",
"makeInstance",
"(",
"KauderwelschService",
"::",
"class",
")",
"->",
"getLorem... | Random Kauderwelsch quote
@param InputInterface $input
@param OutputInterface $output
@return int | [
"Random",
"Kauderwelsch",
"quote"
] | 0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c | https://github.com/TYPO3/styleguide/blob/0c7af4ccd0aef49fdf5eda2c9cd494b907146f7c/Classes/Command/KauderwelschCommand.php#L36-L40 | train |
mage2pro/core | StripeClone/P/Preorder.php | Preorder.request | final static function request(M $m) {
$i = df_new(df_con_heir($m, __CLASS__), $m); /** @var self $i */
return $i->p();
} | php | final static function request(M $m) {
$i = df_new(df_con_heir($m, __CLASS__), $m); /** @var self $i */
return $i->p();
} | [
"final",
"static",
"function",
"request",
"(",
"M",
"$",
"m",
")",
"{",
"$",
"i",
"=",
"df_new",
"(",
"df_con_heir",
"(",
"$",
"m",
",",
"__CLASS__",
")",
",",
"$",
"m",
")",
";",
"/** @var self $i */",
"return",
"$",
"i",
"->",
"p",
"(",
")",
";... | 2017-06-12
@used-by \Df\StripeClone\Method::chargeNew()
@param M $m
@return array(string => mixed) | [
"2017",
"-",
"06",
"-",
"12"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/StripeClone/P/Preorder.php#L24-L27 | train |
mage2pro/core | Xml/X.php | X.asNiceXml | function asNiceXml($filename = '', $level = 0) {
if (is_numeric($level)) {
$pad = str_pad('', $level * 1, "\t", STR_PAD_LEFT);
$nl = "\n";
} else {
$pad = '';
$nl = '';
}
$out = $pad . '<' . $this->getName();
$attributes = $this->attributes();
if ($attributes) {
foreach ($attributes as $key => $value) {
$out .= ' ' . $key . '="' . str_replace('"', '\"', (string)$value) . '"';
}
}
$attributes = $this->attributes('xsi', true);
if ($attributes) {
foreach ($attributes as $key => $value) {
$out .= ' xsi:' . $key . '="' . str_replace('"', '\"', (string)$value) . '"';
}
}
if ($this->hasChildren()) {
$out .= '>';
$value = trim((string)$this);
if (strlen($value)) {
$out .= $this->xmlentities($value);
}
$out .= $nl;
foreach ($this->children() as $child) {
/** @var X $child */
$out .= $child->asNiceXml('', is_numeric($level) ? $level + 1 : true);
}
$out .= $pad . '</' . $this->getName() . '>' . $nl;
}
else {
$value = (string)$this;
if (strlen($value)) {
$out .= '>' . $this->xmlentities($value) . '</' . $this->getName() . '>' . $nl;
}
else {
$out .= '/>' . $nl;
}
}
if ((0 === $level || false === $level) && !empty($filename)) {
file_put_contents($filename, $out);
}
return $out;
} | php | function asNiceXml($filename = '', $level = 0) {
if (is_numeric($level)) {
$pad = str_pad('', $level * 1, "\t", STR_PAD_LEFT);
$nl = "\n";
} else {
$pad = '';
$nl = '';
}
$out = $pad . '<' . $this->getName();
$attributes = $this->attributes();
if ($attributes) {
foreach ($attributes as $key => $value) {
$out .= ' ' . $key . '="' . str_replace('"', '\"', (string)$value) . '"';
}
}
$attributes = $this->attributes('xsi', true);
if ($attributes) {
foreach ($attributes as $key => $value) {
$out .= ' xsi:' . $key . '="' . str_replace('"', '\"', (string)$value) . '"';
}
}
if ($this->hasChildren()) {
$out .= '>';
$value = trim((string)$this);
if (strlen($value)) {
$out .= $this->xmlentities($value);
}
$out .= $nl;
foreach ($this->children() as $child) {
/** @var X $child */
$out .= $child->asNiceXml('', is_numeric($level) ? $level + 1 : true);
}
$out .= $pad . '</' . $this->getName() . '>' . $nl;
}
else {
$value = (string)$this;
if (strlen($value)) {
$out .= '>' . $this->xmlentities($value) . '</' . $this->getName() . '>' . $nl;
}
else {
$out .= '/>' . $nl;
}
}
if ((0 === $level || false === $level) && !empty($filename)) {
file_put_contents($filename, $out);
}
return $out;
} | [
"function",
"asNiceXml",
"(",
"$",
"filename",
"=",
"''",
",",
"$",
"level",
"=",
"0",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"level",
")",
")",
"{",
"$",
"pad",
"=",
"str_pad",
"(",
"''",
",",
"$",
"level",
"*",
"1",
",",
"\"\\t\"",
",",... | 2016-09-01
@override
@see \Magento\Framework\Simplexml\Element::asNiceXml()
Родительсктй метод задаёт вложенность тремя пробелами,
а я предпочитаю символ табуляции.
@param string $filename [optional]
@param int $level [optional]
@return string | [
"2016",
"-",
"09",
"-",
"01"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Xml/X.php#L117-L164 | train |
mage2pro/core | Xml/X.php | X.leafs | function leafs($path) {
/** @var array(string => string) $result */
$result = [];
/** @var X[] $nodes */
$nodes = $this->xpathA($path);
foreach ($nodes as $node) {
/** @var X $node */
$result[] = df_leaf_s($node);
}
return $result;
} | php | function leafs($path) {
/** @var array(string => string) $result */
$result = [];
/** @var X[] $nodes */
$nodes = $this->xpathA($path);
foreach ($nodes as $node) {
/** @var X $node */
$result[] = df_leaf_s($node);
}
return $result;
} | [
"function",
"leafs",
"(",
"$",
"path",
")",
"{",
"/** @var array(string => string) $result */",
"$",
"result",
"=",
"[",
"]",
";",
"/** @var X[] $nodes */",
"$",
"nodes",
"=",
"$",
"this",
"->",
"xpathA",
"(",
"$",
"path",
")",
";",
"foreach",
"(",
"$",
"n... | 2015-08-15
@used-by \Dfr\Core\Realtime\Dictionary::hasEntry()
@param string $path
@return string[] | [
"2015",
"-",
"08",
"-",
"15"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Xml/X.php#L426-L436 | train |
mage2pro/core | Payment/W/Event.php | Event.tl | final function tl() {return dfc($this, function() {return $this->tl_(
$this->useRawTypeForLabel() ? $this->_r->tRaw() : $this->t()
);});} | php | final function tl() {return dfc($this, function() {return $this->tl_(
$this->useRawTypeForLabel() ? $this->_r->tRaw() : $this->t()
);});} | [
"final",
"function",
"tl",
"(",
")",
"{",
"return",
"dfc",
"(",
"$",
"this",
",",
"function",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"tl_",
"(",
"$",
"this",
"->",
"useRawTypeForLabel",
"(",
")",
"?",
"$",
"this",
"->",
"_r",
"->",
"tRaw",
"... | 2017-03-10 Type label.
@override
@see \Df\Payment\W\IEvent::r()
@used-by \Df\Payment\W\Action::ignoredLog()
@used-by \Df\Payment\W\Handler::log()
@used-by \Dfe\AllPay\Choice::title()
@return string | [
"2017",
"-",
"03",
"-",
"10",
"Type",
"label",
"."
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Payment/W/Event.php#L238-L240 | train |
mage2pro/core | Core/T/lib/db-column.php | DbColumn.df_db_column_exists | function df_db_column_exists() {
$this->assertTrue(df_db_column_exists(self::$TABLE, 'customer_group_id'));
$this->assertFalse(df_db_column_exists(self::$TABLE, 'non_existent_column'));
} | php | function df_db_column_exists() {
$this->assertTrue(df_db_column_exists(self::$TABLE, 'customer_group_id'));
$this->assertFalse(df_db_column_exists(self::$TABLE, 'non_existent_column'));
} | [
"function",
"df_db_column_exists",
"(",
")",
"{",
"$",
"this",
"->",
"assertTrue",
"(",
"df_db_column_exists",
"(",
"self",
"::",
"$",
"TABLE",
",",
"'customer_group_id'",
")",
")",
";",
"$",
"this",
"->",
"assertFalse",
"(",
"df_db_column_exists",
"(",
"self"... | 2016-11-01 | [
"2016",
"-",
"11",
"-",
"01"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Core/T/lib/db-column.php#L37-L40 | train |
mage2pro/core | Config/Source/Block.php | Block.map | protected function map() {return df_map_0(df_sort_a(df_map_r(df_cms_blocks(), function(B $b) {return [
$b->getId(), $b->getTitle()
];})), '-- select a CMS block --');} | php | protected function map() {return df_map_0(df_sort_a(df_map_r(df_cms_blocks(), function(B $b) {return [
$b->getId(), $b->getTitle()
];})), '-- select a CMS block --');} | [
"protected",
"function",
"map",
"(",
")",
"{",
"return",
"df_map_0",
"(",
"df_sort_a",
"(",
"df_map_r",
"(",
"df_cms_blocks",
"(",
")",
",",
"function",
"(",
"B",
"$",
"b",
")",
"{",
"return",
"[",
"$",
"b",
"->",
"getId",
"(",
")",
",",
"$",
"b",
... | 2018-05-21
@override
@see \Df\Config\Source::map()
@used-by \Df\Config\Source::toOptionArray()
@return array(string => string) | [
"2018",
"-",
"05",
"-",
"21"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Config/Source/Block.php#L17-L19 | train |
mage2pro/core | Payment/Settings.php | Settings.applicableForQuoteByMinMaxTotal | final function applicableForQuoteByMinMaxTotal($option) {
$a = df_quote()->getBaseGrandTotal(); /** @var float $a */
$max = $this->v("$option/" . T::MAX_ORDER_TOTAL); /** @var float $max */
$min = $this->v("$option/" . T::MIN_ORDER_TOTAL); /** @var float $min */
return !($min && $a < $min || $max && $a > $max);
} | php | final function applicableForQuoteByMinMaxTotal($option) {
$a = df_quote()->getBaseGrandTotal(); /** @var float $a */
$max = $this->v("$option/" . T::MAX_ORDER_TOTAL); /** @var float $max */
$min = $this->v("$option/" . T::MIN_ORDER_TOTAL); /** @var float $min */
return !($min && $a < $min || $max && $a > $max);
} | [
"final",
"function",
"applicableForQuoteByMinMaxTotal",
"(",
"$",
"option",
")",
"{",
"$",
"a",
"=",
"df_quote",
"(",
")",
"->",
"getBaseGrandTotal",
"(",
")",
";",
"/** @var float $a */",
"$",
"max",
"=",
"$",
"this",
"->",
"v",
"(",
"\"$option/\"",
".",
... | 2017-07-29
It is implemented by analogy with @see \Magento\Payment\Model\Checks\TotalMinMax::isApplicable()
@used-by \Dfe\AlphaCommerceHub\ConfigProvider::option()
@used-by \Dfe\Moip\ConfigProvider::config()
@param string $option
@return boolean | [
"2017",
"-",
"07",
"-",
"29",
"It",
"is",
"implemented",
"by",
"analogy",
"with"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Payment/Settings.php#L64-L69 | train |
mage2pro/core | Payment/Settings.php | Settings._options | final protected function _options($source) {return dfc($this, function($s) {return new Options(
$this, is_object($s) ? $s : df_sc($s, ConfigSource::class)
);}, func_get_args());} | php | final protected function _options($source) {return dfc($this, function($s) {return new Options(
$this, is_object($s) ? $s : df_sc($s, ConfigSource::class)
);}, func_get_args());} | [
"final",
"protected",
"function",
"_options",
"(",
"$",
"source",
")",
"{",
"return",
"dfc",
"(",
"$",
"this",
",",
"function",
"(",
"$",
"s",
")",
"{",
"return",
"new",
"Options",
"(",
"$",
"this",
",",
"is_object",
"(",
"$",
"s",
")",
"?",
"$",
... | 2017-03-03
@used-by \Df\GingerPaymentsBase\Settings::options()
@used-by \Dfe\AllPay\Settings::options()
@used-by \Dfe\AlphaCommerceHub\Settings::options()
@used-by \Dfe\IPay88\Settings::options()
@used-by \Dfe\YandexKassa\Settings::options()
@param string|ConfigSource $source
@return Options | [
"2017",
"-",
"03",
"-",
"03"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Payment/Settings.php#L189-L191 | train |
mage2pro/core | Framework/Mail/TransportObserver.php | TransportObserver.execute | final function execute(Ob $ob) {
if (dfs($this)->enable()) {
$ob[P::CONTAINER][P::K_TRANSPORT] = df_con($this, 'Transport');
}
} | php | final function execute(Ob $ob) {
if (dfs($this)->enable()) {
$ob[P::CONTAINER][P::K_TRANSPORT] = df_con($this, 'Transport');
}
} | [
"final",
"function",
"execute",
"(",
"Ob",
"$",
"ob",
")",
"{",
"if",
"(",
"dfs",
"(",
"$",
"this",
")",
"->",
"enable",
"(",
")",
")",
"{",
"$",
"ob",
"[",
"P",
"::",
"CONTAINER",
"]",
"[",
"P",
"::",
"K_TRANSPORT",
"]",
"=",
"df_con",
"(",
... | 2018-01-28
@override
@see IOb::execute()
@used-by \Magento\Framework\Event\Invoker\InvokerDefault::_callObserverMethod()
@param Ob $ob | [
"2018",
"-",
"01",
"-",
"28"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Framework/Mail/TransportObserver.php#L19-L23 | train |
mage2pro/core | Payment/BankCardNetworkDetector.php | BankCardNetworkDetector.label | static function label($c) {return dftr($c, [
self::AE => 'American Express'
,self::DN => 'Diners Club'
,self::DS => 'Discover'
,self::JC => 'JCB'
,self::MC => 'MasterCard'
,self::VI => 'Visa'
]);} | php | static function label($c) {return dftr($c, [
self::AE => 'American Express'
,self::DN => 'Diners Club'
,self::DS => 'Discover'
,self::JC => 'JCB'
,self::MC => 'MasterCard'
,self::VI => 'Visa'
]);} | [
"static",
"function",
"label",
"(",
"$",
"c",
")",
"{",
"return",
"dftr",
"(",
"$",
"c",
",",
"[",
"self",
"::",
"AE",
"=>",
"'American Express'",
",",
"self",
"::",
"DN",
"=>",
"'Diners Club'",
",",
"self",
"::",
"DS",
"=>",
"'Discover'",
",",
"self... | 2018-12-19
@used-by \Dfe\Vantiv\Facade\Card::brand()
@param string $c
@return string | [
"2018",
"-",
"12",
"-",
"19"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Payment/BankCardNetworkDetector.php#L11-L18 | train |
mage2pro/core | Customer/Setup/UpgradeData.php | UpgradeData._process | final protected function _process() {
/**
* 2016-08-22
* Помимо добавления поля в таблицу «customer_entity» надо ещё добавить атрибут,
* иначе данные не будут сохраняться:
* $attribute = $this->getAttribute($k);
* if (empty($attribute)) {
* continue;
* }
* https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Eav/Model/Entity/AbstractEntity.php#L1262-L1265
*/
if ($this->v('1.7.4')) {
df_eav_setup()->addAttribute('customer', UpgradeSchema::F__DF, [
'input' => 'text'
,'label' => 'Mage2.PRO'
,'position' => 1000
,'required' => false
,'sort_order' => 1000
,'system' => false
,'type' => 'static'
,'visible' => false
]);
}
} | php | final protected function _process() {
/**
* 2016-08-22
* Помимо добавления поля в таблицу «customer_entity» надо ещё добавить атрибут,
* иначе данные не будут сохраняться:
* $attribute = $this->getAttribute($k);
* if (empty($attribute)) {
* continue;
* }
* https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Eav/Model/Entity/AbstractEntity.php#L1262-L1265
*/
if ($this->v('1.7.4')) {
df_eav_setup()->addAttribute('customer', UpgradeSchema::F__DF, [
'input' => 'text'
,'label' => 'Mage2.PRO'
,'position' => 1000
,'required' => false
,'sort_order' => 1000
,'system' => false
,'type' => 'static'
,'visible' => false
]);
}
} | [
"final",
"protected",
"function",
"_process",
"(",
")",
"{",
"/**\n\t\t * 2016-08-22\n\t\t * Помимо добавления поля в таблицу «customer_entity» надо ещё добавить атрибут,\n\t\t * иначе данные не будут сохраняться:\n\t\t *\t\t$attribute = $this->getAttribute($k);\n\t\t *\t\tif (empty($attribute)) {\n\t... | 2017-10-14
@override
@see \Df\Framework\Upgrade::_process()
@used-by \Df\Framework\Upgrade::process() | [
"2017",
"-",
"10",
"-",
"14"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Customer/Setup/UpgradeData.php#L18-L41 | train |
mage2pro/core | Directory/FE/Currency.php | Currency.getValue | function getValue() {
$chosen = parent::getValue(); /** @var string|null $chosen */
$allowed = $this->dfValues(); /** @var string[] $allowed */
// 2016-11-13
// Обрабатываем тот случай, когда значения self::$ORDER и self::$BASE были разрешены
// в предыдущих версиях модуля, а потом стали запрещены.
// Так, например, было с модулем Square:
// там на сегодняшний день разрешены всего 2 валюты: USD и CAD,
// поэтому я решил убрать опции self::$ORDER и self::$BASE,
// однако чтобы это не поломало магазины тех клиентов,
// у которых одно из этих значений уже выбрано (а self::$ORDER было значением по умолчанию).
return $allowed && (!$chosen || !in_array($chosen, $allowed)) ? df_first($allowed) :
($chosen ?: self::$ORDER)
;
} | php | function getValue() {
$chosen = parent::getValue(); /** @var string|null $chosen */
$allowed = $this->dfValues(); /** @var string[] $allowed */
// 2016-11-13
// Обрабатываем тот случай, когда значения self::$ORDER и self::$BASE были разрешены
// в предыдущих версиях модуля, а потом стали запрещены.
// Так, например, было с модулем Square:
// там на сегодняшний день разрешены всего 2 валюты: USD и CAD,
// поэтому я решил убрать опции self::$ORDER и self::$BASE,
// однако чтобы это не поломало магазины тех клиентов,
// у которых одно из этих значений уже выбрано (а self::$ORDER было значением по умолчанию).
return $allowed && (!$chosen || !in_array($chosen, $allowed)) ? df_first($allowed) :
($chosen ?: self::$ORDER)
;
} | [
"function",
"getValue",
"(",
")",
"{",
"$",
"chosen",
"=",
"parent",
"::",
"getValue",
"(",
")",
";",
"/** @var string|null $chosen */",
"$",
"allowed",
"=",
"$",
"this",
"->",
"dfValues",
"(",
")",
";",
"/** @var string[] $allowed */",
"// 2016-11-13",
"// Обра... | 2016-09-04
@override
@see \Df\Framework\Form\Element\Select::getValue()
@used-by \Df\Framework\Form\Element\Select2::setRenderer()
@see \Dfe\Stripe\FE\Currency::getValue()
@return string|null | [
"2016",
"-",
"09",
"-",
"04"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Directory/FE/Currency.php#L16-L30 | train |
mage2pro/core | Directory/FE/Currency.php | Currency.map | private static function map($store = null, $orderCurrency = null) {return dfcf(
function($store = null, $orderCurrency = null) {return [
self::$BASE => df_currency_base_c($store)
,self::$ORDER => $orderCurrency ?: df_currency_current_c($store)
];}
, func_get_args());} | php | private static function map($store = null, $orderCurrency = null) {return dfcf(
function($store = null, $orderCurrency = null) {return [
self::$BASE => df_currency_base_c($store)
,self::$ORDER => $orderCurrency ?: df_currency_current_c($store)
];}
, func_get_args());} | [
"private",
"static",
"function",
"map",
"(",
"$",
"store",
"=",
"null",
",",
"$",
"orderCurrency",
"=",
"null",
")",
"{",
"return",
"dfcf",
"(",
"function",
"(",
"$",
"store",
"=",
"null",
",",
"$",
"orderCurrency",
"=",
"null",
")",
"{",
"return",
"... | 2016-09-05
@used-by v()
@param null|string|int|S|Store $store [optional]
@param string|null $orderCurrency [optional]
@return array(string => string|null) | [
"2016",
"-",
"09",
"-",
"05"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Directory/FE/Currency.php#L94-L99 | train |
mage2pro/core | Payment/Operation.php | Operation.customerNameA | private function customerNameA() {return dfc($this, function() {
/** @var O $o */ $o = $this->o();
/** @var OA $ba */ $ba = $this->addressB();
/** @var C|DFCustomer $c */
/** @var string|null $f */
return ($f = $o->getCustomerFirstname()) ? [$f, $o->getCustomerLastname()] : (
($c = $o->getCustomer()) && ($f = $c->getFirstname()) ? [$f, $c->getLastname()] : (
$f = $ba->getFirstname() ? [$f, $ba->getLastname()] : (
($sa = $this->addressS()) && ($f = $sa->getFirstname()) ? [$f, $sa->getLastname()] :
[null, null]
)
)
);
});} | php | private function customerNameA() {return dfc($this, function() {
/** @var O $o */ $o = $this->o();
/** @var OA $ba */ $ba = $this->addressB();
/** @var C|DFCustomer $c */
/** @var string|null $f */
return ($f = $o->getCustomerFirstname()) ? [$f, $o->getCustomerLastname()] : (
($c = $o->getCustomer()) && ($f = $c->getFirstname()) ? [$f, $c->getLastname()] : (
$f = $ba->getFirstname() ? [$f, $ba->getLastname()] : (
($sa = $this->addressS()) && ($f = $sa->getFirstname()) ? [$f, $sa->getLastname()] :
[null, null]
)
)
);
});} | [
"private",
"function",
"customerNameA",
"(",
")",
"{",
"return",
"dfc",
"(",
"$",
"this",
",",
"function",
"(",
")",
"{",
"/** @var O $o */",
"$",
"o",
"=",
"$",
"this",
"->",
"o",
"(",
")",
";",
"/** @var OA $ba */",
"$",
"ba",
"=",
"$",
"this",
"->... | 2016-08-26
@return array(string|null) | [
"2016",
"-",
"08",
"-",
"26"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Payment/Operation.php#L518-L531 | train |
mage2pro/core | Payment/TM.php | TM.confirmed | function confirmed() {return dfc($this, function() {/** @var T|null|false $t */ return
df_order($this->_ii)->hasInvoices()
// 2017-03-27
// Тот случай, когда платёж только авторизован.
// Magento не создаёт в этом случае invoice
// @todo Может, надо просто создавать invoice при авторизации платежа?
|| ($t = $this->tReq(false)) && (T::TYPE_AUTH === $t->getTxnType())
/**
* 2017-08-31
* It is for modules with a redirection (PayPal clones).
* @see \Dfe\PostFinance\W\Event::ttCurrent()
* https://github.com/mage2pro/postfinance/blob/0.1.7/W/Event.php#L35
*/
|| df_find(function(T $t) {return T::TYPE_AUTH === $t->getTxnType();}, $this->tResponses())
;});} | php | function confirmed() {return dfc($this, function() {/** @var T|null|false $t */ return
df_order($this->_ii)->hasInvoices()
// 2017-03-27
// Тот случай, когда платёж только авторизован.
// Magento не создаёт в этом случае invoice
// @todo Может, надо просто создавать invoice при авторизации платежа?
|| ($t = $this->tReq(false)) && (T::TYPE_AUTH === $t->getTxnType())
/**
* 2017-08-31
* It is for modules with a redirection (PayPal clones).
* @see \Dfe\PostFinance\W\Event::ttCurrent()
* https://github.com/mage2pro/postfinance/blob/0.1.7/W/Event.php#L35
*/
|| df_find(function(T $t) {return T::TYPE_AUTH === $t->getTxnType();}, $this->tResponses())
;});} | [
"function",
"confirmed",
"(",
")",
"{",
"return",
"dfc",
"(",
"$",
"this",
",",
"function",
"(",
")",
"{",
"/** @var T|null|false $t */",
"return",
"df_order",
"(",
"$",
"this",
"->",
"_ii",
")",
"->",
"hasInvoices",
"(",
")",
"// 2017-03-27",
"// Тот случай... | 2017-03-25
2017-11-11
The @see \Magento\Sales\Api\Data\TransactionInterface::TYPE_AUTH constant
is absent in Magento < 2.1.0,
but is present as @uses \Magento\Sales\Model\Order\Payment\Transaction::TYPE_AUTH
https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Sales/Model/Order/Payment/Transaction.php#L37
https://github.com/magento/magento2/blob/2.0.17/app/code/Magento/Sales/Api/Data/TransactionInterface.php
@used-by \Df\Payment\Block\Info::prepareToRendering()
@return bool | [
"2017",
"-",
"03",
"-",
"25",
"2017",
"-",
"11",
"-",
"11",
"The"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Payment/TM.php#L25-L39 | train |
mage2pro/core | Payment/TM.php | TM.res0 | function res0($k = null) {return dfak($this, function() {return df_trd(
$this->tReq(), M::IIA_TR_RESPONSE
);}, $k);} | php | function res0($k = null) {return dfak($this, function() {return df_trd(
$this->tReq(), M::IIA_TR_RESPONSE
);}, $k);} | [
"function",
"res0",
"(",
"$",
"k",
"=",
"null",
")",
"{",
"return",
"dfak",
"(",
"$",
"this",
",",
"function",
"(",
")",
"{",
"return",
"df_trd",
"(",
"$",
"this",
"->",
"tReq",
"(",
")",
",",
"M",
"::",
"IIA_TR_RESPONSE",
")",
";",
"}",
",",
"... | 2017-03-29 It returns a response to the primary request to the PSP API.
@used-by \Df\GingerPaymentsBase\Block\Info::res0()
@used-by \Df\Payment\Choice::res0()
@used-by \Df\StripeClone\Block\Info::cardData()
@used-by \Dfe\Moip\Block\Info\Boleto::prepare()
@used-by \Dfe\Moip\Block\Info\Boleto::rCustomerAccount()
@used-by \Dfe\Moip\Block\Info\Boleto::url()
@used-by \Dfe\Square\Block\Info::prepare()
@used-by \Dfe\Stripe\Block\Info::cardData()
@param string|string[]|null $k [optional]
@return array(string => string)|string|null | [
"2017",
"-",
"03",
"-",
"29",
"It",
"returns",
"a",
"response",
"to",
"the",
"primary",
"request",
"to",
"the",
"PSP",
"API",
"."
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Payment/TM.php#L98-L100 | train |
mage2pro/core | Payment/TM.php | TM.responses | private function responses() {return dfc($this, function() {return array_map(function(T $t) {return
F::s($this->_m, df_trd($t))->e()
;}, $this->tResponses());});} | php | private function responses() {return dfc($this, function() {return array_map(function(T $t) {return
F::s($this->_m, df_trd($t))->e()
;}, $this->tResponses());});} | [
"private",
"function",
"responses",
"(",
")",
"{",
"return",
"dfc",
"(",
"$",
"this",
",",
"function",
"(",
")",
"{",
"return",
"array_map",
"(",
"function",
"(",
"T",
"$",
"t",
")",
"{",
"return",
"F",
"::",
"s",
"(",
"$",
"this",
"->",
"_m",
",... | 2016-07-18
2017-11-12 It returns all the payment's transactions except the first one, wrapped by event instances.
@used-by response()
@return Ev[] | [
"2016",
"-",
"07",
"-",
"18",
"2017",
"-",
"11",
"-",
"12",
"It",
"returns",
"all",
"the",
"payment",
"s",
"transactions",
"except",
"the",
"first",
"one",
"wrapped",
"by",
"event",
"instances",
"."
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Payment/TM.php#L152-L154 | train |
mage2pro/core | Payment/TM.php | TM.tResponses | private function tResponses() {return dfc($this, function() {return
!($p = $this->tReq(false)) ? [] : df_sort($p->getChildTransactions())
;});} | php | private function tResponses() {return dfc($this, function() {return
!($p = $this->tReq(false)) ? [] : df_sort($p->getChildTransactions())
;});} | [
"private",
"function",
"tResponses",
"(",
")",
"{",
"return",
"dfc",
"(",
"$",
"this",
",",
"function",
"(",
")",
"{",
"return",
"!",
"(",
"$",
"p",
"=",
"$",
"this",
"->",
"tReq",
"(",
"false",
")",
")",
"?",
"[",
"]",
":",
"df_sort",
"(",
"$"... | 2017-08-31
2017-11-12 It returns all the payment's transactions except the first one.
@used-by confirmed()
@used-by responses()
@return T[] | [
"2017",
"-",
"08",
"-",
"31",
"2017",
"-",
"11",
"-",
"12",
"It",
"returns",
"all",
"the",
"payment",
"s",
"transactions",
"except",
"the",
"first",
"one",
"."
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Payment/TM.php#L163-L165 | train |
mage2pro/core | Payment/W/Responder.php | Responder.setSoftFailure | final function setSoftFailure($v) {$this->set(
($v = is_string($v) ? __($v) : $v) instanceof Phrase ? Text::i($v) : $v
);} | php | final function setSoftFailure($v) {$this->set(
($v = is_string($v) ? __($v) : $v) instanceof Phrase ? Text::i($v) : $v
);} | [
"final",
"function",
"setSoftFailure",
"(",
"$",
"v",
")",
"{",
"$",
"this",
"->",
"set",
"(",
"(",
"$",
"v",
"=",
"is_string",
"(",
"$",
"v",
")",
"?",
"__",
"(",
"$",
"v",
")",
":",
"$",
"v",
")",
"instanceof",
"Phrase",
"?",
"Text",
"::",
... | 2017-09-13
@used-by \Df\Payment\W\Strategy::softFailure()
@param wResult|Phrase|string|null $v | [
"2017",
"-",
"09",
"-",
"13"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Payment/W/Responder.php#L66-L68 | train |
mage2pro/core | Config/Source/LetterCase.php | LetterCase.map | protected function map() {
/** @var string|null $sample */
$sample = $this->f('dfSample');
/** @var string[] $values */
$values = [self::_DEFAULT, self::$UCFIRST, self::$UCWORDS, self::$UPPERCASE, self::$LOWERCASE];
/** @var string[] $labels */
$labels = [
'As Is'
, 'Uppercase first letter'
, 'Uppercase Each Word\'s First Letter'
,'UPPERCASE'
,'lowercase'
];
return array_combine(
$values
,!$sample
? $labels
: array_map(function($value, $label) use($sample) {
return sprintf('%s (%s)', self::apply($sample, $value), $label);
}, $values, $labels)
//: df_map([__CLASS__, 'apply'], $keys, [], $sample)
);
} | php | protected function map() {
/** @var string|null $sample */
$sample = $this->f('dfSample');
/** @var string[] $values */
$values = [self::_DEFAULT, self::$UCFIRST, self::$UCWORDS, self::$UPPERCASE, self::$LOWERCASE];
/** @var string[] $labels */
$labels = [
'As Is'
, 'Uppercase first letter'
, 'Uppercase Each Word\'s First Letter'
,'UPPERCASE'
,'lowercase'
];
return array_combine(
$values
,!$sample
? $labels
: array_map(function($value, $label) use($sample) {
return sprintf('%s (%s)', self::apply($sample, $value), $label);
}, $values, $labels)
//: df_map([__CLASS__, 'apply'], $keys, [], $sample)
);
} | [
"protected",
"function",
"map",
"(",
")",
"{",
"/** @var string|null $sample */",
"$",
"sample",
"=",
"$",
"this",
"->",
"f",
"(",
"'dfSample'",
")",
";",
"/** @var string[] $values */",
"$",
"values",
"=",
"[",
"self",
"::",
"_DEFAULT",
",",
"self",
"::",
"... | 2015-11-14
@override
@see \Df\Config\Source::map()
@used-by \Df\Config\Source::toOptionArray()
@return array(string => string) | [
"2015",
"-",
"11",
"-",
"14"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Config/Source/LetterCase.php#L12-L34 | train |
mage2pro/core | StripeClone/Method.php | Method.charge | final function charge($capture = true) {
df_sentry_extra($this, 'Amount', $a = dfp_due($this)); /** @var float $a */
df_sentry_extra($this, 'Need Capture?', df_bts($capture));
/**
* 2017-11-11
* Despite of its name, @uses \Magento\Sales\Model\Order\Payment::getAuthorizationTransaction()
* simply returns the previous transaction,
* and it can be not only an `authorization` transaction,
* but a transaction of another type (e.g. `payment`) too.
* public function getAuthorizationTransaction() {
* return $this->transactionManager->getAuthorizationTransaction(
* $this->getParentTransactionId(),
* $this->getId(),
* $this->getOrder()->getId()
* );
* }
* The code is the same in Magento 2.0.0 - 2.2.1:
* https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Sales/Model/Order/Payment.php#L1242-#L1253
* https://github.com/magento/magento2/blob/2.2.1/app/code/Magento/Sales/Model/Order/Payment.php#L1316-L1327
* @see \Magento\Sales\Model\Order\Payment\Transaction\Manager::getAuthorizationTransaction()
* public function getAuthorizationTransaction($parentTransactionId, $paymentId, $orderId) {
* $transaction = false;
* if ($parentTransactionId) {
* $transaction = $this->transactionRepository->getByTransactionId(
* $parentTransactionId,
* $paymentId,
* $orderId
* );
* }
* return $transaction ?: $this->transactionRepository->getByTransactionType(
* Transaction::TYPE_AUTH,
* $paymentId,
* $orderId
* );
* }
* The code is the same in Magento 2.0.0 - 2.2.1:
* https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Sales/Model/Order/Payment/Transaction/Manager.php#L31-L47
* https://github.com/magento/magento2/blob/2.2.1/app/code/Magento/Sales/Model/Order/Payment/Transaction/Manager.php#L31-L47
*/
$tPrev = !$capture ? null : $this->ii()->getAuthorizationTransaction(); /** @var T|false|null $tPrev */
/**
* 2017-11-11
* The @see \Magento\Sales\Api\Data\TransactionInterface::TYPE_AUTH constant
* is absent in Magento < 2.1.0,
* but is present as @uses \Magento\Sales\Model\Order\Payment\Transaction::TYPE_AUTH
* https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Sales/Model/Order/Payment/Transaction.php#L37
* https://github.com/magento/magento2/blob/2.0.17/app/code/Magento/Sales/Api/Data/TransactionInterface.php
*/
if (!$tPrev || T::TYPE_AUTH !== $tPrev->getTxnType()) {
$this->chargeNew($capture);
}
else {
/** @var string $txnId */
df_sentry_extra($this, 'Parent Transaction ID', $txnId = $tPrev->getTxnId());
df_sentry_extra($this, 'Charge ID', $id = $this->i2e($txnId)); /** @var string $id */
$this->transInfo($this->fCharge()->capturePreauthorized($id, $this->amountFormat($a)));
// 2016-12-16
// Система в этом сценарии по-умолчанию формирует идентификатор транзации как
// «<идентификатор родительской транзации>-capture».
// У нас же идентификатор родительской транзации имеет окончание «-authorize»,
// и оно нам реально нужно (смотрите комментарий к ветке else ниже),
// поэтому здесь мы окончание «-authorize» вручную подменяем на «-capture».
$this->ii()->setTransactionId($this->e2i($id, Ev::T_CAPTURE));
}
} | php | final function charge($capture = true) {
df_sentry_extra($this, 'Amount', $a = dfp_due($this)); /** @var float $a */
df_sentry_extra($this, 'Need Capture?', df_bts($capture));
/**
* 2017-11-11
* Despite of its name, @uses \Magento\Sales\Model\Order\Payment::getAuthorizationTransaction()
* simply returns the previous transaction,
* and it can be not only an `authorization` transaction,
* but a transaction of another type (e.g. `payment`) too.
* public function getAuthorizationTransaction() {
* return $this->transactionManager->getAuthorizationTransaction(
* $this->getParentTransactionId(),
* $this->getId(),
* $this->getOrder()->getId()
* );
* }
* The code is the same in Magento 2.0.0 - 2.2.1:
* https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Sales/Model/Order/Payment.php#L1242-#L1253
* https://github.com/magento/magento2/blob/2.2.1/app/code/Magento/Sales/Model/Order/Payment.php#L1316-L1327
* @see \Magento\Sales\Model\Order\Payment\Transaction\Manager::getAuthorizationTransaction()
* public function getAuthorizationTransaction($parentTransactionId, $paymentId, $orderId) {
* $transaction = false;
* if ($parentTransactionId) {
* $transaction = $this->transactionRepository->getByTransactionId(
* $parentTransactionId,
* $paymentId,
* $orderId
* );
* }
* return $transaction ?: $this->transactionRepository->getByTransactionType(
* Transaction::TYPE_AUTH,
* $paymentId,
* $orderId
* );
* }
* The code is the same in Magento 2.0.0 - 2.2.1:
* https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Sales/Model/Order/Payment/Transaction/Manager.php#L31-L47
* https://github.com/magento/magento2/blob/2.2.1/app/code/Magento/Sales/Model/Order/Payment/Transaction/Manager.php#L31-L47
*/
$tPrev = !$capture ? null : $this->ii()->getAuthorizationTransaction(); /** @var T|false|null $tPrev */
/**
* 2017-11-11
* The @see \Magento\Sales\Api\Data\TransactionInterface::TYPE_AUTH constant
* is absent in Magento < 2.1.0,
* but is present as @uses \Magento\Sales\Model\Order\Payment\Transaction::TYPE_AUTH
* https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Sales/Model/Order/Payment/Transaction.php#L37
* https://github.com/magento/magento2/blob/2.0.17/app/code/Magento/Sales/Api/Data/TransactionInterface.php
*/
if (!$tPrev || T::TYPE_AUTH !== $tPrev->getTxnType()) {
$this->chargeNew($capture);
}
else {
/** @var string $txnId */
df_sentry_extra($this, 'Parent Transaction ID', $txnId = $tPrev->getTxnId());
df_sentry_extra($this, 'Charge ID', $id = $this->i2e($txnId)); /** @var string $id */
$this->transInfo($this->fCharge()->capturePreauthorized($id, $this->amountFormat($a)));
// 2016-12-16
// Система в этом сценарии по-умолчанию формирует идентификатор транзации как
// «<идентификатор родительской транзации>-capture».
// У нас же идентификатор родительской транзации имеет окончание «-authorize»,
// и оно нам реально нужно (смотрите комментарий к ветке else ниже),
// поэтому здесь мы окончание «-authorize» вручную подменяем на «-capture».
$this->ii()->setTransactionId($this->e2i($id, Ev::T_CAPTURE));
}
} | [
"final",
"function",
"charge",
"(",
"$",
"capture",
"=",
"true",
")",
"{",
"df_sentry_extra",
"(",
"$",
"this",
",",
"'Amount'",
",",
"$",
"a",
"=",
"dfp_due",
"(",
"$",
"this",
")",
")",
";",
"/** @var float $a */",
"df_sentry_extra",
"(",
"$",
"this",
... | 2016-03-07
@override
@see https://stripe.com/docs/charges
@see \Df\Payment\Method::charge()
@used-by \Df\Payment\Method::authorize()
@used-by \Df\Payment\Method::capture()
@used-by \Dfe\Omise\Init\Action::redirectUrl()
@param bool|null $capture [optional]
@throws \Stripe\Error\Card | [
"2016",
"-",
"03",
"-",
"07"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/StripeClone/Method.php#L169-L233 | train |
mage2pro/core | StripeClone/Method.php | Method._refund | final protected function _refund($a) {
$ii = $this->ii(); /** @var OP $ii */
/**
* 2016-03-17, 2017-11-11
* Despite of its name, @uses \Magento\Sales\Model\Order\Payment::getAuthorizationTransaction()
* simply returns the previous transaction,
* and it can be not only an `authorization` transaction,
* but a transaction of another type (e.g. `payment`) too.
* public function getAuthorizationTransaction() {
* return $this->transactionManager->getAuthorizationTransaction(
* $this->getParentTransactionId(),
* $this->getId(),
* $this->getOrder()->getId()
* );
* }
* The code is the same in Magento 2.0.0 - 2.2.1:
* https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Sales/Model/Order/Payment.php#L1242-#L1253
* https://github.com/magento/magento2/blob/2.2.1/app/code/Magento/Sales/Model/Order/Payment.php#L1316-L1327
* @see \Magento\Sales\Model\Order\Payment\Transaction\Manager::getAuthorizationTransaction()
* public function getAuthorizationTransaction($parentTransactionId, $paymentId, $orderId) {
* $transaction = false;
* if ($parentTransactionId) {
* $transaction = $this->transactionRepository->getByTransactionId(
* $parentTransactionId,
* $paymentId,
* $orderId
* );
* }
* return $transaction ?: $this->transactionRepository->getByTransactionType(
* Transaction::TYPE_AUTH,
* $paymentId,
* $orderId
* );
* }
* The code is the same in Magento 2.0.0 - 2.2.1:
* https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Sales/Model/Order/Payment/Transaction/Manager.php#L31-L47
* https://github.com/magento/magento2/blob/2.2.1/app/code/Magento/Sales/Model/Order/Payment/Transaction/Manager.php#L31-L47
* It is exactly what we need,
* because the module can be set up to capture payments without a preliminary authorization.
*/
if ($tPrev = $ii->getAuthorizationTransaction() /** @var T|false $tPrev */) {
$id = $this->i2e($tPrev->getTxnId()); /** @var string $id */
// 2016-03-24
// Credit Memo и Invoice отсутствуют в сценарии Authorize / Capture
// и присутствуют в сценарии Capture / Refund.
$cm = $ii->getCreditmemo(); /** @var CM|null $cm */
$fc = $this->fCharge(); /** @var fCharge $fc */
$resp = $cm ? $fc->refund($id, $this->amountFormat($a)) : $fc->void($id); /** @var object $resp */
$this->transInfo($resp);
$ii->setTransactionId($this->e2i($id, $cm ? Ev::T_REFUND : 'void'));
if ($cm) {
/**
* 2017-01-19
* Записаваем идентификатор операции в БД,
* чтобы затем, при обработке оповещений от платёжной системы,
* проверять, не было ли это оповещение инициировано нашей же операцией,
* и если было, то не обрабатывать его повторно:
* @see \Df\Payment\W\Strategy\Refund::_handle()
* https://github.com/mage2pro/core/blob/1.12.16/StripeClone/WebhookStrategy/Charge/Refunded.php?ts=4#L21-L23
*/
dfp_container_add($this->ii(), self::II_TRANS, fRefund::s($this)->transId($resp));
}
}
} | php | final protected function _refund($a) {
$ii = $this->ii(); /** @var OP $ii */
/**
* 2016-03-17, 2017-11-11
* Despite of its name, @uses \Magento\Sales\Model\Order\Payment::getAuthorizationTransaction()
* simply returns the previous transaction,
* and it can be not only an `authorization` transaction,
* but a transaction of another type (e.g. `payment`) too.
* public function getAuthorizationTransaction() {
* return $this->transactionManager->getAuthorizationTransaction(
* $this->getParentTransactionId(),
* $this->getId(),
* $this->getOrder()->getId()
* );
* }
* The code is the same in Magento 2.0.0 - 2.2.1:
* https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Sales/Model/Order/Payment.php#L1242-#L1253
* https://github.com/magento/magento2/blob/2.2.1/app/code/Magento/Sales/Model/Order/Payment.php#L1316-L1327
* @see \Magento\Sales\Model\Order\Payment\Transaction\Manager::getAuthorizationTransaction()
* public function getAuthorizationTransaction($parentTransactionId, $paymentId, $orderId) {
* $transaction = false;
* if ($parentTransactionId) {
* $transaction = $this->transactionRepository->getByTransactionId(
* $parentTransactionId,
* $paymentId,
* $orderId
* );
* }
* return $transaction ?: $this->transactionRepository->getByTransactionType(
* Transaction::TYPE_AUTH,
* $paymentId,
* $orderId
* );
* }
* The code is the same in Magento 2.0.0 - 2.2.1:
* https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Sales/Model/Order/Payment/Transaction/Manager.php#L31-L47
* https://github.com/magento/magento2/blob/2.2.1/app/code/Magento/Sales/Model/Order/Payment/Transaction/Manager.php#L31-L47
* It is exactly what we need,
* because the module can be set up to capture payments without a preliminary authorization.
*/
if ($tPrev = $ii->getAuthorizationTransaction() /** @var T|false $tPrev */) {
$id = $this->i2e($tPrev->getTxnId()); /** @var string $id */
// 2016-03-24
// Credit Memo и Invoice отсутствуют в сценарии Authorize / Capture
// и присутствуют в сценарии Capture / Refund.
$cm = $ii->getCreditmemo(); /** @var CM|null $cm */
$fc = $this->fCharge(); /** @var fCharge $fc */
$resp = $cm ? $fc->refund($id, $this->amountFormat($a)) : $fc->void($id); /** @var object $resp */
$this->transInfo($resp);
$ii->setTransactionId($this->e2i($id, $cm ? Ev::T_REFUND : 'void'));
if ($cm) {
/**
* 2017-01-19
* Записаваем идентификатор операции в БД,
* чтобы затем, при обработке оповещений от платёжной системы,
* проверять, не было ли это оповещение инициировано нашей же операцией,
* и если было, то не обрабатывать его повторно:
* @see \Df\Payment\W\Strategy\Refund::_handle()
* https://github.com/mage2pro/core/blob/1.12.16/StripeClone/WebhookStrategy/Charge/Refunded.php?ts=4#L21-L23
*/
dfp_container_add($this->ii(), self::II_TRANS, fRefund::s($this)->transId($resp));
}
}
} | [
"final",
"protected",
"function",
"_refund",
"(",
"$",
"a",
")",
"{",
"$",
"ii",
"=",
"$",
"this",
"->",
"ii",
"(",
")",
";",
"/** @var OP $ii */",
"/**\n\t\t * 2016-03-17, 2017-11-11\n\t\t * Despite of its name, @uses \\Magento\\Sales\\Model\\Order\\Payment::getAuthorization... | 2017-01-19
@override
@see \Df\Payment\Method::_refund()
@used-by \Df\Payment\Method::refund()
@param float|null $a | [
"2017",
"-",
"01",
"-",
"19"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/StripeClone/Method.php#L460-L523 | train |
mage2pro/core | StripeClone/Method.php | Method.transInfo | private function transInfo($response, array $request = []) {
$responseA = fO::s($this)->toArray($response); /** @var array(string => mixed) $responseA */
if ($this->s()->log()) {
// 2017-01-12, 2017-12-07
// I log the both request and its response to Sentry, but I log only response to the local log
dfp_report($this, $responseA, df_caller_ff());
}
$this->iiaSetTRR($request, $responseA);
} | php | private function transInfo($response, array $request = []) {
$responseA = fO::s($this)->toArray($response); /** @var array(string => mixed) $responseA */
if ($this->s()->log()) {
// 2017-01-12, 2017-12-07
// I log the both request and its response to Sentry, but I log only response to the local log
dfp_report($this, $responseA, df_caller_ff());
}
$this->iiaSetTRR($request, $responseA);
} | [
"private",
"function",
"transInfo",
"(",
"$",
"response",
",",
"array",
"$",
"request",
"=",
"[",
"]",
")",
"{",
"$",
"responseA",
"=",
"fO",
"::",
"s",
"(",
"$",
"this",
")",
"->",
"toArray",
"(",
"$",
"response",
")",
";",
"/** @var array(string => m... | 2016-12-27
@used-by _refund()
@used-by charge()
@used-by chargeNew()
@param object $response
@param array(string => mixed) $request [optional] | [
"2016",
"-",
"12",
"-",
"27"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/StripeClone/Method.php#L789-L797 | train |
mage2pro/core | Payment/W/Strategy/CapturePreauthorized.php | CapturePreauthorized._handle | protected function _handle() {
$o = $this->o(); /** @var O|DFO $o */
// 2016-12-30
// Мы не должны считать исключительной ситуацией повторное получение
// ранее уже полученного оповещения.
// В документации к Stripe, например, явно сказано:
// «Webhook endpoints may occasionally receive the same event more than once.
// We advise you to guard against duplicated event receipts
// by making your event processing idempotent.»
// https://stripe.com/docs/webhooks#best-practices
if (!$o->canInvoice()) {
$this->softFailure('The order does not allow an invoice to be created.');
}
else {
$o->setCustomerNoteNotify(true)->setIsInProcess(true);
/** @var Invoice $i */
df_db_transaction()->addObject($i = $this->invoice())->addObject($o)->save();
df_mail_invoice($i);
// 2017-09-13
// We do not set a response here, because PayPal clones require a specific response on success.
}
} | php | protected function _handle() {
$o = $this->o(); /** @var O|DFO $o */
// 2016-12-30
// Мы не должны считать исключительной ситуацией повторное получение
// ранее уже полученного оповещения.
// В документации к Stripe, например, явно сказано:
// «Webhook endpoints may occasionally receive the same event more than once.
// We advise you to guard against duplicated event receipts
// by making your event processing idempotent.»
// https://stripe.com/docs/webhooks#best-practices
if (!$o->canInvoice()) {
$this->softFailure('The order does not allow an invoice to be created.');
}
else {
$o->setCustomerNoteNotify(true)->setIsInProcess(true);
/** @var Invoice $i */
df_db_transaction()->addObject($i = $this->invoice())->addObject($o)->save();
df_mail_invoice($i);
// 2017-09-13
// We do not set a response here, because PayPal clones require a specific response on success.
}
} | [
"protected",
"function",
"_handle",
"(",
")",
"{",
"$",
"o",
"=",
"$",
"this",
"->",
"o",
"(",
")",
";",
"/** @var O|DFO $o */",
"// 2016-12-30",
"// Мы не должны считать исключительной ситуацией повторное получение",
"// ранее уже полученного оповещения.",
"// В документации... | 2017-01-07
@override
@see \Df\Payment\W\Strategy::_handle()
@used-by \Df\Payment\W\Strategy::handle() | [
"2017",
"-",
"01",
"-",
"07"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Payment/W/Strategy/CapturePreauthorized.php#L38-L59 | train |
mage2pro/core | Payment/W/Strategy/CapturePreauthorized.php | CapturePreauthorized.invoice | private function invoice() {
$invoiceService = df_o(InvoiceService::class); /** @var InvoiceService $invoiceService */
/** @var Invoice|DfInvoice $result */
if (!($result = $invoiceService->prepareInvoice($this->o()))) {
throw new LE(__('We can\'t save the invoice right now.'));
}
if (!$result->getTotalQty()) {
throw new LE(__('You can\'t create an invoice without products.'));
}
df_register('current_invoice', $result);
/**
* 2016-03-26
* @used-by \Magento\Sales\Model\Order\Invoice::register()
* https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Sales/Model/Order/Invoice.php#L599-L609
* Используем именно @see \Magento\Sales\Model\Order\Invoice::CAPTURE_ONLINE,
* а не @see \Magento\Sales\Model\Order\Invoice::CAPTURE_OFFINE,
* чтобы была создана транзакция capture.
*/
$result->setRequestedCaptureCase(Invoice::CAPTURE_ONLINE);
$result->register();
return $result;
} | php | private function invoice() {
$invoiceService = df_o(InvoiceService::class); /** @var InvoiceService $invoiceService */
/** @var Invoice|DfInvoice $result */
if (!($result = $invoiceService->prepareInvoice($this->o()))) {
throw new LE(__('We can\'t save the invoice right now.'));
}
if (!$result->getTotalQty()) {
throw new LE(__('You can\'t create an invoice without products.'));
}
df_register('current_invoice', $result);
/**
* 2016-03-26
* @used-by \Magento\Sales\Model\Order\Invoice::register()
* https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Sales/Model/Order/Invoice.php#L599-L609
* Используем именно @see \Magento\Sales\Model\Order\Invoice::CAPTURE_ONLINE,
* а не @see \Magento\Sales\Model\Order\Invoice::CAPTURE_OFFINE,
* чтобы была создана транзакция capture.
*/
$result->setRequestedCaptureCase(Invoice::CAPTURE_ONLINE);
$result->register();
return $result;
} | [
"private",
"function",
"invoice",
"(",
")",
"{",
"$",
"invoiceService",
"=",
"df_o",
"(",
"InvoiceService",
"::",
"class",
")",
";",
"/** @var InvoiceService $invoiceService */",
"/** @var Invoice|DfInvoice $result */",
"if",
"(",
"!",
"(",
"$",
"result",
"=",
"$",
... | 2016-03-26
@used-by _handle()
@return Invoice|DfInvoice
@throws LE | [
"2016",
"-",
"03",
"-",
"26"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Payment/W/Strategy/CapturePreauthorized.php#L67-L88 | train |
mage2pro/core | Checkout/Block/Messages.php | Messages._toHtml | final protected function _toHtml() {
$sess = df_checkout_session(); /** @var Session|DfSession $m */
$m = $sess->getDfMessages(); /** @var array(array(string => bool|Phrase)) $m */
$sess->unsDfMessages();
return !$m ? '' : df_js(__CLASS__, 'messages', ['messages' => $m]);
} | php | final protected function _toHtml() {
$sess = df_checkout_session(); /** @var Session|DfSession $m */
$m = $sess->getDfMessages(); /** @var array(array(string => bool|Phrase)) $m */
$sess->unsDfMessages();
return !$m ? '' : df_js(__CLASS__, 'messages', ['messages' => $m]);
} | [
"final",
"protected",
"function",
"_toHtml",
"(",
")",
"{",
"$",
"sess",
"=",
"df_checkout_session",
"(",
")",
";",
"/** @var Session|DfSession $m */",
"$",
"m",
"=",
"$",
"sess",
"->",
"getDfMessages",
"(",
")",
";",
"/** @var array(array(string => bool|Phrase)) $m... | 2016-07-14
@override
@see _P::_toHtml()
@used-by _P::toHtml():
$html = $this->_loadCache();
if ($html === false) {
if ($this->hasData('translate_inline')) {
$this->inlineTranslation->suspend($this->getData('translate_inline'));
}
$this->_beforeToHtml();
$html = $this->_toHtml();
$this->_saveCache($html);
if ($this->hasData('translate_inline')) {
$this->inlineTranslation->resume();
}
}
$html = $this->_afterToHtml($html);
https://github.com/magento/magento2/blob/2.2.0/lib/internal/Magento/Framework/View/Element/AbstractBlock.php#L643-L689
@return string | [
"2016",
"-",
"07",
"-",
"14"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Checkout/Block/Messages.php#L33-L38 | train |
mage2pro/core | Sentry/Client.php | Client.setProcessorsFromOptions | function setProcessorsFromOptions($options)
{
$processors = [];
foreach (Util::get($options, 'processors', self::getDefaultProcessors()) as $processor) {
$new_processor = new $processor($this);
if (isset($options['processorOptions']) && is_array($options['processorOptions'])) {
if (isset($options['processorOptions'][$processor]) && method_exists($processor, 'setProcessorOptions')) {
$new_processor->setProcessorOptions($options['processorOptions'][$processor]);
}
}
$processors[] = $new_processor;
}
return $processors;
} | php | function setProcessorsFromOptions($options)
{
$processors = [];
foreach (Util::get($options, 'processors', self::getDefaultProcessors()) as $processor) {
$new_processor = new $processor($this);
if (isset($options['processorOptions']) && is_array($options['processorOptions'])) {
if (isset($options['processorOptions'][$processor]) && method_exists($processor, 'setProcessorOptions')) {
$new_processor->setProcessorOptions($options['processorOptions'][$processor]);
}
}
$processors[] = $new_processor;
}
return $processors;
} | [
"function",
"setProcessorsFromOptions",
"(",
"$",
"options",
")",
"{",
"$",
"processors",
"=",
"[",
"]",
";",
"foreach",
"(",
"Util",
"::",
"get",
"(",
"$",
"options",
",",
"'processors'",
",",
"self",
"::",
"getDefaultProcessors",
"(",
")",
")",
"as",
"... | Sets the Processor sub-classes to be used when data is processed before being
sent to Sentry.
@param $options
@return array | [
"Sets",
"the",
"Processor",
"sub",
"-",
"classes",
"to",
"be",
"used",
"when",
"data",
"is",
"processed",
"before",
"being",
"sent",
"to",
"Sentry",
"."
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L282-L296 | train |
mage2pro/core | Sentry/Client.php | Client.parseDSN | static function parseDSN($dsn)
{
$url = parse_url($dsn);
$scheme = (isset($url['scheme']) ? $url['scheme'] : '');
if (!in_array($scheme, array('http', 'https'))) {
throw new \InvalidArgumentException('Unsupported Sentry DSN scheme: ' . (!empty($scheme) ? $scheme : '<not set>'));
}
$netloc = (isset($url['host']) ? $url['host'] : null);
$netloc.= (isset($url['port']) ? ':'.$url['port'] : null);
$rawpath = (isset($url['path']) ? $url['path'] : null);
if ($rawpath) {
$pos = strrpos($rawpath, '/', 1);
if ($pos !== false) {
$path = substr($rawpath, 0, $pos);
$project = substr($rawpath, $pos + 1);
} else {
$path = '';
$project = substr($rawpath, 1);
}
} else {
$project = null;
$path = '';
}
$username = (isset($url['user']) ? $url['user'] : null);
$password = (isset($url['pass']) ? $url['pass'] : null);
if (empty($netloc) || empty($project) || empty($username) || empty($password)) {
throw new \InvalidArgumentException('Invalid Sentry DSN: ' . $dsn);
}
return array(
'server' => sprintf('%s://%s%s/api/%s/store/', $scheme, $netloc, $path, $project),
'project' => $project,
'public_key' => $username,
'secret_key' => $password,
);
} | php | static function parseDSN($dsn)
{
$url = parse_url($dsn);
$scheme = (isset($url['scheme']) ? $url['scheme'] : '');
if (!in_array($scheme, array('http', 'https'))) {
throw new \InvalidArgumentException('Unsupported Sentry DSN scheme: ' . (!empty($scheme) ? $scheme : '<not set>'));
}
$netloc = (isset($url['host']) ? $url['host'] : null);
$netloc.= (isset($url['port']) ? ':'.$url['port'] : null);
$rawpath = (isset($url['path']) ? $url['path'] : null);
if ($rawpath) {
$pos = strrpos($rawpath, '/', 1);
if ($pos !== false) {
$path = substr($rawpath, 0, $pos);
$project = substr($rawpath, $pos + 1);
} else {
$path = '';
$project = substr($rawpath, 1);
}
} else {
$project = null;
$path = '';
}
$username = (isset($url['user']) ? $url['user'] : null);
$password = (isset($url['pass']) ? $url['pass'] : null);
if (empty($netloc) || empty($project) || empty($username) || empty($password)) {
throw new \InvalidArgumentException('Invalid Sentry DSN: ' . $dsn);
}
return array(
'server' => sprintf('%s://%s%s/api/%s/store/', $scheme, $netloc, $path, $project),
'project' => $project,
'public_key' => $username,
'secret_key' => $password,
);
} | [
"static",
"function",
"parseDSN",
"(",
"$",
"dsn",
")",
"{",
"$",
"url",
"=",
"parse_url",
"(",
"$",
"dsn",
")",
";",
"$",
"scheme",
"=",
"(",
"isset",
"(",
"$",
"url",
"[",
"'scheme'",
"]",
")",
"?",
"$",
"url",
"[",
"'scheme'",
"]",
":",
"''"... | Parses a Raven-compatible DSN and returns an array of its values.
@param string $dsn Raven compatible DSN: http://raven.readthedocs.org/en/latest/config/#the-sentry-dsn
@return array parsed DSN | [
"Parses",
"a",
"Raven",
"-",
"compatible",
"DSN",
"and",
"returns",
"an",
"array",
"of",
"its",
"values",
"."
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L304-L339 | train |
mage2pro/core | Sentry/Client.php | Client.captureException | function captureException(E $e, $data=null, $logger=null, $vars=null) {
if (in_array(get_class($e), $this->exclude)) {
return null;
}
if ($data === null) {
$data = [];
}
$eOriginal = $e; /** @var E $eOriginal */
do {
$isDFE = $e instanceof DFE;
$exc_data = [
'type' => $isDFE ? $e->sentryType() : get_class($e)
,'value' => $this->serializer->serialize($isDFE ? $e->messageSentry() : $e->getMessage())
];
/**'exception'
* Exception::getTrace doesn't store the point at where the exception
* was thrown, so we have to stuff it in ourselves. Ugh.
*/
$trace = $e->getTrace();
/**
* 2016-12-22
* Убираем @see \Magento\Framework\App\ErrorHandler
* 2016-12-23
* И @see Breadcrumbs\ErrorHandler тоже убираем.
*/
/** @var bool $needAddFaceFrame */
$needAddFakeFrame = !self::needSkipFrame($trace[0]);
while (self::needSkipFrame($trace[0])) {
array_shift($trace);
}
if ($needAddFakeFrame) {
$frame_where_exception_thrown = array(
'file' => $e->getFile(),
'line' => $e->getLine(),
);
array_unshift($trace, $frame_where_exception_thrown);
}
$exc_data['stacktrace'] = array(
'frames' => Stacktrace::get_stack_info(
$trace, $this->trace, $vars, $this->message_limit, $this->prefixes,
$this->app_path, $this->excluded_app_paths, $this->serializer, $this->reprSerializer
),
);
$exceptions[] = $exc_data;
} while ($e = $e->getPrevious());
$data['exception'] = array('values' => array_reverse($exceptions),);
if ($logger !== null) {
$data['logger'] = $logger;
}
if (empty($data['level'])) {
if (method_exists($eOriginal, 'getSeverity')) {
$data['level'] = $this->translateSeverity($eOriginal->getSeverity());
}
else {
$data['level'] = self::ERROR;
}
}
return $this->capture($data, $trace, $vars);
} | php | function captureException(E $e, $data=null, $logger=null, $vars=null) {
if (in_array(get_class($e), $this->exclude)) {
return null;
}
if ($data === null) {
$data = [];
}
$eOriginal = $e; /** @var E $eOriginal */
do {
$isDFE = $e instanceof DFE;
$exc_data = [
'type' => $isDFE ? $e->sentryType() : get_class($e)
,'value' => $this->serializer->serialize($isDFE ? $e->messageSentry() : $e->getMessage())
];
/**'exception'
* Exception::getTrace doesn't store the point at where the exception
* was thrown, so we have to stuff it in ourselves. Ugh.
*/
$trace = $e->getTrace();
/**
* 2016-12-22
* Убираем @see \Magento\Framework\App\ErrorHandler
* 2016-12-23
* И @see Breadcrumbs\ErrorHandler тоже убираем.
*/
/** @var bool $needAddFaceFrame */
$needAddFakeFrame = !self::needSkipFrame($trace[0]);
while (self::needSkipFrame($trace[0])) {
array_shift($trace);
}
if ($needAddFakeFrame) {
$frame_where_exception_thrown = array(
'file' => $e->getFile(),
'line' => $e->getLine(),
);
array_unshift($trace, $frame_where_exception_thrown);
}
$exc_data['stacktrace'] = array(
'frames' => Stacktrace::get_stack_info(
$trace, $this->trace, $vars, $this->message_limit, $this->prefixes,
$this->app_path, $this->excluded_app_paths, $this->serializer, $this->reprSerializer
),
);
$exceptions[] = $exc_data;
} while ($e = $e->getPrevious());
$data['exception'] = array('values' => array_reverse($exceptions),);
if ($logger !== null) {
$data['logger'] = $logger;
}
if (empty($data['level'])) {
if (method_exists($eOriginal, 'getSeverity')) {
$data['level'] = $this->translateSeverity($eOriginal->getSeverity());
}
else {
$data['level'] = self::ERROR;
}
}
return $this->capture($data, $trace, $vars);
} | [
"function",
"captureException",
"(",
"E",
"$",
"e",
",",
"$",
"data",
"=",
"null",
",",
"$",
"logger",
"=",
"null",
",",
"$",
"vars",
"=",
"null",
")",
"{",
"if",
"(",
"in_array",
"(",
"get_class",
"(",
"$",
"e",
")",
",",
"$",
"this",
"->",
"e... | Log an exception to sentry
@param E|DFE $e
@param array $data | [
"Log",
"an",
"exception",
"to",
"sentry"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L404-L462 | train |
mage2pro/core | Sentry/Client.php | Client.captureQuery | function captureQuery($query, $level=self::INFO, $engine = '')
{
$data = array(
'message' => $query,
'level' => $level,
'sentry.interfaces.Query' => array(
'query' => $query
)
);
if ($engine !== '') {
$data['sentry.interfaces.Query']['engine'] = $engine;
}
return $this->capture($data, false);
} | php | function captureQuery($query, $level=self::INFO, $engine = '')
{
$data = array(
'message' => $query,
'level' => $level,
'sentry.interfaces.Query' => array(
'query' => $query
)
);
if ($engine !== '') {
$data['sentry.interfaces.Query']['engine'] = $engine;
}
return $this->capture($data, false);
} | [
"function",
"captureQuery",
"(",
"$",
"query",
",",
"$",
"level",
"=",
"self",
"::",
"INFO",
",",
"$",
"engine",
"=",
"''",
")",
"{",
"$",
"data",
"=",
"array",
"(",
"'message'",
"=>",
"$",
"query",
",",
"'level'",
"=>",
"$",
"level",
",",
"'sentry... | Log an query to sentry | [
"Log",
"an",
"query",
"to",
"sentry"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L485-L499 | train |
mage2pro/core | Sentry/Client.php | Client.send | function send(&$data)
{
if (
is_callable($this->send_callback)
&& false === call_user_func_array($this->send_callback, array(&$data))
) {
// if send_callback returns false, end native send
return;
}
if (!$this->server) {
return;
}
if ($this->transport) {
return call_user_func($this->transport, $this, $data);
}
$message = $this->encode($data);
$headers = array(
'User-Agent' => $this->getUserAgent(),
'X-Sentry-Auth' => $this->getAuthHeader(),
'Content-Type' => 'application/octet-stream'
);
$this->send_remote($this->server, $message, $headers);
} | php | function send(&$data)
{
if (
is_callable($this->send_callback)
&& false === call_user_func_array($this->send_callback, array(&$data))
) {
// if send_callback returns false, end native send
return;
}
if (!$this->server) {
return;
}
if ($this->transport) {
return call_user_func($this->transport, $this, $data);
}
$message = $this->encode($data);
$headers = array(
'User-Agent' => $this->getUserAgent(),
'X-Sentry-Auth' => $this->getAuthHeader(),
'Content-Type' => 'application/octet-stream'
);
$this->send_remote($this->server, $message, $headers);
} | [
"function",
"send",
"(",
"&",
"$",
"data",
")",
"{",
"if",
"(",
"is_callable",
"(",
"$",
"this",
"->",
"send_callback",
")",
"&&",
"false",
"===",
"call_user_func_array",
"(",
"$",
"this",
"->",
"send_callback",
",",
"array",
"(",
"&",
"$",
"data",
")"... | Wrapper to handle encoding and sending data to the Sentry API server.
@param array $data Associative array of data to log | [
"Wrapper",
"to",
"handle",
"encoding",
"and",
"sending",
"data",
"to",
"the",
"Sentry",
"API",
"server",
"."
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L781-L808 | train |
mage2pro/core | Sentry/Client.php | Client.send_remote | private function send_remote($url, $data, $headers=[])
{
$parts = parse_url($url);
$parts['netloc'] = $parts['host'].(isset($parts['port']) ? ':'.$parts['port'] : null);
$this->send_http($url, $data, $headers);
} | php | private function send_remote($url, $data, $headers=[])
{
$parts = parse_url($url);
$parts['netloc'] = $parts['host'].(isset($parts['port']) ? ':'.$parts['port'] : null);
$this->send_http($url, $data, $headers);
} | [
"private",
"function",
"send_remote",
"(",
"$",
"url",
",",
"$",
"data",
",",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"$",
"parts",
"=",
"parse_url",
"(",
"$",
"url",
")",
";",
"$",
"parts",
"[",
"'netloc'",
"]",
"=",
"$",
"parts",
"[",
"'host'"... | Send data to Sentry
@param string $url Full URL to Sentry
@param array $data Associative array of data to log
@param array $headers Associative array of headers | [
"Send",
"data",
"to",
"Sentry"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L817-L822 | train |
mage2pro/core | Sentry/Client.php | Client.send_http | private function send_http($url, $data, $headers=[])
{
if ($this->curl_method == 'async') {
$this->_curl_handler->enqueue($url, $data, $headers);
} elseif ($this->curl_method == 'exec') {
$this->send_http_asynchronous_curl_exec($url, $data, $headers);
} else {
$this->send_http_synchronous($url, $data, $headers);
}
} | php | private function send_http($url, $data, $headers=[])
{
if ($this->curl_method == 'async') {
$this->_curl_handler->enqueue($url, $data, $headers);
} elseif ($this->curl_method == 'exec') {
$this->send_http_asynchronous_curl_exec($url, $data, $headers);
} else {
$this->send_http_synchronous($url, $data, $headers);
}
} | [
"private",
"function",
"send_http",
"(",
"$",
"url",
",",
"$",
"data",
",",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"curl_method",
"==",
"'async'",
")",
"{",
"$",
"this",
"->",
"_curl_handler",
"->",
"enqueue",
"(",
"... | Send the message over http to the sentry url given
@param string $url URL of the Sentry instance to log to
@param array $data Associative array of data to log
@param array $headers Associative array of headers | [
"Send",
"the",
"message",
"over",
"http",
"to",
"the",
"sentry",
"url",
"given"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L875-L884 | train |
mage2pro/core | Sentry/Client.php | Client.send_http_asynchronous_curl_exec | private function send_http_asynchronous_curl_exec($url, $data, $headers)
{
exec($this->buildCurlCommand($url, $data, $headers));
return true; // The exec method is just fire and forget, so just assume it always works
} | php | private function send_http_asynchronous_curl_exec($url, $data, $headers)
{
exec($this->buildCurlCommand($url, $data, $headers));
return true; // The exec method is just fire and forget, so just assume it always works
} | [
"private",
"function",
"send_http_asynchronous_curl_exec",
"(",
"$",
"url",
",",
"$",
"data",
",",
"$",
"headers",
")",
"{",
"exec",
"(",
"$",
"this",
"->",
"buildCurlCommand",
"(",
"$",
"url",
",",
"$",
"data",
",",
"$",
"headers",
")",
")",
";",
"ret... | Send the cURL to Sentry asynchronously. No errors will be returned from cURL
@param string $url URL of the Sentry instance to log to
@param array $data Associative array of data to log
@param array $headers Associative array of headers
@return bool | [
"Send",
"the",
"cURL",
"to",
"Sentry",
"asynchronously",
".",
"No",
"errors",
"will",
"be",
"returned",
"from",
"cURL"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L912-L916 | train |
mage2pro/core | Sentry/Client.php | Client.send_http_synchronous | private function send_http_synchronous($url, $data, $headers)
{
$new_headers = [];
foreach ($headers as $key => $value) {
array_push($new_headers, $key .': '. $value);
}
// XXX(dcramer): Prevent 100-continue response form server (Fixes GH-216)
$new_headers[] = 'Expect:';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $new_headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$options = $this->get_curl_options();
$ca_cert = $options[CURLOPT_CAINFO];
unset($options[CURLOPT_CAINFO]);
curl_setopt_array($curl, $options);
curl_exec($curl);
$errno = curl_errno($curl);
// CURLE_SSL_CACERT || CURLE_SSL_CACERT_BADFILE
if ($errno == 60 || $errno == 77) {
curl_setopt($curl, CURLOPT_CAINFO, $ca_cert);
curl_exec($curl);
}
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$success = ($code == 200);
if (!$success) {
// It'd be nice just to raise an exception here, but it's not very PHP-like
$this->_lasterror = curl_error($curl);
} else {
$this->_lasterror = null;
}
curl_close($curl);
return $success;
} | php | private function send_http_synchronous($url, $data, $headers)
{
$new_headers = [];
foreach ($headers as $key => $value) {
array_push($new_headers, $key .': '. $value);
}
// XXX(dcramer): Prevent 100-continue response form server (Fixes GH-216)
$new_headers[] = 'Expect:';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $new_headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$options = $this->get_curl_options();
$ca_cert = $options[CURLOPT_CAINFO];
unset($options[CURLOPT_CAINFO]);
curl_setopt_array($curl, $options);
curl_exec($curl);
$errno = curl_errno($curl);
// CURLE_SSL_CACERT || CURLE_SSL_CACERT_BADFILE
if ($errno == 60 || $errno == 77) {
curl_setopt($curl, CURLOPT_CAINFO, $ca_cert);
curl_exec($curl);
}
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$success = ($code == 200);
if (!$success) {
// It'd be nice just to raise an exception here, but it's not very PHP-like
$this->_lasterror = curl_error($curl);
} else {
$this->_lasterror = null;
}
curl_close($curl);
return $success;
} | [
"private",
"function",
"send_http_synchronous",
"(",
"$",
"url",
",",
"$",
"data",
",",
"$",
"headers",
")",
"{",
"$",
"new_headers",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"headers",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"array_push",
"(... | Send a blocking cURL to Sentry and check for errors from cURL
@param string $url URL of the Sentry instance to log to
@param array $data Associative array of data to log
@param array $headers Associative array of headers
@return bool | [
"Send",
"a",
"blocking",
"cURL",
"to",
"Sentry",
"and",
"check",
"for",
"errors",
"from",
"cURL"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L926-L966 | train |
mage2pro/core | Sentry/Client.php | Client.get_auth_header | protected function get_auth_header($timestamp, $client, $api_key, $secret_key)
{
$header = array(
sprintf('sentry_timestamp=%F', $timestamp),
"sentry_client={$client}",
sprintf('sentry_version=%s', self::PROTOCOL),
);
if ($api_key) {
$header[] = "sentry_key={$api_key}";
}
if ($secret_key) {
$header[] = "sentry_secret={$secret_key}";
}
return sprintf('Sentry %s', implode(', ', $header));
} | php | protected function get_auth_header($timestamp, $client, $api_key, $secret_key)
{
$header = array(
sprintf('sentry_timestamp=%F', $timestamp),
"sentry_client={$client}",
sprintf('sentry_version=%s', self::PROTOCOL),
);
if ($api_key) {
$header[] = "sentry_key={$api_key}";
}
if ($secret_key) {
$header[] = "sentry_secret={$secret_key}";
}
return sprintf('Sentry %s', implode(', ', $header));
} | [
"protected",
"function",
"get_auth_header",
"(",
"$",
"timestamp",
",",
"$",
"client",
",",
"$",
"api_key",
",",
"$",
"secret_key",
")",
"{",
"$",
"header",
"=",
"array",
"(",
"sprintf",
"(",
"'sentry_timestamp=%F'",
",",
"$",
"timestamp",
")",
",",
"\"sen... | Generate a Sentry authorization header string
@param string $timestamp Timestamp when the event occurred
@param string $client HTTP client name (not Client object)
@param string $api_key Sentry API key
@param string $secret_key Sentry API key
@return string | [
"Generate",
"a",
"Sentry",
"authorization",
"header",
"string"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L977-L995 | train |
mage2pro/core | Sentry/Client.php | Client.uuid4 | private function uuid4()
{
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
// 16 bits for "time_mid"
mt_rand(0, 0xffff),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,
// 48 bits for "node"
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
return str_replace('-', '', $uuid);
} | php | private function uuid4()
{
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
// 16 bits for "time_mid"
mt_rand(0, 0xffff),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,
// 48 bits for "node"
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
return str_replace('-', '', $uuid);
} | [
"private",
"function",
"uuid4",
"(",
")",
"{",
"$",
"uuid",
"=",
"sprintf",
"(",
"'%04x%04x-%04x-%04x-%04x-%04x%04x%04x'",
",",
"// 32 bits for \"time_low\"",
"mt_rand",
"(",
"0",
",",
"0xffff",
")",
",",
"mt_rand",
"(",
"0",
",",
"0xffff",
")",
",",
"// 16 bi... | Generate an uuid4 value
@return string | [
"Generate",
"an",
"uuid4",
"value"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L1008-L1031 | train |
mage2pro/core | Sentry/Client.php | Client.get_current_url | protected function get_current_url()
{
// When running from commandline the REQUEST_URI is missing.
if (!isset($_SERVER['REQUEST_URI'])) {
return null;
}
// HTTP_HOST is a client-supplied header that is optional in HTTP 1.0
$host = (!empty($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST']
: (!empty($_SERVER['LOCAL_ADDR']) ? $_SERVER['LOCAL_ADDR']
: (!empty($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '')));
$httpS = $this->isHttps() ? 's' : '';
return "http{$httpS}://{$host}{$_SERVER['REQUEST_URI']}";
} | php | protected function get_current_url()
{
// When running from commandline the REQUEST_URI is missing.
if (!isset($_SERVER['REQUEST_URI'])) {
return null;
}
// HTTP_HOST is a client-supplied header that is optional in HTTP 1.0
$host = (!empty($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST']
: (!empty($_SERVER['LOCAL_ADDR']) ? $_SERVER['LOCAL_ADDR']
: (!empty($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '')));
$httpS = $this->isHttps() ? 's' : '';
return "http{$httpS}://{$host}{$_SERVER['REQUEST_URI']}";
} | [
"protected",
"function",
"get_current_url",
"(",
")",
"{",
"// When running from commandline the REQUEST_URI is missing.",
"if",
"(",
"!",
"isset",
"(",
"$",
"_SERVER",
"[",
"'REQUEST_URI'",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"// HTTP_HOST is a client-sup... | Return the URL for the current request
@return string|null | [
"Return",
"the",
"URL",
"for",
"the",
"current",
"request"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L1038-L1052 | train |
mage2pro/core | Sentry/Client.php | Client.isHttps | protected function isHttps()
{
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
return true;
}
if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) {
return true;
}
if (!empty($this->trust_x_forwarded_proto) &&
!empty($_SERVER['X-FORWARDED-PROTO']) &&
$_SERVER['X-FORWARDED-PROTO'] === 'https') {
return true;
}
return false;
} | php | protected function isHttps()
{
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
return true;
}
if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) {
return true;
}
if (!empty($this->trust_x_forwarded_proto) &&
!empty($_SERVER['X-FORWARDED-PROTO']) &&
$_SERVER['X-FORWARDED-PROTO'] === 'https') {
return true;
}
return false;
} | [
"protected",
"function",
"isHttps",
"(",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"_SERVER",
"[",
"'HTTPS'",
"]",
")",
"&&",
"$",
"_SERVER",
"[",
"'HTTPS'",
"]",
"!==",
"'off'",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"empty",
"... | Was the current request made over https?
@return bool | [
"Was",
"the",
"current",
"request",
"made",
"over",
"https?"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L1059-L1076 | train |
mage2pro/core | Sentry/Client.php | Client.translateSeverity | function translateSeverity($severity)
{
if (is_array($this->severity_map) && isset($this->severity_map[$severity])) {
return $this->severity_map[$severity];
}
switch ($severity) {
case E_ERROR: return Client::ERROR;
case E_WARNING: return Client::WARN;
case E_PARSE: return Client::ERROR;
case E_NOTICE: return Client::INFO;
case E_CORE_ERROR: return Client::ERROR;
case E_CORE_WARNING: return Client::WARN;
case E_COMPILE_ERROR: return Client::ERROR;
case E_COMPILE_WARNING: return Client::WARN;
case E_USER_ERROR: return Client::ERROR;
case E_USER_WARNING: return Client::WARN;
case E_USER_NOTICE: return Client::INFO;
case E_STRICT: return Client::INFO;
case E_RECOVERABLE_ERROR: return Client::ERROR;
}
if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
switch ($severity) {
case E_DEPRECATED: return Client::WARN;
case E_USER_DEPRECATED: return Client::WARN;
}
}
return Client::ERROR;
} | php | function translateSeverity($severity)
{
if (is_array($this->severity_map) && isset($this->severity_map[$severity])) {
return $this->severity_map[$severity];
}
switch ($severity) {
case E_ERROR: return Client::ERROR;
case E_WARNING: return Client::WARN;
case E_PARSE: return Client::ERROR;
case E_NOTICE: return Client::INFO;
case E_CORE_ERROR: return Client::ERROR;
case E_CORE_WARNING: return Client::WARN;
case E_COMPILE_ERROR: return Client::ERROR;
case E_COMPILE_WARNING: return Client::WARN;
case E_USER_ERROR: return Client::ERROR;
case E_USER_WARNING: return Client::WARN;
case E_USER_NOTICE: return Client::INFO;
case E_STRICT: return Client::INFO;
case E_RECOVERABLE_ERROR: return Client::ERROR;
}
if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
switch ($severity) {
case E_DEPRECATED: return Client::WARN;
case E_USER_DEPRECATED: return Client::WARN;
}
}
return Client::ERROR;
} | [
"function",
"translateSeverity",
"(",
"$",
"severity",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"severity_map",
")",
"&&",
"isset",
"(",
"$",
"this",
"->",
"severity_map",
"[",
"$",
"severity",
"]",
")",
")",
"{",
"return",
"$",
"this",... | Translate a PHP Error constant into a Sentry log level group
@param string $severity PHP E_$x error constant
@return string Sentry log level group | [
"Translate",
"a",
"PHP",
"Error",
"constant",
"into",
"a",
"Sentry",
"log",
"level",
"group"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L1099-L1126 | train |
mage2pro/core | Sentry/Client.php | Client.set_user_data | function set_user_data($id, $email=null, $data=[])
{
$user = array('id' => $id);
if (isset($email)) {
$user['email'] = $email;
}
$this->user_context(array_merge($user, $data));
} | php | function set_user_data($id, $email=null, $data=[])
{
$user = array('id' => $id);
if (isset($email)) {
$user['email'] = $email;
}
$this->user_context(array_merge($user, $data));
} | [
"function",
"set_user_data",
"(",
"$",
"id",
",",
"$",
"email",
"=",
"null",
",",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"$",
"user",
"=",
"array",
"(",
"'id'",
"=>",
"$",
"id",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"email",
")",
")",
"{",
... | Convenience function for setting a user's ID and Email
@deprecated
@param string $id User's ID
@param string|null $email User's email
@param array $data Additional user data | [
"Convenience",
"function",
"for",
"setting",
"a",
"user",
"s",
"ID",
"and",
"Email"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L1147-L1154 | train |
mage2pro/core | Sentry/Client.php | Client.user_context | function user_context($data, $merge=true)
{
if ($merge && $this->context->user !== null) {
// bail if data is null
if (!$data) {
return;
}
$this->context->user = array_merge($this->context->user, $data);
} else {
$this->context->user = $data;
}
} | php | function user_context($data, $merge=true)
{
if ($merge && $this->context->user !== null) {
// bail if data is null
if (!$data) {
return;
}
$this->context->user = array_merge($this->context->user, $data);
} else {
$this->context->user = $data;
}
} | [
"function",
"user_context",
"(",
"$",
"data",
",",
"$",
"merge",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"merge",
"&&",
"$",
"this",
"->",
"context",
"->",
"user",
"!==",
"null",
")",
"{",
"// bail if data is null",
"if",
"(",
"!",
"$",
"data",
")",
... | Sets user context.
@param array $data Associative array of user data
@param bool $merge Merge existing context with new context | [
"Sets",
"user",
"context",
"."
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L1173-L1184 | train |
mage2pro/core | Sentry/Client.php | Client.needSkipFrame | private static function needSkipFrame(array $frame) {return
\Magento\Framework\App\ErrorHandler::class === dfa($frame, 'class')
|| df_ends_with(df_path_n(dfa($frame, 'file')), 'Sentry/Breadcrumbs/ErrorHandler.php')
;} | php | private static function needSkipFrame(array $frame) {return
\Magento\Framework\App\ErrorHandler::class === dfa($frame, 'class')
|| df_ends_with(df_path_n(dfa($frame, 'file')), 'Sentry/Breadcrumbs/ErrorHandler.php')
;} | [
"private",
"static",
"function",
"needSkipFrame",
"(",
"array",
"$",
"frame",
")",
"{",
"return",
"\\",
"Magento",
"\\",
"Framework",
"\\",
"App",
"\\",
"ErrorHandler",
"::",
"class",
"===",
"dfa",
"(",
"$",
"frame",
",",
"'class'",
")",
"||",
"df_ends_wit... | 2016-12-23
@param array(string => string|int|array) $frame
@return bool | [
"2016",
"-",
"12",
"-",
"23"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/Client.php#L1221-L1224 | train |
mage2pro/core | Core/R/ConT.php | ConT.p | static function p($allowAbstract, \Closure $f) {
/** @var bool $prev */
$prev = self::$allow_abstract;
self::$allow_abstract = $allowAbstract;
try {return $f();}
finally {self::$allow_abstract = $prev;}
} | php | static function p($allowAbstract, \Closure $f) {
/** @var bool $prev */
$prev = self::$allow_abstract;
self::$allow_abstract = $allowAbstract;
try {return $f();}
finally {self::$allow_abstract = $prev;}
} | [
"static",
"function",
"p",
"(",
"$",
"allowAbstract",
",",
"\\",
"Closure",
"$",
"f",
")",
"{",
"/** @var bool $prev */",
"$",
"prev",
"=",
"self",
"::",
"$",
"allow_abstract",
";",
"self",
"::",
"$",
"allow_abstract",
"=",
"$",
"allowAbstract",
";",
"try"... | 2017-04-01
@used-by dfpm_c()
@used-by dfsm_c()
@param bool $allowAbstract
@param \Closure $f
@return mixed | [
"2017",
"-",
"04",
"-",
"01"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Core/R/ConT.php#L13-L19 | train |
mage2pro/core | Backend/Model/Auth.php | Auth.loginByEmail | function loginByEmail($email) {
$this->_initCredentialStorage();
/** @var \Magento\Backend\Model\Auth\Credential\StorageInterface|\Magento\User\Model\User $user */
$user = $this->getCredentialStorage();
$user->{\Df\User\Plugin\Model\User::LOGIN_BY_EMAIL} = true;
$user->login($email, null);
if ($user->getId()) {
/** @var IStorage|\Magento\Backend\Model\Auth\Session $authSession */
$authSession = $this->getAuthStorage();
$authSession->setUser($user);
$authSession->processLogin();
//$cookieManager->setSensitiveCookie($session->getName(), session_id());
$_COOKIE[$authSession->getName()] = session_id();
df_session_manager()->setData(\Magento\Framework\Data\Form\FormKey::FORM_KEY, df_request('form_key'));
df_dispatch('backend_auth_user_login_success', ['user' => $user]);
// 2016-04-10
// Обязательно, иначе авторизация работать не будет.
// https://mage2.pro/t/1199
/** @var SecurityPlugin $securityPlugin */
$securityPlugin = df_o(SecurityPlugin::class);
$securityPlugin->afterLogin($this);
}
} | php | function loginByEmail($email) {
$this->_initCredentialStorage();
/** @var \Magento\Backend\Model\Auth\Credential\StorageInterface|\Magento\User\Model\User $user */
$user = $this->getCredentialStorage();
$user->{\Df\User\Plugin\Model\User::LOGIN_BY_EMAIL} = true;
$user->login($email, null);
if ($user->getId()) {
/** @var IStorage|\Magento\Backend\Model\Auth\Session $authSession */
$authSession = $this->getAuthStorage();
$authSession->setUser($user);
$authSession->processLogin();
//$cookieManager->setSensitiveCookie($session->getName(), session_id());
$_COOKIE[$authSession->getName()] = session_id();
df_session_manager()->setData(\Magento\Framework\Data\Form\FormKey::FORM_KEY, df_request('form_key'));
df_dispatch('backend_auth_user_login_success', ['user' => $user]);
// 2016-04-10
// Обязательно, иначе авторизация работать не будет.
// https://mage2.pro/t/1199
/** @var SecurityPlugin $securityPlugin */
$securityPlugin = df_o(SecurityPlugin::class);
$securityPlugin->afterLogin($this);
}
} | [
"function",
"loginByEmail",
"(",
"$",
"email",
")",
"{",
"$",
"this",
"->",
"_initCredentialStorage",
"(",
")",
";",
"/** @var \\Magento\\Backend\\Model\\Auth\\Credential\\StorageInterface|\\Magento\\User\\Model\\User $user */",
"$",
"user",
"=",
"$",
"this",
"->",
"getCred... | 2016-04-10
It is implemented by analogy with @see \Magento\Backend\Model\Auth::login()
https://github.com/magento/magento2/blob/052e789/app/code/Magento/Backend/Model/Auth.php#L137-L182
@param string $email
@throws \Magento\Framework\Exception\AuthenticationException | [
"2016",
"-",
"04",
"-",
"10",
"It",
"is",
"implemented",
"by",
"analogy",
"with"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Backend/Model/Auth.php#L14-L36 | train |
mage2pro/core | Shipping/Plugin/Model/CarrierFactoryT.php | CarrierFactoryT.aroundCreate | function aroundCreate(Sb $sb, \Closure $f, $c, $sid = null) {
/** @var $r */
if (!is_a($c, M::class, true)) {
$r = $f($c, $sid);
}
else {
$r = M::sg($c);
$r->setId($c);
$r->setStore($sid);
}
return $r;
} | php | function aroundCreate(Sb $sb, \Closure $f, $c, $sid = null) {
/** @var $r */
if (!is_a($c, M::class, true)) {
$r = $f($c, $sid);
}
else {
$r = M::sg($c);
$r->setId($c);
$r->setStore($sid);
}
return $r;
} | [
"function",
"aroundCreate",
"(",
"Sb",
"$",
"sb",
",",
"\\",
"Closure",
"$",
"f",
",",
"$",
"c",
",",
"$",
"sid",
"=",
"null",
")",
"{",
"/** @var $r */",
"if",
"(",
"!",
"is_a",
"(",
"$",
"c",
",",
"M",
"::",
"class",
",",
"true",
")",
")",
... | 2018-04-21
It forces the @see \Df\Shipping\Method descendants to be singletons:
@see \Magento\Shipping\Model\CarrierFactory::create()
https://github.com/magento/magento2/blob/2.2.3/app/code/Magento/Shipping/Model/CarrierFactory.php#L57-L80
@param Sb $sb
@param \Closure $f
@param string $c
@param int|null $sid [optional]
@return M|IM | [
"2018",
"-",
"04",
"-",
"21",
"It",
"forces",
"the"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Shipping/Plugin/Model/CarrierFactoryT.php#L19-L30 | train |
mage2pro/core | Sso/FE/CustomerReturn.php | CustomerReturn.url | final protected function url() {
$isBackend = df_fe_fc_b($this, 'dfWebhook_backend'); /** @var bool $isBackend */
$route = df_route($this->m(), df_fe_fc($this, 'dfWebhook_suffix'), $isBackend); /** @var string $route */
return $isBackend ? df_url_backend_ns($route) : df_url_frontend($route);
} | php | final protected function url() {
$isBackend = df_fe_fc_b($this, 'dfWebhook_backend'); /** @var bool $isBackend */
$route = df_route($this->m(), df_fe_fc($this, 'dfWebhook_suffix'), $isBackend); /** @var string $route */
return $isBackend ? df_url_backend_ns($route) : df_url_frontend($route);
} | [
"final",
"protected",
"function",
"url",
"(",
")",
"{",
"$",
"isBackend",
"=",
"df_fe_fc_b",
"(",
"$",
"this",
",",
"'dfWebhook_backend'",
")",
";",
"/** @var bool $isBackend */",
"$",
"route",
"=",
"df_route",
"(",
"$",
"this",
"->",
"m",
"(",
")",
",",
... | 2017-04-23
@see https://github.com/mage2pro/dynamics365/blob/0.0.4/etc/adminhtml/system.xml#L57
@override
@see \Df\Framework\Form\Element\Url::url()
@used-by \Df\Framework\Form\Element\Url::messageForOthers()
@return string | [
"2017",
"-",
"04",
"-",
"23"
] | e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f | https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sso/FE/CustomerReturn.php#L28-L32 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.