id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
43,000
mage2pro/core
API/Client.php
Client.resPath
final protected function resPath($k) {$this->addFilterResAV(function(array $a) use($k) {return dfa_deep($a, $k, $a) ;});}
php
final protected function resPath($k) {$this->addFilterResAV(function(array $a) use($k) {return dfa_deep($a, $k, $a) ;});}
[ "final", "protected", "function", "resPath", "(", "$", "k", ")", "{", "$", "this", "->", "addFilterResAV", "(", "function", "(", "array", "$", "a", ")", "use", "(", "$", "k", ")", "{", "return", "dfa_deep", "(", "$", "a", ",", "$", "k", ",", "$",...
2019-04-04 @used-by \Inkifi\Pwinty\API\Client::_construct() @param string $k
[ "2019", "-", "04", "-", "04" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/API/Client.php#L256-L258
43,001
mage2pro/core
API/Client.php
Client.setup
private function setup(array $config) { $r = new C(null, $config + [ 'timeout' => 120 /** * 2017-07-16 * By default it is «Zend_Http_Client»: @see C::$config * https://github.com/magento/zf1/blob/1.13.1/library/Zend/Http/Client.php#L126 */ ,'useragent' => 'Mage2.PRO' ]); /** @var C $r */ /** @var aProxy|aSocket $a */ if (!($p = $this->proxy())) { /** @var IProxy $p */ $a = new aSocket; } else { // 2019-01-14 // https://framework.zend.com/manual/1.12/en/zend.http.client.adapters.html#zend.http.client.adapters.proxy $a = new aProxy; $r->setConfig([ 'proxy_host' => $p->host() ,'proxy_pass' => $p->password() ,'proxy_port' => $p->port() ,'proxy_user' => $p->username() ]); } if ($p || !$this->verifyCertificate()) { $ssl = ['allow_self_signed' => true, 'verify_peer' => false]; /** @var array(string => bool) $ssl */ if ($p) { // 2019-01-14 It is needed for my proxy: https://stackoverflow.com/a/32047219 $ssl['verify_peer_name'] = false; } $a->setStreamContext(['ssl' => $ssl]); } $r->setAdapter($a); return $r; }
php
private function setup(array $config) { $r = new C(null, $config + [ 'timeout' => 120 /** * 2017-07-16 * By default it is «Zend_Http_Client»: @see C::$config * https://github.com/magento/zf1/blob/1.13.1/library/Zend/Http/Client.php#L126 */ ,'useragent' => 'Mage2.PRO' ]); /** @var C $r */ /** @var aProxy|aSocket $a */ if (!($p = $this->proxy())) { /** @var IProxy $p */ $a = new aSocket; } else { // 2019-01-14 // https://framework.zend.com/manual/1.12/en/zend.http.client.adapters.html#zend.http.client.adapters.proxy $a = new aProxy; $r->setConfig([ 'proxy_host' => $p->host() ,'proxy_pass' => $p->password() ,'proxy_port' => $p->port() ,'proxy_user' => $p->username() ]); } if ($p || !$this->verifyCertificate()) { $ssl = ['allow_self_signed' => true, 'verify_peer' => false]; /** @var array(string => bool) $ssl */ if ($p) { // 2019-01-14 It is needed for my proxy: https://stackoverflow.com/a/32047219 $ssl['verify_peer_name'] = false; } $a->setStreamContext(['ssl' => $ssl]); } $r->setAdapter($a); return $r; }
[ "private", "function", "setup", "(", "array", "$", "config", ")", "{", "$", "r", "=", "new", "C", "(", "null", ",", "$", "config", "+", "[", "'timeout'", "=>", "120", "/**\n\t\t\t * 2017-07-16\n\t\t\t * By default it is «Zend_Http_Client»: @see C::$config\n\t\t\t * ht...
2019-01-14 @used-by __construct() @param array(string => mixed) $config @return C
[ "2019", "-", "01", "-", "14" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/API/Client.php#L440-L475
43,002
mage2pro/core
Core/T/lib/url.php
url.t01
function t01() { print_r(df_url_trim_index('https://mage2.pro/sandbox/dfe-paymill/index/index/') . "\n"); print_r(df_url_trim_index('https://mage2.pro/sandbox/dfe-paymill/index/index') . "\n"); print_r(df_url_trim_index('https://mage2.pro/sandbox/dfe-paymill/index/') . "\n"); print_r(df_url_trim_index('https://mage2.pro/sandbox/dfe-paymill/index') . "\n"); print_r(df_url_trim_index('https://mage2.pro/sandbox/dfe-paymill/') . "\n"); print_r(df_url_trim_index('https://mage2.pro/sandbox/dfe-paymill') . "\n"); print_r(df_url_trim_index('https://mage2.pro') . "\n"); print_r(df_url_trim_index('/sandbox/dfe-paymill/index/index/') . "\n"); }
php
function t01() { print_r(df_url_trim_index('https://mage2.pro/sandbox/dfe-paymill/index/index/') . "\n"); print_r(df_url_trim_index('https://mage2.pro/sandbox/dfe-paymill/index/index') . "\n"); print_r(df_url_trim_index('https://mage2.pro/sandbox/dfe-paymill/index/') . "\n"); print_r(df_url_trim_index('https://mage2.pro/sandbox/dfe-paymill/index') . "\n"); print_r(df_url_trim_index('https://mage2.pro/sandbox/dfe-paymill/') . "\n"); print_r(df_url_trim_index('https://mage2.pro/sandbox/dfe-paymill') . "\n"); print_r(df_url_trim_index('https://mage2.pro') . "\n"); print_r(df_url_trim_index('/sandbox/dfe-paymill/index/index/') . "\n"); }
[ "function", "t01", "(", ")", "{", "print_r", "(", "df_url_trim_index", "(", "'https://mage2.pro/sandbox/dfe-paymill/index/index/'", ")", ".", "\"\\n\"", ")", ";", "print_r", "(", "df_url_trim_index", "(", "'https://mage2.pro/sandbox/dfe-paymill/index/index'", ")", ".", "\...
2017-02-13
[ "2017", "-", "02", "-", "13" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Core/T/lib/url.php#L9-L18
43,003
mage2pro/core
Framework/Form/Element/Multiselect.php
Multiselect.getElementHtml
function getElementHtml() { /** @var string $r */ if (!$this->ordered()) { $r = parent::getElementHtml(); } else { $r = ''; $this->addClass('select multiselect admin__control-multiselect'); if ($this->getCanBeEmpty()) { $r .= '<input type="hidden" name="' . parent::getName() . '" value="" />'; } $r .= '<select id="' . $this->getHtmlId() . '" name="' . $this->getName() . '" ' . $this->serialize($this->getHtmlAttributes()) . $this->_getUiId() . ' multiple="multiple">' . "\n" ; $selectedA = $this->getValue(); if (!is_array($selectedA)) { $selectedA = explode(',', $selectedA); } if ($options = $this->getValues()) { // 2017-09-23 BEGIN PATCH $options = df_map_r(function(array $o) {return [ is_array($o['value']) ? df_uid() : $o['value'], $o ];}, $options); $prepend = []; /** @var array $prepend */ foreach ($selectedA as $selectedI) { /** @var string $selectedI */ if (isset($options[$selectedI])) { $prepend[]= $options[$selectedI]; unset($options[$selectedI]); } } $options = array_merge($prepend, $options); // 2017-09-23 END PATCH foreach ($options as $option) { if (is_array($option['value'])) { $r .= '<optgroup label="' . $option['label'] . '">' . "\n"; foreach ($option['value'] as $groupItem) { $r .= $this->_optionToHtml($groupItem, $selectedA); } $r .= '</optgroup>' . "\n"; } else { $r .= $this->_optionToHtml($option, $selectedA); } } } $r .= '</select>' . "\n"; $r .= $this->getAfterElementHtml(); } return $r; }
php
function getElementHtml() { /** @var string $r */ if (!$this->ordered()) { $r = parent::getElementHtml(); } else { $r = ''; $this->addClass('select multiselect admin__control-multiselect'); if ($this->getCanBeEmpty()) { $r .= '<input type="hidden" name="' . parent::getName() . '" value="" />'; } $r .= '<select id="' . $this->getHtmlId() . '" name="' . $this->getName() . '" ' . $this->serialize($this->getHtmlAttributes()) . $this->_getUiId() . ' multiple="multiple">' . "\n" ; $selectedA = $this->getValue(); if (!is_array($selectedA)) { $selectedA = explode(',', $selectedA); } if ($options = $this->getValues()) { // 2017-09-23 BEGIN PATCH $options = df_map_r(function(array $o) {return [ is_array($o['value']) ? df_uid() : $o['value'], $o ];}, $options); $prepend = []; /** @var array $prepend */ foreach ($selectedA as $selectedI) { /** @var string $selectedI */ if (isset($options[$selectedI])) { $prepend[]= $options[$selectedI]; unset($options[$selectedI]); } } $options = array_merge($prepend, $options); // 2017-09-23 END PATCH foreach ($options as $option) { if (is_array($option['value'])) { $r .= '<optgroup label="' . $option['label'] . '">' . "\n"; foreach ($option['value'] as $groupItem) { $r .= $this->_optionToHtml($groupItem, $selectedA); } $r .= '</optgroup>' . "\n"; } else { $r .= $this->_optionToHtml($option, $selectedA); } } } $r .= '</select>' . "\n"; $r .= $this->getAfterElementHtml(); } return $r; }
[ "function", "getElementHtml", "(", ")", "{", "/** @var string $r */", "if", "(", "!", "$", "this", "->", "ordered", "(", ")", ")", "{", "$", "r", "=", "parent", "::", "getElementHtml", "(", ")", ";", "}", "else", "{", "$", "r", "=", "''", ";", "$",...
2017-09-23 @override @see _Multiselect::getElementHtml() @used-by \Magento\Config\Block\System\Config\Form\Field::_getElementHtml() protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element) { return $element->getElementHtml(); } https://github.com/magento/magento2/blob/2.2.0/app/code/Magento/Config/Block/System/Config/Form/Field.php#L21-L30 @return string
[ "2017", "-", "09", "-", "23" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Framework/Form/Element/Multiselect.php#L24-L75
43,004
mage2pro/core
Framework/Plugin/Reflection/DataObjectProcessor.php
DataObjectProcessor.aroundBuildOutputDataArray
function aroundBuildOutputDataArray(Sb $sb, \Closure $f, $object, $type) { $result = $f($object, $type); /** @var array(string => mixed) $result */ if ($object instanceof DC) { $result += df_clean([Schema::F__DF => df_api_object_get($object, Schema::F__DF)]); } return $result; }
php
function aroundBuildOutputDataArray(Sb $sb, \Closure $f, $object, $type) { $result = $f($object, $type); /** @var array(string => mixed) $result */ if ($object instanceof DC) { $result += df_clean([Schema::F__DF => df_api_object_get($object, Schema::F__DF)]); } return $result; }
[ "function", "aroundBuildOutputDataArray", "(", "Sb", "$", "sb", ",", "\\", "Closure", "$", "f", ",", "$", "object", ",", "$", "type", ")", "{", "$", "result", "=", "$", "f", "(", "$", "object", ",", "$", "type", ")", ";", "/** @var array(string => mixe...
2017-05-22 @see \Magento\Framework\Reflection\DataObjectProcessor::buildOutputDataArray() @param Sb $sb @param \Closure $f @param object|DC $object @param string $type @return array(string => mixed)
[ "2017", "-", "05", "-", "22" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Framework/Plugin/Reflection/DataObjectProcessor.php#L17-L23
43,005
mage2pro/core
API/Settings.php
Settings.key
private function key($method, $type, $alt, $s = null, $throw = true) {return $this->$method("{$type}Key", $s, function() use($method, $alt, $s) {return $this->$method("{$alt}Key", $s);} ) ?: ($throw ? df_error("Please set your {$this->titleB()} $type key in the Magento backend.") : null) ;}
php
private function key($method, $type, $alt, $s = null, $throw = true) {return $this->$method("{$type}Key", $s, function() use($method, $alt, $s) {return $this->$method("{$alt}Key", $s);} ) ?: ($throw ? df_error("Please set your {$this->titleB()} $type key in the Magento backend.") : null) ;}
[ "private", "function", "key", "(", "$", "method", ",", "$", "type", ",", "$", "alt", ",", "$", "s", "=", "null", ",", "$", "throw", "=", "true", ")", "{", "return", "$", "this", "->", "$", "method", "(", "\"{$type}Key\"", ",", "$", "s", ",", "f...
2017-02-08 @used-by privateKey() @used-by publicKey() @uses testable() @uses testableP() @param string $method @param string $type @param string $alt @param null|string|int|S|Store $s [optional] @param bool $throw [optional] @return string|null @throws DFE
[ "2017", "-", "02", "-", "08" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/API/Settings.php#L193-L197
43,006
mage2pro/core
Framework/Config/Dom.php
Dom.validate
function validate($schemaFileName, &$errors = []) { parent::validate($schemaFileName, $errors); $errors = array_filter($errors, function($message) { /** @var string $message */ // 2015-11-15 // Не отключаем валидацию составного файла полностью, // а лишь убираем их диагностического отчёта сообщения о сбоях в наших полях. return // 2015-11-15 // «Element 'dfSample': This element is not expected. Line: 55» // https://github.com/mage2pro/core/tree/57607cc23405c3dcde50999d063b2a7f49499260/Config/etc/system_file.xsd#L207 !df_contains($message, 'Element \'df') // 2015-12-29 // https://github.com/mage2pro/core/tree/57607cc23405c3dcde50999d063b2a7f49499260/Config/etc/system_file.xsd#L70 // «Element 'field', attribute 'dfItemFormElement': The attribute 'dfItemFormElement' is not allowed.» && !df_contains($message, 'attribute \'df') ; }); return !$errors; }
php
function validate($schemaFileName, &$errors = []) { parent::validate($schemaFileName, $errors); $errors = array_filter($errors, function($message) { /** @var string $message */ // 2015-11-15 // Не отключаем валидацию составного файла полностью, // а лишь убираем их диагностического отчёта сообщения о сбоях в наших полях. return // 2015-11-15 // «Element 'dfSample': This element is not expected. Line: 55» // https://github.com/mage2pro/core/tree/57607cc23405c3dcde50999d063b2a7f49499260/Config/etc/system_file.xsd#L207 !df_contains($message, 'Element \'df') // 2015-12-29 // https://github.com/mage2pro/core/tree/57607cc23405c3dcde50999d063b2a7f49499260/Config/etc/system_file.xsd#L70 // «Element 'field', attribute 'dfItemFormElement': The attribute 'dfItemFormElement' is not allowed.» && !df_contains($message, 'attribute \'df') ; }); return !$errors; }
[ "function", "validate", "(", "$", "schemaFileName", ",", "&", "$", "errors", "=", "[", "]", ")", "{", "parent", "::", "validate", "(", "$", "schemaFileName", ",", "$", "errors", ")", ";", "$", "errors", "=", "array_filter", "(", "$", "errors", ",", "...
2015-11-15 @override @see \Magento\Framework\Config\Dom::validate() @param string $schemaFileName @param array $errors @return bool @throws \Exception
[ "2015", "-", "11", "-", "15" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Framework/Config/Dom.php#L28-L47
43,007
mage2pro/core
Payment/W/F.php
F.aspect
private function aspect($base, ...$a) {return dfc($this, function($base, ...$a) {return df_newa($this->c(df_class_l($base)), $base, ...$a) ;}, func_get_args());}
php
private function aspect($base, ...$a) {return dfc($this, function($base, ...$a) {return df_newa($this->c(df_class_l($base)), $base, ...$a) ;}, func_get_args());}
[ "private", "function", "aspect", "(", "$", "base", ",", "...", "$", "a", ")", "{", "return", "dfc", "(", "$", "this", ",", "function", "(", "$", "base", ",", "...", "$", "a", ")", "{", "return", "df_newa", "(", "$", "this", "->", "c", "(", "df_...
2017-03-15 @used-by event() @used-by handler() @param string $base @param mixed[] ...$a @return object @throws Critical|Ignored
[ "2017", "-", "03", "-", "15" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Payment/W/F.php#L101-L103
43,008
mage2pro/core
Payment/W/F.php
F.s
final static function s($m, $req = null) {return dfcf(function(M $m, $req = null) { $c = df_con_hier($m, self::class); /** @var string $c */ return new $c($m, $req); }, [dfpm($m), $req]);}
php
final static function s($m, $req = null) {return dfcf(function(M $m, $req = null) { $c = df_con_hier($m, self::class); /** @var string $c */ return new $c($m, $req); }, [dfpm($m), $req]);}
[ "final", "static", "function", "s", "(", "$", "m", ",", "$", "req", "=", "null", ")", "{", "return", "dfcf", "(", "function", "(", "M", "$", "m", ",", "$", "req", "=", "null", ")", "{", "$", "c", "=", "df_con_hier", "(", "$", "m", ",", "self"...
2017-03-13 @used-by \Df\Payment\W\Action::execute() @used-by \Df\Payment\TM::responses() @used-by \Dfe\SecurePay\Signer\Response::values() @param string|object $m @param array(string => mixed)|null $req [optional] @return self @throws Critical|Ignored
[ "2017", "-", "03", "-", "13" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Payment/W/F.php#L202-L205
43,009
mage2pro/core
OAuth/FE/Button.php
Button.getCommentText
function getCommentText($v) {return (string)__($this->s()->authenticatedB() ? "<b>Your Magento instance is <span class='df-ok'>successfully authenticated</span> to your %1 instance.</b>" : "<b>You <span class='df-warning'>need to authenticate</span> your Magento instance to your %1 instance.</b>" ,df_api_name($this->m()));}
php
function getCommentText($v) {return (string)__($this->s()->authenticatedB() ? "<b>Your Magento instance is <span class='df-ok'>successfully authenticated</span> to your %1 instance.</b>" : "<b>You <span class='df-warning'>need to authenticate</span> your Magento instance to your %1 instance.</b>" ,df_api_name($this->m()));}
[ "function", "getCommentText", "(", "$", "v", ")", "{", "return", "(", "string", ")", "__", "(", "$", "this", "->", "s", "(", ")", "->", "authenticatedB", "(", ")", "?", "\"<b>Your Magento instance is <span class='df-ok'>successfully authenticated</span> to your %1 ins...
2017-06-29 @final Unable to use the PHP «final» keyword here because of the M2 code generation. «How to implement a dynamically generated comment for a backend configuration field?» https://mage2.pro/t/4076 @override @see IComment::getCommentText() @used-by \Magento\Config\Model\Config\Structure\Element\Field::getComment(): public function getComment($currentValue = '') { $comment = ''; if (isset($this->_data['comment']) && $this->_data['comment']) { if (is_array($this->_data['comment'])) { if (isset($this->_data['comment']['model'])) { $model = $this->_commentFactory->create($this->_data['comment']['model']); $comment = $model->getCommentText($currentValue); } } else { $comment = parent::getComment(); } } return $comment; } https://github.com/magento/magento2/blob/2.2.0-RC1.8/app/code/Magento/Config/Model/Config/Structure/Element/Field.php#L106-L126 @param string $v @return string
[ "2017", "-", "06", "-", "29" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/OAuth/FE/Button.php#L42-L45
43,010
mage2pro/core
Sales/Block/Order/Total.php
Total.addBefore
final protected function addBefore($code, $label, $value, $valueBase, $before = null) {$this->add( 'addTotalBefore', $code, $label, $value, $valueBase, $before );}
php
final protected function addBefore($code, $label, $value, $valueBase, $before = null) {$this->add( 'addTotalBefore', $code, $label, $value, $valueBase, $before );}
[ "final", "protected", "function", "addBefore", "(", "$", "code", ",", "$", "label", ",", "$", "value", ",", "$", "valueBase", ",", "$", "before", "=", "null", ")", "{", "$", "this", "->", "add", "(", "'addTotalBefore'", ",", "$", "code", ",", "$", ...
2016-08-14 Add new total to totals array before specific total or after first total by default. @used-by \Dfe\AllPay\Block\Total::initTotals() @uses \Magento\Sales\Block\Order\Totals::addTotalBefore() @param string $code @param string $label @param float $value @param float $valueBase @param string|null $before [optional]
[ "2016", "-", "08", "-", "14", "Add", "new", "total", "to", "totals", "array", "before", "specific", "total", "or", "after", "first", "total", "by", "default", "." ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sales/Block/Order/Total.php#L45-L47
43,011
mage2pro/core
StripeClone/Facade/Card.php
Card.isActive
final function isActive() {return /** @var int $y1 */ /** @var int $y2 */ ($y1 = df_year()) < ($y2 = $this->expYear()) || ($y1 === $y2 && df_month() <= $this->expMonth()) ;}
php
final function isActive() {return /** @var int $y1 */ /** @var int $y2 */ ($y1 = df_year()) < ($y2 = $this->expYear()) || ($y1 === $y2 && df_month() <= $this->expMonth()) ;}
[ "final", "function", "isActive", "(", ")", "{", "return", "/** @var int $y1 */", "/** @var int $y2 */", "(", "$", "y1", "=", "df_year", "(", ")", ")", "<", "(", "$", "y2", "=", "$", "this", "->", "expYear", "(", ")", ")", "||", "(", "$", "y1", "===",...
2018-11-13 @used-by \Df\StripeClone\Facade\Customer::cardsActive() @return bool
[ "2018", "-", "11", "-", "13" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/StripeClone/Facade/Card.php#L97-L99
43,012
mage2pro/core
Core/T/lib/date.php
date.t03
function t03() { $d = ZD::now(); /** @var ZD $d */ /** * 2017-09-05 * Эта операция конвертирует время из пояса @see date_default_timezone_get() в пояс аргумента. * Пример: * $dateS = «2016/07/28 11:35:03», * date_default_timezone_get() = «Asia/Taipei» * пояс аргумента = «Europe/Moscow» * $result->toString() = 'Jul 28, 2016 6:35:03 AM' */ $d->setTimezone('Europe/Moscow'); $d->addDay(45); print_r($d->toString('y-MM-ddTHH:mm:ss')); }
php
function t03() { $d = ZD::now(); /** @var ZD $d */ /** * 2017-09-05 * Эта операция конвертирует время из пояса @see date_default_timezone_get() в пояс аргумента. * Пример: * $dateS = «2016/07/28 11:35:03», * date_default_timezone_get() = «Asia/Taipei» * пояс аргумента = «Europe/Moscow» * $result->toString() = 'Jul 28, 2016 6:35:03 AM' */ $d->setTimezone('Europe/Moscow'); $d->addDay(45); print_r($d->toString('y-MM-ddTHH:mm:ss')); }
[ "function", "t03", "(", ")", "{", "$", "d", "=", "ZD", "::", "now", "(", ")", ";", "/** @var ZD $d */", "/**\n\t\t * 2017-09-05\n\t\t * Эта операция конвертирует время из пояса @see date_default_timezone_get() в пояс аргумента.\n\t\t * Пример:\n\t\t * $dateS = «2016/07/28 11:35:03»,\n\...
2017-09-05
[ "2017", "-", "09", "-", "05" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Core/T/lib/date.php#L20-L34
43,013
mage2pro/core
Zf/Validate/Between.php
Between.i
static function i($min, $max = null, $inclusive = true) {return new self( is_null($min) ? PHP_INT_MIN : $min, is_null($max) ? PHP_INT_MAX : $max, $inclusive );}
php
static function i($min, $max = null, $inclusive = true) {return new self( is_null($min) ? PHP_INT_MIN : $min, is_null($max) ? PHP_INT_MAX : $max, $inclusive );}
[ "static", "function", "i", "(", "$", "min", ",", "$", "max", "=", "null", ",", "$", "inclusive", "=", "true", ")", "{", "return", "new", "self", "(", "is_null", "(", "$", "min", ")", "?", "PHP_INT_MIN", ":", "$", "min", ",", "is_null", "(", "$", ...
2017-01-14 @used-by \Df\Qa\Method::assertParamIsBetween() @used-by \Df\Qa\Method::assertResultIsBetween() @used-by \Df\Qa\Method::assertValueIsBetween() @param int|float|null $min @param int|float|null $max [optional] @param bool $inclusive [optional] @return self
[ "2017", "-", "01", "-", "14" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Zf/Validate/Between.php#L14-L16
43,014
mage2pro/core
Framework/Module/Dir/Reader.php
Reader.getComposerJsonFiles
function getComposerJsonFiles() {$r = parent::getComposerJsonFiles(); /** @var I $r */return dfI::pathsSet($r, array_filter(dfI::pathsGet($r), function($f) {return '/composer.json' !== $f;})) ;}
php
function getComposerJsonFiles() {$r = parent::getComposerJsonFiles(); /** @var I $r */return dfI::pathsSet($r, array_filter(dfI::pathsGet($r), function($f) {return '/composer.json' !== $f;})) ;}
[ "function", "getComposerJsonFiles", "(", ")", "{", "$", "r", "=", "parent", "::", "getComposerJsonFiles", "(", ")", ";", "/** @var I $r */", "return", "dfI", "::", "pathsSet", "(", "$", "r", ",", "array_filter", "(", "dfI", "::", "pathsGet", "(", "$", "r",...
2017-07-26 @final Unable to use the PHP «final» keyword here because of the M2 code generation. @override @see \Magento\Framework\Module\Dir\Reader::getComposerJsonFiles(): public function getComposerJsonFiles() { return $this->getFilesIterator('composer.json'); } https://github.com/magento/magento2/blob/2.2.0-RC1.8/lib/internal/Magento/Framework/Module/Dir/Reader.php#L89-L97 @used-by \Magento\Framework\Module\PackageInfo::load(): $jsonData = $this->reader->getComposerJsonFiles()->toArray(); https://github.com/magento/magento2/blob/2.2.0-RC1.8/lib/internal/Magento/Framework/Module/PackageInfo.php#L73-L114 @return I
[ "2017", "-", "07", "-", "26" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Framework/Module/Dir/Reader.php#L53-L55
43,015
mage2pro/core
Sentry/SanitizeDataProcessor.php
SanitizeDataProcessor.setProcessorOptions
function setProcessorOptions(array $options) { if (isset($options['fields_re'])) { $this->fields_re = $options['fields_re']; } if (isset($options['values_re'])) { $this->values_re = $options['values_re']; } }
php
function setProcessorOptions(array $options) { if (isset($options['fields_re'])) { $this->fields_re = $options['fields_re']; } if (isset($options['values_re'])) { $this->values_re = $options['values_re']; } }
[ "function", "setProcessorOptions", "(", "array", "$", "options", ")", "{", "if", "(", "isset", "(", "$", "options", "[", "'fields_re'", "]", ")", ")", "{", "$", "this", "->", "fields_re", "=", "$", "options", "[", "'fields_re'", "]", ";", "}", "if", ...
Override the default processor options @param array $options Associative array of processor options
[ "Override", "the", "default", "processor", "options" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/SanitizeDataProcessor.php#L32-L41
43,016
mage2pro/core
Sentry/SanitizeDataProcessor.php
SanitizeDataProcessor.sanitize
function sanitize(&$item, $key) { if (empty($item)) { return; } if (preg_match($this->values_re, $item)) { $item = self::MASK; } if (empty($key)) { return; } if (preg_match($this->fields_re, $key)) { $item = self::MASK; } }
php
function sanitize(&$item, $key) { if (empty($item)) { return; } if (preg_match($this->values_re, $item)) { $item = self::MASK; } if (empty($key)) { return; } if (preg_match($this->fields_re, $key)) { $item = self::MASK; } }
[ "function", "sanitize", "(", "&", "$", "item", ",", "$", "key", ")", "{", "if", "(", "empty", "(", "$", "item", ")", ")", "{", "return", ";", "}", "if", "(", "preg_match", "(", "$", "this", "->", "values_re", ",", "$", "item", ")", ")", "{", ...
Replace any array values with our mask if the field name or the value matches a respective regex @param mixed $item Associative array value @param string $key Associative array key
[ "Replace", "any", "array", "values", "with", "our", "mask", "if", "the", "field", "name", "or", "the", "value", "matches", "a", "respective", "regex" ]
e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f
https://github.com/mage2pro/core/blob/e04c31bb8a91376df2c2c8a9b29dbad5e8f0cc3f/Sentry/SanitizeDataProcessor.php#L49-L66
43,017
CMB2/cmb2-attached-posts
init.php
WDS_CMB2_Attached_Posts_Field.list_item
public function list_item( $object, $li_class, $icon_class = 'dashicons-plus' ) { // Build our list item printf( '<li data-id="%1$d" class="%2$s" target="_blank">%3$s<a title="' . __( 'Edit' ) . '" href="%4$s">%5$s</a>%6$s<span class="dashicons %7$s add-remove"></span></li>', $this->get_id( $object ), $li_class, $this->get_thumb( $object ), $this->get_edit_link( $object ), $this->get_title( $object ), $this->get_object_label( $object ), $icon_class ); }
php
public function list_item( $object, $li_class, $icon_class = 'dashicons-plus' ) { // Build our list item printf( '<li data-id="%1$d" class="%2$s" target="_blank">%3$s<a title="' . __( 'Edit' ) . '" href="%4$s">%5$s</a>%6$s<span class="dashicons %7$s add-remove"></span></li>', $this->get_id( $object ), $li_class, $this->get_thumb( $object ), $this->get_edit_link( $object ), $this->get_title( $object ), $this->get_object_label( $object ), $icon_class ); }
[ "public", "function", "list_item", "(", "$", "object", ",", "$", "li_class", ",", "$", "icon_class", "=", "'dashicons-plus'", ")", "{", "// Build our list item", "printf", "(", "'<li data-id=\"%1$d\" class=\"%2$s\" target=\"_blank\">%3$s<a title=\"'", ".", "__", "(", "'...
Outputs a column list item. @since 1.2.5 @param mixed $object Post or User. @param string $li_class The list item (zebra) class. @param string $icon_class The icon class. Either 'dashicons-plus' or 'dashicons-minus'. @return void
[ "Outputs", "a", "column", "list", "item", "." ]
556701d8f032931838c524ddc55c40b177a0e1a8
https://github.com/CMB2/cmb2-attached-posts/blob/556701d8f032931838c524ddc55c40b177a0e1a8/init.php#L287-L299
43,018
CMB2/cmb2-attached-posts
init.php
WDS_CMB2_Attached_Posts_Field.get_thumb
public function get_thumb( $object ) { $thumbnail = ''; if ( $this->field->options( 'show_thumbnails' ) ) { // Set thumbnail if the options is true $thumbnail = $this->field->options( 'query_users' ) ? get_avatar( $object->ID, 25 ) : get_the_post_thumbnail( $object->ID, array( 50, 50 ) ); } return $thumbnail; }
php
public function get_thumb( $object ) { $thumbnail = ''; if ( $this->field->options( 'show_thumbnails' ) ) { // Set thumbnail if the options is true $thumbnail = $this->field->options( 'query_users' ) ? get_avatar( $object->ID, 25 ) : get_the_post_thumbnail( $object->ID, array( 50, 50 ) ); } return $thumbnail; }
[ "public", "function", "get_thumb", "(", "$", "object", ")", "{", "$", "thumbnail", "=", "''", ";", "if", "(", "$", "this", "->", "field", "->", "options", "(", "'show_thumbnails'", ")", ")", "{", "// Set thumbnail if the options is true", "$", "thumbnail", "...
Get thumbnail for the object. @since 1.2.4 @param mixed $object Post or User @return string The thumbnail, if endabled/found.
[ "Get", "thumbnail", "for", "the", "object", "." ]
556701d8f032931838c524ddc55c40b177a0e1a8
https://github.com/CMB2/cmb2-attached-posts/blob/556701d8f032931838c524ddc55c40b177a0e1a8/init.php#L310-L321
43,019
CMB2/cmb2-attached-posts
init.php
WDS_CMB2_Attached_Posts_Field.get_title
public function get_title( $object ) { return $this->field->options( 'query_users' ) ? $object->data->display_name : get_the_title( $object ); }
php
public function get_title( $object ) { return $this->field->options( 'query_users' ) ? $object->data->display_name : get_the_title( $object ); }
[ "public", "function", "get_title", "(", "$", "object", ")", "{", "return", "$", "this", "->", "field", "->", "options", "(", "'query_users'", ")", "?", "$", "object", "->", "data", "->", "display_name", ":", "get_the_title", "(", "$", "object", ")", ";",...
Get title for the object. @since 1.2.4 @param mixed $object Post or User @return string The object title.
[ "Get", "title", "for", "the", "object", "." ]
556701d8f032931838c524ddc55c40b177a0e1a8
https://github.com/CMB2/cmb2-attached-posts/blob/556701d8f032931838c524ddc55c40b177a0e1a8/init.php#L345-L349
43,020
CMB2/cmb2-attached-posts
init.php
WDS_CMB2_Attached_Posts_Field.get_object_label
public function get_object_label( $object ) { if ( ! $this->do_type_label ) { return ''; } $post_type_obj = get_post_type_object( $object->post_type ); $label = isset( $post_type_obj->labels->singular_name ) ? $post_type_obj->labels->singular_name : $post_type_obj->label; return ' &mdash; <span class="object-label">'. $label .'</span>'; }
php
public function get_object_label( $object ) { if ( ! $this->do_type_label ) { return ''; } $post_type_obj = get_post_type_object( $object->post_type ); $label = isset( $post_type_obj->labels->singular_name ) ? $post_type_obj->labels->singular_name : $post_type_obj->label; return ' &mdash; <span class="object-label">'. $label .'</span>'; }
[ "public", "function", "get_object_label", "(", "$", "object", ")", "{", "if", "(", "!", "$", "this", "->", "do_type_label", ")", "{", "return", "''", ";", "}", "$", "post_type_obj", "=", "get_post_type_object", "(", "$", "object", "->", "post_type", ")", ...
Get object label. @since 1.2.6 @param mixed $object Post or User @return string The object label.
[ "Get", "object", "label", "." ]
556701d8f032931838c524ddc55c40b177a0e1a8
https://github.com/CMB2/cmb2-attached-posts/blob/556701d8f032931838c524ddc55c40b177a0e1a8/init.php#L360-L369
43,021
CMB2/cmb2-attached-posts
init.php
WDS_CMB2_Attached_Posts_Field.get_edit_link
public function get_edit_link( $object ) { return $this->field->options( 'query_users' ) ? get_edit_user_link( $object->ID ) : get_edit_post_link( $object ); }
php
public function get_edit_link( $object ) { return $this->field->options( 'query_users' ) ? get_edit_user_link( $object->ID ) : get_edit_post_link( $object ); }
[ "public", "function", "get_edit_link", "(", "$", "object", ")", "{", "return", "$", "this", "->", "field", "->", "options", "(", "'query_users'", ")", "?", "get_edit_user_link", "(", "$", "object", "->", "ID", ")", ":", "get_edit_post_link", "(", "$", "obj...
Get edit link for the object. @since 1.2.4 @param mixed $object Post or User @return string The object edit link.
[ "Get", "edit", "link", "for", "the", "object", "." ]
556701d8f032931838c524ddc55c40b177a0e1a8
https://github.com/CMB2/cmb2-attached-posts/blob/556701d8f032931838c524ddc55c40b177a0e1a8/init.php#L380-L384
43,022
CMB2/cmb2-attached-posts
init.php
WDS_CMB2_Attached_Posts_Field.get_object
public function get_object( $id ) { return $this->field->options( 'query_users' ) ? get_user_by( 'id', absint( $id ) ) : get_post( absint( $id ) ); }
php
public function get_object( $id ) { return $this->field->options( 'query_users' ) ? get_user_by( 'id', absint( $id ) ) : get_post( absint( $id ) ); }
[ "public", "function", "get_object", "(", "$", "id", ")", "{", "return", "$", "this", "->", "field", "->", "options", "(", "'query_users'", ")", "?", "get_user_by", "(", "'id'", ",", "absint", "(", "$", "id", ")", ")", ":", "get_post", "(", "absint", ...
Get object by id. @since 1.2.4 @param int $id Post or User ID. @return mixed Post or User if found.
[ "Get", "object", "by", "id", "." ]
556701d8f032931838c524ddc55c40b177a0e1a8
https://github.com/CMB2/cmb2-attached-posts/blob/556701d8f032931838c524ddc55c40b177a0e1a8/init.php#L395-L399
43,023
CMB2/cmb2-attached-posts
init.php
WDS_CMB2_Attached_Posts_Field.get_all_objects
public function get_all_objects( $args, $attached = array() ) { $objects = $this->get_objects( $args ); $attached_objects = array(); foreach ( $objects as $object ) { $attached_objects[ $this->get_id( $object ) ] = $object; } if ( ! empty( $attached ) ) { $is_users = $this->field->options( 'query_users' ); $args[ $is_users ? 'include' : 'post__in' ] = $attached; $args[ $is_users ? 'number' : 'posts_per_page' ] = count( $attached ); $new = $this->get_objects( $args ); foreach ( $new as $object ) { if ( ! isset( $attached_objects[ $this->get_id( $object ) ] ) ) { $attached_objects[ $this->get_id( $object ) ] = $object; } } } return $attached_objects; }
php
public function get_all_objects( $args, $attached = array() ) { $objects = $this->get_objects( $args ); $attached_objects = array(); foreach ( $objects as $object ) { $attached_objects[ $this->get_id( $object ) ] = $object; } if ( ! empty( $attached ) ) { $is_users = $this->field->options( 'query_users' ); $args[ $is_users ? 'include' : 'post__in' ] = $attached; $args[ $is_users ? 'number' : 'posts_per_page' ] = count( $attached ); $new = $this->get_objects( $args ); foreach ( $new as $object ) { if ( ! isset( $attached_objects[ $this->get_id( $object ) ] ) ) { $attached_objects[ $this->get_id( $object ) ] = $object; } } } return $attached_objects; }
[ "public", "function", "get_all_objects", "(", "$", "args", ",", "$", "attached", "=", "array", "(", ")", ")", "{", "$", "objects", "=", "$", "this", "->", "get_objects", "(", "$", "args", ")", ";", "$", "attached_objects", "=", "array", "(", ")", ";"...
Fetches the default query for items, and combines with any objects attached. @since 1.2.4 @param array $args Array of query args. @param array $attached Array of attached object ids. @return array Array of attached object ids.
[ "Fetches", "the", "default", "query", "for", "items", "and", "combines", "with", "any", "objects", "attached", "." ]
556701d8f032931838c524ddc55c40b177a0e1a8
https://github.com/CMB2/cmb2-attached-posts/blob/556701d8f032931838c524ddc55c40b177a0e1a8/init.php#L411-L434
43,024
CMB2/cmb2-attached-posts
init.php
WDS_CMB2_Attached_Posts_Field.setup_scripts
protected static function setup_scripts() { static $once = false; $dir = CMB2_ATTACHED_POSTS_FIELD_DIR; if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) ) { // Windows $content_dir = str_replace( '/', DIRECTORY_SEPARATOR, WP_CONTENT_DIR ); $content_url = str_replace( $content_dir, WP_CONTENT_URL, $dir ); $url = str_replace( DIRECTORY_SEPARATOR, '/', $content_url ); } else { $url = str_replace( array( WP_CONTENT_DIR, WP_PLUGIN_DIR ), array( WP_CONTENT_URL, WP_PLUGIN_URL ), $dir ); } $url = set_url_scheme( $url ); $url = apply_filters( 'cmb2_attached_posts_field_assets_url', $url ); $requirements = array( 'jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-mouse', 'jquery-ui-draggable', 'jquery-ui-droppable', 'jquery-ui-sortable', 'wp-backbone', ); wp_enqueue_script( 'cmb2-attached-posts-field', $url . 'js/attached-posts.js', $requirements, self::VERSION, true ); wp_enqueue_style( 'cmb2-attached-posts-field', $url . 'css/attached-posts-admin.css', array(), self::VERSION ); if ( ! $once ) { wp_localize_script( 'cmb2-attached-posts-field', 'CMBAP', array( 'edit_link_template' => str_replace( get_the_ID(), 'REPLACEME', get_edit_post_link( get_the_ID() ) ), 'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ), ) ); $once = true; } }
php
protected static function setup_scripts() { static $once = false; $dir = CMB2_ATTACHED_POSTS_FIELD_DIR; if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) ) { // Windows $content_dir = str_replace( '/', DIRECTORY_SEPARATOR, WP_CONTENT_DIR ); $content_url = str_replace( $content_dir, WP_CONTENT_URL, $dir ); $url = str_replace( DIRECTORY_SEPARATOR, '/', $content_url ); } else { $url = str_replace( array( WP_CONTENT_DIR, WP_PLUGIN_DIR ), array( WP_CONTENT_URL, WP_PLUGIN_URL ), $dir ); } $url = set_url_scheme( $url ); $url = apply_filters( 'cmb2_attached_posts_field_assets_url', $url ); $requirements = array( 'jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-mouse', 'jquery-ui-draggable', 'jquery-ui-droppable', 'jquery-ui-sortable', 'wp-backbone', ); wp_enqueue_script( 'cmb2-attached-posts-field', $url . 'js/attached-posts.js', $requirements, self::VERSION, true ); wp_enqueue_style( 'cmb2-attached-posts-field', $url . 'css/attached-posts-admin.css', array(), self::VERSION ); if ( ! $once ) { wp_localize_script( 'cmb2-attached-posts-field', 'CMBAP', array( 'edit_link_template' => str_replace( get_the_ID(), 'REPLACEME', get_edit_post_link( get_the_ID() ) ), 'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ), ) ); $once = true; } }
[ "protected", "static", "function", "setup_scripts", "(", ")", "{", "static", "$", "once", "=", "false", ";", "$", "dir", "=", "CMB2_ATTACHED_POSTS_FIELD_DIR", ";", "if", "(", "'WIN'", "===", "strtoupper", "(", "substr", "(", "PHP_OS", ",", "0", ",", "3", ...
Enqueue admin scripts for our attached posts field
[ "Enqueue", "admin", "scripts", "for", "our", "attached", "posts", "field" ]
556701d8f032931838c524ddc55c40b177a0e1a8
https://github.com/CMB2/cmb2-attached-posts/blob/556701d8f032931838c524ddc55c40b177a0e1a8/init.php#L452-L495
43,025
CMB2/cmb2-attached-posts
init.php
WDS_CMB2_Attached_Posts_Field.ajax_find_posts
public function ajax_find_posts() { if ( defined( 'DOING_AJAX' ) && DOING_AJAX && isset( $_POST['cmb2_attached_search'], $_POST['retrieved'], $_POST['action'], $_POST['search_types'] ) && 'find_posts' == $_POST['action'] && ! empty( $_POST['search_types'] ) ) { // This is not working until we fix the user query bit. if ( ! empty( $_POST['query_users'] ) ) { add_action( 'pre_get_users', array( $this, 'modify_query' ) ); } else { add_action( 'pre_get_posts', array( $this, 'modify_query' ) ); } } }
php
public function ajax_find_posts() { if ( defined( 'DOING_AJAX' ) && DOING_AJAX && isset( $_POST['cmb2_attached_search'], $_POST['retrieved'], $_POST['action'], $_POST['search_types'] ) && 'find_posts' == $_POST['action'] && ! empty( $_POST['search_types'] ) ) { // This is not working until we fix the user query bit. if ( ! empty( $_POST['query_users'] ) ) { add_action( 'pre_get_users', array( $this, 'modify_query' ) ); } else { add_action( 'pre_get_posts', array( $this, 'modify_query' ) ); } } }
[ "public", "function", "ajax_find_posts", "(", ")", "{", "if", "(", "defined", "(", "'DOING_AJAX'", ")", "&&", "DOING_AJAX", "&&", "isset", "(", "$", "_POST", "[", "'cmb2_attached_search'", "]", ",", "$", "_POST", "[", "'retrieved'", "]", ",", "$", "_POST",...
Check to see if we have a post type set and, if so, add the pre_get_posts action to set the queried post type @since 1.2.4 @return void
[ "Check", "to", "see", "if", "we", "have", "a", "post", "type", "set", "and", "if", "so", "add", "the", "pre_get_posts", "action", "to", "set", "the", "queried", "post", "type" ]
556701d8f032931838c524ddc55c40b177a0e1a8
https://github.com/CMB2/cmb2-attached-posts/blob/556701d8f032931838c524ddc55c40b177a0e1a8/init.php#L531-L546
43,026
CMB2/cmb2-attached-posts
init.php
WDS_CMB2_Attached_Posts_Field.modify_query
public function modify_query( $query ) { $is_users = 'pre_get_users' === current_filter(); if ( $is_users ) { // This is not working until we fix the user query bit. } else { $types = $_POST['search_types']; $types = is_array( $types ) ? array_map( 'esc_attr', $types ) : esc_attr( $types ); $query->set( 'post_type', $types ); } if ( ! empty( $_POST['retrieved'] ) && is_array( $_POST['retrieved'] ) ) { // Exclude posts/users already existing. $ids = array_map( 'absint', $_POST['retrieved'] ); if ( ! empty( $_POST['exclude'] ) && is_array( $_POST['exclude'] ) ) { // Exclude the post that we're looking at. $exclude = array_map( 'absint', $_POST['exclude'] ); $ids = array_merge( $ids, $exclude ); } $query->set( $is_users ? 'exclude' : 'post__not_in', $ids ); } $this->maybe_callback( $query, $_POST ); }
php
public function modify_query( $query ) { $is_users = 'pre_get_users' === current_filter(); if ( $is_users ) { // This is not working until we fix the user query bit. } else { $types = $_POST['search_types']; $types = is_array( $types ) ? array_map( 'esc_attr', $types ) : esc_attr( $types ); $query->set( 'post_type', $types ); } if ( ! empty( $_POST['retrieved'] ) && is_array( $_POST['retrieved'] ) ) { // Exclude posts/users already existing. $ids = array_map( 'absint', $_POST['retrieved'] ); if ( ! empty( $_POST['exclude'] ) && is_array( $_POST['exclude'] ) ) { // Exclude the post that we're looking at. $exclude = array_map( 'absint', $_POST['exclude'] ); $ids = array_merge( $ids, $exclude ); } $query->set( $is_users ? 'exclude' : 'post__not_in', $ids ); } $this->maybe_callback( $query, $_POST ); }
[ "public", "function", "modify_query", "(", "$", "query", ")", "{", "$", "is_users", "=", "'pre_get_users'", "===", "current_filter", "(", ")", ";", "if", "(", "$", "is_users", ")", "{", "// This is not working until we fix the user query bit.", "}", "else", "{", ...
Modify the search query. @since 1.2.4 @param WP_Query $query WP_Query instance during the pre_get_posts hook. @return void
[ "Modify", "the", "search", "query", "." ]
556701d8f032931838c524ddc55c40b177a0e1a8
https://github.com/CMB2/cmb2-attached-posts/blob/556701d8f032931838c524ddc55c40b177a0e1a8/init.php#L557-L582
43,027
CMB2/cmb2-attached-posts
init.php
WDS_CMB2_Attached_Posts_Field.maybe_callback
public function maybe_callback( $query, $post_args ) { $cmb = isset( $post_args['cmb_id'] ) ? $post_args['cmb_id'] : ''; $group = isset( $post_args['group_id'] ) ? $post_args['group_id'] : ''; $field = isset( $post_args['field_id'] ) ? $post_args['field_id'] : ''; $cmb = cmb2_get_metabox( $cmb ); if ( $cmb && $group ) { $group = $cmb->get_field( $group ); } if ( $cmb && $field ) { $group = $group ? $group : null; $field = $cmb->get_field( $field, $group ); } if ( $field && ( $cb = $field->maybe_callback( 'attached_posts_search_query_cb' ) ) ) { call_user_func( $cb, $query, $field, $this ); } }
php
public function maybe_callback( $query, $post_args ) { $cmb = isset( $post_args['cmb_id'] ) ? $post_args['cmb_id'] : ''; $group = isset( $post_args['group_id'] ) ? $post_args['group_id'] : ''; $field = isset( $post_args['field_id'] ) ? $post_args['field_id'] : ''; $cmb = cmb2_get_metabox( $cmb ); if ( $cmb && $group ) { $group = $cmb->get_field( $group ); } if ( $cmb && $field ) { $group = $group ? $group : null; $field = $cmb->get_field( $field, $group ); } if ( $field && ( $cb = $field->maybe_callback( 'attached_posts_search_query_cb' ) ) ) { call_user_func( $cb, $query, $field, $this ); } }
[ "public", "function", "maybe_callback", "(", "$", "query", ",", "$", "post_args", ")", "{", "$", "cmb", "=", "isset", "(", "$", "post_args", "[", "'cmb_id'", "]", ")", "?", "$", "post_args", "[", "'cmb_id'", "]", ":", "''", ";", "$", "group", "=", ...
If field has a 'attached_posts_search_query_cb', run the callback. @since 1.2.4 @param WP_Query $query WP_Query instance during the pre_get_posts hook. @param array $post_args The $_POST array. @return void
[ "If", "field", "has", "a", "attached_posts_search_query_cb", "run", "the", "callback", "." ]
556701d8f032931838c524ddc55c40b177a0e1a8
https://github.com/CMB2/cmb2-attached-posts/blob/556701d8f032931838c524ddc55c40b177a0e1a8/init.php#L594-L612
43,028
CMB2/cmb2-attached-posts
init.php
WDS_CMB2_Attached_Posts_Field.display_render
public function display_render( $pre_output, $field, $display ) { if ( ! empty( $pre_output ) ) { return $pre_output; } $return = ''; // If repeatable if ( $display->field->args( 'repeatable' ) ) { $rows = array(); // And has a repeatable value if ( is_array( $display->field->value ) ) { // Then loop and output. foreach ( $display->field->value as $val ) { $rows[] = $this->_display_render( $display->field, $val ); } } if ( ! empty( $rows ) ) { $return .= '<ul class="cmb2-' . str_replace( '_', '-', $display->field->type() ) . '"><li>'; foreach ( (array) $rows as $row ) { $return .= sprintf( '<li>%s</a>', $row ); } $return .= '</ul>'; } else { $return .= '&mdash;'; } } else { $return .= $this->_display_render( $display->field, $display->field->value ); } return $return ? $return : $pre_output; }
php
public function display_render( $pre_output, $field, $display ) { if ( ! empty( $pre_output ) ) { return $pre_output; } $return = ''; // If repeatable if ( $display->field->args( 'repeatable' ) ) { $rows = array(); // And has a repeatable value if ( is_array( $display->field->value ) ) { // Then loop and output. foreach ( $display->field->value as $val ) { $rows[] = $this->_display_render( $display->field, $val ); } } if ( ! empty( $rows ) ) { $return .= '<ul class="cmb2-' . str_replace( '_', '-', $display->field->type() ) . '"><li>'; foreach ( (array) $rows as $row ) { $return .= sprintf( '<li>%s</a>', $row ); } $return .= '</ul>'; } else { $return .= '&mdash;'; } } else { $return .= $this->_display_render( $display->field, $display->field->value ); } return $return ? $return : $pre_output; }
[ "public", "function", "display_render", "(", "$", "pre_output", ",", "$", "field", ",", "$", "display", ")", "{", "if", "(", "!", "empty", "(", "$", "pre_output", ")", ")", "{", "return", "$", "pre_output", ";", "}", "$", "return", "=", "''", ";", ...
Outputs the display of our custom field. @since 1.2.7 @param bool|mixed $pre_output Default null value. @param CMB2_Field $field This field object. @param CMB2_Field_Display $display The `CMB2_Field_Display` object.
[ "Outputs", "the", "display", "of", "our", "custom", "field", "." ]
556701d8f032931838c524ddc55c40b177a0e1a8
https://github.com/CMB2/cmb2-attached-posts/blob/556701d8f032931838c524ddc55c40b177a0e1a8/init.php#L623-L660
43,029
CMB2/cmb2-attached-posts
init.php
WDS_CMB2_Attached_Posts_Field._display_render
public function _display_render( $field, $val ) { $return = ''; $posts = array(); if ( ! empty( $val ) ) { foreach ( (array) $val as $id ) { $title = get_the_title( $id ); if ( $title ) { $edit_link = get_edit_post_link( $id ); $posts[ $id ] = compact( 'title', 'edit_link' ); } } } if ( ! empty( $posts ) ) { $return .= '<ol>'; foreach ( (array) $posts as $id => $post ) { $return .= sprintf( '<li id="attached-%d"><a href="%s">%s</a></li>', $id, $post['edit_link'], $post['title'] ); } $return .= '</ol>'; } else { $return .= '&mdash;'; } return $return; }
php
public function _display_render( $field, $val ) { $return = ''; $posts = array(); if ( ! empty( $val ) ) { foreach ( (array) $val as $id ) { $title = get_the_title( $id ); if ( $title ) { $edit_link = get_edit_post_link( $id ); $posts[ $id ] = compact( 'title', 'edit_link' ); } } } if ( ! empty( $posts ) ) { $return .= '<ol>'; foreach ( (array) $posts as $id => $post ) { $return .= sprintf( '<li id="attached-%d"><a href="%s">%s</a></li>', $id, $post['edit_link'], $post['title'] ); } $return .= '</ol>'; } else { $return .= '&mdash;'; } return $return; }
[ "public", "function", "_display_render", "(", "$", "field", ",", "$", "val", ")", "{", "$", "return", "=", "''", ";", "$", "posts", "=", "array", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "val", ")", ")", "{", "foreach", "(", "(", "arra...
Outputs the display of our custom field per repeatable value, if applicable. @since 1.2.7 @param CMB2_Field $field This field object. @param mixed $val The field value.
[ "Outputs", "the", "display", "of", "our", "custom", "field", "per", "repeatable", "value", "if", "applicable", "." ]
556701d8f032931838c524ddc55c40b177a0e1a8
https://github.com/CMB2/cmb2-attached-posts/blob/556701d8f032931838c524ddc55c40b177a0e1a8/init.php#L670-L702
43,030
silverstripe/silverstripe-versioned
src/ChangeSet.php
ChangeSet.publish
public function publish($isSynced = false) { // Logical checks prior to publish if ($this->State !== static::STATE_OPEN) { throw new BadMethodCallException( "ChangeSet can't be published if it has been already published or reverted." ); } if (!$isSynced && !$this->isSynced()) { throw new ValidationException( "ChangeSet does not include all necessary changes and cannot be published." ); } DB::get_conn()->withTransaction(function () { foreach ($this->Changes() as $change) { /** @var ChangeSetItem $change */ $change->publish(); } // Once this changeset is published, unlink any objects linking to // records in this changeset as unlinked (set RelationID to 0). // This is done as a safer alternative to deleting records on live that // are deleted on stage. foreach ($this->Changes() as $change) { /** @var ChangeSetItem $change */ $change->unlinkDisownedObjects(); } $this->State = static::STATE_PUBLISHED; $this->PublisherID = Security::getCurrentUser() ? Security::getCurrentUser()->ID : 0; $this->PublishDate = DBDatetime::now()->Rfc2822(); $this->write(); }); return true; }
php
public function publish($isSynced = false) { // Logical checks prior to publish if ($this->State !== static::STATE_OPEN) { throw new BadMethodCallException( "ChangeSet can't be published if it has been already published or reverted." ); } if (!$isSynced && !$this->isSynced()) { throw new ValidationException( "ChangeSet does not include all necessary changes and cannot be published." ); } DB::get_conn()->withTransaction(function () { foreach ($this->Changes() as $change) { /** @var ChangeSetItem $change */ $change->publish(); } // Once this changeset is published, unlink any objects linking to // records in this changeset as unlinked (set RelationID to 0). // This is done as a safer alternative to deleting records on live that // are deleted on stage. foreach ($this->Changes() as $change) { /** @var ChangeSetItem $change */ $change->unlinkDisownedObjects(); } $this->State = static::STATE_PUBLISHED; $this->PublisherID = Security::getCurrentUser() ? Security::getCurrentUser()->ID : 0; $this->PublishDate = DBDatetime::now()->Rfc2822(); $this->write(); }); return true; }
[ "public", "function", "publish", "(", "$", "isSynced", "=", "false", ")", "{", "// Logical checks prior to publish", "if", "(", "$", "this", "->", "State", "!==", "static", "::", "STATE_OPEN", ")", "{", "throw", "new", "BadMethodCallException", "(", "\"ChangeSet...
Publish this changeset, then closes it. User code should call {@see canPublish()} prior to invoking this method. @throws BadMethodCallException ChangeSet has already been published or reverted. @throws ValidationException ChangeSet is not synced an can not be published. @param boolean $isSynced Whatever to assume the ChangeSet is synced. Only set this to true if the ChangetSet just got built. Defaults to false. @return bool True if successful
[ "Publish", "this", "changeset", "then", "closes", "it", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSet.php#L124-L162
43,031
silverstripe/silverstripe-versioned
src/ChangeSet.php
ChangeSet.addObject
public function addObject(DataObject $object) { if (!$this->isInDB()) { throw new BadMethodCallException("ChangeSet must be saved before adding items"); } if (!$object->isInDB()) { throw new BadMethodCallException("Items must be saved before adding to a changeset"); } $references = [ 'ObjectID' => $object->ID, 'ObjectClass' => $object->baseClass(), ]; // Get existing item in case already added $item = $this->Changes()->filter($references)->first(); if (!$item) { $item = new ChangeSetItem($references); $this->Changes()->add($item); } $item->ReferencedBy()->removeAll(); $item->Added = ChangeSetItem::EXPLICITLY; $item->write(); $this->sync(); }
php
public function addObject(DataObject $object) { if (!$this->isInDB()) { throw new BadMethodCallException("ChangeSet must be saved before adding items"); } if (!$object->isInDB()) { throw new BadMethodCallException("Items must be saved before adding to a changeset"); } $references = [ 'ObjectID' => $object->ID, 'ObjectClass' => $object->baseClass(), ]; // Get existing item in case already added $item = $this->Changes()->filter($references)->first(); if (!$item) { $item = new ChangeSetItem($references); $this->Changes()->add($item); } $item->ReferencedBy()->removeAll(); $item->Added = ChangeSetItem::EXPLICITLY; $item->write(); $this->sync(); }
[ "public", "function", "addObject", "(", "DataObject", "$", "object", ")", "{", "if", "(", "!", "$", "this", "->", "isInDB", "(", ")", ")", "{", "throw", "new", "BadMethodCallException", "(", "\"ChangeSet must be saved before adding items\"", ")", ";", "}", "if...
Add a new change to this changeset. Will automatically include all owned changes as those are dependencies of this item. @param DataObject $object
[ "Add", "a", "new", "change", "to", "this", "changeset", ".", "Will", "automatically", "include", "all", "owned", "changes", "as", "those", "are", "dependencies", "of", "this", "item", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSet.php#L170-L199
43,032
silverstripe/silverstripe-versioned
src/ChangeSet.php
ChangeSet.implicitKey
protected function implicitKey(DataObject $item) { if ($item instanceof ChangeSetItem) { return $item->ObjectClass . '.' . $item->ObjectID; } return $item->baseClass() . '.' . $item->ID; }
php
protected function implicitKey(DataObject $item) { if ($item instanceof ChangeSetItem) { return $item->ObjectClass . '.' . $item->ObjectID; } return $item->baseClass() . '.' . $item->ID; }
[ "protected", "function", "implicitKey", "(", "DataObject", "$", "item", ")", "{", "if", "(", "$", "item", "instanceof", "ChangeSetItem", ")", "{", "return", "$", "item", "->", "ObjectClass", ".", "'.'", ".", "$", "item", "->", "ObjectID", ";", "}", "retu...
Build identifying string key for this object @param DataObject $item @return string
[ "Build", "identifying", "string", "key", "for", "this", "object" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSet.php#L230-L236
43,033
silverstripe/silverstripe-versioned
src/ChangeSet.php
ChangeSet.calculateImplicit
protected function calculateImplicit() { /** @var string[][] $explicit List of all items that have been explicitly added to this ChangeSet */ $explicit = []; /** @var string[][] $referenced List of all items that are "referenced" by items in $explicit */ $referenced = []; /** @var string[][] $references List of which explicit items reference each thing in referenced */ $references = []; /** @var ChangeSetItem $item */ foreach ($this->Changes()->filter(['Added' => ChangeSetItem::EXPLICITLY]) as $item) { $explicitKey = $this->implicitKey($item); $explicit[$explicitKey] = true; foreach ($item->findReferenced() as $referee) { try { /** @var DataObject $referee */ $key = $this->implicitKey($referee); $referenced[$key] = [ 'ObjectID' => $referee->ID, 'ObjectClass' => $referee->baseClass(), ]; $references[$key][] = $item->ID; // Skip any bad records } catch (UnexpectedDataException $e) { } } } /** @var string[][] $explicit List of all items that are either in $explicit, $referenced or both */ $all = array_merge($referenced, $explicit); /** @var string[][] $implicit Anything that is in $all, but not in $explicit, is an implicit inclusion */ $implicit = array_diff_key($all, $explicit); foreach ($implicit as $key => $object) { $implicit[$key]['ReferencedBy'] = $references[$key]; } return $implicit; }
php
protected function calculateImplicit() { /** @var string[][] $explicit List of all items that have been explicitly added to this ChangeSet */ $explicit = []; /** @var string[][] $referenced List of all items that are "referenced" by items in $explicit */ $referenced = []; /** @var string[][] $references List of which explicit items reference each thing in referenced */ $references = []; /** @var ChangeSetItem $item */ foreach ($this->Changes()->filter(['Added' => ChangeSetItem::EXPLICITLY]) as $item) { $explicitKey = $this->implicitKey($item); $explicit[$explicitKey] = true; foreach ($item->findReferenced() as $referee) { try { /** @var DataObject $referee */ $key = $this->implicitKey($referee); $referenced[$key] = [ 'ObjectID' => $referee->ID, 'ObjectClass' => $referee->baseClass(), ]; $references[$key][] = $item->ID; // Skip any bad records } catch (UnexpectedDataException $e) { } } } /** @var string[][] $explicit List of all items that are either in $explicit, $referenced or both */ $all = array_merge($referenced, $explicit); /** @var string[][] $implicit Anything that is in $all, but not in $explicit, is an implicit inclusion */ $implicit = array_diff_key($all, $explicit); foreach ($implicit as $key => $object) { $implicit[$key]['ReferencedBy'] = $references[$key]; } return $implicit; }
[ "protected", "function", "calculateImplicit", "(", ")", "{", "/** @var string[][] $explicit List of all items that have been explicitly added to this ChangeSet */", "$", "explicit", "=", "[", "]", ";", "/** @var string[][] $referenced List of all items that are \"referenced\" by items in $...
List of all implicit items inferred from all currently assigned explicit changes @return array
[ "List", "of", "all", "implicit", "items", "inferred", "from", "all", "currently", "assigned", "explicit", "changes" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSet.php#L243-L288
43,034
silverstripe/silverstripe-versioned
src/ChangeSet.php
ChangeSet.sync
public function sync() { // Only sync open changesets if ($this->State !== static::STATE_OPEN) { return; } // Start a transaction (if we can) DB::get_conn()->withTransaction(function () { // Get the implicitly included items for this ChangeSet $implicit = $this->calculateImplicit(); // Adjust the existing implicit ChangeSetItems for this ChangeSet /** @var ChangeSetItem $item */ foreach ($this->Changes()->filter(['Added' => ChangeSetItem::IMPLICITLY]) as $item) { $objectKey = $this->implicitKey($item); // If a ChangeSetItem exists, but isn't in $implicit, it's no longer required, so delete it if (!array_key_exists($objectKey, $implicit)) { $item->delete(); } else { // Otherwise it is required, so update ReferencedBy and remove from $implicit $item->ReferencedBy()->setByIDList($implicit[$objectKey]['ReferencedBy']); unset($implicit[$objectKey]); } } // Now $implicit is all those items that are implicitly included, but don't currently have a ChangeSetItem. // So create new ChangeSetItems to match foreach ($implicit as $key => $props) { $item = new ChangeSetItem($props); $item->Added = ChangeSetItem::IMPLICITLY; $item->ChangeSetID = $this->ID; $item->ReferencedBy()->setByIDList($props['ReferencedBy']); $item->write(); } // Mark last synced $this->LastSynced = DBDatetime::now()->getValue(); $this->write(); }); }
php
public function sync() { // Only sync open changesets if ($this->State !== static::STATE_OPEN) { return; } // Start a transaction (if we can) DB::get_conn()->withTransaction(function () { // Get the implicitly included items for this ChangeSet $implicit = $this->calculateImplicit(); // Adjust the existing implicit ChangeSetItems for this ChangeSet /** @var ChangeSetItem $item */ foreach ($this->Changes()->filter(['Added' => ChangeSetItem::IMPLICITLY]) as $item) { $objectKey = $this->implicitKey($item); // If a ChangeSetItem exists, but isn't in $implicit, it's no longer required, so delete it if (!array_key_exists($objectKey, $implicit)) { $item->delete(); } else { // Otherwise it is required, so update ReferencedBy and remove from $implicit $item->ReferencedBy()->setByIDList($implicit[$objectKey]['ReferencedBy']); unset($implicit[$objectKey]); } } // Now $implicit is all those items that are implicitly included, but don't currently have a ChangeSetItem. // So create new ChangeSetItems to match foreach ($implicit as $key => $props) { $item = new ChangeSetItem($props); $item->Added = ChangeSetItem::IMPLICITLY; $item->ChangeSetID = $this->ID; $item->ReferencedBy()->setByIDList($props['ReferencedBy']); $item->write(); } // Mark last synced $this->LastSynced = DBDatetime::now()->getValue(); $this->write(); }); }
[ "public", "function", "sync", "(", ")", "{", "// Only sync open changesets", "if", "(", "$", "this", "->", "State", "!==", "static", "::", "STATE_OPEN", ")", "{", "return", ";", "}", "// Start a transaction (if we can)", "DB", "::", "get_conn", "(", ")", "->",...
Add implicit changes that should be included in this changeset When an item is created or changed, all it's owned items which have changes are implicitly added When an item is deleted, it's owner (even if that owner does not have changes) is implicitly added
[ "Add", "implicit", "changes", "that", "should", "be", "included", "in", "this", "changeset" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSet.php#L299-L342
43,035
silverstripe/silverstripe-versioned
src/ChangeSet.php
ChangeSet.isSynced
public function isSynced() { $implicit = $this->calculateImplicit(); // Check the existing implicit ChangeSetItems for this ChangeSet foreach ($this->Changes()->filter(['Added' => ChangeSetItem::IMPLICITLY]) as $item) { $objectKey = $this->implicitKey($item); // If a ChangeSetItem exists, but isn't in $implicit -> validation failure if (!array_key_exists($objectKey, $implicit)) { return false; } // Exists, remove from $implicit unset($implicit[$objectKey]); } // If there's anything left in $implicit -> validation failure return empty($implicit); }
php
public function isSynced() { $implicit = $this->calculateImplicit(); // Check the existing implicit ChangeSetItems for this ChangeSet foreach ($this->Changes()->filter(['Added' => ChangeSetItem::IMPLICITLY]) as $item) { $objectKey = $this->implicitKey($item); // If a ChangeSetItem exists, but isn't in $implicit -> validation failure if (!array_key_exists($objectKey, $implicit)) { return false; } // Exists, remove from $implicit unset($implicit[$objectKey]); } // If there's anything left in $implicit -> validation failure return empty($implicit); }
[ "public", "function", "isSynced", "(", ")", "{", "$", "implicit", "=", "$", "this", "->", "calculateImplicit", "(", ")", ";", "// Check the existing implicit ChangeSetItems for this ChangeSet", "foreach", "(", "$", "this", "->", "Changes", "(", ")", "->", "filter"...
Verify that any objects in this changeset include all owned changes
[ "Verify", "that", "any", "objects", "in", "this", "changeset", "include", "all", "owned", "changes" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSet.php#L345-L364
43,036
silverstripe/silverstripe-versioned
src/ChangeSet.php
ChangeSet.canPublish
public function canPublish($member = null) { if (!$member) { $member = Security::getCurrentUser(); } // Check all explicitly added items foreach ($this->Changes()->filter(['Added' => ChangeSetItem::EXPLICITLY]) as $change) { /** @var ChangeSetItem $change */ if (!$change->canPublish($member)) { return false; } } return true; }
php
public function canPublish($member = null) { if (!$member) { $member = Security::getCurrentUser(); } // Check all explicitly added items foreach ($this->Changes()->filter(['Added' => ChangeSetItem::EXPLICITLY]) as $change) { /** @var ChangeSetItem $change */ if (!$change->canPublish($member)) { return false; } } return true; }
[ "public", "function", "canPublish", "(", "$", "member", "=", "null", ")", "{", "if", "(", "!", "$", "member", ")", "{", "$", "member", "=", "Security", "::", "getCurrentUser", "(", ")", ";", "}", "// Check all explicitly added items", "foreach", "(", "$", ...
Check if this item is allowed to be published @param Member $member @return bool
[ "Check", "if", "this", "item", "is", "allowed", "to", "be", "published" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSet.php#L392-L406
43,037
silverstripe/silverstripe-versioned
src/ChangeSet.php
ChangeSet.getDetails
public function getDetails() { // Check each change item /** @var ChangeSetItem $change */ $total = 0; $withChanges = 0; foreach ($this->Changes() as $change) { $total++; if ($change->hasChange()) { $withChanges++; } } // Empty state if (empty($total)) { return _t(__CLASS__ . '.EMPTY', 'Empty'); } // Count all items $totalText = _t( __CLASS__ . '.ITEMS_TOTAL', '1 total|{count} total', ['count' => $total] ); if (empty($withChanges)) { return $totalText; } // Interpolate with changes text return _t( __CLASS__ . '.ITEMS_CHANGES', '{total} (1 change)|{total} ({count} changes)', [ 'total' => $totalText, 'count' => $withChanges, ] ); }
php
public function getDetails() { // Check each change item /** @var ChangeSetItem $change */ $total = 0; $withChanges = 0; foreach ($this->Changes() as $change) { $total++; if ($change->hasChange()) { $withChanges++; } } // Empty state if (empty($total)) { return _t(__CLASS__ . '.EMPTY', 'Empty'); } // Count all items $totalText = _t( __CLASS__ . '.ITEMS_TOTAL', '1 total|{count} total', ['count' => $total] ); if (empty($withChanges)) { return $totalText; } // Interpolate with changes text return _t( __CLASS__ . '.ITEMS_CHANGES', '{total} (1 change)|{total} ({count} changes)', [ 'total' => $totalText, 'count' => $withChanges, ] ); }
[ "public", "function", "getDetails", "(", ")", "{", "// Check each change item", "/** @var ChangeSetItem $change */", "$", "total", "=", "0", ";", "$", "withChanges", "=", "0", ";", "foreach", "(", "$", "this", "->", "Changes", "(", ")", "as", "$", "change", ...
Gets summary of items in changeset @return string
[ "Gets", "summary", "of", "items", "in", "changeset" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSet.php#L514-L551
43,038
silverstripe/silverstripe-versioned
src/ChangeSet.php
ChangeSet.getPublishedLabel
public function getPublishedLabel() { $dateObj = $this->obj('PublishDate'); if (!$dateObj) { return null; } $publisher = $this->getPublisherName(); // Use "today" if ($dateObj->IsToday()) { if ($publisher) { return _t( __CLASS__ . '.PUBLISHED_TODAY_BY', 'Today {time} by {name}', [ 'time' => $dateObj->Time12(), 'name' => $publisher, ] ); } // Today, no publisher return _t( __CLASS__ . '.PUBLISHED_TODAY', 'Today {time}', ['time' => $dateObj->Time12()] ); } // Use date if ($publisher) { return _t( __CLASS__ . '.PUBLISHED_DATE_BY', '{date} by {name}', [ 'date' => $dateObj->FormatFromSettings(), 'name' => $publisher, ] ); } // Date, no publisher return $dateObj->FormatFromSettings(); }
php
public function getPublishedLabel() { $dateObj = $this->obj('PublishDate'); if (!$dateObj) { return null; } $publisher = $this->getPublisherName(); // Use "today" if ($dateObj->IsToday()) { if ($publisher) { return _t( __CLASS__ . '.PUBLISHED_TODAY_BY', 'Today {time} by {name}', [ 'time' => $dateObj->Time12(), 'name' => $publisher, ] ); } // Today, no publisher return _t( __CLASS__ . '.PUBLISHED_TODAY', 'Today {time}', ['time' => $dateObj->Time12()] ); } // Use date if ($publisher) { return _t( __CLASS__ . '.PUBLISHED_DATE_BY', '{date} by {name}', [ 'date' => $dateObj->FormatFromSettings(), 'name' => $publisher, ] ); } // Date, no publisher return $dateObj->FormatFromSettings(); }
[ "public", "function", "getPublishedLabel", "(", ")", "{", "$", "dateObj", "=", "$", "this", "->", "obj", "(", "'PublishDate'", ")", ";", "if", "(", "!", "$", "dateObj", ")", "{", "return", "null", ";", "}", "$", "publisher", "=", "$", "this", "->", ...
Gets the label for the "last published" date. Special case for "today" @return string
[ "Gets", "the", "label", "for", "the", "last", "published", "date", ".", "Special", "case", "for", "today" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSet.php#L568-L611
43,039
silverstripe/silverstripe-versioned
src/ChangeSet.php
ChangeSet.getStateLabel
public function getStateLabel() { switch ($this->State) { case self::STATE_OPEN: return _t(__CLASS__.'.STATE_OPEN', 'Active'); case self::STATE_PUBLISHED: return _t(__CLASS__.'.STATE_PUBLISHED', 'Published'); case self::STATE_REVERTED: return _t(__CLASS__.'.STATE_REVERTED', 'Reverted'); default: return null; } }
php
public function getStateLabel() { switch ($this->State) { case self::STATE_OPEN: return _t(__CLASS__.'.STATE_OPEN', 'Active'); case self::STATE_PUBLISHED: return _t(__CLASS__.'.STATE_PUBLISHED', 'Published'); case self::STATE_REVERTED: return _t(__CLASS__.'.STATE_REVERTED', 'Reverted'); default: return null; } }
[ "public", "function", "getStateLabel", "(", ")", "{", "switch", "(", "$", "this", "->", "State", ")", "{", "case", "self", "::", "STATE_OPEN", ":", "return", "_t", "(", "__CLASS__", ".", "'.STATE_OPEN'", ",", "'Active'", ")", ";", "case", "self", "::", ...
Description for state @return string
[ "Description", "for", "state" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSet.php#L618-L630
43,040
silverstripe/silverstripe-versioned
src/VersionedGridFieldItemRequest.php
VersionedGridFieldItemRequest.saveFormIntoRecord
public function saveFormIntoRecord($data, $form) { $record = parent::saveFormIntoRecord($data, $form); // Note: Don't publish if versioned, since that's a separate action $ownerIsVersioned = $record && $record->hasExtension(Versioned::class); $ownerIsPublishable = $record && $record->hasExtension(RecursivePublishable::class); if ($ownerIsPublishable && !$ownerIsVersioned) { /** @var RecursivePublishable $record */ $record->publishRecursive(); } return $record; }
php
public function saveFormIntoRecord($data, $form) { $record = parent::saveFormIntoRecord($data, $form); // Note: Don't publish if versioned, since that's a separate action $ownerIsVersioned = $record && $record->hasExtension(Versioned::class); $ownerIsPublishable = $record && $record->hasExtension(RecursivePublishable::class); if ($ownerIsPublishable && !$ownerIsVersioned) { /** @var RecursivePublishable $record */ $record->publishRecursive(); } return $record; }
[ "public", "function", "saveFormIntoRecord", "(", "$", "data", ",", "$", "form", ")", "{", "$", "record", "=", "parent", "::", "saveFormIntoRecord", "(", "$", "data", ",", "$", "form", ")", ";", "// Note: Don't publish if versioned, since that's a separate action", ...
If a record is recursive publishable, but not versioned, all saves should trigger a recursive publish. @param array $data @param Form $form @return DataObject $record
[ "If", "a", "record", "is", "recursive", "publishable", "but", "not", "versioned", "all", "saves", "should", "trigger", "a", "recursive", "publish", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedGridFieldItemRequest.php#L96-L109
43,041
silverstripe/silverstripe-versioned
src/VersionedGridFieldItemRequest.php
VersionedGridFieldItemRequest.doArchive
public function doArchive($data, $form) { /** @var Versioned|DataObject $record */ $record = $this->getRecord(); if (!$record->canArchive()) { return $this->httpError(403); } // Record name before it's deleted $title = $record->Title; $record->doArchive(); $message = _t( __CLASS__ . '.Archived', 'Archived {name} {title}', [ 'name' => $record->i18n_singular_name(), 'title' => Convert::raw2xml($title) ] ); $this->setFormMessage($form, $message); //when an item is deleted, redirect to the parent controller $controller = $this->getToplevelController(); $controller->getRequest()->addHeader('X-Pjax', 'Content'); // Force a content refresh return $controller->redirect($this->getBackLink(), 302); //redirect back to admin section }
php
public function doArchive($data, $form) { /** @var Versioned|DataObject $record */ $record = $this->getRecord(); if (!$record->canArchive()) { return $this->httpError(403); } // Record name before it's deleted $title = $record->Title; $record->doArchive(); $message = _t( __CLASS__ . '.Archived', 'Archived {name} {title}', [ 'name' => $record->i18n_singular_name(), 'title' => Convert::raw2xml($title) ] ); $this->setFormMessage($form, $message); //when an item is deleted, redirect to the parent controller $controller = $this->getToplevelController(); $controller->getRequest()->addHeader('X-Pjax', 'Content'); // Force a content refresh return $controller->redirect($this->getBackLink(), 302); //redirect back to admin section }
[ "public", "function", "doArchive", "(", "$", "data", ",", "$", "form", ")", "{", "/** @var Versioned|DataObject $record */", "$", "record", "=", "$", "this", "->", "getRecord", "(", ")", ";", "if", "(", "!", "$", "record", "->", "canArchive", "(", ")", "...
Archive this versioned record @param array $data @param Form $form @return HTTPResponse
[ "Archive", "this", "versioned", "record" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedGridFieldItemRequest.php#L118-L145
43,042
silverstripe/silverstripe-versioned
src/VersionedGridFieldItemRequest.php
VersionedGridFieldItemRequest.doPublish
public function doPublish($data, $form) { /** @var Versioned|RecursivePublishable|DataObject $record */ $record = $this->getRecord(); $isNewRecord = $record->ID == 0; // Check permission if (!$record->canPublish()) { return $this->httpError(403); } // Initial save and reload $record = $this->saveFormIntoRecord($data, $form); $record->publishRecursive(); $editURL = $this->Link('edit'); $xmlTitle = Convert::raw2xml($record->Title); $link = "<a href=\"{$editURL}\">{$xmlTitle}</a>"; $message = _t( __CLASS__ . '.Published', 'Published {name} {link}', [ 'name' => $record->i18n_singular_name(), 'link' => $link ] ); $this->setFormMessage($form, $message); return $this->redirectAfterSave($isNewRecord); }
php
public function doPublish($data, $form) { /** @var Versioned|RecursivePublishable|DataObject $record */ $record = $this->getRecord(); $isNewRecord = $record->ID == 0; // Check permission if (!$record->canPublish()) { return $this->httpError(403); } // Initial save and reload $record = $this->saveFormIntoRecord($data, $form); $record->publishRecursive(); $editURL = $this->Link('edit'); $xmlTitle = Convert::raw2xml($record->Title); $link = "<a href=\"{$editURL}\">{$xmlTitle}</a>"; $message = _t( __CLASS__ . '.Published', 'Published {name} {link}', [ 'name' => $record->i18n_singular_name(), 'link' => $link ] ); $this->setFormMessage($form, $message); return $this->redirectAfterSave($isNewRecord); }
[ "public", "function", "doPublish", "(", "$", "data", ",", "$", "form", ")", "{", "/** @var Versioned|RecursivePublishable|DataObject $record */", "$", "record", "=", "$", "this", "->", "getRecord", "(", ")", ";", "$", "isNewRecord", "=", "$", "record", "->", "...
Publish this versioned record @param array $data @param Form $form @return HTTPResponse
[ "Publish", "this", "versioned", "record" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedGridFieldItemRequest.php#L154-L183
43,043
silverstripe/silverstripe-versioned
src/VersionedGridFieldItemRequest.php
VersionedGridFieldItemRequest.doUnpublish
public function doUnpublish($data, $form) { /** @var Versioned|DataObject $record */ $record = $this->getRecord(); if (!$record->canUnpublish()) { return $this->httpError(403); } // Record name before it's deleted $title = $record->Title; $record->doUnpublish(); $message = _t( __CLASS__ . '.Unpublished', 'Unpublished {name} {title}', [ 'name' => $record->i18n_singular_name(), 'title' => Convert::raw2xml($title) ] ); $this->setFormMessage($form, $message); // Redirect back to edit return $this->redirectAfterSave(false); }
php
public function doUnpublish($data, $form) { /** @var Versioned|DataObject $record */ $record = $this->getRecord(); if (!$record->canUnpublish()) { return $this->httpError(403); } // Record name before it's deleted $title = $record->Title; $record->doUnpublish(); $message = _t( __CLASS__ . '.Unpublished', 'Unpublished {name} {title}', [ 'name' => $record->i18n_singular_name(), 'title' => Convert::raw2xml($title) ] ); $this->setFormMessage($form, $message); // Redirect back to edit return $this->redirectAfterSave(false); }
[ "public", "function", "doUnpublish", "(", "$", "data", ",", "$", "form", ")", "{", "/** @var Versioned|DataObject $record */", "$", "record", "=", "$", "this", "->", "getRecord", "(", ")", ";", "if", "(", "!", "$", "record", "->", "canUnpublish", "(", ")",...
Delete this record from the live site @param array $data @param Form $form @return HTTPResponse
[ "Delete", "this", "record", "from", "the", "live", "site" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedGridFieldItemRequest.php#L192-L216
43,044
silverstripe/silverstripe-versioned
src/VersionedGridFieldItemRequest.php
VersionedGridFieldItemRequest.addVersionedButtons
protected function addVersionedButtons(DataObject $record, FieldList $actions) { // Save & Publish action if ($record->canPublish()) { // "publish", as with "save", it supports an alternate state to show when action is needed. $publish = FormAction::create( 'doPublish', _t(__CLASS__ . '.BUTTONPUBLISH', 'Publish') ) ->setUseButtonTag(true) ->addExtraClass('btn btn-primary font-icon-rocket'); // Insert after save if ($actions->fieldByName('action_doSave')) { $actions->insertAfter('action_doSave', $publish); } else { $actions->push($publish); } } // Unpublish action if ($record->isInDB() && $record->canUnpublish()) { /** @var DataObject|Versioned|RecursivePublishable $liveRecord */ $liveRecord = Versioned::get_by_stage($record->baseClass(), Versioned::LIVE) ->byID($record->ID); if ($liveRecord) { $liveOwners = $liveRecord->findOwners(false)->count(); $actions->push( FormAction::create( 'doUnpublish', _t(__CLASS__ . '.BUTTONUNPUBLISH', 'Unpublish') ) ->setUseButtonTag(true) ->setDescription(_t( __CLASS__ . '.BUTTONUNPUBLISHDESC', 'Remove this record from the published site' )) ->addExtraClass('btn-secondary') ->setAttribute('data-owners', $liveOwners) ); } } // Archive action if ($record->isInDB() && $record->canArchive()) { // Replace "delete" action $actions->removeByName('action_doDelete'); // "archive" $actions->push( FormAction::create('doArchive', _t(__CLASS__ . '.ARCHIVE', 'Archive')) ->setUseButtonTag(true) ->setDescription(_t( __CLASS__ . '.BUTTONARCHIVEDESC', 'Unpublish and send to archive' )) ->addExtraClass('btn-secondary action--archive font-icon-box') ); } }
php
protected function addVersionedButtons(DataObject $record, FieldList $actions) { // Save & Publish action if ($record->canPublish()) { // "publish", as with "save", it supports an alternate state to show when action is needed. $publish = FormAction::create( 'doPublish', _t(__CLASS__ . '.BUTTONPUBLISH', 'Publish') ) ->setUseButtonTag(true) ->addExtraClass('btn btn-primary font-icon-rocket'); // Insert after save if ($actions->fieldByName('action_doSave')) { $actions->insertAfter('action_doSave', $publish); } else { $actions->push($publish); } } // Unpublish action if ($record->isInDB() && $record->canUnpublish()) { /** @var DataObject|Versioned|RecursivePublishable $liveRecord */ $liveRecord = Versioned::get_by_stage($record->baseClass(), Versioned::LIVE) ->byID($record->ID); if ($liveRecord) { $liveOwners = $liveRecord->findOwners(false)->count(); $actions->push( FormAction::create( 'doUnpublish', _t(__CLASS__ . '.BUTTONUNPUBLISH', 'Unpublish') ) ->setUseButtonTag(true) ->setDescription(_t( __CLASS__ . '.BUTTONUNPUBLISHDESC', 'Remove this record from the published site' )) ->addExtraClass('btn-secondary') ->setAttribute('data-owners', $liveOwners) ); } } // Archive action if ($record->isInDB() && $record->canArchive()) { // Replace "delete" action $actions->removeByName('action_doDelete'); // "archive" $actions->push( FormAction::create('doArchive', _t(__CLASS__ . '.ARCHIVE', 'Archive')) ->setUseButtonTag(true) ->setDescription(_t( __CLASS__ . '.BUTTONARCHIVEDESC', 'Unpublish and send to archive' )) ->addExtraClass('btn-secondary action--archive font-icon-box') ); } }
[ "protected", "function", "addVersionedButtons", "(", "DataObject", "$", "record", ",", "FieldList", "$", "actions", ")", "{", "// Save & Publish action", "if", "(", "$", "record", "->", "canPublish", "(", ")", ")", "{", "// \"publish\", as with \"save\", it supports a...
Getting buttons that are for versioned objects @param DataObject|Versioned|RecursivePublishable $record @param FieldList $actions
[ "Getting", "buttons", "that", "are", "for", "versioned", "objects" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedGridFieldItemRequest.php#L271-L330
43,045
silverstripe/silverstripe-versioned
src/VersionedGridFieldItemRequest.php
VersionedGridFieldItemRequest.addUnversionedButtons
protected function addUnversionedButtons(DataObject $record, FieldList $actions) { if (!$record->canEdit()) { return; } $saveAction = $actions->fieldByName('action_doSave'); if (!$saveAction) { return; } if (!$this->record->ID) { return; } $saveAction->setTitle(_t( __CLASS__ . '.BUTTONAPPLYCHANGES', 'Apply changes' ))->addExtraClass('btn-primary font-icon-save'); }
php
protected function addUnversionedButtons(DataObject $record, FieldList $actions) { if (!$record->canEdit()) { return; } $saveAction = $actions->fieldByName('action_doSave'); if (!$saveAction) { return; } if (!$this->record->ID) { return; } $saveAction->setTitle(_t( __CLASS__ . '.BUTTONAPPLYCHANGES', 'Apply changes' ))->addExtraClass('btn-primary font-icon-save'); }
[ "protected", "function", "addUnversionedButtons", "(", "DataObject", "$", "record", ",", "FieldList", "$", "actions", ")", "{", "if", "(", "!", "$", "record", "->", "canEdit", "(", ")", ")", "{", "return", ";", "}", "$", "saveAction", "=", "$", "actions"...
Getting buttons that are for unversioned objects @param DataObject $record @param FieldList $actions
[ "Getting", "buttons", "that", "are", "for", "unversioned", "objects" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedGridFieldItemRequest.php#L338-L354
43,046
silverstripe/silverstripe-versioned
src/DataDifferencer.php
DataDifferencer.ignoreFields
public function ignoreFields($ignoredFields) { if (!is_array($ignoredFields)) { $ignoredFields = func_get_args(); } $this->ignoredFields = array_merge($this->ignoredFields, $ignoredFields); return $this; }
php
public function ignoreFields($ignoredFields) { if (!is_array($ignoredFields)) { $ignoredFields = func_get_args(); } $this->ignoredFields = array_merge($this->ignoredFields, $ignoredFields); return $this; }
[ "public", "function", "ignoreFields", "(", "$", "ignoredFields", ")", "{", "if", "(", "!", "is_array", "(", "$", "ignoredFields", ")", ")", "{", "$", "ignoredFields", "=", "func_get_args", "(", ")", ";", "}", "$", "this", "->", "ignoredFields", "=", "arr...
Specify some fields to ignore changes from. Repeated calls are cumulative. @param array $ignoredFields An array of field names to ignore. Alternatively, pass the field names as separate args. @return $this
[ "Specify", "some", "fields", "to", "ignore", "changes", "from", ".", "Repeated", "calls", "are", "cumulative", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/DataDifferencer.php#L74-L82
43,047
silverstripe/silverstripe-versioned
src/DataDifferencer.php
DataDifferencer.getObjectDisplay
protected function getObjectDisplay($object = null) { if (!$object || !$object->isInDB()) { return ''; } // Use image tag // TODO Use CMSThumbnail instead to limit max size, blocked by DataDifferencerTest and GC // not playing nice with mocked images if ($object instanceof Image) { return $object->getTag(); } // Format title return $object->obj('Title')->forTemplate(); }
php
protected function getObjectDisplay($object = null) { if (!$object || !$object->isInDB()) { return ''; } // Use image tag // TODO Use CMSThumbnail instead to limit max size, blocked by DataDifferencerTest and GC // not playing nice with mocked images if ($object instanceof Image) { return $object->getTag(); } // Format title return $object->obj('Title')->forTemplate(); }
[ "protected", "function", "getObjectDisplay", "(", "$", "object", "=", "null", ")", "{", "if", "(", "!", "$", "object", "||", "!", "$", "object", "->", "isInDB", "(", ")", ")", "{", "return", "''", ";", "}", "// Use image tag", "// TODO Use CMSThumbnail ins...
Get HTML to display for a dataobject @param DataObject $object @return string HTML output
[ "Get", "HTML", "to", "display", "for", "a", "dataobject" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/DataDifferencer.php#L183-L198
43,048
silverstripe/silverstripe-versioned
src/ChangeSetItem.php
ChangeSetItem.ThumbnailURL
public function ThumbnailURL($width, $height) { $object = $this->getObjectLatestVersion(); if ($object instanceof Thumbnail) { return $object->ThumbnailURL($width, $height); } return null; }
php
public function ThumbnailURL($width, $height) { $object = $this->getObjectLatestVersion(); if ($object instanceof Thumbnail) { return $object->ThumbnailURL($width, $height); } return null; }
[ "public", "function", "ThumbnailURL", "(", "$", "width", ",", "$", "height", ")", "{", "$", "object", "=", "$", "this", "->", "getObjectLatestVersion", "(", ")", ";", "if", "(", "$", "object", "instanceof", "Thumbnail", ")", "{", "return", "$", "object",...
Get a thumbnail for this object @param int $width Preferred width of the thumbnail @param int $height Preferred height of the thumbnail @return string URL to the thumbnail, if available
[ "Get", "a", "thumbnail", "for", "this", "object" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L110-L117
43,049
silverstripe/silverstripe-versioned
src/ChangeSetItem.php
ChangeSetItem.getObjectInStage
protected function getObjectInStage($stage) { if (!class_exists($this->ObjectClass)) { throw new UnexpectedDataException("Invalid Class '{$this->ObjectClass}' in ChangeSetItem #{$this->ID}"); } // Ignore stage for unversioned objects if (!$this->isVersioned()) { return DataObject::get_by_id($this->ObjectClass, $this->ObjectID); } // Get versioned object return Versioned::get_by_stage($this->ObjectClass, $stage)->byID($this->ObjectID); }
php
protected function getObjectInStage($stage) { if (!class_exists($this->ObjectClass)) { throw new UnexpectedDataException("Invalid Class '{$this->ObjectClass}' in ChangeSetItem #{$this->ID}"); } // Ignore stage for unversioned objects if (!$this->isVersioned()) { return DataObject::get_by_id($this->ObjectClass, $this->ObjectID); } // Get versioned object return Versioned::get_by_stage($this->ObjectClass, $stage)->byID($this->ObjectID); }
[ "protected", "function", "getObjectInStage", "(", "$", "stage", ")", "{", "if", "(", "!", "class_exists", "(", "$", "this", "->", "ObjectClass", ")", ")", "{", "throw", "new", "UnexpectedDataException", "(", "\"Invalid Class '{$this->ObjectClass}' in ChangeSetItem #{$...
Find version of this object in the given stage. If the object isn't versioned it will return the normal record. @param string $stage @return DataObject|Versioned|RecursivePublishable Object in this stage (may not be Versioned) @throws UnexpectedDataException
[ "Find", "version", "of", "this", "object", "in", "the", "given", "stage", ".", "If", "the", "object", "isn", "t", "versioned", "it", "will", "return", "the", "normal", "record", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L176-L189
43,050
silverstripe/silverstripe-versioned
src/ChangeSetItem.php
ChangeSetItem.findReferenced
public function findReferenced() { $liveRecord = $this->getObjectInStage(Versioned::LIVE); // For unversioned objects, simply return all owned objects if (!$this->isVersioned()) { return $liveRecord->findOwned(); } // If we have deleted this record, recursively delete live objects on publish if ($this->getChangeType() === ChangeSetItem::CHANGE_DELETED) { if (!$liveRecord) { return ArrayList::create(); } return $liveRecord->findCascadeDeletes(true); } // If changed on stage, include all owned objects for publish /** @var DataObject|RecursivePublishable $draftRecord */ $draftRecord = $this->getObjectInStage(Versioned::DRAFT); if (!$draftRecord) { return ArrayList::create(); } $references = $draftRecord->findOwned(); // When publishing, use cascade_deletes to partially unpublished sets if ($liveRecord) { foreach ($liveRecord->findCascadeDeletes(true) as $next) { /** @var Versioned|DataObject $next */ if ($next->hasExtension(Versioned::class) && $next->hasStages() && $next->isOnLiveOnly()) { $this->mergeRelatedObject($references, ArrayList::create(), $next); } } } return $references; }
php
public function findReferenced() { $liveRecord = $this->getObjectInStage(Versioned::LIVE); // For unversioned objects, simply return all owned objects if (!$this->isVersioned()) { return $liveRecord->findOwned(); } // If we have deleted this record, recursively delete live objects on publish if ($this->getChangeType() === ChangeSetItem::CHANGE_DELETED) { if (!$liveRecord) { return ArrayList::create(); } return $liveRecord->findCascadeDeletes(true); } // If changed on stage, include all owned objects for publish /** @var DataObject|RecursivePublishable $draftRecord */ $draftRecord = $this->getObjectInStage(Versioned::DRAFT); if (!$draftRecord) { return ArrayList::create(); } $references = $draftRecord->findOwned(); // When publishing, use cascade_deletes to partially unpublished sets if ($liveRecord) { foreach ($liveRecord->findCascadeDeletes(true) as $next) { /** @var Versioned|DataObject $next */ if ($next->hasExtension(Versioned::class) && $next->hasStages() && $next->isOnLiveOnly()) { $this->mergeRelatedObject($references, ArrayList::create(), $next); } } } return $references; }
[ "public", "function", "findReferenced", "(", ")", "{", "$", "liveRecord", "=", "$", "this", "->", "getObjectInStage", "(", "Versioned", "::", "LIVE", ")", ";", "// For unversioned objects, simply return all owned objects", "if", "(", "!", "$", "this", "->", "isVer...
Get all implicit objects for this change @return SS_List
[ "Get", "all", "implicit", "objects", "for", "this", "change" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L216-L251
43,051
silverstripe/silverstripe-versioned
src/ChangeSetItem.php
ChangeSetItem.publish
public function publish() { if (!class_exists($this->ObjectClass)) { throw new UnexpectedDataException("Invalid Class '{$this->ObjectClass}' in ChangeSetItem #{$this->ID}"); } // Logical checks prior to publish if ($this->VersionBefore || $this->VersionAfter) { throw new BadMethodCallException("This ChangeSetItem has already been published"); } // Skip unversioned records if (!$this->isVersioned()) { $this->VersionBefore = 0; $this->VersionAfter = 0; $this->write(); return; } // Record state changed $this->VersionAfter = Versioned::get_versionnumber_by_stage( $this->ObjectClass, Versioned::DRAFT, $this->ObjectID, false ); $this->VersionBefore = Versioned::get_versionnumber_by_stage( $this->ObjectClass, Versioned::LIVE, $this->ObjectID, false ); // Enact change $changeType = $this->getChangeType(); switch ($changeType) { case static::CHANGE_NONE: { break; } case static::CHANGE_DELETED: { // Non-recursive delete $object = $this->getObjectInStage(Versioned::LIVE); $object->deleteFromStage(Versioned::LIVE); break; } case static::CHANGE_MODIFIED: case static::CHANGE_CREATED: { // Non-recursive publish $object = $this->getObjectInStage(Versioned::DRAFT); $object->publishSingle(); // Point after version to the published version actually created, not the // version copied from draft. $this->VersionAfter = Versioned::get_versionnumber_by_stage( $this->ObjectClass, Versioned::LIVE, $this->ObjectID, false ); break; } default: throw new LogicException("Invalid change type: {$changeType}"); } $this->write(); }
php
public function publish() { if (!class_exists($this->ObjectClass)) { throw new UnexpectedDataException("Invalid Class '{$this->ObjectClass}' in ChangeSetItem #{$this->ID}"); } // Logical checks prior to publish if ($this->VersionBefore || $this->VersionAfter) { throw new BadMethodCallException("This ChangeSetItem has already been published"); } // Skip unversioned records if (!$this->isVersioned()) { $this->VersionBefore = 0; $this->VersionAfter = 0; $this->write(); return; } // Record state changed $this->VersionAfter = Versioned::get_versionnumber_by_stage( $this->ObjectClass, Versioned::DRAFT, $this->ObjectID, false ); $this->VersionBefore = Versioned::get_versionnumber_by_stage( $this->ObjectClass, Versioned::LIVE, $this->ObjectID, false ); // Enact change $changeType = $this->getChangeType(); switch ($changeType) { case static::CHANGE_NONE: { break; } case static::CHANGE_DELETED: { // Non-recursive delete $object = $this->getObjectInStage(Versioned::LIVE); $object->deleteFromStage(Versioned::LIVE); break; } case static::CHANGE_MODIFIED: case static::CHANGE_CREATED: { // Non-recursive publish $object = $this->getObjectInStage(Versioned::DRAFT); $object->publishSingle(); // Point after version to the published version actually created, not the // version copied from draft. $this->VersionAfter = Versioned::get_versionnumber_by_stage( $this->ObjectClass, Versioned::LIVE, $this->ObjectID, false ); break; } default: throw new LogicException("Invalid change type: {$changeType}"); } $this->write(); }
[ "public", "function", "publish", "(", ")", "{", "if", "(", "!", "class_exists", "(", "$", "this", "->", "ObjectClass", ")", ")", "{", "throw", "new", "UnexpectedDataException", "(", "\"Invalid Class '{$this->ObjectClass}' in ChangeSetItem #{$this->ID}\"", ")", ";", ...
Publish this item, then close it. Note: Unlike Versioned::doPublish() and Versioned::doUnpublish, this action is not recursive.
[ "Publish", "this", "item", "then", "close", "it", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L258-L324
43,052
silverstripe/silverstripe-versioned
src/ChangeSetItem.php
ChangeSetItem.canRevert
public function canRevert($member) { // No action for unversiond objects so no action to deny if (!$this->isVersioned()) { return true; } // Just get the best version as this object may not even exist on either stage anymore. /** @var Versioned|DataObject $object */ $object = $this->getObjectLatestVersion(); if (!$object) { return false; } // Check change type switch ($this->getChangeType()) { case static::CHANGE_CREATED: { // Revert creation by deleting from stage return $object->canDelete($member); } default: { // All other actions are typically editing draft stage return $object->canEdit($member); } } }
php
public function canRevert($member) { // No action for unversiond objects so no action to deny if (!$this->isVersioned()) { return true; } // Just get the best version as this object may not even exist on either stage anymore. /** @var Versioned|DataObject $object */ $object = $this->getObjectLatestVersion(); if (!$object) { return false; } // Check change type switch ($this->getChangeType()) { case static::CHANGE_CREATED: { // Revert creation by deleting from stage return $object->canDelete($member); } default: { // All other actions are typically editing draft stage return $object->canEdit($member); } } }
[ "public", "function", "canRevert", "(", "$", "member", ")", "{", "// No action for unversiond objects so no action to deny", "if", "(", "!", "$", "this", "->", "isVersioned", "(", ")", ")", "{", "return", "true", ";", "}", "// Just get the best version as this object ...
Check if the BeforeVersion of this changeset can be restored to draft @param Member $member @return bool
[ "Check", "if", "the", "BeforeVersion", "of", "this", "changeset", "can", "be", "restored", "to", "draft" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L370-L395
43,053
silverstripe/silverstripe-versioned
src/ChangeSetItem.php
ChangeSetItem.canPublish
public function canPublish($member = null) { // No action for unversiond objects so no action to deny // Implicitly added items allow publish if (!$this->isVersioned() || $this->Added === self::IMPLICITLY) { return true; } // Check canMethod to invoke on object switch ($this->getChangeType()) { case static::CHANGE_DELETED: { /** @var Versioned|DataObject $object */ $object = Versioned::get_by_stage($this->ObjectClass, Versioned::LIVE)->byID($this->ObjectID); if ($object) { return $object->canUnpublish($member); } break; } default: { /** @var Versioned|DataObject $object */ $object = Versioned::get_by_stage($this->ObjectClass, Versioned::DRAFT)->byID($this->ObjectID); if ($object) { return $object->canPublish($member); } break; } } return true; }
php
public function canPublish($member = null) { // No action for unversiond objects so no action to deny // Implicitly added items allow publish if (!$this->isVersioned() || $this->Added === self::IMPLICITLY) { return true; } // Check canMethod to invoke on object switch ($this->getChangeType()) { case static::CHANGE_DELETED: { /** @var Versioned|DataObject $object */ $object = Versioned::get_by_stage($this->ObjectClass, Versioned::LIVE)->byID($this->ObjectID); if ($object) { return $object->canUnpublish($member); } break; } default: { /** @var Versioned|DataObject $object */ $object = Versioned::get_by_stage($this->ObjectClass, Versioned::DRAFT)->byID($this->ObjectID); if ($object) { return $object->canPublish($member); } break; } } return true; }
[ "public", "function", "canPublish", "(", "$", "member", "=", "null", ")", "{", "// No action for unversiond objects so no action to deny", "// Implicitly added items allow publish", "if", "(", "!", "$", "this", "->", "isVersioned", "(", ")", "||", "$", "this", "->", ...
Check if this ChangeSetItem can be published @param Member $member @return bool
[ "Check", "if", "this", "ChangeSetItem", "can", "be", "published" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L403-L432
43,054
silverstripe/silverstripe-versioned
src/ChangeSetItem.php
ChangeSetItem.can
public function can($perm, $member = null, $context = []) { if (!$member) { $member = Security::getCurrentUser(); } // Allow extensions to bypass default permissions, but only if // each change can be individually published. $extended = $this->extendedCan($perm, $member, $context); if ($extended !== null) { return $extended; } // Default permissions return (bool)Permission::checkMember($member, ChangeSet::config()->get('required_permission')); }
php
public function can($perm, $member = null, $context = []) { if (!$member) { $member = Security::getCurrentUser(); } // Allow extensions to bypass default permissions, but only if // each change can be individually published. $extended = $this->extendedCan($perm, $member, $context); if ($extended !== null) { return $extended; } // Default permissions return (bool)Permission::checkMember($member, ChangeSet::config()->get('required_permission')); }
[ "public", "function", "can", "(", "$", "perm", ",", "$", "member", "=", "null", ",", "$", "context", "=", "[", "]", ")", "{", "if", "(", "!", "$", "member", ")", "{", "$", "member", "=", "Security", "::", "getCurrentUser", "(", ")", ";", "}", "...
Default permissions for this ChangeSetItem @param string $perm @param Member $member @param array $context @return bool
[ "Default", "permissions", "for", "this", "ChangeSetItem" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L452-L467
43,055
silverstripe/silverstripe-versioned
src/ChangeSetItem.php
ChangeSetItem.getPreviewLinks
public function getPreviewLinks() { $links = []; // Preview draft $stage = $this->getObjectInStage(Versioned::DRAFT); if ($stage instanceof CMSPreviewable && $stage->canView() && ($link = $stage->PreviewLink())) { $links[Versioned::DRAFT] = [ 'href' => Controller::join_links($link, '?stage=' . Versioned::DRAFT), 'type' => $stage->getMimeType(), ]; } // Preview live if versioned if ($this->isVersioned()) { $live = $this->getObjectInStage(Versioned::LIVE); if ($live instanceof CMSPreviewable && $live->canView() && ($link = $live->PreviewLink())) { $links[Versioned::LIVE] = [ 'href' => Controller::join_links($link, '?stage=' . Versioned::LIVE), 'type' => $live->getMimeType(), ]; } } return $links; }
php
public function getPreviewLinks() { $links = []; // Preview draft $stage = $this->getObjectInStage(Versioned::DRAFT); if ($stage instanceof CMSPreviewable && $stage->canView() && ($link = $stage->PreviewLink())) { $links[Versioned::DRAFT] = [ 'href' => Controller::join_links($link, '?stage=' . Versioned::DRAFT), 'type' => $stage->getMimeType(), ]; } // Preview live if versioned if ($this->isVersioned()) { $live = $this->getObjectInStage(Versioned::LIVE); if ($live instanceof CMSPreviewable && $live->canView() && ($link = $live->PreviewLink())) { $links[Versioned::LIVE] = [ 'href' => Controller::join_links($link, '?stage=' . Versioned::LIVE), 'type' => $live->getMimeType(), ]; } } return $links; }
[ "public", "function", "getPreviewLinks", "(", ")", "{", "$", "links", "=", "[", "]", ";", "// Preview draft", "$", "stage", "=", "$", "this", "->", "getObjectInStage", "(", "Versioned", "::", "DRAFT", ")", ";", "if", "(", "$", "stage", "instanceof", "CMS...
Gets the list of modes this record can be previewed in. {@link https://tools.ietf.org/html/draft-kelly-json-hal-07#section-5} @return array Map of links in acceptable HAL format
[ "Gets", "the", "list", "of", "modes", "this", "record", "can", "be", "previewed", "in", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L509-L534
43,056
silverstripe/silverstripe-versioned
src/ChangeSetItem.php
ChangeSetItem.CMSEditLink
public function CMSEditLink() { $link = $this->getObjectInStage(Versioned::DRAFT); if ($link instanceof CMSPreviewable) { return $link->CMSEditLink(); } return null; }
php
public function CMSEditLink() { $link = $this->getObjectInStage(Versioned::DRAFT); if ($link instanceof CMSPreviewable) { return $link->CMSEditLink(); } return null; }
[ "public", "function", "CMSEditLink", "(", ")", "{", "$", "link", "=", "$", "this", "->", "getObjectInStage", "(", "Versioned", "::", "DRAFT", ")", ";", "if", "(", "$", "link", "instanceof", "CMSPreviewable", ")", "{", "return", "$", "link", "->", "CMSEdi...
Get edit link for this item @return string
[ "Get", "edit", "link", "for", "this", "item" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L541-L548
43,057
silverstripe/silverstripe-versioned
src/ChangeSetItem.php
ChangeSetItem.isVersioned
public function isVersioned() { if (!$this->ObjectClass || !class_exists($this->ObjectClass)) { return false; } /** @var Versioned|DataObject $singleton */ $singleton = DataObject::singleton($this->ObjectClass); return $singleton->hasExtension(Versioned::class) && $singleton->hasStages(); }
php
public function isVersioned() { if (!$this->ObjectClass || !class_exists($this->ObjectClass)) { return false; } /** @var Versioned|DataObject $singleton */ $singleton = DataObject::singleton($this->ObjectClass); return $singleton->hasExtension(Versioned::class) && $singleton->hasStages(); }
[ "public", "function", "isVersioned", "(", ")", "{", "if", "(", "!", "$", "this", "->", "ObjectClass", "||", "!", "class_exists", "(", "$", "this", "->", "ObjectClass", ")", ")", "{", "return", "false", ";", "}", "/** @var Versioned|DataObject $singleton */", ...
Check if the object attached to this changesetitem is versionable @return bool
[ "Check", "if", "the", "object", "attached", "to", "this", "changesetitem", "is", "versionable" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/ChangeSetItem.php#L555-L563
43,058
silverstripe/silverstripe-versioned
src/GraphQL/Extensions/ManagerExtension.php
ManagerExtension.updateConfig
public function updateConfig(&$config) { if (!isset($config['types'])) { $config['types'] = []; } $config['types']['VersionedStage'] = VersionedStage::class; $config['types']['VersionedStatus'] = VersionedStatus::class; $config['types']['VersionedQueryMode'] = VersionedQueryMode::class; $config['types']['VersionedInputType'] = VersionedInputType::class; $config['types']['CopyToStageInputType'] = CopyToStageInputType::class; }
php
public function updateConfig(&$config) { if (!isset($config['types'])) { $config['types'] = []; } $config['types']['VersionedStage'] = VersionedStage::class; $config['types']['VersionedStatus'] = VersionedStatus::class; $config['types']['VersionedQueryMode'] = VersionedQueryMode::class; $config['types']['VersionedInputType'] = VersionedInputType::class; $config['types']['CopyToStageInputType'] = CopyToStageInputType::class; }
[ "public", "function", "updateConfig", "(", "&", "$", "config", ")", "{", "if", "(", "!", "isset", "(", "$", "config", "[", "'types'", "]", ")", ")", "{", "$", "config", "[", "'types'", "]", "=", "[", "]", ";", "}", "$", "config", "[", "'types'", ...
Adds the versioned types to all schemas @param $config
[ "Adds", "the", "versioned", "types", "to", "all", "schemas" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GraphQL/Extensions/ManagerExtension.php#L19-L30
43,059
silverstripe/silverstripe-versioned
src/Caching/ProxyCacheAdapter.php
ProxyCacheAdapter.getKeyIDs
protected function getKeyIDs($keys) { // Force iterator to array with simple temp array $map = []; foreach ($keys as $key) { $map[] = $this->getKeyID($key); } return $map; }
php
protected function getKeyIDs($keys) { // Force iterator to array with simple temp array $map = []; foreach ($keys as $key) { $map[] = $this->getKeyID($key); } return $map; }
[ "protected", "function", "getKeyIDs", "(", "$", "keys", ")", "{", "// Force iterator to array with simple temp array", "$", "map", "=", "[", "]", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "map", "[", "]", "=", "$", "this", "->", ...
Get key ids @param iterable $keys @return array Array where keys are passed in $keys, and values are key IDs
[ "Get", "key", "ids" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Caching/ProxyCacheAdapter.php#L163-L171
43,060
silverstripe/silverstripe-versioned
src/Caching/ProxyCacheAdapter.php
ProxyCacheAdapter.iteratorToArray
protected function iteratorToArray($keys) { // Already array if (is_array($keys)) { return $keys; } // Handle iterable if ($keys instanceof Traversable) { return iterator_to_array($keys, false); } // Error $keysType = is_object($keys) ? get_class($keys) : gettype($keys); throw new InvalidArgumentException("Cache keys must be array or Traversable, \"{$keysType}\" given"); }
php
protected function iteratorToArray($keys) { // Already array if (is_array($keys)) { return $keys; } // Handle iterable if ($keys instanceof Traversable) { return iterator_to_array($keys, false); } // Error $keysType = is_object($keys) ? get_class($keys) : gettype($keys); throw new InvalidArgumentException("Cache keys must be array or Traversable, \"{$keysType}\" given"); }
[ "protected", "function", "iteratorToArray", "(", "$", "keys", ")", "{", "// Already array", "if", "(", "is_array", "(", "$", "keys", ")", ")", "{", "return", "$", "keys", ";", "}", "// Handle iterable", "if", "(", "$", "keys", "instanceof", "Traversable", ...
Ensure that a list is cast to an array @param iterable $keys @return array
[ "Ensure", "that", "a", "list", "is", "cast", "to", "an", "array" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Caching/ProxyCacheAdapter.php#L179-L194
43,061
silverstripe/silverstripe-versioned
src/GraphQL/Extensions/SchemaScaffolderExtension.php
SchemaScaffolderExtension.onBeforeAddToManager
public function onBeforeAddToManager(Manager $manager) { $memberType = StaticSchema::inst()->typeNameForDataObject(Member::class); if ($manager->hasType($memberType)) { return; } /* @var SchemaScaffolder $owner */ $owner = $this->owner; foreach ($owner->getTypes() as $scaffold) { if ($scaffold->getDataObjectInstance()->hasExtension(Versioned::class)) { $owner->type(Member::class); break; } } }
php
public function onBeforeAddToManager(Manager $manager) { $memberType = StaticSchema::inst()->typeNameForDataObject(Member::class); if ($manager->hasType($memberType)) { return; } /* @var SchemaScaffolder $owner */ $owner = $this->owner; foreach ($owner->getTypes() as $scaffold) { if ($scaffold->getDataObjectInstance()->hasExtension(Versioned::class)) { $owner->type(Member::class); break; } } }
[ "public", "function", "onBeforeAddToManager", "(", "Manager", "$", "manager", ")", "{", "$", "memberType", "=", "StaticSchema", "::", "inst", "(", ")", "->", "typeNameForDataObject", "(", "Member", "::", "class", ")", ";", "if", "(", "$", "manager", "->", ...
If any types are using Versioned, make sure Member is added as a type. Because the Versioned_Version object is just ViewableData, it has to be added explicitly. @param Manager $manager
[ "If", "any", "types", "are", "using", "Versioned", "make", "sure", "Member", "is", "added", "as", "a", "type", ".", "Because", "the", "Versioned_Version", "object", "is", "just", "ViewableData", "it", "has", "to", "be", "added", "explicitly", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GraphQL/Extensions/SchemaScaffolderExtension.php#L20-L36
43,062
silverstripe/silverstripe-versioned
src/GridFieldRestoreAction.php
GridFieldRestoreAction.getRestoreAction
public function getRestoreAction($gridField, $record, $columnName) { $canRestoreToDraft = $record->canRestoreToDraft(); if ($canRestoreToDraft) { $restoreToRoot = RestoreAction::shouldRestoreToRoot($record); $title = $restoreToRoot ? _t('SilverStripe\\Versioned\\RestoreAction.RESTORE_TO_ROOT', 'Restore to draft at top level') : _t('SilverStripe\\Versioned\\RestoreAction.RESTORE', 'Restore to draft'); $description = $restoreToRoot ? _t('SilverStripe\\Versioned\\RestoreAction.RESTORE_TO_ROOT_DESC', 'Restore the archived version to draft as a top level item') : _t('SilverStripe\\Versioned\\RestoreAction.RESTORE_DESC', 'Restore the archived version to draft'); $field = GridField_FormAction::create( $gridField, 'Restore' . $record->ID, false, "restore", ['RecordID' => $record->ID] ) ->addExtraClass('btn btn--no-text btn--icon-md font-icon-back-in-time grid-field__icon-action action-menu--handled action-restore') ->setAttribute('classNames', 'font-icon-back-in-time action-restore') ->setAttribute('data-to-root', $restoreToRoot) ->setDescription($description) ->setAttribute('aria-label', $title); } return isset($field) ? $field : null; }
php
public function getRestoreAction($gridField, $record, $columnName) { $canRestoreToDraft = $record->canRestoreToDraft(); if ($canRestoreToDraft) { $restoreToRoot = RestoreAction::shouldRestoreToRoot($record); $title = $restoreToRoot ? _t('SilverStripe\\Versioned\\RestoreAction.RESTORE_TO_ROOT', 'Restore to draft at top level') : _t('SilverStripe\\Versioned\\RestoreAction.RESTORE', 'Restore to draft'); $description = $restoreToRoot ? _t('SilverStripe\\Versioned\\RestoreAction.RESTORE_TO_ROOT_DESC', 'Restore the archived version to draft as a top level item') : _t('SilverStripe\\Versioned\\RestoreAction.RESTORE_DESC', 'Restore the archived version to draft'); $field = GridField_FormAction::create( $gridField, 'Restore' . $record->ID, false, "restore", ['RecordID' => $record->ID] ) ->addExtraClass('btn btn--no-text btn--icon-md font-icon-back-in-time grid-field__icon-action action-menu--handled action-restore') ->setAttribute('classNames', 'font-icon-back-in-time action-restore') ->setAttribute('data-to-root', $restoreToRoot) ->setDescription($description) ->setAttribute('aria-label', $title); } return isset($field) ? $field : null; }
[ "public", "function", "getRestoreAction", "(", "$", "gridField", ",", "$", "record", ",", "$", "columnName", ")", "{", "$", "canRestoreToDraft", "=", "$", "record", "->", "canRestoreToDraft", "(", ")", ";", "if", "(", "$", "canRestoreToDraft", ")", "{", "$...
Creates a restore action if the action is able to be preformed @param GridField $gridField @param DataObject $record @param string $columnName @return GridField_FormAction|null
[ "Creates", "a", "restore", "action", "if", "the", "action", "is", "able", "to", "be", "preformed" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GridFieldRestoreAction.php#L121-L150
43,063
silverstripe/silverstripe-versioned
src/GridFieldRestoreAction.php
GridFieldRestoreAction.handleAction
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { if ($actionName == 'restore') { /** @var DataObject $item */ $item = $gridField->getList()->byID($arguments['RecordID']); if (!$item) { return; } $message = RestoreAction::restore($item); // If this is handled in a form context then show a message if ($message && $controller = $gridField->form->controller) { $controller->getResponse()->addHeader('X-Message-Text', $message['text']); $controller->getResponse()->addHeader('X-Message-Type', $message['type']); } $gridField->getList()->remove($item); } }
php
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { if ($actionName == 'restore') { /** @var DataObject $item */ $item = $gridField->getList()->byID($arguments['RecordID']); if (!$item) { return; } $message = RestoreAction::restore($item); // If this is handled in a form context then show a message if ($message && $controller = $gridField->form->controller) { $controller->getResponse()->addHeader('X-Message-Text', $message['text']); $controller->getResponse()->addHeader('X-Message-Type', $message['type']); } $gridField->getList()->remove($item); } }
[ "public", "function", "handleAction", "(", "GridField", "$", "gridField", ",", "$", "actionName", ",", "$", "arguments", ",", "$", "data", ")", "{", "if", "(", "$", "actionName", "==", "'restore'", ")", "{", "/** @var DataObject $item */", "$", "item", "=", ...
Handle the actions and apply any changes to the GridField. @param GridField $gridField @param string $actionName @param mixed $arguments @param array $data - form data @return void
[ "Handle", "the", "actions", "and", "apply", "any", "changes", "to", "the", "GridField", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GridFieldRestoreAction.php#L175-L194
43,064
silverstripe/silverstripe-versioned
src/RestoreAction.php
RestoreAction.shouldRestoreToRoot
public static function shouldRestoreToRoot($record) { // If the record had a parent and that no longer exists in draft then yes if ($record->hasExtension(Hierarchy::class) && $record->ParentID != false) { return $record->getParent() === null; } // Otherwise it should be restored normally return false; }
php
public static function shouldRestoreToRoot($record) { // If the record had a parent and that no longer exists in draft then yes if ($record->hasExtension(Hierarchy::class) && $record->ParentID != false) { return $record->getParent() === null; } // Otherwise it should be restored normally return false; }
[ "public", "static", "function", "shouldRestoreToRoot", "(", "$", "record", ")", "{", "// If the record had a parent and that no longer exists in draft then yes", "if", "(", "$", "record", "->", "hasExtension", "(", "Hierarchy", "::", "class", ")", "&&", "$", "record", ...
Determines whether this record can be restored to it's original location @param $record @return bool
[ "Determines", "whether", "this", "record", "can", "be", "restored", "to", "it", "s", "original", "location" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RestoreAction.php#L157-L166
43,065
silverstripe/silverstripe-versioned
src/GraphQL/Resolvers/ApplyVersionFilters.php
ApplyVersionFilters.isValidDate
protected function isValidDate($date) { $dt = DateTime::createFromFormat('Y-m-d', $date); return ($dt !== false && !array_sum($dt->getLastErrors())); }
php
protected function isValidDate($date) { $dt = DateTime::createFromFormat('Y-m-d', $date); return ($dt !== false && !array_sum($dt->getLastErrors())); }
[ "protected", "function", "isValidDate", "(", "$", "date", ")", "{", "$", "dt", "=", "DateTime", "::", "createFromFormat", "(", "'Y-m-d'", ",", "$", "date", ")", ";", "return", "(", "$", "dt", "!==", "false", "&&", "!", "array_sum", "(", "$", "dt", "-...
Returns true if date is in proper YYYY-MM-DD format @param string $date @return bool
[ "Returns", "true", "if", "date", "is", "in", "proper", "YYYY", "-", "MM", "-", "DD", "format" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GraphQL/Resolvers/ApplyVersionFilters.php#L144-L149
43,066
silverstripe/silverstripe-versioned
src/RecursivePublishable.php
RecursivePublishable.publishRecursive
public function publishRecursive() { // Create a new changeset for this item and publish it $changeset = ChangeSet::create(); $changeset->IsInferred = true; $changeset->Name = _t( __CLASS__ . '.INFERRED_TITLE', "Generated by publish of '{title}' at {created}", [ 'title' => $this->owner->Title, 'created' => DBDatetime::now()->Nice() ] ); $changeset->write(); $changeset->addObject($this->owner); return $changeset->publish(true); }
php
public function publishRecursive() { // Create a new changeset for this item and publish it $changeset = ChangeSet::create(); $changeset->IsInferred = true; $changeset->Name = _t( __CLASS__ . '.INFERRED_TITLE', "Generated by publish of '{title}' at {created}", [ 'title' => $this->owner->Title, 'created' => DBDatetime::now()->Nice() ] ); $changeset->write(); $changeset->addObject($this->owner); return $changeset->publish(true); }
[ "public", "function", "publishRecursive", "(", ")", "{", "// Create a new changeset for this item and publish it", "$", "changeset", "=", "ChangeSet", "::", "create", "(", ")", ";", "$", "changeset", "->", "IsInferred", "=", "true", ";", "$", "changeset", "->", "N...
Publish this object and all owned objects to Live @return bool
[ "Publish", "this", "object", "and", "all", "owned", "objects", "to", "Live" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RecursivePublishable.php#L58-L74
43,067
silverstripe/silverstripe-versioned
src/RecursivePublishable.php
RecursivePublishable.rollbackRelations
public function rollbackRelations($version) { $owner = $this->owner; // Rollback recursively foreach ($owner->findOwned(false) as $object) { if ($object->hasExtension(Versioned::class)) { // Pass in null to rollback to self version /** @var Versioned $object */ $object->rollbackRecursive(null); } else { // Rollback unversioned record (inherits parent query parameters) $object->rollbackRelations($version); } } }
php
public function rollbackRelations($version) { $owner = $this->owner; // Rollback recursively foreach ($owner->findOwned(false) as $object) { if ($object->hasExtension(Versioned::class)) { // Pass in null to rollback to self version /** @var Versioned $object */ $object->rollbackRecursive(null); } else { // Rollback unversioned record (inherits parent query parameters) $object->rollbackRelations($version); } } }
[ "public", "function", "rollbackRelations", "(", "$", "version", ")", "{", "$", "owner", "=", "$", "this", "->", "owner", ";", "// Rollback recursively", "foreach", "(", "$", "owner", "->", "findOwned", "(", "false", ")", "as", "$", "object", ")", "{", "i...
Rollback all related objects on this stage. Note: This method should be called on the source object queried in the appropriate "from" for this rollback, as it will rely on the parent object's query parameters to return nested objects. @internal Do not call this directly! This should only be invoked by Versioned::rollbackRecursive() @param int|string $version Parent version / stage to rollback from
[ "Rollback", "all", "related", "objects", "on", "this", "stage", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RecursivePublishable.php#L86-L100
43,068
silverstripe/silverstripe-versioned
src/RecursivePublishable.php
RecursivePublishable.deleteFromChangeSets
public function deleteFromChangeSets() { $changeSetIDs = []; // Remove all ChangeSetItems matching this record /** @var ChangeSetItem $changeSetItem */ foreach (ChangeSetItem::get_for_object($this->owner) as $changeSetItem) { $changeSetIDs[$changeSetItem->ChangeSetID] = $changeSetItem->ChangeSetID; $changeSetItem->delete(); } // Sync all affected changesets if ($changeSetIDs) { /** @var ChangeSet $changeSet */ foreach (ChangeSet::get()->byIDs($changeSetIDs) as $changeSet) { $changeSet->sync(); } } return true; }
php
public function deleteFromChangeSets() { $changeSetIDs = []; // Remove all ChangeSetItems matching this record /** @var ChangeSetItem $changeSetItem */ foreach (ChangeSetItem::get_for_object($this->owner) as $changeSetItem) { $changeSetIDs[$changeSetItem->ChangeSetID] = $changeSetItem->ChangeSetID; $changeSetItem->delete(); } // Sync all affected changesets if ($changeSetIDs) { /** @var ChangeSet $changeSet */ foreach (ChangeSet::get()->byIDs($changeSetIDs) as $changeSet) { $changeSet->sync(); } } return true; }
[ "public", "function", "deleteFromChangeSets", "(", ")", "{", "$", "changeSetIDs", "=", "[", "]", ";", "// Remove all ChangeSetItems matching this record", "/** @var ChangeSetItem $changeSetItem */", "foreach", "(", "ChangeSetItem", "::", "get_for_object", "(", "$", "this", ...
Remove this item from any changesets @return bool
[ "Remove", "this", "item", "from", "any", "changesets" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RecursivePublishable.php#L107-L126
43,069
silverstripe/silverstripe-versioned
src/RecursivePublishable.php
RecursivePublishable.findOwned
public function findOwned($recursive = true, $list = null) { // Find objects in these relationships return $this->owner->findRelatedObjects('owns', $recursive, $list); }
php
public function findOwned($recursive = true, $list = null) { // Find objects in these relationships return $this->owner->findRelatedObjects('owns', $recursive, $list); }
[ "public", "function", "findOwned", "(", "$", "recursive", "=", "true", ",", "$", "list", "=", "null", ")", "{", "// Find objects in these relationships", "return", "$", "this", "->", "owner", "->", "findRelatedObjects", "(", "'owns'", ",", "$", "recursive", ",...
Find all objects owned by the current object. Note that objects will only be searched in the same stage as the given record. @param bool $recursive True if recursive @param ArrayList $list Optional list to add items to @return ArrayList list of objects
[ "Find", "all", "objects", "owned", "by", "the", "current", "object", ".", "Note", "that", "objects", "will", "only", "be", "searched", "in", "the", "same", "stage", "as", "the", "given", "record", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RecursivePublishable.php#L136-L140
43,070
silverstripe/silverstripe-versioned
src/RecursivePublishable.php
RecursivePublishable.hasOwned
public function hasOwned() { if (!$this->owner->isInDB()) { return false; } $ownedRelationships = $this->owner->config()->get('owns') ?: []; foreach ($ownedRelationships as $relationship) { /* @var DataObject|SS_List $result */ $result = $this->owner->{$relationship}(); if ($result->exists()) { return true; } } return false; }
php
public function hasOwned() { if (!$this->owner->isInDB()) { return false; } $ownedRelationships = $this->owner->config()->get('owns') ?: []; foreach ($ownedRelationships as $relationship) { /* @var DataObject|SS_List $result */ $result = $this->owner->{$relationship}(); if ($result->exists()) { return true; } } return false; }
[ "public", "function", "hasOwned", "(", ")", "{", "if", "(", "!", "$", "this", "->", "owner", "->", "isInDB", "(", ")", ")", "{", "return", "false", ";", "}", "$", "ownedRelationships", "=", "$", "this", "->", "owner", "->", "config", "(", ")", "->"...
Returns true if the record has any owned relationships that exist @return bool
[ "Returns", "true", "if", "the", "record", "has", "any", "owned", "relationships", "that", "exist" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RecursivePublishable.php#L146-L162
43,071
silverstripe/silverstripe-versioned
src/RecursivePublishable.php
RecursivePublishable.lookupReverseOwners
protected function lookupReverseOwners() { // Find all classes with 'owns' config $lookup = []; $classes = ClassInfo::subclassesFor(DataObject::class); array_shift($classes); // skip DataObject foreach ($classes as $class) { // Ensure this class is RecursivePublishable if (!DataObject::has_extension($class, static::class)) { continue; } // Check owned objects for this class $owns = Config::inst()->get($class, 'owns', Config::UNINHERITED); if (empty($owns)) { continue; } $instance = DataObject::singleton($class); foreach ($owns as $owned) { // Find owned class $ownedClass = $instance->getRelationClass($owned); // Skip custom methods that don't have db relations, or cannot be inferred if (!$ownedClass || $ownedClass === DataObject::class) { continue; } // Add lookup for owned class if (!isset($lookup[$ownedClass])) { $lookup[$ownedClass] = []; } $lookup[$ownedClass][] = [ 'class' => $class, 'relation' => $owned ]; } } return $lookup; }
php
protected function lookupReverseOwners() { // Find all classes with 'owns' config $lookup = []; $classes = ClassInfo::subclassesFor(DataObject::class); array_shift($classes); // skip DataObject foreach ($classes as $class) { // Ensure this class is RecursivePublishable if (!DataObject::has_extension($class, static::class)) { continue; } // Check owned objects for this class $owns = Config::inst()->get($class, 'owns', Config::UNINHERITED); if (empty($owns)) { continue; } $instance = DataObject::singleton($class); foreach ($owns as $owned) { // Find owned class $ownedClass = $instance->getRelationClass($owned); // Skip custom methods that don't have db relations, or cannot be inferred if (!$ownedClass || $ownedClass === DataObject::class) { continue; } // Add lookup for owned class if (!isset($lookup[$ownedClass])) { $lookup[$ownedClass] = []; } $lookup[$ownedClass][] = [ 'class' => $class, 'relation' => $owned ]; } } return $lookup; }
[ "protected", "function", "lookupReverseOwners", "(", ")", "{", "// Find all classes with 'owns' config", "$", "lookup", "=", "[", "]", ";", "$", "classes", "=", "ClassInfo", "::", "subclassesFor", "(", "DataObject", "::", "class", ")", ";", "array_shift", "(", "...
Find a list of classes, each of which with a list of methods to invoke to lookup owners. @return array
[ "Find", "a", "list", "of", "classes", "each", "of", "which", "with", "a", "list", "of", "methods", "to", "invoke", "to", "lookup", "owners", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RecursivePublishable.php#L239-L277
43,072
silverstripe/silverstripe-versioned
src/RecursivePublishable.php
RecursivePublishable.onBeforeDuplicate
public function onBeforeDuplicate($original, &$doWrite, &$relations) { // If relations to duplicate are declared (or forced off) don't rewrite if ($relations || $relations === false) { return; } // Only duplicate owned relationships that are either exclusively owned, // or require additional writes. Also exclude any custom non-relation ownerships. $allowed = array_merge( array_keys($this->owner->manyMany()), // Require mapping table duplications array_keys($this->owner->belongsTo()), // Exclusive record must be duplicated array_keys($this->owner->hasMany()) // Exclusive records should be duplicated ); // Note: don't assume that owned has_one needs duplication, as these can be // shared non-exclusively by both clone and original. // Get candidates from ownership and intersect $owns = $this->owner->config()->get('owns'); $relations = array_intersect($allowed, $owns); }
php
public function onBeforeDuplicate($original, &$doWrite, &$relations) { // If relations to duplicate are declared (or forced off) don't rewrite if ($relations || $relations === false) { return; } // Only duplicate owned relationships that are either exclusively owned, // or require additional writes. Also exclude any custom non-relation ownerships. $allowed = array_merge( array_keys($this->owner->manyMany()), // Require mapping table duplications array_keys($this->owner->belongsTo()), // Exclusive record must be duplicated array_keys($this->owner->hasMany()) // Exclusive records should be duplicated ); // Note: don't assume that owned has_one needs duplication, as these can be // shared non-exclusively by both clone and original. // Get candidates from ownership and intersect $owns = $this->owner->config()->get('owns'); $relations = array_intersect($allowed, $owns); }
[ "public", "function", "onBeforeDuplicate", "(", "$", "original", ",", "&", "$", "doWrite", ",", "&", "$", "relations", ")", "{", "// If relations to duplicate are declared (or forced off) don't rewrite", "if", "(", "$", "relations", "||", "$", "relations", "===", "f...
If `cascade_duplications` is empty, default to `owns` config @param DataObject $original @param bool $doWrite @param array|null|false $relations
[ "If", "cascade_duplications", "is", "empty", "default", "to", "owns", "config" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/RecursivePublishable.php#L404-L423
43,073
silverstripe/silverstripe-versioned
src/GridFieldArchiveAction.php
GridFieldArchiveAction.augmentColumns
public function augmentColumns($gridField, &$columns) { $model = $gridField->getModelClass(); $isModelVersioned = $model::has_extension(Versioned::class); if ($isModelVersioned) { $gridField->getConfig()->removeComponentsByType(GridFieldDeleteAction::class); } if (!in_array('Actions', $columns)) { $columns[] = 'Actions'; } }
php
public function augmentColumns($gridField, &$columns) { $model = $gridField->getModelClass(); $isModelVersioned = $model::has_extension(Versioned::class); if ($isModelVersioned) { $gridField->getConfig()->removeComponentsByType(GridFieldDeleteAction::class); } if (!in_array('Actions', $columns)) { $columns[] = 'Actions'; } }
[ "public", "function", "augmentColumns", "(", "$", "gridField", ",", "&", "$", "columns", ")", "{", "$", "model", "=", "$", "gridField", "->", "getModelClass", "(", ")", ";", "$", "isModelVersioned", "=", "$", "model", "::", "has_extension", "(", "Versioned...
Add a column 'Actions' @param GridField $gridField @param array $columns
[ "Add", "a", "column", "Actions" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GridFieldArchiveAction.php#L71-L81
43,074
silverstripe/silverstripe-versioned
src/GridFieldArchiveAction.php
GridFieldArchiveAction.getArchiveAction
public function getArchiveAction($gridField, $record) { /* @var DataObject|Versioned $record */ if (!$record->hasMethod('canArchive') || !$record->canArchive()) { return null; } $title = _t(__CLASS__ . '.Archive', "Archive"); $field = GridField_FormAction::create( $gridField, 'ArchiveRecord' . $record->ID, false, "archiverecord", ['RecordID' => $record->ID] ) ->addExtraClass('action--archive btn--icon-md font-icon-box btn--no-text grid-field__icon-action action-menu--handled') ->setAttribute('classNames', 'action--archive font-icon-box') ->setDescription($title) ->setAttribute('aria-label', $title); return $field; }
php
public function getArchiveAction($gridField, $record) { /* @var DataObject|Versioned $record */ if (!$record->hasMethod('canArchive') || !$record->canArchive()) { return null; } $title = _t(__CLASS__ . '.Archive', "Archive"); $field = GridField_FormAction::create( $gridField, 'ArchiveRecord' . $record->ID, false, "archiverecord", ['RecordID' => $record->ID] ) ->addExtraClass('action--archive btn--icon-md font-icon-box btn--no-text grid-field__icon-action action-menu--handled') ->setAttribute('classNames', 'action--archive font-icon-box') ->setDescription($title) ->setAttribute('aria-label', $title); return $field; }
[ "public", "function", "getArchiveAction", "(", "$", "gridField", ",", "$", "record", ")", "{", "/* @var DataObject|Versioned $record */", "if", "(", "!", "$", "record", "->", "hasMethod", "(", "'canArchive'", ")", "||", "!", "$", "record", "->", "canArchive", ...
Returns the GridField_FormAction if archive can be performed @param GridField $gridField @param DataObject $record @return GridField_FormAction|null
[ "Returns", "the", "GridField_FormAction", "if", "archive", "can", "be", "performed" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GridFieldArchiveAction.php#L187-L209
43,075
silverstripe/silverstripe-versioned
src/GraphQL/Extensions/DataObjectScaffolderExtension.php
DataObjectScaffolderExtension.onBeforeAddToManager
public function onBeforeAddToManager(Manager $manager) { /* @var DataObjectScaffolder $owner */ $owner = $this->owner; $memberType = StaticSchema::inst()->typeNameForDataObject(Member::class); $instance = $owner->getDataObjectInstance(); $class = $owner->getDataObjectClass(); if (!$instance->hasExtension(Versioned::class)) { return; } /* @var ObjectType $rawType */ $rawType = $owner->scaffold($manager); $versionName = $this->createVersionedTypeName($class); $coreFieldsFn = $rawType->config['fields']; // Create the "version" type for this dataobject. Takes the original fields // and augments them with the Versioned_Version specific fields $versionType = new ObjectType([ 'name' => $versionName, 'fields' => function () use ($coreFieldsFn, $manager, $memberType) { $coreFields = $coreFieldsFn(); $versionFields = [ 'Author' => [ 'type' => $manager->getType($memberType), 'resolve' => function ($obj) { return $obj->Author(); } ], 'Publisher' => [ 'type' => $manager->getType($memberType), 'resolve' => function ($obj) { return $obj->Publisher(); } ], 'Published' => [ 'type' => Type::boolean(), 'resolve' => function ($obj) { return $obj->WasPublished; } ], 'LiveVersion' => [ 'type' => Type::boolean(), 'resolve' => function ($obj) { return $obj->isLiveVersion(); } ], 'LatestDraftVersion' => [ 'type' => Type::boolean(), 'resolve' => function ($obj) { return $obj->isLatestDraftVersion(); } ], ]; // Remove this recursive madness. unset($coreFields['Versions']); return array_merge($coreFields, $versionFields); } ]); $manager->addType($versionType, $versionName); // With the version type in the manager now, add the versioning fields to the dataobject type $owner ->addFields(['Version']) ->nestedQuery('Versions', new ReadVersions($class, $versionName)); }
php
public function onBeforeAddToManager(Manager $manager) { /* @var DataObjectScaffolder $owner */ $owner = $this->owner; $memberType = StaticSchema::inst()->typeNameForDataObject(Member::class); $instance = $owner->getDataObjectInstance(); $class = $owner->getDataObjectClass(); if (!$instance->hasExtension(Versioned::class)) { return; } /* @var ObjectType $rawType */ $rawType = $owner->scaffold($manager); $versionName = $this->createVersionedTypeName($class); $coreFieldsFn = $rawType->config['fields']; // Create the "version" type for this dataobject. Takes the original fields // and augments them with the Versioned_Version specific fields $versionType = new ObjectType([ 'name' => $versionName, 'fields' => function () use ($coreFieldsFn, $manager, $memberType) { $coreFields = $coreFieldsFn(); $versionFields = [ 'Author' => [ 'type' => $manager->getType($memberType), 'resolve' => function ($obj) { return $obj->Author(); } ], 'Publisher' => [ 'type' => $manager->getType($memberType), 'resolve' => function ($obj) { return $obj->Publisher(); } ], 'Published' => [ 'type' => Type::boolean(), 'resolve' => function ($obj) { return $obj->WasPublished; } ], 'LiveVersion' => [ 'type' => Type::boolean(), 'resolve' => function ($obj) { return $obj->isLiveVersion(); } ], 'LatestDraftVersion' => [ 'type' => Type::boolean(), 'resolve' => function ($obj) { return $obj->isLatestDraftVersion(); } ], ]; // Remove this recursive madness. unset($coreFields['Versions']); return array_merge($coreFields, $versionFields); } ]); $manager->addType($versionType, $versionName); // With the version type in the manager now, add the versioning fields to the dataobject type $owner ->addFields(['Version']) ->nestedQuery('Versions', new ReadVersions($class, $versionName)); }
[ "public", "function", "onBeforeAddToManager", "(", "Manager", "$", "manager", ")", "{", "/* @var DataObjectScaffolder $owner */", "$", "owner", "=", "$", "this", "->", "owner", ";", "$", "memberType", "=", "StaticSchema", "::", "inst", "(", ")", "->", "typeNameF...
Adds the "Version" and "Versions" fields to any dataobject that has the Versioned extension. @param Manager $manager
[ "Adds", "the", "Version", "and", "Versions", "fields", "to", "any", "dataobject", "that", "has", "the", "Versioned", "extension", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/GraphQL/Extensions/DataObjectScaffolderExtension.php#L21-L87
43,076
silverstripe/silverstripe-versioned
src/Caching/VersionedCacheAdapter.php
VersionedCacheAdapter.getKeyID
protected function getKeyID($key) { $state = Versioned::get_reading_mode(); if ($state) { return $key . '_' . md5($state); } return $key; }
php
protected function getKeyID($key) { $state = Versioned::get_reading_mode(); if ($state) { return $key . '_' . md5($state); } return $key; }
[ "protected", "function", "getKeyID", "(", "$", "key", ")", "{", "$", "state", "=", "Versioned", "::", "get_reading_mode", "(", ")", ";", "if", "(", "$", "state", ")", "{", "return", "$", "key", ".", "'_'", ".", "md5", "(", "$", "state", ")", ";", ...
Ensure keys are segmented based on reading mode @param string $key @return string
[ "Ensure", "keys", "are", "segmented", "based", "on", "reading", "mode" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Caching/VersionedCacheAdapter.php#L16-L23
43,077
silverstripe/silverstripe-versioned
src/VersionedStateExtension.php
VersionedStateExtension.updateLink
public function updateLink(&$link) { // Skip if link already contains reading mode if ($this->hasVersionedQuery($link)) { return; } // Skip if current mode matches default mode // See LeftAndMain::init() for example of this being overridden. $readingMode = $this->getReadingmode(); if ($readingMode === Versioned::get_default_reading_mode()) { return; } // Determine if query args are supported for the current mode $queryargs = ReadingMode::toQueryString($readingMode); if (!$queryargs) { return; } // Don't touch Admin/CMS links if (class_exists(LeftAndMain::class) && $this->getOwner() instanceof LeftAndMain) { return; } // Decorate $link = Controller::join_links( $link, '?' . http_build_query($queryargs) ); }
php
public function updateLink(&$link) { // Skip if link already contains reading mode if ($this->hasVersionedQuery($link)) { return; } // Skip if current mode matches default mode // See LeftAndMain::init() for example of this being overridden. $readingMode = $this->getReadingmode(); if ($readingMode === Versioned::get_default_reading_mode()) { return; } // Determine if query args are supported for the current mode $queryargs = ReadingMode::toQueryString($readingMode); if (!$queryargs) { return; } // Don't touch Admin/CMS links if (class_exists(LeftAndMain::class) && $this->getOwner() instanceof LeftAndMain) { return; } // Decorate $link = Controller::join_links( $link, '?' . http_build_query($queryargs) ); }
[ "public", "function", "updateLink", "(", "&", "$", "link", ")", "{", "// Skip if link already contains reading mode", "if", "(", "$", "this", "->", "hasVersionedQuery", "(", "$", "link", ")", ")", "{", "return", ";", "}", "// Skip if current mode matches default mod...
Auto-append current stage if we're in draft, to avoid relying on session state for this, and the related potential of showing draft content without varying the URL itself. Assumes that if the user has access to view the current record in draft stage, they can also view other draft records. Does not concern itself with verifying permissions for performance reasons. This should also pull through to form actions. @param string $link
[ "Auto", "-", "append", "current", "stage", "if", "we", "re", "in", "draft", "to", "avoid", "relying", "on", "session", "state", "for", "this", "and", "the", "related", "potential", "of", "showing", "draft", "content", "without", "varying", "the", "URL", "i...
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedStateExtension.php#L32-L62
43,078
silverstripe/silverstripe-versioned
src/VersionedStateExtension.php
VersionedStateExtension.hasVersionedQuery
protected function hasVersionedQuery($link) { // Find querystrings $parts = explode('?', $link, 2); if (count($parts) < 2) { return false; } // Parse args $readingMode = ReadingMode::fromQueryString($parts[1]); return !empty($readingMode); }
php
protected function hasVersionedQuery($link) { // Find querystrings $parts = explode('?', $link, 2); if (count($parts) < 2) { return false; } // Parse args $readingMode = ReadingMode::fromQueryString($parts[1]); return !empty($readingMode); }
[ "protected", "function", "hasVersionedQuery", "(", "$", "link", ")", "{", "// Find querystrings", "$", "parts", "=", "explode", "(", "'?'", ",", "$", "link", ",", "2", ")", ";", "if", "(", "count", "(", "$", "parts", ")", "<", "2", ")", "{", "return"...
Check if link contains versioned queryargs @param string $link @return bool
[ "Check", "if", "link", "contains", "versioned", "queryargs" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/VersionedStateExtension.php#L70-L81
43,079
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.augmentDataQueryCreation
public function augmentDataQueryCreation(SQLSelect &$query, DataQuery &$dataQuery) { // Convert reading mode to dataquery params and assign $args = ReadingMode::toDataQueryParams(Versioned::get_reading_mode()); if ($args) { foreach ($args as $key => $value) { $dataQuery->setQueryParam($key, $value); } } }
php
public function augmentDataQueryCreation(SQLSelect &$query, DataQuery &$dataQuery) { // Convert reading mode to dataquery params and assign $args = ReadingMode::toDataQueryParams(Versioned::get_reading_mode()); if ($args) { foreach ($args as $key => $value) { $dataQuery->setQueryParam($key, $value); } } }
[ "public", "function", "augmentDataQueryCreation", "(", "SQLSelect", "&", "$", "query", ",", "DataQuery", "&", "$", "dataQuery", ")", "{", "// Convert reading mode to dataquery params and assign", "$", "args", "=", "ReadingMode", "::", "toDataQueryParams", "(", "Versione...
Amend freshly created DataQuery objects with versioned-specific information. @param SQLSelect $query @param DataQuery $dataQuery
[ "Amend", "freshly", "created", "DataQuery", "objects", "with", "versioned", "-", "specific", "information", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L304-L313
43,080
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.getAtVersion
public function getAtVersion($from) { // Null implies return current version if (is_null($from)) { return $this->owner; } $baseClass = $this->owner->baseClass(); $id = $this->owner->ID ?: $this->owner->OldID; // By version number if (is_numeric($from)) { return Versioned::get_version($baseClass, $id, $from); } // By stage return Versioned::get_by_stage($baseClass, $from)->byID($id); }
php
public function getAtVersion($from) { // Null implies return current version if (is_null($from)) { return $this->owner; } $baseClass = $this->owner->baseClass(); $id = $this->owner->ID ?: $this->owner->OldID; // By version number if (is_numeric($from)) { return Versioned::get_version($baseClass, $id, $from); } // By stage return Versioned::get_by_stage($baseClass, $from)->byID($id); }
[ "public", "function", "getAtVersion", "(", "$", "from", ")", "{", "// Null implies return current version", "if", "(", "is_null", "(", "$", "from", ")", ")", "{", "return", "$", "this", "->", "owner", ";", "}", "$", "baseClass", "=", "$", "this", "->", "...
Get this record at a specific version @param int|string|null $from Version or stage to get at. Null mean returns self object @return Versioned|DataObject
[ "Get", "this", "record", "at", "a", "specific", "version" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L346-L363
43,081
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.getLastEditedForVersion
protected function getLastEditedForVersion($version) { Deprecation::notice('5.0', 'Use getLastEditedAndStageForVersion instead'); $result = $this->getLastEditedAndStageForVersion($version); if ($result) { return reset($result); } return null; }
php
protected function getLastEditedForVersion($version) { Deprecation::notice('5.0', 'Use getLastEditedAndStageForVersion instead'); $result = $this->getLastEditedAndStageForVersion($version); if ($result) { return reset($result); } return null; }
[ "protected", "function", "getLastEditedForVersion", "(", "$", "version", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'Use getLastEditedAndStageForVersion instead'", ")", ";", "$", "result", "=", "$", "this", "->", "getLastEditedAndStageForVersion", "(...
Get modified date for the given version @deprecated 4.2..5.0 Use getLastEditedAndStageForVersion instead @param int $version @return string
[ "Get", "modified", "date", "for", "the", "given", "version" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L372-L380
43,082
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.getLastEditedAndStageForVersion
protected function getLastEditedAndStageForVersion($version) { // Cache key $baseTable = $this->baseTable(); $id = $this->owner->ID; $key = "{$baseTable}#{$id}/{$version}"; // Check cache if (isset($this->versionModifiedCache[$key])) { return $this->versionModifiedCache[$key]; } // Build query $table = "\"{$baseTable}_Versions\""; $query = SQLSelect::create(['"LastEdited"', '"WasPublished"'], $table) ->addWhere([ "{$table}.\"RecordID\"" => $id, "{$table}.\"Version\"" => $version ]); $result = $query->execute()->record(); if (!$result) { return null; } $list = [ $result['LastEdited'], $result['WasPublished'] ? static::LIVE : static::DRAFT, ]; $this->versionModifiedCache[$key] = $list; return $list; }
php
protected function getLastEditedAndStageForVersion($version) { // Cache key $baseTable = $this->baseTable(); $id = $this->owner->ID; $key = "{$baseTable}#{$id}/{$version}"; // Check cache if (isset($this->versionModifiedCache[$key])) { return $this->versionModifiedCache[$key]; } // Build query $table = "\"{$baseTable}_Versions\""; $query = SQLSelect::create(['"LastEdited"', '"WasPublished"'], $table) ->addWhere([ "{$table}.\"RecordID\"" => $id, "{$table}.\"Version\"" => $version ]); $result = $query->execute()->record(); if (!$result) { return null; } $list = [ $result['LastEdited'], $result['WasPublished'] ? static::LIVE : static::DRAFT, ]; $this->versionModifiedCache[$key] = $list; return $list; }
[ "protected", "function", "getLastEditedAndStageForVersion", "(", "$", "version", ")", "{", "// Cache key", "$", "baseTable", "=", "$", "this", "->", "baseTable", "(", ")", ";", "$", "id", "=", "$", "this", "->", "owner", "->", "ID", ";", "$", "key", "=",...
Get modified date and stage for the given version @param int $version @return array A list containing 0 => LastEdited, 1 => Stage
[ "Get", "modified", "date", "and", "stage", "for", "the", "given", "version" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L388-L417
43,083
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.updateInheritableQueryParams
public function updateInheritableQueryParams(&$params) { // Skip if versioned isn't set if (!isset($params['Versioned.mode'])) { return; } // Adjust query based on original selection criterea switch ($params['Versioned.mode']) { case 'all_versions': { // Versioned.mode === all_versions doesn't inherit very well, so default to stage $params['Versioned.mode'] = 'stage'; $params['Versioned.stage'] = static::DRAFT; break; } case 'version': { // If we selected this object from a specific version, we need // to find the date this version was published, and ensure // inherited queries select from that date. $version = $params['Versioned.version']; $dateAndStage = $this->getLastEditedAndStageForVersion($version); // Filter related objects at the same date as this version unset($params['Versioned.version']); if ($dateAndStage) { list($date, $stage) = $dateAndStage; $params['Versioned.mode'] = 'archive'; $params['Versioned.date'] = $date; $params['Versioned.stage'] = $stage; } else { // Fallback to default $params['Versioned.mode'] = 'stage'; $params['Versioned.stage'] = static::DRAFT; } break; } } }
php
public function updateInheritableQueryParams(&$params) { // Skip if versioned isn't set if (!isset($params['Versioned.mode'])) { return; } // Adjust query based on original selection criterea switch ($params['Versioned.mode']) { case 'all_versions': { // Versioned.mode === all_versions doesn't inherit very well, so default to stage $params['Versioned.mode'] = 'stage'; $params['Versioned.stage'] = static::DRAFT; break; } case 'version': { // If we selected this object from a specific version, we need // to find the date this version was published, and ensure // inherited queries select from that date. $version = $params['Versioned.version']; $dateAndStage = $this->getLastEditedAndStageForVersion($version); // Filter related objects at the same date as this version unset($params['Versioned.version']); if ($dateAndStage) { list($date, $stage) = $dateAndStage; $params['Versioned.mode'] = 'archive'; $params['Versioned.date'] = $date; $params['Versioned.stage'] = $stage; } else { // Fallback to default $params['Versioned.mode'] = 'stage'; $params['Versioned.stage'] = static::DRAFT; } break; } } }
[ "public", "function", "updateInheritableQueryParams", "(", "&", "$", "params", ")", "{", "// Skip if versioned isn't set", "if", "(", "!", "isset", "(", "$", "params", "[", "'Versioned.mode'", "]", ")", ")", "{", "return", ";", "}", "// Adjust query based on origi...
Updates query parameters of relations attached to versioned dataobjects @param array $params
[ "Updates", "query", "parameters", "of", "relations", "attached", "to", "versioned", "dataobjects" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L424-L463
43,084
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.augmentSQL
public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null) { // Ensure query mode exists $versionedMode = $dataQuery->getQueryParam('Versioned.mode'); if (!$versionedMode) { return; } switch ($versionedMode) { case 'stage': $this->augmentSQLStage($query, $dataQuery); break; case 'stage_unique': $this->augmentSQLStageUnique($query, $dataQuery); break; case 'archive': $this->augmentSQLVersionedArchive($query, $dataQuery); break; case 'latest_version_single': $this->augmentSQLVersionedLatestSingle($query, $dataQuery); break; case 'latest_versions': $this->augmentSQLVersionedLatest($query); break; case 'version': $this->augmentSQLVersionedVersion($query, $dataQuery); break; case 'all_versions': $this->augmentSQLVersionedAll($query); break; default: throw new InvalidArgumentException("Bad value for query parameter Versioned.mode: {$versionedMode}"); } }
php
public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null) { // Ensure query mode exists $versionedMode = $dataQuery->getQueryParam('Versioned.mode'); if (!$versionedMode) { return; } switch ($versionedMode) { case 'stage': $this->augmentSQLStage($query, $dataQuery); break; case 'stage_unique': $this->augmentSQLStageUnique($query, $dataQuery); break; case 'archive': $this->augmentSQLVersionedArchive($query, $dataQuery); break; case 'latest_version_single': $this->augmentSQLVersionedLatestSingle($query, $dataQuery); break; case 'latest_versions': $this->augmentSQLVersionedLatest($query); break; case 'version': $this->augmentSQLVersionedVersion($query, $dataQuery); break; case 'all_versions': $this->augmentSQLVersionedAll($query); break; default: throw new InvalidArgumentException("Bad value for query parameter Versioned.mode: {$versionedMode}"); } }
[ "public", "function", "augmentSQL", "(", "SQLSelect", "$", "query", ",", "DataQuery", "$", "dataQuery", "=", "null", ")", "{", "// Ensure query mode exists", "$", "versionedMode", "=", "$", "dataQuery", "->", "getQueryParam", "(", "'Versioned.mode'", ")", ";", "...
Augment the the SQLSelect that is created by the DataQuery See {@see augmentLazyLoadFields} for lazy-loading applied prior to this. @param SQLSelect $query @param DataQuery $dataQuery @throws InvalidArgumentException
[ "Augment", "the", "the", "SQLSelect", "that", "is", "created", "by", "the", "DataQuery" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L474-L506
43,085
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.augmentSQLStageUnique
protected function augmentSQLStageUnique(SQLSelect $query, DataQuery $dataQuery) { if (!$this->hasStages()) { return; } // Set stage first $this->augmentSQLStage($query, $dataQuery); // Now exclude any ID from any other stage. $stage = $dataQuery->getQueryParam('Versioned.stage'); $excludingStage = $stage === static::DRAFT ? static::LIVE : static::DRAFT; // Note that we double rename to avoid the regular stage rename // renaming all subquery references to be Versioned.stage $tempName = 'ExclusionarySource_' . $excludingStage; $excludingTable = $this->baseTable($excludingStage); $baseTable = $this->baseTable($stage); $query->addWhere("\"{$baseTable}\".\"ID\" NOT IN (SELECT \"ID\" FROM \"{$tempName}\")"); $query->renameTable($tempName, $excludingTable); }
php
protected function augmentSQLStageUnique(SQLSelect $query, DataQuery $dataQuery) { if (!$this->hasStages()) { return; } // Set stage first $this->augmentSQLStage($query, $dataQuery); // Now exclude any ID from any other stage. $stage = $dataQuery->getQueryParam('Versioned.stage'); $excludingStage = $stage === static::DRAFT ? static::LIVE : static::DRAFT; // Note that we double rename to avoid the regular stage rename // renaming all subquery references to be Versioned.stage $tempName = 'ExclusionarySource_' . $excludingStage; $excludingTable = $this->baseTable($excludingStage); $baseTable = $this->baseTable($stage); $query->addWhere("\"{$baseTable}\".\"ID\" NOT IN (SELECT \"ID\" FROM \"{$tempName}\")"); $query->renameTable($tempName, $excludingTable); }
[ "protected", "function", "augmentSQLStageUnique", "(", "SQLSelect", "$", "query", ",", "DataQuery", "$", "dataQuery", ")", "{", "if", "(", "!", "$", "this", "->", "hasStages", "(", ")", ")", "{", "return", ";", "}", "// Set stage first", "$", "this", "->",...
Reading a specific stage, but only return items that aren't in any other stage @param SQLSelect $query @param DataQuery $dataQuery
[ "Reading", "a", "specific", "stage", "but", "only", "return", "items", "that", "aren", "t", "in", "any", "other", "stage" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L540-L559
43,086
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.augmentSQLVersioned
protected function augmentSQLVersioned(SQLSelect $query) { $baseTable = $this->baseTable(); foreach ($query->getFrom() as $alias => $join) { if (!$this->isTableVersioned($alias)) { continue; } if ($alias != $baseTable) { // Make sure join includes version as well $query->setJoinFilter( $alias, "\"{$alias}_Versions\".\"RecordID\" = \"{$baseTable}_Versions\".\"RecordID\"" . " AND \"{$alias}_Versions\".\"Version\" = \"{$baseTable}_Versions\".\"Version\"" ); } // Rewrite all usages of `Table` to `Table_Versions` $query->renameTable($alias, $alias . '_Versions'); // However, add an alias back to the base table in case this must later be joined. // See ApplyVersionFilters for example which joins _Versions back onto draft table. $query->renameTable($alias . '_Draft', $alias); } // Add all <basetable>_Versions columns foreach (Config::inst()->get(static::class, 'db_for_versions_table') as $name => $type) { $query->selectField(sprintf('"%s_Versions"."%s"', $baseTable, $name), $name); } // Alias the record ID as the row ID, and ensure ID filters are aliased correctly $query->selectField("\"{$baseTable}_Versions\".\"RecordID\"", "ID"); $query->replaceText("\"{$baseTable}_Versions\".\"ID\"", "\"{$baseTable}_Versions\".\"RecordID\""); // However, if doing count, undo rewrite of "ID" column $query->replaceText( "count(DISTINCT \"{$baseTable}_Versions\".\"RecordID\")", "count(DISTINCT \"{$baseTable}_Versions\".\"ID\")" ); // Filter deleted versions, which are all unqueryable $query->addWhere(["\"{$baseTable}_Versions\".\"WasDeleted\"" => 0]); }
php
protected function augmentSQLVersioned(SQLSelect $query) { $baseTable = $this->baseTable(); foreach ($query->getFrom() as $alias => $join) { if (!$this->isTableVersioned($alias)) { continue; } if ($alias != $baseTable) { // Make sure join includes version as well $query->setJoinFilter( $alias, "\"{$alias}_Versions\".\"RecordID\" = \"{$baseTable}_Versions\".\"RecordID\"" . " AND \"{$alias}_Versions\".\"Version\" = \"{$baseTable}_Versions\".\"Version\"" ); } // Rewrite all usages of `Table` to `Table_Versions` $query->renameTable($alias, $alias . '_Versions'); // However, add an alias back to the base table in case this must later be joined. // See ApplyVersionFilters for example which joins _Versions back onto draft table. $query->renameTable($alias . '_Draft', $alias); } // Add all <basetable>_Versions columns foreach (Config::inst()->get(static::class, 'db_for_versions_table') as $name => $type) { $query->selectField(sprintf('"%s_Versions"."%s"', $baseTable, $name), $name); } // Alias the record ID as the row ID, and ensure ID filters are aliased correctly $query->selectField("\"{$baseTable}_Versions\".\"RecordID\"", "ID"); $query->replaceText("\"{$baseTable}_Versions\".\"ID\"", "\"{$baseTable}_Versions\".\"RecordID\""); // However, if doing count, undo rewrite of "ID" column $query->replaceText( "count(DISTINCT \"{$baseTable}_Versions\".\"RecordID\")", "count(DISTINCT \"{$baseTable}_Versions\".\"ID\")" ); // Filter deleted versions, which are all unqueryable $query->addWhere(["\"{$baseTable}_Versions\".\"WasDeleted\"" => 0]); }
[ "protected", "function", "augmentSQLVersioned", "(", "SQLSelect", "$", "query", ")", "{", "$", "baseTable", "=", "$", "this", "->", "baseTable", "(", ")", ";", "foreach", "(", "$", "query", "->", "getFrom", "(", ")", "as", "$", "alias", "=>", "$", "joi...
Augment SQL to select from `_Versions` table instead. @param SQLSelect $query
[ "Augment", "SQL", "to", "select", "from", "_Versions", "table", "instead", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L566-L607
43,087
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.augmentSQLVersionedArchive
protected function augmentSQLVersionedArchive(SQLSelect $query, DataQuery $dataQuery) { $baseTable = $this->baseTable(); $date = $dataQuery->getQueryParam('Versioned.date'); if (!$date) { throw new InvalidArgumentException("Invalid archive date"); } // Query against _Versions table first $this->augmentSQLVersioned($query); // Validate stage $stage = $dataQuery->getQueryParam('Versioned.stage'); ReadingMode::validateStage($stage); // Filter on appropriate stage column in addition to date if ($this->hasStages()) { $stageColumn = $stage === static::LIVE ? 'WasPublished' : 'WasDraft'; $stageCondition = "AND \"{$baseTable}_Versions\".\"{$stageColumn}\" = 1"; } else { $stageCondition = ''; } // Join on latest version filtered by date $query->addInnerJoin( <<<SQL ( SELECT "{$baseTable}_Versions"."RecordID", MAX("{$baseTable}_Versions"."Version") AS "LatestVersion" FROM "{$baseTable}_Versions" WHERE "{$baseTable}_Versions"."LastEdited" <= ? {$stageCondition} GROUP BY "{$baseTable}_Versions"."RecordID" ) SQL , <<<SQL "{$baseTable}_Versions_Latest"."RecordID" = "{$baseTable}_Versions"."RecordID" AND "{$baseTable}_Versions_Latest"."LatestVersion" = "{$baseTable}_Versions"."Version" SQL , "{$baseTable}_Versions_Latest", 20, [$date] ); }
php
protected function augmentSQLVersionedArchive(SQLSelect $query, DataQuery $dataQuery) { $baseTable = $this->baseTable(); $date = $dataQuery->getQueryParam('Versioned.date'); if (!$date) { throw new InvalidArgumentException("Invalid archive date"); } // Query against _Versions table first $this->augmentSQLVersioned($query); // Validate stage $stage = $dataQuery->getQueryParam('Versioned.stage'); ReadingMode::validateStage($stage); // Filter on appropriate stage column in addition to date if ($this->hasStages()) { $stageColumn = $stage === static::LIVE ? 'WasPublished' : 'WasDraft'; $stageCondition = "AND \"{$baseTable}_Versions\".\"{$stageColumn}\" = 1"; } else { $stageCondition = ''; } // Join on latest version filtered by date $query->addInnerJoin( <<<SQL ( SELECT "{$baseTable}_Versions"."RecordID", MAX("{$baseTable}_Versions"."Version") AS "LatestVersion" FROM "{$baseTable}_Versions" WHERE "{$baseTable}_Versions"."LastEdited" <= ? {$stageCondition} GROUP BY "{$baseTable}_Versions"."RecordID" ) SQL , <<<SQL "{$baseTable}_Versions_Latest"."RecordID" = "{$baseTable}_Versions"."RecordID" AND "{$baseTable}_Versions_Latest"."LatestVersion" = "{$baseTable}_Versions"."Version" SQL , "{$baseTable}_Versions_Latest", 20, [$date] ); }
[ "protected", "function", "augmentSQLVersionedArchive", "(", "SQLSelect", "$", "query", ",", "DataQuery", "$", "dataQuery", ")", "{", "$", "baseTable", "=", "$", "this", "->", "baseTable", "(", ")", ";", "$", "date", "=", "$", "dataQuery", "->", "getQueryPara...
Filter the versioned history by a specific date and archive stage @param SQLSelect $query @param DataQuery $dataQuery
[ "Filter", "the", "versioned", "history", "by", "a", "specific", "date", "and", "archive", "stage" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L615-L662
43,088
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.augmentSQLVersionedVersion
protected function augmentSQLVersionedVersion(SQLSelect $query, DataQuery $dataQuery) { $version = $dataQuery->getQueryParam('Versioned.version'); if (!$version) { throw new InvalidArgumentException("Invalid version"); } // Query against _Versions table first $this->augmentSQLVersioned($query); // Add filter on version field $baseTable = $this->baseTable(); $query->addWhere([ "\"{$baseTable}_Versions\".\"Version\"" => $version, ]); }
php
protected function augmentSQLVersionedVersion(SQLSelect $query, DataQuery $dataQuery) { $version = $dataQuery->getQueryParam('Versioned.version'); if (!$version) { throw new InvalidArgumentException("Invalid version"); } // Query against _Versions table first $this->augmentSQLVersioned($query); // Add filter on version field $baseTable = $this->baseTable(); $query->addWhere([ "\"{$baseTable}_Versions\".\"Version\"" => $version, ]); }
[ "protected", "function", "augmentSQLVersionedVersion", "(", "SQLSelect", "$", "query", ",", "DataQuery", "$", "dataQuery", ")", "{", "$", "version", "=", "$", "dataQuery", "->", "getQueryParam", "(", "'Versioned.version'", ")", ";", "if", "(", "!", "$", "versi...
If selecting a specific version, filter it here @param SQLSelect $query @param DataQuery $dataQuery
[ "If", "selecting", "a", "specific", "version", "filter", "it", "here" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L731-L746
43,089
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.augmentSQLVersionedAll
protected function augmentSQLVersionedAll(SQLSelect $query) { // Query against _Versions table first $this->augmentSQLVersioned($query); $baseTable = $this->baseTable(); $query->addOrderBy("\"{$baseTable}_Versions\".\"Version\""); }
php
protected function augmentSQLVersionedAll(SQLSelect $query) { // Query against _Versions table first $this->augmentSQLVersioned($query); $baseTable = $this->baseTable(); $query->addOrderBy("\"{$baseTable}_Versions\".\"Version\""); }
[ "protected", "function", "augmentSQLVersionedAll", "(", "SQLSelect", "$", "query", ")", "{", "// Query against _Versions table first", "$", "this", "->", "augmentSQLVersioned", "(", "$", "query", ")", ";", "$", "baseTable", "=", "$", "this", "->", "baseTable", "("...
If all versions are requested, ensure that records are sorted by this field @param SQLSelect $query
[ "If", "all", "versions", "are", "requested", "ensure", "that", "records", "are", "sorted", "by", "this", "field" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L753-L760
43,090
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.isTableVersioned
protected function isTableVersioned($table) { $schema = DataObject::getSchema(); $tableClass = $schema->tableClass($table); if (empty($tableClass)) { return false; } // Check that this class belongs to the same tree $baseClass = $schema->baseDataClass($this->owner); if (!is_a($tableClass, $baseClass, true)) { return false; } // Check that this isn't a derived table // (e.g. _Live, or a many_many table) $mainTable = $schema->tableName($tableClass); if ($mainTable !== $table) { return false; } return true; }
php
protected function isTableVersioned($table) { $schema = DataObject::getSchema(); $tableClass = $schema->tableClass($table); if (empty($tableClass)) { return false; } // Check that this class belongs to the same tree $baseClass = $schema->baseDataClass($this->owner); if (!is_a($tableClass, $baseClass, true)) { return false; } // Check that this isn't a derived table // (e.g. _Live, or a many_many table) $mainTable = $schema->tableName($tableClass); if ($mainTable !== $table) { return false; } return true; }
[ "protected", "function", "isTableVersioned", "(", "$", "table", ")", "{", "$", "schema", "=", "DataObject", "::", "getSchema", "(", ")", ";", "$", "tableClass", "=", "$", "schema", "->", "tableClass", "(", "$", "table", ")", ";", "if", "(", "empty", "(...
Determine if the given versioned table is a part of the sub-tree of the current dataobject This helps prevent rewriting of other tables that get joined in, in particular, many_many tables @param string $table @return bool True if this table should be versioned
[ "Determine", "if", "the", "given", "versioned", "table", "is", "a", "part", "of", "the", "sub", "-", "tree", "of", "the", "current", "dataobject", "This", "helps", "prevent", "rewriting", "of", "other", "tables", "that", "get", "joined", "in", "in", "parti...
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L769-L791
43,091
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.augmentLoadLazyFields
public function augmentLoadLazyFields(SQLSelect &$query, DataQuery &$dataQuery = null, $dataObject) { // The VersionedMode local variable ensures that this decorator only applies to // queries that have originated from the Versioned object, and have the Versioned // metadata set on the query object. This prevents regular queries from // accidentally querying the *_Versions tables. $versionedMode = $dataObject->getSourceQueryParam('Versioned.mode'); $modesToAllowVersioning = ['all_versions', 'latest_versions', 'archive', 'version']; if (!empty($dataObject->Version) && (!empty($versionedMode) && in_array($versionedMode, $modesToAllowVersioning)) ) { // This will ensure that augmentSQL will select only the same version as the owner, // regardless of how this object was initially selected $versionColumn = $this->owner->getSchema()->sqlColumnForField($this->owner, 'Version'); $dataQuery->where([ $versionColumn => $dataObject->Version ]); $dataQuery->setQueryParam('Versioned.mode', 'all_versions'); } }
php
public function augmentLoadLazyFields(SQLSelect &$query, DataQuery &$dataQuery = null, $dataObject) { // The VersionedMode local variable ensures that this decorator only applies to // queries that have originated from the Versioned object, and have the Versioned // metadata set on the query object. This prevents regular queries from // accidentally querying the *_Versions tables. $versionedMode = $dataObject->getSourceQueryParam('Versioned.mode'); $modesToAllowVersioning = ['all_versions', 'latest_versions', 'archive', 'version']; if (!empty($dataObject->Version) && (!empty($versionedMode) && in_array($versionedMode, $modesToAllowVersioning)) ) { // This will ensure that augmentSQL will select only the same version as the owner, // regardless of how this object was initially selected $versionColumn = $this->owner->getSchema()->sqlColumnForField($this->owner, 'Version'); $dataQuery->where([ $versionColumn => $dataObject->Version ]); $dataQuery->setQueryParam('Versioned.mode', 'all_versions'); } }
[ "public", "function", "augmentLoadLazyFields", "(", "SQLSelect", "&", "$", "query", ",", "DataQuery", "&", "$", "dataQuery", "=", "null", ",", "$", "dataObject", ")", "{", "// The VersionedMode local variable ensures that this decorator only applies to", "// queries that ha...
For lazy loaded fields requiring extra sql manipulation, ie versioning. @param SQLSelect $query @param DataQuery $dataQuery @param DataObject $dataObject
[ "For", "lazy", "loaded", "fields", "requiring", "extra", "sql", "manipulation", "ie", "versioning", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L800-L819
43,092
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.cleanupVersionedOrphans
protected function cleanupVersionedOrphans($baseTable, $childTable) { // Avoid if disabled if ($this->owner->config()->get('versioned_orphans_disabled')) { return; } // Skip if tables are the same (ignore case) if (strcasecmp($childTable, $baseTable) === 0) { return; } // Skip if child table doesn't exist // If it does, ensure query case matches found case $tables = DB::get_schema()->tableList(); if (!array_key_exists(strtolower($childTable), $tables)) { return; } $childTable = $tables[strtolower($childTable)]; // Select all orphaned version records $orphanedQuery = SQLSelect::create() ->selectField("\"{$childTable}\".\"ID\"") ->setFrom("\"{$childTable}\""); // If we have a parent table limit orphaned records // to only those that exist in this if (array_key_exists(strtolower($baseTable), $tables)) { // Ensure we match db table case $baseTable = $tables[strtolower($baseTable)]; $orphanedQuery ->addLeftJoin( $baseTable, "\"{$childTable}\".\"RecordID\" = \"{$baseTable}\".\"RecordID\" AND \"{$childTable}\".\"Version\" = \"{$baseTable}\".\"Version\"" ) ->addWhere("\"{$baseTable}\".\"ID\" IS NULL"); } $count = $orphanedQuery->count(); if ($count > 0) { DB::alteration_message("Removing {$count} orphaned versioned records", "deleted"); $ids = $orphanedQuery->execute()->column(); foreach ($ids as $id) { DB::prepared_query("DELETE FROM \"{$childTable}\" WHERE \"ID\" = ?", [$id]); } } }
php
protected function cleanupVersionedOrphans($baseTable, $childTable) { // Avoid if disabled if ($this->owner->config()->get('versioned_orphans_disabled')) { return; } // Skip if tables are the same (ignore case) if (strcasecmp($childTable, $baseTable) === 0) { return; } // Skip if child table doesn't exist // If it does, ensure query case matches found case $tables = DB::get_schema()->tableList(); if (!array_key_exists(strtolower($childTable), $tables)) { return; } $childTable = $tables[strtolower($childTable)]; // Select all orphaned version records $orphanedQuery = SQLSelect::create() ->selectField("\"{$childTable}\".\"ID\"") ->setFrom("\"{$childTable}\""); // If we have a parent table limit orphaned records // to only those that exist in this if (array_key_exists(strtolower($baseTable), $tables)) { // Ensure we match db table case $baseTable = $tables[strtolower($baseTable)]; $orphanedQuery ->addLeftJoin( $baseTable, "\"{$childTable}\".\"RecordID\" = \"{$baseTable}\".\"RecordID\" AND \"{$childTable}\".\"Version\" = \"{$baseTable}\".\"Version\"" ) ->addWhere("\"{$baseTable}\".\"ID\" IS NULL"); } $count = $orphanedQuery->count(); if ($count > 0) { DB::alteration_message("Removing {$count} orphaned versioned records", "deleted"); $ids = $orphanedQuery->execute()->column(); foreach ($ids as $id) { DB::prepared_query("DELETE FROM \"{$childTable}\" WHERE \"ID\" = ?", [$id]); } } }
[ "protected", "function", "cleanupVersionedOrphans", "(", "$", "baseTable", ",", "$", "childTable", ")", "{", "// Avoid if disabled", "if", "(", "$", "this", "->", "owner", "->", "config", "(", ")", "->", "get", "(", "'versioned_orphans_disabled'", ")", ")", "{...
Cleanup orphaned records in the _Versions table @param string $baseTable base table to use as authoritative source of records @param string $childTable Sub-table to clean orphans from
[ "Cleanup", "orphaned", "records", "in", "the", "_Versions", "table" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L948-L995
43,093
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.createDeletedVersion
protected function createDeletedVersion($stages = []) { // Skip if suppressed by parent delete if (!$this->getDeleteWritesVersion()) { return; } // Prepare manipulation $baseTable = $this->owner->baseTable(); $now = DBDatetime::now()->Rfc2822(); // Ensure all fixed_fields are specified $manipulation = [ $baseTable => [ 'fields' => [ 'ID' => $this->owner->ID, 'LastEdited' => $now, 'Created' => $this->owner->Created ?: $now, 'ClassName' => $this->owner->ClassName, ], ], ]; // Prepare "deleted" augment write $this->augmentWriteVersioned( $manipulation, $this->owner->baseClass(), $baseTable, $this->owner->ID, $stages, true ); unset($manipulation[$baseTable]); $this->owner->extend('augmentWriteDeletedVersion', $manipulation, $stages); DB::manipulate($manipulation); }
php
protected function createDeletedVersion($stages = []) { // Skip if suppressed by parent delete if (!$this->getDeleteWritesVersion()) { return; } // Prepare manipulation $baseTable = $this->owner->baseTable(); $now = DBDatetime::now()->Rfc2822(); // Ensure all fixed_fields are specified $manipulation = [ $baseTable => [ 'fields' => [ 'ID' => $this->owner->ID, 'LastEdited' => $now, 'Created' => $this->owner->Created ?: $now, 'ClassName' => $this->owner->ClassName, ], ], ]; // Prepare "deleted" augment write $this->augmentWriteVersioned( $manipulation, $this->owner->baseClass(), $baseTable, $this->owner->ID, $stages, true ); unset($manipulation[$baseTable]); $this->owner->extend('augmentWriteDeletedVersion', $manipulation, $stages); DB::manipulate($manipulation); }
[ "protected", "function", "createDeletedVersion", "(", "$", "stages", "=", "[", "]", ")", "{", "// Skip if suppressed by parent delete", "if", "(", "!", "$", "this", "->", "getDeleteWritesVersion", "(", ")", ")", "{", "return", ";", "}", "// Prepare manipulation", ...
Adds a WasDeleted=1 version entry for this record, and records any stages the deletion applies to @param string[]|string $stages Stage or array of affected stages
[ "Adds", "a", "WasDeleted", "=", "1", "version", "entry", "for", "this", "record", "and", "records", "any", "stages", "the", "deletion", "applies", "to" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1127-L1159
43,094
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.suppressDeletedVersion
protected function suppressDeletedVersion($callback) { $original = $this->getDeleteWritesVersion(); try { $this->setDeleteWritesVersion(false); return $callback(); } finally { $this->setDeleteWritesVersion($original); } }
php
protected function suppressDeletedVersion($callback) { $original = $this->getDeleteWritesVersion(); try { $this->setDeleteWritesVersion(false); return $callback(); } finally { $this->setDeleteWritesVersion($original); } }
[ "protected", "function", "suppressDeletedVersion", "(", "$", "callback", ")", "{", "$", "original", "=", "$", "this", "->", "getDeleteWritesVersion", "(", ")", ";", "try", "{", "$", "this", "->", "setDeleteWritesVersion", "(", "false", ")", ";", "return", "$...
Helper method to safely suppress delete callback @param callable $callback @return mixed Result of $callback()
[ "Helper", "method", "to", "safely", "suppress", "delete", "callback" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1303-L1312
43,095
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.canArchive
public function canArchive($member = null) { // Skip if invoked by extendedCan() if (func_num_args() > 4) { return null; } if (!$member) { $member = Security::getCurrentUser(); } // Standard mechanism for accepting permission changes from extensions $owner = $this->owner; $extended = $owner->extendedCan('canArchive', $member); if ($extended !== null) { return $extended; } // Admin permissions allow if (Permission::checkMember($member, "ADMIN")) { return true; } // Check if this record can be deleted from stage if (!$owner->canDelete($member)) { return false; } // Check if we can delete from live if (!$owner->canUnpublish($member)) { return false; } return true; }
php
public function canArchive($member = null) { // Skip if invoked by extendedCan() if (func_num_args() > 4) { return null; } if (!$member) { $member = Security::getCurrentUser(); } // Standard mechanism for accepting permission changes from extensions $owner = $this->owner; $extended = $owner->extendedCan('canArchive', $member); if ($extended !== null) { return $extended; } // Admin permissions allow if (Permission::checkMember($member, "ADMIN")) { return true; } // Check if this record can be deleted from stage if (!$owner->canDelete($member)) { return false; } // Check if we can delete from live if (!$owner->canUnpublish($member)) { return false; } return true; }
[ "public", "function", "canArchive", "(", "$", "member", "=", "null", ")", "{", "// Skip if invoked by extendedCan()", "if", "(", "func_num_args", "(", ")", ">", "4", ")", "{", "return", "null", ";", "}", "if", "(", "!", "$", "member", ")", "{", "$", "m...
Check if the current user is allowed to archive this record. If extended, ensure that both canDelete and canUnpublish are extended also @param Member $member @return bool
[ "Check", "if", "the", "current", "user", "is", "allowed", "to", "archive", "this", "record", ".", "If", "extended", "ensure", "that", "both", "canDelete", "and", "canUnpublish", "are", "extended", "also" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1399-L1433
43,096
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.canRevertToLive
public function canRevertToLive($member = null) { $owner = $this->owner; // Skip if invoked by extendedCan() if (func_num_args() > 4) { return null; } // Can't revert if not on live if (!$owner->isPublished()) { return false; } if (!$member) { $member = Security::getCurrentUser(); } if (Permission::checkMember($member, "ADMIN")) { return true; } // Standard mechanism for accepting permission changes from extensions $extended = $owner->extendedCan('canRevertToLive', $member); if ($extended !== null) { return $extended; } // Default to canEdit return $owner->canEdit($member); }
php
public function canRevertToLive($member = null) { $owner = $this->owner; // Skip if invoked by extendedCan() if (func_num_args() > 4) { return null; } // Can't revert if not on live if (!$owner->isPublished()) { return false; } if (!$member) { $member = Security::getCurrentUser(); } if (Permission::checkMember($member, "ADMIN")) { return true; } // Standard mechanism for accepting permission changes from extensions $extended = $owner->extendedCan('canRevertToLive', $member); if ($extended !== null) { return $extended; } // Default to canEdit return $owner->canEdit($member); }
[ "public", "function", "canRevertToLive", "(", "$", "member", "=", "null", ")", "{", "$", "owner", "=", "$", "this", "->", "owner", ";", "// Skip if invoked by extendedCan()", "if", "(", "func_num_args", "(", ")", ">", "4", ")", "{", "return", "null", ";", ...
Check if the user can revert this record to live @param Member $member @return bool
[ "Check", "if", "the", "user", "can", "revert", "this", "record", "to", "live" ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1441-L1471
43,097
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.canView
public function canView($member = null) { // Invoke default version-gnostic canView if ($this->owner->canViewVersioned($member) === false) { return false; } return null; }
php
public function canView($member = null) { // Invoke default version-gnostic canView if ($this->owner->canViewVersioned($member) === false) { return false; } return null; }
[ "public", "function", "canView", "(", "$", "member", "=", "null", ")", "{", "// Invoke default version-gnostic canView", "if", "(", "$", "this", "->", "owner", "->", "canViewVersioned", "(", "$", "member", ")", "===", "false", ")", "{", "return", "false", ";...
Extend permissions to include additional security for objects that are not published to live. @param Member $member @return bool|null
[ "Extend", "permissions", "to", "include", "additional", "security", "for", "objects", "that", "are", "not", "published", "to", "live", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1512-L1519
43,098
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.canViewVersioned
public function canViewVersioned($member = null) { // Bypass when live stage $owner = $this->owner; // Bypass if site is unsecured if (!self::get_draft_site_secured()) { return true; } // Get reading mode from source query (or current mode) $readingParams = $owner->getSourceQueryParams() // Guess record mode from current reading mode instead ?: ReadingMode::toDataQueryParams(static::get_reading_mode()); // If this is the live record we can view it if (isset($readingParams["Versioned.mode"]) && $readingParams["Versioned.mode"] === 'stage' && $readingParams["Versioned.stage"] === static::LIVE ) { return true; } // Bypass if record doesn't have a live stage if (!$this->hasStages()) { return true; } // If we weren't definitely loaded from live, and we can't view non-live content, we need to // check to make sure this version is the live version and so can be viewed $latestVersion = Versioned::get_versionnumber_by_stage(get_class($owner), static::LIVE, $owner->ID); if ($latestVersion == $owner->Version) { // Even if this is loaded from a non-live stage, this is the live version return true; } // If stages are synchronised treat this as the live stage if (!$this->stagesDiffer()) { return true; } // Extend versioned behaviour $extended = $owner->extendedCan('canViewNonLive', $member); if ($extended !== null) { return (bool)$extended; } // Fall back to default permission check $permissions = Config::inst()->get(get_class($owner), 'non_live_permissions'); $check = Permission::checkMember($member, $permissions); return (bool)$check; }
php
public function canViewVersioned($member = null) { // Bypass when live stage $owner = $this->owner; // Bypass if site is unsecured if (!self::get_draft_site_secured()) { return true; } // Get reading mode from source query (or current mode) $readingParams = $owner->getSourceQueryParams() // Guess record mode from current reading mode instead ?: ReadingMode::toDataQueryParams(static::get_reading_mode()); // If this is the live record we can view it if (isset($readingParams["Versioned.mode"]) && $readingParams["Versioned.mode"] === 'stage' && $readingParams["Versioned.stage"] === static::LIVE ) { return true; } // Bypass if record doesn't have a live stage if (!$this->hasStages()) { return true; } // If we weren't definitely loaded from live, and we can't view non-live content, we need to // check to make sure this version is the live version and so can be viewed $latestVersion = Versioned::get_versionnumber_by_stage(get_class($owner), static::LIVE, $owner->ID); if ($latestVersion == $owner->Version) { // Even if this is loaded from a non-live stage, this is the live version return true; } // If stages are synchronised treat this as the live stage if (!$this->stagesDiffer()) { return true; } // Extend versioned behaviour $extended = $owner->extendedCan('canViewNonLive', $member); if ($extended !== null) { return (bool)$extended; } // Fall back to default permission check $permissions = Config::inst()->get(get_class($owner), 'non_live_permissions'); $check = Permission::checkMember($member, $permissions); return (bool)$check; }
[ "public", "function", "canViewVersioned", "(", "$", "member", "=", "null", ")", "{", "// Bypass when live stage", "$", "owner", "=", "$", "this", "->", "owner", ";", "// Bypass if site is unsecured", "if", "(", "!", "self", "::", "get_draft_site_secured", "(", "...
Determine if there are any additional restrictions on this object for the given reading version. Override this in a subclass to customise any additional effect that Versioned applies to canView. This is expected to be called by canView, and thus is only responsible for denying access if the default canView would otherwise ALLOW access. Thus it should not be called in isolation as an authoritative permission check. This has the following extension points: - canViewDraft is invoked if Mode = stage and Stage = stage - canViewArchived is invoked if Mode = archive @param Member $member @return bool False is returned if the current viewing mode denies visibility
[ "Determine", "if", "there", "are", "any", "additional", "restrictions", "on", "this", "object", "for", "the", "given", "reading", "version", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1537-L1588
43,099
silverstripe/silverstripe-versioned
src/Versioned.php
Versioned.publishSingle
public function publishSingle() { $owner = $this->owner; // get the last published version $original = null; if ($this->isPublished()) { $original = self::get_by_stage($owner->baseClass(), self::LIVE) ->byID($owner->ID); } // Publish it $owner->invokeWithExtensions('onBeforePublish', $original); $owner->writeToStage(static::LIVE); $owner->invokeWithExtensions('onAfterPublish', $original); return true; }
php
public function publishSingle() { $owner = $this->owner; // get the last published version $original = null; if ($this->isPublished()) { $original = self::get_by_stage($owner->baseClass(), self::LIVE) ->byID($owner->ID); } // Publish it $owner->invokeWithExtensions('onBeforePublish', $original); $owner->writeToStage(static::LIVE); $owner->invokeWithExtensions('onAfterPublish', $original); return true; }
[ "public", "function", "publishSingle", "(", ")", "{", "$", "owner", "=", "$", "this", "->", "owner", ";", "// get the last published version", "$", "original", "=", "null", ";", "if", "(", "$", "this", "->", "isPublished", "(", ")", ")", "{", "$", "origi...
Publishes this object to Live, but doesn't publish owned objects. User code should call {@see canPublish()} prior to invoking this method. @return bool True if publish was successful
[ "Publishes", "this", "object", "to", "Live", "but", "doesn", "t", "publish", "owned", "objects", "." ]
bddf25fd3a713e7ed7a861d6c6992febc3c7998b
https://github.com/silverstripe/silverstripe-versioned/blob/bddf25fd3a713e7ed7a861d6c6992febc3c7998b/src/Versioned.php#L1706-L1721