sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
public function establish(array $config = [], $assign = false) {
$client = new Client($config + $this->config + $this->defaults());
if ($assign) {
$this->client = $client;
}
return $client;
} | Establishes the ES client using the provided config.
Provided config values will take place over the object's config attribute.
Finally, the defaults() result will be used as a final config source.
@param array $config Config value to override the general config params
@return Client | entailment |
protected function _find($type, $id) {
if (is_array($id)) {
return $this->__mfind($this->index(), $type, $id);
} else {
return $this->__find($this->index(), $type, $id);
}
} | A decorator method to get specific document by its id.
If the id is and array of strings or integers,
then multiple documents will be retreived by id.
@param string $type
@param mixed|string|integer|mixed[]|int[]|string[] $id
@return Model | entailment |
protected function _create(array $data, $type, $id = null, array $parameters = []) {
return $this->__create($data, $this->index(), $type, $id, $parameters);
} | Index a new document
@param array $data the document data
@param string $type
@param string|number $id
@param array $parameters
@return array | entailment |
protected function __create(array $data, $index, $type, $id = null, array $parameters = []) {
$parameters+=["api" => "create"];
$api = strtolower($parameters["api"]) == "index" ? "index" : "create";
unset($parameters["api"]);
$result = $this->client->$api([
'index' => $index,... | Index a new document
@param array $data the document data
@param string $index
@param string $type
@param string|number $id
@param array $parameters
@return array | entailment |
protected function _delete($type, $id = null, array $parameters = []) {
return $this->__delete($this->index(), $type, $id, $parameters);
} | Deletes a document
@param string $type
@param string|number $id
@param array $parameters
@return array | entailment |
protected function __delete($index, $type, $id, array $parameters = []) {
$result = $this->client->delete([
'index' => $index,
'type' => $type,
'id' => $id] + $parameters);
return $result;
} | Deletes a document
@param string $index
@param string $type
@param string|number $id
@param array $parameters
@return array | entailment |
protected function __query($index, $type = null, array $query = []) {
$result = $this->client->search([
'index' => $index,
'body' => array_merge_recursive($query, $this->additionalQuery())
] + ($type ? ['type' => $type] : []));
return $this->_makeResult($result);
... | The actual method to call client's search method.
Returns Result object
@param string $index
@param string $type if null, then all types will be searched
@param array $query
@return Result|Model[] | entailment |
protected function __find($index, $type, $id) {
try {
$result = $this->client->get([
'index' => $index,
'type' => $type,
'id' => $id
]);
if ($result['found']) {
return $this->_makeModel($result);
} el... | The actual method to call client's get method.
Returns either a Model object or null on failure.
@param string $index
@param string $type
@param sring|int $id
@return null|Model | entailment |
protected function __mfind($index, $type, $ids) {
try {
$docs = $this->client->mget([
'index' => $index,
'type' => $type,
'body' => [
"ids" => $ids
]
]);
$result = ['ids' => $ids, 'found' => [... | The actual method to call client's mget method.
Returns either a result of Model objects or null on failure.
@param string $index
@param string $type
@param sring[]|int[] $ids
@return null|Model | entailment |
protected function _makeResult(array $result) {
return Result::make($result, $this->getClient())->setModelClass($this->_fullModelClassNamePattern());
} | Creates a results set for ES query hits
@param array $result
@return Result | entailment |
protected function _makeMultiGetResult(array $result) {
return MultiGetResult::make($result, $this->getClient())->setModelClass($this->_fullModelClassNamePattern());
} | Creates a results set for ES query hits
@param array $result
@return Result | entailment |
protected function _meta($features = null, array $options = []) {
if ($features) {
$features = join(',', array_map(function($item) {
return '_' . strtolower(trim($item, '_'));
}, is_scalar($features) ? explode(",", $features) : $features));
}
... | Retreives the meta data of an index
@param string|array $features a list of meta objects to fetch. null means
everything. Can be
* 1 string (i.e. '_settings'),
* csv (i.e. '_settings,_aliases'),
* array (i.e. ['_settings','_aliases']
@param array $options can contain:
['ignore_unavailable']
(bool) Whether specified con... | entailment |
public function setAuth($username, $password)
{
if (strlen($username) > 255 || strlen($password) > 255) {
throw new InvalidArgumentException('Both username and password MUST NOT exceed a length of 255 bytes each');
}
if ($this->protocolVersion !== null && $this->protocolVersion !... | set login data for username/password authentication method (RFC1929)
@param string $username
@param string $password
@link http://tools.ietf.org/html/rfc1929 | entailment |
public static function discoverAll()
{
$components = [];
// Run through all extensions
foreach (ExtensionManagementUtility::getLoadedExtensionListArray() as $extensionKey) {
$components = array_merge($components, self::discoverExtensionComponents($extensionKey));
}
... | Discover all components
@return array Components | entailment |
protected static function discoverExtensionComponents($extensionKey)
{
// Test if the extension contains a component directory
$extCompRootDirectory = ExtensionManagementUtility::extPath($extensionKey, 'Components');
return is_dir($extCompRootDirectory) ? self::discoverExtensionComponentDir... | Discover the components of a single extension
@param $extensionKey | entailment |
protected static function discoverExtensionComponentDirectory($directory)
{
$components = [];
$directoryIterator = new \RecursiveDirectoryIterator($directory);
$recursiveIterator = new \RecursiveIteratorIterator($directoryIterator);
$regexIterator = new \RegexIterator(
... | Recursively scan a directory for components and return a component list
@param string $directory Directory path
@return array Components | entailment |
protected static function discoverClassesInFile($phpCode)
{
$classes = array();
$tokens = token_get_all($phpCode);
$gettingClassname = $gettingNamespace = false;
$namespace = '';
$lastToken = null;
// Run through all tokens
fo... | Discover the classes declared in a file
@param string $phpCode PHP code
@return array Class names | entailment |
protected static function addLocalConfiguration($componentDirectory, array $component)
{
$component['local'] = [];
$componentDirectories = [];
for ($dir = 0; $dir < count($component['path']); ++$dir) {
$componentDirectory = $componentDirectories[] = dirname($componentDirectory)... | Amend the directory specific local configuration
@param string $componentDirectory Component directory
@param array $component Component
@return array Amended component | entailment |
protected static function getLocalConfiguration($dirname)
{
if (is_dir($dirname) && empty(self::$localConfigurations[$dirname])) {
$localConfig = $dirname.DIRECTORY_SEPARATOR.'local.json';
self::$localConfigurations[$dirname] = file_exists($localConfig) ?
... | Read, cache and return a directory specific local configuration
@param string $dirname Directory name
@return array Directory specific local configuration | entailment |
public function writeTypeMarker(&$data, $markerType = null, $dataByVal = false)
{
// Workaround for PHP5 with E_STRICT enabled complaining about "Only
// variables should be passed by reference"
if ((null === $data) && ($dataByVal !== false)) {
$data = &$dataByVal;
}
... | Determine type and serialize accordingly
Checks to see if the type was declared and then either
auto negotiates the type or relies on the user defined markerType to
serialize the data into amf
@param mixed $data
@param mixed $markerType
@param mixed $dataByVal
@return Zend_Amf_Parse_Amf0_Serializer
@throws Zend_Am... | entailment |
protected function writeObjectReference(&$object, $markerType, $objectByVal = false)
{
// Workaround for PHP5 with E_STRICT enabled complaining about "Only
// variables should be passed by reference"
if ((null === $object) && ($objectByVal !== false)) {
$object = &$objectByVal;
... | Check if the given object is in the reference table, write the reference if it exists,
otherwise add the object to the reference table
@param mixed $object object reference to check for reference
@param string $markerType AMF type of the object to write
@param mixed $objectByVal object to check for reference
@return... | entailment |
public function writeObject($object)
{
// Loop each element and write the name of the property.
foreach ($object as $key => &$value) {
// skip variables starting with an _ private transient
if( $key[0] == "_") continue;
$this->_stream->writeUTF($key);
... | Write a PHP array with string or mixed keys.
@param object $data
@return Zend_Amf_Parse_Amf0_Serializer | entailment |
public function writeArray(&$array)
{
$length = count($array);
if (!$length < 0) {
// write the length of the array
$this->_stream->writeLong(0);
} else {
// Write the length of the numeric array
$this->_stream->writeLong($length);
... | Write a standard numeric array to the output stream. If a mixed array
is encountered call writeTypeMarker with mixed array.
@param array $array
@return Zend_Amf_Parse_Amf0_Serializer | entailment |
public function writeDate($data)
{
if ($data instanceof DateTime) {
$dateString = $data->format('U');
} elseif ($data instanceof Zend_Date) {
$dateString = $data->toString('U');
} else {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf... | Convert the DateTime into an AMF Date
@param DateTime|Zend_Date $data
@return Zend_Amf_Parse_Amf0_Serializer | entailment |
public function writeTypedObject($data)
{
$this->_stream->writeUTF($this->_className);
$this->writeObject($data);
return $this;
} | Write a class mapped object to the output stream.
@param object $data
@return Zend_Amf_Parse_Amf0_Serializer | entailment |
public function writeAmf3TypeMarker(&$data)
{
require_once 'Zend/Amf/Parse/Amf3/Serializer.php';
$serializer = new Zend_Amf_Parse_Amf3_Serializer($this->_stream);
$serializer->writeTypeMarker($data);
return $this;
} | Encountered and AMF3 Type Marker use AMF3 serializer. Once AMF3 is
encountered it will not return to AMf0.
@param string $data
@return Zend_Amf_Parse_Amf0_Serializer | entailment |
protected function getClassName($object)
{
require_once 'Zend/Amf/Parse/TypeLoader.php';
//Check to see if the object is a typed object and we need to change
$className = '';
switch (true) {
// the return class mapped name back to actionscript class name.
case... | Find if the class name is a class mapped name and return the
respective classname if it is.
@param object $object
@return false|string $className | entailment |
public static function extractTypoScriptKeyForPidAndType($id, $typeNum, $key)
{
$key = trim($key);
if (!strlen($key)) {
throw new \RuntimeException(sprintf('Invalid TypoScript key "%s"', $key), 1481365294);
}
// Get a frontend controller for the page id and type
... | Extract and return a TypoScript key for a particular page and type
@param int $id Page ID
@param int $typeNum Page type
@param string $key TypoScript key
@return array TypoScript values
@throws \TYPO3\CMS\Core\Error\Http\ServiceUnavailableException
@throws \Exception If the TypoScript key is invalid | entailment |
public static function getTSFE($id, $typeNum)
{
// Initialize the tracker if necessary
if (!is_object($GLOBALS['TT'])) {
$GLOBALS['TT'] = new TimeTracker(false);
$GLOBALS['TT']->start();
}
if (!array_key_exists("$id/$typeNum", self::$frontendControllers)) {
... | Instantiate a Frontend controller for the given configuration
@param int $id Page ID
@param int $typeNum Page Type
@return TypoScriptFrontendController Frontend controller
@throws \Exception
@throws \TYPO3\CMS\Core\Error\Http\ServiceUnavailableException | entailment |
public static function serialize($prefix, array $typoscript, $indent = 0)
{
$serialized = [];
// Sort the TypoScript fragment
ksort($typoscript, SORT_NATURAL);
// Run through the TypoScript fragment
foreach ($typoscript as $key => $value) {
$line = str_repeat(' ... | Serialize a TypoScript fragment
@param string $prefix Key prefix
@param array $typoscript TypoScript fragment
@param int $indent Indentation level
@return string Serialized TypoScript | entailment |
public function getSteam2RenderedID($newerFormat = false) {
if ($this->type != self::TYPE_INDIVIDUAL) {
throw new Exception("Can't get Steam2 rendered ID for non-individual ID");
} else {
$universe = $this->universe;
if ($universe == 1 && !$newerFormat) {
$universe = 0;
}
return 'STEAM_' . $univ... | Gets the rendered STEAM_X:Y:Z format.
@param bool $newerFormat If the universe is public, should X be 1 instead of 0?
@return string
@throws Exception If this isn't an individual account SteamID | entailment |
public function getSteam3RenderedID() {
$type_char = self::$typeChars[$this->type] ? self::$typeChars[$this->type] : 'i';
if ($this->instance & self::CHAT_INSTANCE_FLAG_CLAN) {
$type_char = 'c';
} elseif ($this->instance & self::CHAT_INSTANCE_FLAG_LOBBY) {
$type_char = 'L';
}
$render_instance = ($this... | Gets the rendered [T:U:A(:I)] format (T = type, U = universe, A = accountid, I = instance)
@return string | entailment |
public function getSteamID64() {
if (PHP_INT_SIZE == 4) {
$ret = new Math_BigInteger();
$ret = $ret->add((new Math_BigInteger($this->universe))->bitwise_leftShift(56));
$ret = $ret->add((new Math_BigInteger($this->type))->bitwise_leftShift(52));
$ret = $ret->add((new Math_BigInteger($this->instance))->bit... | Gets the SteamID as a 64-bit integer
@return string | entailment |
public static function makeForQueryInstance(Query $instance, array $query = []) {
$query = static::make($query);
return $query->setQueryInstance($instance);
} | Initiates a new query builder for a specific Query instance
This helps in fluiding the query stream. i.e.
SomeTypeQuery::make($config)->builder()->where("id",8)->where("age",">=",19)->execute();
@param Query $instance
@param array $query
@return AutoQueryBuilder | entailment |
public function init() {
LeftAndMain::init();
Requirements::css(CB_DIR.'/css/CodeBank.css');
Requirements::customScript("var CB_DIR='".CB_DIR."';", 'cb_dir');
if(empty(CodeBankConfig::CurrentConfig()->IPMessage) || Session::get('CodeBankIPAgreed')===true) {
... | Initializes the code bank admin | entailment |
public function getEditForm($id=null, $fields=null) {
$defaultPanel=Config::inst()->get('AdminRootController', 'default_panel');
if($defaultPanel=='CodeBank') {
$defaultPanel='SecurityAdmin';
$sng=singleton($defaultPanel);
}
$fields=new F... | Gets the form used for agreeing or disagreeing to the ip agreement
@param {int} $id ID of the record to fetch
@param {FieldList} $fields Fields to use
@return {Form} Form to be used | entailment |
public function render()
{
// Set the request arguments as GET parameters
$_GET = $this->getRequestArguments();
try {
$rendererClassName = $this->element->getRendererClassName();
/** @var FluidFormRenderer $renderer */
$renderer = $this->objectManager->g... | Render this component
@return string Rendered component (HTML) | entailment |
protected function initialize()
{
parent::initialize();
// Use the standard language file as fallback
if ($this->translationFile === null) {
$this->translationFile = 'EXT:'.$this->extensionKey.'/Resources/Private/Language/locallang.xlf';
}
$configurationService ... | Initialize the component
Gets called immediately after construction. Override this method in components to initialize the component.
@return void
@throws \TYPO3\CMS\Form\Domain\Configuration\Exception\PrototypeNotFoundException
@throws \TYPO3\CMS\Form\Domain\Exception\TypeDefinitionNotFoundException | entailment |
protected function createElement($typeName, $identifier = null)
{
$identifier = trim($identifier) ?:
strtr(GeneralUtility::camelCaseToLowerCaseUnderscored($typeName), '_', '-').'-1';
$this->element = $this->page->createElement($identifier, $typeName);
$this->element->setProper... | Create a form element
@param string $typeName Type of the new form element
@param string $identifier Form element identifier
@return AbstractRenderable Renderable form element
@throws \TYPO3\CMS\Form\Domain\Exception\TypeDefinitionNotFoundException
@throws \TYPO3\CMS\Form\Domain\Exception\TypeDefinitionNotValidExce... | entailment |
protected function addElementError($message)
{
if ($this->element === null) {
throw new \RuntimeException('Create a form element prior to adding a validation error', 1519731421);
}
$this->addError($this->element->getIdentifier(), $message);
} | Register a validation error for the form element
@param string $message Validation error message
@throws \RuntimeException If no element has been created prior to adding an error message | entailment |
protected function exportInternal()
{
// Read the linked TypoScript
if ($this->config !== null) {
$templateFile = GeneralUtility::getFileAbsFileName($this->config);
if (!strlen($templateFile) || !is_file($templateFile)) {
throw new \RuntimeException(sprintf('I... | Return component specific properties
@return array Component specific properties | entailment |
public function AddForm() {
$sng=singleton('Snippet');
$fields=$sng->getCMSFields();
$validator=$sng->getCMSValidator();
$actions=new FieldList(
FormAction::create('doAdd', _t('CodeBank.CREATE', '_Create'))->addExtraClass('ss-ui-action-const... | Generates the form used for adding snippets
@return {Form} Form used to add snippets | entailment |
public function doAdd($data, Form $form) {
$record=$this->getRecord(null);
$form->saveInto($record);
$record->write();
$editController=singleton('CodeBank');
$editController->setCurrentPageID($record->ID);
return $this->redirect(Controller::join_... | Handles adding the snippet to the database
@param {array} $data Data submitted by the user
@param {Form} $form Form submitted | entailment |
public function doSnippetSearch($keywords, $languageID=false, $folderID=false) {
$list=Snippet::get();
if(isset($languageID) && !empty($languageID)) {
$list=$list->filter('LanguageID', intval($languageID));
}
if(isset($folderID) && !empty($folderID)... | Performs the search against the snippets in the system
@param {string} $keywords Keywords to search for
@param {int} $languageID Language to filter to
@param {int} $folderID Folder to filter to
@return {DataList} Data list pointing to the snippets in the results | entailment |
public function open()
{
if (!$this->isRemoteFile($this->path) && !is_readable($this->path)) {
throw new BoxClientException('Failed to create BoxFile instance. Unable to read resource: ' . $this->path . '.');
}
$this->stream = \GuzzleHttp\Psr7\stream_for(fopen($this->path, 'r'))... | Opens the File Stream
@throws BoxClientException
@return void | entailment |
public function getContents()
{
// If an offset is provided
if ($this->offset !== -1) {
// Seek to the offset
$this->stream->seek($this->offset);
}
// If a max length is provided
if ($this->maxLength !== -1) {
// Read from the offset till ... | Return the contents of the file
@return string | entailment |
public function FieldHolder($properties=array()) {
$obj=($properties ? $this->customise($properties):$this);
Requirements::css(CB_DIR.'/css/PackageViewField.css');
Requirements::javascript(CB_DIR.'/javascript/PackageViewField.js');
return $obj->renderWit... | Returns a "field holder" for this field - used by templates.
@param {array} $properties key value pairs of template variables
@return {string} HTML to be used | entailment |
public function load(array $configs, ContainerBuilder $container)
{
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
if (!method_exists(AbstractType::class, 'getBlockPrefix')) {
$container->getDefinition('iv... | {@inheritdoc} | entailment |
public function getServices()
{
$this->_zendAmfServer = ZendAmfServiceBrowser::$ZEND_AMF_SERVER;
$methods = $this->_zendAmfServer->getFunctions();
$methodsTable = '<methods>';
foreach ($methods as $method => $value)
{
$functionReflection = $methods[ $method ];
$parameters = $functionReflect... | The getServices() method returns all of the available services for the Zend_Amf_Server object.
@return array Table of parameters for each method key ("Class.method"). | entailment |
public function addListener(Listener $listener) : void {
$this->listeners = $this->listeners->add($listener);
} | add an event listener to the dispatcher
@param Listener $listener | entailment |
public function dispatch(DomainEvents $events) : void {
$events->each(function (DomainEvent $event) {
$this->listeners->each(function (Listener $listener) use ($event) {
$listener->handle($event);
});
});
} | dispatch domain events to listeners
@param DomainEvents $events | entailment |
public function toChunks(Csv $csv, $size=1000)
{
return Writer\ChunksWriter::write($this, $csv, $size);
} | /* Special writers | entailment |
public function initialize($request)
{
$this->_inputStream = new Zend_Amf_Parse_InputStream($request);
$this->_deserializer = new Zend_Amf_Parse_Amf0_Deserializer($this->_inputStream);
$this->readMessage($this->_inputStream);
return $this;
} | Prepare the AMF InputStream for parsing.
@param string $request
@return Zend_Amf_Request | entailment |
public function readMessage(Zend_Amf_Parse_InputStream $stream)
{
$clientVersion = $stream->readUnsignedShort();
if (($clientVersion != Zend_Amf_Constants::AMF0_OBJECT_ENCODING)
&& ($clientVersion != Zend_Amf_Constants::AMF3_OBJECT_ENCODING)
&& ($clientVersion != Zend_Amf_Con... | Takes the raw AMF input stream and converts it into valid PHP objects
@param Zend_Amf_Parse_InputStream
@return Zend_Amf_Request | entailment |
public function readHeader()
{
$name = $this->_inputStream->readUTF();
$mustRead = (bool)$this->_inputStream->readByte();
$length = $this->_inputStream->readLong();
try {
$data = $this->_deserializer->readTypeMarker();
} catch (Exception $e) {
r... | Deserialize a message header from the input stream.
A message header is structured as:
- NAME String
- MUST UNDERSTAND Boolean
- LENGTH Int
- DATA Object
@return Zend_Amf_Value_MessageHeader | entailment |
public function readBody()
{
$targetURI = $this->_inputStream->readUTF();
$responseURI = $this->_inputStream->readUTF();
$length = $this->_inputStream->readLong();
try {
$data = $this->_deserializer->readTypeMarker();
} catch (Exception $e) {
r... | Deserialize a message body from the input stream
@return Zend_Amf_Value_MessageBody | entailment |
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
// if the user hit a secure page and start() was called, this was
// the URL they were on, and probably where you want to redirect to
$targetPath = $request->getSession()->get('_security.'.$provi... | Override to change what happens after successful authentication
@param Request $request
@param TokenInterface $token
@param string $providerKey
@return RedirectResponse | entailment |
protected function addRelation()
{
if ($this->relationType == 'hasAndBelongsToMany')
{
$junction = $this->getJunction();
try
{
Validate::table($junction)->exists();
}
catch (dbException $e)
{
... | Add data to configs and create all necessary files | entailment |
protected function insertRelationData($from, $to, $type, array $keys)
{
$config = Config::table($from);
$content = $config->get();
$content->relations->{$to} = [
'type' => $type,
'keys' => $keys,
];
$config-... | Inserts relation data to config file
@param string $from Local table
@param string $to Related table
@param string $type Relation type
@param array $keys Relationed keys | entailment |
protected function join($row)
{
$keys['local'] = $this->keys['local'];
$keys['foreign'] = $this->keys['foreign'];
if ($this->relationType == 'hasAndBelongsToMany')
{
$join = Database::table($this->getJunction())
->groupBy($this->tables['loca... | Process query with joined data
@param object $row One row of data
@return Database | entailment |
protected function buildUrl($endpoint = '', $type = 'api')
{
//Get the base path
$base = $this->getBasePath();
//If the endpoint type is 'upload'
if ($type === 'upload') {
//Get the Content Path
$base = $this->getUploadPath();
}
//Join and re... | Build URL for the Request
@param string $endpoint Relative API endpoint
@param string $type Endpoint Type
@return string The Full URL to the API Endpoints | entailment |
public function sendRequest(BoxRequest $request)
{
//Method
$method = $request->getMethod();
//Prepare Request
list($url, $headers, $requestBody, $options) = $this->prepareRequest($request);
//Send the Request to the Server through the HTTP Client
//and fetch the ra... | Send the Request to the Server and return the Response
@param BoxRequest $request
@return BoxResponse
@throws Exceptions\BoxClientException | entailment |
protected function prepareRequest(BoxRequest $request)
{
$options = array();
$contentType = true;
//Build URL
$url = $this->buildUrl($request->getEndpoint(), $request->getEndpointType());
//The Endpoint is content
if ($request->getEndpointType() === 'upload') {
... | Prepare a Request before being sent to the HTTP Client
@param BoxResponse $request
@return array [Request URL, Request Headers, Request Body, Options Array] | entailment |
function Text_Diff3($orig, $final1, $final2)
{
if (extension_loaded('xdiff')) {
$engine = new Text_Diff_Engine_xdiff();
} else {
$engine = new Text_Diff_Engine_native();
}
$this->_edits = $this->_diff3($engine->diff($orig, $final1),
... | Computes diff between 3 sequences of strings.
@param array $orig The original lines to use.
@param array $final1 The first version to compare to.
@param array $final2 The second version to compare to. | entailment |
public function serialize($value) {
if ($value instanceof SerializablePersonalDataValue) {
return $this->serializePersonalDataValue($value);
} elseif ($value instanceof SerializableValue) {
return $this->serializeValue($value);
}
return $value;
} | serialize a value object into its string-based persistence form
@param $value
@return array | entailment |
private function serializePersonalDataValue(SerializablePersonalDataValue $value): array {
$dataKey = PersonalDataKey::generate();
$dataString = json_encode($value->serialize());
$this->dataStore->storeData($value->personalKey(), $dataKey, PersonalData::fromString($dataString));
ret... | serialize a value that contains personal data
@param SerializablePersonalDataValue $value
@return array | entailment |
public function deserializePersonalValue(string $type, string $json): SerializablePersonalDataValue {
$values = json_decode($json);
$personalKey = PersonalKey::deserialize($values->personalKey);
$dataKey = PersonalDataKey::deserialize($values->dataKey);
return $type::deseri... | deserialize a value that contains personal data
@param string $type
@param string $json
@return SerializablePersonalDataValue | entailment |
public function addParameter($parameter)
{
if ($parameter instanceof Zend_Server_Method_Parameter) {
$this->_parameters[] = $parameter;
if (null !== ($name = $parameter->getName())) {
$this->_parameterNameMap[$name] = count($this->_parameters) - 1;
}
... | Add a parameter
@param string $parameter
@return Zend_Server_Method_Prototype | entailment |
public function setParameters(array $parameters)
{
$this->_parameters = array();
$this->_parameterNameMap = array();
$this->addParameters($parameters);
return $this;
} | Set parameters
@param array $parameters
@return Zend_Server_Method_Prototype | entailment |
public function getParameters()
{
$types = array();
foreach ($this->_parameters as $parameter) {
$types[] = $parameter->getType();
}
return $types;
} | Retrieve parameters as list of types
@return array | entailment |
public function getParameter($index)
{
if (!is_string($index) && !is_numeric($index)) {
return null;
}
if (array_key_exists($index, $this->_parameterNameMap)) {
$index = $this->_parameterNameMap[$index];
}
if (array_key_exists($index, $this->_parameter... | Retrieve a single parameter by name or index
@param string|int $index
@return null|Zend_Server_Method_Parameter | entailment |
public static function create($name, $type, $extension, $vendor)
{
// Prepare the component name
$componentLabel = $componentName = array_pop($name);
if (substr($componentName, -9) !== 'Component') {
$componentName .= 'Component';
}
// Prepare the component direc... | Kickstart a new component
@param string $name Component name
@param string $type Component type
@param string $extension Host extension
@throws CommandException If the provider extension is invalid | entailment |
protected function processParams(array $params)
{
//If a file needs to be uploaded
if (isset($params['file']) && $params['file'] instanceof BoxFile) {
//Set the file property
$this->setFile($params['file']);
//Remove the file item from the params array
... | Process Params for the File parameter
@param array $params Request Params
@return array | entailment |
public function handleUploadedFiles(UploadedFile $file, $extension, $dir)
{
$original_file = $file->getClientOriginalName();
$path_parts = pathinfo($original_file);
$increment = '';
while (file_exists($dir . FileManager::DS . $path_parts['filename'] . $increment . '.' . $extension))... | Upload the files
@param UploadedFile $file
@param string $extension
@param string $dir | entailment |
public function makeDir($dir_path)
{
$fm = new Filesystem();
if (!file_exists($dir_path)) {
$fm->mkdir($dir_path, 0755);
} else {
$this->getFileManager()
->throwError("Cannot create directory '" . $dir_path . "': Directory already exists", 500);
... | Create new directory
@param string $dir_path | entailment |
public function renameFile(FileInfo $fileInfo, $new_file_name)
{
try {
$this->validateFile($fileInfo, $new_file_name);
$fm = new Filesystem();
$old_file = $fileInfo->getFilepath(true);
$new_file = $new_file_name;
$fm->rename($old_file, $new_file);
... | Renames the file
@param FileInfo $fileInfo
@param string $new_file_name | entailment |
public function validateFile(FileInfo $fileInfo, $new_filename = null)
{
$file_path = $fileInfo->getFilePath(true);
if (!is_dir($file_path)) {
$fm = new Filesystem();
$tmp_dir = $this->createTmpDir($fm);
$fm->copy($file_path, $tmp_dir . FileManager::DS . $fileInf... | Validate the files to check if they have a valid file type
@param FileInfo $fileInfo
@param null|string $new_filename | entailment |
public function createTmpDir(Filesystem $fm)
{
$tmp_dir = $this->getFileManager()->getUploadPath() . FileManager::DS . "." . strtotime("now");
$fm->mkdir($tmp_dir);
return $tmp_dir;
} | Create a temporary directory
@param Filesystem $fm
@return string | entailment |
public function checkFileType(Filesystem $fm, $tmp_dir)
{
$di = new \RecursiveDirectoryIterator($tmp_dir);
foreach (new \RecursiveIteratorIterator($di) as $filepath => $file) {
$fileInfo = new FileInfo($filepath, $this->getFileManager());
$mime_valid = $this->checkMimeType($f... | Check if the file type is an valid file type by extracting the zip inside a temporary directory
@param Filesystem $fm
@param string $tmp_dir | entailment |
public function checkMimeType($fileInfo)
{
$mime = $fileInfo->getMimetype();
if ($mime != 'directory' && !in_array($mime, $this->getFileManager()->getExtensionsAllowed())) {
return 'Mime type "' . $mime . '" not allowed for file "' . $fileInfo->getFilename() . '"';
}
ret... | Check the mimetype
@param FileInfo $fileInfo
@return string|bool | entailment |
public function moveFile(FileInfo $fileInfo, $new_file_name)
{
try {
$this->validateFile($fileInfo);
$file_path = $fileInfo->getFilepath(true);
$file = new File($file_path, false);
$file->move($new_file_name);
} catch (\Exception $e) {
$thi... | Move the file
@param FileInfo $fileInfo
@param string $new_file_name | entailment |
public function pasteFile(FileInfo $fileInfo, $type)
{
try {
$target_file_path = $this->getFileManager()->getTargetFile()->getFilepath(true);
$source_file_path = $fileInfo->getFilepath(true);
$this->validateFile($fileInfo);
$fileSystem = new Filesystem();
... | Paste the file
@param FileInfo $fileInfo
@param string $type | entailment |
public function deleteFile(FileInfo $fileInfo)
{
try {
$fm = new Filesystem();
$file = $fileInfo->getFilepath(true);
$fm->remove($file);
} catch (\Exception $e) {
$this->getFileManager()->throwError("Cannot delete file or directory", 500, $e);
... | Delete the file
@param FileInfo $fileInfo | entailment |
public function extractZip(FileInfo $fileInfo)
{
$fm = new Filesystem();
$tmp_dir = $this->createTmpDir($fm);
$this->extractZipTo($fileInfo->getFilepath(true), $tmp_dir);
$this->checkFileType($fm, $tmp_dir);
try {
$this->extractZipTo($fileInfo->getFilepath(true)... | Extract the zip
@param FileInfo $fileInfo | entailment |
public function extractZipTo($filepath, $destination)
{
$chapterZip = new \ZipArchive ();
if ($chapterZip->open($filepath)) {
$chapterZip->extractTo($destination);
$chapterZip->close();
}
} | Extract the zip to the given location
@param string $filepath
@param string $destination | entailment |
function Text_Diff_Mapped($from_lines, $to_lines,
$mapped_from_lines, $mapped_to_lines)
{
assert(count($from_lines) == count($mapped_from_lines));
assert(count($to_lines) == count($mapped_to_lines));
parent::Text_Diff($mapped_from_lines, $mapped_to_lines);
... | Computes a diff between sequences of strings.
This can be used to compute things like case-insensitve diffs, or diffs
which ignore changes in white-space.
@param array $from_lines An array of strings.
@param array $to_lines An array of strings.
@param array $mapped_from_lines This array should have... | entailment |
public function getResponseNegotiator() {
$neg=parent::getResponseNegotiator();
$controller=$this;
$neg->setCallback('CurrentForm', function() use(&$controller) {
return $controller->renderWith($controller->getTemplatesWithS... | @return {PjaxResponseNegotiator}
@see LeftAndMain::getResponseNegotiator() | entailment |
public function doSave($data, $form) {
$config=CodeBankConfig::CurrentConfig();
$form->saveInto($config);
$config->write();
$this->response->addHeader('X-Status', rawurlencode(_t('LeftAndMain.SAVEDUP', 'Saved.')));
return $this->getResponseNegotiator()->respond($this->re... | 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 import_from_client() {
if(!Permission::check('ADMIN')) {
Security::permissionFailure($this);
return;
}
$form=$this->ImportFromClientForm();
if(Session::get('reloadOnImportDialogClose')) {
Requirements::javascript(CB_DIR.'/javas... | Handles requests for the import from client popup
@return {string} Rendered template | entailment |
public function ImportFromClientForm() {
if(!Permission::check('ADMIN')) {
Security::permissionFailure($this);
return;
}
$uploadField=new FileField('ImportFile', _t('CodeBank.EXPORT_FILE', '_Client Export File'));
$uploadField->getValidator()->setAllowedE... | Form used for importing data from the client
@return {Form} Form to be used in the popup | entailment |
public function doImportData($data, Form $form) {
if(!Permission::check('ADMIN')) {
Security::permissionFailure($this);
return;
}
$fileData=$form->Fields()->dataFieldByName('ImportFile')->Value();
//Check that the file uploaded
if(!array_key_exist... | Processes the upload request
@param {array} $data Submitted data
@param {Form} $form Submitting form
@return {SS_HTTPResponse} Response | entailment |
protected function raise(DomainEvent $event): void {
$this->apply($event);
$this->streamEvents = $this->streamEvents->add(
new StreamEvent($this->aggregateId(), $this->aggregateVersion(), $event)
);
} | raise an event from within the aggregate. this applies
the event to the aggregate state and stores it in the
pending stream events collection awaiting flush.
@param DomainEvent $event | entailment |
public function flushEvents(): StreamEvents {
$events = $this->streamEvents->copy();
$this->streamEvents = StreamEvents::make();
return $events;
} | returns and clears the internal pending stream events.
this DOES violate CQS, however it's important not to
retrieve or store these events multiple times. pass these
directly into the event store.
@return StreamEvents | entailment |
public static function buildFrom(StreamEvents $events): Aggregate {
$aggregate = new static;
$events->each(function (StreamEvent $event) use ($aggregate) {
$aggregate->apply($event->event());
if ( ! $event->version()->equals($aggregate->aggregateVersion())) {
thro... | reconstruct the aggregate state from domain events
@param StreamEvents $events
@return Aggregate | entailment |
protected function apply(DomainEvent $event): void {
$eventName = explode('\\', get_class($event));
$method = 'apply' . $eventName[count($eventName) - 1];
if (method_exists($this, $method)) {
$this->$method($event);
}
$this->version = $this->version->next();
} | apply domain events to aggregate state by mapping the class
name to method name using strings
@param DomainEvent $event | entailment |
public static function types(array $types)
{
$defined = array('boolean', 'integer', 'double', 'string');
$diff = array_diff($types, $defined);
if (empty($diff))
{
return true;
}
throw new dbException('Wrong types: "' . implode(', ', $diff) . '". ... | Checking that types from array matching with [boolean, integer, string, double, array, object]
@param array $types Indexed array
@return bool
@throws dbException | entailment |
public function fields(array $fields)
{
$fields = self::filter($fields);
$diff = array_diff($fields, Config::table($this->name)->fields());
if (empty($diff))
{
return true;
}
throw new dbException('Field(s) "' . implode(', ', $diff) . '" does n... | Checking that typed fields really exist in table
@param array $fields Indexed array
@return boolean
@throws dbException If field(s) does not exist | entailment |
public function field($name)
{
if (in_array($name, Config::table($this->name)->fields()))
{
return true;
}
throw new dbException('Field ' . $name . ' does not exists in table "' . $this->name . '"');
} | Checking that typed field really exist in table
@param string $name
@return boolean
@throws dbException If field does not exist | entailment |
public function exists()
{
if (!Data::table($this->name)->exists())
throw new dbException('Table "' . $this->name . '" does not exists');
if (!Config::table($this->name)->exists())
throw new dbException('Config "' . $this->name . '" does not exists');
return... | Checking that Table and Config exists and throw exceptions if not
@return boolean
@throws dbException | entailment |
public function type($name, $value)
{
$schema = Config::table($this->name)->schema();
if (array_key_exists($name, $schema) && $schema[$name] == gettype($value))
{
return true;
}
throw new dbException('Wrong data type');
} | Checking that typed field have correct type of value
@param string $name
@param mixed $value
@return boolean
@throws dbException If type is wrong | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.