repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
yiisoft/yii2-mongodb
src/file/Upload.php
Upload.cancel
public function cancel() { $this->_buffer = null; $this->collection->getChunkCollection()->remove(['files_id' => $this->_documentId], ['limit' => 0]); $this->collection->remove(['_id' => $this->_documentId], ['limit' => 1]); $this->_isComplete = true; }
php
public function cancel() { $this->_buffer = null; $this->collection->getChunkCollection()->remove(['files_id' => $this->_documentId], ['limit' => 0]); $this->collection->remove(['_id' => $this->_documentId], ['limit' => 1]); $this->_isComplete = true; }
[ "public", "function", "cancel", "(", ")", "{", "$", "this", "->", "_buffer", "=", "null", ";", "$", "this", "->", "collection", "->", "getChunkCollection", "(", ")", "->", "remove", "(", "[", "'files_id'", "=>", "$", "this", "->", "_documentId", "]", "...
Cancels the upload.
[ "Cancels", "the", "upload", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Upload.php#L206-L214
yiisoft/yii2-mongodb
src/file/Upload.php
Upload.flushBuffer
private function flushBuffer($force = false) { if ($this->_buffer === null) { return; } if ($force || StringHelper::byteLength($this->_buffer) == $this->chunkSize) { $this->insertChunk($this->_buffer); $this->_buffer = null; } }
php
private function flushBuffer($force = false) { if ($this->_buffer === null) { return; } if ($force || StringHelper::byteLength($this->_buffer) == $this->chunkSize) { $this->insertChunk($this->_buffer); $this->_buffer = null; } }
[ "private", "function", "flushBuffer", "(", "$", "force", "=", "false", ")", "{", "if", "(", "$", "this", "->", "_buffer", "===", "null", ")", "{", "return", ";", "}", "if", "(", "$", "force", "||", "StringHelper", "::", "byteLength", "(", "$", "this"...
Flushes [[buffer]] to the chunk if it is full. @param bool $force whether to enforce flushing.
[ "Flushes", "[[", "buffer", "]]", "to", "the", "chunk", "if", "it", "is", "full", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Upload.php#L220-L230
yiisoft/yii2-mongodb
src/file/Upload.php
Upload.insertChunk
private function insertChunk($data) { $chunkDocument = [ 'files_id' => $this->_documentId, 'n' => $this->chunkCount, 'data' => new Binary($data, Binary::TYPE_GENERIC), ]; hash_update($this->_hashContext, $data); $this->collection->getChunkCollection()->insert($chunkDocument); $this->length += StringHelper::byteLength($data); $this->chunkCount++; }
php
private function insertChunk($data) { $chunkDocument = [ 'files_id' => $this->_documentId, 'n' => $this->chunkCount, 'data' => new Binary($data, Binary::TYPE_GENERIC), ]; hash_update($this->_hashContext, $data); $this->collection->getChunkCollection()->insert($chunkDocument); $this->length += StringHelper::byteLength($data); $this->chunkCount++; }
[ "private", "function", "insertChunk", "(", "$", "data", ")", "{", "$", "chunkDocument", "=", "[", "'files_id'", "=>", "$", "this", "->", "_documentId", ",", "'n'", "=>", "$", "this", "->", "chunkCount", ",", "'data'", "=>", "new", "Binary", "(", "$", "...
Inserts file chunk. @param string $data chunk binary content.
[ "Inserts", "file", "chunk", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Upload.php#L236-L249
yiisoft/yii2-mongodb
src/file/Upload.php
Upload.insertFile
private function insertFile() { $fileDocument = [ '_id' => $this->_documentId, 'uploadDate' => new UTCDateTime(round(microtime(true) * 1000)), ]; if ($this->filename === null) { $fileDocument['filename'] = $this->_documentId . '.dat'; } else { $fileDocument['filename'] = $this->filename; } $fileDocument = array_merge( $fileDocument, $this->document, [ 'chunkSize' => $this->chunkSize, 'length' => $this->length, 'md5' => hash_final($this->_hashContext), ] ); $this->collection->insert($fileDocument); return $fileDocument; }
php
private function insertFile() { $fileDocument = [ '_id' => $this->_documentId, 'uploadDate' => new UTCDateTime(round(microtime(true) * 1000)), ]; if ($this->filename === null) { $fileDocument['filename'] = $this->_documentId . '.dat'; } else { $fileDocument['filename'] = $this->filename; } $fileDocument = array_merge( $fileDocument, $this->document, [ 'chunkSize' => $this->chunkSize, 'length' => $this->length, 'md5' => hash_final($this->_hashContext), ] ); $this->collection->insert($fileDocument); return $fileDocument; }
[ "private", "function", "insertFile", "(", ")", "{", "$", "fileDocument", "=", "[", "'_id'", "=>", "$", "this", "->", "_documentId", ",", "'uploadDate'", "=>", "new", "UTCDateTime", "(", "round", "(", "microtime", "(", "true", ")", "*", "1000", ")", ")", ...
Inserts [[document]] into file collection. @return array inserted file document data.
[ "Inserts", "[[", "document", "]]", "into", "file", "collection", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Upload.php#L255-L279
yiisoft/yii2-mongodb
src/file/ActiveRecord.php
ActiveRecord.extractFileName
protected function extractFileName($file) { if ($file instanceof UploadedFile) { return $file->tempName; } elseif (is_string($file)) { if (file_exists($file)) { return $file; } throw new InvalidParamException("File '{$file}' does not exist."); } throw new InvalidParamException('Unsupported type of "file" attribute.'); }
php
protected function extractFileName($file) { if ($file instanceof UploadedFile) { return $file->tempName; } elseif (is_string($file)) { if (file_exists($file)) { return $file; } throw new InvalidParamException("File '{$file}' does not exist."); } throw new InvalidParamException('Unsupported type of "file" attribute.'); }
[ "protected", "function", "extractFileName", "(", "$", "file", ")", "{", "if", "(", "$", "file", "instanceof", "UploadedFile", ")", "{", "return", "$", "file", "->", "tempName", ";", "}", "elseif", "(", "is_string", "(", "$", "file", ")", ")", "{", "if"...
Extracts filename from given raw file value. @param mixed $file raw file value. @return string file name. @throws \yii\base\InvalidParamException on invalid file value.
[ "Extracts", "filename", "from", "given", "raw", "file", "value", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/ActiveRecord.php#L222-L234
yiisoft/yii2-mongodb
src/file/ActiveRecord.php
ActiveRecord.refreshFile
public function refreshFile() { $mongoFile = $this->getCollection()->get($this->getPrimaryKey()); $this->setAttribute('file', $mongoFile); return $mongoFile; }
php
public function refreshFile() { $mongoFile = $this->getCollection()->get($this->getPrimaryKey()); $this->setAttribute('file', $mongoFile); return $mongoFile; }
[ "public", "function", "refreshFile", "(", ")", "{", "$", "mongoFile", "=", "$", "this", "->", "getCollection", "(", ")", "->", "get", "(", "$", "this", "->", "getPrimaryKey", "(", ")", ")", ";", "$", "this", "->", "setAttribute", "(", "'file'", ",", ...
Refreshes the [[file]] attribute from file collection, using current primary key. @return \MongoGridFSFile|null refreshed file value.
[ "Refreshes", "the", "[[", "file", "]]", "attribute", "from", "file", "collection", "using", "current", "primary", "key", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/ActiveRecord.php#L240-L246
yiisoft/yii2-mongodb
src/file/ActiveRecord.php
ActiveRecord.getFileContent
public function getFileContent() { $file = $this->getAttribute('file'); if (empty($file) && !$this->getIsNewRecord()) { $file = $this->refreshFile(); } if (empty($file)) { return null; } elseif ($file instanceof Download) { $fileSize = $file->getSize(); return empty($fileSize) ? null : $file->toString(); } elseif ($file instanceof UploadedFile) { return file_get_contents($file->tempName); } elseif (is_string($file)) { if (file_exists($file)) { return file_get_contents($file); } throw new InvalidParamException("File '{$file}' does not exist."); } throw new InvalidParamException('Unsupported type of "file" attribute.'); }
php
public function getFileContent() { $file = $this->getAttribute('file'); if (empty($file) && !$this->getIsNewRecord()) { $file = $this->refreshFile(); } if (empty($file)) { return null; } elseif ($file instanceof Download) { $fileSize = $file->getSize(); return empty($fileSize) ? null : $file->toString(); } elseif ($file instanceof UploadedFile) { return file_get_contents($file->tempName); } elseif (is_string($file)) { if (file_exists($file)) { return file_get_contents($file); } throw new InvalidParamException("File '{$file}' does not exist."); } throw new InvalidParamException('Unsupported type of "file" attribute.'); }
[ "public", "function", "getFileContent", "(", ")", "{", "$", "file", "=", "$", "this", "->", "getAttribute", "(", "'file'", ")", ";", "if", "(", "empty", "(", "$", "file", ")", "&&", "!", "$", "this", "->", "getIsNewRecord", "(", ")", ")", "{", "$",...
Returns the associated file content. @return null|string file content. @throws \yii\base\InvalidParamException on invalid file attribute value.
[ "Returns", "the", "associated", "file", "content", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/ActiveRecord.php#L253-L275
yiisoft/yii2-mongodb
src/file/ActiveRecord.php
ActiveRecord.writeFile
public function writeFile($filename) { $file = $this->getAttribute('file'); if (empty($file) && !$this->getIsNewRecord()) { $file = $this->refreshFile(); } if (empty($file)) { throw new InvalidParamException('There is no file associated with this object.'); } elseif ($file instanceof Download) { return ($file->toFile($filename) == $file->getSize()); } elseif ($file instanceof UploadedFile) { return copy($file->tempName, $filename); } elseif (is_string($file)) { if (file_exists($file)) { return copy($file, $filename); } throw new InvalidParamException("File '{$file}' does not exist."); } throw new InvalidParamException('Unsupported type of "file" attribute.'); }
php
public function writeFile($filename) { $file = $this->getAttribute('file'); if (empty($file) && !$this->getIsNewRecord()) { $file = $this->refreshFile(); } if (empty($file)) { throw new InvalidParamException('There is no file associated with this object.'); } elseif ($file instanceof Download) { return ($file->toFile($filename) == $file->getSize()); } elseif ($file instanceof UploadedFile) { return copy($file->tempName, $filename); } elseif (is_string($file)) { if (file_exists($file)) { return copy($file, $filename); } throw new InvalidParamException("File '{$file}' does not exist."); } throw new InvalidParamException('Unsupported type of "file" attribute.'); }
[ "public", "function", "writeFile", "(", "$", "filename", ")", "{", "$", "file", "=", "$", "this", "->", "getAttribute", "(", "'file'", ")", ";", "if", "(", "empty", "(", "$", "file", ")", "&&", "!", "$", "this", "->", "getIsNewRecord", "(", ")", ")...
Writes the the internal file content into the given filename. @param string $filename full filename to be written. @return bool whether the operation was successful. @throws \yii\base\InvalidParamException on invalid file attribute value.
[ "Writes", "the", "the", "internal", "file", "content", "into", "the", "given", "filename", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/ActiveRecord.php#L283-L304
yiisoft/yii2-mongodb
src/file/ActiveRecord.php
ActiveRecord.getFileResource
public function getFileResource() { $file = $this->getAttribute('file'); if (empty($file) && !$this->getIsNewRecord()) { $file = $this->refreshFile(); } if (empty($file)) { throw new InvalidParamException('There is no file associated with this object.'); } elseif ($file instanceof Download) { return $file->getResource(); } elseif ($file instanceof UploadedFile) { return fopen($file->tempName, 'r'); } elseif (is_string($file)) { if (file_exists($file)) { return fopen($file, 'r'); } throw new InvalidParamException("File '{$file}' does not exist."); } throw new InvalidParamException('Unsupported type of "file" attribute.'); }
php
public function getFileResource() { $file = $this->getAttribute('file'); if (empty($file) && !$this->getIsNewRecord()) { $file = $this->refreshFile(); } if (empty($file)) { throw new InvalidParamException('There is no file associated with this object.'); } elseif ($file instanceof Download) { return $file->getResource(); } elseif ($file instanceof UploadedFile) { return fopen($file->tempName, 'r'); } elseif (is_string($file)) { if (file_exists($file)) { return fopen($file, 'r'); } throw new InvalidParamException("File '{$file}' does not exist."); } throw new InvalidParamException('Unsupported type of "file" attribute.'); }
[ "public", "function", "getFileResource", "(", ")", "{", "$", "file", "=", "$", "this", "->", "getAttribute", "(", "'file'", ")", ";", "if", "(", "empty", "(", "$", "file", ")", "&&", "!", "$", "this", "->", "getIsNewRecord", "(", ")", ")", "{", "$"...
This method returns a stream resource that can be used with all file functions in PHP, which deal with reading files. The contents of the file are pulled out of MongoDB on the fly, so that the whole file does not have to be loaded into memory first. @return resource file stream resource. @throws \yii\base\InvalidParamException on invalid file attribute value.
[ "This", "method", "returns", "a", "stream", "resource", "that", "can", "be", "used", "with", "all", "file", "functions", "in", "PHP", "which", "deal", "with", "reading", "files", ".", "The", "contents", "of", "the", "file", "are", "pulled", "out", "of", ...
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/ActiveRecord.php#L313-L334
yiisoft/yii2-mongodb
src/Connection.php
Connection.getDefaultDatabaseName
public function getDefaultDatabaseName() { if ($this->_defaultDatabaseName === null) { if (preg_match('/^mongodb:\\/\\/.+\\/([^?&]+)/s', $this->dsn, $matches)) { $this->_defaultDatabaseName = $matches[1]; } else { throw new InvalidConfigException("Unable to determine default database name from dsn."); } } return $this->_defaultDatabaseName; }
php
public function getDefaultDatabaseName() { if ($this->_defaultDatabaseName === null) { if (preg_match('/^mongodb:\\/\\/.+\\/([^?&]+)/s', $this->dsn, $matches)) { $this->_defaultDatabaseName = $matches[1]; } else { throw new InvalidConfigException("Unable to determine default database name from dsn."); } } return $this->_defaultDatabaseName; }
[ "public", "function", "getDefaultDatabaseName", "(", ")", "{", "if", "(", "$", "this", "->", "_defaultDatabaseName", "===", "null", ")", "{", "if", "(", "preg_match", "(", "'/^mongodb:\\\\/\\\\/.+\\\\/([^?&]+)/s'", ",", "$", "this", "->", "dsn", ",", "$", "mat...
Returns default database name, if it is not set, attempts to determine it from [[dsn]] value. @return string default database name @throws \yii\base\InvalidConfigException if unable to determine default database name.
[ "Returns", "default", "database", "name", "if", "it", "is", "not", "set", "attempts", "to", "determine", "it", "from", "[[", "dsn", "]]", "value", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Connection.php#L200-L211
yiisoft/yii2-mongodb
src/Connection.php
Connection.getQueryBuilder
public function getQueryBuilder() { if (!is_object($this->_queryBuilder)) { $this->_queryBuilder = Yii::createObject($this->_queryBuilder, [$this]); } return $this->_queryBuilder; }
php
public function getQueryBuilder() { if (!is_object($this->_queryBuilder)) { $this->_queryBuilder = Yii::createObject($this->_queryBuilder, [$this]); } return $this->_queryBuilder; }
[ "public", "function", "getQueryBuilder", "(", ")", "{", "if", "(", "!", "is_object", "(", "$", "this", "->", "_queryBuilder", ")", ")", "{", "$", "this", "->", "_queryBuilder", "=", "Yii", "::", "createObject", "(", "$", "this", "->", "_queryBuilder", ",...
Returns the query builder for the this MongoDB connection. @return QueryBuilder the query builder for the this MongoDB connection. @since 2.1
[ "Returns", "the", "query", "builder", "for", "the", "this", "MongoDB", "connection", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Connection.php#L218-L224
yiisoft/yii2-mongodb
src/Connection.php
Connection.getLogBuilder
public function getLogBuilder() { if (!is_object($this->_logBuilder)) { $this->_logBuilder = Yii::createObject($this->_logBuilder); } return $this->_logBuilder; }
php
public function getLogBuilder() { if (!is_object($this->_logBuilder)) { $this->_logBuilder = Yii::createObject($this->_logBuilder); } return $this->_logBuilder; }
[ "public", "function", "getLogBuilder", "(", ")", "{", "if", "(", "!", "is_object", "(", "$", "this", "->", "_logBuilder", ")", ")", "{", "$", "this", "->", "_logBuilder", "=", "Yii", "::", "createObject", "(", "$", "this", "->", "_logBuilder", ")", ";"...
Returns log builder for this connection. @return LogBuilder the log builder for this connection. @since 2.1
[ "Returns", "log", "builder", "for", "this", "connection", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Connection.php#L241-L247
yiisoft/yii2-mongodb
src/Connection.php
Connection.getDatabase
public function getDatabase($name = null, $refresh = false) { if ($name === null) { $name = $this->getDefaultDatabaseName(); } if ($refresh || !array_key_exists($name, $this->_databases)) { $this->_databases[$name] = $this->selectDatabase($name); } return $this->_databases[$name]; }
php
public function getDatabase($name = null, $refresh = false) { if ($name === null) { $name = $this->getDefaultDatabaseName(); } if ($refresh || !array_key_exists($name, $this->_databases)) { $this->_databases[$name] = $this->selectDatabase($name); } return $this->_databases[$name]; }
[ "public", "function", "getDatabase", "(", "$", "name", "=", "null", ",", "$", "refresh", "=", "false", ")", "{", "if", "(", "$", "name", "===", "null", ")", "{", "$", "name", "=", "$", "this", "->", "getDefaultDatabaseName", "(", ")", ";", "}", "if...
Returns the MongoDB database with the given name. @param string|null $name database name, if null default one will be used. @param bool $refresh whether to reestablish the database connection even, if it is found in the cache. @return Database database instance.
[ "Returns", "the", "MongoDB", "database", "with", "the", "given", "name", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Connection.php#L265-L275
yiisoft/yii2-mongodb
src/Connection.php
Connection.getCollection
public function getCollection($name, $refresh = false) { if (is_array($name)) { list ($dbName, $collectionName) = $name; return $this->getDatabase($dbName)->getCollection($collectionName, $refresh); } return $this->getDatabase()->getCollection($name, $refresh); }
php
public function getCollection($name, $refresh = false) { if (is_array($name)) { list ($dbName, $collectionName) = $name; return $this->getDatabase($dbName)->getCollection($collectionName, $refresh); } return $this->getDatabase()->getCollection($name, $refresh); }
[ "public", "function", "getCollection", "(", "$", "name", ",", "$", "refresh", "=", "false", ")", "{", "if", "(", "is_array", "(", "$", "name", ")", ")", "{", "list", "(", "$", "dbName", ",", "$", "collectionName", ")", "=", "$", "name", ";", "retur...
Returns the MongoDB collection with the given name. @param string|array $name collection name. If string considered as the name of the collection inside the default database. If array - first element considered as the name of the database, second - as name of collection inside that database @param bool $refresh whether to reload the collection instance even if it is found in the cache. @return Collection Mongo collection instance.
[ "Returns", "the", "MongoDB", "collection", "with", "the", "given", "name", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Connection.php#L299-L306
yiisoft/yii2-mongodb
src/Connection.php
Connection.getFileCollection
public function getFileCollection($prefix = 'fs', $refresh = false) { if (is_array($prefix)) { list ($dbName, $collectionPrefix) = $prefix; if (!isset($collectionPrefix)) { $collectionPrefix = 'fs'; } return $this->getDatabase($dbName)->getFileCollection($collectionPrefix, $refresh); } return $this->getDatabase()->getFileCollection($prefix, $refresh); }
php
public function getFileCollection($prefix = 'fs', $refresh = false) { if (is_array($prefix)) { list ($dbName, $collectionPrefix) = $prefix; if (!isset($collectionPrefix)) { $collectionPrefix = 'fs'; } return $this->getDatabase($dbName)->getFileCollection($collectionPrefix, $refresh); } return $this->getDatabase()->getFileCollection($prefix, $refresh); }
[ "public", "function", "getFileCollection", "(", "$", "prefix", "=", "'fs'", ",", "$", "refresh", "=", "false", ")", "{", "if", "(", "is_array", "(", "$", "prefix", ")", ")", "{", "list", "(", "$", "dbName", ",", "$", "collectionPrefix", ")", "=", "$"...
Returns the MongoDB GridFS collection. @param string|array $prefix collection prefix. If string considered as the prefix of the GridFS collection inside the default database. If array - first element considered as the name of the database, second - as prefix of the GridFS collection inside that database, if no second element present default "fs" prefix will be used. @param bool $refresh whether to reload the collection instance even if it is found in the cache. @return file\Collection Mongo GridFS collection instance.
[ "Returns", "the", "MongoDB", "GridFS", "collection", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Connection.php#L317-L328
yiisoft/yii2-mongodb
src/Connection.php
Connection.open
public function open() { if ($this->manager === null) { if (empty($this->dsn)) { throw new InvalidConfigException($this->className() . '::dsn cannot be empty.'); } $token = 'Opening MongoDB connection: ' . $this->dsn; try { Yii::trace($token, __METHOD__); Yii::beginProfile($token, __METHOD__); $options = $this->options; $this->manager = new Manager($this->dsn, $options, $this->driverOptions); $this->manager->selectServer($this->manager->getReadPreference()); $this->initConnection(); Yii::endProfile($token, __METHOD__); } catch (\Exception $e) { Yii::endProfile($token, __METHOD__); throw new Exception($e->getMessage(), (int) $e->getCode(), $e); } $this->typeMap = array_merge( $this->typeMap, [ 'root' => 'array', 'document' => 'array' ] ); } }
php
public function open() { if ($this->manager === null) { if (empty($this->dsn)) { throw new InvalidConfigException($this->className() . '::dsn cannot be empty.'); } $token = 'Opening MongoDB connection: ' . $this->dsn; try { Yii::trace($token, __METHOD__); Yii::beginProfile($token, __METHOD__); $options = $this->options; $this->manager = new Manager($this->dsn, $options, $this->driverOptions); $this->manager->selectServer($this->manager->getReadPreference()); $this->initConnection(); Yii::endProfile($token, __METHOD__); } catch (\Exception $e) { Yii::endProfile($token, __METHOD__); throw new Exception($e->getMessage(), (int) $e->getCode(), $e); } $this->typeMap = array_merge( $this->typeMap, [ 'root' => 'array', 'document' => 'array' ] ); } }
[ "public", "function", "open", "(", ")", "{", "if", "(", "$", "this", "->", "manager", "===", "null", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "dsn", ")", ")", "{", "throw", "new", "InvalidConfigException", "(", "$", "this", "->", "clas...
Establishes a Mongo connection. It does nothing if a MongoDB connection has already been established. @throws Exception if connection fails
[ "Establishes", "a", "Mongo", "connection", ".", "It", "does", "nothing", "if", "a", "MongoDB", "connection", "has", "already", "been", "established", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Connection.php#L344-L374
yiisoft/yii2-mongodb
src/Connection.php
Connection.close
public function close() { if ($this->manager !== null) { Yii::trace('Closing MongoDB connection: ' . $this->dsn, __METHOD__); $this->manager = null; foreach ($this->_databases as $database) { $database->clearCollections(); } $this->_databases = []; } }
php
public function close() { if ($this->manager !== null) { Yii::trace('Closing MongoDB connection: ' . $this->dsn, __METHOD__); $this->manager = null; foreach ($this->_databases as $database) { $database->clearCollections(); } $this->_databases = []; } }
[ "public", "function", "close", "(", ")", "{", "if", "(", "$", "this", "->", "manager", "!==", "null", ")", "{", "Yii", "::", "trace", "(", "'Closing MongoDB connection: '", ".", "$", "this", "->", "dsn", ",", "__METHOD__", ")", ";", "$", "this", "->", ...
Closes the currently active DB connection. It does nothing if the connection is already closed.
[ "Closes", "the", "currently", "active", "DB", "connection", ".", "It", "does", "nothing", "if", "the", "connection", "is", "already", "closed", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Connection.php#L380-L390
yiisoft/yii2-mongodb
src/Connection.php
Connection.registerFileStreamWrapper
public function registerFileStreamWrapper($force = false) { if ($force || !$this->_fileStreamWrapperRegistered) { /* @var $class \yii\mongodb\file\StreamWrapper */ $class = $this->fileStreamWrapperClass; $class::register($this->fileStreamProtocol, $force); $this->_fileStreamWrapperRegistered = true; } return $this->fileStreamProtocol; }
php
public function registerFileStreamWrapper($force = false) { if ($force || !$this->_fileStreamWrapperRegistered) { /* @var $class \yii\mongodb\file\StreamWrapper */ $class = $this->fileStreamWrapperClass; $class::register($this->fileStreamProtocol, $force); $this->_fileStreamWrapperRegistered = true; } return $this->fileStreamProtocol; }
[ "public", "function", "registerFileStreamWrapper", "(", "$", "force", "=", "false", ")", "{", "if", "(", "$", "force", "||", "!", "$", "this", "->", "_fileStreamWrapperRegistered", ")", "{", "/* @var $class \\yii\\mongodb\\file\\StreamWrapper */", "$", "class", "=",...
Registers GridFS stream wrapper for the [[fileStreamProtocol]] protocol. @param bool $force whether to enforce registration even wrapper has been already registered. @return string registered stream protocol name.
[ "Registers", "GridFS", "stream", "wrapper", "for", "the", "[[", "fileStreamProtocol", "]]", "protocol", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Connection.php#L423-L434
yiisoft/yii2-mongodb
src/BatchQueryResult.php
BatchQueryResult.reset
public function reset() { $this->_iterator = null; $this->_batch = null; $this->_value = null; $this->_key = null; }
php
public function reset() { $this->_iterator = null; $this->_batch = null; $this->_value = null; $this->_key = null; }
[ "public", "function", "reset", "(", ")", "{", "$", "this", "->", "_iterator", "=", "null", ";", "$", "this", "->", "_batch", "=", "null", ";", "$", "this", "->", "_value", "=", "null", ";", "$", "this", "->", "_key", "=", "null", ";", "}" ]
Resets the batch query. This method will clean up the existing batch query so that a new batch query can be performed.
[ "Resets", "the", "batch", "query", ".", "This", "method", "will", "clean", "up", "the", "existing", "batch", "query", "so", "that", "a", "new", "batch", "query", "can", "be", "performed", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/BatchQueryResult.php#L76-L82
yiisoft/yii2-mongodb
src/BatchQueryResult.php
BatchQueryResult.fetchData
protected function fetchData() { if ($this->_iterator === null) { if (empty($this->query->orderBy)) { // setting cursor batch size may setup implicit limit on the query with 'sort' // @see https://jira.mongodb.org/browse/PHP-457 $this->query->addOptions(['batchSize' => $this->batchSize]); } $cursor = $this->query->buildCursor($this->db); $token = 'fetch cursor id = ' . $cursor->getId(); Yii::info($token, __METHOD__); if ($cursor instanceof \Iterator) { $this->_iterator = $cursor; } else { $this->_iterator = new \IteratorIterator($cursor); } $this->_iterator->rewind(); } $rows = []; $count = 0; while ($count++ < $this->batchSize) { $row = $this->_iterator->current(); if ($row === null) { break; } $this->_iterator->next(); //var_dump($row); $rows[] = $row; } return $this->query->populate($rows); }
php
protected function fetchData() { if ($this->_iterator === null) { if (empty($this->query->orderBy)) { // setting cursor batch size may setup implicit limit on the query with 'sort' // @see https://jira.mongodb.org/browse/PHP-457 $this->query->addOptions(['batchSize' => $this->batchSize]); } $cursor = $this->query->buildCursor($this->db); $token = 'fetch cursor id = ' . $cursor->getId(); Yii::info($token, __METHOD__); if ($cursor instanceof \Iterator) { $this->_iterator = $cursor; } else { $this->_iterator = new \IteratorIterator($cursor); } $this->_iterator->rewind(); } $rows = []; $count = 0; while ($count++ < $this->batchSize) { $row = $this->_iterator->current(); if ($row === null) { break; } $this->_iterator->next(); //var_dump($row); $rows[] = $row; } return $this->query->populate($rows); }
[ "protected", "function", "fetchData", "(", ")", "{", "if", "(", "$", "this", "->", "_iterator", "===", "null", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "query", "->", "orderBy", ")", ")", "{", "// setting cursor batch size may setup implicit lim...
Fetches the next batch of data. @return array the data fetched
[ "Fetches", "the", "next", "batch", "of", "data", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/BatchQueryResult.php#L124-L158
yiisoft/yii2-mongodb
src/validators/MongoDateValidator.php
MongoDateValidator.validateAttribute
public function validateAttribute($model, $attribute) { $mongoDateAttribute = $this->mongoDateAttribute; if ($this->timestampAttribute === null) { $this->timestampAttribute = $mongoDateAttribute; } $originalErrorCount = count($model->getErrors($attribute)); parent::validateAttribute($model, $attribute); $afterValidateErrorCount = count($model->getErrors($attribute)); if ($originalErrorCount === $afterValidateErrorCount) { if ($this->mongoDateAttribute !== null) { $timestamp = $model->{$this->timestampAttribute}; $mongoDateAttributeValue = $model->{$this->mongoDateAttribute}; // ensure "dirty attributes" support : if (!($mongoDateAttributeValue instanceof UTCDateTime) || $mongoDateAttributeValue->sec !== $timestamp) { $model->{$this->mongoDateAttribute} = new UTCDateTime($timestamp * 1000); } } } }
php
public function validateAttribute($model, $attribute) { $mongoDateAttribute = $this->mongoDateAttribute; if ($this->timestampAttribute === null) { $this->timestampAttribute = $mongoDateAttribute; } $originalErrorCount = count($model->getErrors($attribute)); parent::validateAttribute($model, $attribute); $afterValidateErrorCount = count($model->getErrors($attribute)); if ($originalErrorCount === $afterValidateErrorCount) { if ($this->mongoDateAttribute !== null) { $timestamp = $model->{$this->timestampAttribute}; $mongoDateAttributeValue = $model->{$this->mongoDateAttribute}; // ensure "dirty attributes" support : if (!($mongoDateAttributeValue instanceof UTCDateTime) || $mongoDateAttributeValue->sec !== $timestamp) { $model->{$this->mongoDateAttribute} = new UTCDateTime($timestamp * 1000); } } } }
[ "public", "function", "validateAttribute", "(", "$", "model", ",", "$", "attribute", ")", "{", "$", "mongoDateAttribute", "=", "$", "this", "->", "mongoDateAttribute", ";", "if", "(", "$", "this", "->", "timestampAttribute", "===", "null", ")", "{", "$", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/validators/MongoDateValidator.php#L52-L73
yiisoft/yii2-mongodb
src/validators/MongoDateValidator.php
MongoDateValidator.parseDateValue
protected function parseDateValue($value) { return $value instanceof UTCDateTime ? $value->toDateTime()->getTimestamp() : parent::parseDateValue($value); }
php
protected function parseDateValue($value) { return $value instanceof UTCDateTime ? $value->toDateTime()->getTimestamp() : parent::parseDateValue($value); }
[ "protected", "function", "parseDateValue", "(", "$", "value", ")", "{", "return", "$", "value", "instanceof", "UTCDateTime", "?", "$", "value", "->", "toDateTime", "(", ")", "->", "getTimestamp", "(", ")", ":", "parent", "::", "parseDateValue", "(", "$", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/validators/MongoDateValidator.php#L78-L83
yiisoft/yii2-mongodb
src/debug/ExplainAction.php
ExplainAction.run
public function run($seq, $tag) { $this->controller->loadData($tag); $timings = $this->panel->calculateTimings(); if (!isset($timings[$seq])) { throw new HttpException(404, 'Log message not found.'); } $query = $timings[$seq]['info']; if (strpos($query, 'find({') !== 0) { return ''; } $query = substr($query, strlen('find('), -1); $result = $this->explainQuery($query); if (!$result) { return ''; } return Json::encode($result, JSON_PRETTY_PRINT); }
php
public function run($seq, $tag) { $this->controller->loadData($tag); $timings = $this->panel->calculateTimings(); if (!isset($timings[$seq])) { throw new HttpException(404, 'Log message not found.'); } $query = $timings[$seq]['info']; if (strpos($query, 'find({') !== 0) { return ''; } $query = substr($query, strlen('find('), -1); $result = $this->explainQuery($query); if (!$result) { return ''; } return Json::encode($result, JSON_PRETTY_PRINT); }
[ "public", "function", "run", "(", "$", "seq", ",", "$", "tag", ")", "{", "$", "this", "->", "controller", "->", "loadData", "(", "$", "tag", ")", ";", "$", "timings", "=", "$", "this", "->", "panel", "->", "calculateTimings", "(", ")", ";", "if", ...
Runs the explain action @param int $seq @param string $tag @return string explain result content @throws HttpException if requested log not found
[ "Runs", "the", "explain", "action" ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/debug/ExplainAction.php#L36-L59
yiisoft/yii2-mongodb
src/debug/ExplainAction.php
ExplainAction.explainQuery
protected function explainQuery($queryString) { /* @var $connection \yii\mongodb\Connection */ $connection = $this->panel->getDb(); $queryInfo = Json::decode($queryString); if (!isset($queryInfo['ns'])) { return false; } list($databaseName, $collectionName) = explode('.', $queryInfo['ns'], 2); unset($queryInfo['ns']); if (!empty($queryInfo['filer'])) { $queryInfo['filer'] = $this->prepareQueryFiler($queryInfo['filer']); } return $connection->createCommand($databaseName)->explain($collectionName, $queryInfo); }
php
protected function explainQuery($queryString) { /* @var $connection \yii\mongodb\Connection */ $connection = $this->panel->getDb(); $queryInfo = Json::decode($queryString); if (!isset($queryInfo['ns'])) { return false; } list($databaseName, $collectionName) = explode('.', $queryInfo['ns'], 2); unset($queryInfo['ns']); if (!empty($queryInfo['filer'])) { $queryInfo['filer'] = $this->prepareQueryFiler($queryInfo['filer']); } return $connection->createCommand($databaseName)->explain($collectionName, $queryInfo); }
[ "protected", "function", "explainQuery", "(", "$", "queryString", ")", "{", "/* @var $connection \\yii\\mongodb\\Connection */", "$", "connection", "=", "$", "this", "->", "panel", "->", "getDb", "(", ")", ";", "$", "queryInfo", "=", "Json", "::", "decode", "(",...
Runs explain command over the query @param string $queryString query log string. @return array|false explain results, `false` on failure.
[ "Runs", "explain", "command", "over", "the", "query" ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/debug/ExplainAction.php#L67-L85
yiisoft/yii2-mongodb
src/debug/ExplainAction.php
ExplainAction.prepareQueryFiler
private function prepareQueryFiler($query) { $result = []; foreach ($query as $key => $value) { if (is_array($value)) { $result[$key] = $this->prepareQueryFiler($value); } elseif (is_string($value) && preg_match('#^(MongoDB\\\\BSON\\\\[A-Za-z]+)\\((.*)\\)$#s', $value, $matches)) { $class = $matches[1]; $objectValue = $matches[1]; try { $result[$key] = new $class($objectValue); } catch (\Exception $e) { $result[$key] = $value; } } else { $result[$key] = $value; } } return $result; }
php
private function prepareQueryFiler($query) { $result = []; foreach ($query as $key => $value) { if (is_array($value)) { $result[$key] = $this->prepareQueryFiler($value); } elseif (is_string($value) && preg_match('#^(MongoDB\\\\BSON\\\\[A-Za-z]+)\\((.*)\\)$#s', $value, $matches)) { $class = $matches[1]; $objectValue = $matches[1]; try { $result[$key] = new $class($objectValue); } catch (\Exception $e) { $result[$key] = $value; } } else { $result[$key] = $value; } } return $result; }
[ "private", "function", "prepareQueryFiler", "(", "$", "query", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "query", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$"...
Prepare query filer for explain. Converts BSON object log entries into actual objects. @param array $query raw query filter. @return array|string prepared query
[ "Prepare", "query", "filer", "for", "explain", ".", "Converts", "BSON", "object", "log", "entries", "into", "actual", "objects", "." ]
train
https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/debug/ExplainAction.php#L94-L114
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowAction.php
WorkflowAction.canEditTarget
public function canEditTarget(DataObject $target) { $currentUser = Security::getCurrentUser(); if ($currentUser && Permission::checkMember($currentUser, 'ADMIN')) { return true; } return null; }
php
public function canEditTarget(DataObject $target) { $currentUser = Security::getCurrentUser(); if ($currentUser && Permission::checkMember($currentUser, 'ADMIN')) { return true; } return null; }
[ "public", "function", "canEditTarget", "(", "DataObject", "$", "target", ")", "{", "$", "currentUser", "=", "Security", "::", "getCurrentUser", "(", ")", ";", "if", "(", "$", "currentUser", "&&", "Permission", "::", "checkMember", "(", "$", "currentUser", ",...
Can documents in the current workflow state be edited? Only return true or false if this is an absolute value; the WorkflowActionInstance will try and figure out an appropriate value for the actively running workflow if null is returned from this method. Admin level users can always edit. @param DataObject $target @return bool
[ "Can", "documents", "in", "the", "current", "workflow", "state", "be", "edited?" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowAction.php#L80-L88
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowAction.php
WorkflowAction.getInstanceForWorkflow
public function getInstanceForWorkflow() { $instanceClass = $this->config()->get('instance_class'); $instance = new $instanceClass(); $instance->BaseActionID = $this->ID; return $instance; }
php
public function getInstanceForWorkflow() { $instanceClass = $this->config()->get('instance_class'); $instance = new $instanceClass(); $instance->BaseActionID = $this->ID; return $instance; }
[ "public", "function", "getInstanceForWorkflow", "(", ")", "{", "$", "instanceClass", "=", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'instance_class'", ")", ";", "$", "instance", "=", "new", "$", "instanceClass", "(", ")", ";", "$", "insta...
Gets an object that is used for saving the actual state of things during a running workflow. It still uses the workflow action def for managing the functional execution, however if you need to store additional data for the state, you can specify your own WorkflowActionInstance instead of the default to capture these elements @return WorkflowActionInstance
[ "Gets", "an", "object", "that", "is", "used", "for", "saving", "the", "actual", "state", "of", "things", "during", "a", "running", "workflow", ".", "It", "still", "uses", "the", "workflow", "action", "def", "for", "managing", "the", "functional", "execution"...
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowAction.php#L163-L169
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowAction.php
WorkflowAction.onAfterDelete
public function onAfterDelete() { parent::onAfterDelete(); $wfActionInstances = WorkflowActionInstance::get() /** @skipUpgrade */ ->leftJoin('WorkflowInstance', '"WorkflowInstance"."ID" = "WorkflowActionInstance"."WorkflowID"') ->where(sprintf('"BaseActionID" = %d AND ("WorkflowStatus" IN (\'Active\',\'Paused\'))', $this->ID)); foreach ($wfActionInstances as $wfActionInstance) { $wfInstances = WorkflowInstance::get()->filter('CurrentActionID', $wfActionInstance->ID); foreach ($wfInstances as $wfInstance) { $wfInstance->Groups()->removeAll(); $wfInstance->Users()->removeAll(); $wfInstance->delete(); } $wfActionInstance->delete(); } // Delete outbound transitions $transitions = WorkflowTransition::get()->filter('ActionID', $this->ID); foreach ($transitions as $transition) { $transition->Groups()->removeAll(); $transition->Users()->removeAll(); $transition->delete(); } }
php
public function onAfterDelete() { parent::onAfterDelete(); $wfActionInstances = WorkflowActionInstance::get() /** @skipUpgrade */ ->leftJoin('WorkflowInstance', '"WorkflowInstance"."ID" = "WorkflowActionInstance"."WorkflowID"') ->where(sprintf('"BaseActionID" = %d AND ("WorkflowStatus" IN (\'Active\',\'Paused\'))', $this->ID)); foreach ($wfActionInstances as $wfActionInstance) { $wfInstances = WorkflowInstance::get()->filter('CurrentActionID', $wfActionInstance->ID); foreach ($wfInstances as $wfInstance) { $wfInstance->Groups()->removeAll(); $wfInstance->Users()->removeAll(); $wfInstance->delete(); } $wfActionInstance->delete(); } // Delete outbound transitions $transitions = WorkflowTransition::get()->filter('ActionID', $this->ID); foreach ($transitions as $transition) { $transition->Groups()->removeAll(); $transition->Users()->removeAll(); $transition->delete(); } }
[ "public", "function", "onAfterDelete", "(", ")", "{", "parent", "::", "onAfterDelete", "(", ")", ";", "$", "wfActionInstances", "=", "WorkflowActionInstance", "::", "get", "(", ")", "/** @skipUpgrade */", "->", "leftJoin", "(", "'WorkflowInstance'", ",", "'\"Workf...
When deleting an action from a workflow definition, make sure that workflows currently paused on that action are deleted Also removes all outbound transitions
[ "When", "deleting", "an", "action", "from", "a", "workflow", "definition", "make", "sure", "that", "workflows", "currently", "paused", "on", "that", "action", "are", "deleted", "Also", "removes", "all", "outbound", "transitions" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowAction.php#L198-L221
symbiote/silverstripe-advancedworkflow
src/Admin/WorkflowDefinitionExporter.php
WorkflowDefinitionExporter.export
public function export() { // Disable any access to use of WorkflowExport if user has no SecurityAdmin access if (!Permission::check('CMS_ACCESS_SecurityAdmin')) { throw new Exception(_t('SilverStripe\\ErrorPage\\ErrorPage.CODE_403', '403 - Forbidden'), 403); } $def = $this->getDefinition(); $templateData = new ArrayData(array( 'ExportMetaData' => $this->ExportMetaData(), 'ExportActions' => $def->Actions(), 'ExportUsers' => $def->Users(), 'ExportGroups' => $def->Groups() )); return $this->format($templateData); }
php
public function export() { // Disable any access to use of WorkflowExport if user has no SecurityAdmin access if (!Permission::check('CMS_ACCESS_SecurityAdmin')) { throw new Exception(_t('SilverStripe\\ErrorPage\\ErrorPage.CODE_403', '403 - Forbidden'), 403); } $def = $this->getDefinition(); $templateData = new ArrayData(array( 'ExportMetaData' => $this->ExportMetaData(), 'ExportActions' => $def->Actions(), 'ExportUsers' => $def->Users(), 'ExportGroups' => $def->Groups() )); return $this->format($templateData); }
[ "public", "function", "export", "(", ")", "{", "// Disable any access to use of WorkflowExport if user has no SecurityAdmin access", "if", "(", "!", "Permission", "::", "check", "(", "'CMS_ACCESS_SecurityAdmin'", ")", ")", "{", "throw", "new", "Exception", "(", "_t", "(...
Runs the export @return string $template @throws Exception if the current user doesn't have permission to access export functionality
[ "Runs", "the", "export" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Admin/WorkflowDefinitionExporter.php#L88-L102
symbiote/silverstripe-advancedworkflow
src/Admin/WorkflowDefinitionExporter.php
WorkflowDefinitionExporter.format
public function format($templateData) { $viewer = SSViewer::execute_template(['type' => 'Includes', 'WorkflowDefinitionExport'], $templateData); // Temporary until we find the source of the replacement in SSViewer $processed = str_replace('&amp;', '&', $viewer); // Clean-up newline "gaps" that SSViewer leaves behind from the placement of template control structures return preg_replace("#^\R+|^[\t\s]*\R+#m", '', $processed); }
php
public function format($templateData) { $viewer = SSViewer::execute_template(['type' => 'Includes', 'WorkflowDefinitionExport'], $templateData); // Temporary until we find the source of the replacement in SSViewer $processed = str_replace('&amp;', '&', $viewer); // Clean-up newline "gaps" that SSViewer leaves behind from the placement of template control structures return preg_replace("#^\R+|^[\t\s]*\R+#m", '', $processed); }
[ "public", "function", "format", "(", "$", "templateData", ")", "{", "$", "viewer", "=", "SSViewer", "::", "execute_template", "(", "[", "'type'", "=>", "'Includes'", ",", "'WorkflowDefinitionExport'", "]", ",", "$", "templateData", ")", ";", "// Temporary until ...
Format the exported data as YAML. @param ArrayData $templateData @return void
[ "Format", "the", "exported", "data", "as", "YAML", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Admin/WorkflowDefinitionExporter.php#L110-L117
symbiote/silverstripe-advancedworkflow
src/Admin/WorkflowDefinitionExporter.php
WorkflowDefinitionExporter.ExportMetaData
public function ExportMetaData() { $def = $this->getDefinition(); return new ArrayData(array( 'ExportHost' => preg_replace("#http(s)?://#", '', Director::protocolAndHost()), 'ExportDate' => date('d/m/Y H-i-s'), 'ExportUser' => $this->member->FirstName.' '.$this->member->Surname, 'ExportVersionFramework' => $this->ssVersion(), 'ExportWorkflowDefName' => $this->processTitle($def->Title), 'ExportRemindDays' => $def->RemindDays, 'ExportSort' => $def->Sort )); }
php
public function ExportMetaData() { $def = $this->getDefinition(); return new ArrayData(array( 'ExportHost' => preg_replace("#http(s)?://#", '', Director::protocolAndHost()), 'ExportDate' => date('d/m/Y H-i-s'), 'ExportUser' => $this->member->FirstName.' '.$this->member->Surname, 'ExportVersionFramework' => $this->ssVersion(), 'ExportWorkflowDefName' => $this->processTitle($def->Title), 'ExportRemindDays' => $def->RemindDays, 'ExportSort' => $def->Sort )); }
[ "public", "function", "ExportMetaData", "(", ")", "{", "$", "def", "=", "$", "this", "->", "getDefinition", "(", ")", ";", "return", "new", "ArrayData", "(", "array", "(", "'ExportHost'", "=>", "preg_replace", "(", "\"#http(s)?://#\"", ",", "''", ",", "Dir...
Generate template vars for metadata @return ArrayData
[ "Generate", "template", "vars", "for", "metadata" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Admin/WorkflowDefinitionExporter.php#L136-L148
symbiote/silverstripe-advancedworkflow
src/Admin/WorkflowDefinitionExporter.php
WorkflowDefinitionExporter.ssVersion
private function ssVersion() { // Remove colons so they don't screw with YAML parsing $versionSapphire = str_replace(':', '', singleton(SapphireInfo::class)->Version()); $versionLeftMain = str_replace(':', '', singleton(LeftAndMain::class)->CMSVersion()); if ($versionSapphire != _t('SilverStripe\\Admin\\LeftAndMain.VersionUnknown', 'Unknown')) { return $versionSapphire; } return $versionLeftMain; }
php
private function ssVersion() { // Remove colons so they don't screw with YAML parsing $versionSapphire = str_replace(':', '', singleton(SapphireInfo::class)->Version()); $versionLeftMain = str_replace(':', '', singleton(LeftAndMain::class)->CMSVersion()); if ($versionSapphire != _t('SilverStripe\\Admin\\LeftAndMain.VersionUnknown', 'Unknown')) { return $versionSapphire; } return $versionLeftMain; }
[ "private", "function", "ssVersion", "(", ")", "{", "// Remove colons so they don't screw with YAML parsing", "$", "versionSapphire", "=", "str_replace", "(", "':'", ",", "''", ",", "singleton", "(", "SapphireInfo", "::", "class", ")", "->", "Version", "(", ")", ")...
Try different ways of obtaining the current SilverStripe version for YAML output. @return string
[ "Try", "different", "ways", "of", "obtaining", "the", "current", "SilverStripe", "version", "for", "YAML", "output", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Admin/WorkflowDefinitionExporter.php#L155-L164
symbiote/silverstripe-advancedworkflow
src/Admin/WorkflowDefinitionExporter.php
WorkflowDefinitionExporter.sendFile
public function sendFile($filedata) { $response = new HTTPResponse($filedata['body']); if (preg_match("#MSIE\s(6|7|8)?\.0#", $_SERVER['HTTP_USER_AGENT'])) { // IE headers $response->addHeader("Cache-Control", "public"); $response->addHeader("Content-Disposition", "attachment; filename=\"".basename($filedata['name'])."\""); $response->addHeader("Content-Type", "application/force-download"); $response->addHeader("Content-Type", "application/octet-stream"); $response->addHeader("Content-Type", "application/download"); $response->addHeader("Content-Type", $filedata['mime']); $response->addHeader("Content-Description", "File Transfer"); $response->addHeader("Content-Length", $filedata['size']); } else { // Everyone else $response->addHeader("Content-Type", $filedata['mime']."; name=\"".addslashes($filedata['name'])."\""); $response->addHeader("Content-disposition", "attachment; filename=".addslashes($filedata['name'])); $response->addHeader("Content-Length", $filedata['size']); } return $response; }
php
public function sendFile($filedata) { $response = new HTTPResponse($filedata['body']); if (preg_match("#MSIE\s(6|7|8)?\.0#", $_SERVER['HTTP_USER_AGENT'])) { // IE headers $response->addHeader("Cache-Control", "public"); $response->addHeader("Content-Disposition", "attachment; filename=\"".basename($filedata['name'])."\""); $response->addHeader("Content-Type", "application/force-download"); $response->addHeader("Content-Type", "application/octet-stream"); $response->addHeader("Content-Type", "application/download"); $response->addHeader("Content-Type", $filedata['mime']); $response->addHeader("Content-Description", "File Transfer"); $response->addHeader("Content-Length", $filedata['size']); } else { // Everyone else $response->addHeader("Content-Type", $filedata['mime']."; name=\"".addslashes($filedata['name'])."\""); $response->addHeader("Content-disposition", "attachment; filename=".addslashes($filedata['name'])); $response->addHeader("Content-Length", $filedata['size']); } return $response; }
[ "public", "function", "sendFile", "(", "$", "filedata", ")", "{", "$", "response", "=", "new", "HTTPResponse", "(", "$", "filedata", "[", "'body'", "]", ")", ";", "if", "(", "preg_match", "(", "\"#MSIE\\s(6|7|8)?\\.0#\"", ",", "$", "_SERVER", "[", "'HTTP_U...
Prompt the client for file download. We're "overriding" SS_HTTPRequest::send_file() for more robust cross-browser support @param array $filedata @return HTTPResponse $response
[ "Prompt", "the", "client", "for", "file", "download", ".", "We", "re", "overriding", "SS_HTTPRequest", "::", "send_file", "()", "for", "more", "robust", "cross", "-", "browser", "support" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Admin/WorkflowDefinitionExporter.php#L180-L200
symbiote/silverstripe-advancedworkflow
src/Controllers/FrontEndWorkflowController.php
FrontEndWorkflowController.Form
public function Form() { $svc = singleton(WorkflowService::class); $active = $svc->getWorkflowFor($this->getContextObject()); if (!$active) { return; //throw new Exception('Workflow not found, or not specified for Context Object'); } $wfFields = $active->getFrontEndWorkflowFields(); $wfActions = $active->getFrontEndWorkflowActions(); $wfValidator = $active->getFrontEndRequiredFields(); //Get DataObject for Form (falls back to ContextObject if not defined in WorkflowAction) $wfDataObject = $active->getFrontEndDataObject(); // set any requirements spcific to this contextobject $active->setFrontendFormRequirements(); // hooks for decorators $this->extend('updateFrontEndWorkflowFields', $wfFields); $this->extend('updateFrontEndWorkflowActions', $wfActions); $this->extend('updateFrontEndRequiredFields', $wfValidator); $this->extend('updateFrontendFormRequirements'); $form = new FrontendWorkflowForm($this, 'Form/' . $this->getContextID(), $wfFields, $wfActions, $wfValidator); $form->addExtraClass("fwf"); if ($wfDataObject) { $form->loadDataFrom($wfDataObject); } return $form; }
php
public function Form() { $svc = singleton(WorkflowService::class); $active = $svc->getWorkflowFor($this->getContextObject()); if (!$active) { return; //throw new Exception('Workflow not found, or not specified for Context Object'); } $wfFields = $active->getFrontEndWorkflowFields(); $wfActions = $active->getFrontEndWorkflowActions(); $wfValidator = $active->getFrontEndRequiredFields(); //Get DataObject for Form (falls back to ContextObject if not defined in WorkflowAction) $wfDataObject = $active->getFrontEndDataObject(); // set any requirements spcific to this contextobject $active->setFrontendFormRequirements(); // hooks for decorators $this->extend('updateFrontEndWorkflowFields', $wfFields); $this->extend('updateFrontEndWorkflowActions', $wfActions); $this->extend('updateFrontEndRequiredFields', $wfValidator); $this->extend('updateFrontendFormRequirements'); $form = new FrontendWorkflowForm($this, 'Form/' . $this->getContextID(), $wfFields, $wfActions, $wfValidator); $form->addExtraClass("fwf"); if ($wfDataObject) { $form->loadDataFrom($wfDataObject); } return $form; }
[ "public", "function", "Form", "(", ")", "{", "$", "svc", "=", "singleton", "(", "WorkflowService", "::", "class", ")", ";", "$", "active", "=", "$", "svc", "->", "getWorkflowFor", "(", "$", "this", "->", "getContextObject", "(", ")", ")", ";", "if", ...
Create the Form containing: - fields from the Context Object - required fields from the Context Object - Actions from the connected WorkflowTransitions @return Form
[ "Create", "the", "Form", "containing", ":", "-", "fields", "from", "the", "Context", "Object", "-", "required", "fields", "from", "the", "Context", "Object", "-", "Actions", "from", "the", "connected", "WorkflowTransitions" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Controllers/FrontEndWorkflowController.php#L99-L134
symbiote/silverstripe-advancedworkflow
src/Controllers/FrontEndWorkflowController.php
FrontEndWorkflowController.doFrontEndAction
public function doFrontEndAction(array $data, Form $form, HTTPRequest $request) { if (!$obj = $this->getContextObject()) { throw new Exception( _t( 'FrontEndWorkflowController.FRONTENDACTION_CONTEXT_EXCEPTION', 'Context Object Not Found' ) ); } if (!$this->getCurrentTransition()->canExecute($this->contextObj->getWorkflowInstance())) { throw new Exception( _t( 'FrontEndWorkflowController.FRONTENDACTION_TRANSITION_EXCEPTION', 'You do not have permission to execute this action' ) ); } //Only Save data when Transition is 'Active' if ($this->getCurrentTransition()->Type == 'Active') { //Hand off to WorkflowAction to perform Save $svc = singleton(WorkflowService::class); $active = $svc->getWorkflowFor($obj); $active->doFrontEndAction($data, $form, $request); } //run execute on WorkflowInstance instance $action = $this->contextObj->getWorkflowInstance()->currentAction(); $action->BaseAction()->execute($this->contextObj->getWorkflowInstance()); //get valid transitions $transitions = $action->getValidTransitions(); //tell instance to execute transition if it's in the permitted list if ($transitions->find('ID', $this->transitionID)) { $this->contextObj->getWorkflowInstance()->performTransition($this->getCurrentTransition()); } }
php
public function doFrontEndAction(array $data, Form $form, HTTPRequest $request) { if (!$obj = $this->getContextObject()) { throw new Exception( _t( 'FrontEndWorkflowController.FRONTENDACTION_CONTEXT_EXCEPTION', 'Context Object Not Found' ) ); } if (!$this->getCurrentTransition()->canExecute($this->contextObj->getWorkflowInstance())) { throw new Exception( _t( 'FrontEndWorkflowController.FRONTENDACTION_TRANSITION_EXCEPTION', 'You do not have permission to execute this action' ) ); } //Only Save data when Transition is 'Active' if ($this->getCurrentTransition()->Type == 'Active') { //Hand off to WorkflowAction to perform Save $svc = singleton(WorkflowService::class); $active = $svc->getWorkflowFor($obj); $active->doFrontEndAction($data, $form, $request); } //run execute on WorkflowInstance instance $action = $this->contextObj->getWorkflowInstance()->currentAction(); $action->BaseAction()->execute($this->contextObj->getWorkflowInstance()); //get valid transitions $transitions = $action->getValidTransitions(); //tell instance to execute transition if it's in the permitted list if ($transitions->find('ID', $this->transitionID)) { $this->contextObj->getWorkflowInstance()->performTransition($this->getCurrentTransition()); } }
[ "public", "function", "doFrontEndAction", "(", "array", "$", "data", ",", "Form", "$", "form", ",", "HTTPRequest", "$", "request", ")", "{", "if", "(", "!", "$", "obj", "=", "$", "this", "->", "getContextObject", "(", ")", ")", "{", "throw", "new", "...
Save the Form Data to the defined Context Object @param array $data @param Form $form @param SS_HTTPRequest $request @throws Exception
[ "Save", "the", "Form", "Data", "to", "the", "defined", "Context", "Object" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Controllers/FrontEndWorkflowController.php#L156-L196
symbiote/silverstripe-advancedworkflow
src/Controllers/FrontEndWorkflowController.php
FrontEndWorkflowController.Title
public function Title() { if (!$this->Title) { if ($this->getContextObject()) { if ($workflow = $this->contextObj->getWorkflowInstance()) { $this->Title = $workflow->currentAction()->BaseAction()->PageTitle ? $workflow->currentAction()->BaseAction()->PageTitle : $workflow->currentAction()->Title; } } } return $this->Title; }
php
public function Title() { if (!$this->Title) { if ($this->getContextObject()) { if ($workflow = $this->contextObj->getWorkflowInstance()) { $this->Title = $workflow->currentAction()->BaseAction()->PageTitle ? $workflow->currentAction()->BaseAction()->PageTitle : $workflow->currentAction()->Title; } } } return $this->Title; }
[ "public", "function", "Title", "(", ")", "{", "if", "(", "!", "$", "this", "->", "Title", ")", "{", "if", "(", "$", "this", "->", "getContextObject", "(", ")", ")", "{", "if", "(", "$", "workflow", "=", "$", "this", "->", "contextObj", "->", "get...
checks to see if there is a title set on the current workflow action uses that or falls back to controller->Title
[ "checks", "to", "see", "if", "there", "is", "a", "title", "set", "on", "the", "current", "workflow", "action", "uses", "that", "or", "falls", "back", "to", "controller", "-", ">", "Title" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Controllers/FrontEndWorkflowController.php#L202-L214
symbiote/silverstripe-advancedworkflow
src/Templates/WorkflowTemplate.php
WorkflowTemplate.createRelations
public function createRelations($definition = null) { $actions = array(); $transitions = new ArrayObject(); $sort = 1; foreach ($this->structure as $relationName => $relationTemplate) { $isAction = isset($relationTemplate['type']); $isUsers = ($relationName == 'users'); $isGroups = ($relationName == 'groups'); // Process actions on WorkflowDefinition from the template if ($isAction) { $action = $this->createAction($relationName, $relationTemplate, $definition); // add a sort value in! $action->Sort = $sort++; $action->write(); $actions[$relationName] = $action; $newTransitions = $this->updateActionTransitions($relationTemplate, $action); foreach ($newTransitions as $t) { $transitions->append($t); } } // Process users on WorkflowDefinition from the template if ($isUsers) { $this->createUsers($relationTemplate, $definition); } // Process groups on WorkflowDefinition from the template if ($isGroups) { $this->createGroups($relationTemplate, $definition); } } foreach ($transitions as $transition) { if (isset($actions[$transition->Target])) { $transition->NextActionID = $actions[$transition->Target]->ID; } $transition->write(); } return $actions; }
php
public function createRelations($definition = null) { $actions = array(); $transitions = new ArrayObject(); $sort = 1; foreach ($this->structure as $relationName => $relationTemplate) { $isAction = isset($relationTemplate['type']); $isUsers = ($relationName == 'users'); $isGroups = ($relationName == 'groups'); // Process actions on WorkflowDefinition from the template if ($isAction) { $action = $this->createAction($relationName, $relationTemplate, $definition); // add a sort value in! $action->Sort = $sort++; $action->write(); $actions[$relationName] = $action; $newTransitions = $this->updateActionTransitions($relationTemplate, $action); foreach ($newTransitions as $t) { $transitions->append($t); } } // Process users on WorkflowDefinition from the template if ($isUsers) { $this->createUsers($relationTemplate, $definition); } // Process groups on WorkflowDefinition from the template if ($isGroups) { $this->createGroups($relationTemplate, $definition); } } foreach ($transitions as $transition) { if (isset($actions[$transition->Target])) { $transition->NextActionID = $actions[$transition->Target]->ID; } $transition->write(); } return $actions; }
[ "public", "function", "createRelations", "(", "$", "definition", "=", "null", ")", "{", "$", "actions", "=", "array", "(", ")", ";", "$", "transitions", "=", "new", "ArrayObject", "(", ")", ";", "$", "sort", "=", "1", ";", "foreach", "(", "$", "this"...
Creates the relevant data objects for this structure, returning an array of actions in the order they've been created @param WorkflowDefinition $definitino An optional workflow definition to bind the actions into @return array
[ "Creates", "the", "relevant", "data", "objects", "for", "this", "structure", "returning", "an", "array", "of", "actions", "in", "the", "order", "they", "ve", "been", "created" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Templates/WorkflowTemplate.php#L138-L180
symbiote/silverstripe-advancedworkflow
src/Templates/WorkflowTemplate.php
WorkflowTemplate.createAction
protected function createAction($name, $actionTemplate, WorkflowDefinition $definition = null) { $type = $actionTemplate['type']; if (!$type || !class_exists($type)) { throw new Exception(_t( 'WorkflowTemplate.INVALID_TEMPLATE_ACTION', 'Invalid action class specified in template' )); } $action = $type::create(); $action->Title = $name; if (isset($actionTemplate['properties']) && is_array($actionTemplate['properties'])) { foreach ($actionTemplate['properties'] as $prop => $val) { $action->$prop = $val; } } // Deal with User + Group many_many relations on an action $this->addManyManyToObject($action, $actionTemplate); if ($definition) { $action->WorkflowDefID = $definition->ID; } $action->write(); return $action; }
php
protected function createAction($name, $actionTemplate, WorkflowDefinition $definition = null) { $type = $actionTemplate['type']; if (!$type || !class_exists($type)) { throw new Exception(_t( 'WorkflowTemplate.INVALID_TEMPLATE_ACTION', 'Invalid action class specified in template' )); } $action = $type::create(); $action->Title = $name; if (isset($actionTemplate['properties']) && is_array($actionTemplate['properties'])) { foreach ($actionTemplate['properties'] as $prop => $val) { $action->$prop = $val; } } // Deal with User + Group many_many relations on an action $this->addManyManyToObject($action, $actionTemplate); if ($definition) { $action->WorkflowDefID = $definition->ID; } $action->write(); return $action; }
[ "protected", "function", "createAction", "(", "$", "name", ",", "$", "actionTemplate", ",", "WorkflowDefinition", "$", "definition", "=", "null", ")", "{", "$", "type", "=", "$", "actionTemplate", "[", "'type'", "]", ";", "if", "(", "!", "$", "type", "||...
Create a workflow action based on a template @param string $name @param array $template @param WorkflowDefinition $definition @return WorkflowAction @throws Exception
[ "Create", "a", "workflow", "action", "based", "on", "a", "template" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Templates/WorkflowTemplate.php#L191-L221
symbiote/silverstripe-advancedworkflow
src/Templates/WorkflowTemplate.php
WorkflowTemplate.createUsers
protected function createUsers($users, WorkflowDefinition $definition, $clear = false) { // Create the necessary relation in WorkflowDefinition_Users $source = array('users' => $users); $this->addManyManyToObject($definition, $source, $clear); }
php
protected function createUsers($users, WorkflowDefinition $definition, $clear = false) { // Create the necessary relation in WorkflowDefinition_Users $source = array('users' => $users); $this->addManyManyToObject($definition, $source, $clear); }
[ "protected", "function", "createUsers", "(", "$", "users", ",", "WorkflowDefinition", "$", "definition", ",", "$", "clear", "=", "false", ")", "{", "// Create the necessary relation in WorkflowDefinition_Users", "$", "source", "=", "array", "(", "'users'", "=>", "$"...
Create a WorkflowDefinition->Users relation based on template data. But only if the related groups from the export, can be foud in the target environment's DB. Note: The template gives us a Member Email to work with rather than an ID as it's arguably more likely that Member Emails will be the same between environments than their IDs. @param array $users @param WorkflowDefinition $definition @param boolean $clear @return void
[ "Create", "a", "WorkflowDefinition", "-", ">", "Users", "relation", "based", "on", "template", "data", ".", "But", "only", "if", "the", "related", "groups", "from", "the", "export", "can", "be", "foud", "in", "the", "target", "environment", "s", "DB", "." ...
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Templates/WorkflowTemplate.php#L235-L240
symbiote/silverstripe-advancedworkflow
src/Templates/WorkflowTemplate.php
WorkflowTemplate.createGroups
protected function createGroups($groups, WorkflowDefinition $definition, $clear = false) { // Create the necessary relation in WorkflowDefinition_Groups $source = array('groups' => $groups); $this->addManyManyToObject($definition, $source, $clear); }
php
protected function createGroups($groups, WorkflowDefinition $definition, $clear = false) { // Create the necessary relation in WorkflowDefinition_Groups $source = array('groups' => $groups); $this->addManyManyToObject($definition, $source, $clear); }
[ "protected", "function", "createGroups", "(", "$", "groups", ",", "WorkflowDefinition", "$", "definition", ",", "$", "clear", "=", "false", ")", "{", "// Create the necessary relation in WorkflowDefinition_Groups", "$", "source", "=", "array", "(", "'groups'", "=>", ...
Create a WorkflowDefinition->Groups relation based on template data, But only if the related groups from the export, can be foud in the target environment's DB. Note: The template gives us a Group Title to work with rther than an ID as it's arguably more likely that Group titles will be the same between environments than their IDs. @param array $groups @param WorkflowDefinition $definition @param boolean $clear @return void
[ "Create", "a", "WorkflowDefinition", "-", ">", "Groups", "relation", "based", "on", "template", "data", "But", "only", "if", "the", "related", "groups", "from", "the", "export", "can", "be", "foud", "in", "the", "target", "environment", "s", "DB", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Templates/WorkflowTemplate.php#L254-L259
symbiote/silverstripe-advancedworkflow
src/Templates/WorkflowTemplate.php
WorkflowTemplate.updateActionTransitions
protected function updateActionTransitions($actionTemplate, $action) { $transitions = array(); if (isset($actionTemplate['transitions']) && is_array($actionTemplate['transitions'])) { $existing = $action->Transitions(); $transitionMap = array(); foreach ($existing as $transition) { $transitionMap[$transition->Title] = $transition; } foreach ($actionTemplate['transitions'] as $transitionName => $transitionTemplate) { $target = $transitionTemplate; if (is_array($transitionTemplate)) { $to = array_keys($transitionTemplate); $transitionName = $to[0]; $target = $transitionTemplate[$transitionName]; } if (isset($transitionMap[$transitionName])) { $transition = $transitionMap[$transitionName]; } else { $transition = WorkflowTransition::create(); } // Add Member and Group relations to this Transition $this->addManyManyToObject($transition, $transitionTemplate); $transition->Title = $transitionName; $transition->ActionID = $action->ID; // we don't have the NextAction yet other than the target name, so we store that against // the transition and do a second pass later on to match things up $transition->Target = $target; $transitions[] = $transition; } } return $transitions; }
php
protected function updateActionTransitions($actionTemplate, $action) { $transitions = array(); if (isset($actionTemplate['transitions']) && is_array($actionTemplate['transitions'])) { $existing = $action->Transitions(); $transitionMap = array(); foreach ($existing as $transition) { $transitionMap[$transition->Title] = $transition; } foreach ($actionTemplate['transitions'] as $transitionName => $transitionTemplate) { $target = $transitionTemplate; if (is_array($transitionTemplate)) { $to = array_keys($transitionTemplate); $transitionName = $to[0]; $target = $transitionTemplate[$transitionName]; } if (isset($transitionMap[$transitionName])) { $transition = $transitionMap[$transitionName]; } else { $transition = WorkflowTransition::create(); } // Add Member and Group relations to this Transition $this->addManyManyToObject($transition, $transitionTemplate); $transition->Title = $transitionName; $transition->ActionID = $action->ID; // we don't have the NextAction yet other than the target name, so we store that against // the transition and do a second pass later on to match things up $transition->Target = $target; $transitions[] = $transition; } } return $transitions; }
[ "protected", "function", "updateActionTransitions", "(", "$", "actionTemplate", ",", "$", "action", ")", "{", "$", "transitions", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "actionTemplate", "[", "'transitions'", "]", ")", "&&", "is_array", ...
Update the transitions for a given action @param array $actionTemplate @param WorkflowAction $action @return array
[ "Update", "the", "transitions", "for", "a", "given", "action" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Templates/WorkflowTemplate.php#L269-L306
symbiote/silverstripe-advancedworkflow
src/Templates/WorkflowTemplate.php
WorkflowTemplate.updateDefinition
public function updateDefinition(WorkflowDefinition $definition) { $existingActions = array(); $existing = $definition->Actions()->column('Title'); $structure = array_keys($this->structure); $removeNames = array_diff($existing, $structure); foreach ($definition->Actions() as $action) { if (in_array($action->Title, $removeNames)) { $action->delete(); continue; } $existingActions[$action->Title] = $action; } $actions = array(); $transitions = new ArrayObject; $sort = 1; // now, go through the structure and create/realign things foreach ($this->structure as $relationName => $relationTemplate) { $isAction = isset($relationTemplate['type']); $isUsers = ($relationName == 'users'); $isGroups = ($relationName == 'groups'); if ($isAction) { $action = null; if (isset($existingActions[$relationName])) { $action = $existingActions[$relationName]; } else { $action = $this->createAction($relationName, $relationTemplate, $definition, $transitions); } // add a sort value in! $action->Sort = $sort++; $action->write(); $actions[$relationName] = $action; $newTransitions = $this->updateActionTransitions($relationTemplate, $action); foreach ($newTransitions as $t) { $transitions->append($t); } } // Process users on WorkflowDefinition from the template if ($isUsers) { $this->createUsers($relationTemplate, $definition, true); } // Process groups on WorkflowDefinition from the template if ($isGroups) { $this->createGroups($relationTemplate, $definition, true); } } foreach ($transitions as $transition) { if (isset($actions[$transition->Target])) { $transition->NextActionID = $actions[$transition->Target]->ID; } $transition->write(); } // Set the version and do the write at the end so that we don't trigger an infinite loop!! $definition->Description = $this->getDescription(); $definition->TemplateVersion = $this->getVersion(); $definition->RemindDays = $this->getRemindDays(); $definition->Sort = $this->getSort(); $definition->write(); }
php
public function updateDefinition(WorkflowDefinition $definition) { $existingActions = array(); $existing = $definition->Actions()->column('Title'); $structure = array_keys($this->structure); $removeNames = array_diff($existing, $structure); foreach ($definition->Actions() as $action) { if (in_array($action->Title, $removeNames)) { $action->delete(); continue; } $existingActions[$action->Title] = $action; } $actions = array(); $transitions = new ArrayObject; $sort = 1; // now, go through the structure and create/realign things foreach ($this->structure as $relationName => $relationTemplate) { $isAction = isset($relationTemplate['type']); $isUsers = ($relationName == 'users'); $isGroups = ($relationName == 'groups'); if ($isAction) { $action = null; if (isset($existingActions[$relationName])) { $action = $existingActions[$relationName]; } else { $action = $this->createAction($relationName, $relationTemplate, $definition, $transitions); } // add a sort value in! $action->Sort = $sort++; $action->write(); $actions[$relationName] = $action; $newTransitions = $this->updateActionTransitions($relationTemplate, $action); foreach ($newTransitions as $t) { $transitions->append($t); } } // Process users on WorkflowDefinition from the template if ($isUsers) { $this->createUsers($relationTemplate, $definition, true); } // Process groups on WorkflowDefinition from the template if ($isGroups) { $this->createGroups($relationTemplate, $definition, true); } } foreach ($transitions as $transition) { if (isset($actions[$transition->Target])) { $transition->NextActionID = $actions[$transition->Target]->ID; } $transition->write(); } // Set the version and do the write at the end so that we don't trigger an infinite loop!! $definition->Description = $this->getDescription(); $definition->TemplateVersion = $this->getVersion(); $definition->RemindDays = $this->getRemindDays(); $definition->Sort = $this->getSort(); $definition->write(); }
[ "public", "function", "updateDefinition", "(", "WorkflowDefinition", "$", "definition", ")", "{", "$", "existingActions", "=", "array", "(", ")", ";", "$", "existing", "=", "$", "definition", "->", "Actions", "(", ")", "->", "column", "(", "'Title'", ")", ...
Update a workflow definition @param WorkflowDefinition $definition The definition to update
[ "Update", "a", "workflow", "definition" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Templates/WorkflowTemplate.php#L313-L381
symbiote/silverstripe-advancedworkflow
src/Templates/WorkflowTemplate.php
WorkflowTemplate.addManyManyToObject
protected function addManyManyToObject($object, $source, $clear = false) { // Check incoming if (!is_object($object) || !is_array($source)) { return; } // Only some target class variants actually have Group/User relations $hasUsers = false; $hasGroups = false; if ($manyMany = $object->stat('many_many')) { if (in_array(Member::class, $manyMany)) { $hasUsers = true; $userRelationName = array_keys($manyMany); } if (in_array(Group::class, $manyMany)) { $hasGroups = true; $groupRelationName = array_keys($manyMany); } } // Deal with User relations on target object if ($hasUsers) { if ($clear) { $relName = $userRelationName[0]; $object->$relName()->removeAll(); } if (isset($source['users']) && is_array($source['users'])) { foreach ($source['users'] as $user) { $email = Convert::raw2sql($user['email']); if ($_user = DataObject::get_one(Member::class, "Email = '".$email."'")) { $object->Users()->add($_user); } } } } // Deal with Group relations on target object if ($hasGroups) { if ($clear) { $relName = $groupRelationName[0]; $object->$relName()->removeAll(); } if (isset($source['groups']) && is_array($source['groups'])) { foreach ($source['groups'] as $group) { $title = Convert::raw2sql($group['title']); if ($_group = DataObject::get_one(Group::class, "Title = '".$title."'")) { $object->Groups()->add($_group); } } } } }
php
protected function addManyManyToObject($object, $source, $clear = false) { // Check incoming if (!is_object($object) || !is_array($source)) { return; } // Only some target class variants actually have Group/User relations $hasUsers = false; $hasGroups = false; if ($manyMany = $object->stat('many_many')) { if (in_array(Member::class, $manyMany)) { $hasUsers = true; $userRelationName = array_keys($manyMany); } if (in_array(Group::class, $manyMany)) { $hasGroups = true; $groupRelationName = array_keys($manyMany); } } // Deal with User relations on target object if ($hasUsers) { if ($clear) { $relName = $userRelationName[0]; $object->$relName()->removeAll(); } if (isset($source['users']) && is_array($source['users'])) { foreach ($source['users'] as $user) { $email = Convert::raw2sql($user['email']); if ($_user = DataObject::get_one(Member::class, "Email = '".$email."'")) { $object->Users()->add($_user); } } } } // Deal with Group relations on target object if ($hasGroups) { if ($clear) { $relName = $groupRelationName[0]; $object->$relName()->removeAll(); } if (isset($source['groups']) && is_array($source['groups'])) { foreach ($source['groups'] as $group) { $title = Convert::raw2sql($group['title']); if ($_group = DataObject::get_one(Group::class, "Title = '".$title."'")) { $object->Groups()->add($_group); } } } } }
[ "protected", "function", "addManyManyToObject", "(", "$", "object", ",", "$", "source", ",", "$", "clear", "=", "false", ")", "{", "// Check incoming", "if", "(", "!", "is_object", "(", "$", "object", ")", "||", "!", "is_array", "(", "$", "source", ")", ...
Given an object, first check it has a ManyMany relation on it and add() Member and Group relations as required. @param Object $object (e.g. WorkflowDefinition, WorkflowAction, WorkflowTransition) @param array $source Usually data taken from a YAML template @param boolean $clear Lose/keep Group/Member relations on $object (useful for reloading/refreshing definition) @return void
[ "Given", "an", "object", "first", "check", "it", "has", "a", "ManyMany", "relation", "on", "it", "and", "add", "()", "Member", "and", "Group", "relations", "as", "required", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Templates/WorkflowTemplate.php#L391-L443
symbiote/silverstripe-advancedworkflow
src/Actions/AssignUsersToWorkflowAction.php
AssignUsersToWorkflowAction.getAssignedMembers
public function getAssignedMembers() { $members = $this->Users(); $groups = $this->Groups(); // Can't merge instances of DataList so convert to something where we can $_members = ArrayList::create(); $members->each(function ($item) use ($_members) { $_members->push($item); }); $_groups = ArrayList::create(); $groups->each(function ($item) use ($_groups) { $_groups->push($item); }); foreach ($_groups as $group) { $_members->merge($group->Members()); } $_members->removeDuplicates(); return $_members; }
php
public function getAssignedMembers() { $members = $this->Users(); $groups = $this->Groups(); // Can't merge instances of DataList so convert to something where we can $_members = ArrayList::create(); $members->each(function ($item) use ($_members) { $_members->push($item); }); $_groups = ArrayList::create(); $groups->each(function ($item) use ($_groups) { $_groups->push($item); }); foreach ($_groups as $group) { $_members->merge($group->Members()); } $_members->removeDuplicates(); return $_members; }
[ "public", "function", "getAssignedMembers", "(", ")", "{", "$", "members", "=", "$", "this", "->", "Users", "(", ")", ";", "$", "groups", "=", "$", "this", "->", "Groups", "(", ")", ";", "// Can't merge instances of DataList so convert to something where we can", ...
Returns a set of all Members that are assigned to this WorkflowAction subclass, either directly or via a group. @return ArrayList
[ "Returns", "a", "set", "of", "all", "Members", "that", "are", "assigned", "to", "this", "WorkflowAction", "subclass", "either", "directly", "or", "via", "a", "group", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Actions/AssignUsersToWorkflowAction.php#L92-L114
symbiote/silverstripe-advancedworkflow
src/Services/WorkflowService.php
WorkflowService.getNamedTemplate
public function getNamedTemplate($name) { if ($importedTemplate = singleton(WorkflowDefinitionImporter::class)->getImportedWorkflows($name)) { return $importedTemplate; } if (!is_array($this->templates)) { return; } foreach ($this->templates as $template) { if ($template->getName() == $name) { return $template; } } }
php
public function getNamedTemplate($name) { if ($importedTemplate = singleton(WorkflowDefinitionImporter::class)->getImportedWorkflows($name)) { return $importedTemplate; } if (!is_array($this->templates)) { return; } foreach ($this->templates as $template) { if ($template->getName() == $name) { return $template; } } }
[ "public", "function", "getNamedTemplate", "(", "$", "name", ")", "{", "if", "(", "$", "importedTemplate", "=", "singleton", "(", "WorkflowDefinitionImporter", "::", "class", ")", "->", "getImportedWorkflows", "(", "$", "name", ")", ")", "{", "return", "$", "...
Get a template by name @param string $name @return WorkflowTemplate|null
[ "Get", "a", "template", "by", "name" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Services/WorkflowService.php#L64-L78
symbiote/silverstripe-advancedworkflow
src/Services/WorkflowService.php
WorkflowService.getDefinitionFor
public function getDefinitionFor(DataObject $dataObject) { if ($dataObject->hasExtension(WorkflowApplicable::class) || $dataObject->hasExtension(FileWorkflowApplicable::class) ) { if ($dataObject->WorkflowDefinitionID) { return DataObject::get_by_id(WorkflowDefinition::class, $dataObject->WorkflowDefinitionID); } if ($dataObject->hasMethod('useInheritedWorkflow') && !$dataObject->useInheritedWorkflow()) { return null; } if ($dataObject->ParentID) { return $this->getDefinitionFor($dataObject->Parent()); } if ($dataObject->hasMethod('workflowParent')) { $obj = $dataObject->workflowParent(); if ($obj) { return $this->getDefinitionFor($obj); } } } return null; }
php
public function getDefinitionFor(DataObject $dataObject) { if ($dataObject->hasExtension(WorkflowApplicable::class) || $dataObject->hasExtension(FileWorkflowApplicable::class) ) { if ($dataObject->WorkflowDefinitionID) { return DataObject::get_by_id(WorkflowDefinition::class, $dataObject->WorkflowDefinitionID); } if ($dataObject->hasMethod('useInheritedWorkflow') && !$dataObject->useInheritedWorkflow()) { return null; } if ($dataObject->ParentID) { return $this->getDefinitionFor($dataObject->Parent()); } if ($dataObject->hasMethod('workflowParent')) { $obj = $dataObject->workflowParent(); if ($obj) { return $this->getDefinitionFor($obj); } } } return null; }
[ "public", "function", "getDefinitionFor", "(", "DataObject", "$", "dataObject", ")", "{", "if", "(", "$", "dataObject", "->", "hasExtension", "(", "WorkflowApplicable", "::", "class", ")", "||", "$", "dataObject", "->", "hasExtension", "(", "FileWorkflowApplicable...
Gets the workflow definition for a given dataobject, if there is one Will recursively query parent elements until it finds one, if available @param DataObject $dataObject
[ "Gets", "the", "workflow", "definition", "for", "a", "given", "dataobject", "if", "there", "is", "one" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Services/WorkflowService.php#L87-L109
symbiote/silverstripe-advancedworkflow
src/Services/WorkflowService.php
WorkflowService.getDefinitionByID
public function getDefinitionByID($object, $workflowID) { // Make sure the correct extensions have been applied to the data object. $workflow = null; if ($object->hasExtension(WorkflowApplicable::class) || $object->hasExtension(FileWorkflowApplicable::class) ) { // Validate the workflow ID against the data object. if (($object->WorkflowDefinitionID == $workflowID) || ($workflow = $object->AdditionalWorkflowDefinitions()->byID($workflowID)) ) { if (is_null($workflow)) { $workflow = DataObject::get_by_id(WorkflowDefinition::class, $workflowID); } } } return $workflow ? $workflow : null; }
php
public function getDefinitionByID($object, $workflowID) { // Make sure the correct extensions have been applied to the data object. $workflow = null; if ($object->hasExtension(WorkflowApplicable::class) || $object->hasExtension(FileWorkflowApplicable::class) ) { // Validate the workflow ID against the data object. if (($object->WorkflowDefinitionID == $workflowID) || ($workflow = $object->AdditionalWorkflowDefinitions()->byID($workflowID)) ) { if (is_null($workflow)) { $workflow = DataObject::get_by_id(WorkflowDefinition::class, $workflowID); } } } return $workflow ? $workflow : null; }
[ "public", "function", "getDefinitionByID", "(", "$", "object", ",", "$", "workflowID", ")", "{", "// Make sure the correct extensions have been applied to the data object.", "$", "workflow", "=", "null", ";", "if", "(", "$", "object", "->", "hasExtension", "(", "Workf...
Retrieves a workflow definition by ID for a data object. @param DataObject $object @param integer $workflowID @return WorkflowDefinition|null
[ "Retrieves", "a", "workflow", "definition", "by", "ID", "for", "a", "data", "object", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Services/WorkflowService.php#L118-L137
symbiote/silverstripe-advancedworkflow
src/Services/WorkflowService.php
WorkflowService.getDefinitionsFor
public function getDefinitionsFor($object) { // Retrieve the main workflow definition. $default = $this->getDefinitionFor($object); if ($default) { // Merge the additional workflow definitions. return array_merge(array( $default ), $object->AdditionalWorkflowDefinitions()->toArray()); } return null; }
php
public function getDefinitionsFor($object) { // Retrieve the main workflow definition. $default = $this->getDefinitionFor($object); if ($default) { // Merge the additional workflow definitions. return array_merge(array( $default ), $object->AdditionalWorkflowDefinitions()->toArray()); } return null; }
[ "public", "function", "getDefinitionsFor", "(", "$", "object", ")", "{", "// Retrieve the main workflow definition.", "$", "default", "=", "$", "this", "->", "getDefinitionFor", "(", "$", "object", ")", ";", "if", "(", "$", "default", ")", "{", "// Merge the add...
Retrieves and collates the workflow definitions for a data object, where the first element will be the main workflow definition. @param DataObject object @return array
[ "Retrieves", "and", "collates", "the", "workflow", "definitions", "for", "a", "data", "object", "where", "the", "first", "element", "will", "be", "the", "main", "workflow", "definition", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Services/WorkflowService.php#L147-L161
symbiote/silverstripe-advancedworkflow
src/Services/WorkflowService.php
WorkflowService.getWorkflowFor
public function getWorkflowFor($item, $includeComplete = false) { $id = $item; if ($item instanceof WorkflowAction) { $id = $item->WorkflowID; return DataObject::get_by_id(WorkflowInstance::class, $id); } elseif (is_object($item) && ($item->hasExtension(WorkflowApplicable::class) || $item->hasExtension(FileWorkflowApplicable::class)) ) { $filter = sprintf( '"TargetClass" = \'%s\' AND "TargetID" = %d', Convert::raw2sql(ClassInfo::baseDataClass($item)), $item->ID ); $complete = $includeComplete ? 'OR "WorkflowStatus" = \'Complete\' ' : ''; return DataObject::get_one( WorkflowInstance::class, $filter . ' AND ("WorkflowStatus" = \'Active\' OR "WorkflowStatus"=\'Paused\' ' . $complete . ')' ); } }
php
public function getWorkflowFor($item, $includeComplete = false) { $id = $item; if ($item instanceof WorkflowAction) { $id = $item->WorkflowID; return DataObject::get_by_id(WorkflowInstance::class, $id); } elseif (is_object($item) && ($item->hasExtension(WorkflowApplicable::class) || $item->hasExtension(FileWorkflowApplicable::class)) ) { $filter = sprintf( '"TargetClass" = \'%s\' AND "TargetID" = %d', Convert::raw2sql(ClassInfo::baseDataClass($item)), $item->ID ); $complete = $includeComplete ? 'OR "WorkflowStatus" = \'Complete\' ' : ''; return DataObject::get_one( WorkflowInstance::class, $filter . ' AND ("WorkflowStatus" = \'Active\' OR "WorkflowStatus"=\'Paused\' ' . $complete . ')' ); } }
[ "public", "function", "getWorkflowFor", "(", "$", "item", ",", "$", "includeComplete", "=", "false", ")", "{", "$", "id", "=", "$", "item", ";", "if", "(", "$", "item", "instanceof", "WorkflowAction", ")", "{", "$", "id", "=", "$", "item", "->", "Wor...
Gets the workflow for the given item The item can be a data object in which case the ActiveWorkflow will be returned, an action, in which case the Workflow will be returned an integer, in which case the workflow with that ID will be returned @param mixed $item @param bool $includeComplete @return WorkflowInstance|null
[ "Gets", "the", "workflow", "for", "the", "given", "item" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Services/WorkflowService.php#L176-L197
symbiote/silverstripe-advancedworkflow
src/Services/WorkflowService.php
WorkflowService.getWorkflowHistoryFor
public function getWorkflowHistoryFor($item, $limit = null) { if ($active = $this->getWorkflowFor($item, true)) { $limit = $limit ? "0,$limit" : ''; return $active->Actions('', 'ID DESC ', null, $limit); } }
php
public function getWorkflowHistoryFor($item, $limit = null) { if ($active = $this->getWorkflowFor($item, true)) { $limit = $limit ? "0,$limit" : ''; return $active->Actions('', 'ID DESC ', null, $limit); } }
[ "public", "function", "getWorkflowHistoryFor", "(", "$", "item", ",", "$", "limit", "=", "null", ")", "{", "if", "(", "$", "active", "=", "$", "this", "->", "getWorkflowFor", "(", "$", "item", ",", "true", ")", ")", "{", "$", "limit", "=", "$", "li...
Get all the workflow action instances for an item @return DataList|null
[ "Get", "all", "the", "workflow", "action", "instances", "for", "an", "item" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Services/WorkflowService.php#L204-L210
symbiote/silverstripe-advancedworkflow
src/Services/WorkflowService.php
WorkflowService.executeTransition
public function executeTransition(DataObject $target, $transitionId) { $workflow = $this->getWorkflowFor($target); $transition = DataObject::get_by_id(WorkflowTransition::class, $transitionId); if (!$transition) { throw new Exception(_t('WorkflowService.INVALID_TRANSITION_ID', "Invalid transition ID $transitionId")); } if (!$workflow) { throw new Exception(_t( 'WorkflowService.INVALID_WORKFLOW_TARGET', "A transition was executed on a target that does not have a workflow." )); } if ($transition->Action()->WorkflowDefID != $workflow->DefinitionID) { throw new Exception(_t( 'WorkflowService.INVALID_TRANSITION_WORKFLOW', "Transition #$transition->ID is not attached to workflow #$workflow->ID." )); } $workflow->performTransition($transition); }
php
public function executeTransition(DataObject $target, $transitionId) { $workflow = $this->getWorkflowFor($target); $transition = DataObject::get_by_id(WorkflowTransition::class, $transitionId); if (!$transition) { throw new Exception(_t('WorkflowService.INVALID_TRANSITION_ID', "Invalid transition ID $transitionId")); } if (!$workflow) { throw new Exception(_t( 'WorkflowService.INVALID_WORKFLOW_TARGET', "A transition was executed on a target that does not have a workflow." )); } if ($transition->Action()->WorkflowDefID != $workflow->DefinitionID) { throw new Exception(_t( 'WorkflowService.INVALID_TRANSITION_WORKFLOW', "Transition #$transition->ID is not attached to workflow #$workflow->ID." )); } $workflow->performTransition($transition); }
[ "public", "function", "executeTransition", "(", "DataObject", "$", "target", ",", "$", "transitionId", ")", "{", "$", "workflow", "=", "$", "this", "->", "getWorkflowFor", "(", "$", "target", ")", ";", "$", "transition", "=", "DataObject", "::", "get_by_id",...
Given a transition ID, figure out what should happen to the given $subject. In the normal case, this will load the current workflow instance for the object and then transition as expected. However, in some cases (eg to start the workflow) it is necessary to instead create a new instance. @param DataObject $target @param int $transitionId @throws Exception
[ "Given", "a", "transition", "ID", "figure", "out", "what", "should", "happen", "to", "the", "given", "$subject", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Services/WorkflowService.php#L234-L258
symbiote/silverstripe-advancedworkflow
src/Services/WorkflowService.php
WorkflowService.startWorkflow
public function startWorkflow(DataObject $object, $workflowID = null) { $existing = $this->getWorkflowFor($object); if ($existing) { throw new ExistingWorkflowException(_t( 'WorkflowService.EXISTING_WORKFLOW_ERROR', "That object already has a workflow running" )); } $definition = null; if ($workflowID) { // Retrieve the workflow definition that has been triggered. $definition = $this->getDefinitionByID($object, $workflowID); } if (is_null($definition)) { // Fall back to the main workflow definition. $definition = $this->getDefinitionFor($object); } if ($definition) { $instance = new WorkflowInstance(); $instance->beginWorkflow($definition, $object); $instance->execute(); } }
php
public function startWorkflow(DataObject $object, $workflowID = null) { $existing = $this->getWorkflowFor($object); if ($existing) { throw new ExistingWorkflowException(_t( 'WorkflowService.EXISTING_WORKFLOW_ERROR', "That object already has a workflow running" )); } $definition = null; if ($workflowID) { // Retrieve the workflow definition that has been triggered. $definition = $this->getDefinitionByID($object, $workflowID); } if (is_null($definition)) { // Fall back to the main workflow definition. $definition = $this->getDefinitionFor($object); } if ($definition) { $instance = new WorkflowInstance(); $instance->beginWorkflow($definition, $object); $instance->execute(); } }
[ "public", "function", "startWorkflow", "(", "DataObject", "$", "object", ",", "$", "workflowID", "=", "null", ")", "{", "$", "existing", "=", "$", "this", "->", "getWorkflowFor", "(", "$", "object", ")", ";", "if", "(", "$", "existing", ")", "{", "thro...
Starts the workflow for the given data object, assuming it or a parent has a definition specified. @param DataObject $object @param int $workflowID
[ "Starts", "the", "workflow", "for", "the", "given", "data", "object", "assuming", "it", "or", "a", "parent", "has", "a", "definition", "specified", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Services/WorkflowService.php#L267-L294
symbiote/silverstripe-advancedworkflow
src/Services/WorkflowService.php
WorkflowService.usersWorkflows
public function usersWorkflows(Member $user) { $groupIds = $user->Groups()->column('ID'); $groupInstances = null; $filter = array(''); if (is_array($groupIds)) { $groupInstances = DataList::create(WorkflowInstance::class) ->filter(array('Group.ID:ExactMatchMulti' => $groupIds)) ->where('"WorkflowStatus" != \'Complete\''); } $userInstances = DataList::create(WorkflowInstance::class) ->filter(array('Users.ID:ExactMatch' => $user->ID)) ->where('"WorkflowStatus" != \'Complete\''); if ($userInstances) { $userInstances = $userInstances->toArray(); } else { $userInstances = array(); } if ($groupInstances) { $groupInstances = $groupInstances->toArray(); } else { $groupInstances = array(); } $all = array_merge($groupInstances, $userInstances); return ArrayList::create($all); }
php
public function usersWorkflows(Member $user) { $groupIds = $user->Groups()->column('ID'); $groupInstances = null; $filter = array(''); if (is_array($groupIds)) { $groupInstances = DataList::create(WorkflowInstance::class) ->filter(array('Group.ID:ExactMatchMulti' => $groupIds)) ->where('"WorkflowStatus" != \'Complete\''); } $userInstances = DataList::create(WorkflowInstance::class) ->filter(array('Users.ID:ExactMatch' => $user->ID)) ->where('"WorkflowStatus" != \'Complete\''); if ($userInstances) { $userInstances = $userInstances->toArray(); } else { $userInstances = array(); } if ($groupInstances) { $groupInstances = $groupInstances->toArray(); } else { $groupInstances = array(); } $all = array_merge($groupInstances, $userInstances); return ArrayList::create($all); }
[ "public", "function", "usersWorkflows", "(", "Member", "$", "user", ")", "{", "$", "groupIds", "=", "$", "user", "->", "Groups", "(", ")", "->", "column", "(", "'ID'", ")", ";", "$", "groupInstances", "=", "null", ";", "$", "filter", "=", "array", "(...
Get all the workflows that this user is responsible for @param Member $user The user to get workflows for @return ArrayList The list of workflow instances this user owns
[ "Get", "all", "the", "workflows", "that", "this", "user", "is", "responsible", "for" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Services/WorkflowService.php#L302-L336
symbiote/silverstripe-advancedworkflow
src/Services/WorkflowService.php
WorkflowService.userPendingItems
public function userPendingItems(Member $user) { // Don't restrict anything for ADMIN users $userInstances = DataList::create(WorkflowInstance::class) ->where('"WorkflowStatus" != \'Complete\'') ->sort('LastEdited DESC'); if (Permission::checkMember($user, 'ADMIN')) { return $userInstances; } $instances = new ArrayList(); foreach ($userInstances as $inst) { $instToArray = $inst->getAssignedMembers(); if (!count($instToArray)>0 || !in_array($user->ID, $instToArray->column())) { continue; } $instances->push($inst); } return $instances; }
php
public function userPendingItems(Member $user) { // Don't restrict anything for ADMIN users $userInstances = DataList::create(WorkflowInstance::class) ->where('"WorkflowStatus" != \'Complete\'') ->sort('LastEdited DESC'); if (Permission::checkMember($user, 'ADMIN')) { return $userInstances; } $instances = new ArrayList(); foreach ($userInstances as $inst) { $instToArray = $inst->getAssignedMembers(); if (!count($instToArray)>0 || !in_array($user->ID, $instToArray->column())) { continue; } $instances->push($inst); } return $instances; }
[ "public", "function", "userPendingItems", "(", "Member", "$", "user", ")", "{", "// Don't restrict anything for ADMIN users", "$", "userInstances", "=", "DataList", "::", "create", "(", "WorkflowInstance", "::", "class", ")", "->", "where", "(", "'\"WorkflowStatus\" !...
Get items that the passed-in user has awaiting for them to action @param Member $member @return DataList
[ "Get", "items", "that", "the", "passed", "-", "in", "user", "has", "awaiting", "for", "them", "to", "action" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Services/WorkflowService.php#L344-L364
symbiote/silverstripe-advancedworkflow
src/Services/WorkflowService.php
WorkflowService.userSubmittedItems
public function userSubmittedItems(Member $user) { $userInstances = DataList::create(WorkflowInstance::class) ->where('"WorkflowStatus" != \'Complete\'') ->sort('LastEdited DESC'); // Restrict the user if they're not an ADMIN. if (!Permission::checkMember($user, 'ADMIN')) { $userInstances = $userInstances->filter('InitiatorID:ExactMatch', $user->ID); } return $userInstances; }
php
public function userSubmittedItems(Member $user) { $userInstances = DataList::create(WorkflowInstance::class) ->where('"WorkflowStatus" != \'Complete\'') ->sort('LastEdited DESC'); // Restrict the user if they're not an ADMIN. if (!Permission::checkMember($user, 'ADMIN')) { $userInstances = $userInstances->filter('InitiatorID:ExactMatch', $user->ID); } return $userInstances; }
[ "public", "function", "userSubmittedItems", "(", "Member", "$", "user", ")", "{", "$", "userInstances", "=", "DataList", "::", "create", "(", "WorkflowInstance", "::", "class", ")", "->", "where", "(", "'\"WorkflowStatus\" != \\'Complete\\''", ")", "->", "sort", ...
Get items that the passed-in user has submitted for workflow review @param Member $member @return DataList
[ "Get", "items", "that", "the", "passed", "-", "in", "user", "has", "submitted", "for", "workflow", "review" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Services/WorkflowService.php#L372-L384
symbiote/silverstripe-advancedworkflow
src/Services/WorkflowService.php
WorkflowService.defineFromTemplate
public function defineFromTemplate(WorkflowDefinition $definition, $templateName) { $template = null; /* @var $template WorkflowTemplate */ if (!is_array($this->templates)) { return; } $template = $this->getNamedTemplate($templateName); if (!$template) { return; } $template->createRelations($definition); // Set the version and do the write at the end so that we don't trigger an infinite loop!! if (!$definition->Description) { $definition->Description = $template->getDescription(); } $definition->TemplateVersion = $template->getVersion(); $definition->RemindDays = $template->getRemindDays(); $definition->Sort = $template->getSort(); $definition->write(); return $definition; }
php
public function defineFromTemplate(WorkflowDefinition $definition, $templateName) { $template = null; /* @var $template WorkflowTemplate */ if (!is_array($this->templates)) { return; } $template = $this->getNamedTemplate($templateName); if (!$template) { return; } $template->createRelations($definition); // Set the version and do the write at the end so that we don't trigger an infinite loop!! if (!$definition->Description) { $definition->Description = $template->getDescription(); } $definition->TemplateVersion = $template->getVersion(); $definition->RemindDays = $template->getRemindDays(); $definition->Sort = $template->getSort(); $definition->write(); return $definition; }
[ "public", "function", "defineFromTemplate", "(", "WorkflowDefinition", "$", "definition", ",", "$", "templateName", ")", "{", "$", "template", "=", "null", ";", "/* @var $template WorkflowTemplate */", "if", "(", "!", "is_array", "(", "$", "this", "->", "templates...
Generate a workflow definition based on a template @param WorkflowDefinition $definition @param string $templateName @return WorkflowDefinition|null
[ "Generate", "a", "workflow", "definition", "based", "on", "a", "template" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Services/WorkflowService.php#L393-L419
symbiote/silverstripe-advancedworkflow
src/Services/WorkflowService.php
WorkflowService.reorder
public function reorder($objects, $newOrder) { $sortVals = array_values($objects->map('ID', 'Sort')->toArray()); sort($sortVals); // save the new ID values - but only use existing sort values to prevent // conflicts with items not in the table foreach ($newOrder as $key => $id) { if (!$id) { continue; } $object = $objects->find('ID', $id); $object->Sort = $sortVals[$key]; $object->write(); } }
php
public function reorder($objects, $newOrder) { $sortVals = array_values($objects->map('ID', 'Sort')->toArray()); sort($sortVals); // save the new ID values - but only use existing sort values to prevent // conflicts with items not in the table foreach ($newOrder as $key => $id) { if (!$id) { continue; } $object = $objects->find('ID', $id); $object->Sort = $sortVals[$key]; $object->write(); } }
[ "public", "function", "reorder", "(", "$", "objects", ",", "$", "newOrder", ")", "{", "$", "sortVals", "=", "array_values", "(", "$", "objects", "->", "map", "(", "'ID'", ",", "'Sort'", ")", "->", "toArray", "(", ")", ")", ";", "sort", "(", "$", "s...
Reorders actions within a definition @param WorkflowDefinition|WorkflowAction $objects The objects to be reordered @param array $newOrder An array of IDs of the actions in the order they should be.
[ "Reorders", "actions", "within", "a", "definition" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Services/WorkflowService.php#L427-L442
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.getCMSFields
public function getCMSFields() { $fields = new FieldList(); $fields->push(new TabSet('Root', new Tab('Main'))); if (Permission::check('REASSIGN_ACTIVE_WORKFLOWS')) { if ($this->WorkflowStatus == 'Paused' || $this->WorkflowStatus == 'Active') { $cmsUsers = Member::mapInCMSGroups(); $fields->addFieldsToTab('Root.Main', array( new HiddenField('DirectUpdate', '', 1), new HeaderField( 'InstanceReassignHeader', _t('WorkflowInstance.REASSIGN_HEADER', 'Reassign workflow') ), new CheckboxSetField('Users', _t('WorkflowDefinition.USERS', 'Users'), $cmsUsers), new TreeMultiselectField('Groups', _t('WorkflowDefinition.GROUPS', 'Groups'), Group::class) )); } } if ($this->canEdit()) { $action = $this->CurrentAction(); if ($action->exists()) { $actionFields = $this->getWorkflowFields(); $fields->addFieldsToTab('Root.Main', $actionFields); $transitions = $action->getValidTransitions(); if ($transitions) { $fields->replaceField( 'TransitionID', DropdownField::create("TransitionID", "Next action", $transitions->map()) ); } } } $items = WorkflowActionInstance::get()->filter(array( 'Finished' => 1, 'WorkflowID' => $this->ID )); $grid = new GridField( 'Actions', _t('WorkflowInstance.ActionLogTitle', 'Log'), $items ); $fields->addFieldsToTab('Root.Main', $grid); return $fields; }
php
public function getCMSFields() { $fields = new FieldList(); $fields->push(new TabSet('Root', new Tab('Main'))); if (Permission::check('REASSIGN_ACTIVE_WORKFLOWS')) { if ($this->WorkflowStatus == 'Paused' || $this->WorkflowStatus == 'Active') { $cmsUsers = Member::mapInCMSGroups(); $fields->addFieldsToTab('Root.Main', array( new HiddenField('DirectUpdate', '', 1), new HeaderField( 'InstanceReassignHeader', _t('WorkflowInstance.REASSIGN_HEADER', 'Reassign workflow') ), new CheckboxSetField('Users', _t('WorkflowDefinition.USERS', 'Users'), $cmsUsers), new TreeMultiselectField('Groups', _t('WorkflowDefinition.GROUPS', 'Groups'), Group::class) )); } } if ($this->canEdit()) { $action = $this->CurrentAction(); if ($action->exists()) { $actionFields = $this->getWorkflowFields(); $fields->addFieldsToTab('Root.Main', $actionFields); $transitions = $action->getValidTransitions(); if ($transitions) { $fields->replaceField( 'TransitionID', DropdownField::create("TransitionID", "Next action", $transitions->map()) ); } } } $items = WorkflowActionInstance::get()->filter(array( 'Finished' => 1, 'WorkflowID' => $this->ID )); $grid = new GridField( 'Actions', _t('WorkflowInstance.ActionLogTitle', 'Log'), $items ); $fields->addFieldsToTab('Root.Main', $grid); return $fields; }
[ "public", "function", "getCMSFields", "(", ")", "{", "$", "fields", "=", "new", "FieldList", "(", ")", ";", "$", "fields", "->", "push", "(", "new", "TabSet", "(", "'Root'", ",", "new", "Tab", "(", "'Main'", ")", ")", ")", ";", "if", "(", "Permissi...
Get the CMS view of the instance. This is used to display the log of this workflow, and options to reassign if the workflow hasn't been finished yet @return FieldList
[ "Get", "the", "CMS", "view", "of", "the", "instance", ".", "This", "is", "used", "to", "display", "the", "log", "of", "this", "workflow", "and", "options", "to", "reassign", "if", "the", "workflow", "hasn", "t", "been", "finished", "yet" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L118-L169
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.onBeforeWrite
public function onBeforeWrite() { parent::onBeforeWrite(); $vars = $this->record; if (isset($vars['DirectUpdate'])) { // Unset now so that we don't end up in an infinite loop! unset($this->record['DirectUpdate']); $this->updateWorkflow($vars); } }
php
public function onBeforeWrite() { parent::onBeforeWrite(); $vars = $this->record; if (isset($vars['DirectUpdate'])) { // Unset now so that we don't end up in an infinite loop! unset($this->record['DirectUpdate']); $this->updateWorkflow($vars); } }
[ "public", "function", "onBeforeWrite", "(", ")", "{", "parent", "::", "onBeforeWrite", "(", ")", ";", "$", "vars", "=", "$", "this", "->", "record", ";", "if", "(", "isset", "(", "$", "vars", "[", "'DirectUpdate'", "]", ")", ")", "{", "// Unset now so ...
See if we've been saved in context of managing the workflow directly
[ "See", "if", "we", "ve", "been", "saved", "in", "context", "of", "managing", "the", "workflow", "directly" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L185-L196
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.updateWorkflow
public function updateWorkflow($data) { $action = $this->CurrentAction(); if (!$this->getTarget() || !$this->getTarget()->canEditWorkflow()) { return; } $allowedFields = $this->getWorkflowFields()->saveableFields(); unset($allowedFields['TransitionID']); foreach ($allowedFields as $field) { $fieldName = $field->getName(); $action->$fieldName = $data[$fieldName]; } $action->write(); $svc = singleton(WorkflowService::class); if (isset($data['TransitionID']) && $data['TransitionID']) { $svc->executeTransition($this->getTarget(), $data['TransitionID']); } else { // otherwise, just try to execute the current workflow to see if it // can now proceed based on user input $this->execute(); } }
php
public function updateWorkflow($data) { $action = $this->CurrentAction(); if (!$this->getTarget() || !$this->getTarget()->canEditWorkflow()) { return; } $allowedFields = $this->getWorkflowFields()->saveableFields(); unset($allowedFields['TransitionID']); foreach ($allowedFields as $field) { $fieldName = $field->getName(); $action->$fieldName = $data[$fieldName]; } $action->write(); $svc = singleton(WorkflowService::class); if (isset($data['TransitionID']) && $data['TransitionID']) { $svc->executeTransition($this->getTarget(), $data['TransitionID']); } else { // otherwise, just try to execute the current workflow to see if it // can now proceed based on user input $this->execute(); } }
[ "public", "function", "updateWorkflow", "(", "$", "data", ")", "{", "$", "action", "=", "$", "this", "->", "CurrentAction", "(", ")", ";", "if", "(", "!", "$", "this", "->", "getTarget", "(", ")", "||", "!", "$", "this", "->", "getTarget", "(", ")"...
Update the current state of the workflow Typically, this is triggered by someone modifiying the workflow instance via the modeladmin form side of things when administering things, such as re-assigning or manually approving a stuck workflow Note that this is VERY similar to AdvancedWorkflowExtension::updateworkflow but without the formy bits. These two implementations should PROBABLY be merged @todo refactor with AdvancedWorkflowExtension @param type $data @return
[ "Update", "the", "current", "state", "of", "the", "workflow" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L213-L237
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.getTarget
public function getTarget($getLive = false) { if ($this->TargetID && $this->TargetClass) { $versionable = Injector::inst()->get($this->TargetClass)->has_extension(Versioned::class); $targetObject = null; if (!$versionable && $getLive) { return; } if ($versionable) { $targetObject = Versioned::get_by_stage( $this->TargetClass, $getLive ? Versioned::LIVE : Versioned::DRAFT )->byID($this->TargetID); } if (!$targetObject) { $targetObject = DataObject::get_by_id($this->TargetClass, $this->TargetID); } return $targetObject; } }
php
public function getTarget($getLive = false) { if ($this->TargetID && $this->TargetClass) { $versionable = Injector::inst()->get($this->TargetClass)->has_extension(Versioned::class); $targetObject = null; if (!$versionable && $getLive) { return; } if ($versionable) { $targetObject = Versioned::get_by_stage( $this->TargetClass, $getLive ? Versioned::LIVE : Versioned::DRAFT )->byID($this->TargetID); } if (!$targetObject) { $targetObject = DataObject::get_by_id($this->TargetClass, $this->TargetID); } return $targetObject; } }
[ "public", "function", "getTarget", "(", "$", "getLive", "=", "false", ")", "{", "if", "(", "$", "this", "->", "TargetID", "&&", "$", "this", "->", "TargetClass", ")", "{", "$", "versionable", "=", "Injector", "::", "inst", "(", ")", "->", "get", "(",...
Get the target-object that this WorkflowInstance "points" to. Workflows are not restricted to being active on SiteTree objects, so we need to account for being attached to anything. Sets Versioned::set_reading_mode() to allow fetching of Draft _and_ Published content. @param boolean $getLive @return null|DataObject
[ "Get", "the", "target", "-", "object", "that", "this", "WorkflowInstance", "points", "to", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L251-L272
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.getTargetDiff
public function getTargetDiff() { $liveTarget = $this->Target(true); $draftTarget = $this->Target(); $diff = DataDifferencer::create($liveTarget, $draftTarget); $diff->ignoreFields($this->config()->get('diff_ignore_fields')); $fields = ArrayList::create(); try { $fields = $diff->ChangedFields(); } catch (\InvalidArgumentException $iae) { // noop } return $fields; }
php
public function getTargetDiff() { $liveTarget = $this->Target(true); $draftTarget = $this->Target(); $diff = DataDifferencer::create($liveTarget, $draftTarget); $diff->ignoreFields($this->config()->get('diff_ignore_fields')); $fields = ArrayList::create(); try { $fields = $diff->ChangedFields(); } catch (\InvalidArgumentException $iae) { // noop } return $fields; }
[ "public", "function", "getTargetDiff", "(", ")", "{", "$", "liveTarget", "=", "$", "this", "->", "Target", "(", "true", ")", ";", "$", "draftTarget", "=", "$", "this", "->", "Target", "(", ")", ";", "$", "diff", "=", "DataDifferencer", "::", "create", ...
Returns the field differences between the older version and current version of Target @return ArrayList
[ "Returns", "the", "field", "differences", "between", "the", "older", "version", "and", "current", "version", "of", "Target" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L290-L306
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.beginWorkflow
public function beginWorkflow(WorkflowDefinition $definition, DataObject $for = null) { if (!$this->ID) { $this->write(); } if ($for && ($for->hasExtension(WorkflowApplicable::class) || $for->hasExtension(FileWorkflowApplicable::class)) ) { $this->TargetClass = DataObject::getSchema()->baseDataClass($for); $this->TargetID = $for->ID; } // lets create the first WorkflowActionInstance. $action = $definition->getInitialAction()->getInstanceForWorkflow(); $action->WorkflowID = $this->ID; $action->write(); $title = $for && $for->hasField('Title') ? sprintf(_t('WorkflowInstance.TITLE_FOR_DO', '%s - %s'), $definition->Title, $for->Title) : sprintf(_t('WorkflowInstance.TITLE_STUB', 'Instance #%s of %s'), $this->ID, $definition->Title); $this->Title = $title; $this->DefinitionID = $definition->ID; $this->CurrentActionID = $action->ID; $this->InitiatorID = Security::getCurrentUser()->ID; $this->write(); $this->Users()->addMany($definition->Users()); $this->Groups()->addMany($definition->Groups()); }
php
public function beginWorkflow(WorkflowDefinition $definition, DataObject $for = null) { if (!$this->ID) { $this->write(); } if ($for && ($for->hasExtension(WorkflowApplicable::class) || $for->hasExtension(FileWorkflowApplicable::class)) ) { $this->TargetClass = DataObject::getSchema()->baseDataClass($for); $this->TargetID = $for->ID; } // lets create the first WorkflowActionInstance. $action = $definition->getInitialAction()->getInstanceForWorkflow(); $action->WorkflowID = $this->ID; $action->write(); $title = $for && $for->hasField('Title') ? sprintf(_t('WorkflowInstance.TITLE_FOR_DO', '%s - %s'), $definition->Title, $for->Title) : sprintf(_t('WorkflowInstance.TITLE_STUB', 'Instance #%s of %s'), $this->ID, $definition->Title); $this->Title = $title; $this->DefinitionID = $definition->ID; $this->CurrentActionID = $action->ID; $this->InitiatorID = Security::getCurrentUser()->ID; $this->write(); $this->Users()->addMany($definition->Users()); $this->Groups()->addMany($definition->Groups()); }
[ "public", "function", "beginWorkflow", "(", "WorkflowDefinition", "$", "definition", ",", "DataObject", "$", "for", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "ID", ")", "{", "$", "this", "->", "write", "(", ")", ";", "}", "if", "(", ...
Start a workflow based on a particular definition for a particular object. The object is optional; if not specified, it is assumed that this workflow is simply a task based checklist type of workflow. @param WorkflowDefinition $definition @param DataObject $for
[ "Start", "a", "workflow", "based", "on", "a", "particular", "definition", "for", "a", "particular", "object", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L317-L348
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.execute
public function execute() { if (!$this->CurrentActionID) { throw new Exception( sprintf(_t( 'WorkflowInstance.EXECUTE_EXCEPTION', 'Attempted to start an invalid workflow instance #%s!' ), $this->ID) ); } $action = $this->CurrentAction(); $transition = false; // if the action has already finished, it means it has either multiple (or no // transitions at the time), so a subsequent check should be run. if ($action->Finished) { $transition = $this->checkTransitions($action); } else { $result = $action->BaseAction()->execute($this); // if the action was successful, then the action has finished running and // next transition should be run (if only one). // input. if ($result) { $action->MemberID = Security::getCurrentUser()->ID; $action->Finished = true; $action->write(); $transition = $this->checkTransitions($action); } } // if the action finished, and there's only one available transition then // move onto that step - otherwise check if the workflow has finished. if ($transition) { $this->performTransition($transition); } else { // see if there are any transitions available, even if they are not valid. if ($action->Finished && !count($action->BaseAction()->Transitions())) { $this->WorkflowStatus = 'Complete'; $this->CurrentActionID = 0; } else { $this->WorkflowStatus = 'Paused'; } $this->write(); } }
php
public function execute() { if (!$this->CurrentActionID) { throw new Exception( sprintf(_t( 'WorkflowInstance.EXECUTE_EXCEPTION', 'Attempted to start an invalid workflow instance #%s!' ), $this->ID) ); } $action = $this->CurrentAction(); $transition = false; // if the action has already finished, it means it has either multiple (or no // transitions at the time), so a subsequent check should be run. if ($action->Finished) { $transition = $this->checkTransitions($action); } else { $result = $action->BaseAction()->execute($this); // if the action was successful, then the action has finished running and // next transition should be run (if only one). // input. if ($result) { $action->MemberID = Security::getCurrentUser()->ID; $action->Finished = true; $action->write(); $transition = $this->checkTransitions($action); } } // if the action finished, and there's only one available transition then // move onto that step - otherwise check if the workflow has finished. if ($transition) { $this->performTransition($transition); } else { // see if there are any transitions available, even if they are not valid. if ($action->Finished && !count($action->BaseAction()->Transitions())) { $this->WorkflowStatus = 'Complete'; $this->CurrentActionID = 0; } else { $this->WorkflowStatus = 'Paused'; } $this->write(); } }
[ "public", "function", "execute", "(", ")", "{", "if", "(", "!", "$", "this", "->", "CurrentActionID", ")", "{", "throw", "new", "Exception", "(", "sprintf", "(", "_t", "(", "'WorkflowInstance.EXECUTE_EXCEPTION'", ",", "'Attempted to start an invalid workflow instanc...
Execute this workflow. In rare cases this will actually execute all actions, but typically, it will stop and wait for the user to input something The basic process is to get the current action, and see whether it has been finished by some process, if not it attempts to execute it. If it has been finished, we check to see if there's some transitions to follow. If there's only one transition, then we execute that immediately. If there's multiple transitions, we just stop and wait for the user to manually trigger a transition. If there's no transitions, we make the assumption that we've finished the workflow and mark it as such.
[ "Execute", "this", "workflow", ".", "In", "rare", "cases", "this", "will", "actually", "execute", "all", "actions", "but", "typically", "it", "will", "stop", "and", "wait", "for", "the", "user", "to", "input", "something" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L368-L415
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.checkTransitions
protected function checkTransitions(WorkflowActionInstance $action) { $transitions = $action->getValidTransitions(); // if there's JUST ONE transition, then we need should // immediately follow it. if ($transitions && $transitions->count() == 1) { return $transitions->First(); } }
php
protected function checkTransitions(WorkflowActionInstance $action) { $transitions = $action->getValidTransitions(); // if there's JUST ONE transition, then we need should // immediately follow it. if ($transitions && $transitions->count() == 1) { return $transitions->First(); } }
[ "protected", "function", "checkTransitions", "(", "WorkflowActionInstance", "$", "action", ")", "{", "$", "transitions", "=", "$", "action", "->", "getValidTransitions", "(", ")", ";", "// if there's JUST ONE transition, then we need should", "// immediately follow it.", "i...
Evaluate all the transitions of an action and determine whether we should follow any of them yet. @param WorkflowActionInstance $action @return WorkflowTransition
[ "Evaluate", "all", "the", "transitions", "of", "an", "action", "and", "determine", "whether", "we", "should", "follow", "any", "of", "them", "yet", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L424-L432
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.performTransition
public function performTransition(WorkflowTransition $transition) { // first make sure that the transition is valid to execute! $action = $this->CurrentAction(); $allTransitions = $action->BaseAction()->Transitions(); $valid = $allTransitions->find('ID', $transition->ID); if (!$valid) { throw new Exception( sprintf(_t( 'WorkflowInstance.WORKFLOW_TRANSITION_EXCEPTION', 'Invalid transition state for action #%s' ), $action->ID) ); } $action->actionComplete($transition); $definition = DataObject::get_by_id(WorkflowAction::class, $transition->NextActionID); $action = $definition->getInstanceForWorkflow(); $action->WorkflowID = $this->ID; $action->write(); $this->CurrentActionID = $action->ID; $this->write(); $this->components = array(); // manually clear the has_one cache $action->actionStart($transition); $transition->extend('onTransition'); $this->execute(); }
php
public function performTransition(WorkflowTransition $transition) { // first make sure that the transition is valid to execute! $action = $this->CurrentAction(); $allTransitions = $action->BaseAction()->Transitions(); $valid = $allTransitions->find('ID', $transition->ID); if (!$valid) { throw new Exception( sprintf(_t( 'WorkflowInstance.WORKFLOW_TRANSITION_EXCEPTION', 'Invalid transition state for action #%s' ), $action->ID) ); } $action->actionComplete($transition); $definition = DataObject::get_by_id(WorkflowAction::class, $transition->NextActionID); $action = $definition->getInstanceForWorkflow(); $action->WorkflowID = $this->ID; $action->write(); $this->CurrentActionID = $action->ID; $this->write(); $this->components = array(); // manually clear the has_one cache $action->actionStart($transition); $transition->extend('onTransition'); $this->execute(); }
[ "public", "function", "performTransition", "(", "WorkflowTransition", "$", "transition", ")", "{", "// first make sure that the transition is valid to execute!", "$", "action", "=", "$", "this", "->", "CurrentAction", "(", ")", ";", "$", "allTransitions", "=", "$", "a...
Transitions a workflow to the next step defined by the given transition. After transitioning, the action is 'executed', and next steps determined. @param WorkflowTransition $transition
[ "Transitions", "a", "workflow", "to", "the", "next", "step", "defined", "by", "the", "given", "transition", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L442-L473
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.getAssignedMembers
public function getAssignedMembers() { $list = new ArrayList(); $groups = $this->Groups(); $list->merge($this->Users()); foreach ($groups as $group) { $list->merge($group->Members()); } $list->removeDuplicates(); return $list; }
php
public function getAssignedMembers() { $list = new ArrayList(); $groups = $this->Groups(); $list->merge($this->Users()); foreach ($groups as $group) { $list->merge($group->Members()); } $list->removeDuplicates(); return $list; }
[ "public", "function", "getAssignedMembers", "(", ")", "{", "$", "list", "=", "new", "ArrayList", "(", ")", ";", "$", "groups", "=", "$", "this", "->", "Groups", "(", ")", ";", "$", "list", "->", "merge", "(", "$", "this", "->", "Users", "(", ")", ...
Returns a list of all Members that are assigned to this instance, either directly or via a group. @todo This could be made more efficient. @return ArrayList
[ "Returns", "a", "list", "of", "all", "Members", "that", "are", "assigned", "to", "this", "instance", "either", "directly", "or", "via", "a", "group", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L481-L494
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.userHasAccess
protected function userHasAccess($member) { if (!$member) { if (!Security::getCurrentUser()) { return false; } $member = Security::getCurrentUser(); } if (Permission::checkMember($member, "ADMIN")) { return true; } // This method primarily "protects" access to a WorkflowInstance, but assumes access only to be granted to // users assigned-to that WorkflowInstance. However; lowly authors (users entering items into a workflow) are // not assigned - but we still wish them to see their submitted content. $inWorkflowGroupOrUserTables = ($member->inGroups($this->Groups()) || $this->Users()->find('ID', $member->ID)); // This method is used in more than just the ModelAdmin. Check for the current controller to determine where // canView() expectations differ if ($this->getTarget() && Controller::curr()->getAction() == 'index' && !$inWorkflowGroupOrUserTables) { if ($this->getVersionedConnection($this->getTarget()->ID, $member->ID)) { return true; } return false; } return $inWorkflowGroupOrUserTables; }
php
protected function userHasAccess($member) { if (!$member) { if (!Security::getCurrentUser()) { return false; } $member = Security::getCurrentUser(); } if (Permission::checkMember($member, "ADMIN")) { return true; } // This method primarily "protects" access to a WorkflowInstance, but assumes access only to be granted to // users assigned-to that WorkflowInstance. However; lowly authors (users entering items into a workflow) are // not assigned - but we still wish them to see their submitted content. $inWorkflowGroupOrUserTables = ($member->inGroups($this->Groups()) || $this->Users()->find('ID', $member->ID)); // This method is used in more than just the ModelAdmin. Check for the current controller to determine where // canView() expectations differ if ($this->getTarget() && Controller::curr()->getAction() == 'index' && !$inWorkflowGroupOrUserTables) { if ($this->getVersionedConnection($this->getTarget()->ID, $member->ID)) { return true; } return false; } return $inWorkflowGroupOrUserTables; }
[ "protected", "function", "userHasAccess", "(", "$", "member", ")", "{", "if", "(", "!", "$", "member", ")", "{", "if", "(", "!", "Security", "::", "getCurrentUser", "(", ")", ")", "{", "return", "false", ";", "}", "$", "member", "=", "Security", "::"...
Checks whether the given user is in the list of users assigned to this workflow @param Member $member
[ "Checks", "whether", "the", "given", "user", "is", "in", "the", "list", "of", "users", "assigned", "to", "this", "workflow" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L562-L588
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.canEditTarget
public function canEditTarget() { if ($this->CurrentActionID && ($target = $this->getTarget())) { return $this->CurrentAction()->canEditTarget($target); } }
php
public function canEditTarget() { if ($this->CurrentActionID && ($target = $this->getTarget())) { return $this->CurrentAction()->canEditTarget($target); } }
[ "public", "function", "canEditTarget", "(", ")", "{", "if", "(", "$", "this", "->", "CurrentActionID", "&&", "(", "$", "target", "=", "$", "this", "->", "getTarget", "(", ")", ")", ")", "{", "return", "$", "this", "->", "CurrentAction", "(", ")", "->...
Can documents in the current workflow state be edited?
[ "Can", "documents", "in", "the", "current", "workflow", "state", "be", "edited?" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L593-L598
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.canViewTarget
public function canViewTarget() { $action = $this->CurrentAction(); if ($action) { return $action->canViewTarget($this->getTarget()); } return true; }
php
public function canViewTarget() { $action = $this->CurrentAction(); if ($action) { return $action->canViewTarget($this->getTarget()); } return true; }
[ "public", "function", "canViewTarget", "(", ")", "{", "$", "action", "=", "$", "this", "->", "CurrentAction", "(", ")", ";", "if", "(", "$", "action", ")", "{", "return", "$", "action", "->", "canViewTarget", "(", "$", "this", "->", "getTarget", "(", ...
Does this action restrict viewing of the document? @return boolean
[ "Does", "this", "action", "restrict", "viewing", "of", "the", "document?" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L605-L612
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.canPublishTarget
public function canPublishTarget() { if ($this->CurrentActionID && ($target = $this->getTarget())) { return $this->CurrentAction()->canPublishTarget($target); } }
php
public function canPublishTarget() { if ($this->CurrentActionID && ($target = $this->getTarget())) { return $this->CurrentAction()->canPublishTarget($target); } }
[ "public", "function", "canPublishTarget", "(", ")", "{", "if", "(", "$", "this", "->", "CurrentActionID", "&&", "(", "$", "target", "=", "$", "this", "->", "getTarget", "(", ")", ")", ")", "{", "return", "$", "this", "->", "CurrentAction", "(", ")", ...
Does this action restrict the publishing of a document? @return boolean
[ "Does", "this", "action", "restrict", "the", "publishing", "of", "a", "document?" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L619-L624
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.validTransitions
public function validTransitions() { $action = $this->CurrentAction(); $transitions = $action->getValidTransitions(); // Filter by execute permission return $transitions->filterByCallback(function ($transition) { return $transition->canExecute($this); }); }
php
public function validTransitions() { $action = $this->CurrentAction(); $transitions = $action->getValidTransitions(); // Filter by execute permission return $transitions->filterByCallback(function ($transition) { return $transition->canExecute($this); }); }
[ "public", "function", "validTransitions", "(", ")", "{", "$", "action", "=", "$", "this", "->", "CurrentAction", "(", ")", ";", "$", "transitions", "=", "$", "action", "->", "getValidTransitions", "(", ")", ";", "// Filter by execute permission", "return", "$"...
Get the current set of transitions that are valid for the current workflow state, and are available to the current user. @return array
[ "Get", "the", "current", "set", "of", "transitions", "that", "are", "valid", "for", "the", "current", "workflow", "state", "and", "are", "available", "to", "the", "current", "user", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L632-L641
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.getWorkflowFields
public function getWorkflowFields() { $action = $this->CurrentAction(); $options = $this->validTransitions(); $wfOptions = $options->map('ID', 'Title', ' '); $fields = new FieldList(); $fields->push(new HeaderField('WorkflowHeader', $action->Title)); $fields->push(HiddenField::create('TransitionID', '')); // Let the Active Action update the fields that the user can interact with so that data can be // stored for the workflow. $action->updateWorkflowFields($fields); $action->invokeWithExtensions('updateWorkflowFields', $fields); return $fields; }
php
public function getWorkflowFields() { $action = $this->CurrentAction(); $options = $this->validTransitions(); $wfOptions = $options->map('ID', 'Title', ' '); $fields = new FieldList(); $fields->push(new HeaderField('WorkflowHeader', $action->Title)); $fields->push(HiddenField::create('TransitionID', '')); // Let the Active Action update the fields that the user can interact with so that data can be // stored for the workflow. $action->updateWorkflowFields($fields); $action->invokeWithExtensions('updateWorkflowFields', $fields); return $fields; }
[ "public", "function", "getWorkflowFields", "(", ")", "{", "$", "action", "=", "$", "this", "->", "CurrentAction", "(", ")", ";", "$", "options", "=", "$", "this", "->", "validTransitions", "(", ")", ";", "$", "wfOptions", "=", "$", "options", "->", "ma...
Gets fields for managing this workflow instance in its current step @return FieldList
[ "Gets", "fields", "for", "managing", "this", "workflow", "instance", "in", "its", "current", "step" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L650-L665
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.getFrontEndWorkflowFields
public function getFrontEndWorkflowFields() { $action = $this->CurrentAction(); $fields = new FieldList(); $action->updateFrontEndWorkflowFields($fields); return $fields; }
php
public function getFrontEndWorkflowFields() { $action = $this->CurrentAction(); $fields = new FieldList(); $action->updateFrontEndWorkflowFields($fields); return $fields; }
[ "public", "function", "getFrontEndWorkflowFields", "(", ")", "{", "$", "action", "=", "$", "this", "->", "CurrentAction", "(", ")", ";", "$", "fields", "=", "new", "FieldList", "(", ")", ";", "$", "action", "->", "updateFrontEndWorkflowFields", "(", "$", "...
Gets Front-End form fields from current Action @return FieldList
[ "Gets", "Front", "-", "End", "form", "fields", "from", "current", "Action" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L672-L680
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.getFrontEndWorkflowActions
public function getFrontEndWorkflowActions() { $action = $this->CurrentAction(); $options = $action->getValidTransitions(); $actions = new FieldList(); $hide_disabled_actions_on_frontend = $this->config()->hide_disabled_actions_on_frontend; foreach ($options as $option) { $btn = new FormAction("transition_{$option->ID}", $option->Title); // add cancel class to passive actions, this prevents js validation (using jquery.validate) if ($option->Type == 'Passive') { $btn->addExtraClass('cancel'); } // disable the button if canExecute() returns false if (!$option->canExecute($this)) { if ($hide_disabled_actions_on_frontend) { continue; } $btn = $btn->performReadonlyTransformation(); $btn->addExtraClass('hide'); } $actions->push($btn); } $action->updateFrontEndWorkflowActions($actions); return $actions; }
php
public function getFrontEndWorkflowActions() { $action = $this->CurrentAction(); $options = $action->getValidTransitions(); $actions = new FieldList(); $hide_disabled_actions_on_frontend = $this->config()->hide_disabled_actions_on_frontend; foreach ($options as $option) { $btn = new FormAction("transition_{$option->ID}", $option->Title); // add cancel class to passive actions, this prevents js validation (using jquery.validate) if ($option->Type == 'Passive') { $btn->addExtraClass('cancel'); } // disable the button if canExecute() returns false if (!$option->canExecute($this)) { if ($hide_disabled_actions_on_frontend) { continue; } $btn = $btn->performReadonlyTransformation(); $btn->addExtraClass('hide'); } $actions->push($btn); } $action->updateFrontEndWorkflowActions($actions); return $actions; }
[ "public", "function", "getFrontEndWorkflowActions", "(", ")", "{", "$", "action", "=", "$", "this", "->", "CurrentAction", "(", ")", ";", "$", "options", "=", "$", "action", "->", "getValidTransitions", "(", ")", ";", "$", "actions", "=", "new", "FieldList...
Gets Transitions for display as Front-End Form Actions @return FieldList
[ "Gets", "Transitions", "for", "display", "as", "Front", "-", "End", "Form", "Actions" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L687-L719
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.getVersionedConnection
public function getVersionedConnection($recordID, $userID, $wasPublished = 0) { // Turn this into an array and run through implode() $filter = "RecordID = {$recordID} AND AuthorID = {$userID} AND WasPublished = {$wasPublished}"; $query = new SQLSelect(); $query->setFrom('"SiteTree_Versions"')->setSelect('COUNT("ID")')->setWhere($filter); $query->firstRow(); $hasAuthored = $query->execute(); if ($hasAuthored) { return true; } return false; }
php
public function getVersionedConnection($recordID, $userID, $wasPublished = 0) { // Turn this into an array and run through implode() $filter = "RecordID = {$recordID} AND AuthorID = {$userID} AND WasPublished = {$wasPublished}"; $query = new SQLSelect(); $query->setFrom('"SiteTree_Versions"')->setSelect('COUNT("ID")')->setWhere($filter); $query->firstRow(); $hasAuthored = $query->execute(); if ($hasAuthored) { return true; } return false; }
[ "public", "function", "getVersionedConnection", "(", "$", "recordID", ",", "$", "userID", ",", "$", "wasPublished", "=", "0", ")", "{", "// Turn this into an array and run through implode()", "$", "filter", "=", "\"RecordID = {$recordID} AND AuthorID = {$userID} AND WasPublis...
We need a way to "associate" an author with this WorkflowInstance and its Target() to see if she is "allowed" to view WorkflowInstances within GridFields @see {@link $this->userHasAccess()} @param number $recordID @param number $userID @param number $wasPublished @return boolean
[ "We", "need", "a", "way", "to", "associate", "an", "author", "with", "this", "WorkflowInstance", "and", "its", "Target", "()", "to", "see", "if", "she", "is", "allowed", "to", "view", "WorkflowInstances", "within", "GridFields", "@see", "{", "@link", "$this"...
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L769-L781
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.getCurrentAction
public function getCurrentAction() { $join = '"WorkflowAction"."ID" = "WorkflowActionInstance"."BaseActionID"'; $action = WorkflowAction::get() /** @skipUpgrade */ ->leftJoin('WorkflowActionInstance', $join) ->where('"WorkflowActionInstance"."ID" = '.$this->CurrentActionID) ->first(); if (!$action) { return 'N/A'; } return $action->getField('Title'); }
php
public function getCurrentAction() { $join = '"WorkflowAction"."ID" = "WorkflowActionInstance"."BaseActionID"'; $action = WorkflowAction::get() /** @skipUpgrade */ ->leftJoin('WorkflowActionInstance', $join) ->where('"WorkflowActionInstance"."ID" = '.$this->CurrentActionID) ->first(); if (!$action) { return 'N/A'; } return $action->getField('Title'); }
[ "public", "function", "getCurrentAction", "(", ")", "{", "$", "join", "=", "'\"WorkflowAction\".\"ID\" = \"WorkflowActionInstance\".\"BaseActionID\"'", ";", "$", "action", "=", "WorkflowAction", "::", "get", "(", ")", "/** @skipUpgrade */", "->", "leftJoin", "(", "'Work...
Simple method to retrieve the current action, on the current WorkflowInstance
[ "Simple", "method", "to", "retrieve", "the", "current", "action", "on", "the", "current", "WorkflowInstance" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L786-L798
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowInstance.php
WorkflowInstance.getMostRecentActionForUser
public function getMostRecentActionForUser($member = null) { if (!$member) { if (!Security::getCurrentUser()) { return false; } $member = Security::getCurrentUser(); } // WorkflowActionInstances in reverse creation-order so we get the most recent one's first $history = $this->Actions()->filter(array( 'Finished' =>1, 'BaseAction.ClassName' => AssignUsersToWorkflowAction::class ))->Sort('Created', 'DESC'); $i = 0; foreach ($history as $inst) { /* * This iteration represents the 1st instance in the list - the most recent AssignUsersToWorkflowAction * in $history. * If there's no match for $member here or on the _previous_ AssignUsersToWorkflowAction, then bail out: */ $assignedMembers = $inst->BaseAction()->getAssignedMembers(); if ($i <= 1 && $assignedMembers->count() > 0 && $assignedMembers->find('ID', $member->ID)) { return $inst; } ++$i; } return false; }
php
public function getMostRecentActionForUser($member = null) { if (!$member) { if (!Security::getCurrentUser()) { return false; } $member = Security::getCurrentUser(); } // WorkflowActionInstances in reverse creation-order so we get the most recent one's first $history = $this->Actions()->filter(array( 'Finished' =>1, 'BaseAction.ClassName' => AssignUsersToWorkflowAction::class ))->Sort('Created', 'DESC'); $i = 0; foreach ($history as $inst) { /* * This iteration represents the 1st instance in the list - the most recent AssignUsersToWorkflowAction * in $history. * If there's no match for $member here or on the _previous_ AssignUsersToWorkflowAction, then bail out: */ $assignedMembers = $inst->BaseAction()->getAssignedMembers(); if ($i <= 1 && $assignedMembers->count() > 0 && $assignedMembers->find('ID', $member->ID)) { return $inst; } ++$i; } return false; }
[ "public", "function", "getMostRecentActionForUser", "(", "$", "member", "=", "null", ")", "{", "if", "(", "!", "$", "member", ")", "{", "if", "(", "!", "Security", "::", "getCurrentUser", "(", ")", ")", "{", "return", "false", ";", "}", "$", "member", ...
Tells us if $member has had permissions over some part of the current WorkflowInstance. @param $member @return WorkflowAction|boolean
[ "Tells", "us", "if", "$member", "has", "had", "permissions", "over", "some", "part", "of", "the", "current", "WorkflowInstance", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowInstance.php#L806-L835
symbiote/silverstripe-advancedworkflow
src/Forms/AWRequiredFields.php
AWRequiredFields.getExtendedValidationRoutines
public function getExtendedValidationRoutines() { // Setup a return array $return = array( 'fieldValid' => true, 'fieldName' => null, 'fieldField' => null, 'fieldMsg' => null, ); $caller = $this->getCaller(); $methods = get_class_methods($caller); if (!$methods) { return $return; } foreach ($methods as $method) { if (!preg_match("#extendedRequiredFields#", $method)) { continue; } // One of the DO's validation methods has failed $extended = $caller->$method($this->getData()); if ($extended['fieldValid'] !== true) { $return['fieldValid'] = $extended['fieldValid']; $return['fieldName'] = $extended['fieldName']; $return['fieldField'] = $extended['fieldField']; $return['fieldMsg'] = $extended['fieldMsg']; break; } } return $return; }
php
public function getExtendedValidationRoutines() { // Setup a return array $return = array( 'fieldValid' => true, 'fieldName' => null, 'fieldField' => null, 'fieldMsg' => null, ); $caller = $this->getCaller(); $methods = get_class_methods($caller); if (!$methods) { return $return; } foreach ($methods as $method) { if (!preg_match("#extendedRequiredFields#", $method)) { continue; } // One of the DO's validation methods has failed $extended = $caller->$method($this->getData()); if ($extended['fieldValid'] !== true) { $return['fieldValid'] = $extended['fieldValid']; $return['fieldName'] = $extended['fieldName']; $return['fieldField'] = $extended['fieldField']; $return['fieldMsg'] = $extended['fieldMsg']; break; } } return $return; }
[ "public", "function", "getExtendedValidationRoutines", "(", ")", "{", "// Setup a return array", "$", "return", "=", "array", "(", "'fieldValid'", "=>", "true", ",", "'fieldName'", "=>", "null", ",", "'fieldField'", "=>", "null", ",", "'fieldMsg'", "=>", "null", ...
Allows for the addition of an arbitrary no. additional, dedicated and "extended" validation methods on classes that call AWRequiredFields. To add specific validation methods to a caller: 1). Write each checking method using this naming prototype: public function extendedRequiredFieldsXXX(). All methods so named will be called. 2). Call AWRequiredFields->setCaller($this) Each extended method thus called, should return an array of a specific format. (See: static $extendedMethodReturn on the caller) @return array $return
[ "Allows", "for", "the", "addition", "of", "an", "arbitrary", "no", ".", "additional", "dedicated", "and", "extended", "validation", "methods", "on", "classes", "that", "call", "AWRequiredFields", ".", "To", "add", "specific", "validation", "methods", "to", "a", ...
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Forms/AWRequiredFields.php#L65-L94
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowTransition.php
WorkflowTransition.onBeforeWrite
public function onBeforeWrite() { if (!$this->Sort) { $this->Sort = DB::query('SELECT MAX("Sort") + 1 FROM "WorkflowTransition"')->value(); } parent::onBeforeWrite(); }
php
public function onBeforeWrite() { if (!$this->Sort) { $this->Sort = DB::query('SELECT MAX("Sort") + 1 FROM "WorkflowTransition"')->value(); } parent::onBeforeWrite(); }
[ "public", "function", "onBeforeWrite", "(", ")", "{", "if", "(", "!", "$", "this", "->", "Sort", ")", "{", "$", "this", "->", "Sort", "=", "DB", "::", "query", "(", "'SELECT MAX(\"Sort\") + 1 FROM \"WorkflowTransition\"'", ")", "->", "value", "(", ")", ";"...
Before saving, make sure we're not in an infinite loop
[ "Before", "saving", "make", "sure", "we", "re", "not", "in", "an", "infinite", "loop" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowTransition.php#L86-L93
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowTransition.php
WorkflowTransition.getCMSFields
public function getCMSFields() { $fields = new FieldList(new TabSet('Root')); $fields->addFieldToTab('Root.Main', new TextField('Title', $this->fieldLabel('Title'))); $filter = ''; $reqParent = isset($_REQUEST['ParentID']) ? (int) $_REQUEST['ParentID'] : 0; $attachTo = $this->ActionID ? $this->ActionID : $reqParent; if ($attachTo) { $action = DataObject::get_by_id(WorkflowAction::class, $attachTo); if ($action && $action->ID) { $filter = '"WorkflowDefID" = '.((int) $action->WorkflowDefID); } } $actions = DataObject::get(WorkflowAction::class, $filter); $options = array(); if ($actions) { $options = $actions->map(); } $defaultAction = $action ? $action->ID : ""; $typeOptions = array( 'Active' => _t('WorkflowTransition.Active', 'Active'), 'Passive' => _t('WorkflowTransition.Passive', 'Passive'), ); $fields->addFieldToTab('Root.Main', new DropdownField( 'ActionID', $this->fieldLabel('ActionID'), $options, $defaultAction )); $fields->addFieldToTab('Root.Main', $nextActionDropdownField = new DropdownField( 'NextActionID', $this->fieldLabel('NextActionID'), $options )); $nextActionDropdownField->setEmptyString(_t('WorkflowTransition.SELECTONE', '(Select one)')); $fields->addFieldToTab('Root.Main', new DropdownField( 'Type', _t('WorkflowTransition.TYPE', 'Type'), $typeOptions )); $members = Member::get(); $fields->findOrMakeTab( 'Root.RestrictToUsers', _t('WorkflowTransition.TabTitle', 'Restrict to users') ); $fields->addFieldToTab( 'Root.RestrictToUsers', new CheckboxSetField('Users', _t('WorkflowDefinition.USERS', 'Restrict to Users'), $members) ); $fields->addFieldToTab( 'Root.RestrictToUsers', new TreeMultiselectField('Groups', _t('WorkflowDefinition.GROUPS', 'Restrict to Groups'), Group::class) ); $this->extend('updateCMSFields', $fields); return $fields; }
php
public function getCMSFields() { $fields = new FieldList(new TabSet('Root')); $fields->addFieldToTab('Root.Main', new TextField('Title', $this->fieldLabel('Title'))); $filter = ''; $reqParent = isset($_REQUEST['ParentID']) ? (int) $_REQUEST['ParentID'] : 0; $attachTo = $this->ActionID ? $this->ActionID : $reqParent; if ($attachTo) { $action = DataObject::get_by_id(WorkflowAction::class, $attachTo); if ($action && $action->ID) { $filter = '"WorkflowDefID" = '.((int) $action->WorkflowDefID); } } $actions = DataObject::get(WorkflowAction::class, $filter); $options = array(); if ($actions) { $options = $actions->map(); } $defaultAction = $action ? $action->ID : ""; $typeOptions = array( 'Active' => _t('WorkflowTransition.Active', 'Active'), 'Passive' => _t('WorkflowTransition.Passive', 'Passive'), ); $fields->addFieldToTab('Root.Main', new DropdownField( 'ActionID', $this->fieldLabel('ActionID'), $options, $defaultAction )); $fields->addFieldToTab('Root.Main', $nextActionDropdownField = new DropdownField( 'NextActionID', $this->fieldLabel('NextActionID'), $options )); $nextActionDropdownField->setEmptyString(_t('WorkflowTransition.SELECTONE', '(Select one)')); $fields->addFieldToTab('Root.Main', new DropdownField( 'Type', _t('WorkflowTransition.TYPE', 'Type'), $typeOptions )); $members = Member::get(); $fields->findOrMakeTab( 'Root.RestrictToUsers', _t('WorkflowTransition.TabTitle', 'Restrict to users') ); $fields->addFieldToTab( 'Root.RestrictToUsers', new CheckboxSetField('Users', _t('WorkflowDefinition.USERS', 'Restrict to Users'), $members) ); $fields->addFieldToTab( 'Root.RestrictToUsers', new TreeMultiselectField('Groups', _t('WorkflowDefinition.GROUPS', 'Restrict to Groups'), Group::class) ); $this->extend('updateCMSFields', $fields); return $fields; }
[ "public", "function", "getCMSFields", "(", ")", "{", "$", "fields", "=", "new", "FieldList", "(", "new", "TabSet", "(", "'Root'", ")", ")", ";", "$", "fields", "->", "addFieldToTab", "(", "'Root.Main'", ",", "new", "TextField", "(", "'Title'", ",", "$", ...
/* CMS FUNCTIONS
[ "/", "*", "CMS", "FUNCTIONS" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowTransition.php#L97-L162
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowTransition.php
WorkflowTransition.canExecute
public function canExecute(WorkflowInstance $workflow) { $return = true; $members = $this->getAssignedMembers(); // If not admin, check if the member is in the list of assigned members if (!Permission::check('ADMIN') && $members->exists()) { if (!$members->find('ID', Security::getCurrentUser()->ID)) { $return = false; } } if ($return) { $extended = $this->extend('extendCanExecute', $workflow); if ($extended) { $return = min($extended); } } return $return !== false; }
php
public function canExecute(WorkflowInstance $workflow) { $return = true; $members = $this->getAssignedMembers(); // If not admin, check if the member is in the list of assigned members if (!Permission::check('ADMIN') && $members->exists()) { if (!$members->find('ID', Security::getCurrentUser()->ID)) { $return = false; } } if ($return) { $extended = $this->extend('extendCanExecute', $workflow); if ($extended) { $return = min($extended); } } return $return !== false; }
[ "public", "function", "canExecute", "(", "WorkflowInstance", "$", "workflow", ")", "{", "$", "return", "=", "true", ";", "$", "members", "=", "$", "this", "->", "getAssignedMembers", "(", ")", ";", "// If not admin, check if the member is in the list of assigned membe...
Check if the current user can execute this transition @return bool
[ "Check", "if", "the", "current", "user", "can", "execute", "this", "transition" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowTransition.php#L199-L219
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowTransition.php
WorkflowTransition.canCreate
public function canCreate($member = null, $context = array()) { return $this->Action()->WorkflowDef()->canCreate($member, $context); }
php
public function canCreate($member = null, $context = array()) { return $this->Action()->WorkflowDef()->canCreate($member, $context); }
[ "public", "function", "canCreate", "(", "$", "member", "=", "null", ",", "$", "context", "=", "array", "(", ")", ")", "{", "return", "$", "this", "->", "Action", "(", ")", "->", "WorkflowDef", "(", ")", "->", "canCreate", "(", "$", "member", ",", "...
Allows users who have permission to create a WorkflowDefinition, to create actions on it too. @param Member $member @param array $context @return bool
[ "Allows", "users", "who", "have", "permission", "to", "create", "a", "WorkflowDefinition", "to", "create", "actions", "on", "it", "too", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowTransition.php#L228-L231
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowTransition.php
WorkflowTransition.getAssignedMembers
public function getAssignedMembers() { $members = ArrayList::create($this->Users()->toArray()); $groups = $this->Groups(); foreach ($groups as $group) { $members->merge($group->Members()); } $members->removeDuplicates(); return $members; }
php
public function getAssignedMembers() { $members = ArrayList::create($this->Users()->toArray()); $groups = $this->Groups(); foreach ($groups as $group) { $members->merge($group->Members()); } $members->removeDuplicates(); return $members; }
[ "public", "function", "getAssignedMembers", "(", ")", "{", "$", "members", "=", "ArrayList", "::", "create", "(", "$", "this", "->", "Users", "(", ")", "->", "toArray", "(", ")", ")", ";", "$", "groups", "=", "$", "this", "->", "Groups", "(", ")", ...
Returns a set of all Members that are assigned to this transition, either directly or via a group. @return ArrayList
[ "Returns", "a", "set", "of", "all", "Members", "that", "are", "assigned", "to", "this", "transition", "either", "directly", "or", "via", "a", "group", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowTransition.php#L256-L267
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowTransition.php
WorkflowTransition.extendedRequiredFieldsNotSame
public function extendedRequiredFieldsNotSame($data = null) { $check = array('ActionID','NextActionID'); foreach ($check as $fieldName) { if (!isset($data[$fieldName])) { return self::$extendedMethodReturn; } } // Have we found some identical values? if ($data[$check[0]] == $data[$check[1]]) { // Used to display to the user, so the first of the array is fine self::$extendedMethodReturn['fieldName'] = $check[0]; self::$extendedMethodReturn['fieldValid'] = false; self::$extendedMethodReturn['fieldMsg'] = _t( 'WorkflowTransition.TRANSITIONLOOP', 'A transition cannot lead back to its parent action.' ); } return self::$extendedMethodReturn; }
php
public function extendedRequiredFieldsNotSame($data = null) { $check = array('ActionID','NextActionID'); foreach ($check as $fieldName) { if (!isset($data[$fieldName])) { return self::$extendedMethodReturn; } } // Have we found some identical values? if ($data[$check[0]] == $data[$check[1]]) { // Used to display to the user, so the first of the array is fine self::$extendedMethodReturn['fieldName'] = $check[0]; self::$extendedMethodReturn['fieldValid'] = false; self::$extendedMethodReturn['fieldMsg'] = _t( 'WorkflowTransition.TRANSITIONLOOP', 'A transition cannot lead back to its parent action.' ); } return self::$extendedMethodReturn; }
[ "public", "function", "extendedRequiredFieldsNotSame", "(", "$", "data", "=", "null", ")", "{", "$", "check", "=", "array", "(", "'ActionID'", ",", "'NextActionID'", ")", ";", "foreach", "(", "$", "check", "as", "$", "fieldName", ")", "{", "if", "(", "!"...
/* A simple field same-value checker. @param array $data @return array @see {@link AWRequiredFields}
[ "/", "*", "A", "simple", "field", "same", "-", "value", "checker", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowTransition.php#L276-L295
symbiote/silverstripe-advancedworkflow
src/Extensions/AdvancedWorkflowExtension.php
AdvancedWorkflowExtension.updateEditForm
public function updateEditForm(Form $form) { Requirements::javascript('symbiote/silverstripe-advancedworkflow:client/dist/js/advancedworkflow.js'); /** @var WorkflowService $service */ $service = singleton(WorkflowService::class); /** @var DataObject|WorkflowApplicable $record */ $record = $form->getRecord(); $active = $service->getWorkflowFor($record); if ($active) { $fields = $form->Fields(); $current = $active->CurrentAction(); $wfFields = $active->getWorkflowFields(); $allowed = array_keys($wfFields->saveableFields()); $data = []; foreach ($allowed as $fieldName) { $data[$fieldName] = $current->$fieldName; } $fields->findOrMakeTab( 'Root.WorkflowActions', _t('Workflow.WorkflowActionsTabTitle', 'Workflow Actions') ); $fields->addFieldsToTab('Root.WorkflowActions', $wfFields); $form->loadDataFrom($data); // Set the form to readonly if the current user doesn't have permission to edit the record, and/or it // is in a state that requires review if (!$record->canEditWorkflow() && !$fields->isReadonly()) { $fields->makeReadonly(); } $this->owner->extend('updateWorkflowEditForm', $form); } }
php
public function updateEditForm(Form $form) { Requirements::javascript('symbiote/silverstripe-advancedworkflow:client/dist/js/advancedworkflow.js'); /** @var WorkflowService $service */ $service = singleton(WorkflowService::class); /** @var DataObject|WorkflowApplicable $record */ $record = $form->getRecord(); $active = $service->getWorkflowFor($record); if ($active) { $fields = $form->Fields(); $current = $active->CurrentAction(); $wfFields = $active->getWorkflowFields(); $allowed = array_keys($wfFields->saveableFields()); $data = []; foreach ($allowed as $fieldName) { $data[$fieldName] = $current->$fieldName; } $fields->findOrMakeTab( 'Root.WorkflowActions', _t('Workflow.WorkflowActionsTabTitle', 'Workflow Actions') ); $fields->addFieldsToTab('Root.WorkflowActions', $wfFields); $form->loadDataFrom($data); // Set the form to readonly if the current user doesn't have permission to edit the record, and/or it // is in a state that requires review if (!$record->canEditWorkflow() && !$fields->isReadonly()) { $fields->makeReadonly(); } $this->owner->extend('updateWorkflowEditForm', $form); } }
[ "public", "function", "updateEditForm", "(", "Form", "$", "form", ")", "{", "Requirements", "::", "javascript", "(", "'symbiote/silverstripe-advancedworkflow:client/dist/js/advancedworkflow.js'", ")", ";", "/** @var WorkflowService $service */", "$", "service", "=", "singleto...
Need to update the edit form AFTER it's been transformed to read only so that the workflow stuff is still allowed to be added with 'write' permissions @param Form $form
[ "Need", "to", "update", "the", "edit", "form", "AFTER", "it", "s", "been", "transformed", "to", "read", "only", "so", "that", "the", "workflow", "stuff", "is", "still", "allowed", "to", "be", "added", "with", "write", "permissions" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/AdvancedWorkflowExtension.php#L62-L98
symbiote/silverstripe-advancedworkflow
src/Extensions/AdvancedWorkflowExtension.php
AdvancedWorkflowExtension.updateworkflow
public function updateworkflow($data, Form $form, $request) { /** @var WorkflowService $service */ $service = singleton(WorkflowService::class); /** @var DataObject $record */ $record = $form->getRecord(); $workflow = $service->getWorkflowFor($record); if (!$workflow) { return null; } $action = $workflow->CurrentAction(); if (!$record || !$record->canEditWorkflow()) { return null; } $allowedFields = $workflow->getWorkflowFields()->saveableFields(); unset($allowedFields['TransitionID']); $allowed = array_keys($allowedFields); if (count($allowed)) { $form->saveInto($action, $allowed); $action->write(); } if (isset($data['TransitionID']) && $data['TransitionID']) { $service->executeTransition($record, $data['TransitionID']); } else { // otherwise, just try to execute the current workflow to see if it // can now proceed based on user input $workflow->execute(); } return $this->returnResponse($form); }
php
public function updateworkflow($data, Form $form, $request) { /** @var WorkflowService $service */ $service = singleton(WorkflowService::class); /** @var DataObject $record */ $record = $form->getRecord(); $workflow = $service->getWorkflowFor($record); if (!$workflow) { return null; } $action = $workflow->CurrentAction(); if (!$record || !$record->canEditWorkflow()) { return null; } $allowedFields = $workflow->getWorkflowFields()->saveableFields(); unset($allowedFields['TransitionID']); $allowed = array_keys($allowedFields); if (count($allowed)) { $form->saveInto($action, $allowed); $action->write(); } if (isset($data['TransitionID']) && $data['TransitionID']) { $service->executeTransition($record, $data['TransitionID']); } else { // otherwise, just try to execute the current workflow to see if it // can now proceed based on user input $workflow->execute(); } return $this->returnResponse($form); }
[ "public", "function", "updateworkflow", "(", "$", "data", ",", "Form", "$", "form", ",", "$", "request", ")", "{", "/** @var WorkflowService $service */", "$", "service", "=", "singleton", "(", "WorkflowService", "::", "class", ")", ";", "/** @var DataObject $reco...
Update a workflow based on user input. @todo refactor with WorkflowInstance::updateWorkflow @param array $data @param Form $form @param HTTPRequest $request @return string|null
[ "Update", "a", "workflow", "based", "on", "user", "input", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/AdvancedWorkflowExtension.php#L124-L159
symbiote/silverstripe-advancedworkflow
src/Extensions/AdvancedWorkflowExtension.php
AdvancedWorkflowExtension.saveAsDraftWithAction
protected function saveAsDraftWithAction(Form $form, DataObject $item) { $form->saveInto($item); $item->write(); }
php
protected function saveAsDraftWithAction(Form $form, DataObject $item) { $form->saveInto($item); $item->write(); }
[ "protected", "function", "saveAsDraftWithAction", "(", "Form", "$", "form", ",", "DataObject", "$", "item", ")", "{", "$", "form", "->", "saveInto", "(", "$", "item", ")", ";", "$", "item", "->", "write", "(", ")", ";", "}" ]
Ocassionally users forget to apply their changes via the standard CMS "Save Draft" button, and select the action button instead - losing their changes. Calling this from a controller method saves a draft automatically for the user, whenever a workflow action is run See: #72 and #77 @param Form $form @param DataObject $item @return void
[ "Ocassionally", "users", "forget", "to", "apply", "their", "changes", "via", "the", "standard", "CMS", "Save", "Draft", "button", "and", "select", "the", "action", "button", "instead", "-", "losing", "their", "changes", ".", "Calling", "this", "from", "a", "...
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/AdvancedWorkflowExtension.php#L186-L190
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowEmbargoExpiryExtension.php
WorkflowEmbargoExpiryExtension.clearPublishJob
public function clearPublishJob() { $job = $this->owner->PublishJob(); if ($job && $job->exists()) { $job->delete(); } $this->owner->PublishJobID = 0; }
php
public function clearPublishJob() { $job = $this->owner->PublishJob(); if ($job && $job->exists()) { $job->delete(); } $this->owner->PublishJobID = 0; }
[ "public", "function", "clearPublishJob", "(", ")", "{", "$", "job", "=", "$", "this", "->", "owner", "->", "PublishJob", "(", ")", ";", "if", "(", "$", "job", "&&", "$", "job", "->", "exists", "(", ")", ")", "{", "$", "job", "->", "delete", "(", ...
Clears any existing publish job against this dataobject
[ "Clears", "any", "existing", "publish", "job", "against", "this", "dataobject" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowEmbargoExpiryExtension.php#L181-L188
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowEmbargoExpiryExtension.php
WorkflowEmbargoExpiryExtension.clearUnPublishJob
public function clearUnPublishJob() { // Cancel any in-progress unpublish job $job = $this->owner->UnPublishJob(); if ($job && $job->exists()) { $job->delete(); } $this->owner->UnPublishJobID = 0; }
php
public function clearUnPublishJob() { // Cancel any in-progress unpublish job $job = $this->owner->UnPublishJob(); if ($job && $job->exists()) { $job->delete(); } $this->owner->UnPublishJobID = 0; }
[ "public", "function", "clearUnPublishJob", "(", ")", "{", "// Cancel any in-progress unpublish job", "$", "job", "=", "$", "this", "->", "owner", "->", "UnPublishJob", "(", ")", ";", "if", "(", "$", "job", "&&", "$", "job", "->", "exists", "(", ")", ")", ...
Clears any existing unpublish job
[ "Clears", "any", "existing", "unpublish", "job" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowEmbargoExpiryExtension.php#L193-L201
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowEmbargoExpiryExtension.php
WorkflowEmbargoExpiryExtension.ensurePublishJob
protected function ensurePublishJob($when) { // Check if there is a prior job if ($this->owner->PublishJobID) { $job = $this->owner->PublishJob(); // Use timestamp for sake of comparison. if ($job && $job->exists() && DBDatetime::create()->setValue($job->StartAfter)->getTimestamp() == $when) { return; } $this->clearPublishJob(); } // Create a new job with the specified schedule $job = new WorkflowPublishTargetJob($this->owner, 'publish'); $this->owner->PublishJobID = Injector::inst()->get(QueuedJobService::class) ->queueJob($job, $when ? date('Y-m-d H:i:s', $when) : null); }
php
protected function ensurePublishJob($when) { // Check if there is a prior job if ($this->owner->PublishJobID) { $job = $this->owner->PublishJob(); // Use timestamp for sake of comparison. if ($job && $job->exists() && DBDatetime::create()->setValue($job->StartAfter)->getTimestamp() == $when) { return; } $this->clearPublishJob(); } // Create a new job with the specified schedule $job = new WorkflowPublishTargetJob($this->owner, 'publish'); $this->owner->PublishJobID = Injector::inst()->get(QueuedJobService::class) ->queueJob($job, $when ? date('Y-m-d H:i:s', $when) : null); }
[ "protected", "function", "ensurePublishJob", "(", "$", "when", ")", "{", "// Check if there is a prior job", "if", "(", "$", "this", "->", "owner", "->", "PublishJobID", ")", "{", "$", "job", "=", "$", "this", "->", "owner", "->", "PublishJob", "(", ")", "...
Ensure the existence of a publish job at the specified time @param int $when Timestamp to start this job, or null to start immediately
[ "Ensure", "the", "existence", "of", "a", "publish", "job", "at", "the", "specified", "time" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowEmbargoExpiryExtension.php#L208-L224
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowEmbargoExpiryExtension.php
WorkflowEmbargoExpiryExtension.ensureUnPublishJob
protected function ensureUnPublishJob($when) { // Check if there is a prior job if ($this->owner->UnPublishJobID) { $job = $this->owner->UnPublishJob(); // Use timestamp for sake of comparison. if ($job && $job->exists() && DBDatetime::create()->setValue($job->StartAfter)->getTimestamp() == $when) { return; } $this->clearUnPublishJob(); } // Create a new job with the specified schedule $job = new WorkflowPublishTargetJob($this->owner, 'unpublish'); $this->owner->UnPublishJobID = Injector::inst()->get(QueuedJobService::class) ->queueJob($job, $when ? date('Y-m-d H:i:s', $when) : null); }
php
protected function ensureUnPublishJob($when) { // Check if there is a prior job if ($this->owner->UnPublishJobID) { $job = $this->owner->UnPublishJob(); // Use timestamp for sake of comparison. if ($job && $job->exists() && DBDatetime::create()->setValue($job->StartAfter)->getTimestamp() == $when) { return; } $this->clearUnPublishJob(); } // Create a new job with the specified schedule $job = new WorkflowPublishTargetJob($this->owner, 'unpublish'); $this->owner->UnPublishJobID = Injector::inst()->get(QueuedJobService::class) ->queueJob($job, $when ? date('Y-m-d H:i:s', $when) : null); }
[ "protected", "function", "ensureUnPublishJob", "(", "$", "when", ")", "{", "// Check if there is a prior job", "if", "(", "$", "this", "->", "owner", "->", "UnPublishJobID", ")", "{", "$", "job", "=", "$", "this", "->", "owner", "->", "UnPublishJob", "(", ")...
Ensure the existence of an unpublish job at the specified time @param int $when Timestamp to start this job, or null to start immediately
[ "Ensure", "the", "existence", "of", "an", "unpublish", "job", "at", "the", "specified", "time" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowEmbargoExpiryExtension.php#L231-L247
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowEmbargoExpiryExtension.php
WorkflowEmbargoExpiryExtension.onBeforeWrite
public function onBeforeWrite() { parent::onBeforeWrite(); // only operate on staging content for this extension; otherwise, you // need to publish the page to be able to set a 'future' publish... // while the same could be said for the unpublish, the 'publish' state // is the one that must be avoided so we allow setting the 'unpublish' // date for as-yet-not-published content. if (Versioned::get_stage() === Versioned::LIVE) { return; } /* * Without checking if there's actually a workflow in effect, simply saving * as draft, would clear the Scheduled Publish & Unpublish date fields, which we obviously * don't want during a workflow: These date fields should be treated as a content * change that also requires approval (where such an approval step exists). * * - Check to see if we've got 'desired' publish/unpublish date(s). * - Check if there's a workflow attached to this content * - Reset values if it's safe to do so */ if (!$this->getIsWorkflowInEffect()) { $resetPublishOnDate = $this->owner->DesiredPublishDate && $this->owner->PublishOnDate; if ($resetPublishOnDate) { $this->owner->PublishOnDate = null; } $resetUnPublishOnDate = $this->owner->DesiredUnPublishDate && $this->owner->UnPublishOnDate; if ($resetUnPublishOnDate) { $this->owner->UnPublishOnDate = null; } } // Jobs can only be queued for records that already exist if (!$this->owner->ID) { return; } // Check requested dates of publish / unpublish, and whether the page should have already been unpublished $now = DBDatetime::now()->getTimestamp(); $publishTime = $this->owner->dbObject('PublishOnDate')->getTimestamp(); $unPublishTime = $this->owner->dbObject('UnPublishOnDate')->getTimestamp(); // We should have a publish job if: // if no unpublish or publish time, then the Workflow Publish Action will publish without a job if ((!$unPublishTime && $publishTime) // the unpublish date is not set || ( // unpublish date has not passed $unPublishTime > $now // publish date not set or happens before unpublish date && ($publishTime && ($publishTime < $unPublishTime)) ) ) { // Trigger time immediately if passed $this->ensurePublishJob($publishTime < $now ? null : $publishTime); } else { $this->clearPublishJob(); } // We should have an unpublish job if: if ($unPublishTime // we have an unpublish date && $publishTime < $unPublishTime // publish date is before to unpublish date ) { // Trigger time immediately if passed $this->ensureUnPublishJob($unPublishTime < $now ? null : $unPublishTime); } else { $this->clearUnPublishJob(); } }
php
public function onBeforeWrite() { parent::onBeforeWrite(); // only operate on staging content for this extension; otherwise, you // need to publish the page to be able to set a 'future' publish... // while the same could be said for the unpublish, the 'publish' state // is the one that must be avoided so we allow setting the 'unpublish' // date for as-yet-not-published content. if (Versioned::get_stage() === Versioned::LIVE) { return; } /* * Without checking if there's actually a workflow in effect, simply saving * as draft, would clear the Scheduled Publish & Unpublish date fields, which we obviously * don't want during a workflow: These date fields should be treated as a content * change that also requires approval (where such an approval step exists). * * - Check to see if we've got 'desired' publish/unpublish date(s). * - Check if there's a workflow attached to this content * - Reset values if it's safe to do so */ if (!$this->getIsWorkflowInEffect()) { $resetPublishOnDate = $this->owner->DesiredPublishDate && $this->owner->PublishOnDate; if ($resetPublishOnDate) { $this->owner->PublishOnDate = null; } $resetUnPublishOnDate = $this->owner->DesiredUnPublishDate && $this->owner->UnPublishOnDate; if ($resetUnPublishOnDate) { $this->owner->UnPublishOnDate = null; } } // Jobs can only be queued for records that already exist if (!$this->owner->ID) { return; } // Check requested dates of publish / unpublish, and whether the page should have already been unpublished $now = DBDatetime::now()->getTimestamp(); $publishTime = $this->owner->dbObject('PublishOnDate')->getTimestamp(); $unPublishTime = $this->owner->dbObject('UnPublishOnDate')->getTimestamp(); // We should have a publish job if: // if no unpublish or publish time, then the Workflow Publish Action will publish without a job if ((!$unPublishTime && $publishTime) // the unpublish date is not set || ( // unpublish date has not passed $unPublishTime > $now // publish date not set or happens before unpublish date && ($publishTime && ($publishTime < $unPublishTime)) ) ) { // Trigger time immediately if passed $this->ensurePublishJob($publishTime < $now ? null : $publishTime); } else { $this->clearPublishJob(); } // We should have an unpublish job if: if ($unPublishTime // we have an unpublish date && $publishTime < $unPublishTime // publish date is before to unpublish date ) { // Trigger time immediately if passed $this->ensureUnPublishJob($unPublishTime < $now ? null : $unPublishTime); } else { $this->clearUnPublishJob(); } }
[ "public", "function", "onBeforeWrite", "(", ")", "{", "parent", "::", "onBeforeWrite", "(", ")", ";", "// only operate on staging content for this extension; otherwise, you", "// need to publish the page to be able to set a 'future' publish...", "// while the same could be said for the u...
{@see PublishItemWorkflowAction} for approval of requested publish dates
[ "{" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowEmbargoExpiryExtension.php#L262-L333
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowEmbargoExpiryExtension.php
WorkflowEmbargoExpiryExtension.updateStatusFlags
public function updateStatusFlags(&$flags) { $embargo = $this->getIsPublishScheduled(); $expiry = $this->getIsUnPublishScheduled(); if ($embargo || $expiry) { unset($flags['addedtodraft'], $flags['modified']); } if ($embargo && $expiry) { $flags['embargo_expiry'] = array( 'text' => _t('WorkflowEmbargoExpiryExtension.BADGE_PUBLISH_UNPUBLISH', 'Embargo+Expiry'), 'title' => sprintf( '%s: %s, %s: %s', _t('WorkflowEmbargoExpiryExtension.PUBLISH_ON', 'Scheduled publish date'), $this->owner->PublishOnDate, _t('WorkflowEmbargoExpiryExtension.UNPUBLISH_ON', 'Scheduled un-publish date'), $this->owner->UnPublishOnDate ), ); } elseif ($embargo) { $flags['embargo'] = array( 'text' => _t('WorkflowEmbargoExpiryExtension.BADGE_PUBLISH', 'Embargo'), 'title' => sprintf( '%s: %s', _t('WorkflowEmbargoExpiryExtension.PUBLISH_ON', 'Scheduled publish date'), $this->owner->PublishOnDate ), ); } elseif ($expiry) { $flags['expiry'] = array( 'text' => _t('WorkflowEmbargoExpiryExtension.BADGE_UNPUBLISH', 'Expiry'), 'title' => sprintf( '%s: %s', _t('WorkflowEmbargoExpiryExtension.UNPUBLISH_ON', 'Scheduled un-publish date'), $this->owner->UnPublishOnDate ), ); } }
php
public function updateStatusFlags(&$flags) { $embargo = $this->getIsPublishScheduled(); $expiry = $this->getIsUnPublishScheduled(); if ($embargo || $expiry) { unset($flags['addedtodraft'], $flags['modified']); } if ($embargo && $expiry) { $flags['embargo_expiry'] = array( 'text' => _t('WorkflowEmbargoExpiryExtension.BADGE_PUBLISH_UNPUBLISH', 'Embargo+Expiry'), 'title' => sprintf( '%s: %s, %s: %s', _t('WorkflowEmbargoExpiryExtension.PUBLISH_ON', 'Scheduled publish date'), $this->owner->PublishOnDate, _t('WorkflowEmbargoExpiryExtension.UNPUBLISH_ON', 'Scheduled un-publish date'), $this->owner->UnPublishOnDate ), ); } elseif ($embargo) { $flags['embargo'] = array( 'text' => _t('WorkflowEmbargoExpiryExtension.BADGE_PUBLISH', 'Embargo'), 'title' => sprintf( '%s: %s', _t('WorkflowEmbargoExpiryExtension.PUBLISH_ON', 'Scheduled publish date'), $this->owner->PublishOnDate ), ); } elseif ($expiry) { $flags['expiry'] = array( 'text' => _t('WorkflowEmbargoExpiryExtension.BADGE_UNPUBLISH', 'Expiry'), 'title' => sprintf( '%s: %s', _t('WorkflowEmbargoExpiryExtension.UNPUBLISH_ON', 'Scheduled un-publish date'), $this->owner->UnPublishOnDate ), ); } }
[ "public", "function", "updateStatusFlags", "(", "&", "$", "flags", ")", "{", "$", "embargo", "=", "$", "this", "->", "getIsPublishScheduled", "(", ")", ";", "$", "expiry", "=", "$", "this", "->", "getIsUnPublishScheduled", "(", ")", ";", "if", "(", "$", ...
Add badges to the site tree view to show that a page has been scheduled for publishing or unpublishing @param $flags
[ "Add", "badges", "to", "the", "site", "tree", "view", "to", "show", "that", "a", "page", "has", "been", "scheduled", "for", "publishing", "or", "unpublishing" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowEmbargoExpiryExtension.php#L340-L379
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowEmbargoExpiryExtension.php
WorkflowEmbargoExpiryExtension.getIntroMessageParts
public function getIntroMessageParts($key) { $parts = array( 'PublishDateIntro' => array( 'INTRO'=>_t( 'WorkflowEmbargoExpiryExtension.REQUESTED_PUBLISH_DATE_INTRO', 'Enter a date and/or time to specify embargo and expiry dates.' ), 'BULLET_1'=>_t( 'WorkflowEmbargoExpiryExtension.REQUESTED_PUBLISH_DATE_INTRO_BULLET_1', 'These settings won\'t take effect until any approval actions are run' ), 'BULLET_2'=>_t( 'WorkflowEmbargoExpiryExtension.REQUESTED_PUBLISH_DATE_INTRO_BULLET_2', 'If an embargo is already set, adding a new one prior to that date\'s passing will overwrite it' ) ) ); // If there's no effective workflow, no need for the first bullet-point if (!$this->getIsWorkflowInEffect()) { $parts['PublishDateIntro']['BULLET_1'] = false; } return $parts[$key]; }
php
public function getIntroMessageParts($key) { $parts = array( 'PublishDateIntro' => array( 'INTRO'=>_t( 'WorkflowEmbargoExpiryExtension.REQUESTED_PUBLISH_DATE_INTRO', 'Enter a date and/or time to specify embargo and expiry dates.' ), 'BULLET_1'=>_t( 'WorkflowEmbargoExpiryExtension.REQUESTED_PUBLISH_DATE_INTRO_BULLET_1', 'These settings won\'t take effect until any approval actions are run' ), 'BULLET_2'=>_t( 'WorkflowEmbargoExpiryExtension.REQUESTED_PUBLISH_DATE_INTRO_BULLET_2', 'If an embargo is already set, adding a new one prior to that date\'s passing will overwrite it' ) ) ); // If there's no effective workflow, no need for the first bullet-point if (!$this->getIsWorkflowInEffect()) { $parts['PublishDateIntro']['BULLET_1'] = false; } return $parts[$key]; }
[ "public", "function", "getIntroMessageParts", "(", "$", "key", ")", "{", "$", "parts", "=", "array", "(", "'PublishDateIntro'", "=>", "array", "(", "'INTRO'", "=>", "_t", "(", "'WorkflowEmbargoExpiryExtension.REQUESTED_PUBLISH_DATE_INTRO'", ",", "'Enter a date and/or ti...
/* Define an array of message-parts for use by {@link getIntroMessage()} @param string $key @return array
[ "/", "*", "Define", "an", "array", "of", "message", "-", "parts", "for", "use", "by", "{", "@link", "getIntroMessage", "()", "}" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowEmbargoExpiryExtension.php#L387-L410
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowEmbargoExpiryExtension.php
WorkflowEmbargoExpiryExtension.getIntroMessage
public function getIntroMessage($key) { $msg = $this->getIntroMessageParts($key); $curr = Controller::curr(); $msg = $curr->customise($msg)->renderWith('Includes/embargoIntro'); return $msg; }
php
public function getIntroMessage($key) { $msg = $this->getIntroMessageParts($key); $curr = Controller::curr(); $msg = $curr->customise($msg)->renderWith('Includes/embargoIntro'); return $msg; }
[ "public", "function", "getIntroMessage", "(", "$", "key", ")", "{", "$", "msg", "=", "$", "this", "->", "getIntroMessageParts", "(", "$", "key", ")", ";", "$", "curr", "=", "Controller", "::", "curr", "(", ")", ";", "$", "msg", "=", "$", "curr", "-...
/* Display some messages to the user, a little more complex that a simple one-liner @param string $key @return string
[ "/", "*", "Display", "some", "messages", "to", "the", "user", "a", "little", "more", "complex", "that", "a", "simple", "one", "-", "liner" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowEmbargoExpiryExtension.php#L418-L424
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowEmbargoExpiryExtension.php
WorkflowEmbargoExpiryExtension.extendedRequiredFieldsEmbargoExpiry
public function extendedRequiredFieldsEmbargoExpiry($data) { $response = array( 'fieldName' => 'DesiredUnPublishDate[date]', 'fieldField' => null, 'fieldMsg' => null, 'fieldValid' => true ); if (isset($data['DesiredPublishDate'], $data['DesiredUnPublishDate'])) { $publish = DBDatetime::create()->setValue($data['DesiredPublishDate'])->getTimestamp(); $unpublish = DBDatetime::create()->setValue($data['DesiredUnPublishDate'])->getTimestamp(); // the times are the same if ($publish && $unpublish && $publish == $unpublish) { $response = array_merge($response, array( 'fieldMsg' => _t( 'WorkflowEmbargoExpiryExtension.INVALIDSAMEEMBARGOEXPIRY', 'The publish date and unpublish date cannot be the same.' ), 'fieldValid' => false )); } elseif ($publish && $unpublish && $publish > $unpublish) { $response = array_merge($response, array( 'fieldMsg' => _t( 'WorkflowEmbargoExpiryExtension.INVALIDEXPIRY', 'The unpublish date cannot be before the publish date.' ), 'fieldValid' => false )); } } return $response; }
php
public function extendedRequiredFieldsEmbargoExpiry($data) { $response = array( 'fieldName' => 'DesiredUnPublishDate[date]', 'fieldField' => null, 'fieldMsg' => null, 'fieldValid' => true ); if (isset($data['DesiredPublishDate'], $data['DesiredUnPublishDate'])) { $publish = DBDatetime::create()->setValue($data['DesiredPublishDate'])->getTimestamp(); $unpublish = DBDatetime::create()->setValue($data['DesiredUnPublishDate'])->getTimestamp(); // the times are the same if ($publish && $unpublish && $publish == $unpublish) { $response = array_merge($response, array( 'fieldMsg' => _t( 'WorkflowEmbargoExpiryExtension.INVALIDSAMEEMBARGOEXPIRY', 'The publish date and unpublish date cannot be the same.' ), 'fieldValid' => false )); } elseif ($publish && $unpublish && $publish > $unpublish) { $response = array_merge($response, array( 'fieldMsg' => _t( 'WorkflowEmbargoExpiryExtension.INVALIDEXPIRY', 'The unpublish date cannot be before the publish date.' ), 'fieldValid' => false )); } } return $response; }
[ "public", "function", "extendedRequiredFieldsEmbargoExpiry", "(", "$", "data", ")", "{", "$", "response", "=", "array", "(", "'fieldName'", "=>", "'DesiredUnPublishDate[date]'", ",", "'fieldField'", "=>", "null", ",", "'fieldMsg'", "=>", "null", ",", "'fieldValid'",...
This is called in the AWRequiredFields class, this validates whether an Embargo and Expiry are not equal and that Embargo is before Expiry, returning the appropriate message when it fails. @param $data @return array
[ "This", "is", "called", "in", "the", "AWRequiredFields", "class", "this", "validates", "whether", "an", "Embargo", "and", "Expiry", "are", "not", "equal", "and", "that", "Embargo", "is", "before", "Expiry", "returning", "the", "appropriate", "message", "when", ...
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowEmbargoExpiryExtension.php#L443-L477
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowEmbargoExpiryExtension.php
WorkflowEmbargoExpiryExtension.getUserDate
public function getUserDate($date) { $date = DBDatetime::create()->setValue($date); $member = Security::getCurrentUser(); return $date->FormatFromSettings($member); }
php
public function getUserDate($date) { $date = DBDatetime::create()->setValue($date); $member = Security::getCurrentUser(); return $date->FormatFromSettings($member); }
[ "public", "function", "getUserDate", "(", "$", "date", ")", "{", "$", "date", "=", "DBDatetime", "::", "create", "(", ")", "->", "setValue", "(", "$", "date", ")", ";", "$", "member", "=", "Security", "::", "getCurrentUser", "(", ")", ";", "return", ...
Format a date according to member/user preferences @param string $date @return string $date
[ "Format", "a", "date", "according", "to", "member", "/", "user", "preferences" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowEmbargoExpiryExtension.php#L485-L490
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowEmbargoExpiryExtension.php
WorkflowEmbargoExpiryExtension.setIsWorkflowInEffect
public function setIsWorkflowInEffect() { // if there is a workflow applied, we can't set the publishing date directly, only the 'desired' publishing date $effective = $this->getWorkflowService()->getDefinitionFor($this->owner); $this->isWorkflowInEffect = $effective ? true : false; }
php
public function setIsWorkflowInEffect() { // if there is a workflow applied, we can't set the publishing date directly, only the 'desired' publishing date $effective = $this->getWorkflowService()->getDefinitionFor($this->owner); $this->isWorkflowInEffect = $effective ? true : false; }
[ "public", "function", "setIsWorkflowInEffect", "(", ")", "{", "// if there is a workflow applied, we can't set the publishing date directly, only the 'desired' publishing date", "$", "effective", "=", "$", "this", "->", "getWorkflowService", "(", ")", "->", "getDefinitionFor", "(...
/* Sets property as boolean true|false if an effective workflow is found or not
[ "/", "*", "Sets", "property", "as", "boolean", "true|false", "if", "an", "effective", "workflow", "is", "found", "or", "not" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowEmbargoExpiryExtension.php#L495-L500
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowEmbargoExpiryExtension.php
WorkflowEmbargoExpiryExtension.getIsPublishScheduled
public function getIsPublishScheduled() { if (!$this->owner->PublishOnDate) { return false; } $now = DBDatetime::now()->getTimestamp(); $publish = $this->owner->dbObject('PublishOnDate')->getTimestamp(); return $now < $publish; }
php
public function getIsPublishScheduled() { if (!$this->owner->PublishOnDate) { return false; } $now = DBDatetime::now()->getTimestamp(); $publish = $this->owner->dbObject('PublishOnDate')->getTimestamp(); return $now < $publish; }
[ "public", "function", "getIsPublishScheduled", "(", ")", "{", "if", "(", "!", "$", "this", "->", "owner", "->", "PublishOnDate", ")", "{", "return", "false", ";", "}", "$", "now", "=", "DBDatetime", "::", "now", "(", ")", "->", "getTimestamp", "(", ")"...
Returns whether a publishing date has been set and is after the current date @return bool
[ "Returns", "whether", "a", "publishing", "date", "has", "been", "set", "and", "is", "after", "the", "current", "date" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowEmbargoExpiryExtension.php#L512-L521