sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public static function relation($local, $foreign)
{
$relations = Config::table($local)->relations();
if (isset($relations->{$foreign}))
{
return true;
}
throw new dbException('Relation "' . $local . '" to "' . $foreign . '" doesn\'t exist');
} | Checking that relation between tables exists
@param string $local local table
@param string $foreign related table
@return bool relation exists
@throws dbException | entailment |
public function render()
{
// Set the request arguments as GET parameters
$_GET = $this->getRequestArguments();
// Instantiate a frontend controller
$typoScript = TypoScriptUtility::extractTypoScriptKeyForPidAndType(
$this->page,
$this->typeNum,
$this->config
);
try {
$this->controllerContext->getRequest()->setOriginalRequestMappingResults($this->validationErrors);
$result = $this->beautify(call_user_func_array([$GLOBALS['TSFE']->cObj, 'cObjGetSingle'], $typoScript));
// In case of an error
} catch (\Exception $e) {
$result = '<pre class="error"><strong>'.$e->getMessage().'</strong>'.PHP_EOL
.$e->getTraceAsString().'</pre>';
}
return $result;
} | Render this component
@return string Rendered component (HTML) | entailment |
protected function exportInternal()
{
// Read the linked TypoScript
if ($this->config !== null) {
$typoScript = TypoScriptUtility::extractTypoScriptKeyForPidAndType(
$this->page,
$this->typeNum,
$this->config
);
$this->template = empty($typoScript) ?
null : TypoScriptUtility::serialize(implode('.', explode('.', $this->config, -1)), $typoScript);
}
return parent::exportInternal();
} | Return component specific properties
@return array Component specific properties | entailment |
public function Field($properties=array()) {
$obj=($properties ? $this->customise($properties):$this);
Requirements::css(CB_DIR.'/javascript/external/syntaxhighlighter/themes/shCore.css');
Requirements::css(CB_DIR.'/javascript/external/syntaxhighlighter/themes/shCore'.$this->theme_file().'.css');
Requirements::css(CB_DIR.'/javascript/external/syntaxhighlighter/themes/shTheme'.$this->theme_file().'.css');
Requirements::css(CB_DIR.'/css/HighlightedContentField.css');
Requirements::javascript(CB_DIR.'/javascript/external/syntaxhighlighter/brushes/shCore.js');
$brushName=$this->getBrushName();
if(!empty($brushName)) {
Requirements::javascript(CB_DIR.'/javascript/external/syntaxhighlighter/brushes/'.$this->getBrushName().'.js');
}else {
$lang=SnippetLanguage::get()->filter('HighlightCode', Convert::raw2sql($this->language))->filter('UserLanguage', true)->first();
if(!empty($lang) && $lang!==false && $lang->ID>0 && !empty($lang->BrushFile)) {
Requirements::javascript($lang->BrushFile);
}
}
Requirements::javascript(CB_DIR.'/javascript/HighlightedContentField.js');
return $obj->renderWith('HighlightedContentField');
} | Returns the form field - used by templates. Although FieldHolder is generally what is inserted into templates, all of the field holder templates make use of $Field. It's expected that FieldHolder will give you the "complete" representation of the field on the form, whereas Field will give you the core editing widget, such as an input tag.
@param {array} $properties key value pairs of template variables
@return {string} Returns the html to be sent to the browser | entailment |
public function parse($resource) {
$result = array();
$fieldcnt = mysqli_num_fields($resource);
$fields_transform = array();
for($i=0;$i<$fieldcnt;$i++) {
$finfo = mysqli_fetch_field_direct($resource, $i);
if(isset(self::$mysqli_type[$finfo->type])) {
$fields_transform[$finfo->name] = self::$mysqli_to_php[self::$mysqli_type[$finfo->type]];
}
}
while($row = mysqli_fetch_assoc($resource)) {
foreach($fields_transform as $fieldname => $fieldtype) {
settype($row[$fieldname], $fieldtype);
}
$result[] = $row;
}
return $result;
} | Parse resource into array
@param resource $resource
@return array | entailment |
public function doSnippetSearch($keywords, $languageID=false, $folderID=false) {
$searchIndex=singleton('CodeBankSolrIndex');
$searchQuery=new SearchQuery();
$searchQuery->classes=array(
array(
'class'=>'Snippet',
'includeSubclasses'=>true
)
);
//Add language filtering
if($languageID!==false && $languageID>0) {
$searchQuery->filter('Snippet_LanguageID', $languageID);
}
//Add language filtering
if($folderID!==false && $folderID>0) {
$searchQuery->filter('Snippet_FolderID', $folderID);
}
//Configure search
$searchQuery->search($keywords, null, array(
'Snippet_Title'=>2,
'Snippet_Description'=>1
));
return $searchIndex->search($searchQuery, null, null)->Matches->getList();
} | Performs the search against the snippets in the system
@param {string} $keywords Keywords to search for
@param {int} $languageID Language to filter to
@param {int} $folderID Folder to filter to
@return {DataList} Data list pointing to the snippets in the results | entailment |
public function send($url, $method, $body, $headers = [], $options = [])
{
//Create a new Request Object
$request = new Request($method, $url, $headers, $body);
try {
//Send the Request
$rawResponse = $this->client->send($request, $options);
} catch (RequestException $e) {
$rawResponse = $e->getResponse();
if ($e->getCode() === 409) {
$body = $this->getResponseBody($rawResponse);
$rawHeaders = $rawResponse->getHeaders();
$httpStatusCode = $rawResponse->getStatusCode();
//Create and return a BoxRawResponse object
return new BoxRawResponse($rawHeaders, $body, $httpStatusCode);
}
if ($e->getPrevious() instanceof RingException || !$rawResponse instanceof ResponseInterface) {
throw new Exceptions\BoxClientException($e->getMessage(), $e->getCode());
}
}
//Something went wrong
if ($rawResponse->getStatusCode() >= 400) {
throw new Exceptions\BoxClientException($rawResponse->getBody());
}
//Get the Response Body
$body = $this->getResponseBody($rawResponse);
$rawHeaders = $rawResponse->getHeaders();
$httpStatusCode = $rawResponse->getStatusCode();
//Create and return a BoxRawResponse object
return new BoxRawResponse($rawHeaders, $body, $httpStatusCode);
} | Send request to the server and fetch the raw response
@param string $url URL/Endpoint to send the request to
@param string $method Request Method
@param string|resource|StreamInterface $body Request Body
@param array $headers Request Headers
@param array $options Additional Options
@return BoxRawResponse Raw response from the server
@throws BoxClientException | entailment |
public function renderAction($component)
{
// Register common stylesheets & scripts
FluidTemplate::addCommonStylesheets($this->settings['stylesheets']);
FluidTemplate::addCommonHeaderScripts($this->settings['headerScripts']);
FluidTemplate::addCommonFooterScripts($this->settings['footerScripts']);
$componentInstance = $this->objectManager->get($component, $this->controllerContext);
if ($componentInstance instanceof ComponentInterface) {
return trim($componentInstance->render());
}
return $this->view->render();
} | Render a component
@param string $component Component class
@return string Rendered component | entailment |
public function graphAction($component = null)
{
$graphvizService = GeneralUtility::makeInstanceService('graphviz', 'svg');
if ($graphvizService instanceof GraphvizService) {
$graph = new Graph(Scanner::discoverAll());
return $graphvizService->createGraph($graph($component));
}
return '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="30" viewBox=".2 -6.2 200 30"><text x="100" y="7" text-anchor="middle" font-family="sans-serif" font-size="11">Component graph cannot be created</text><text x="100" y="17" text-anchor="middle" font-family="sans-serif" font-size="8">Please check your GraphViz installation</text><path fill="none" stroke="#000" stroke-miterlimit="10" d="M199.73 18.133c0 2.75-2.25 5-5 5h-189c-2.75 0-5-2.25-5-5v-19c0-2.75 2.25-5 5-5h189c2.75 0 5 2.25 5 5v19z"/></svg>';
} | Graph action
@param string $component Component class
@return string SVG component graph
@todo Add a dummy graph telling that GraphViz isn't available | entailment |
protected function populateLanguageIDs() {
$this->_cache_language_ids=array();
if($snippetLanguages=$this->snippetLanguagesIncluded()) {
// And keep a record of parents we don't need to get
// parents of themselves, as well as IDs to mark
foreach($snippetLanguages as $langId) {
$this->_cache_language_ids[$langId]=true;
}
}
} | Populate the IDs of the snippet languages returned by snippetLanguagesIncluded() | entailment |
protected function populateSnippetIDs() {
$this->_cache_snippet_ids=array();
if($snippets=$this->snippetsIncluded()) {
// And keep a record of parents we don't need to get
// parents of themselves, as well as IDs to mark
foreach($snippets as $snippetId) {
$this->_cache_snippet_ids[$snippetId]=true;
}
}
} | Populate the IDs of the snippets returned by snippetsIncluded() | entailment |
protected function populateFolderIDs() {
$this->_cache_language_ids=array();
if($snippetFolders=$this->snippetFoldersIncluded()) {
// And keep a record of parents we don't need to get
// parents of themselves, as well as IDs to mark
foreach($snippetFolders as $folderId) {
$this->_cache_folder_ids[$folderId]=true;
}
}
} | Populate the IDs of the snippet languages returned by snippetLanguagesIncluded() | entailment |
public function isSnippetLanguageIncluded($obj) {
if($obj instanceof SnippetLanguage) {
if($this->_cache_language_ids===null) {
$this->populateLanguageIDs();
}
return (isset($this->_cache_language_ids[$obj->ID]) && $this->_cache_language_ids[$obj->ID]);
}else if($obj instanceof Snippet) {
if($this->_cache_snippet_ids===null) {
$this->populateSnippetIDs();
}
return (isset($this->_cache_snippet_ids[$obj->ID]) && $this->_cache_snippet_ids[$obj->ID]);
}else if($obj instanceof SnippetFolder) {
if($this->_cache_folder_ids===null) {
$this->populateFolderIDs();
}
return (isset($this->_cache_folder_ids[$obj->ID]) && $this->_cache_folder_ids[$obj->ID]);
}
return false;
} | Returns TRUE if the given snippet or language should be included in the tree.
@param {SnippetLanguage|Snippet|SnippetFolder} $obj Object to be checked
@return {bool} Returns boolean true if the snippet or language or folder should be included in the tree false otherwise | entailment |
public function init() {
parent::init();
Requirements::css(CB_DIR.'/css/CodeBank.css');
Requirements::add_i18n_javascript(CB_DIR.'/javascript/lang');
Requirements::customScript("var CB_DIR='".CB_DIR."';", 'cb_dir');
Requirements::javascript(CB_DIR.'/javascript/CodeBank.Tree.js');
if(!empty(CodeBankConfig::CurrentConfig()->IPMessage) && Session::get('CodeBankIPAgreed')!==true) {
$this->redirect('admin/codeBank/agreement');
}
} | Initializes the code bank admin | entailment |
public function Link($action=null) {
$link = Controller::join_links(
$this->stat('url_base', true),
$this->stat('url_segment', true), // in case we want to change the segment
'/', // trailing slash needed if $action is null!
"$action"
);
$this->extend('updateLink', $link);
return $link;
} | Override {@link LeftAndMain} Link to allow blank URL segment for CMSMain.
@param {string} $action Action to be used
@return {string} Resulting link | entailment |
protected function LinkWithSearch($link) {
// Whitelist to avoid side effects
$params=array(
'q'=>(array)$this->request->getVar('q'),
'tag'=>$this->request->getVar('tag'),
'creator'=>$this->request->getVar('creator'),
'ParentID'=>$this->request->getVar('ParentID')
);
$link=Controller::join_links(
$link,
(array_filter(array_values($params)) ? '?'.http_build_query($params):null)
);
$this->extend('updateLinkWithSearch', $link);
return $link;
} | Generates the link with search params
@param {string} Link to
@return {string} Link with search params | entailment |
public function getLinkMain() {
if($this->currentPageID()!=0 && $this->class=='CodeBankEditSnippet') {
return $this->LinkWithSearch(Controller::join_links($this->Link('show'), $this->currentPageID()));
}else if($this->currentPageID()!=0 && $this->class=='CodeBank') {
$otherID=null;
if(!empty($this->urlParams['OtherID']) && is_numeric($this->urlParams['OtherID'])) {
$otherID=intval($this->urlParams['OtherID']);
}
return $this->LinkWithSearch(Controller::join_links($this->Link('show'), $this->currentPageID(), $otherID));
}
return $this->LinkWithSearch(singleton('CodeBank')->Link());
} | Gets the main tab link
@return {string} URL to the main tab | entailment |
public function getEditForm($id=null, $fields=null) {
if(!$id) {
$id=$this->currentPageID();
}
$form=parent::getEditForm($id);
$record=$this->getRecord($id);
if($record && !$record->canView()) {
return Security::permissionFailure($this);
}
if(!$fields) {
$fields=$form->Fields();
}
$actions=$form->Actions();
if($record) {
$fields->push($idField=new HiddenField("ID", false, $id));
$versions=$record->Versions()->filter('ID:not', $record->CurrentVersionID)->Map('ID', 'Created');
$actions=new FieldList(
new FormAction('doCopy', _t('CodeBank.COPY', '_Copy')),
new FormAction('doEditRedirect', _t('CodeBank.EDIT', '_Edit')),
new FormAction('doExport', _t('CodeBank.EXPORT', '_Export')),
new FormAction('doPrint', _t('CodeBank.PRINT', '_Print')),
new LabelField('Revision', _t('CodeBank.REVISION', '_Revision').': '),
DropdownField::create('RevisionID', '', $versions, $this->urlParams['OtherID'])
->setEmptyString('{'._t('CodeBank.CURRENT_REVISION', '_Current Revision').'}')
->setDisabled($record->Versions()->Count()<=1)
->addExtraClass('no-change-track'),
FormAction::create('compareRevision', _t('CodeBank.COMPARE_WITH_CURRENT', '_Compare with Current'))->setDisabled($record->Versions()->Count()<=1 || empty($this->urlParams['OtherID']) || !is_numeric($this->urlParams['OtherID']))
);
// Use <button> to allow full jQuery UI styling
$actionsFlattened=$actions->dataFields();
if($actionsFlattened) {
foreach($actionsFlattened as $action) {
if($action instanceof FormAction) {
$action->setUseButtonTag(true);
}
}
}
if($record->hasMethod('getCMSValidator')) {
$validator=$record->getCMSValidator();
}else {
$validator=new RequiredFields();
}
if($record->Package() && $record->Package()!==false && $record->Package()->ID!=0) {
$package=new ArrayList(array($record->Package()));
}else {
$package=null;
}
$fields->insertBefore($fields->dataFieldByName('Title'), 'LanguageID');
$fields->replaceField('PackageID', new PackageViewField('PackageID', _t('Snippet.PACKAGE', '_Package'), $package, $record->ID));
$fields->replaceField('Text', HighlightedContentField::create('SnippetText', _t('Snippet.CODE', '_Code'), $record->Language()->HighlightCode)->setForm($form));
$fields->replaceField('Tags', new TagsViewField('Tags', _t('Snippet.TAGS_COLUMN', '_Tags')));
$fields->addFieldToTab('Root.Main', $creator=ReadonlyField::create('CreatorName', _t('CodeBank.CREATOR', '_Creator'), ($record->Creator() && $record->Creator()->ID>0 ? '<a href="'.$this->Link().'?creator='.$record->CreatorID.'">'.$record->Creator()->Name.'</a>':_t('CodeBank.UNKNOWN_USER', '_Unknown User')))->setForm($form));
$creator->dontEscape=true;
$fields->addFieldToTab('Root.Main', ReadonlyField::create('LanguageName', _t('CodeBank.LANGUAGE', '_Language'), $record->Language()->Name)->setForm($form));
$fields->addFieldToTab('Root.Main', DatetimeField_Readonly::create('LastModified', _t('CodeBank.LAST_MODIFIED', '_Last Modified'), $record->CurrentVersion->LastEdited)->setForm($form));
$fields->addFieldToTab('Root.Main', ReadonlyField::create('LastEditorName', _t('CodeBank.LAST_EDITED_BY', '_Last Edited By'), ($record->LastEditor() && $record->LastEditor()->ID>0 ? $record->LastEditor()->Name:_t('CodeBank.UNKNOWN_USER', '_Unknown User')))->setForm($form));
$fields->addFieldToTab('Root.Main', ReadonlyField::create('SnippetID', _t('CodeBank.ID', '_ID'), $record->ID));
$fields->addFieldToTab('Root.Main', ReadonlyField::create('CurrentVersionID', _t('CodeBank.VERSION', '_Version')));
$fields->push(new HiddenField('ID', 'ID'));
$form=new Form($this, 'EditForm', $fields, $actions, $validator);
$form->loadDataFrom($record);
$form->disableDefaultAction();
$form->addExtraClass('cms-edit-form');
$form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
$form->addExtraClass('center '.$this->BaseCSSClasses());
$form->setAttribute('data-pjax-fragment', 'CurrentForm');
//Swap content for version text
if(!empty($this->urlParams['OtherID']) && is_numeric($this->urlParams['OtherID'])) {
$version=$record->Version(intval($this->urlParams['OtherID']));
if(!empty($version) && $version!==false && $version->ID!=0) {
$fields->dataFieldByName('SnippetText')->setValue($version->Text);
$fields->dataFieldByName('LastModified')->setValue($version->LastEdited);
$fields->dataFieldByName('CurrentVersionID')->setValue($version->ID);
}
$form->Fields()->insertBefore(new LiteralField('NotCurrentVersion', '<p class="message warning">'._t('CodeBank.NOT_CURRENT_VERSION', '_You are viewing a past version of this snippet\'s content, {linkopen}click here{linkclose} to view the current version', array('linkopen'=>'<a href="admin/codeBank/show/'.$record->ID.'">', 'linkclose'=>'</a>')).'</p>'), 'Title');
}
$readonlyFields=$form->Fields()->makeReadonly();
$form->setFields($readonlyFields);
$this->extend('updateEditForm', $form);
$form->Actions()->push(new LiteralField('CodeBankVersion', '<p class="codeBankVersion">Code Bank: '.$this->getVersion().'</p>'));
Requirements::add_i18n_javascript(CB_DIR.'/javascript/lang');
Requirements::add_i18n_javascript('mysite/javascript/lang');
Requirements::javascript(CB_DIR.'/javascript/external/jquery-zclip/jquery.zclip.min.js');
Requirements::javascript(CB_DIR.'/javascript/CodeBank.ViewForm.js');
//Display message telling user to run dev/build because the version numbers are out of sync
if(CB_VERSION!='@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version!=CB_VERSION.' '.CB_BUILD_DATE) {
$form->Fields()->insertBefore(new LiteralField('DBUpgrade', '<p class="message error">'._t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink'=>'<a href="dev/build?flush=all">', 'endlink'=>'</a>')).'</p>'), 'Title');
}else if($this->hasOldTables()) {
$form->Fields()->insertBefore(new LiteralField('DBUpgrade', '<p class="message warning">'._t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink'=>'<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink'=>'</a>')).'</p>'), 'Title');
}
return $form;
}else if($id) {
$form=CMSForm::create($this, 'EditForm', new FieldList(
new TabSet('Root',
new Tab('Main', ' ',
new LabelField('DoesntExistLabel', _t('CodeBank.SNIPPIT_NOT_EXIST', '_Snippit does not exist'))
)
)
), new FieldList())->setHTMLID('Form_EditForm');
$form->addExtraClass('cms-edit-form');
$form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
$form->addExtraClass('center '.$this->BaseCSSClasses());
$form->setAttribute('data-pjax-fragment', 'CurrentForm');
//Display message telling user to run dev/build because the version numbers are out of sync
if(CB_VERSION!='@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version!=CB_VERSION.' '.CB_BUILD_DATE) {
$form->Fields()->insertBefore(new LiteralField('DBUpgrade', '<p class="message error">'._t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink'=>'<a href="dev/build?flush=all">', 'endlink'=>'</a>')).'</p>'), 'DoesntExist');
}else if($this->hasOldTables()) {
$form->Fields()->insertBefore(new LiteralField('DBUpgrade', '<p class="message warning">'._t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink'=>'<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink'=>'</a>')).'</p>'), 'DoesntExistLabel');
}
}else {
$form=$this->EmptyForm();
if(Session::get('CodeBank.deletedSnippetID')) {
$form->Fields()->push(new HiddenField('ID', 'ID', Session::get('CodeBank.deletedSnippetID')));
}
//Display message telling user to run dev/build because the version numbers are out of sync
if(CB_VERSION!='@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version!=CB_VERSION.' '.CB_BUILD_DATE) {
$form->Fields()->push(new LiteralField('DBUpgrade', '<p class="message error">'._t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink'=>'<a href="dev/build?flush=all">', 'endlink'=>'</a>')).'</p>'));
}else if($this->hasOldTables()) {
$form->Fields()->push(new LiteralField('DBUpgrade', '<p class="message warning">'._t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink'=>'<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink'=>'</a>')).'</p>'));
}
}
$form->disableDefaultAction();
$form->addExtraClass('cms-edit-form');
$form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
$form->addExtraClass('center '.$this->BaseCSSClasses());
$form->Actions()->push(new LiteralField('CodeBankVersion', '<p class="codeBankVersion">Code Bank: '.$this->getVersion().'</p>'));
return $form;
} | Gets the form used for viewing snippets
@param {int} $id ID of the record to fetch
@param {FieldList} $fields Fields to use
@return {Form} Form to be used | entailment |
public function getsubtree($request) {
if(strpos($request->getVar('ID'), 'folder-')!==false) {
$folderID=(strpos($request->getVar('ID'), 'folder-')!==false ? intval(str_replace('folder-', '', $request->getVar('ID'))):null);
$html=$this->getSiteTreeFor('SnippetFolder', $folderID, 'Children', null, array($this, 'hasSnippets'));
}else {
$languageID=(strpos($request->getVar('ID'), 'language-')!==false ? intval(str_replace('language-', '', $request->getVar('ID'))):null);
$html=$this->getSiteTreeFor($this->stat('tree_class'), $languageID, 'Children', null, array($this, 'hasSnippets'));
}
// Trim off the outer tag
$html=preg_replace('/^[\s\t\r\n]*<ul[^>]*>/','', $html);
$html=preg_replace('/<\/ul[^>]*>[\s\t\r\n]*$/','', $html);
return $html;
} | Get a subtree underneath the request param 'ID'.
If ID = 0, then get the whole tree. | entailment |
public function updatetreenodes($request) {
$data=array();
$ids=explode(',', $request->getVar('ids'));
foreach($ids as $id) {
if($id==Session::get('CodeBank.deletedSnippetID')) {
Session::clear('CodeBank.deletedSnippetID');
$this->response->addHeader('Content-Type', 'text/json');
return '{"'.$id.'": false}';
}
$record=$this->getRecord($id);
$recordController=singleton('CodeBank');
//Find the next & previous nodes, for proper positioning (Sort isn't good enough - it's not a raw offset)
$next=$prev=null;
$className=$this->stat('tree_class');
$next=Snippet::get()->filter('LanguageID', $record->LanguageID)->filter('FolderID', $record->FolderID)->filter('Title:GreaterThan', $record->Title)->first();
if(!$next) {
$prev=Snippet::get()->filter('LanguageID', $record->LanguageID)->filter('FolderID', $record->FolderID)->filter('Title:LessThan', $record->Title)->reverse()->first();
}
$link=Controller::join_links($recordController->Link("show"), $record->ID);
$html=CodeBank_TreeNode::create($record, $link, $this->isCurrentPage($record))->forTemplate().'</li>';
$folder=$record->Folder();
$data[$id]=array(
'html'=>$html,
'ParentID'=>(!empty($folder) && $folder!==false && $folder->ID!=0 ? 'folder-'.$record->FolderID:'language-'.$record->LanguageID),
'NextID'=>($next ? $next->ID:null),
'PrevID'=>($prev ? $prev->ID:null)
);
}
$this->response->addHeader('Content-Type', 'text/json');
return Convert::raw2json($data);
} | Allows requesting a view update on specific tree nodes.
Similar to {@link getsubtree()}, but doesn't enforce loading
all children with the node. Useful to refresh views after
state modifications, e.g. saving a form.
@return String JSON | entailment |
public function TreeIsFiltered() {
return ($this->request->getVar('q') || $this->request->getVar('tag') || $this->request->getVar('creator'));
} | Checks to see if the tree should be filtered or not
@return {bool} | entailment |
public function SiteTreeAsUL() {
$html=$this->getSiteTreeFor($this->stat('tree_class'), null, 'Children', null);
$this->extend('updateSiteTreeAsUL', $html);
return $html;
} | Gets the snippet language tree as an unordered list
@return {string} XHTML forming the tree of languages to snippets | entailment |
public function getSiteTreeFor($className, $rootID=null, $childrenMethod=null, $numChildrenMethod=null, $filterFunction=null, $minNodeCount=30) {
// Filter criteria
$params=$this->request->getVar('q');
$tag=$this->request->getVar('tag');
$creator=$this->request->getVar('creator');
if($params) {
$filterClass=CodeBank::$filter_class;
if($filterClass!='SnippetTreeFilter' && !is_subclass_of($filterClass, 'SnippetTreeFilter')) {
throw new Exception(sprintf('Invalid filter class passed: %s', $filterClass));
}
$filter=new $filterClass($params);
}else if($tag && !empty($tag)) {
$filter=new SnippetTreeTagFilter($tag);
}else if($creator && intval($creator)>0) {
$filter=new SnippetTreeCreatorFilter($creator);
}else {
$filter=null;
}
// Default childrenMethod and numChildrenMethod
if(!$childrenMethod) {
$childrenMethod=($filter && $filter->getChildrenMethod() ? $filter->getChildrenMethod():'AllChildrenIncludingDeleted');
}
if(!$numChildrenMethod) {
$numChildrenMethod='numChildren';
}
if(!$filterFunction) {
$filterFunction=($filter ? array($filter, 'isSnippetLanguageIncluded'):array($this, 'hasSnippets'));
}
// Get the tree root
$record=($rootID ? $className::get()->byID($rootID):null);
$obj=($record ? $record:singleton($className));
// Mark the nodes of the tree to return
if($filterFunction) {
$obj->setMarkingFilterFunction($filterFunction);
}
$obj->markPartialTree($minNodeCount, $this, $childrenMethod, $numChildrenMethod);
// Ensure current page is exposed
if($p=$this->currentPage()) {
$obj->markToExpose($p);
}
// getChildrenAsUL is a flexible and complex way of traversing the tree
$controller=$this;
$recordController=singleton('CodeBank');
$titleFn=function(&$child) use(&$controller, &$recordController) {
$link=Controller::join_links($recordController->Link("show"), $child->ID);
return CodeBank_TreeNode::create($child, $link, $controller->isCurrentPage($child))->forTemplate();
};
$html=$obj->getChildrenAsUL("", $titleFn, null, true, $childrenMethod, $numChildrenMethod, $minNodeCount);
// Wrap the root if needs be.
if(!$rootID) {
$rootLink=$this->Link('show') . '/root';
// This lets us override the tree title with an extension
if($this->hasMethod('getCMSTreeTitle') && $customTreeTitle=$this->getCMSTreeTitle()) {
$treeTitle=$customTreeTitle;
}else if(class_exists('SiteConfig')) {
$siteConfig=SiteConfig::current_site_config();
$treeTitle=$siteConfig->Title;
}else {
$treeTitle='...';
}
$html="<ul><li id=\"record-0\" data-id=\"0\" class=\"Root nodelete\"><strong>$treeTitle</strong>".$html."</li></ul>";
}
return $html;
} | Get a site tree HTML listing which displays the nodes under the given criteria.
@param $className The class of the root object
@param $rootID The ID of the root object. If this is null then a complete tree will be shown
@param $childrenMethod The method to call to get the children of the tree. For example, Children, AllChildrenIncludingDeleted, or AllHistoricalChildren
@return String Nested unordered list with links to each page | entailment |
public function getRecord($id) {
$className='Snippet';
if($className && $id instanceof $className) {
return $id;
}else if($id=='root') {
return singleton($className);
}else if(is_numeric($id)) {
return DataObject::get_by_id($className, $id);
}else {
return false;
}
} | Gets the snippet for editing/viewing
@param {int} $id ID of the snippet to fetch
@return {DataObject} DataObject to use | entailment |
public function getEditLink() {
if(!empty($this->urlParams['OtherID']) && is_numeric($this->urlParams['OtherID'])) {
return $this->LinkWithSearch('admin/codeBank/show/'.$this->currentPageID().'/'.intval($this->urlParams['OtherID']));
}
return $this->LinkWithSearch('admin/codeBank/show/'.$this->currentPageID());
} | Returns the link to view/edit snippets
@return {string} Link to view/edit snippets | entailment |
public function SearchForm() {
$languages=SnippetLanguage::get()
->leftJoin('Snippet', '"Snippet"."LanguageID"="SnippetLanguage"."ID"')
->where('"SnippetLanguage"."Hidden"=0 OR "Snippet"."ID" IS NOT NULL')
->sort('Name');
$fields=new FieldList(
new TextField('q[Term]', _t('CodeBank.KEYWORD', '_Keyword')),
$classDropdown=new DropdownField(
'q[LanguageID]',
_t('CodeBank.LANGUAGE', '_Language'),
$languages->map('ID', 'Name')
)
);
$classDropdown->setEmptyString(_t('CodeBank.ALL_LANGUAGES', '_All Languages'));
$actions=new FieldList(
FormAction::create('doSearch', _t('CodeBank.APPLY_FILTER', '_Apply Filter'))->setUseButtonTag(true)
);
$form=Form::create($this, 'SearchForm', $fields, $actions)
->addExtraClass('cms-search-form')
->setFormMethod('GET')
->setFormAction($this->Link())
->disableSecurityToken()
->unsetValidator();
$form->loadDataFrom($this->request->getVars());
$this->extend('updateSearchForm', $form);
return $form;
} | Generates the search form
@return {Form} Form used for searching | entailment |
public function compare() {
$compareContent=false;
//Get the Main Revision
$snippet1=Snippet::get()->byID(intval($this->urlParams['ID']));
if(empty($snippet1) || $snippet1===false || $snippet1->ID==0) {
$snippet1=false;
}
if($snippet1!==false) {
//Get the Comparision Revision
$snippet2=$snippet1->Version(intval($this->urlParams['OtherID']));
if(empty($snippet2) || $snippet1===false || $snippet2->ID==0) {
$snippet2=false;
}
if($snippet2!==false) {
$snippet1Text=preg_replace('/\r\n|\n|\r/', "\n", $snippet1->SnippetText);
$snippet2Text=preg_replace('/\r\n|\n|\r/', "\n", $snippet2->Text);
//Generate the diff file
$diff=new Text_Diff('auto', array(preg_split('/\n/', $snippet1Text), preg_split('/\n/', $snippet2Text)));
$renderer=new WP_Text_Diff_Renderer_Table();
$renderedDiff=$renderer->render($diff);
if(!empty($renderedDiff)) {
$lTable='<table cellspacing="0" cellpadding="0" border="0" class="diff">'.
'<colgroup>'.
'<col class="ltype"/>'.
'<col class="content"/>'.
'</colgroup>'.
'<tbody>';
$rTable=$lTable;
header('content-type: text/plain');
$xml=simplexml_load_string('<tbody>'.str_replace(' ', ' ', $renderedDiff).'</tbody>');
foreach($xml->children() as $row) {
$i=0;
$lTable.='<tr>';
$rTable.='<tr>';
foreach($row->children() as $td) {
$attr=$td->attributes();
if($i==0) {
$lTable.=$td->asXML();
}else {
$rTable.=$td->asXML();
}
$i++;
}
$lTable.='</tr>';
$rTable.='</tr>';
}
$lTable.='</tbody></table>';
$rTable.='</tbody></table>';
$compareContent='<div class="compare leftSide">'.$lTable.'</div>'.
'<div class="compare rightSide">'.$rTable.'</div>';
}
}
}
Requirements::css(CB_DIR.'/css/CompareView.css');
Requirements::javascript(CB_DIR.'/javascript/CodeBank.CompareView.js');
return $this->renderWith('CodeBank_CompareView', array(
'CompareContent'=>$compareContent
));
} | Handles rendering of the compare view
@return {string} HTML to be sent to the browser | entailment |
public function getTreeHints() {
$json = '';
$classes = array('Snippet', 'SnippetLanguage', 'SnippetFolder');
$cacheCanCreate = array();
foreach($classes as $class) $cacheCanCreate[$class] = singleton($class)->canCreate();
// Generate basic cache key. Too complex to encompass all variations
$cache=SS_Cache::factory('CodeBank_TreeHints');
$cacheKey = md5(implode('_', array(Member::currentUserID(), implode(',', $cacheCanCreate), implode(',', $classes))));
if($this->request->getVar('flush')) $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
$json = $cache->load($cacheKey);
if(!$json) {
$def['Root'] = array();
$def['Root']['disallowedParents'] = array();
foreach($classes as $class) {
$sng=singleton($class);
$allowedChildren = $sng->allowedChildren();
// SiteTree::allowedChildren() returns null rather than an empty array if SiteTree::allowed_chldren == 'none'
if($allowedChildren == null) $allowedChildren = array();
// Find i18n - names and build allowed children array
foreach($allowedChildren as $child) {
$instance = singleton($child);
if($instance instanceof HiddenClass) continue;
if(!array_key_exists($child, $cacheCanCreate) || !$cacheCanCreate[$child]) continue;
// skip this type if it is restricted
if($instance->stat('need_permission') && !$this->can(singleton($class)->stat('need_permission'))) continue;
$title = $instance->i18n_singular_name();
$def[$class]['allowedChildren'][] = array("ssclass" => $child, "ssname" => $title);
}
$allowedChildren = array_keys(array_diff($classes, $allowedChildren));
if($allowedChildren) $def[$class]['disallowedChildren'] = $allowedChildren;
$defaultChild = $sng->default_child();
if($defaultChild != null) $def[$class]['defaultChild'] = $defaultChild;
if(isset($def[$class]['disallowedChildren'])) {
foreach($def[$class]['disallowedChildren'] as $disallowedChild) {
$def[$disallowedChild]['disallowedParents'][] = $class;
}
}
// Are any classes allowed to be parents of root?
$def['Root']['disallowedParents'][] = $class;
}
$json = Convert::raw2xml(Convert::raw2json($def));
$cache->save($json, $cacheKey);
}
return $json;
} | Create serialized JSON string with tree hints data to be injected into 'data-hints' attribute of root node of jsTree.
@return {string} Serialized JSON | entailment |
public function addSnippet(SS_HTTPRequest $request) {
if($request->getVar('Type')=='SnippetFolder') {
return $this->redirect(Controller::join_links($this->Link('addFolder'), '?FolderID='.str_replace('folder-', '', $request->getVar('ID'))));
}else {
return $this->redirect(Controller::join_links($this->Link('add'), '?LanguageID='.str_replace('language-', '', $request->getVar('ID'))));
}
} | Handles requests to add a snippet or folder to a language
@param {SS_HTTPRequest} $request HTTP Request | entailment |
public function moveSnippet(SS_HTTPRequest $request) {
$snippet=Snippet::get()->byID(intval($request->getVar('ID')));
if(empty($snippet) || $snippet===false || $snippet->ID==0) {
$this->response->setStatusCode(403, _t('CodeBank.SNIPPIT_NOT_EXIST', '_Snippit does not exist'));
return;
}
$parentID=$request->getVar('ParentID');
if(strpos($parentID, 'language-')!==false) {
$lang=SnippetLanguage::get()->byID(intval(str_replace('language-', '', $parentID)));
if(empty($lang) || $lang===false || $lang->ID==0) {
$this->response->setStatusCode(403, _t('CodeBank.LANGUAGE_NOT_EXIST', '_Language does not exist'));
return;
}
if($lang->ID!=$snippet->LanguageID) {
$this->response->setStatusCode(403, _t('CodeBank.CANNOT_MOVE_TO_LANGUAGE', '_You cannot move a snippet to another language'));
return;
}
//Move out of folder
DB::query('UPDATE "Snippet" SET "FolderID"=0 WHERE "ID"='.$snippet->ID);
$this->response->addHeader('X-Status', rawurlencode(_t('CodeBank.SNIPPET_MOVED', '_Snippet moved successfully')));
return;
}else if(strpos($parentID, 'folder-')!==false) {
$folder=SnippetFolder::get()->byID(intval(str_replace('folder-', '', $parentID)));
if(empty($folder) || $folder===false || $folder->ID==0) {
$this->response->setStatusCode(403, _t('CodeBank.FOLDER_NOT_EXIST', '_Folder does not exist'));
return;
}
if($folder->LanguageID!=$snippet->LanguageID) {
$this->response->setStatusCode(403, _t('CodeBank.CANNOT_MOVE_TO_FOLDER', '_You cannot move a snippet to a folder in another language'));
return;
}
//Move to folder
DB::query('UPDATE "Snippet" SET "FolderID"='.$folder->ID.' WHERE "ID"='.$snippet->ID);
$this->response->addHeader('X-Status', rawurlencode(_t('CodeBank.SNIPPET_MOVED', '_Snippet moved successfully')));
return;
}
$this->response->setStatusCode(403, _t('CodeBank.UNKNOWN_PARENT', '_Unknown Parent'));
} | Handles moving of a snippet when the tree is reordered
@param {SS_HTTPRequest} $request HTTP Request | entailment |
public function AddFolderForm() {
$fields=new FieldList(
new TabSet('Root',
new Tab('Main', 'Main',
new TextField('Name', _t('SnippetFolder.NAME', '_Name'), null, 150)
)
)
);
$noParent=true;
if(strpos($this->request->getVar('ParentID'), 'language-')!==false) {
$fields->push(new HiddenField('LanguageID', 'LanguageID', intval(str_replace('language-', '', $this->request->getVar('ParentID')))));
$noParent=false;
}else if(strpos($this->request->getVar('ParentID'), 'folder-')!==false) {
$folder=SnippetFolder::get()->byID(intval(str_replace('folder-', '', $this->request->getVar('ParentID'))));
if(!empty($folder) && $folder!==false && $folder->ID!=0) {
$fields->push(new HiddenField('ParentID', 'ParentID', $folder->ID));
$fields->push(new HiddenField('LanguageID', 'LanguageID', $folder->LanguageID));
$noParent=false;
}
}else {
if($this->request->postVar('LanguageID')) {
$fields->push(new HiddenField('LanguageID', 'LanguageID', intval($this->request->postVar('LanguageID'))));
$noParent=false;
}
if($this->request->postVar('ParentID')) {
$fields->push(new HiddenField('ParentID', 'ParentID', intval($this->request->postVar('ParentID'))));
$noParent=false;
}
}
$actions=new FieldList(
new FormAction('doAddFolder', _t('CodeBank.SAVE', '_Save'))
);
$validator=new RequiredFields('Name');
$form=new Form($this, 'AddFolderForm', $fields, $actions, $validator);
$form->addExtraClass('member-profile-form');
//If no parent disable folder
if($noParent) {
$form->setMessage(_t('CodeBank.FOLDER_NO_PARENT', '_Folder does not have a parent language or folder'), 'bad');
$form->setFields(new FieldList());
$form->setActions(new FieldList());
}
return $form;
} | Form used for adding a folder
@return {Form} Form to be used for adding a folder | entailment |
public function doAddFolder($data, Form $form) {
//Existing Check
$existingCheck=SnippetFolder::get()->filter('Name:nocase', Convert::raw2sql($data['Name']))->filter('LanguageID', intval($data['LanguageID']));
if(array_key_exists('FolderID', $data)) {
$existingCheck=$existingCheck->filter('ParentID', intval($data['FolderID']));
}else {
$existingCheck->filter('ParentID', 0);
}
if($existingCheck->Count()>0) {
$form->sessionMessage(_t('CodeBank.FOLDER_EXISTS', '_A folder already exists with that name'), 'bad');
return $this->redirectBack();
}
$folder=new SnippetFolder();
$folder->Name=$data['Name'];
$folder->LanguageID=$data['LanguageID'];
if(array_key_exists('ParentID', $data)) {
$folder->ParentID=$data['ParentID'];
}
//Write the folder to the database
$folder->write();
//Find the next & previous nodes, for proper positioning (Sort isn't good enough - it's not a raw offset)
$next=$prev=null;
$next=SnippetFolder::get()->filter('LanguageID', $folder->LanguageID)->filter('ParentID', $folder->ParentID)->filter('Name:GreaterThan', Convert::raw2sql($folder->Title))->first();
if(!$next) {
$prev=SnippetFolder::get()->filter('LanguageID', $folder->LanguageID)->filter('ParentID', $folder->ParentID)->filter('Name:LessThan', Convert::raw2sql($folder->Title))->reverse()->first();
}
//Setup js that will add the node to the tree
$html=CodeBank_TreeNode::create($folder, '', false)->forTemplate().'</li>';
$parentFolder=$folder->Parent();
$outputData=array('folder-'.$folder->ID=>array(
'html'=>$html,
'ParentID'=>(!empty($parentFolder) && $parentFolder!==false && $parentFolder->ID!=0 ? 'folder-'.$folder->ParentID:'language-'.$folder->LanguageID),
'NextID'=>($next ? 'folder-'.$next->ID:null),
'PrevID'=>($prev ? 'folder-'.$prev->ID:null)
));
Requirements::customScript('window.parent.updateCodeBankTreeNodes('.json_encode($outputData).');');
//Re-render the form
$form->setFields(new FieldList());
$form->setActions(new FieldList());
$form->setMessage(_t('CodeBank.FOLDER_ADDED', '_Folder added you may now close this dialog'), 'good');
return $this->customise(array(
'Content'=>' ',
'Form'=>$form
))->renderWith('CMSDialog');
} | Handles actually adding a folder to the databsae
@param {array} $data Submitted data
@param {Form} $form Submitting form
@return {string} HTML to be rendered | entailment |
public function RenameFolderForm() {
$folder=SnippetFolder::get()->byID(intval(str_replace('folder-', '', $this->request->getVar('ID'))));
if(!empty($folder) && $folder!==false && $folder->ID!=0) {
$fields=new FieldList(
new TabSet('Root',
new Tab('Main', 'Main',
new TextField('Name', _t('SnippetFolder.NAME', '_Name'), null, 150)
)
),
new HiddenField('ID', 'ID')
);
$actions=new FieldList(
new FormAction('doRenameFolder', _t('CodeBank.SAVE', '_Save'))
);
}else {
$fields=new FieldList();
$actions=new FieldList();
}
$validator=new RequiredFields('Name');
$form=new Form($this, 'RenameFolderForm', $fields, $actions, $validator);
$form->addExtraClass('member-profile-form');
//If no parent disable folder
if(empty($folder) || $folder===false || $folder->ID==0) {
$form->setMessage(_t('CodeBank.FOLDER_NOT_FOUND', '_Folder could not be found'), 'bad');
}else {
$form->loadDataFrom($folder);
$form->setFormAction(Controller::join_links($form->FormAction(), '?ID='.$folder->ID));
}
return $form;
} | Form used for renaming a folder
@return {Form} Form to be used for renaming a folder | entailment |
public function doRenameFolder($data, Form $form) {
$folder=SnippetFolder::get()->byID(intval($data['ID']));
if(empty($folder) || $folder===false || $folder->ID==0) {
$form->sessionMessage(_t('CodeBank.FOLDER_NOT_FOUND', '_Folder could not be found'), 'bad');
return $this->redirectBack();
}
//Existing Check
$existingCheck=SnippetFolder::get()
->filter('Name:nocase', Convert::raw2sql($data['Name']))
->filter('LanguageID', $folder->LanguageID)
->filter('ParentID', $folder->ParentID)
->filter('ID:not', $folder->ID);
if($existingCheck->Count()>0) {
$form->sessionMessage(_t('CodeBank.FOLDER_EXISTS', '_A folder already exists with that name'), 'bad');
return $this->redirectBack();
}
//Update Folder
$form->saveInto($folder);
$folder->write();
//Add script to rename the folder in the tree
Requirements::customScript('window.parent.renameCodeBankTreeNode("folder-'.$folder->ID.'", "'.addslashes($folder->TreeTitle).'");');
//Re-render the form
$form->setMessage(_t('CodeBank.FOLDER_RENAMED', '_Folder Renamed'), 'good');
return $this->customise(array(
'Content'=>' ',
'Form'=>$form
))->renderWith('CMSDialog');
} | Performs the rename of the folder
@param {array} $data Submitted data
@param {Form} $form Submitting form
@return {string} HTML to be rendered | entailment |
public function deleteFolder() {
$folder=SnippetFolder::get()->byID(intval(str_replace('folder-', '', $this->request->getVar('ID'))));
if(empty($folder) || $folder===false || $folder->ID==0) {
$this->response->setStatusCode(404, _t('CodeBank.FOLDER_NOT_FOUND', '_Folder could not be found'));
return;
}
$folder->delete();
return 'HELO';
} | Deletes a folder node | entailment |
public function printSnippet() {
$record=$this->getRecord($this->currentPageID());
if(!empty($record) && $record!==false && $record->ID>0) {
$version=false;
if(!empty($this->urlParams['OtherID']) && is_numeric($this->urlParams['OtherID'])) {
$version=$record->Version(intval($this->urlParams['OtherID']));
}
Requirements::css(CB_DIR.'/javascript/external/syntaxhighlighter/themes/shCore.css');
Requirements::css(CB_DIR.'/javascript/external/syntaxhighlighter/themes/shCoreDefault.css');
Requirements::css(CB_DIR.'/javascript/external/syntaxhighlighter/themes/shThemeDefault.css');
Requirements::javascript(CB_DIR.'/javascript/external/syntaxhighlighter/brushes/shCore.js');
Requirements::javascript(CB_DIR.'/javascript/external/syntaxhighlighter/brushes/'.$record->getBrushName().'.js');
Requirements::javascript(CB_DIR.'/javascript/CodeBank_PrinterFriendly.js');
return $this->renderWith('CodeBank_PrinterFriendly', array('Snippet'=>$record, 'SnippetVersion'=>$version, 'CodeBankDir'=>CB_DIR));
}
return $this->response->setStatusCode(404);
} | Handles requests to print the current snippet
@return {string} Rendered template | entailment |
protected function hasOldTables() {
if(!file_exists(ASSETS_PATH.'/.codeBankMigrated')) {
$tables=DB::tableList();
if(array_key_exists('snippits', $tables) && array_key_exists('snippit_search', $tables)) {
return true;
}else {
touch(ASSETS_PATH.'/.codeBankMigrated');
}
}
return false;
} | Tests to see if the old tables exist
@return {bool} Returns boolean true if the old tables are detected and the migration file is not detected | entailment |
public function forTemplate() {
$obj=$this->obj;
if($this->obj instanceof SnippetLanguage) {
$liAttrib='id="language-'.$obj->ID.'" data-id="language-'.$obj->ID.'"';
}else if($this->obj instanceof SnippetFolder) {
$liAttrib='id="folder-'.$obj->ID.'" data-id="folder-'.$obj->ID.'" data-languageID="'.$obj->LanguageID.'"';
}else {
$liAttrib='id="record-'.$obj->ID.'" data-id="'.$obj->ID.'" data-languageID="'.$obj->LanguageID.'"';
}
return "<li ".$liAttrib." data-pagetype=\"$obj->ClassName\" class=\"".$this->getClasses()."\">" .
"<ins class=\"jstree-icon\"> </ins>".
"<a href=\"".($this->obj instanceof SnippetLanguage || $this->obj instanceof SnippetFolder ? '':$this->getLink())."\" title=\"$obj->class: ".strip_tags($obj->TreeTitle)."\">".
"<ins class=\"jstree-icon\"> </ins><span class=\"text\">".($obj->TreeTitle)."</span></a>";
} | Returns template, for further processing by {@link Hierarchy->getChildrenAsUL()}. Does not include closing tag to allow this method to inject its own children.
@return {string} HTML to be used | entailment |
public function each(Callable $f) : void {
foreach ($this->items as $i) {
$f($i);
}
} | run a function against each item in the collection
@param callable $f | entailment |
public function equals(Collection $that) : bool {
return
get_class($this) == get_class($that) &&
$this->items === $that->items;
} | compare one collection against another. collections are
considered equal if both collection classes are of the same
type and both item arrays are considered equal with strict
comparison.
@param Collection $that
@return bool | entailment |
public function reduce(Callable $f, $initial = null) {
return array_reduce($this->items, $f, $initial);
} | return a single value reduced from the collection by the
provided function.
@param callable $f
@param null $initial
@return mixed | entailment |
public function setExtbaseConfiguration($pluginName, $controllerClass, $actionName, $extensionName = null)
{
// Validate the extension name
if (!empty($extensionName)) {
$extensionName = GeneralUtility::camelCaseToLowerCaseUnderscored(trim($extensionName));
if (!in_array($extensionName, ExtensionManagementUtility::getLoadedExtensionListArray())) {
throw new \RuntimeException(sprintf('Extension "%s" is not available', $extensionName), 1481645834);
}
$this->extbaseExtensionName = $extensionName;
}
// Validate the plugin name
$pluginName = trim($pluginName);
if (empty($pluginName)) {
throw new \RuntimeException(sprintf('Invalid plugin name "%s"', $pluginName), 1481646376);
}
$this->extbasePlugin = $pluginName;
// Validate the controller name
$controllerClass = trim($controllerClass);
if (empty($controllerClass)
|| !class_exists($controllerClass)
|| !($controllerReflection = new \ReflectionClass($controllerClass))->implementsInterface(
ControllerInterface::class
)
) {
throw new \RuntimeException(sprintf('Invalid controller class "%s"', $controllerClass), 1481646376);
}
$this->extbaseControllerClass = $controllerClass;
$this->extbaseController = preg_replace('/Controller$/', '', $controllerReflection->getShortName());
// Validate the controller action
$actionName = trim($actionName);
if (empty($actionName) || !is_callable([$this->extbaseControllerClass, $actionName.'Action'])) {
throw new \RuntimeException(sprintf('Invalid controller action "%s"', $actionName), 1481646569);
}
$this->extbaseAction = $actionName;
// Construct the controller argument request prefix
$this->controllerArgumentRequestPrefix = 'tx_'.strtolower(str_replace('_', '', $this->extbaseExtensionName)).
'_'.strtolower($this->extbasePlugin);
// Construct and set the controller request arguments
$this->request->setControllerObjectName($this->extbaseControllerClass);
$this->request->setControllerExtensionName($this->extbaseExtensionName);
$this->request->setControllerName($this->extbaseController);
$this->request->setControllerActionName($this->extbaseAction);
$this->request->setPluginName($this->extbasePlugin);
$this->request->setArgument(
$this->controllerArgumentRequestPrefix,
[
'controller' => $this->extbaseController,
'action' => $this->extbaseAction,
]
);
// Determine the default controller settings
/** @var ConfigurationManagerInterface $configurationManager */
$configurationManager = $this->objectManager->get(ConfigurationManagerInterface::class);
$this->controllerSettings = $configurationManager->getConfiguration(
ConfigurationManagerInterface::CONFIGURATION_TYPE_SETTINGS,
GeneralUtility::underscoredToUpperCamelCase($this->extbaseExtensionName),
$this->extbasePlugin
);
} | Set the extbase configuration
@param string $pluginName Plugin name
@param string $controllerClass Controller name
@param string $actionName Action name
@param string|null $extensionName Extension name | entailment |
public function setControllerActionArgument($name, $value)
{
// Validate the argument name
$name = trim($name);
if (empty($name)) {
throw new \RuntimeException('Invalid extbase controller argument name', 1481708515);
}
$this->request->setArgument($name, $value);
} | Set a controller action argument
@param string $name Argument name
@param mixed $value Argument value | entailment |
public function setControllerSettings(array $settings, $override = false)
{
$this->controllerSettings = $override ? $settings : array_replace($this->controllerSettings, $settings);
} | Set the controller settings
@param array $settings Controller settings
@param bool $override Override current settings (instead of amending them) | entailment |
public function render()
{
// Set the request arguments as GET parameters
$_GET = $this->getRequestArguments();
try {
/** @var \TYPO3\CMS\Extbase\Mvc\Web\Response $response */
$response = $this->objectManager->get(Response::class);
$this->request->setOriginalRequestMappingResults($this->validationErrors);
$this->getControllerInstance()->processRequest($this->request, $response);
$result = $this->beautify($response->getContent());
// In case of an error
} catch (\Exception $e) {
$result = '<pre class="error"><strong>'.$e->getMessage().'</strong>'.PHP_EOL
.$e->getTraceAsString().'</pre>';
}
return $result;
} | Render this component
@return string Rendered component (HTML) | entailment |
protected function getControllerInstance()
{
// One-time instantiation of an extended controller object
if ($this->controllerInstance === null) {
$extendedControllerClassName = $this->extbaseController.'ComponentController_'.md5(
$this->extbaseControllerClass
);
// One-off class declaration
if (!class_exists($extendedControllerClassName, false)) {
$extendedControllerPhp = 'class '.$extendedControllerClassName.' extends '.$this->extbaseControllerClass;
$extendedControllerPhp .= ' implements '.ComponentControllerInterface::class;
$extendedControllerPhp .= ' { use '.ComponentControllerTrait::class.'; }';
eval($extendedControllerPhp);
}
$this->controllerInstance = $this->objectManager->get($extendedControllerClassName);
}
$settings = $this->controllerSettings ?: [];
return $this->controllerInstance->setSettings($settings);
} | Return an extend Extbase controller instance
@return ActionController|ComponentControllerInterface Extended Extbase controller instance | entailment |
protected function exportInternal()
{
// Compose a configuration string
if ($this->extbaseExtensionName && $this->extbasePlugin && $this->extbaseController && $this->extbaseAction) {
$this->config = [
'extension' => $this->extbaseExtensionName,
'plugin' => $this->extbasePlugin,
'controller' => $this->extbaseController,
'action' => $this->extbaseAction,
'settings' => $this->controllerSettings,
];
$controllerInstance = $this->getControllerInstance();
$controllerInstance->skipActionCall(true);
/** @var \TYPO3\CMS\Extbase\Mvc\Web\Response $response */
$response = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Mvc\\Web\\Response');
$controllerInstance->processRequest($this->request, $response);
$this->template = $controllerInstance->getView()
->getComponentTemplate($this->extbaseController, $this->extbaseAction);
}
return parent::exportInternal();
} | Return component specific properties
@return array Component specific properties | entailment |
public function writeTypeMarker(&$data, $markerType = null, $dataByVal = false)
{
// Workaround for PHP5 with E_STRICT enabled complaining about "Only
// variables should be passed by reference"
if ((null === $data) && ($dataByVal !== false)) {
$data = &$dataByVal;
}
if (null !== $markerType) {
// Write the Type Marker to denote the following action script data type
$this->_stream->writeByte($markerType);
switch ($markerType) {
case Zend_Amf_Constants::AMF3_NULL:
break;
case Zend_Amf_Constants::AMF3_BOOLEAN_FALSE:
break;
case Zend_Amf_Constants::AMF3_BOOLEAN_TRUE:
break;
case Zend_Amf_Constants::AMF3_INTEGER:
$this->writeInteger($data);
break;
case Zend_Amf_Constants::AMF3_NUMBER:
$this->_stream->writeDouble($data);
break;
case Zend_Amf_Constants::AMF3_STRING:
$this->writeString($data);
break;
case Zend_Amf_Constants::AMF3_DATE:
$this->writeDate($data);
break;
case Zend_Amf_Constants::AMF3_ARRAY:
$this->writeArray($data);
break;
case Zend_Amf_Constants::AMF3_OBJECT:
$this->writeObject($data);
break;
case Zend_Amf_Constants::AMF3_BYTEARRAY:
$this->writeByteArray($data);
break;
case Zend_Amf_Constants::AMF3_XMLSTRING;
$this->writeXml($data);
break;
default:
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unknown Type Marker: ' . $markerType);
}
} else {
// Detect Type Marker
if (is_resource($data)) {
$data = Zend_Amf_Parse_TypeLoader::handleResource($data);
}
switch (true) {
case (null === $data):
$markerType = Zend_Amf_Constants::AMF3_NULL;
break;
case (is_bool($data)):
if ($data){
$markerType = Zend_Amf_Constants::AMF3_BOOLEAN_TRUE;
} else {
$markerType = Zend_Amf_Constants::AMF3_BOOLEAN_FALSE;
}
break;
case (is_int($data)):
if (($data > 0xFFFFFFF) || ($data < -268435456)) {
$markerType = Zend_Amf_Constants::AMF3_NUMBER;
} else {
$markerType = Zend_Amf_Constants::AMF3_INTEGER;
}
break;
case (is_float($data)):
$markerType = Zend_Amf_Constants::AMF3_NUMBER;
break;
case (is_string($data)):
$markerType = Zend_Amf_Constants::AMF3_STRING;
break;
case (is_array($data)):
$markerType = Zend_Amf_Constants::AMF3_ARRAY;
break;
case (is_object($data)):
// Handle object types.
if (($data instanceof DateTime) || ($data instanceof Zend_Date)) {
$markerType = Zend_Amf_Constants::AMF3_DATE;
} else if ($data instanceof Zend_Amf_Value_ByteArray) {
$markerType = Zend_Amf_Constants::AMF3_BYTEARRAY;
} else if (($data instanceof DOMDocument) || ($data instanceof SimpleXMLElement)) {
$markerType = Zend_Amf_Constants::AMF3_XMLSTRING;
} else {
$markerType = Zend_Amf_Constants::AMF3_OBJECT;
}
break;
default:
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unsupported data type: ' . gettype($data));
}
$this->writeTypeMarker($data, $markerType);
}
} | Serialize PHP types to AMF3 and write to stream
Checks to see if the type was declared and then either
auto negotiates the type or use the user defined markerType to
serialize the data from php back to AMF3
@param mixed $data
@param int $markerType
@param mixed $dataByVal
@return void | entailment |
public function writeInteger($int)
{
if (($int & 0xffffff80) == 0) {
$this->_stream->writeByte($int & 0x7f);
return $this;
}
if (($int & 0xffffc000) == 0 ) {
$this->_stream->writeByte(($int >> 7 ) | 0x80);
$this->_stream->writeByte($int & 0x7f);
return $this;
}
if (($int & 0xffe00000) == 0) {
$this->_stream->writeByte(($int >> 14 ) | 0x80);
$this->_stream->writeByte(($int >> 7 ) | 0x80);
$this->_stream->writeByte($int & 0x7f);
return $this;
}
$this->_stream->writeByte(($int >> 22 ) | 0x80);
$this->_stream->writeByte(($int >> 15 ) | 0x80);
$this->_stream->writeByte(($int >> 8 ) | 0x80);
$this->_stream->writeByte($int & 0xff);
return $this;
} | Write an AMF3 integer
@param int|float $data
@return Zend_Amf_Parse_Amf3_Serializer | entailment |
protected function writeBinaryString(&$string){
$ref = strlen($string) << 1 | 0x01;
$this->writeInteger($ref);
$this->_stream->writeBytes($string);
return $this;
} | Send string to output stream, without trying to reference it.
The string is prepended with strlen($string) << 1 | 0x01
@param string $string
@return Zend_Amf_Parse_Amf3_Serializer | entailment |
public function writeString(&$string)
{
$len = strlen($string);
if(!$len){
$this->writeInteger(0x01);
return $this;
}
$ref = array_key_exists($string, $this->_referenceStrings)
? $this->_referenceStrings[$string]
: false;
if ($ref === false){
$this->_referenceStrings[$string] = count($this->_referenceStrings);
$this->writeBinaryString($string);
} else {
$ref <<= 1;
$this->writeInteger($ref);
}
return $this;
} | Send string to output stream
@param string $string
@return Zend_Amf_Parse_Amf3_Serializer | entailment |
public function writeByteArray(&$data)
{
if ($this->writeObjectReference($data)) {
return $this;
}
if (is_string($data)) {
//nothing to do
} else if ($data instanceof Zend_Amf_Value_ByteArray) {
$data = $data->getData();
} else {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Invalid ByteArray specified; must be a string or Zend_Amf_Value_ByteArray');
}
$this->writeBinaryString($data);
return $this;
} | Send ByteArray to output stream
@param string|Zend_Amf_Value_ByteArray $data
@return Zend_Amf_Parse_Amf3_Serializer | entailment |
public function writeXml($xml)
{
if ($this->writeObjectReference($xml)) {
return $this;
}
if(is_string($xml)) {
//nothing to do
} else if ($xml instanceof DOMDocument) {
$xml = $xml->saveXml();
} else if ($xml instanceof SimpleXMLElement) {
$xml = $xml->asXML();
} else {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Invalid xml specified; must be a DOMDocument or SimpleXMLElement');
}
$this->writeBinaryString($xml);
return $this;
} | Send xml to output stream
@param DOMDocument|SimpleXMLElement $xml
@return Zend_Amf_Parse_Amf3_Serializer | entailment |
public function writeDate($date)
{
if ($this->writeObjectReference($date)) {
return $this;
}
if ($date instanceof DateTime) {
$dateString = $date->format('U') * 1000;
} elseif ($date instanceof Zend_Date) {
$dateString = $date->toString('U') * 1000;
} else {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Invalid date specified; must be a string DateTime or Zend_Date object');
}
$this->writeInteger(0x01);
// write time to stream minus milliseconds
$this->_stream->writeDouble($dateString);
return $this;
} | Convert DateTime/Zend_Date to AMF date
@param DateTime|Zend_Date $date
@return Zend_Amf_Parse_Amf3_Serializer | entailment |
public function writeArray(&$array)
{
// arrays aren't reference here but still counted
$this->_referenceObjects[] = $array;
// have to seperate mixed from numberic keys.
$numeric = array();
$string = array();
foreach ($array as $key => &$value) {
if (is_int($key)) {
$numeric[] = $value;
} else {
$string[$key] = $value;
}
}
// write the preamble id of the array
$length = count($numeric);
$id = ($length << 1) | 0x01;
$this->writeInteger($id);
//Write the mixed type array to the output stream
foreach($string as $key => &$value) {
$this->writeString($key)
->writeTypeMarker($value);
}
$this->writeString($this->_strEmpty);
// Write the numeric array to ouput stream
foreach($numeric as &$value) {
$this->writeTypeMarker($value);
}
return $this;
} | Write a PHP array back to the amf output stream
@param array $array
@return Zend_Amf_Parse_Amf3_Serializer | entailment |
protected function writeObjectReference(&$object, $objectByVal = false)
{
// Workaround for PHP5 with E_STRICT enabled complaining about "Only
// variables should be passed by reference"
if ((null === $object) && ($objectByVal !== false)) {
$object = &$objectByVal;
}
$hash = spl_object_hash($object);
$ref = array_key_exists($hash, $this->_referenceObjects)
? $this->_referenceObjects[$hash]
: false;
// quickly handle object references
if ($ref !== false){
$ref <<= 1;
$this->writeInteger($ref);
return true;
}
$this->_referenceObjects[$hash] = count($this->_referenceObjects);
return false;
} | Check if the given object is in the reference table, write the reference if it exists,
otherwise add the object to the reference table
@param mixed $object object reference to check for reference
@param mixed $objectByVal object to check for reference
@return Boolean true, if the reference was written, false otherwise | entailment |
public function writeObject($object)
{
if($this->writeObjectReference($object)){
return $this;
}
$className = '';
//Check to see if the object is a typed object and we need to change
switch (true) {
// the return class mapped name back to actionscript class name.
case ($className = Zend_Amf_Parse_TypeLoader::getMappedClassName(get_class($object))):
break;
// Check to see if the user has defined an explicit Action Script type.
case isset($object->_explicitType):
$className = $object->_explicitType;
break;
// Check if user has defined a method for accessing the Action Script type
case method_exists($object, 'getASClassName'):
$className = $object->getASClassName();
break;
// No return class name is set make it a generic object
case ($object instanceof stdClass):
$className = '';
break;
// By default, use object's class name
default:
$className = get_class($object);
break;
}
$writeTraits = true;
//check to see, if we have a corresponding definition
if(array_key_exists($className, $this->_referenceDefinitions)){
$traitsInfo = $this->_referenceDefinitions[$className]['id'];
$encoding = $this->_referenceDefinitions[$className]['encoding'];
$propertyNames = $this->_referenceDefinitions[$className]['propertyNames'];
$traitsInfo = ($traitsInfo << 2) | 0x01;
$writeTraits = false;
} else {
$propertyNames = array();
if($className == ''){
//if there is no className, we interpret the class as dynamic without any sealed members
$encoding = Zend_Amf_Constants::ET_DYNAMIC;
} else {
$encoding = Zend_Amf_Constants::ET_PROPLIST;
foreach($object as $key => $value) {
if( $key[0] != "_") {
$propertyNames[] = $key;
}
}
}
$this->_referenceDefinitions[$className] = array(
'id' => count($this->_referenceDefinitions),
'encoding' => $encoding,
'propertyNames' => $propertyNames,
);
$traitsInfo = Zend_Amf_Constants::AMF3_OBJECT_ENCODING;
$traitsInfo |= $encoding << 2;
$traitsInfo |= (count($propertyNames) << 4);
}
$this->writeInteger($traitsInfo);
if($writeTraits){
$this->writeString($className);
foreach ($propertyNames as $value) {
$this->writeString($value);
}
}
try {
switch($encoding) {
case Zend_Amf_Constants::ET_PROPLIST:
//Write the sealed values to the output stream.
foreach ($propertyNames as $key) {
$this->writeTypeMarker($object->$key);
}
break;
case Zend_Amf_Constants::ET_DYNAMIC:
//Write the sealed values to the output stream.
foreach ($propertyNames as $key) {
$this->writeTypeMarker($object->$key);
}
//Write remaining properties
foreach($object as $key => $value){
if(!in_array($key,$propertyNames) && $key[0] != "_"){
$this->writeString($key);
$this->writeTypeMarker($value);
}
}
//Write an empty string to end the dynamic part
$this->writeString($this->_strEmpty);
break;
case Zend_Amf_Constants::ET_EXTERNAL:
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('External Object Encoding not implemented');
break;
default:
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unknown Object Encoding type: ' . $encoding);
}
} catch (Exception $e) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unable to writeObject output: ' . $e->getMessage(), 0, $e);
}
return $this;
} | Write object to ouput stream
@param mixed $data
@return Zend_Amf_Parse_Amf3_Serializer | entailment |
public function login($data) {
$response=CodeBank_ClientAPI::responseBase();
$response['login']=true;
//Try to login
$member=MemberAuthenticator::authenticate(array(
'Email'=>$data->user,
'Password'=>$data->pass
));
if($member instanceof Member && $member->ID!=0 && Permission::check('CODE_BANK_ACCESS', 'any', $member)) {
try {
$member->logIn();
$ipAgrement=CodeBankConfig::CurrentConfig()->IPAgreement;
//Get preferences
$prefs=new stdClass();
$prefs->heartbeat=$member->UseHeartbeat;
//Set the response to HELO
$response['status']='HELO';
$response['message']=_t('CodeBankAPI.WELCOME_USER', '_Welcome {user}', array('user'=>htmlentities($member->Name))); //Set the message to "Welcome ...."
$response['data']=array(
'id'=>Member::currentUserID(),
'hasIPAgreement'=>!empty($ipAgrement),
'preferences'=>$prefs,
'isAdmin'=>(Permission::check('ADMIN')!==false),
'displayName'=>(trim($member->Name)=='' ? $member->Email:trim($member->Name))
);
}catch (Exception $e) {
//Something happend on the server
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.SERVER_ERROR', '_Server error has occured, please try again later');
}
}else {
//Bad username/pass combo
$response['status']='EROR';
$response['message']=_t('CodeBankAPI.INVALID_LOGIN', '_Invalid Login');
}
return $response;
} | Attempt to login
@param {stdClass} $data Data passed from ActionScript
@return {array} Returns a standard response array | entailment |
public function logout() {
$response=CodeBank_ClientAPI::responseBase();
//Session now expired
$response['session']='expired';
$member=Member::currentUser();
if($member) {
$member->logOut();
}
return $response;
} | Closes the users session
@return {array} Default response base | entailment |
public function lostPassword($data) {
$response=CodeBank_ClientAPI::responseBase();
$response['login']=true;
$SQL_email=Convert::raw2sql($data->user);
$member=Member::get_one('Member', "\"Email\"='{$SQL_email}'");
// Allow vetoing forgot password requests
$sng=new MemberLoginForm(Controller::has_curr() ? Controller::curr():singleton('Controller'), 'LoginForm');
$results=$sng->extend('forgotPassword', $member);
if($results && is_array($results) && in_array(false, $results, true)) {
$response['status']='HELO';
$response['message']=_t('CodeBankAPI.PASSWORD_SENT_TEXT', "A reset link has been sent to '{email}', provided an account exists for this email address.", array('email'=>$data['Email']));
}
if($member) {
$token=$member->generateAutologinTokenAndStoreHash();
$e=Member_ForgotPasswordEmail::create();
$e->populateTemplate($member);
$e->populateTemplate(array(
'PasswordResetLink'=>Security::getPasswordResetLink($member, $token)
));
$e->setTo($member->Email);
$e->send();
$response['status']='HELO';
$response['message']=_t('CodeBankAPI.PASSWORD_SENT_TEXT', "A reset link has been sent to '{email}', provided an account exists for this email address.", array('email'=>$data->user));
}else if(!empty($data->user)) {
$response['status']='HELO';
$response['message']=_t('CodeBankAPI.PASSWORD_SENT_TEXT', "A reset link has been sent to '{email}', provided an account exists for this email address.", array('email'=>$data->user));
}else {
$response['status']='EROR';
$response['message']=_t('Member.ENTEREMAIL', 'Please enter an email address to get a password reset link.');
}
return $response;
} | Method for allowing a user to reset their password
@param {stdClass} $data Data passed from ActionScript
@return {array} Returns a standard response array | entailment |
public static function renderStatic(
array $arguments,
\Closure $renderChildrenClosure,
RenderingContextInterface $renderingContext
) {
$content = trim($renderChildrenClosure());
return preg_match('%^https?\:\/\/%', $content) ?
htmlspecialchars($content) : '{{ path \'/'.ltrim($content, '/').'\' }}';
} | Render a resource URL for Fractal, possibly treated with the `path` view helper
@param array $arguments
@param \Closure $renderChildrenClosure
@param RenderingContextInterface $renderingContext
@return string | entailment |
protected function _addTree(Zend_Server_Reflection_Node $parent, $level = 0)
{
if ($level >= $this->_sigParamsDepth) {
return;
}
foreach ($this->_sigParams[$level] as $value) {
$node = new Zend_Server_Reflection_Node($value, $parent);
if ((null !== $value) && ($this->_sigParamsDepth > $level + 1)) {
$this->_addTree($node, $level + 1);
}
}
} | Create signature node tree
Recursive method to build the signature node tree. Increments through
each array in {@link $_sigParams}, adding every value of the next level
to the current value (unless the current value is null).
@param Zend_Server_Reflection_Node $parent
@param int $level
@return void | entailment |
protected function _buildTree()
{
$returnTree = array();
foreach ((array) $this->_return as $value) {
$node = new Zend_Server_Reflection_Node($value);
$this->_addTree($node);
$returnTree[] = $node;
}
return $returnTree;
} | Build the signature tree
Builds a signature tree starting at the return values and descending
through each method argument. Returns an array of
{@link Zend_Server_Reflection_Node}s.
@return array | entailment |
protected function _buildSignatures($return, $returnDesc, $paramTypes, $paramDesc)
{
$this->_return = $return;
$this->_returnDesc = $returnDesc;
$this->_paramDesc = $paramDesc;
$this->_sigParams = $paramTypes;
$this->_sigParamsDepth = count($paramTypes);
$signatureTrees = $this->_buildTree();
$signatures = array();
$endPoints = array();
foreach ($signatureTrees as $root) {
$tmp = $root->getEndPoints();
if (empty($tmp)) {
$endPoints = array_merge($endPoints, array($root));
} else {
$endPoints = array_merge($endPoints, $tmp);
}
}
foreach ($endPoints as $node) {
if (!$node instanceof Zend_Server_Reflection_Node) {
continue;
}
$signature = array();
do {
array_unshift($signature, $node->getValue());
$node = $node->getParent();
} while ($node instanceof Zend_Server_Reflection_Node);
$signatures[] = $signature;
}
// Build prototypes
$params = $this->_reflection->getParameters();
foreach ($signatures as $signature) {
$return = new Zend_Server_Reflection_ReturnValue(array_shift($signature), $this->_returnDesc);
$tmp = array();
foreach ($signature as $key => $type) {
$param = new Zend_Server_Reflection_Parameter($params[$key], $type, (isset($this->_paramDesc[$key]) ? $this->_paramDesc[$key] : null));
$param->setPosition($key);
$tmp[] = $param;
}
$this->_prototypes[] = new Zend_Server_Reflection_Prototype($return, $tmp);
}
} | Build method signatures
Builds method signatures using the array of return types and the array of
parameters types
@param array $return Array of return types
@param string $returnDesc Return value description
@param array $params Array of arguments (each an array of types)
@param array $paramDesc Array of parameter descriptions
@return array | entailment |
protected function _reflect()
{
$function = $this->_reflection;
$helpText = '';
$signatures = array();
$returnDesc = '';
$paramCount = $function->getNumberOfParameters();
$paramCountRequired = $function->getNumberOfRequiredParameters();
$parameters = $function->getParameters();
$docBlock = $function->getDocComment();
if (!empty($docBlock)) {
// Get help text
if (preg_match(':/\*\*\s*\r?\n\s*\*\s(.*?)\r?\n\s*\*(\s@|/):s', $docBlock, $matches))
{
$helpText = $matches[1];
$helpText = preg_replace('/(^\s*\*\s)/m', '', $helpText);
$helpText = preg_replace('/\r?\n\s*\*\s*(\r?\n)*/s', "\n", $helpText);
$helpText = trim($helpText);
}
// Get return type(s) and description
$return = 'void';
if (preg_match('/@return\s+(\S+)/', $docBlock, $matches)) {
$return = explode('|', $matches[1]);
if (preg_match('/@return\s+\S+\s+(.*?)(@|\*\/)/s', $docBlock, $matches))
{
$value = $matches[1];
$value = preg_replace('/\s?\*\s/m', '', $value);
$value = preg_replace('/\s{2,}/', ' ', $value);
$returnDesc = trim($value);
}
}
// Get param types and description
if (preg_match_all('/@param\s+([^\s]+)/m', $docBlock, $matches)) {
$paramTypesTmp = $matches[1];
if (preg_match_all('/@param\s+\S+\s+(\$\S+)\s+(.*?)(?=@|\*\/)/s', $docBlock, $matches))
{
$paramDesc = $matches[2];
foreach ($paramDesc as $key => $value) {
$value = preg_replace('/\s?\*\s/m', '', $value);
$value = preg_replace('/\s{2,}/', ' ', $value);
$paramDesc[$key] = trim($value);
}
}
}
} else {
$helpText = $function->getName();
$return = 'void';
// Try and auto-determine type, based on reflection
$paramTypesTmp = array();
foreach ($parameters as $i => $param) {
$paramType = 'mixed';
if ($param->isArray()) {
$paramType = 'array';
}
$paramTypesTmp[$i] = $paramType;
}
}
// Set method description
$this->setDescription($helpText);
// Get all param types as arrays
if (!isset($paramTypesTmp) && (0 < $paramCount)) {
$paramTypesTmp = array_fill(0, $paramCount, 'mixed');
} elseif (!isset($paramTypesTmp)) {
$paramTypesTmp = array();
} elseif (count($paramTypesTmp) < $paramCount) {
$start = $paramCount - count($paramTypesTmp);
for ($i = $start; $i < $paramCount; ++$i) {
$paramTypesTmp[$i] = 'mixed';
}
}
// Get all param descriptions as arrays
if (!isset($paramDesc) && (0 < $paramCount)) {
$paramDesc = array_fill(0, $paramCount, '');
} elseif (!isset($paramDesc)) {
$paramDesc = array();
} elseif (count($paramDesc) < $paramCount) {
$start = $paramCount - count($paramDesc);
for ($i = $start; $i < $paramCount; ++$i) {
$paramDesc[$i] = '';
}
}
if (count($paramTypesTmp) != $paramCount) {
require_once 'Zend/Server/Reflection/Exception.php';
throw new Zend_Server_Reflection_Exception(
'Variable number of arguments is not supported for services (except optional parameters). '
. 'Number of function arguments in ' . $function->getDeclaringClass()->getName() . '::'
. $function->getName() . '() must correspond to actual number of arguments described in the '
. 'docblock.');
}
$paramTypes = array();
foreach ($paramTypesTmp as $i => $param) {
$tmp = explode('|', $param);
if ($parameters[$i]->isOptional()) {
array_unshift($tmp, null);
}
$paramTypes[] = $tmp;
}
$this->_buildSignatures($return, $returnDesc, $paramTypes, $paramDesc);
} | Use code reflection to create method signatures
Determines the method help/description text from the function DocBlock
comment. Determines method signatures using a combination of
ReflectionFunction and parsing of DocBlock @param and @return values.
@param ReflectionFunction $function
@return array | entailment |
static public function createWithSafeMessage($safeMessage = "", array $messageData = array(), $code = 0, \Exception $previous = null)
{
$exception = new static($safeMessage, $code, $previous);
$exception->setSafeMessage($safeMessage, $messageData);
return $exception;
} | Helper method to create this exception and set the safe message
that will be shown to the user.
@param string $safeMessage
@param array $messageData
@param int $code
@param \Exception $previous
@return CustomAuthenticationException | entailment |
public function unserialize($str)
{
list($this->messageKey, $this->messageData, $parentData) = unserialize($str);
parent::unserialize($parentData);
} | {@inheritdoc} | entailment |
public function validate(ValidationResult $validationResult) {
if (!$this->owner->ID) return; // The object is new, won't be looping.
if (!$this->owner->LanguageID) return; // The object has no parent, won't be looping.
if (!$this->owner->isChanged('LanguageID')) return; // The parent has not changed, skip the check for performance reasons.
// Walk the hierarchy upwards until we reach the top, or until we reach the originating node again.
$node=$this->owner;
while($node) {
if ($node->LanguageID==$this->owner->ID) {
// Hierarchy is looping.
$validationResult->error(
_t(
'Hierarchy.InfiniteLoopNotAllowed',
'Infinite loop found within the "{type}" hierarchy. Please change the parent to resolve this',
'First argument is the class that makes up the hierarchy.',
array('type' => $this->owner->class)
),
'INFINITE_LOOP'
);
break;
}
$node=$node->LanguageID ? $node->Language() : null;
}
// At this point the $validationResult contains the response.
} | Validate the owner object - check for existence of infinite loops. | entailment |
public function parentStack() {
$p=$this->owner;
while($p) {
$stack[]=$p;
if($p->FolderID && $p->FolderID>0) {
$folder=$p->Folder();
if(!empty($folder) && $folder!==false && $folder->ID!=0) {
$p=$folder;
}
}else {
$p=$p->LanguageID ? $p->Language() : null;
}
}
return $stack;
} | Return an array of this page and its ancestors, ordered item -> root.
@return array | entailment |
public function getAncestors() {
$ancestors=new ArrayList();
$object =$this->owner;
while($object=$object->Language()) {
$ancestors->push($object);
}
return $ancestors;
} | Return all the parents of this class in a set ordered from the lowest to highest parent.
@return SS_List | entailment |
public function naturalNext( $className=null, $root=0, $afterNode=null ) {
// If this node is not the node we are searching from, then we can possibly return this
// node as a solution
if($afterNode && $afterNode->ID != $this->owner->ID) {
if(!$className || ($className && $this->owner->class == $className)) {
return $this->owner;
}
}
$nextNode=null;
$baseClass=ClassInfo::baseDataClass($this->owner->class);
$children=DataObject::get(ClassInfo::baseDataClass($this->owner->class), "\"$baseClass\".\"LanguageID\"={$this->owner->ID}" . ( ( $afterNode ) ? " AND \"Sort\" > " . sprintf( '%d', $afterNode->Sort ) : "" ), '"Sort" ASC');
// Try all the siblings of this node after the given node
/*if( $siblings=DataObject::get( ClassInfo::baseDataClass($this->owner->class), "\"LanguageID\"={$this->owner->LanguageID}" . ( $afterNode ) ? "\"Sort\" > {$afterNode->Sort}" : "" , '\"Sort\" ASC' ) )
$searchNodes->merge( $siblings );*/
if($children) {
foreach($children as $node) {
if($nextNode=$node->naturalNext($className, $node->ID, $this->owner)) {
break;
}
}
if($nextNode) {
return $nextNode;
}
}
// if this is not an instance of the root class or has the root id, search the parent
if(!(is_numeric($root) && $root == $this->owner->ID || $root == $this->owner->class) && ($parent=$this->owner->Language())) {
return $parent->naturalNext( $className, $root, $this->owner );
}
return null;
} | Get the next node in the tree of the type. If there is no instance of the className descended from this node,
then search the parents.
@param string $className Class name of the node to find.
@param string|int $root ID/ClassName of the node to limit the search to
@param DataObject afterNode Used for recursive calls to this function
@return DataObject | entailment |
public function markPartialTree($minNodeCount=30, $context=null, $childrenMethod="AllChildrenIncludingDeleted", $numChildrenMethod="numChildren") {
if(!is_numeric($minNodeCount)) $minNodeCount=30;
$this->markedNodes=array($this->owner->ClassName.'_'.$this->owner->ID=>$this->owner);
$this->owner->markUnexpanded();
// foreach can't handle an ever-growing $nodes list
while(list($id, $node)=each($this->markedNodes)) {
$this->markChildren($node, $context, $childrenMethod, $numChildrenMethod);
if($minNodeCount && sizeof($this->markedNodes)>=$minNodeCount) {
break;
}
}
return sizeof($this->markedNodes);
} | Mark a segment of the tree, by calling mark().
The method performs a breadth-first traversal until the number of nodes is more than minCount.
This is used to get a limited number of tree nodes to show in the CMS initially.
This method returns the number of nodes marked. After this method is called other methods
can check isExpanded() and isMarked() on individual nodes.
@param int $minNodeCount The minimum amount of nodes to mark.
@return int The actual number of nodes marked. | entailment |
public function markChildren($node, $context=null, $childrenMethod='AllChildrenIncludingDeleted', $numChildrenMethod='numChildren') {
if($node->hasMethod($childrenMethod)) {
$children=$node->$childrenMethod($context);
}else {
user_error(sprintf("Can't find the method '%s' on class '%s' for getting tree children", $childrenMethod, get_class($node)), E_USER_ERROR);
}
$node->markExpanded();
if($children) {
foreach($children as $child) {
if(!$this->markingFilter || $this->markingFilterMatches($child)) {
if($child->$numChildrenMethod()) {
$child->markUnexpanded();
}else {
$child->markExpanded();
}
$this->markedNodes[$child->ClassName.'_'.$child->ID]=$child;
}
}
}
} | Mark all children of the given node that match the marking filter.
@param DataObject $node Parent node. | entailment |
public function markById($id, $open=false, $className=null) {
if(isset($this->markedNodes[$className.'_'.$id])) {
$this->markChildren($this->markedNodes[$className.'_'.$id]);
if($open) {
$this->markedNodes[$className.'_'.$id]->markOpened();
}
return true;
} else {
return false;
}
} | Mark the children of the DataObject with the given ID.
@param int $id ID of parent node.
@param boolean $open If this is true, mark the parent node as opened. | entailment |
public function markToExpose($childObj) {
if(is_object($childObj)){
$stack=array_reverse($childObj->parentStack());
foreach($stack as $stackItem) {
$this->markById($stackItem->ID, true, $stackItem->ClassName);
}
}
} | Expose the given object in the tree, by marking this page and all it ancestors.
@param DataObject $childObj | entailment |
public function numChildren($cache=true) {
// Build the cache for this class if it doesn't exist.
if(!$cache || !is_numeric($this->_cache_numChildren)) {
if($this->owner instanceof SnippetLanguage) {
$this->_cache_numChildren=(int)$this->owner->Snippets()->filter('FolderID', 0)->Count() + (int)$this->owner->Folders()->Count();
}else if($this->owner instanceof SnippetFolder) {
$this->_cache_numChildren=(int)$this->owner->Snippets()->Count() + (int)$this->owner->Folders()->Count();
}else {
$this->_cache_numChildren=0;
}
}
// If theres no value in the cache, it just means that it doesn't have any children.
return $this->_cache_numChildren;
} | Return the number of direct children.
By default, values are cached after the first invocation.
Can be augumented by {@link augmentNumChildrenCountQuery()}.
@param Boolean $cache
@return int | entailment |
public function getChildrenAsUL($attributes="", $titleEval='"<li>" . $child->Title', $extraArg=null, $limitToMarked=false, $childrenMethod="AllChildrenIncludingDeleted", $numChildrenMethod="numChildren", $rootCall=true, $minNodeCount=30) {
if($limitToMarked && $rootCall) {
$this->markingFinished($numChildrenMethod);
}
if($this->owner->hasMethod($childrenMethod)) {
$children=$this->owner->$childrenMethod($extraArg);
} else {
user_error(sprintf("Can't find the method '%s' on class '%s' for getting tree children",
$childrenMethod, get_class($this->owner)), E_USER_ERROR);
}
if($children) {
if($attributes) {
$attributes=" $attributes";
}
$output="<ul$attributes>\n";
foreach($children as $child) {
if(!$limitToMarked || $child->isMarked()) {
$foundAChild=true;
$output .= (is_callable($titleEval)) ? $titleEval($child) : eval("return $titleEval;");
$output .= "\n" .
$child->getChildrenAsUL("", $titleEval, $extraArg, $limitToMarked, $childrenMethod, $numChildrenMethod, false, $minNodeCount) . "</li>\n";
}
}
$output .= "</ul>\n";
}
if(isset($foundAChild) && $foundAChild) {
return $output;
}
} | Returns the children of this DataObject as an XHTML UL. This will be called recursively on each child,
so if they have children they will be displayed as a UL inside a LI.
@param string $attributes Attributes to add to the UL.
@param string|callable $titleEval PHP code to evaluate to start each child - this should include '<li>'
@param string $extraArg Extra arguments that will be passed on to children, for if they overload this function.
@param boolean $limitToMarked Display only marked children.
@param string $childrenMethod The name of the method used to get children from each object
@param boolean $rootCall Set to true for this first call, and then to false for calls inside the recursion. You should not change this.
@param int $minNodeCount
@return string | entailment |
public function markingFilterMatches($node) {
if(!$this->markingFilter) {
return true;
}
if(isset($this->markingFilter['parameter']) && $parameterName=$this->markingFilter['parameter']) {
if(is_array($this->markingFilter['value'])){
$ret=false;
foreach($this->markingFilter['value'] as $value) {
$ret=$ret||$node->$parameterName==$value;
if($ret == true) {
break;
}
}
return $ret;
} else {
return ($node->$parameterName == $this->markingFilter['value']);
}
} else if ($func=$this->markingFilter['func']) {
return call_user_func($func, $node);
}
} | Returns true if the marking filter matches on the given node.
@param DataObject $node Node to check.
@return boolean | entailment |
protected function markingFinished($numChildrenMethod="numChildren") {
// Mark childless nodes as expanded.
if($this->markedNodes) {
foreach($this->markedNodes as $id => $node) {
if(!$node->isExpanded() && !$node->$numChildrenMethod()) {
$node->markExpanded();
}
}
}
} | Ensure marked nodes that have children are also marked expanded.
Call this after marking but before iterating over the tree. | entailment |
public function markingClasses() {
$classes='';
if(!$this->isExpanded()) {
$classes .= " unexpanded jstree-closed";
}
if($this->isTreeOpened()) {
if($this->numChildren() > 0) $classes .= " jstree-open";
} else {
$classes .= " closed";
}
return $classes;
} | Return CSS classes of 'unexpanded', 'closed', both, or neither, depending on
the marking of this DataObject. | entailment |
public function markExpanded() {
self::$marked[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID]=true;
self::$expanded[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID]=true;
} | Mark this DataObject as expanded. | entailment |
public function markUnexpanded() {
self::$marked[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID]=true;
self::$expanded[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID]=false;
} | Mark this DataObject as unexpanded. | entailment |
public function markOpened() {
self::$marked[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID]=true;
self::$treeOpened[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID]=true;
} | Mark this DataObject's tree as opened. | entailment |
public function isMarked() {
$baseClass=ClassInfo::baseDataClass($this->owner->class);
$id=$this->owner->ID;
return isset(self::$marked[$baseClass][$id]) ? self::$marked[$baseClass][$id] : false;
} | Check if this DataObject is marked.
@return boolean | entailment |
public function isExpanded() {
$baseClass=ClassInfo::baseDataClass($this->owner->class);
$id=$this->owner->ID;
return isset(self::$expanded[$baseClass][$id]) ? self::$expanded[$baseClass][$id] : false;
} | Check if this DataObject is expanded.
@return boolean | entailment |
public function isTreeOpened() {
$baseClass=ClassInfo::baseDataClass($this->owner->class);
$id=$this->owner->ID;
return isset(self::$treeOpened[$baseClass][$id]) ? self::$treeOpened[$baseClass][$id] : false;
} | Check if this DataObject's tree is opened. | entailment |
public function partialTreeAsUL($minCount=50) {
$children=$this->owner->AllChildren();
if($children) {
if($attributes) $attributes=" $attributes";
$output="<ul$attributes>\n";
foreach($children as $child) {
$output .= eval("return $titleEval;") . "\n" .
$child->getChildrenAsUL("", $titleEval, $extraArg) . "</li>\n";
}
$output .= "</ul>\n";
}
return $output;
} | Return a partial tree as an HTML UL. | entailment |
public function loadDescendantIDListInto(&$idList) {
if($children=$this->AllChildren()) {
foreach($children as $child) {
if(in_array($child->ID, $idList)) {
continue;
}
$idList[]=$child->ID;
$ext=$child->getExtensionInstance('Hierarchy');
$ext->setOwner($child);
$ext->loadDescendantIDListInto($idList);
$ext->clearOwner();
}
}
} | Get a list of this DataObject's and all it's descendants ID, and put it in $idList.
@var array $idList Array to put results in. | entailment |
public function Children() {
if(!(isset($this->_cache_children) && $this->_cache_children)) {
$result=$this->owner->stageChildren(false);
if(isset($result)) {
$this->_cache_children=new ArrayList();
foreach($result as $child) {
if($child->canView()) {
$this->_cache_children->push($child);
}
}
}
}
return $this->_cache_children;
} | Get the children for this DataObject.
@return SS_List | entailment |
public function doAllChildrenIncludingDeleted($context=null) {
if(!$this->owner) user_error('Hierarchy::doAllChildrenIncludingDeleted() called without $this->owner');
$idxStageChildren=array();
$idxLiveChildren=array();
$baseClass=ClassInfo::baseDataClass($this->owner->class);
if($baseClass) {
$stageChildren=$this->owner->stageChildren(true);
$this->owner->extend("augmentAllChildrenIncludingDeleted", $stageChildren, $context);
}else {
user_error("SnippetHierarchy::AllChildren() Couldn't determine base class for '{$this->owner->class}'", E_USER_ERROR);
}
return $stageChildren;
} | @see AllChildrenIncludingDeleted
@param unknown_type $context
@return SS_List | entailment |
public function stageChildren($showAll=false) {
$baseClass=ClassInfo::baseDataClass($this->owner->class);
if($baseClass=='SnippetPackage') {
if($this->owner->ID==0) {
$staged=SnippetPackage::get();
}
}else if($baseClass=='SnippetLanguage') {
if($this->owner->ID==0) {
$staged=SnippetLanguage::get();
}else {
$staged=ArrayList::create(array_merge($this->owner->Folders()->toArray(), $this->owner->Snippets()->filter('FolderID', 0)->toArray()));
}
}else if($baseClass=='SnippetFolder') {
$staged=ArrayList::create(array_merge($this->owner->Folders()->toArray(), $this->owner->Snippets()->toArray()));
}else {
$staged=new ArrayList();
}
$this->owner->extend("augmentStageChildren", $staged, $showAll);
return $staged;
} | Return children from the stage site
@param showAll Inlcude all of the elements, even those not shown in the menus.
(only applicable when extension is applied to {@link SiteTree}).
@return SS_List | entailment |
public function getBreadcrumbs($separator=' » ') {
$crumbs=array();
$ancestors=array_reverse($this->owner->getAncestors()->toArray());
foreach($ancestors as $ancestor) $crumbs[]=$ancestor->Title;
$crumbs[]=$this->owner->Title;
return implode($separator, $crumbs);
} | Returns a human-readable, flattened representation of the path to the object,
using its {@link Title()} attribute.
@param String
@return String | entailment |
public function authenticate(TokenInterface $token)
{
if (!$this->supports($token)) {
throw new \InvalidArgumentException('GuardAuthenticationProvider only supports GuardTokenInterface.');
}
if (!$token instanceof PreAuthenticationGuardToken) {
/*
* The listener *only* passes PreAuthenticationGuardToken instances.
* This means that an authenticated token (e.g. PostAuthenticationGuardToken)
* is being passed here, which happens if that token becomes
* "not authenticated" (e.g. happens if the user changes between
* requests). In this case, the user should be logged out, so
* we will return an AnonymousToken to accomplish that.
*/
// this should never happen - but technically, the token is
// authenticated... so it could just be returned
if ($token->isAuthenticated()) {
return $token;
}
// cause the logout - the token is not authenticated
return new AnonymousToken($this->providerKey, 'anon.');
}
// find the *one* GuardAuthenticator that this token originated from
foreach ($this->guardAuthenticators as $key => $guardAuthenticator) {
// get a key that's unique to *this* guard authenticator
// this MUST be the same as GuardAuthenticationListener
$uniqueGuardKey = $this->providerKey.'_'.$key;
if ($uniqueGuardKey == $token->getGuardProviderKey()) {
return $this->authenticateViaGuard($guardAuthenticator, $token);
}
}
// no matching authenticator found - but there will be multiple GuardAuthenticationProvider
// instances that will be checked if you have multiple firewalls.
} | Finds the correct authenticator for the token and calls it.
@param GuardTokenInterface $token
@return TokenInterface | entailment |
public function requireDefaultRecords() {
parent::requireDefaultRecords();
$codeVersion=singleton('CodeBank')->getVersion();
if(!CodeBankConfig::get()->first()) {
$conf=new CodeBankConfig();
$conf->Version=$codeVersion;
$conf->write();
DB::alteration_message('Default Code Bank Config Created', 'created');
}
if(!Group::get()->filter('Code', 'code-bank-api')->first()) {
$group=new Group();
$group->Title='Code Bank Users';
$group->Description='Code Bank Access Group';
$group->Code='code-bank-api';
$group->write();
$permission=new Permission();
$permission->Code='CODE_BANK_ACCESS';
$permission->Type=1;
$permission->GroupID=$group->ID;
$permission->write();
DB::alteration_message('Code Bank Users Group Created', 'created');
}
//Check for and perform any needed updates
$codeVersionTmp=explode(' ', $codeVersion);
$dbVerTmp=explode(' ', CodeBankConfig::CurrentConfig()->Version);
if($codeVersionTmp[0]!='@@VERSION@@' && $codeVersionTmp[0]!=$dbVerTmp[0]) {
$updateXML=simplexml_load_string(file_get_contents('http://update.edchipman.ca/codeBank/airUpdate.xml'));
$latestVersion=strip_tags($updateXML->version->asXML());
$versionTmp=explode(' ', $latestVersion);
//Sanity Check code version against latest
if(version_compare($codeVersionTmp[0], $versionTmp[0], '>')) {
DB::alteration_message('Unknown Code Bank server version '.$codeVersion.', current version available for download is '.$latestVersion, 'error');
return;
}
//Sanity Check make sure latest version is installed
if($codeVersionTmp[0]!=$versionTmp[0]) {
DB::alteration_message('A Code Bank Server update is available, please <a href="http://programs.edchipman.ca/applications/code-bank/">download</a> and install the update then run dev/build again.', 'error');
return;
}
//Sanity Check database version against latest
if(version_compare($dbVerTmp[0], $versionTmp[0], '<')) {
$data=array(
'version'=>CodeBankConfig::CurrentConfig()->Version,
'db_type'=>'SERVER'
);
$data=http_build_query($data);
$context=stream_context_create(array(
'http'=>array(
'method'=>'POST',
'header'=>"Content-type: application/x-www-form-urlencoded\r\n"
."Content-Length: ".strlen($data)."\r\n",
'content'=>$data
)
));
//Download and run queries needed
$sql=simplexml_load_string(file_get_contents('http://update.edchipman.ca/codeBank/DatabaseUpgrade.php', false, $context));
$sets=count($sql->query);
foreach($sql->query as $query) {
$queries=explode('$',$query);
$t=count($queries);
foreach($queries as $query) {
if(empty($query)) {
continue;
}
DB::query($query);
}
}
//Update Database Version
$codeBankConfig=CodeBankConfig::CurrentConfig();
$codeBankConfig->Version=$latestVersion;
$codeBankConfig->write();
DB::alteration_message('Code Bank Server database upgraded', 'changed');
}
}
} | Creates the default code bank config | entailment |
public static function CurrentConfig() {
if(empty(self::$_currentConfig)) {
self::$_currentConfig=CodeBankConfig::get()->first();
}
return self::$_currentConfig;
} | Gets the current config
@return {CodeBankConfig} Code Bank Config Data | entailment |
public function getCMSFields() {
$langGridConfig=GridFieldConfig_RecordEditor::create(30);
$langGridConfig->getComponentByType('GridFieldDetailForm')->setItemRequestClass('CodeBankGridField_ItemRequest');
$langGridConfig->getComponentByType('GridFieldDataColumns')->setFieldCasting(array(
'UserLanguage'=>'Boolean->Nice',
'Hidden'=>'Boolean->Nice'
));
$packageGridConfig=GridFieldConfig_RecordEditor::create(30);
$packageGridConfig->addComponent(new ExportPackageButton());
$packageGridConfig->getComponentByType('GridFieldDetailForm')->setItemRequestClass('CodeBankGridField_ItemRequest')->setItemEditFormCallback(function(Form $form, GridFieldDetailForm_ItemRequest $itemRequest) {
Requirements::javascript(CB_DIR.'/javascript/SnippetPackages.ItemEditForm.js');
if($form->getRecord() && $form->getRecord()->ID>0) {
$form->Actions()->push(FormAction::create('doExportPackage', _t('CodeBank.EXPORT', '_Export'))->setForm($form));
}
$form->addExtraClass('CodeBankPackages');
});
if(Permission::check('ADMIN')) {
$fields=new FieldList(
new TabSet('Root',
new Tab('Main', _t('CodeBankConfig.MAIN', '_IP Message'),
HtmlEditorField::create('IPMessage', _t('CodeBankConfig.IP_MESSAGE', '_Intellectual Property Message'))->addExtraClass('stacked')
),
new Tab('Languages', _t('CodeBankConfig.LANGUAGES', '_Languages'),
new GridField('Languages', _t('CodeBankConfig.LANGUAGES', '_Languages'), SnippetLanguage::get(), $langGridConfig)
),
new Tab('Packages', _t('CodeBank.PACKAGES', '_Packages'),
new GridField('Packages', _t('CodeBankConfig.MANAGE_PACKAGES', '_Manage Packages'), SnippetPackage::get(), $packageGridConfig)
)
)
);
}else {
$fields=new FieldList(
new TabSet('Root',
new Tab('Packages', _t('CodeBank.PACKAGES', '_Packages'),
new GridField('Packages', _t('CodeBankConfig.MANAGE_PACKAGES', '_Manage Packages'), SnippetPackage::get(), $packageGridConfig)
)
)
);
}
return $fields;
} | Gets fields used in the cms
@return {FieldList} Fields to be used | entailment |
function setup() {
$dataStore = new PersonalDataStoreStub();
$this->eventStore = new TestEventStoreSpy();
$this->container = new ContainerStub();
$this->container->set(EventStore::class, $this->eventStore);
$this->classMap = new DomainEventClassMap();
$this->commandBus = new ReflectionResolutionCommandBus($this->container);
$this->serializer = new ReflectionBasedDomainEventSerializer(
$this->classMap,
new ValueSerializer($dataStore),
$dataStore
);
} | setup() is the initialization function that will
define our dependencies. call it from the objectbehavior's
let() function
```php
function let() {
$this->setup();
}
``` | entailment |
public function given(StreamId $id, DomainEvent ...$domainEvents) {
$version = StreamVersion::zero();
$this->environment = StreamEvents::make(
array_map(function (DomainEvent $event) use ($id, &$version) {
$streamEvent = new StreamEvent($id, $version, $event);
$version = $version->next();
return $streamEvent;
}, $domainEvents)
);
return $this;
} | given() is the method to use to set up an environment
that consists of a single event stream.
the environment is the collection of events that need to
already exist within the event store in order to test that
the command results in the generation of the correct outcome
the first argument is the stream id, the rest of the arguments
are a variadic list of domain events.
```php
$this->given(
StreamId::fromString('test id'),
new ExampleEvent(1),
new ExampleEvent(1),
)->when(
// ...
)->then(
// ...
);
```
@param StreamId $id
@param DomainEvent ...$domainEvents
@return $this | entailment |
public function givenStreams(StreamEvents ...$streamEvents) {
$arraysOfEvents[] = array_map(function (StreamEvents $streamEvents) {
return $streamEvents->toArray();
}, $streamEvents);
$this->environment = StreamEvents::make(array_merge(...$arraysOfEvents));
return $this;
} | givenStreams() is the method to use to set up an environment
that consists of multiple event streams.
the environment is the collection of events that need to
already exist within the event store in order to test that
the command results in the generation of the correct outcome
the argument is a variadic list of StreamEvents collections.
```php
$this->givenStreams(
$stream1,
$stream2,
$stream3,
)->when(
// ...
)->then(
// ...
);
```
@param StreamEvents[] $streamEvents
@return $this | entailment |
public function then(DomainEvent ...$events) {
if ( ! $this->commandBus) {
throw new FailureException('Cannot execute specification without calling beInitializedWith().');
}
$this->commandBus->execute($this->commandToExecute);
$this->eventsShouldExistInStore(...$events);
} | then() is the method that triggers the execution of the
command and then validates that the Domain Events passed
as the argument exist within the environment.
```php
$this->given(
// ...
)->when(
// ...
)->then(
new ExampleEvent(1),
new ExampleEvent(1)
);
```
@param DomainEvent ...$events
@throws \Exception | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.