sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
private function createWorker()
{
$worker = $this->factory->create();
$worker->start();
$this->workers->attach($worker, 0);
return $worker;
} | Creates a worker and adds them to the pool.
@return Worker The worker created. | entailment |
public function get(): Worker
{
if (!$this->isRunning()) {
throw new StatusError('The queue is not running.');
}
do {
if ($this->idleWorkers->isEmpty()) {
if ($this->getWorkerCount() >= $this->maxSize) {
// All possible workers busy, so shift from head (will be pushed back onto tail below).
$worker = $this->busyQueue->shift();
} else {
// Max worker count has not been reached, so create another worker.
$worker = $this->createWorker();
}
} else {
// Shift a worker off the idle queue.
$worker = $this->idleWorkers->shift();
}
if ($worker->isRunning()) {
break;
}
$this->workers->detach($worker);
} while (true);
$this->busyQueue->push($worker);
$this->workers[$worker] += 1;
return new Internal\PooledWorker($worker, $this->push);
} | {@inheritdoc} | entailment |
private function push(Worker $worker)
{
if (!$this->workers->contains($worker)) {
throw new InvalidArgumentError(
'The provided worker was not part of this queue.'
);
}
if (0 === ($this->workers[$worker] -= 1)) {
// Worker is completely idle, remove from busy queue and add to idle queue.
foreach ($this->busyQueue as $key => $busy) {
if ($busy === $worker) {
unset($this->busyQueue[$key]);
break;
}
}
$this->idleWorkers->push($worker);
}
} | Pushes the worker back into the queue.
@param \Icicle\Concurrent\Worker\Worker $worker
@throws \Icicle\Exception\InvalidArgumentError If the worker was not part of this queue. | entailment |
public function acquire(): \Generator
{
$tsl = function () {
// If there are no locks available or the wait queue is not empty,
// we need to wait our turn to acquire a lock.
if ($this->locks > 0) {
--$this->locks;
return false;
}
return true;
};
while ($this->locks < 1 || $this->synchronized($tsl)) {
yield from Coroutine\sleep(self::LATENCY_TIMEOUT);
}
return new Lock(function () {
$this->release();
});
} | Uses a double locking mechanism to acquire a lock without blocking. A
synchronous mutex is used to make sure that the semaphore is queried one
at a time to preserve the integrity of the semaphore itself. Then a lock
count is used to check if a lock is available without blocking.
If a lock is not available, we add the request to a queue and set a timer
to check again in the future. | entailment |
public function run(): \Generator
{
$task = yield from $this->channel->receive();
while ($task instanceof Task) {
$this->idle = false;
try {
$result = yield $task->run($this->environment);
} catch (\Throwable $exception) {
$result = new TaskFailure($exception);
}
yield from $this->channel->send($result);
$this->idle = true;
$task = yield from $this->channel->receive();
}
return $task;
} | @coroutine
@return \Generator | entailment |
public function getResult()
{
throw new PanicError(
sprintf(
'Uncaught exception in execution context of type "%s" with message "%s"',
$this->type,
$this->message
),
$this->code,
$this->trace
);
} | {@inheritdoc} | entailment |
public function getElementName(string $text = null): string
{
if ($text) {
$text = str_replace('.', '_', $text);
return '_' . $text;
}
return 'js_amiGridList_' . $this->id;
} | @param string|null $text
@return string | entailment |
public function setColumn(\Assurrussa\GridView\Interfaces\ColumnInterface $column): ColumnsInterface
{
$this->_columns[] = $column;
return $this;
} | @param ColumnInterface $column
@return ColumnInterface | entailment |
public function filterActions(\Illuminate\Database\Eloquent\Model $instance): array
{
$listButtons = [];
if ($this->count()) {
$buttons = $this->getActions();
foreach ($buttons as &$button) {
if ($button->getValues($instance)) {
$listButtons[] = $button->render();
unset($button);
}
}
}
return $listButtons;
} | The method gets the buttons for the grid table
@param \Illuminate\Database\Eloquent\Model $instance
@return array | entailment |
public function getInstance($provider)
{
$result = null;
if ($this->container->has('port1_hybrid_auth.' . strtolower($provider) . '_authentication_service')) {
$result = $this->container
->get('port1_hybrid_auth.' . strtolower($provider) . '_authentication_service');
}
return $result;
} | @param string $provider
@return AuthenticationServiceInterface|null
@throws \Exception | entailment |
public function handle()
{
try {
$options = array(
'server' => $this->option('server'),
'repo' => $this->option('repo')
);
$maneuver = new Maneuver($options);
$maneuver->mode(Maneuver::MODE_LIST);
$maneuver->start();
}
catch (Exception $e) {
$this->error($e->getMessage());
}
} | Execute the console command.
@return mixed | entailment |
public function add_entry_or_merge($entry)
{
if (is_array($entry)) {
$entry = new EntryTranslations($entry);
}
$key = $entry->key();
if (false === $key) {
return false;
}
if (isset($this->entries[$key])) {
$this->entries[$key]->merge_with($entry);
} else {
$this->entries[$key] = &$entry;
}
return true;
} | @param array|EntryTranslations $entry
@return bool | entailment |
public function set($key, $value)
{
$this->cacheIsFresh = false;
$this->store->set($key, $value);
} | {@inheritdoc} | entailment |
public function count()
{
if (!$this->cacheIsFresh) {
$this->cache = count($this->store->keys());
$this->cacheIsFresh = true;
}
return $this->cache;
} | {@inheritdoc} | entailment |
public function import_from_file($filename)
{
$reader = new FileReader($filename);
if (!$reader->is_resource()) {
return false;
}
$this->filename = (string) $filename;
return $this->import_from_reader($reader);
} | Fills up with the entries from MO file $filename.
@param string $filename MO file to load
@return bool Success | entailment |
public function export_to_file($filename)
{
$fh = fopen($filename, 'wb');
if (!$fh) {
return false;
}
$res = $this->export_to_file_handle($fh);
fclose($fh);
return $res;
} | @param string $filename
@return bool | entailment |
public function is_entry_good_for_export(EntryTranslations $entry)
{
if (empty($entry->translations)) {
return false;
}
if (!array_filter($entry->translations)) {
return false;
}
return true;
} | @param EntryTranslations $entry
@return bool | entailment |
public function export_to_file_handle($fh)
{
$entries = array_filter(
$this->entries,
array($this, 'is_entry_good_for_export')
);
ksort($entries);
$magic = 0x950412de;
$revision = 0;
$total = count($entries) + 1; // all the headers are one entry
$originals_lenghts_addr = 28;
$translations_lenghts_addr = $originals_lenghts_addr + 8 * $total;
$size_of_hash = 0;
$hash_addr = $translations_lenghts_addr + 8 * $total;
$current_addr = $hash_addr;
fwrite($fh, pack(
'V*',
$magic,
$revision,
$total,
$originals_lenghts_addr,
$translations_lenghts_addr,
$size_of_hash,
$hash_addr
));
fseek($fh, $originals_lenghts_addr);
// headers' msgid is an empty string
fwrite($fh, pack('VV', 0, $current_addr));
$current_addr++;
$originals_table = chr(0);
$reader = new NOOPReader();
foreach ($entries as $entry) {
$originals_table .= $this->export_original($entry) . chr(0);
$length = $reader->strlen($this->export_original($entry));
fwrite($fh, pack('VV', $length, $current_addr));
$current_addr += $length + 1; // account for the NULL byte after
}
$exported_headers = $this->export_headers();
fwrite($fh, pack(
'VV',
$reader->strlen($exported_headers),
$current_addr
));
$current_addr += strlen($exported_headers) + 1;
$translations_table = $exported_headers . chr(0);
foreach ($entries as $entry) {
$translations_table .= $this->export_translations($entry) . chr(0);
$length = $reader->strlen($this->export_translations($entry));
fwrite($fh, pack('VV', $length, $current_addr));
$current_addr += $length + 1;
}
fwrite($fh, $originals_table);
fwrite($fh, $translations_table);
return true;
} | @param resource $fh
@return true | entailment |
public function export_original(EntryTranslations $entry)
{
//TODO: warnings for control characters
$exported = $entry->singular;
if ($entry->is_plural) {
$exported .= chr(0) . $entry->plural;
}
if (!is_null($entry->context)) {
$exported = $entry->context . chr(4) . $exported;
}
return $exported;
} | @param EntryTranslations $entry
@return string | entailment |
public function export_translations(EntryTranslations $entry)
{
//TODO: warnings for control characters
return $entry->is_plural ? implode(chr(0), $entry->translations) : $entry->translations[0];
} | @param EntryTranslations $entry
@return string | entailment |
public function get_byteorder($magic)
{
// The magic is 0x950412de
$magic_little = (int) - 1794895138;
$magic_little_64 = (int) 2500072158;
// 0xde120495
$magic_big = ((int) - 569244523) & 0xFFFFFFFF;
if ($magic_little == $magic || $magic_little_64 == $magic) {
return 'little';
} elseif ($magic_big == $magic) {
return 'big';
} else {
return false;
}
} | @param int $magic
@return string|false | entailment |
public function import_from_reader(FileReader $reader)
{
$endian_string = $this->get_byteorder($reader->readint32());
if (false === $endian_string) {
return false;
}
$reader->setEndian($endian_string);
$endian = ('big' == $endian_string) ? 'N' : 'V';
$header = $reader->read(24);
if ($reader->strlen($header) != 24) {
return false;
}
// parse header
$header = unpack("{$endian}revision/{$endian}total/{$endian}originals_lenghts_addr/{$endian}translations_lenghts_addr/{$endian}hash_length/{$endian}hash_addr", $header);
if (!is_array($header)) {
return false;
}
// support revision 0 of MO format specs, only
if ($header['revision'] != 0) {
return false;
}
// seek to data blocks
$reader->seekto($header['originals_lenghts_addr']);
// read originals' indices
$originals_lengths_length = $header['translations_lenghts_addr'] - $header['originals_lenghts_addr'];
if ($originals_lengths_length != $header['total'] * 8) {
return false;
}
$originals = $reader->read($originals_lengths_length);
if ($reader->strlen($originals) != $originals_lengths_length) {
return false;
}
// read translations' indices
$translations_lenghts_length = $header['hash_addr'] - $header['translations_lenghts_addr'];
if ($translations_lenghts_length != $header['total'] * 8) {
return false;
}
$translations = $reader->read($translations_lenghts_length);
if ($reader->strlen($translations) != $translations_lenghts_length) {
return false;
}
// transform raw data into set of indices
$originals = $reader->str_split($originals, 8);
$translations = $reader->str_split($translations, 8);
// skip hash table
$strings_addr = $header['hash_addr'] + $header['hash_length'] * 4;
$reader->seekto($strings_addr);
$strings = $reader->read_all();
$reader->close();
for ($i = 0; $i < $header['total']; $i++) {
$o = unpack("{$endian}length/{$endian}pos", $originals[$i]);
$t = unpack("{$endian}length/{$endian}pos", $translations[$i]);
if (!$o || !$t) {
return false;
}
// adjust offset due to reading strings to separate space before
$o['pos'] -= $strings_addr;
$t['pos'] -= $strings_addr;
$original = $reader->substr($strings, $o['pos'], $o['length']);
$translation = $reader->substr($strings, $t['pos'], $t['length']);
if ('' === $original) {
$this->set_headers($this->make_headers($translation));
} else {
$entry = &static::make_entry($original, $translation);
$this->entries[$entry->key()] = &$entry;
}
}
return true;
} | @param FileReader $reader
@return bool | entailment |
public static function &make_entry($original, $translation)
{
$entry = new EntryTranslations();
// look for context
$parts = explode(chr(4), $original);
if (isset($parts[1])) {
$original = $parts[1];
$entry->context = $parts[0];
}
// look for plural original
$parts = explode(chr(0), $original);
$entry->singular = $parts[0];
if (isset($parts[1])) {
$entry->is_plural = true;
$entry->plural = $parts[1];
}
// plural translations are also separated by \0
$entry->translations = explode(chr(0), $translation);
return $entry;
} | Build a from original string and translation strings,
found in a MO file.
@param string $original original string to translate from MO file.
Might contain 0x04 as context separator or
0x00 as singular/plural separator
@param string $translation translation string from MO file.Might contain
0x00 as a plural translations separator
@return EntryTranslations New entry | entailment |
public static function forValue($value, $reason = '', $code = 0, Exception $cause = null)
{
return self::forType(is_object($value) ? get_class($value) : gettype($value), $reason, $code, $cause);
} | Creates a new exception for the given value.
@param mixed $value The value that could not be unserialized.
@param string $reason The reason why the value could not be
unserialized.
@param int $code The exception code.
@param Exception $cause The exception that caused this exception.
@return static The new exception. | entailment |
public function loginUser($customer)
{
$this->front->Request()->setPost('email', $customer->getEmail());
$this->front->Request()->setPost('passwordMD5', $customer->getPassword());
return $this->admin->sLogin(true);
} | Logs in the user for the given customer object
@param Customer $customer
@return array|bool
@throws \Exception | entailment |
public static function hasColumn(\Illuminate\Database\Eloquent\Model $model, string $column): bool
{
$table = $model->getTable();
$columns = app('cache')->remember('amigrid.columns.' . $table, 60, function () use ($table) {
return \Schema::getColumnListing($table);
});
return array_search($column, $columns) !== false;
} | Check if model's table has column
@param \Illuminate\Database\Eloquent\Model $model
@param string $column
@return bool | entailment |
public function set($key, $value)
{
KeyUtil::validate($key);
$serialized = $this->serialize->__invoke($value);
try {
$this->collection->replaceOne(
array('_id' => $key),
array('_id' => $key, 'value' => $serialized),
array('upsert' => true)
);
} catch (UnexpectedValueException $e) {
throw UnsupportedValueException::forType('binary', $this, 0, $e);
} catch (Exception $e) {
throw WriteException::forException($e);
}
} | {@inheritdoc} | entailment |
public function get($key, $default = null)
{
KeyUtil::validate($key);
try {
$document = $this->collection->findOne(
array('_id' => $key),
array('typeMap' => self::$typeMap)
);
} catch (Exception $e) {
throw ReadException::forException($e);
}
if (null === $document) {
return $default;
}
return $this->unserialize->__invoke($document['value']);
} | {@inheritdoc} | entailment |
public function getMultiple(array $keys, $default = null)
{
KeyUtil::validateMultiple($keys);
$values = array_fill_keys($keys, $default);
try {
$cursor = $this->collection->find(
array('_id' => array('$in' => array_values($keys))),
array('typeMap' => self::$typeMap)
);
foreach ($cursor as $document) {
$values[$document['_id']] = $this->unserialize->__invoke($document['value']);
}
} catch (UnserializationFailedException $e) {
throw $e;
} catch (Exception $e) {
throw ReadException::forException($e);
}
return $values;
} | {@inheritdoc} | entailment |
public function getMultipleOrFail(array $keys)
{
KeyUtil::validateMultiple($keys);
$values = array();
try {
$cursor = $this->collection->find(
array('_id' => array('$in' => array_values($keys))),
array('typeMap' => self::$typeMap)
);
foreach ($cursor as $document) {
$values[$document['_id']] = $this->unserialize->__invoke($document['value']);
}
} catch (UnserializationFailedException $e) {
throw $e;
} catch (Exception $e) {
throw ReadException::forException($e);
}
$notFoundKeys = array_diff($keys, array_keys($values));
if (count($notFoundKeys) > 0) {
throw NoSuchKeyException::forKeys($notFoundKeys);
}
return $values;
} | {@inheritdoc} | entailment |
public function remove($key)
{
KeyUtil::validate($key);
try {
$result = $this->collection->deleteOne(array('_id' => $key));
$deletedCount = $result->getDeletedCount();
} catch (Exception $e) {
throw WriteException::forException($e);
}
return $deletedCount > 0;
} | {@inheritdoc} | entailment |
public function exists($key)
{
KeyUtil::validate($key);
try {
$count = $this->collection->count(array('_id' => $key));
} catch (Exception $e) {
throw ReadException::forException($e);
}
return $count > 0;
} | {@inheritdoc} | entailment |
public function keys()
{
try {
$cursor = $this->collection->find(array(), array(
'projection' => array('_id' => 1),
));
$keys = array();
foreach ($cursor as $document) {
$keys[] = $document['_id'];
}
} catch (Exception $e) {
throw ReadException::forException($e);
}
return $keys;
} | {@inheritdoc} | entailment |
public function onCollectLessFiles (\Enlight_Event_EventArgs $args)
{
$lessDef = new LessDefinition(
[],
[
sprintf(
'%1$s%2$sResources%2$sviews%2$sfrontend%2$s_public%2$ssrc%2$sless%2$shybrid_auth.less',
$this->getPath(),
\DIRECTORY_SEPARATOR
)
],
$this->getPath()
);
return new ArrayCollection([$lessDef]);
} | @param \Enlight_Event_EventArgs $args
@return ArrayCollection | entailment |
public function set($key, $value)
{
$this->flags = null;
$this->store->set($key, $value);
} | {@inheritdoc} | entailment |
public function keys()
{
$keys = $this->store->keys();
if (null !== $this->flags) {
sort($keys, $this->flags);
}
return $keys;
} | {@inheritdoc} | entailment |
public function set($key, $value)
{
KeyUtil::validate($key);
try {
$existing = $this->exists($key);
} catch (Exception $e) {
throw WriteException::forException($e);
}
if (false === $existing) {
$this->doInsert($key, $value);
} else {
$this->doUpdate($key, $value);
}
} | {@inheritdoc} | entailment |
public function get($key, $default = null)
{
KeyUtil::validate($key);
$dbResult = $this->getDbRow($key);
if (null === $dbResult) {
return $default;
}
return Serializer::unserialize($dbResult['meta_value']);
} | {@inheritdoc} | entailment |
public function getOrFail($key)
{
KeyUtil::validate($key);
$dbResult = $this->getDbRow($key);
if (null === $dbResult) {
throw NoSuchKeyException::forKey($key);
}
return Serializer::unserialize($dbResult['meta_value']);
} | {@inheritdoc} | entailment |
public function getMultiple(array $keys, $default = null)
{
KeyUtil::validateMultiple($keys);
// Normalize indices of the array
$keys = array_values($keys);
$data = $this->doGetMultiple($keys);
$results = array();
$resolved = array();
foreach ($data as $row) {
$results[$row['meta_key']] = Serializer::unserialize($row['meta_value']);
$resolved[$row['meta_key']] = $row['meta_key'];
}
$notResolvedArr = array_diff($keys, $resolved);
foreach ($notResolvedArr as $notResolved) {
$results[$notResolved] = $default;
}
return $results;
} | {@inheritdoc} | entailment |
public function getMultipleOrFail(array $keys)
{
KeyUtil::validateMultiple($keys);
// Normalize indices of the array
$keys = array_values($keys);
$data = $this->doGetMultiple($keys);
$results = array();
$resolved = array();
foreach ($data as $row) {
$results[$row['meta_key']] = Serializer::unserialize($row['meta_value']);
$resolved[] = $row['meta_key'];
}
$notResolvedArr = array_diff($keys, $resolved);
if (!empty($notResolvedArr)) {
throw NoSuchKeyException::forKeys($notResolvedArr);
}
return $results;
} | {@inheritdoc} | entailment |
public function remove($key)
{
KeyUtil::validate($key);
try {
$result = $this->connection->delete($this->tableName, array('meta_key' => $key));
} catch (Exception $e) {
throw WriteException::forException($e);
}
return $result === 1;
} | {@inheritdoc} | entailment |
public function exists($key)
{
KeyUtil::validate($key);
try {
$result = $this->connection->fetchAssoc('SELECT * FROM '.$this->tableName.' WHERE meta_key = ?', array($key));
} catch (Exception $e) {
throw ReadException::forException($e);
}
return $result ? true : false;
} | {@inheritdoc} | entailment |
public function clear()
{
try {
$stmt = $this->connection->query('DELETE FROM '.$this->tableName);
$stmt->execute();
} catch (Exception $e) {
throw WriteException::forException($e);
}
} | {@inheritdoc} | entailment |
public function keys()
{
try {
$stmt = $this->connection->query('SELECT meta_key FROM '.$this->tableName);
$result = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (Exception $e) {
throw ReadException::forException($e);
}
return $result;
} | {@inheritdoc} | entailment |
public function getTableForCreate()
{
$schema = new Schema();
$table = $schema->createTable($this->getTableName());
$table->addColumn('id', 'integer', array('autoincrement' => true));
$table->addColumn('meta_key', 'string', array('length' => 255));
$table->addColumn('meta_value', 'object');
$table->setPrimaryKey(array('id'));
$table->addUniqueIndex(array('meta_key'));
return $table;
} | Object Representation of the table used in this class.
@return Table | entailment |
public function setActionDelete(
string $route = null,
array $params = [],
string $label = '',
string $title = 'Deleted',
string $class = 'btn btn-danger btn-sm flat',
string $icon = 'fa fa-times'
): ButtonInterface {
$this->setAction(self::TYPE_ACTION_DELETE)
->setTypeForm()
->setLabel($label)
->setTitle($title)
->setRoute($route, $params)
->setClass($class)
->setIcon($icon);
return $this;
} | @param string|null $route
@param array $params
@param string $label
@param string $title
@param string $class
@param string $icon
@return ButtonInterface | entailment |
public function setActionEdit(
string $route = null,
array $params = [],
string $label = '',
string $title = 'Edit',
string $class = '',
string $icon = 'fa fa-pencil'
): ButtonInterface {
$this->setAction(self::TYPE_ACTION_EDIT)
->setRoute($route, $params)
->setLabel($label)
->setTitle($title)
->setClass($class)
->setIcon($icon);
return $this;
} | @param string|null $route
@param array $params
@param string $label
@param string $title
@param string $class
@param string $icon
@return ButtonInterface | entailment |
public function setActionCustom(
string $url = null,
string $label = '',
string $class = 'btn btn-primary btn-outline-primary btn-sm flat',
string $icon = 'fa fa-paw'
): ButtonInterface {
if (!$url) {
$url = '#';
}
$this->setAction(self::TYPE_ACTION_CUSTOM)
->setUrl($url)
->setLabel($label)
->setClass($class)
->setIcon($icon);
return $this;
} | @param string|null $url
@param string $label
@param string $class
@param string $icon
@return ButtonInterface | entailment |
public function setButtonExport(string $url = null): ButtonInterface
{
$addUrl = 'export=1';
if (!$url) {
$url = url()->current();
}
if ($array = request()->except('export')) {
$url .= '?' . http_build_query($array);
}
$addUrl = \Illuminate\Support\Str::is('*?*', $url) ? '&' . $addUrl : '?' . $addUrl;
$text = GridView::trans('grid.export');
return $this->setActionCustom($url . $addUrl, $text, 'btn btn-default btn-outline-primary', 'fa fa-download')
->setAction(self::TYPE_ACTION_EXPORT)
->setId('js_amiExportButton');
} | @param string|null $url
@return ButtonInterface | entailment |
public function setButtonCreate(string $url): ButtonInterface
{
$text = GridView::trans('grid.create');
return $this->setActionCustom($url, $text, 'btn btn-primary btn-outline-primary', 'fa fa-plus')
->setAction(self::TYPE_ACTION_CREATE);
} | @param string $url
@return ButtonInterface | entailment |
public function setButtonCheckboxAction(
string $url = null,
string $addPostUrl = null,
string $text = null,
string $confirmText = null,
string $class = null,
string $icon = ''
): ButtonInterface {
$addPostUrl = $addPostUrl ?: '?deleted=';
$class = $class ?: 'btn btn-default btn-outline-primary js_btnCustomAction js_linkDelete';
$text = $text ?: GridView::trans('grid.selectDelete');
$confirmText = $confirmText ?: GridView::trans('grid.clickDelete');
return $this->setActionCustom($url . $addPostUrl, $text, $class, $icon)
->setAction(self::TYPE_ACTION_CUSTOM)
->setConfirmText($confirmText)
->setOptions([
'data-url' => $this->getUrl(),
'data-confirm' => $confirmText,
]);
} | @param string|null $url
@param string|null $addPostUrl
@param string|null $view
@param string|null $text
@param string|null $confirmText
@param string|null $class
@param string|null $icon
@return \Illuminate\Contracts\Support\Renderable | entailment |
public function setMethod(string $method = 'POST'): ButtonInterface
{
if ($this->isVisibility()) {
$this->method = $method;
}
return $this;
} | @param string $method
@return ButtonInterface | entailment |
public function setAction(string $action = ''): ButtonInterface
{
if ($this->isVisibility()) {
$this->action = $action;
}
return $this;
} | @param string $action
@return ButtonInterface | entailment |
public function setLabel(string $label = null): ButtonInterface
{
if ($this->isVisibility()) {
$this->label = $label;
}
return $this;
} | @param string|null $label
@return ButtonInterface | entailment |
public function setIcon(string $icon = null): ButtonInterface
{
if ($this->isVisibility()) {
$this->icon = $icon;
}
return $this;
} | @param string|null $icon
@return ButtonInterface | entailment |
public function setTitle(string $text = null): ButtonInterface
{
if ($this->isVisibility()) {
$this->title = $text;
}
return $this;
} | @param string|null $text
@return ButtonInterface | entailment |
public function setId(string $id = null): ButtonInterface
{
if ($this->isVisibility()) {
$this->id = $id;
}
return $this;
} | @param string|null $id
@return ButtonInterface | entailment |
public function setAddString(string $string): ButtonInterface
{
if ($this->isVisibility()) {
$this->strings[] = $string;
}
return $this;
} | @param string $string
@return ButtonInterface | entailment |
public function setConfirmText(
string $text = null,
string $colorOk = null,
string $colorCancel = null,
string $textOk = null,
string $textCancel = null
): ButtonInterface {
if ($this->isVisibility()) {
if ($text) {
$this->confirmText = $text;
}
if ($colorOk) {
$this->confirmColorOk = $colorOk;
}
if ($colorCancel) {
$this->confirmColorCancel = $colorCancel;
}
if ($textOk) {
$this->confirmTextOk = $textOk;
}
if ($textCancel) {
$this->confirmTextCancel = $textCancel;
}
}
return $this;
} | @param string|null $text
@param string|null $colorOk
@param string|null $colorCancel
@param string|null $textOk
@param string|null $textCancel
@return ButtonInterface | entailment |
public function setUrl(string $url = '#'): ButtonInterface
{
if ($this->isVisibility()) {
// if($this->url !== null) {
// if(strpos($this->url, '://') !== false) {
// return $this;
// }
// }
$this->url = $url;
}
return $this;
} | @param string $url
@return ButtonInterface | entailment |
public function setRoute(string $route = null, array $params = []): ButtonInterface
{
if ($this->isVisibility()) {
if ($route === null) {
$url = '#';
} else {
$url = '#';
if (app('router')->has($route)) {
$url = route($route, $params);
} else {
$this->setVisible(false);
}
}
$this->setUrl($url);
}
return $this;
} | If not found route, the button is not visible automatically
@param string|null $route
@param array $params
@return ButtonInterface | entailment |
public function setType(string $type): ButtonInterface
{
if ($this->isVisibility()) {
$this->type = $type;
}
return $this;
} | @param string $type
@return ButtonInterface | entailment |
public function getValues(\Illuminate\Database\Eloquent\Model $instance = null): bool
{
$this->_instance = $instance;
if ($this->isHandler()) {
return $this->getHandler();
}
return true;
} | @param \Illuminate\Database\Eloquent\Model|null $instance
@return bool | entailment |
public function render(string $view = null, array $params = null): \Illuminate\Contracts\Support\Renderable
{
$view = $view ? $view : 'column.treeControl';
$params = $params ? $params : $this->toArray();
return GridView::view($view, $params);
} | @param string $view
@param array|null $params
@return Renderable | entailment |
protected function parse($str)
{
$pos = 0;
$len = strlen($str);
// Convert infix operators to postfix using the shunting-yard algorithm.
$output = array();
$stack = array();
while ($pos < $len) {
$next = substr($str, $pos, 1);
switch ($next) {
// Ignore whitespace
case ' ':
case "\t":
$pos++;
break;
// Variable (n)
case 'n':
$output[] = array('var');
$pos++;
break;
// Parentheses
case '(':
$stack[] = $next;
$pos++;
break;
case ')':
$found = false;
while (!empty($stack)) {
$o2 = $stack[count($stack) - 1];
if ($o2 !== '(') {
$output[] = array('op', array_pop($stack));
continue;
}
// Discard open paren.
array_pop($stack);
$found = true;
break;
}
if (!$found) {
throw new Exception('Mismatched parentheses');
}
$pos++;
break;
// Operators
case '|':
case '&':
case '>':
case '<':
case '!':
case '=':
case '%':
case '?':
$end_operator = strspn($str, self::OP_CHARS, $pos);
$operator = substr($str, $pos, $end_operator);
if (!array_key_exists($operator, self::$op_precedence)) {
throw new Exception(sprintf('Unknown operator "%s"', $operator));
}
while (!empty($stack)) {
$o2 = $stack[count($stack) - 1];
// Ternary is right-associative in C
if ($operator === '?:' || $operator === '?') {
if (self::$op_precedence[$operator] >= self::$op_precedence[$o2]) {
break;
}
} elseif (self::$op_precedence[$operator] > self::$op_precedence[$o2]) {
break;
}
$output[] = array('op', array_pop($stack));
}
$stack[] = $operator;
$pos += $end_operator;
break;
// Ternary "else"
case ':':
$found = false;
$s_pos = count($stack) - 1;
while ($s_pos >= 0) {
$o2 = $stack[$s_pos];
if ($o2 !== '?') {
$output[] = array('op', array_pop($stack));
$s_pos--;
continue;
}
// Replace.
$stack[$s_pos] = '?:';
$found = true;
break;
}
if (!$found) {
throw new Exception('Missing starting "?" ternary operator');
}
$pos++;
break;
// Default - number or invalid
default:
if ($next >= '0' && $next <= '9') {
$span = strspn($str, self::NUM_CHARS, $pos);
$output[] = array('value', intval(substr($str, $pos, $span)));
$pos += $span;
break;
}
throw new Exception(sprintf('Unknown symbol "%s"', $next));
}
}
while (!empty($stack)) {
$o2 = array_pop($stack);
if ($o2 === '(' || $o2 === ')') {
throw new Exception('Mismatched parentheses');
}
$output[] = array('op', $o2);
}
$this->tokens = $output;
} | Parse a Plural-Forms string into tokens.
Uses the shunting-yard algorithm to convert the string to Reverse Polish
Notation tokens.
@param string $str String to parse.
@throws Exception | entailment |
public function get($num)
{
if (isset($this->cache[$num])) {
return $this->cache[$num];
}
return $this->cache[$num] = $this->execute($num);
} | Get the plural form for a number.
Caches the value for repeated calls.
@param int $num Number to get plural form for.
@return int PluralForms form value.
@throws Exception | entailment |
public function execute($n)
{
$stack = array();
$i = 0;
$total = count($this->tokens);
while ($i < $total) {
$next = $this->tokens[$i];
$i++;
if ($next[0] === 'var') {
$stack[] = $n;
continue;
} elseif ($next[0] === 'value') {
$stack[] = $next[1];
continue;
}
// Only operators left.
switch ($next[1]) {
case '%':
$v2 = array_pop($stack);
$v1 = array_pop($stack);
$stack[] = $v1 % $v2;
break;
case '||':
$v2 = array_pop($stack);
$v1 = array_pop($stack);
$stack[] = $v1 || $v2;
break;
case '&&':
$v2 = array_pop($stack);
$v1 = array_pop($stack);
$stack[] = $v1 && $v2;
break;
case '<':
$v2 = array_pop($stack);
$v1 = array_pop($stack);
$stack[] = $v1 < $v2;
break;
case '<=':
$v2 = array_pop($stack);
$v1 = array_pop($stack);
$stack[] = $v1 <= $v2;
break;
case '>':
$v2 = array_pop($stack);
$v1 = array_pop($stack);
$stack[] = $v1 > $v2;
break;
case '>=':
$v2 = array_pop($stack);
$v1 = array_pop($stack);
$stack[] = $v1 >= $v2;
break;
case '!=':
$v2 = array_pop($stack);
$v1 = array_pop($stack);
$stack[] = $v1 != $v2;
break;
case '==':
$v2 = array_pop($stack);
$v1 = array_pop($stack);
$stack[] = $v1 == $v2;
break;
case '?:':
$v3 = array_pop($stack);
$v2 = array_pop($stack);
$v1 = array_pop($stack);
$stack[] = $v1 ? $v2 : $v3;
break;
default:
throw new Exception(sprintf('Unknown operator "%s"', $next[1]));
}
}
if (count($stack) !== 1) {
throw new Exception('Too many values remaining on the stack');
}
return (int) $stack[0];
} | Execute the plural form function.
@param int $n Variable "n" to substitute.
@throws Exception
@return int PluralForms form value. | entailment |
public static function forType($type, $reason = '', $code = 0, Exception $cause = null)
{
return new static(sprintf(
'Could not serialize value of type %s%s',
$type,
$reason ? ': '.$reason : '.'
), $code, $cause);
} | Creates a new exception for the given value type.
@param string $type The type that could not be serialized.
@param string $reason The reason why the value could not be
unserialized.
@param int $code The exception code.
@param Exception $cause The exception that caused this exception.
@return static The new exception. | entailment |
public function fetch(
\Illuminate\Database\Eloquent\Builder $query,
array $fields = null,
string $filename = null,
int $cacheSecond = 60,
string $format = 'csv',
string $contentType = 'text/csv'
): bool {
$keyCache = class_basename($query->getModel());
$pathCache = storage_path('app') . DIRECTORY_SEPARATOR . 'fetch';
$dataString = '';
$fieldsString = '';
$fields = $fields ? [$fields] : [$query->getModel()->getFillable()];
$fields = \Illuminate\Support\Arr::first($fields);
array_walk($fields, function ($value, $key) use (&$fieldsString) {
$fieldsString .= '"' . ($this->isInt($key) ? $value : $key) . '";';
});
$dataString .= $fieldsString . PHP_EOL;
$fileCache = $pathCache . DIRECTORY_SEPARATOR . md5($keyCache . $dataString);
$timeCacheExpire = $cacheSecond;
if (file_exists($fileCache) && time() - filemtime($fileCache) < $timeCacheExpire) {
$dataString = file_get_contents($fileCache);
} else {
$query->chunk(1000, function ($data) use ($fields, &$dataString) {
foreach ($data as $item) {
$dataExport = [];
if ($data) {
foreach ($fields as $field) {
// достаем значение по пути $field или выполняем функцию $field для $data
$dataExport[] = A::value($item, $field);
}
} else {
continue;
}
$dataString .= A::join($dataExport, ';', '"', '"') . "\n";
}
});
if (!empty($dataString)) {
if (!file_exists($pathCache)) {
F::createDirectory($pathCache);
}
file_put_contents($fileCache, $dataString);
}
}
if (!$filename) {
$filename = 'export' . $keyCache . '.' . $format;
}
header('Content-Type: ' . $contentType);
header('Accept-Ranges: bytes');
header('Content-Length: ' . strlen($dataString));
header('Content-disposition: attachment; filename="' . $filename . '"');
echo $dataString;
return true;
} | Создаем текст для экспорта данных и выдаем в браузер для скачивания
пример array $fields = [
'ID' => 'id',
'Время звонка' => 'setup_at',
0 => 'brand.name',
'Гости' => function() {return 'name';},
];
@param \Illuminate\Database\Eloquent\Builder $query модель с критериями для получения данных
@param bool|array $fields список полей для экспорта,
значение в массиве м.б. или название поля модели или путь до
поля релейшена или функция для создания значения. Если
значение задано с ключом, то ключ используется для первой
строки описания полей. Если значение функция, то оно
обязательно д.б. с ключом.
@param string $filename
@param int $cacheSecond
@param string $format
@param string $contentType | entailment |
protected function isInt($value): bool
{
// При преобразовании в int игнорируются все окружающие пробелы, но is_numeric допускает только пробелы в начале
return is_bool($value) ? false : filter_var($value, FILTER_VALIDATE_INT) !== false;
} | Проверяет содержит ли переменная целое значение.
Возвращает true если типа integer или содержит только допустимые символы без учета начальных и конечных пробелов
Не обрабатывает неопределенные значения! Для безопасной проверки элемента массива или свойства объекта используйте вместе с value().
@param integer|string $val переменная
@return boolean | entailment |
public function compare()
{
$remoteRevision = null;
$filesToUpload = array();
$filesToDelete = array();
// The revision file goes inside the submodule.
if ($this->isSubmodule) {
$this->revisionFile = $this->isSubmodule . '/' . $this->revisionFile;
}
if ($this->bridge->exists($this->revisionFile)) {
$remoteRevision = $this->bridge->get($this->revisionFile);
$message = "\r\n» Taking it from '" . substr($remoteRevision, 0, 7) . "'";
} else {
$message = "\r\n» Fresh deployment - grab a coffee";
}
// A remote version exists.
if ($remoteRevision) {
// Get the files from the diff.
$output = $this->git->diff($remoteRevision);
foreach ($output as $line) {
// Added, changed or modified.
if ($line[0] == 'A' or $line[0] == 'C' or $line[0] == 'M') {
$filesToUpload[] = trim(substr($line, 1));
}
// Deleted.
elseif ($line[0] == 'D') {
$filesToDelete[] = trim(substr($line, 1));
}
// Unknown status.
else {
throw new Exception("Unknown git-diff status: {$line[0]}");
}
}
}
// No remote version. Get all files.
else {
$filesToUpload = $this->git->files();
}
// Remove ignored files from the list of uploads.
$filesToUpload = array_diff($filesToUpload, $this->ignoredFiles);
$this->filesToUpload = $filesToUpload;
$this->filesToDelete = $filesToDelete;
return $message;
} | Compares local revision to the remote one and
builds files to upload and delete
@throws Exception if unknown git diff status
@return string | entailment |
public function upload($file)
{
if ($this->isSubmodule) {
$file = $this->isSubmodule.'/'.$file;
}
$dir = explode('/', dirname($file));
$path = '';
$pathThatExists = null;
$output = array();
// Skip basedir or parent.
if ($dir[0] != '.' and $dir[0] != '..') {
// Iterate through directory pieces.
for ($i = 0, $count = count($dir); $i < $count; $i++) {
$path .= $dir[$i].'/';
if (!isset($pathThatExists[$path])) {
$origin = $this->bridge->pwd();
// The directory doesn't exist.
if (! $this->bridge->exists($path)) {
// Attempt to create the directory.
$this->bridge->mkdir($path);
$output[] = "Created directoy '$path'.'";
}
// The directory exists.
else {
$this->bridge->cd($path);
}
$pathThatExists[$path] = true;
$this->bridge->cd($origin);
}
}
}
$uploaded = false;
$attempts = 1;
// Loop until $uploaded becomes a valid
// resource.
while (!$uploaded) {
// Attempt to upload the file 10 times
// and exit if it fails.
if ($attempts == 10) {
$output[] = "Tried to upload $file 10 times, and failed 10 times. Something is wrong, so I'm going to stop executing now.";
return $output;
}
$data = file_get_contents($file);
$uploaded = $this->bridge->put($data, $file);
if (!$uploaded) {
$attempts++;
}
}
$output[] = "√ \033[0;37m{$file}\033[0m \033[0;32muploaded\033[0m";
return $output;
} | Uploads file
@param string $file
@return array | entailment |
public function writeRevision()
{
if ($this->syncCommit) {
$localRevision = $this->syncCommit;
} else {
$localRevision = $this->git->localRevision()[0];
}
try {
$this->bridge->put($localRevision, $this->revisionFile);
}
catch (Exception $e) {
throw new Exception("Could not update the revision file on server: {$e->getMessage()}");
}
} | Writes latest revision to the remote
revision file
@throws Exception if can't update revision file | entailment |
public function setButton(\Assurrussa\GridView\Interfaces\ButtonInterface $button): ButtonsInterface
{
$this->_buttons[] = $button;
return $this;
} | @param ButtonInterface $button
@return ButtonsInterface | entailment |
public static function forKey($key, Exception $cause = null)
{
return new static(sprintf(
'Expected a key of type integer or string. Got: %s',
is_object($key) ? get_class($key) : gettype($key)
), 0, $cause);
} | Creates an exception for an invalid key.
@param mixed $key The invalid key.
@param Exception|null $cause The exception that caused this exception.
@return static The created exception. | entailment |
public function setQuery(\Illuminate\Database\Eloquent\Builder $query): GridInterface
{
$this->_query = $query;
$this->_model = $this->_query->getModel();
$this->pagination->setQuery($this->_query);
return $this;
} | @param \Illuminate\Database\Eloquent\Builder $query
@return GridInterface | entailment |
public function column(string $name = null, string $title = null): Column
{
$column = new Column();
$this->columns->setColumn($column);
if ($name) {
$column->setKey($name);
}
if ($title) {
$column->setValue($title);
}
return $column;
} | @param string $name
@param string $title
@return Column | entailment |
public function columnActions(Callable $action, string $value = null): ColumnInterface
{
return $this->column(Column::ACTION_NAME, $value)->setActions($action);
} | @param callable $action
@param string|null $value
@return ColumnInterface | entailment |
public function render(array $data = [], string $path = 'gridView', array $mergeData = []): string
{
if (request()->ajax() || request()->wantsJson()) {
$path = $path === 'gridView' ? 'part.grid' : $path;
}
return static::view($path, $data, $mergeData)->render();
} | @param array $data
@param string $path
@param array $mergeData
@return string
@throws \Throwable | entailment |
public function renderFirst(array $data = [], string $path = 'gridView', array $mergeData = []): string
{
$path = $path === 'gridView' ? 'part.tableTrItem' : $path;
$headers = $data['data']->headers;
$item = (array)$data['data']->data;
return static::view($path, [
'headers' => $headers,
'item' => $item,
], $mergeData)->render();
} | @param array $data
@param string $path
@param array $mergeData
@return string
@throws \Throwable | entailment |
public static function view(string $view = null, array $data = [], array $mergeData = []): Renderable
{
return view(self::NAME . '::' . $view, $data, $mergeData);
} | Get the evaluated view contents for the given view.
@param string|null $view
@param array $data
@param array $mergeData
@return Renderable | entailment |
public static function trans(string $id = null, array $parameters = [], string $locale = null): string
{
return (string)trans(self::NAME . '::' . $id, $parameters, $locale);
} | Translate the given message.
@param string|null $id
@param array $parameters
@param string|null $locale
@return string | entailment |
public function get(): \Assurrussa\GridView\Helpers\GridViewResult
{
$gridViewResult = $this->_getGridView();
$gridViewResult->data = $this->pagination->get($this->page, $this->limit);
$gridViewResult->pagination = $this->_getPaginationRender();
$gridViewResult->simple = false;
return $gridViewResult;
} | Return get result
@return \Assurrussa\GridView\Helpers\GridViewResult
@throws ColumnsException
@throws QueryException | entailment |
public function getSimple(bool $isCount = false): \Assurrussa\GridView\Helpers\GridViewResult
{
$gridViewResult = $this->_getGridView($isCount);
$gridViewResult->data = $this->pagination->getSimple($this->page, $this->limit, $isCount);
$gridViewResult->pagination = $this->_getPaginationRender();
$gridViewResult->simple = true;
return $gridViewResult;
} | @param bool $isCount
@return Helpers\GridViewResult
@throws ColumnsException
@throws QueryException | entailment |
private function _getGridView(bool $isCount = false): \Assurrussa\GridView\Helpers\GridViewResult
{
$this->_fetch();
$gridViewResult = new \Assurrussa\GridView\Helpers\GridViewResult();
$gridViewResult->id = $this->getId();
$gridViewResult->ajax = $this->ajax;
$gridViewResult->formAction = $this->getFormAction();
$gridViewResult->requestParams = $this->requestParams;
$gridViewResult->headers = $this->columns->toArray();
$gridViewResult->buttonCreate = $this->buttons->getButtonCreate();
$gridViewResult->buttonExport = $this->buttons->getButtonExport();
$gridViewResult->buttonCustoms = $this->buttons->render();
$gridViewResult->inputCustoms = $this->inputs->render();
$gridViewResult->filter = $this->_request->toArray();
$gridViewResult->page = $this->page;
$gridViewResult->orderBy = $this->orderBy;
$gridViewResult->search = $this->search;
$gridViewResult->limit = $this->limit;
$gridViewResult->sortName = $this->sortName;
$gridViewResult->counts = $this->counts;
$gridViewResult->searchInput = $this->searchInput;
return $gridViewResult;
} | @param bool $isCount
@return Helpers\GridViewResult
@throws ColumnsException
@throws QueryException | entailment |
private function _getConfig(string $key, $default = null)
{
if (isset($this->_config[$key])) {
return $this->_config[$key];
}
return $default;
} | @param string $key
@param mixed|null $default
@return mixed|null | entailment |
private function _filterScopes(): \Illuminate\Support\Collection
{
if (count($this->_request) > 0) {
foreach ($this->_request as $scope => $value) {
if (!empty($value) || $value === 0 || $value === '0') {
$value = (string)$value;
//checked scope method for model
if (method_exists($this->_model, 'scope' . \Illuminate\Support\Str::camel($scope))) {
$this->_query->{\Illuminate\Support\Str::camel($scope)}($value);
} else {
$this->_filterSearch($scope, $value, $this->filter['operator'], $this->filter['beforeValue'],
$this->filter['afterValue']);
}
}
}
$this->_query->addSelect($this->_model->getTable() . '.*');
}
return $this->_request;
} | Very simple filtration scopes.<br><br>
Example:
* method - `public function scopeCatalogId($int) {}`
@return \Illuminate\Support\Collection | entailment |
private function _filterSearch(
string $search = null,
string $value = null,
string $operator = '=',
string $beforeValue = '',
string $afterValue = ''
): void {
if ($search) {
if ($value) {
$value = trim($value);
}
$search = trim($search);
// поиск по словам
$this->_query->where(function ($query) use (
$search,
$value,
$operator,
$beforeValue,
$afterValue
) {
/** @var \Illuminate\Database\Eloquent\Builder $query */
$tableName = $this->_model->getTable();
if ($value) {
if (Model::hasColumn($this->_model, $search)) {
$query->orWhere($tableName . '.' . $search, $operator, $beforeValue . $value . $afterValue);
}
} elseif ($this->isStrictMode()) {
if (method_exists($this->_model, 'toFieldsAmiGrid')) {
$list = $this->_model->toFieldsAmiGrid();
foreach ($list as $column) {
if (Model::hasColumn($this->_model, $column)) {
$query->orWhere($tableName . '.' . $column, $operator, $beforeValue . $search . $afterValue);
}
}
}
} else {
$list = \Schema::getColumnListing($tableName);
foreach ($list as $column) {
if ($this->_hasFilterExecuteForCyrillicColumn($search, $column)) {
continue;
}
if (Model::hasColumn($this->_model, $column)) {
$query->orWhere($tableName . '.' . $column, $operator, $beforeValue . $search . $afterValue);
}
}
}
});
}
} | The method filters the data according
@param string|int|null $search
@param mixed|null $value word
@param string $operator equal sign - '=', 'like' ...
@param string $beforeValue First sign before value
@param string $afterValue Last sign after value | entailment |
private function _hasFilterExecuteForCyrillicColumn(string $search, string $column): bool
{
if (!preg_match("/[\w]+/i", $search) && \Assurrussa\GridView\Enums\FilterEnum::hasFilterExecuteForCyrillicColumn($column)) {
return true;
}
return false;
} | Because of problems with the search Cyrillic, crutch.<br><br>
Из-за проблем поиска с кириллицей, костыль.
@param string $search
@param string $column
@return bool | entailment |
private function _prepareColumns(): void
{
if (method_exists($this->_model, 'toFieldsAmiGrid')) {
$lists = $this->_model->toFieldsAmiGrid();
} else {
$lists = \Schema::getColumnListing($this->_model->getTable());
}
if ($this->isVisibleColumn()) {
$lists = array_diff($lists, $this->_model->getHidden());
}
foreach ($lists as $key => $list) {
$this->column($list, $list)
->setDateActive(true)
->setSort(true);
}
$this->columnActions(function ($data) {
$buttons = [];
if ($this->_getConfig('routes')) {
$pathNameForModel = strtolower(\Illuminate\Support\Str::plural(\Illuminate\Support\Str::camel(class_basename($data))));
$buttons[] = $this->columnAction()
// ->setActionDelete('amigrid.delete', [$pathNameForModel, $data->id])
->setUrl('/' . $pathNameForModel . '/delete')
->setLabel('delete');
$buttons[] = $this->columnAction()
// ->setActionShow('amigrid.show', [$pathNameForModel, $data->id])
->setUrl('/' . $pathNameForModel)
->setLabel('show')
// ->setHandler(function ($data) {
// return $data->id % 2;
// })
;
$buttons[] = $this->columnAction()
// ->setActionEdit('amigrid.edit', [$pathNameForModel, $data->id])
->setUrl('/' . $pathNameForModel . '/edit')
->setLabel('edit');
}
return $buttons;
});
if ($this->_getConfig('routes')) {
$pathNameForModel = strtolower(\Illuminate\Support\Str::plural(\Illuminate\Support\Str::camel(class_basename($this->_model))));
$this->button()->setButtonCreate('/' . $pathNameForModel . '/create');
}
} | The method takes the default column for any model<br><br>
Метод получает колонки по умолчанию для любой модели | entailment |
public static function serialize($value)
{
if (is_resource($value)) {
throw SerializationFailedException::forValue($value);
}
try {
$serialized = serialize($value);
} catch (Exception $e) {
throw SerializationFailedException::forValue($value, $e->getMessage(), $e->getCode(), $e);
}
return $serialized;
} | Serializes a value.
@param mixed $value The value to serialize.
@return string The serialized value.
@throws SerializationFailedException If the value cannot be serialized. | entailment |
public static function unserialize($serialized)
{
if (!is_string($serialized)) {
throw UnserializationFailedException::forValue($serialized);
}
$errorMessage = null;
$errorCode = 0;
set_error_handler(function ($errno, $errstr) use (&$errorMessage, &$errorCode) {
$errorMessage = $errstr;
$errorCode = $errno;
});
$value = unserialize($serialized);
restore_error_handler();
if (null !== $errorMessage) {
if (false !== $pos = strpos($errorMessage, '): ')) {
// cut "unserialize(%path%):" to make message more readable
$errorMessage = substr($errorMessage, $pos + 3);
}
throw UnserializationFailedException::forValue($serialized, $errorMessage, $errorCode);
}
return $value;
} | Unserializes a value.
@param mixed $serialized The serialized value.
@return string The unserialized value.
@throws UnserializationFailedException If the value cannot be unserialized. | entailment |
public function key()
{
if (null === $this->singular || '' === $this->singular) {
return false;
}
// Prepend context and EOT, like in MO files
$key = !$this->context ? $this->singular : $this->context . chr(4) . $this->singular;
// Standardize on \n line endings
$key = str_replace(array("\r\n", "\r"), "\n", $key);
return $key;
} | Generates a unique key for this entry.
@return string|bool the key or false if the entry is empty | entailment |
public function export_headers()
{
$header_string = '';
foreach ($this->headers as $header => $value) {
$header_string .= "$header: $value\n";
}
$poified = self::poify($header_string);
if ($this->comments_before_headers) {
$before_headers = self::prepend_each_line(
rtrim($this->comments_before_headers) . "\n",
'# '
);
} else {
$before_headers = '';
}
return rtrim("{$before_headers}msgid \"\"\nmsgstr $poified");
} | Exports headers to a PO entry.
@return string msgid/msgstr PO entry for this PO file headers, doesn't
contain newline at the end | entailment |
public function export($include_headers = true)
{
$res = '';
if ($include_headers) {
$res .= $this->export_headers();
$res .= "\n\n";
}
$res .= $this->export_entries();
return $res;
} | Exports the whole PO file as a string.
@param bool $include_headers whether to include the headers in the
export
@return string ready for inclusion in PO file string for headers and all
the enrtries | entailment |
public function export_to_file($filename, $include_headers = true)
{
$fh = fopen($filename, 'w');
if (false === $fh) {
return false;
}
$export = $this->export($include_headers);
$res = fwrite($fh, $export);
if (false === $res) {
return false;
}
return fclose($fh);
} | Same as {@link export}, but writes the result to a file.
@param string $filename where to write the PO string
@param bool $include_headers whether to include tje headers in the
export
@return bool true on success, false on error | entailment |
public static function poify($string)
{
$quote = '"';
$slash = '\\';
$newline = "\n";
$replaces = array(
"$slash" => "$slash$slash",
"$quote" => "$slash$quote",
"\t" => '\t',
);
$string = str_replace(
array_keys($replaces),
array_values($replaces),
$string
);
$po = $quote . implode(
"${slash}n$quote$newline$quote",
explode($newline, $string)
) . $quote;
// add empty string on first line for readbility
if (false !== strpos($string, $newline) &&
(substr_count($string, $newline) > 1 ||
!($newline === substr($string, -strlen($newline))))) {
$po = "$quote$quote$newline$po";
}
// remove empty strings
$po = str_replace("$newline$quote$quote", '', $po);
return $po;
} | Formats a string in PO-style.
@param string $string the string to format
@return string the poified string | entailment |
public static function unpoify($string)
{
$escapes = array('t' => "\t", 'n' => "\n", 'r' => "\r", '\\' => '\\');
$lines = array_map('trim', explode("\n", $string));
$lines = array_map(array(__NAMESPACE__ . '\PO', 'trim_quotes'), $lines);
$unpoified = '';
$previous_is_backslash = false;
foreach ($lines as $line) {
preg_match_all('/./u', $line, $chars);
$chars = $chars[0];
foreach ($chars as $char) {
if (!$previous_is_backslash) {
if ('\\' == $char) {
$previous_is_backslash = true;
} else {
$unpoified .= $char;
}
} else {
$previous_is_backslash = false;
$unpoified .= isset($escapes[$char]) ? $escapes[$char] : $char;
}
}
}
// Standardise the line endings on imported content, technically PO files shouldn't contain \r
$unpoified = str_replace(array("\r\n", "\r"), "\n", $unpoified);
return $unpoified;
} | Gives back the original string from a PO-formatted string.
@param string $string PO-formatted string
@return string enascaped string | entailment |
public static function prepend_each_line($string, $with)
{
$lines = explode("\n", $string);
$append = '';
if ("\n" === substr($string, -1) && '' === end($lines)) {
// Last line might be empty because $string was terminated
// with a newline, remove it from the $lines array,
// we'll restore state by re-terminating the string at the end
array_pop($lines);
$append = "\n";
}
foreach ($lines as &$line) {
$line = $with . $line;
}
unset($line);
return implode("\n", $lines) . $append;
} | Inserts $with in the beginning of every new line of $string and
returns the modified string.
@param string $string prepend lines in this string
@param string $with prepend lines with this string
@return string The modified string | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.