sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function thenFail(\Exception $expected) {
try {
$this->commandBus->execute($this->commandToExecute);
$expectedType = get_class($expected);
throw new FailureException("Expected exception {$expectedType} but it was not thrown.");
} catch (\Exception $caught) {
$expectedType = get_class($expected);
$caughtType = get_class($caught);
if (
$caughtType != $expectedType ||
$caught->getMessage() != $expected->getMessage()
) {
throw new FailureException("Expected exception {$expectedType} {$expected->getMessage()} but caught {$caughtType} {$caught->getMessage()} instead.");
}
}
} | thenFail() is the method to use when you want to verify
that given the existing environment, the command will
result in an exception.
```php
$this->given(
// ...
)->when(
// ...
)->thenFail(
new SomethingWentWrong(...)
);
```
@param \Exception $expected
@throws FailureException | entailment |
private function eventsShouldExistInStore(DomainEvent ...$events) {
$expected = array_map(function (DomainEvent $event) {
return $this->serializer->serialize($event);
}, $events);
$existing = $this->eventStore->getEvents()->map(function(DomainEvent $event) {
return $this->serializer->serialize($event);
})->toArray();
$notFound = array_filter($expected, function($expectedEvent) use ($existing) {
return ! in_array($expectedEvent, $existing);
});
if (empty($notFound)) return;
throw new FailureException($this->missingEventExceptionMessage($notFound));
} | internal method that throws an exception should the expected
events not exist within the event store
@param DomainEvent ...$events
@throws FailureException | entailment |
public function parse($resource) {
$result = array();
$fieldcnt = mysql_num_fields($resource);
$fields_transform = array();
for($i=0;$i<$fieldcnt;$i++) {
$type = mysql_field_type($resource, $i);
if(isset(self::$fieldTypes[$type])) {
$fields_transform[mysql_field_name($resource, $i)] = self::$fieldTypes[$type];
}
}
while($row = mysql_fetch_object($resource)) {
foreach($fields_transform as $fieldname => $fieldtype) {
settype($row->$fieldname, $fieldtype);
}
$result[] = $row;
}
return $result;
} | Parse resource into array
@param resource $resource
@return array | entailment |
public function render()
{
// Set the request arguments as GET parameters
$_GET = $this->getRequestArguments();
try {
// Instantiate a TypoScript parser
$configurationManager = $this->objectManager->get(ConfigurationManager::class);
$typoScriptParser = GeneralUtility::makeInstance(TypoScriptParser::class);
list(, $viewConfig) = $typoScriptParser->getVal(
'plugin.tx_'.strtolower($this->extensionName).'.view',
$GLOBALS['TSFE']->tmpl->setup
);
list(, $layoutRootPaths) = $typoScriptParser->getVal('layoutRootPaths', $viewConfig);
list(, $templateRootPaths) = $typoScriptParser->getVal('templateRootPaths', $viewConfig);
list(, $partialRootPaths) = $typoScriptParser->getVal('partialRootPaths', $viewConfig);
/** @var \TYPO3\CMS\Fluid\View\StandaloneView $view */
$view = $this->objectManager->get(StandaloneView::class);
$view->getRenderingContext()->getVariableProvider()->add(
'settings',
$configurationManager->getConfiguration(
ConfigurationManager::CONFIGURATION_TYPE_SETTINGS,
$this->extensionName
)
);
$view->setLayoutRootPaths($layoutRootPaths);
$view->setTemplateRootPaths($templateRootPaths);
$view->setPartialRootPaths($partialRootPaths);
$view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName($this->template));
$view->getRequest()->setControllerExtensionName($this->extensionName);
$view->getRequest()->setOriginalRequestMappingResults($this->validationErrors);
$view->assignMultiple($this->parameters);
$view->assignMultiple($this->parameters);
$result = $this->beautify(
$this->section ? $view->renderSection($this->section, $this->parameters) : $view->render()
);
// In case of an error
} catch (\Exception $e) {
$result = '<pre class="error"><strong>'.$e->getMessage().'</strong>'.PHP_EOL
.$e->getTraceAsString().'</pre>';
}
return $result;
} | Render this component
@return string Rendered component (HTML) | entailment |
protected function loadJsonParameters()
{
$reflectionObject = new \ReflectionObject($this);
$componentFile = $reflectionObject->getFileName();
$parameterFile = dirname($componentFile).DIRECTORY_SEPARATOR.pathinfo(
$componentFile,
PATHINFO_FILENAME
).'.json';
if (is_readable($parameterFile)) {
$jsonParameters = file_get_contents($parameterFile);
if (strlen($jsonParameters)) {
$jsonParameterObj = @json_decode($jsonParameters);
if ($jsonParameterObj && is_object($jsonParameterObj)) {
foreach ($jsonParameterObj as $name => $value) {
$this->setParameter($name, $value);
}
}
}
}
} | Load parameters provided from an external JSON file | entailment |
protected function setParameter($param, $value)
{
$param = trim($param);
if (!strlen($param)) {
throw new \RuntimeException(sprintf('Invalid fluid template parameter "%s"', $param), 1481551574);
}
$this->parameters[$param] = $value;
} | Set a rendering parameter
@param string $param Parameter name
@param mixed $value Parameter value
@throws \RuntimeException If the parameter name is invalid | entailment |
protected function exportInternal()
{
// Read the linked TypoScript
if ($this->template !== null) {
$this->config = [
'template' => $this->template,
'section' => $this->section,
];
$templateFile = GeneralUtility::getFileAbsFileName($this->template);
if (!strlen($templateFile) || !is_file($templateFile)) {
throw new \RuntimeException(sprintf('Invalid template file "%s"', $templateFile), 1481552328);
}
$this->template = file_get_contents($templateFile);
}
return array_merge(
['parameters' => $this->parameters],
parent::exportInternal()
);
} | Return component specific properties
@return array Component specific properties | entailment |
protected function _setDbAdapter(Zend_Db_Adapter_Abstract $zendDb = null)
{
$this->_zendDb = $zendDb;
/**
* If no adapter is specified, fetch default database adapter.
*/
if(null === $this->_zendDb) {
require_once 'Zend/Db/Table/Abstract.php';
$this->_zendDb = Zend_Db_Table_Abstract::getDefaultAdapter();
if (null === $this->_zendDb) {
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('No database adapter present');
}
}
return $this;
} | _setDbAdapter() - set the database adapter to be used for quering
@param Zend_Db_Adapter_Abstract
@throws Zend_Auth_Adapter_Exception
@return Zend_Auth_Adapter_DbTable | entailment |
public function setAmbiguityIdentity($flag)
{
if (is_integer($flag)) {
$this->_ambiguityIdentity = (1 === $flag ? true : false);
} elseif (is_bool($flag)) {
$this->_ambiguityIdentity = $flag;
}
return $this;
} | setAmbiguityIdentity() - sets a flag for usage of identical identities
with unique credentials. It accepts integers (0, 1) or boolean (true,
false) parameters. Default is false.
@param int|bool $flag
@return Zend_Auth_Adapter_DbTable | entailment |
public function getDbSelect()
{
if ($this->_dbSelect == null) {
$this->_dbSelect = $this->_zendDb->select();
}
return $this->_dbSelect;
} | getDbSelect() - Return the preauthentication Db Select object for userland select query modification
@return Zend_Db_Select | entailment |
public function authenticate()
{
$this->_authenticateSetup();
$dbSelect = $this->_authenticateCreateSelect();
$resultIdentities = $this->_authenticateQuerySelect($dbSelect);
if ( ($authResult = $this->_authenticateValidateResultSet($resultIdentities)) instanceof Zend_Auth_Result) {
return $authResult;
}
if (true === $this->getAmbiguityIdentity()) {
$validIdentities = array ();
$zendAuthCredentialMatchColumn = $this->_zendDb->foldCase('zend_auth_credential_match');
foreach ($resultIdentities as $identity) {
if (1 === (int) $identity[$zendAuthCredentialMatchColumn]) {
$validIdentities[] = $identity;
}
}
$resultIdentities = $validIdentities;
}
$authResult = $this->_authenticateValidateResult(array_shift($resultIdentities));
return $authResult;
} | authenticate() - defined by Zend_Auth_Adapter_Interface. This method is called to
attempt an authentication. Previous to this call, this adapter would have already
been configured with all necessary information to successfully connect to a database
table and attempt to find a record matching the provided identity.
@throws Zend_Auth_Adapter_Exception if answering the authentication query is impossible
@return Zend_Auth_Result | entailment |
protected function _authenticateSetup()
{
$exception = null;
if ($this->_tableName == '') {
$exception = 'A table must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
} elseif ($this->_identityColumn == '') {
$exception = 'An identity column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
} elseif ($this->_credentialColumn == '') {
$exception = 'A credential column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
} elseif ($this->_identity == '') {
$exception = 'A value for the identity was not provided prior to authentication with Zend_Auth_Adapter_DbTable.';
} elseif ($this->_credential === null) {
$exception = 'A credential value was not provided prior to authentication with Zend_Auth_Adapter_DbTable.';
}
if (null !== $exception) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception($exception);
}
$this->_authenticateResultInfo = array(
'code' => Zend_Auth_Result::FAILURE,
'identity' => $this->_identity,
'messages' => array()
);
return true;
} | _authenticateSetup() - This method abstracts the steps involved with
making sure that this adapter was indeed setup properly with all
required pieces of information.
@throws Zend_Auth_Adapter_Exception - in the event that setup was not done properly
@return true | entailment |
protected function _authenticateCreateSelect()
{
// build credential expression
if (empty($this->_credentialTreatment) || (strpos($this->_credentialTreatment, '?') === false)) {
$this->_credentialTreatment = '?';
}
$credentialExpression = new Zend_Db_Expr(
'(CASE WHEN ' .
$this->_zendDb->quoteInto(
$this->_zendDb->quoteIdentifier($this->_credentialColumn, true)
. ' = ' . $this->_credentialTreatment, $this->_credential
)
. ' THEN 1 ELSE 0 END) AS '
. $this->_zendDb->quoteIdentifier(
$this->_zendDb->foldCase('zend_auth_credential_match')
)
);
// get select
$dbSelect = clone $this->getDbSelect();
$dbSelect->from($this->_tableName, array('*', $credentialExpression))
->where($this->_zendDb->quoteIdentifier($this->_identityColumn, true) . ' = ?', $this->_identity);
return $dbSelect;
} | _authenticateCreateSelect() - This method creates a Zend_Db_Select object that
is completely configured to be queried against the database.
@return Zend_Db_Select | entailment |
protected function _authenticateQuerySelect(Zend_Db_Select $dbSelect)
{
try {
if ($this->_zendDb->getFetchMode() != Zend_DB::FETCH_ASSOC) {
$origDbFetchMode = $this->_zendDb->getFetchMode();
$this->_zendDb->setFetchMode(Zend_DB::FETCH_ASSOC);
}
$resultIdentities = $this->_zendDb->fetchAll($dbSelect);
if (isset($origDbFetchMode)) {
$this->_zendDb->setFetchMode($origDbFetchMode);
unset($origDbFetchMode);
}
} catch (Exception $e) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('The supplied parameters to Zend_Auth_Adapter_DbTable failed to '
. 'produce a valid sql statement, please check table and column names '
. 'for validity.', 0, $e);
}
return $resultIdentities;
} | _authenticateQuerySelect() - This method accepts a Zend_Db_Select object and
performs a query against the database with that object.
@param Zend_Db_Select $dbSelect
@throws Zend_Auth_Adapter_Exception - when an invalid select
object is encountered
@return array | entailment |
protected function _authenticateValidateResult($resultIdentity)
{
$zendAuthCredentialMatchColumn = $this->_zendDb->foldCase('zend_auth_credential_match');
if ($resultIdentity[$zendAuthCredentialMatchColumn] != '1') {
$this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
$this->_authenticateResultInfo['messages'][] = 'Supplied credential is invalid.';
return $this->_authenticateCreateAuthResult();
}
unset($resultIdentity[$zendAuthCredentialMatchColumn]);
$this->_resultRow = $resultIdentity;
$this->_authenticateResultInfo['code'] = Zend_Auth_Result::SUCCESS;
$this->_authenticateResultInfo['messages'][] = 'Authentication successful.';
return $this->_authenticateCreateAuthResult();
} | _authenticateValidateResult() - This method attempts to validate that
the record in the resultset is indeed a record that matched the
identity provided to this adapter.
@param array $resultIdentity
@return Zend_Auth_Result | entailment |
public function addCertificatePair($private_key_file, $public_key_file, $type = Zend_InfoCard_Cipher::ENC_RSA_OAEP_MGF1P, $password = null)
{
return $this->_infoCard->addCertificatePair($private_key_file, $public_key_file, $type, $password);
} | Add a Certificate Pair to the list of certificates searched by the component
@param string $private_key_file The path to the private key file for the pair
@param string $public_key_file The path to the certificate / public key for the pair
@param string $type (optional) The URI for the type of key pair this is (default RSA with OAEP padding)
@param string $password (optional) The password for the private key file if necessary
@throws Zend_InfoCard_Exception
@return string A key ID representing this key pair in the component | entailment |
public function authenticate()
{
try {
$claims = $this->_infoCard->process($this->getXmlToken());
} catch(Exception $e) {
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE , null, array('Exception Thrown',
$e->getMessage(),
$e->getTraceAsString(),
serialize($e)));
}
if(!$claims->isValid()) {
switch($claims->getCode()) {
case Zend_infoCard_Claims::RESULT_PROCESSING_FAILURE:
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE,
$claims,
array(
'Processing Failure',
$claims->getErrorMsg()
)
);
break;
case Zend_InfoCard_Claims::RESULT_VALIDATION_FAILURE:
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
$claims,
array(
'Validation Failure',
$claims->getErrorMsg()
)
);
break;
default:
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE,
$claims,
array(
'Unknown Failure',
$claims->getErrorMsg()
)
);
break;
}
}
return new Zend_Auth_Result(
Zend_Auth_Result::SUCCESS,
$claims
);
} | Authenticates the XML token
@return Zend_Auth_Result The result of the authentication | entailment |
public function updateAction(ServerRequest $request, Response $response)
{
$script = $GLOBALS['TYPO3_CONF_VARS']['EXT']['extParams']['tw_componentlibrary']['script'];
$descriptorspec = array(
0 => array('pipe', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'a')
);
$process = proc_open($script, $descriptorspec, $pipes);
stream_get_contents($pipes[1]);
fclose($pipes[1]);
$status = proc_get_status($process);
// If an error occured
if ($status['exitcode']) {
return $response->withStatus(500);
}
return $response;
} | Update the fractal component library
@param ServerRequest $request
@param Response $response
@return bool | entailment |
public static function save($filename, Zend_Server_Interface $server)
{
if (!is_string($filename)
|| (!file_exists($filename) && !is_writable(dirname($filename))))
{
return false;
}
$methods = $server->getFunctions();
if ($methods instanceof Zend_Server_Definition) {
$definition = new Zend_Server_Definition();
foreach ($methods as $method) {
if (in_array($method->getName(), self::$_skipMethods)) {
continue;
}
$definition->addMethod($method);
}
$methods = $definition;
}
if (0 === @file_put_contents($filename, serialize($methods))) {
return false;
}
return true;
} | Cache a file containing the dispatch list.
Serializes the server definition stores the information
in $filename.
Returns false on any error (typically, inability to write to file), true
on success.
@param string $filename
@param Zend_Server_Interface $server
@return bool | entailment |
public static function get($filename, Zend_Server_Interface $server)
{
if (!is_string($filename)
|| !file_exists($filename)
|| !is_readable($filename))
{
return false;
}
if (false === ($dispatch = @file_get_contents($filename))) {
return false;
}
if (false === ($dispatchArray = @unserialize($dispatch))) {
return false;
}
$server->loadFunctions($dispatchArray);
return true;
} | Load server definition from a file
Unserializes a stored server definition from $filename. Returns false if
it fails in any way, true on success.
Useful to prevent needing to build the server definition on each
request. Sample usage:
<code>
if (!Zend_Server_Cache::get($filename, $server)) {
require_once 'Some/Service/Class.php';
require_once 'Another/Service/Class.php';
// Attach Some_Service_Class with namespace 'some'
$server->attach('Some_Service_Class', 'some');
// Attach Another_Service_Class with namespace 'another'
$server->attach('Another_Service_Class', 'another');
Zend_Server_Cache::save($filename, $server);
}
$response = $server->handle();
echo $response;
</code>
@param string $filename
@param Zend_Server_Interface $server
@return bool | entailment |
public static function delete($filename)
{
if (is_string($filename) && file_exists($filename)) {
unlink($filename);
return true;
}
return false;
} | Remove a cache file
@param string $filename
@return boolean | entailment |
public function requireTable() {
//Init the search engine
$searchEngine=Config::inst()->get('CodeBank', 'snippet_search_engine');
if($searchEngine && class_exists($searchEngine) && in_array('ICodeBankSearchEngine', class_implements($searchEngine))) {
$searchEngine::requireTable();
}else {
//Class is missing or invalid so fallback to the default
DefaultCodeBankSearchEngine::requireTable();
}
parent::requireTable();
} | Check the database schema and update it as necessary. | entailment |
public function getCMSFields() {
$fields=new FieldList(
new TabSet('Root',
new Tab('Main', _t('Snippet.MAIN', '_Main'),
DropdownField::create('LanguageID', _t('Snippet.LANGUAGE', '_Language'), SnippetLanguage::get()->where('"SnippetLanguage"."Hidden"=0 OR "SnippetLanguage"."ID"='.($this->LanguageID ? $this->LanguageID:0))->map('ID', 'Title'))->setEmptyString('---'),
new TextField('Title', _t('Snippet.TITLE', '_Title'), null, 300),
TextareaField::create('Description', _t('Snippet.DESCRIPTION', '_Description'))->setRows(5),
PackageSelectionField::create('PackageID', _t('Snippet.PACKAGE', '_Package'), SnippetPackage::get()->map('ID', 'Title'))->setEmptyString(_t('Snippet.NOT_IN_PACKAGE', '_Not Part of a Package')),
TextareaField::create('Text', _t('Snippet.CODE', '_Code'), $this->getSnippetText())->setRows(30)->addExtraClass('codeBankFullWidth')->addExtraClass('stacked'),
TextareaField::create('Tags', _t('Snippet.TAGS', '_Tags (comma separate)'))->setRows(2)
)
)
);
return $fields;
} | Gets fields used in the cms
@return {FieldList} Fields to be used | entailment |
protected function onBeforeWrite() {
parent::onBeforeWrite();
if($this->ID==0) {
$this->CreatorID=Member::currentUserID();
}else {
$this->LastEditorID=Member::currentUserID();
//If the language is changing reset the folder id
if($this->isChanged('LanguageID')) {
$this->FolderID=0;
}
}
} | Sets the creator id for new snippets and sets the last editor id for existing snippets | entailment |
protected function onAfterWrite() {
parent::onAfterWrite();
//Write the snippet version record
if(!empty($this->Text)) {
$version=new SnippetVersion();
$version->Text=$this->Text;
$version->ParentID=$this->ID;
$version->write();
}
} | Creates the snippet version record after writing | entailment |
public function equals(self $that): bool
{
if (get_class($this) !== get_class($that)) {
throw new CannotCompareDifferentIds;
}
return $this->id === $that->id;
} | compare two Id instances for equality
Ids are considered equal if they are of the same
type and contain the same underlying string
representations
@param self $that
@return bool
@throws CannotCompareDifferentIds | entailment |
protected function onBeforeDelete() {
parent::onBeforeDelete();
//Remove all Snippets from this folder
DB::query('UPDATE "Snippet" SET "FolderID"='.$this->ParentID.' WHERE "FolderID"='.$this->ID);
//Remove all Snippet Folders from this folder
DB::query('UPDATE "SnippetFolder" SET "ParentID"='.$this->ParentID.' WHERE "ParentID"='.$this->ID);
} | Removes all snippets from the folder before deleting | entailment |
public function positiveMatch(string $name, $subject, array $arguments): ?\PhpSpec\Wrapper\DelayedCall
{
$argumentCount = count($arguments);
if ($argumentCount == 1) {
$this->compare($subject, $arguments[0]);
} else {
for ($i = 0; $i < $argumentCount; $i++) {
$this->compare($subject[0], $arguments[0]);
}
}
return null;
} | Evaluates positive match.
@param string $name
@param mixed $subject
@param array $arguments | entailment |
public function negativeMatch(string $name, $subject, array $arguments): ?\PhpSpec\Wrapper\DelayedCall
{
if ($subject->equals($arguments[0])) {
throw new FailureException('<label>' . get_class($subject) . "</label> <value>{$subject->toString()}</value> should not equal <value>{$arguments[0]->toString()}</value> but does.");
}
} | Evaluates negative match.
@param string $name
@param mixed $subject
@param array $arguments | entailment |
public function authenticate()
{
if (empty($this->_username) ||
empty($this->_password)) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception('Username/password should be set');
}
if(!isset($this->_users[$this->_username])) {
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND,
null,
array('Username not found')
);
}
$user = $this->_users[$this->_username];
if($user["password"] != $this->_password) {
return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
null,
array('Authentication failed')
);
}
$id = new stdClass();
$id->role = $user["role"];
$id->name = $this->_username;
return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $id);
} | Perform authentication
@throws Zend_Auth_Adapter_Exception
@return Zend_Auth_Result
@see Zend_Auth_Adapter_Interface#authenticate() | entailment |
public function setWebPath()
{
$folder_array = explode(self::DS, $this->getUploadPath());
$this->web_path = array_pop($folder_array);
} | Set the correct web path | entailment |
public function setDirPaths($dir_path)
{
if (is_null($dir_path)) {
$this->setDir($this->getUploadPath());
$this->setDirPath("");
} else {
$this->setDirPath($this->DirTrim($dir_path));
$this->setDir($this->getUploadPath() . self::DS . $dir_path);
}
$path_valid = $this->checkPath($this->getDir());
if (!$path_valid) {
$this->setDir($this->getUploadPath());
}
} | Set the dir paths
@param null|string $dir_path | entailment |
public function DirTrim($path, $file = null, $rTrim = false)
{
if ($rTrim) {
$result = rtrim($path, self::DS);
} else {
$result = trim($path, self::DS);
}
if (!is_null($file)) {
$file_result = trim($file, self::DS);
} else {
$file_result = $file;
}
if (!is_null($file_result)) {
$result = $result . self::DS . $file_result;
}
return $result;
} | Trim the directory separators from the file(path)
@param string $path
@param string $file
@param bool $rTrim
@return string | entailment |
public function checkPath($path = null)
{
if (is_null($path)) {
$path = $this->getDir();
}
$real_path = realpath($path);
if (!$real_path) {
$real_path = realpath(dirname($path));
}
$upload_path = realpath($this->getUploadPath());
if (strcasecmp($real_path, $upload_path) > 0) {
return true;
} else {
throw new \Exception("Directory is not in the upload path", 403);
}
} | Check if the path is in the upload directory
@param string $path default is the file dir
@throws \Exception when directory is not in the upload path
@return bool | entailment |
public function resolveRequest(Request $request, $action = null)
{
$this->setDirPath($request->get('dir_path'));
$this->setCurrentFile($this->getPath($this->getDirPath(), $request->get('filename'), true));
if ($action === self::FILE_RENAME && !$this->getCurrentFile()->isDir()) {
$extension = $this->getCurrentFile()->getExtension();
$target_file = $request->get('target_file') . "." . $extension;
} elseif ($action === self::FILE_PASTE) {
$sources = $this->container->get('session')->get('copy');
$this->setCurrentFile($sources['source_dir'] . FileManager::DS . $sources['source_file']);
$target_file = $request->get('target_file') . FileManager::DS . $sources['source_file'];
} else {
$target_file = $request->get('target_file');
}
if (isset($target_file)) {
$this->setTargetFile($target_file);
}
} | Set the required request parameters to the object
@param Request $request
@param int|null $action | entailment |
public function getPath($dir_path = null, $filename = null, $full_path = false)
{
if ($full_path) {
$path = $this->upload_path;
} else {
$path = $this->web_path;
}
if (!is_null($dir_path)) {
$path = self::DS . $this->DirTrim($path, $dir_path);
}
if (!is_null($filename)) {
$path = self::DS . $this->DirTrim($path, $filename);
}
return $path;
} | Get the path of the file
@param null|string $dir_path
@param null|string $filename
@param bool $full_path
@return string | entailment |
public function extractZip()
{
$this->event(YouweFileManagerEvents::BEFORE_FILE_EXTRACTED);
$this->getDriver()->extractZip($this->getCurrentFile());
$this->event(YouweFileManagerEvents::AFTER_FILE_EXTRACTED);
} | Extract the zip | entailment |
public function pasteFile($type)
{
$this->event(YouweFileManagerEvents::BEFORE_FILE_PASTED);
$this->resolveImage();
$this->getDriver()->pasteFile($this->getCurrentFile(), $type);
$this->event(YouweFileManagerEvents::AFTER_FILE_PASTED);
} | Paste the file
@param string $type | entailment |
public function resolveImage()
{
if ($this->FilterImages() && $this->getCurrentFile()->isImage()) {
try {
$imageCacheManager = $this->getCacheManager();
} catch (\Exception $e) {
$exception = 'Cannot resolve the image. Please make sure that LiipImagineBundle is installed';
if (!$this->isFullException() || is_null($e)) {
Throw new \Exception($exception);
} else {
throw new \Exception($exception . ": " . $e->getMessage());
}
}
$imageCacheManager->remove($this->getCurrentFile()->getWebPath(), $this->getFilter());
}
} | Remove the image of the current file
@throws \Exception if Liip Imagine Bundle is not installed | entailment |
public function moveFile()
{
$this->event(YouweFileManagerEvents::BEFORE_FILE_MOVED);
$target_full_path = $this->getTargetFile()->getFilepath(true);
$this->getDriver()->moveFile($this->getCurrentFile(), $target_full_path);
$this->resolveImage();
$this->getCurrentFile()->updateFilepath($target_full_path);
$this->event(YouweFileManagerEvents::AFTER_FILE_MOVED);
} | Move the file | entailment |
public function deleteFile()
{
$this->event(YouweFileManagerEvents::BEFORE_FILE_DELETED);
$this->resolveImage();
$this->getDriver()->deleteFile($this->getCurrentFile());
$this->event(YouweFileManagerEvents::AFTER_FILE_DELETED);
} | Delete the file | entailment |
public function renameFile()
{
$this->event(YouweFileManagerEvents::BEFORE_FILE_RENAMED);
$target_full_path = $this->getTargetFile()->getFilepath(true);
$this->getDriver()->renameFile($this->getCurrentFile(), $target_full_path);
$this->resolveImage();
$this->getCurrentFile()->updateFilepath($target_full_path);
$this->event(YouweFileManagerEvents::AFTER_FILE_RENAMED);
} | Rename the file | entailment |
public function newDirectory()
{
$target_full_path = $this->getTargetFile()->getFilepath(true);
$this->event(YouweFileManagerEvents::BEFORE_FILE_DIR_CREATED);
$this->getDriver()->makeDir($target_full_path);
$this->getCurrentFile()->updateFilepath($target_full_path);
$this->event(YouweFileManagerEvents::AFTER_FILE_DIR_CREATED);
} | Create a new directory | entailment |
public function throwError($string, $code = 500, $e = null)
{
if (!$this->isFullException() || is_null($e)) {
throw new \Exception($string, $code);
} else {
throw new \Exception($string . ": " . $e->getMessage(), $code);
}
} | Throw the error based on the full exception config
@param string $string the displayed exception
@param int $code the displayed code
@param null|\Exception $e the actual exception
@throws \Exception the exception that is given | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$default_mimetypes = array(
'image/png',
'image/jpg',
'image/jpeg',
'image/gif',
'application/pdf',
'application/ogg',
'video/mp4',
'application/zip',
'multipart/x-zip',
'application/rar',
'application/x-rar-compressed',
'application/x-zip-compressed',
'application/tar',
'application/x-tar',
'text/plain',
'text/x-asm',
'application/octet-stream'
);
$rootNode = $treeBuilder->root('youwe_file_manager');
$rootNode
->children()
->arrayNode('mime_allowed')
->prototype('scalar')->defaultValue($default_mimetypes)->cannotBeEmpty()->end()
->end()
->booleanNode('full_exception')
->defaultFalse()
->end()
->scalarNode('upload_path')
->defaultValue('%kernel.root_dir%/../web/uploads')->cannotBeEmpty()
->end()
->arrayNode('theme')
->children()
->scalarNode('css')
->defaultValue("/bundles/youwefilemanager/css/simple/default.css")->cannotBeEmpty()
->end()
->scalarNode('template')
->defaultValue('YouweFileManagerBundle:FileManager:file_manager.html.twig')->cannotBeEmpty()
->end()
->end()
->addDefaultsIfNotSet()
->end()
->scalarNode('filter_images')
->defaultFalse()
->end()
->scalarNode('usage_class')
->defaultFalse()
->end()
->end();
return $treeBuilder;
} | {@inheritDoc} | entailment |
public function FieldHolder($properties=array()) {
Requirements::css(CB_DIR.'/css/PackageSelectionField.css');
Requirements::javascript(CB_DIR.'/javascript/PackageSelectionField.js');
return parent::FieldHolder($properties);
} | Returns a "field holder" for this field - used by templates.
@param {array} $properties Key value pairs of template variables
@return {string} | entailment |
public function AddPackageForm() {
$sng=singleton('SnippetPackage');
$fields=new FieldList(
new TabSet('Root',
new Tab('Main', _t('PackageSelectionField.MAIN', '_Main'),
new TextField('Title', _t('PackageSelectionField.TITLE', '_Title'), null, 300)
)
)
);
$actions=new FieldList(
FormAction::create('doAddPackage', _t('PackageSelectionField.CREATE', '_Create'))
->addExtraClass('ss-ui-action-constructive')
->setAttribute('data-icon', 'accept')
->setUseButtonTag(true)
);
$validator=new RequiredFields(
'Title'
);
return Form::create($this, 'AddPackageForm', $fields, $actions, $validator)
->addExtraClass('member-profile-form')
->setFormAction($this->Link('AddPackageForm'));
} | Generates the form for adding packages
@return {Form} Form to be used | entailment |
public function doAddPackage($data, Form $form) {
$record=new SnippetPackage();
if($record->canEdit()) {
$form->saveInto($record);
$record->write();
Requirements::customScript("window.parent.jQuery('#".$this->getName()."').entwine('ss').handleSuccessResult(".$record->ID.");");
return $this->renderWith('CMSDialog', array('Form'=>''));
}
return Controller::curr()->redirectBack();
} | Handles adding of the package
@param {array} $data Submitted data
@param {Form} $form Submitting form
@return {mixed} | entailment |
public function readTypeMarker($typeMarker = null)
{
if(null === $typeMarker) {
$typeMarker = $this->_stream->readByte();
}
switch($typeMarker) {
case Zend_Amf_Constants::AMF3_UNDEFINED:
return null;
case Zend_Amf_Constants::AMF3_NULL:
return null;
case Zend_Amf_Constants::AMF3_BOOLEAN_FALSE:
return false;
case Zend_Amf_Constants::AMF3_BOOLEAN_TRUE:
return true;
case Zend_Amf_Constants::AMF3_INTEGER:
return $this->readInteger();
case Zend_Amf_Constants::AMF3_NUMBER:
return $this->_stream->readDouble();
case Zend_Amf_Constants::AMF3_STRING:
return $this->readString();
case Zend_Amf_Constants::AMF3_DATE:
return $this->readDate();
case Zend_Amf_Constants::AMF3_ARRAY:
return $this->readArray();
case Zend_Amf_Constants::AMF3_OBJECT:
return $this->readObject();
case Zend_Amf_Constants::AMF3_XML:
case Zend_Amf_Constants::AMF3_XMLSTRING:
return $this->readXmlString();
case Zend_Amf_Constants::AMF3_BYTEARRAY:
return $this->readString();
default:
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unsupported type marker: ' . $typeMarker);
}
} | Read AMF markers and dispatch for deserialization
Checks for AMF marker types and calls the appropriate methods
for deserializing those marker types. markers are the data type of
the following value.
@param integer $typeMarker
@return mixed Whatever the corresponding PHP data type is
@throws Zend_Amf_Exception for unidentified marker type | entailment |
public function readInteger()
{
$count = 1;
$intReference = $this->_stream->readByte();
$result = 0;
while ((($intReference & 0x80) != 0) && $count < 4) {
$result <<= 7;
$result |= ($intReference & 0x7f);
$intReference = $this->_stream->readByte();
$count++;
}
if ($count < 4) {
$result <<= 7;
$result |= $intReference;
} else {
// Use all 8 bits from the 4th byte
$result <<= 8;
$result |= $intReference;
// Check if the integer should be negative
if (($result & 0x10000000) != 0) {
//and extend the sign bit
$result |= ~0xFFFFFFF;
}
}
return $result;
} | Read and deserialize an integer
AMF 3 represents smaller integers with fewer bytes using the most
significant bit of each byte. The worst case uses 32-bits
to represent a 29-bit number, which is what we would have
done with no compression.
- 0x00000000 - 0x0000007F : 0xxxxxxx
- 0x00000080 - 0x00003FFF : 1xxxxxxx 0xxxxxxx
- 0x00004000 - 0x001FFFFF : 1xxxxxxx 1xxxxxxx 0xxxxxxx
- 0x00200000 - 0x3FFFFFFF : 1xxxxxxx 1xxxxxxx 1xxxxxxx xxxxxxxx
- 0x40000000 - 0xFFFFFFFF : throw range exception
0x04 -> integer type code, followed by up to 4 bytes of data.
Parsing integers on OSFlash for the AMF3 integer data format:
@link http://osflash.org/amf3/parsing_integers
@return int|float | entailment |
public function readString()
{
$stringReference = $this->readInteger();
//Check if this is a reference string
if (($stringReference & 0x01) == 0) {
// reference string
$stringReference = $stringReference >> 1;
if ($stringReference >= count($this->_referenceStrings)) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Undefined string reference: ' . $stringReference);
}
// reference string found
return $this->_referenceStrings[$stringReference];
}
$length = $stringReference >> 1;
if ($length) {
$string = $this->_stream->readBytes($length);
$this->_referenceStrings[] = $string;
} else {
$string = "";
}
return $string;
} | Read and deserialize a string
Strings can be sent as a reference to a previously
occurring String by using an index to the implicit string reference table.
Strings are encoding using UTF-8 - however the header may either
describe a string literal or a string reference.
- string = 0x06 string-data
- string-data = integer-data [ modified-utf-8 ]
- modified-utf-8 = *OCTET
@return String | entailment |
public function readDate()
{
$dateReference = $this->readInteger();
if (($dateReference & 0x01) == 0) {
$dateReference = $dateReference >> 1;
if ($dateReference>=count($this->_referenceObjects)) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Undefined date reference: ' . $dateReference);
}
return $this->_referenceObjects[$dateReference];
}
$timestamp = floor($this->_stream->readDouble() / 1000);
require_once 'Zend/Date.php';
$dateTime = new Zend_Date($timestamp);
$this->_referenceObjects[] = $dateTime;
return $dateTime;
} | Read and deserialize a date
Data is the number of milliseconds elapsed since the epoch
of midnight, 1st Jan 1970 in the UTC time zone.
Local time zone information is not sent to flash.
- date = 0x08 integer-data [ number-data ]
@return Zend_Date | entailment |
public function readArray()
{
$arrayReference = $this->readInteger();
if (($arrayReference & 0x01)==0){
$arrayReference = $arrayReference >> 1;
if ($arrayReference>=count($this->_referenceObjects)) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unknow array reference: ' . $arrayReference);
}
return $this->_referenceObjects[$arrayReference];
}
// Create a holder for the array in the reference list
$data = array();
$this->_referenceObjects[] =& $data;
$key = $this->readString();
// Iterating for string based keys.
while ($key != '') {
$data[$key] = $this->readTypeMarker();
$key = $this->readString();
}
$arrayReference = $arrayReference >>1;
//We have a dense array
for ($i=0; $i < $arrayReference; $i++) {
$data[] = $this->readTypeMarker();
}
return $data;
} | Read amf array to PHP array
- array = 0x09 integer-data ( [ 1OCTET *amf3-data ] | [OCTET *amf3-data 1] | [ OCTET *amf-data ] )
@return array | entailment |
public function readObject()
{
$traitsInfo = $this->readInteger();
$storedObject = ($traitsInfo & 0x01)==0;
$traitsInfo = $traitsInfo >> 1;
// Check if the Object is in the stored Objects reference table
if ($storedObject) {
$ref = $traitsInfo;
if (!isset($this->_referenceObjects[$ref])) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unknown Object reference: ' . $ref);
}
$returnObject = $this->_referenceObjects[$ref];
} else {
// Check if the Object is in the stored Definitions reference table
$storedClass = ($traitsInfo & 0x01) == 0;
$traitsInfo = $traitsInfo >> 1;
if ($storedClass) {
$ref = $traitsInfo;
if (!isset($this->_referenceDefinitions[$ref])) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Unknows Definition reference: '. $ref);
}
// Populate the reference attributes
$className = $this->_referenceDefinitions[$ref]['className'];
$encoding = $this->_referenceDefinitions[$ref]['encoding'];
$propertyNames = $this->_referenceDefinitions[$ref]['propertyNames'];
} else {
// The class was not in the reference tables. Start reading rawdata to build traits.
// Create a traits table. Zend_Amf_Value_TraitsInfo would be ideal
$className = $this->readString();
$encoding = $traitsInfo & 0x03;
$propertyNames = array();
$traitsInfo = $traitsInfo >> 2;
}
// We now have the object traits defined in variables. Time to go to work:
if (!$className) {
// No class name generic object
$returnObject = new stdClass();
} else {
// Defined object
// Typed object lookup against registered classname maps
if ($loader = Zend_Amf_Parse_TypeLoader::loadType($className)) {
$returnObject = new $loader();
} else {
//user defined typed object
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Typed object not found: '. $className . ' ');
}
}
// Add the Object to the reference table
$this->_referenceObjects[] = $returnObject;
$properties = array(); // clear value
// Check encoding types for additional processing.
switch ($encoding) {
case (Zend_Amf_Constants::ET_EXTERNAL):
// Externalizable object such as {ArrayCollection} and {ObjectProxy}
if (!$storedClass) {
$this->_referenceDefinitions[] = array(
'className' => $className,
'encoding' => $encoding,
'propertyNames' => $propertyNames,
);
}
$returnObject->externalizedData = $this->readTypeMarker();
break;
case (Zend_Amf_Constants::ET_DYNAMIC):
// used for Name-value encoding
if (!$storedClass) {
$this->_referenceDefinitions[] = array(
'className' => $className,
'encoding' => $encoding,
'propertyNames' => $propertyNames,
);
}
// not a reference object read name value properties from byte stream
do {
$property = $this->readString();
if ($property != "") {
$propertyNames[] = $property;
$properties[$property] = $this->readTypeMarker();
}
} while ($property !="");
break;
default:
// basic property list object.
if (!$storedClass) {
$count = $traitsInfo; // Number of properties in the list
for($i=0; $i< $count; $i++) {
$propertyNames[] = $this->readString();
}
// Add a reference to the class.
$this->_referenceDefinitions[] = array(
'className' => $className,
'encoding' => $encoding,
'propertyNames' => $propertyNames,
);
}
foreach ($propertyNames as $property) {
$properties[$property] = $this->readTypeMarker();
}
break;
}
// Add properties back to the return object.
foreach($properties as $key=>$value) {
if($key) {
$returnObject->$key = $value;
}
}
}
if ($returnObject instanceof Zend_Amf_Value_Messaging_ArrayCollection) {
if (isset($returnObject->externalizedData)) {
$returnObject = $returnObject->externalizedData;
} else {
$returnObject = get_object_vars($returnObject);
}
}
return $returnObject;
} | Read an object from the AMF stream and convert it into a PHP object
@todo Rather than using an array of traitsInfo create Zend_Amf_Value_TraitsInfo
@return object|array | entailment |
public function readXmlString()
{
$xmlReference = $this->readInteger();
$length = $xmlReference >> 1;
$string = $this->_stream->readBytes($length);
return simplexml_load_string($string);
} | Convert XML to SimpleXml
If user wants DomDocument they can use dom_import_simplexml
@return SimpleXml Object | entailment |
public function guessMimeType($filepath)
{
$magic_file = $this->getFileManager()->getMagicFile();
$mimetype = finfo_file(finfo_open(FILEINFO_MIME_TYPE, $magic_file), $filepath);
$extension = pathinfo($filepath, PATHINFO_EXTENSION);
$match_extension = $this->matchMimetypeExtension($mimetype, $extension);
//Use default mimetype guesser if it is not found
if ($mimetype == "application/octet-stream" || !$match_extension) {
$mimetype = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $filepath);
}
$this->setMimetype($mimetype);
if (isset(self::$humanReadableTypes[$mimetype])) {
$this->setReadableType(self::$humanReadableTypes[$mimetype]);
} else {
$this->setReadableType("Undefined");
}
$this->setFileclass($mimetype);
} | Try to guess the mimetypes first with a custom magic file.
This fix the problems with wrong mime type detection.
@param string $filepath
@return mixed | entailment |
public function matchMimetypeExtension($mimetype, $extension)
{
$mime_extensions = self::$mimetypes_extensions;
if (isset($mime_extensions[$extension]) && $mime_extensions[$extension] == $mimetype) {
return true;
}
return false;
} | Check if the mimetype match with the extension
@param string $mimetype
@param string $extension
@return bool | entailment |
public function setFileclass($mimetype)
{
switch ($mimetype) {
case 'directory':
$fileclass = "dir";
$this->is_dir = true;
break;
case 'application/pdf':
$fileclass = "pdf";
break;
case 'application/zip':
case 'application/x-gzip':
case 'application/x-bzip2':
case 'application/x-zip':
case 'application/x-rar':
case 'application/x-tar':
$fileclass = "zip";
break;
case 'video/mp4':
case 'video/ogg':
case 'video/mpeg':
case 'application/ogg':
$fileclass = "video";
$this->is_video = true;
break;
case 'audio/ogg':
case 'audio/mpeg':
$fileclass = "audio";
$this->is_audio = true;
break;
case 'image/jpeg':
case 'image/jpg':
case 'image/gif':
case 'image/png':
$fileclass = "image";
$this->is_image = true;
break;
case 'image/svg+xml':
$fileclass = "svg";
$this->is_image = true;
break;
case 'text/x-shellscript':
$fileclass = 'shellscript';
break;
case 'text/html':
case 'text/javascript':
case 'text/css':
case 'text/xml':
case 'application/javascript':
case 'application/xml':
$fileclass = "code";
break;
case 'text/x-php':
$fileclass = "php";
break;
case 'application/x-shockwave-flash':
$fileclass = 'swf';
break;
default:
$fileclass = "default";
break;
}
$this->fileclass = $fileclass;
} | Set the file class
Javascript uses the fileclass to check which actions the file should have.
CSS uses the file class to check which icon belongs to the file.
@param string $mimetype | entailment |
public function getFilepath($include_filename = false)
{
$filepath = $this->filepath;
if ($include_filename) {
$filepath .= FileManager::DS . $this->getFilename();
}
return $filepath;
} | Returns the full path to the file
@param bool $include_filename
@return string | entailment |
public function setUsages(FileManager $file_manager)
{
$usages = array();
$usage_class = $file_manager->getUsagesClass();
if ($usage_class != false) {
/** @var mixed $usage_object */
$usage_object = new $usage_class;
$usages_result = $usage_object->returnUsages($this->getFilepath(true));
if (!empty($usages_result)) {
$usages = $usages_result;
}
}
$this->usages = count($usages);
} | Set the locations where the file is used in an array.
This function requires a class that is set in the config with the function returnUsages.
@param FileManager $file_manager | entailment |
public function getWebPath($trim = false)
{
if ($trim) {
return trim($this->web_path, FileManager::DS);
} else {
return $this->web_path;
}
} | Returns the web path of the file
@param bool $trim
@return string | entailment |
public function manipulateCacheActions(&$cacheActions, &$optionValues)
{
$extensionConfiguration = $GLOBALS['TYPO3_CONF_VARS']['EXT']['extParams']['tw_componentlibrary'];
if ($GLOBALS['BE_USER']->isAdmin() && !empty($extensionConfiguration['componentlibrary'])) {
$componentLibrary = $extensionConfiguration['componentlibrary'];
$cacheActions[] = array(
'id' => $componentLibrary,
'title' => 'LLL:EXT:tw_componentlibrary/Resources/Private/Language/locallang_core.xlf:cache.'.$componentLibrary.'.title',
'description' => 'LLL:EXT:tw_componentlibrary/Resources/Private/Language/locallang_core.xlf:cache.'.$componentLibrary.'.description',
'href' => '/typo3/index.php?route=%2F'.$componentLibrary,
'iconIdentifier' => 'tx_twcomponentlibrary_cache'
);
}
} | Add an entry to the CacheMenuItems array
@param array $cacheActions Array of CacheMenuItems
@param array $optionValues Array of AccessConfigurations-identifiers (typically used by userTS with
options.clearCache.identifier) | entailment |
public function get(string $name): Projection {
return $this->projections->filter(function (Projection $projection) use ($name) {
return $projection->name() === $name;
})->first();
} | retrieve a projection based on its string name
@param string $name
@return Projection | entailment |
public function handle(DomainEvent $event) : void {
$this->projections->each(function (Projection $projection) use ($event) {
$projection->handle($event);
});
} | receive a domain event and hand it off to every projection
@param DomainEvent $event | entailment |
public function createFileManager(array $parameters, $driver, $dir_path = null)
{
$file_manager = new FileManager($parameters, $driver, $this->container);
$this->file_manager = $file_manager;
$file_manager->setDirPaths($dir_path);
$this->setDisplayType();
return $file_manager;
} | Create the file manager object
@param array $parameters
@param string $dir_path
@param mixed $driver
@return FileManager | entailment |
public function getFilePath(FileManager $file_manager)
{
$current_file = $file_manager->getCurrentFile();
$target_file = $file_manager->getTargetFile();
if (($current_file->getFilename() == "" && !is_null($target_file->getFilename()))) {
throw new \Exception("Filename cannot be empty when there is a target file");
}
$root = $file_manager->getUploadPath();
$dir_path = $file_manager->getDirPath();
if (empty($dir_path)) {
$dir = $root;
} else {
if (strcasecmp("../", $dir_path) >= 1) {
throw new \Exception("Invalid filepath or filename");
}
$dir = $this->getFileManager()->DirTrim($root, $dir_path, true);
}
try {
$file_manager->checkPath($dir);
if (!is_null($target_file)) {
$file_manager->checkPath($target_file->getFilepath(true));
}
} catch (\Exception $e) {
throw new \Exception($e->getMessage(), $e->getCode());
}
return $dir;
} | Get and check the current file path
@param FileManager $file_manager
@throws \Exception when the file name is empty while there is a target file or when the file is invalid
@return bool|string | entailment |
public function checkToken($request_token)
{
$token_manager = $this->container->get('security.csrf.token_manager');
$token = new CsrfToken('file_manager', $request_token);
$valid = $token_manager->isTokenValid($token);
if (!$valid) {
throw new InvalidCsrfTokenException();
}
} | Check if the form token is valid
@param string $request_token
@throws InvalidCsrfTokenException when the token is not valid | entailment |
public function handleUploadFiles($files)
{
$dir = $this->getFileManager()->getDir();
/** @var FileManagerDriver $driver */
$driver = $this->container->get('youwe.file_manager.driver');
$this->getFileManager()->event(YouweFileManagerEvents::BEFORE_FILE_UPLOADED);
/** @var UploadedFile $file */
foreach ($files as $file) {
$extension = $file->guessExtension();
if (!$extension) {
$extension = 'bin';
}
if (in_array($file->getClientMimeType(), $this->getFileManager()->getExtensionsAllowed())) {
$driver->handleUploadedFiles($file, $extension, $dir);
} else {
$this->getFileManager()->throwError("Mimetype is not allowed", 500);
}
}
$this->getFileManager()->event(YouweFileManagerEvents::AFTER_FILE_UPLOADED);
} | Handle the uploaded file(s)
@param array $files
@return bool | entailment |
public function getRenderOptions(Form $form)
{
$file_manager = $this->getFileManager();
$dir_files = scandir($file_manager->getDir());
$root_dirs = scandir($file_manager->getUploadPath());
$is_popup = $this->container->get('request')->get('popup') ? true : false;
$options['files'] = $this->getFiles($dir_files);
$options['file_body_display'] = $file_manager->getDisplayType();
$options['dirs'] = $this->getDirectoryTree($root_dirs, $file_manager->getUploadPath(), "");
$options['isPopup'] = $is_popup;
$options['copy_file'] = $this->container->get('session')->get('copy');
$options['form'] = $form->createView();
$options['copy_type'] = FileManager::FILE_COPY;
$options['cut_type'] = FileManager::FILE_CUT;
$options['root_folder'] = $file_manager->getPath();
$options['current_path'] = $file_manager->getDirPath();
$options['upload_allow'] = $file_manager->getExtensionsAllowed();
$options['usages'] = $file_manager->getUsagesClass();
$options['theme_css'] = $file_manager->getThemeCss();
return $options;
} | Returns an array with all the rendered options
Current options are:
files - All files in the current directory
file_body_display - The display type of the filemanager (block or list)
dirs - The directories in the upload directory
isPopup - Boolean that is true when the window is a popup
copy_file - The copied file that is in the session
form - The form object
root_folder - The root directory path
current_path - The current path
upload_allow - Array with all allowed mimetypes
usages - The usages class
theme_css - The css filepath
@param Form $form
@return array | entailment |
public function getFiles(array $dir_files, $files = array())
{
foreach ($dir_files as $file) {
$filepath = $this->getFileManager()->DirTrim($this->getFileManager()->getDir(), $file, true);
//Only show non-hidden files
if ($file[0] != ".") {
$files[] = new FileInfo($filepath, $this->getFileManager());
}
}
return $files;
} | Returns all files in the current directory
@param array $dir_files
@param array $files
@return array | entailment |
public function setDisplayType()
{
$file_manager = $this->getFileManager();
/** @var Session $session */
$session = $this->container->get('session');
$display_type = $session->get(self::DISPLAY_TYPE_SESSION);
if ($this->container->get('request')->get('display_type') != null) {
$display_type = $this->container->get('request')->get('display_type');
$session->set(self::DISPLAY_TYPE_SESSION, $display_type);
} else {
if (is_null($display_type)) {
$display_type = self::DISPLAY_TYPE_BLOCK;
}
}
$file_body_display = $display_type !== null ? $display_type : self::DISPLAY_TYPE_BLOCK;
$file_manager->setDisplayType($file_body_display);
} | Set the display type
@return string | entailment |
public function getDirectoryTree($dir_files, $dir, $dir_path, $dirs = array())
{
foreach ($dir_files as $file) {
$filepath = $this->getFileManager()->DirTrim($dir, $file, true);
if ($file[0] != ".") {
if (is_dir($filepath)) {
$new_dir_files = scandir($filepath);
$new_dir_path = $this->getFileManager()->DirTrim($dir_path, $file, true);
$new_dir = $this->getFileManager()->getUploadPath() . FileManager::DS . $this->getFileManager()->DirTrim($new_dir_path);
$fileType = "directory";
$tmp_array = array(
"mimetype" => $fileType,
"name" => $file,
"path" => $this->getFileManager()->DirTrim($new_dir_path),
"tree" => $this->getDirectoryTree($new_dir_files, $new_dir, $new_dir_path, array()),
);
$dirs[] = $tmp_array;
}
}
}
return $dirs;
} | Returns the directory tree of the given path. This will loop itself until it has all directories
@param array $dir_files files in the directory
@param string $dir current directory
@param string $dir_path current directory path
@param array $dirs directories
@return array|null | entailment |
public function handleAction(FileManager $fileManager, Request $request, $action)
{
$response = new Response();
try{
$dir = $this->getFilePath($fileManager);
$fileManager->setDir($dir);
$fileManager->checkPath();
if($request->getMethod() === 'POST') {
$this->checkToken($request->get('token'));
}
switch($action){
case FileManager::FILE_DELETE:
$fileManager->deleteFile();
break;
case FileManager::FILE_MOVE:
$fileManager->moveFile();
break;
case FileManager::FILE_EXTRACT:
$fileManager->extractZip();
break;
case FileManager::FILE_RENAME:
$fileManager->renameFile();
break;
case FileManager::FILE_NEW_DIR:
$fileManager->newDirectory();
break;
case FileManager::FILE_COPY:
case FileManager::FILE_CUT:
$this->copyFile($action);
break;
case FileManager::FILE_PASTE:
$this->pasteFile();
break;
case FileManager::FILE_INFO:
$response = new JsonResponse();
$response->setData(json_encode($fileManager->getCurrentFile()->toArray()));
break;
}
} catch(\Exception $e){
$response->setContent($e->getMessage());
$response->setStatusCode($e->getCode() == null ? 500 : $e->getCode());
}
return $response;
} | Validates the request and handles the action
@param FileManager $fileManager
@param Request $request
@param string $action
@return Response | entailment |
public function pasteFile()
{
/** @var Session $session */
$session = $this->container->get('session');
$sources = $session->get('copy');
$type = $sources['type'];
$this->getFileManager()->pasteFile($type);
$session->remove('copy');
} | Paste the file | entailment |
public function getEditForm($id=null, $fields=null) {
if(!$id) {
$id=$this->currentPageID();
}
$record=$this->getRecord($id);
if($record && !$record->canView()) {
return Security::permissionFailure($this);
}
if($record) {
$fields=$record->getCMSFields();
$actions=new FieldList(
FormAction::create('doSave', _t('CodeBank.SAVE', '_Save'))->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept'),
FormAction::create('doCancel', _t('CodeBank.CANCEL', '_Cancel'))
);
if($record->canDelete()) {
$actions->push(FormAction::create('doDelete', _t('CodeBank.DELETE', '_Delete'))->addExtraClass('ss-ui-action-destructive'));
}
// Use <button> to allow full jQuery UI styling
$actionsFlattened=$actions->dataFields();
if($actionsFlattened) {
foreach($actionsFlattened as $action) {
if($action instanceof FormAction) {
$action->setUseButtonTag(true);
}
}
}
if($record->hasMethod('getCMSValidator')) {
$validator=$record->getCMSValidator();
}else {
$validator=new RequiredFields();
}
$fields->push(new HiddenField('ID', 'ID'));
$form=CMSForm::create($this, 'EditForm', $fields, $actions, $validator)->setHTMLID('Form_EditForm');
$form->loadDataFrom($record);
$form->disableDefaultAction();
$form->addExtraClass('cms-edit-form');
$form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
$form->addExtraClass('center '.$this->BaseCSSClasses());
$form->setResponseNegotiator($this->getResponseNegotiator());
$form->setAttribute('data-pjax-fragment', 'CurrentForm');
$this->extend('updateEditForm', $form);
//Display message telling user to run dev/build because the version numbers are out of sync
if(CB_VERSION!='@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version!=CB_VERSION.' '.CB_BUILD_DATE) {
$form->insertBefore(new LiteralField('<p class="message error">'._t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink'=>'<a href="dev/build?flush=all">', 'endlink'=>'</a>')).'</p>'), 'LanguageID');
}else if($this->hasOldTables()) {
$form->insertBefore(new LiteralField('<p class="message warning">'._t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink'=>'<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink'=>'</a>')).'</p>'), 'LanguageID');
}
$form->Actions()->push(new LiteralField('CodeBankVersion', '<p class="codeBankVersion">Code Bank: '.$this->getVersion().'</p>'));
Requirements::javascript(CB_DIR.'/javascript/CodeBank.EditForm.js');
return $form;
}
$form=$this->EmptyForm();
if(Session::get('CodeBank.deletedSnippetID')) {
$form->Fields()->push(new HiddenField('ID', 'ID', Session::get('CodeBank.deletedSnippetID')));
}
//Display message telling user to run dev/build because the version numbers are out of sync
if(CB_VERSION!='@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version!=CB_VERSION.' '.CB_BUILD_DATE) {
$form->push(new LiteralField('<p class="message error">'._t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink'=>'<a href="dev/build?flush=all">', 'endlink'=>'</a>')).'</p>'));
}else if($this->hasOldTables()) {
$form->push(new LiteralField('<p class="message warning">'._t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink'=>'<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink'=>'</a>')).'</p>'));
}
$this->redirect('admin/codeBank/');
return $form;
} | Gets the form used for viewing snippets
@param {int} $id ID of the record to fetch
@param {FieldList} $fields Fields to use
@return {Form} Form to be used | entailment |
public function doSave($data, Form $form) {
$record=$this->currentPage();
if($record->canEdit()) {
$form->saveInto($record);
$record->write();
$this->response->addHeader('X-Status', rawurlencode(_t('CodeBank.SNIPPET_SAVED', '_Snippet has been saved')));
}else {
$this->response->addHeader('X-Status', rawurlencode(_t('CodeBank.PERMISSION_DENIED', '_Permission Denied')));
}
return $this->getResponseNegotiator()->respond($this->request);
} | Saves the snippet to the database
@param {array} $data Data submitted by the user
@param {Form} $form Submitting form
@return {SS_HTTPResponse} Response | entailment |
public function doDelete($data, Form $form) {
$record=$this->currentPage();
if($record->canDelete()) {
Session::set('CodeBank.deletedSnippetID', $record->ID);
$record->delete();
$this->response->addHeader('X-Status', rawurlencode(_t('CodeBank.SNIPPET_DELETED', '_Snippet has been deleted')));
}else {
$this->response->addHeader('X-Status', rawurlencode(_t('CodeBank.PERMISSION_DENIED', '_Permission Denied')));
}
$this->redirect('admin/codeBank/');
return $this->getResponseNegotiator()->respond($this->request);
} | Deletes the snippet from the database
@param {array} $data Data submitted by the user
@param {Form} $form Submitting form
@return {SS_HTTPResponse} Response | entailment |
public function writeMessage(Zend_Amf_Parse_OutputStream $stream)
{
$objectEncoding = $this->_objectEncoding;
//Write encoding to start of stream. Preamble byte is written of two byte Unsigned Short
$stream->writeByte(0x00);
$stream->writeByte($objectEncoding);
// Loop through the AMF Headers that need to be returned.
$headerCount = count($this->_headers);
$stream->writeInt($headerCount);
foreach ($this->getAmfHeaders() as $header) {
$serializer = new Zend_Amf_Parse_Amf0_Serializer($stream);
$stream->writeUTF($header->name);
$stream->writeByte($header->mustRead);
$stream->writeLong(Zend_Amf_Constants::UNKNOWN_CONTENT_LENGTH);
if (is_object($header->data)) {
// Workaround for PHP5 with E_STRICT enabled complaining about
// "Only variables should be passed by reference"
$placeholder = null;
$serializer->writeTypeMarker($placeholder, null, $header->data);
} else {
$serializer->writeTypeMarker($header->data);
}
}
// loop through the AMF bodies that need to be returned.
$bodyCount = count($this->_bodies);
$stream->writeInt($bodyCount);
foreach ($this->_bodies as $body) {
$serializer = new Zend_Amf_Parse_Amf0_Serializer($stream);
$stream->writeUTF($body->getTargetURI());
$stream->writeUTF($body->getResponseURI());
$stream->writeLong(Zend_Amf_Constants::UNKNOWN_CONTENT_LENGTH);
$bodyData = $body->getData();
$markerType = ($this->_objectEncoding == Zend_Amf_Constants::AMF0_OBJECT_ENCODING) ? null : Zend_Amf_Constants::AMF0_AMF3;
if (is_object($bodyData)) {
// Workaround for PHP5 with E_STRICT enabled complaining about
// "Only variables should be passed by reference"
$placeholder = null;
$serializer->writeTypeMarker($placeholder, $markerType, $bodyData);
} else {
$serializer->writeTypeMarker($bodyData, $markerType);
}
}
return $this;
} | Serialize the PHP data types back into Actionscript and
create and AMF stream.
@param Zend_Amf_Parse_OutputStream $stream
@return Zend_Amf_Response | entailment |
function Text_Diff_Renderer($params = array())
{
foreach ($params as $param => $value) {
$v = '_' . $param;
if (isset($this->$v)) {
$this->$v = $value;
}
}
} | Constructor. | entailment |
public function setPassword($password)
{
if ($this->username === null) {
throw new InvalidConfigException('用户名不能为空');
}
$this->password = md5($password . $this->username);
} | 设置密码
@param string $password
@throws InvalidConfigException | entailment |
public function setCallback($callback)
{
if (is_array($callback)) {
require_once 'Zend/Server/Method/Callback.php';
$callback = new Zend_Server_Method_Callback($callback);
} elseif (!$callback instanceof Zend_Server_Method_Callback) {
require_once 'Zend/Server/Exception.php';
throw new Zend_Server_Exception('Invalid method callback provided');
}
$this->_callback = $callback;
return $this;
} | Set method callback
@param array|Zend_Server_Method_Callback $callback
@return Zend_Server_Method_Definition | entailment |
public function addPrototype($prototype)
{
if (is_array($prototype)) {
require_once 'Zend/Server/Method/Prototype.php';
$prototype = new Zend_Server_Method_Prototype($prototype);
} elseif (!$prototype instanceof Zend_Server_Method_Prototype) {
require_once 'Zend/Server/Exception.php';
throw new Zend_Server_Exception('Invalid method prototype provided');
}
$this->_prototypes[] = $prototype;
return $this;
} | Add prototype to method definition
@param array|Zend_Server_Method_Prototype $prototype
@return Zend_Server_Method_Definition | entailment |
public function setObject($object)
{
if (!is_object($object) && (null !== $object)) {
require_once 'Zend/Server/Exception.php';
throw new Zend_Server_Exception('Invalid object passed to ' . __CLASS__ . '::' . __METHOD__);
}
$this->_object = $object;
return $this;
} | Set object to use with method calls
@param object $object
@return Zend_Server_Method_Definition | entailment |
public function toArray()
{
$prototypes = $this->getPrototypes();
$signatures = array();
foreach ($prototypes as $prototype) {
$signatures[] = $prototype->toArray();
}
return array(
'name' => $this->getName(),
'callback' => $this->getCallback()->toArray(),
'prototypes' => $signatures,
'methodHelp' => $this->getMethodHelp(),
'invokeArguments' => $this->getInvokeArguments(),
'object' => $this->getObject(),
);
} | Serialize to array
@return array | entailment |
public function authenticate()
{
$optionsRequired = array('filename', 'realm', 'username', 'password');
foreach ($optionsRequired as $optionRequired) {
if (null === $this->{"_$optionRequired"}) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception("Option '$optionRequired' must be set before authentication");
}
}
if (false === ($fileHandle = @fopen($this->_filename, 'r'))) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Auth_Adapter_Exception("Cannot open '$this->_filename' for reading");
}
$id = "$this->_username:$this->_realm";
$idLength = strlen($id);
$result = array(
'code' => Zend_Auth_Result::FAILURE,
'identity' => array(
'realm' => $this->_realm,
'username' => $this->_username,
),
'messages' => array()
);
while ($line = trim(fgets($fileHandle))) {
if (substr($line, 0, $idLength) === $id) {
if ($this->_secureStringCompare(substr($line, -32), md5("$this->_username:$this->_realm:$this->_password"))) {
$result['code'] = Zend_Auth_Result::SUCCESS;
} else {
$result['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
$result['messages'][] = 'Password incorrect';
}
return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']);
}
}
$result['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
$result['messages'][] = "Username '$this->_username' and realm '$this->_realm' combination not found";
return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']);
} | Defined by Zend_Auth_Adapter_Interface
@throws Zend_Auth_Adapter_Exception
@return Zend_Auth_Result | entailment |
protected function _secureStringCompare($a, $b)
{
if (strlen($a) !== strlen($b)) {
return false;
}
$result = 0;
for ($i = 0; $i < strlen($a); $i++) {
$result |= ord($a[$i]) ^ ord($b[$i]);
}
return $result == 0;
} | Securely compare two strings for equality while avoided C level memcmp()
optimisations capable of leaking timing information useful to an attacker
attempting to iteratively guess the unknown string (e.g. password) being
compared against.
@param string $a
@param string $b
@return bool | entailment |
public static function parse($arguments, $content=null, $parser=null) {
//Ensure ID is pressent in the arguments
if(!array_key_exists('id', $arguments)) {
return '<p><b><i>'._t('CodeBankShortCode.MISSING_ID_ATTRIBUTE', '_Short Code missing the id attribute').'</i></b></p>';
}
//Fetch Snippet
$snippet=Snippet::get()->byID(intval($arguments['id']));
if(empty($snippet) || $snippet===false || $snippet->ID==0) {
return '<p><b><i>'._t('CodeBankShortCode.SNIPPET_NOT_FOUND', '_Snippet not found').'</i></b></p>';
}
//Fetch Text
$snippetText=$snippet->SnippetText;
//If the version exists fetch it, and replace the text with that of the version
if(array_key_exists('version', $arguments)) {
$version=$snippet->Version(intval($arguments['version']));
if(empty($version) || $version===false || $version->ID==0) {
$snippetText=$version->Text;
}
}
//Load CSS Requirements
Requirements::css(CB_DIR.'/javascript/external/syntaxhighlighter/themes/shCore.css');
Requirements::css(CB_DIR.'/javascript/external/syntaxhighlighter/themes/shCoreDefault.css');
Requirements::css(CB_DIR.'/javascript/external/syntaxhighlighter/themes/shThemeDefault.css');
//Load JS Requirements
Requirements::javascript(THIRDPARTY_DIR.'/jquery/jquery.js');
Requirements::javascript(CB_DIR.'/javascript/external/syntaxhighlighter/brushes/shCore.js');
Requirements::javascript(CB_DIR.'/javascript/external/syntaxhighlighter/brushes/'.self::getBrushName($snippet->Language()->HighlightCode).'.js');
Requirements::javascriptTemplate(CB_DIR.'/javascript/CodeBankShortCode.template.js', array('ID'=>$snippet->ID), 'snippet-highlightinit-'.$snippet->ID);
//Render the snippet
$obj=new ViewableData();
return $obj->renderWith('CodeBankShortCode', array(
'ID'=>$snippet->ID,
'Title'=>$snippet->getField('Title'),
'Description'=>$snippet->getField('Description'),
'SnippetText'=>DBField::create_field('Text', $snippetText),
'HighlightCode'=>strtolower($snippet->Language()->HighlightCode)
));
} | Parses the snippet short code
@example [snippet id=123]
@example [snippet id=123 version=456] | entailment |
protected function _setupPrimaryAssignment()
{
if ($this->_primaryAssignment === null) {
$this->_primaryAssignment = array(1 => self::PRIMARY_ASSIGNMENT_SESSION_ID);
} else if (!is_array($this->_primaryAssignment)) {
$this->_primaryAssignment = array(1 => (string) $this->_primaryAssignment);
} else if (isset($this->_primaryAssignment[0])) {
array_unshift($this->_primaryAssignment, null);
unset($this->_primaryAssignment[0]);
}
if (count($this->_primaryAssignment) !== count($this->_primary)) {
/**
* @see Zend_Session_SaveHandler_Exception
*/
require_once 'Zend/Session/SaveHandler/Exception.php';
throw new Zend_Session_SaveHandler_Exception(
"Value for configuration option '" . self::PRIMARY_ASSIGNMENT . "' must have an assignment "
. "for each session table primary key.");
} else if (!in_array(self::PRIMARY_ASSIGNMENT_SESSION_ID, $this->_primaryAssignment)) {
/**
* @see Zend_Session_SaveHandler_Exception
*/
require_once 'Zend/Session/SaveHandler/Exception.php';
throw new Zend_Session_SaveHandler_Exception(
"Value for configuration option '" . self::PRIMARY_ASSIGNMENT . "' must have an assignment "
. "for the session id ('" . self::PRIMARY_ASSIGNMENT_SESSION_ID . "').");
}
} | Initialize session table primary key value assignment
@return void
@throws Zend_Session_SaveHandler_Exception | entailment |
public function render()
{
// Set the request arguments as GET parameters
$_GET = $this->getRequestArguments();
try {
$this->controllerContext->getRequest()->setOriginalRequestMappingResults($this->validationErrors);
// Render the content element
$result = $this->beautify($GLOBALS['TSFE']->cObj->cObjGetSingle('RECORDS', $this->config));
// In case of an error
} catch (\Exception $e) {
$result = '<pre class="error"><strong>'.$e->getMessage().'</strong>'.PHP_EOL
.$e->getTraceAsString().'</pre>';
}
return $result;
} | Render this component
@return string Rendered component (HTML) | entailment |
protected function exportInternal()
{
// Read the TypoScript rendering configuration for the given content record
if ($this->config !== null) {
$this->template = '10 = RECORDS'.PHP_EOL.TypoScriptUtility::serialize('', [10 => $this->config]);
}
return parent::exportInternal();
} | Return component specific properties
@return array Component specific properties | entailment |
public function toDomainEvents(): DomainEvents {
return DomainEvents::make($this->map(function (StreamEvent $streamEvent) {
return $streamEvent->event();
})->toArray());
} | return a DomainEvents collection containing the domain
events from within this stream events collection
@return DomainEvents | entailment |
protected static function _namespaceIsset($namespace, $name = null)
{
if (self::$_readable === false) {
/**
* @see Zend_Session_Exception
*/
require_once 'Zend/Session/Exception.php';
throw new Zend_Session_Exception(self::_THROW_NOT_READABLE_MSG);
}
if ($name === null) {
return ( isset($_SESSION[$namespace]) || isset(self::$_expiringData[$namespace]) );
} else {
return ( isset($_SESSION[$namespace][$name]) || isset(self::$_expiringData[$namespace][$name]) );
}
} | namespaceIsset() - check to see if a namespace or a variable within a namespace is set
@param string $namespace
@param string $name
@return bool | entailment |
protected static function _namespaceUnset($namespace, $name = null)
{
if (self::$_writable === false) {
/**
* @see Zend_Session_Exception
*/
require_once 'Zend/Session/Exception.php';
throw new Zend_Session_Exception(self::_THROW_NOT_WRITABLE_MSG);
}
$name = (string) $name;
// check to see if the api wanted to remove a var from a namespace or a namespace
if ($name === '') {
unset($_SESSION[$namespace]);
unset(self::$_expiringData[$namespace]);
} else {
unset($_SESSION[$namespace][$name]);
unset(self::$_expiringData[$namespace]);
}
// if we remove the last value, remove namespace.
if (empty($_SESSION[$namespace])) {
unset($_SESSION[$namespace]);
}
} | namespaceUnset() - unset a namespace or a variable within a namespace
@param string $namespace
@param string $name
@throws Zend_Session_Exception
@return void | entailment |
protected static function & _namespaceGet($namespace, $name = null)
{
if (self::$_readable === false) {
/**
* @see Zend_Session_Exception
*/
require_once 'Zend/Session/Exception.php';
throw new Zend_Session_Exception(self::_THROW_NOT_READABLE_MSG);
}
if ($name === null) {
if (isset($_SESSION[$namespace])) { // check session first for data requested
return $_SESSION[$namespace];
} elseif (isset(self::$_expiringData[$namespace])) { // check expiring data for data reqeusted
return self::$_expiringData[$namespace];
} else {
return $_SESSION[$namespace]; // satisfy return by reference
}
} else {
if (isset($_SESSION[$namespace][$name])) { // check session first
return $_SESSION[$namespace][$name];
} elseif (isset(self::$_expiringData[$namespace][$name])) { // check expiring data
return self::$_expiringData[$namespace][$name];
} else {
return $_SESSION[$namespace][$name]; // satisfy return by reference
}
}
} | namespaceGet() - Get $name variable from $namespace, returning by reference.
@param string $namespace
@param string $name
@return mixed | entailment |
public function scopeWithRelations(Builder $builder, $relations = null)
{
$with = [];
foreach ($this->getWithRelationsList($relations) as $relation) {
list($relation, $scope) = $this->_parseRelation($relation);
if ($this->isWithableRelation($builder, $relation)) {
if ($scope) {
$with[$relation] = function ($query) use ($scope) {
$query->$scope();
};
} else {
$with[] = $relation;
}
}
}
$builder->with($with);
} | Add eager loaded relations.
@param Builder $builder query builder
@param array $relations list of relations to be loaded | entailment |
protected function _parseRelation($relation)
{
$scope = null;
if (strpos($relation, ':') !== false) {
list($relation, $scope) = explode(':', $relation);
}
return [$relation, $scope];
} | Parse relation string to extract relation name and optional scope
@param $relation
@return array [relation name, scope name] | entailment |
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$this->keyExtractor->hasKey($request)) {
$response = new Response();
$response->setStatusCode(401);
$event->setResponse($response);
return ;
}
$apiKey = $this->keyExtractor->extractKey($request);
$token = new ApiKeyUserToken();
$token->setApiKey($apiKey);
try {
$authToken = $this->authenticationManager->authenticate($token);
$this->tokenStorage->setToken($authToken);
return;
} catch (AuthenticationException $failed) {
$token = $this->tokenStorage->getToken();
if ($token instanceof ApiKeyUserToken && $token->getCredentials() == $apiKey) {
$this->tokenStorage->setToken(null);
}
$message = $failed->getMessage();
}
$response = new Response();
$response->setContent($message);
$response->setStatusCode(403);
$event->setResponse($response);
} | This interface must be implemented by firewall listeners.
@param GetResponseEvent $event | entailment |
public static function getMappedClassName($className)
{
$mappedName = array_search($className, self::$classMap);
if ($mappedName) {
return $mappedName;
}
$mappedName = array_search($className, array_flip(self::$classMap));
if ($mappedName) {
return $mappedName;
}
return false;
} | Looks up the supplied call name to its mapped class name
@param string $className
@return string | entailment |
public static function addResourceDirectory($prefix, $dir)
{
if(self::$_resourceLoader) {
self::$_resourceLoader->addPrefixPath($prefix, $dir);
}
} | Add directory to the list of places where to look for resource handlers
@param string $prefix
@param string $dir | entailment |
public static function getResourceParser($resource)
{
if(self::$_resourceLoader) {
$type = preg_replace("/[^A-Za-z0-9_]/", " ", get_resource_type($resource));
$type = str_replace(" ","", ucwords($type));
return self::$_resourceLoader->load($type);
}
return false;
} | Get plugin class that handles this resource
@param resource $resource Resource type
@return string Class name | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.