Merge pull request #2214 from wilr/patches/anchor-extension

NEW add SiteTree::updateAnchorsOnPage() for defining content anchors
This commit is contained in:
Robbie Averill 2018-07-16 10:07:03 +12:00 committed by GitHub
commit d1112f25b9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 16 deletions

View File

@ -2,7 +2,7 @@
namespace SilverStripe\CMS\Forms;
use Page;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Forms\TextField;
@ -38,34 +38,24 @@ class AnchorSelectorField extends TextField
{
$id = (int)$this->getRequest()->param('PageID');
$anchors = $this->getAnchorsInPage($id);
return json_encode($anchors);
}
/**
* Get anchors in the given page ID
* Get anchors in the given page ID.
*
* @param int $id
* @return array
*/
protected function getAnchorsInPage($id)
{
// Check page is accessible
$page = Page::get()->byID($id);
$page = SiteTree::get()->byID($id);
if (!$page || !$page->canView()) {
return [];
}
// Similar to the regex found in HtmlEditorField.js / getAnchors method.
$parseSuccess = preg_match_all(
"/\\s+(name|id)\\s*=\\s*([\"'])([^\\2\\s>]*?)\\2|\\s+(name|id)\\s*=\\s*([^\"']+)[\\s +>]/im",
$page->Content,
$matches
);
if (!$parseSuccess) {
return [];
}
// Cleanup results
return array_values(array_unique(array_filter(array_merge($matches[3], $matches[5]))));
return $page->getAnchorsOnPage();
}
}

View File

@ -3093,4 +3093,28 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi
$this->extend('updateExcludedURLSegments', $excludes);
return $excludes;
}
/**
* @return array
*/
public function getAnchorsOnPage()
{
$parseSuccess = preg_match_all(
"/\\s+(name|id)\\s*=\\s*([\"'])([^\\2\\s>]*?)\\2|\\s+(name|id)\\s*=\\s*([^\"']+)[\\s +>]/im",
$this->Content,
$matches
);
if (!$parseSuccess) {
return [];
}
$anchors = array_values(array_unique(array_filter(
array_merge($matches[3], $matches[5])
)));
$this->extend('updateAnchorsOnPage', $anchors);
return $anchors;
}
}