sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
public function read($session_id)
{
foreach ($this->getHandlers() as $handler) {
if ($data = $handler->read($session_id)) {
return $data;
}
}
return '';
} | @param string $session_id
@return string | entailment |
public static function init($key = null)
{
$instance = Injector::inst()->get(__CLASS__);
if (empty($key)) {
user_error(
'HybridSession::init() was not given a $key. Disabling cookie-based storage',
E_USER_WARNING
);
} else {
... | Register the session handler as the default
@param string $key Desired session key | entailment |
public function boot()
{
if ($this->isLumen() === false) {
$this->publishes([
__DIR__ . '/../../config/hashids.php' => config_path('hashids.php'),
]);
// Add 'Assets' facade alias
AliasLoader::getInstance()->alias('Hashids', 'Torann\Hashids\Fa... | Bootstrap the application events.
@return void | entailment |
public function register()
{
$this->app->bind('hashids', function ($app) {
$config = $app->config->get('hashids');
return new Hashids(
array_get($config, 'salt'),
array_get($config, 'length', 0),
array_get($config, 'alphabet')
... | Register the service provider.
@return void | entailment |
public function setIpinfoConfig($token = null, $debug = false)
{
$this->ipinfo->__construct(compact('token', 'debug'));
return $this;
} | Set token for Ipinfo if exists.
@access public
@param string $token (default: null)
@param bool $debug (default: false) | entailment |
public function getInfo()
{
$this->hostIpinfo();
$this->clientIpinfo();
$this->getServerInfoSoftware();
$this->serverInfoHardware();
$this->uptime();
$this->databaseInfo();
return $this->results;
} | Get all info.
@access public
@return array | entailment |
protected function databaseInfo()
{
$pdo = $this->database->getConnection()->getPdo();
$version = $this->ifExists($pdo->getAttribute(PDO::ATTR_SERVER_VERSION));
$driver = $this->ifExists($pdo->getAttribute(PDO::ATTR_DRIVER_NAME));
$driver = $this->ifExists((! empty($this->databases... | Get database info.
@access protected | entailment |
protected function hostIpinfo()
{
$ipinfo = $this->ipinfo->getYourOwnIpDetails()->getProperties();
$this->results['host'] = $ipinfo;
return $this;
} | Parse host info.
@access protected | entailment |
protected function clientIpinfo()
{
$ip = $this->request->getClientIp();
$ipinfo = $this->ipinfo->getFullIpDetails($ip)->getProperties();
$this->results['client'] = $ipinfo;
return $this;
} | Parse client info.
@access protected | entailment |
protected function getCPUString($cpus = [])
{
if (empty($cpus)) {
return '';
}
$cpuStrings = [];
foreach ($cpus as $cpu) {
$model = $cpu['Model'];
$model = str_replace('(R)', '®', $model);
$model = str_replace('(TM)', '™', $model);
... | Get CPU string.
@access protected
@param array $cpus (default: array())
@return string | entailment |
protected function getDiskSpace($mounts = [])
{
$total = $free = 0;
if (empty($mounts)) {
return compact('total', 'free');
}
foreach ($mounts as $mount) {
$total += $mount['size'];
$free += $mount['free'];
}
return compact('total... | Get disk space string.
@access protected
@param array $mounts (default: array())
@return string | entailment |
protected function serverInfoSoftware()
{
$linfo = $this->linfo->getParser();
$os = $this->ifExists($linfo->getOS());
$kernel = $this->ifExists($linfo->getKernel());
$arc = $this->ifExists($linfo->getCPUArchitecture());
$webserver = $this->ifExists($linfo->getWebService());
... | Parse server software.
@access protected | entailment |
protected function serverInfoHardware()
{
$linfo = $this->linfo->getParser();
$CPUs = $this->ifExists($linfo->getCPU());
$cpu = $this->getCPUString($CPUs);
$cpu_count = count($CPUs);
$model = $this->ifExists($linfo->getModel());
$virtualization = $this->getVirtualiz... | Parse server hardware.
@access protected | entailment |
protected function uptime()
{
$linfo = $this->linfo->getParser();
$uptime = $booted_at = null;
$systemUptime = $this->ifExists($linfo->getUpTime());
if (! empty($systemUptime['text'])) {
$uptime = $systemUptime['text'];
}
if (! empty($systemUptime['boo... | Parse uptime.
@access protected | entailment |
protected function resolveDispositionHeaderFilename($filename)
{
$userAgent = $this->request->headers->get('User-Agent');
if (preg_match('#MSIE|Safari|Konqueror#', $userAgent)) {
return "filename=".rawurlencode($filename);
}
return "filename*=UTF-8''".rawurlencode($file... | Algorithm inspired by phpBB3 | entailment |
protected function getCrypto($session_id)
{
$key = $this->getKey();
if (!$key) {
return null;
}
if (!$this->crypto || $this->crypto->getSalt() != $session_id) {
$this->crypto = Injector::inst()->create(CryptoHandler::class, $key, $session_id);
}
... | Get the cryptography store for the specified session
@param string $session_id
@return HybridSessionStore_Crypto | entailment |
public function encrypt($cleartext)
{
$iv = mcrypt_create_iv($this->ivSize, MCRYPT_DEV_URANDOM);
$enc = mcrypt_encrypt(
MCRYPT_RIJNDAEL_256,
$this->saltedKey,
$cleartext,
MCRYPT_MODE_CBC,
$iv
);
$hash = hash_hmac('sha256',... | Encrypt and then sign some cleartext
@param $cleartext - The cleartext to encrypt and sign
@return string - The encrypted-and-signed message as base64 ASCII. | entailment |
public function decrypt($data)
{
$data = base64_decode($data);
$iv = substr($data, 0, $this->ivSize);
$hash = substr($data, $this->ivSize, 64);
$enc = substr($data, $this->ivSize + 64);
$cleartext = rtrim(mcrypt_decrypt(
MCRYPT_RIJNDAEL_256,
$this... | Check the signature on an encrypted-and-signed message, and if valid
decrypt the content
@param $data - The encrypted-and-signed message as base64 ASCII
@return bool|string - The decrypted cleartext or false if signature failed | entailment |
public static function authenticateWithToken($token) {
$pkeyResource = openssl_pkey_new(array(
"digest_alg" => "sha256",
"private_key_bits" => 2048
));
openssl_pkey_export($pkeyResource, $generatedPrivateKey);
$pkeyResourceDetails = openssl_pkey_get_details($pkeyResource);
$generatedPu... | Generate new keys and authenticate with token
@param string $token | entailment |
public static function setEnv($value) {
self::$env = $value;
if ($value == "production") {
self::$authservicesUrl = "https://authservices.satispay.com";
} else {
self::$authservicesUrl = "https://".$value.".authservices.satispay.com";
}
} | Set env
@param string $value | entailment |
public static function get($path, $options = array()) {
$requestOptions = array(
"path" => $path,
"method" => "GET"
);
if (!empty($options["sign"])) {
$requestOptions["sign"] = $options["sign"];
}
return self::request($requestOptions);
} | GET request
@param string $path
@param array $options | entailment |
public static function post($path, $options = array()) {
$requestOptions = array(
"path" => $path,
"method" => "POST",
"body" => $options["body"]
);
if (!empty($options["sign"])) {
$requestOptions["sign"] = $options["sign"];
}
return self::request($requestOptions);
} | POST request
@param string $path
@param array $options | entailment |
public static function put($path, $options = array()) {
$requestOptions = array(
"path" => $path,
"method" => "PUT",
"body" => $options["body"]
);
if (!empty($options["sign"])) {
$requestOptions["sign"] = $options["sign"];
}
return self::request($requestOptions);
} | PUT request
@param string $path
@param array $options | entailment |
public static function patch($path, $options = array()) {
$requestOptions = array(
"path" => $path,
"method" => "PATCH",
"body" => $options["body"]
);
if (!empty($options["sign"])) {
$requestOptions["sign"] = $options["sign"];
}
return self::request($requestOptions);
} | PATCH request
@param string $path
@param array $options | entailment |
private static function signRequest($options = array()) {
$headers = array();
$authorizationHeader = "";
$privateKey = Api::getPrivateKey();
$keyId = Api::getKeyId();
$securityBearer = Api::getSecurityBearer();
if (!empty($privateKey) && !empty($keyId)) {
$date = date("r");
array_p... | Sign request
@param array $options | entailment |
private static function request($options = array()) {
$body = "";
$headers = array(
"Accept: application/json",
"User-Agent: ".self::$userAgentName."/".Api::getVersion()
);
$method = "GET";
if (!empty($options["method"])) {
$method = $options["method"];
}
if (!empty($opti... | Execute request
@param array $options | entailment |
private static function curl($options = array()) {
$curlOptions = array();
$curl = curl_init();
$curlOptions[CURLOPT_URL] = $options["url"];
$curlOptions[CURLOPT_RETURNTRANSFER] = true;
if ($options["method"] != "GET") {
if ($options["method"] != "POST") {
$curlOptions[CURLOPT_CUSTOM... | Curl request
@param array $options | entailment |
public function register()
{
$this->app->singleton('larinfo', function ($app) {
$larinfo = new Larinfo(new Ipinfo(), new Request(), new Linfo(), new Manager());
$token = config('services.ipinfo.token');
if (! empty($token)) {
return $larinfo->setIpinfoCo... | Register the application services. | entailment |
protected function url($path, array $parameters = null)
{
$query = [
'client_id' => $this->client_key,
'redirect_uri' => $this->redirect_uri,
'response_type' => 'code'
];
if ($parameters)
$query = array_merge($query, $parameters);
$query = http_b... | Make URLs for user browser navigation.
@param string $path
@param array $parameters
@return string | entailment |
public function post($path, array $parameters, $authorization = false)
{
$query = [];
if ($authorization)
$query = [
'client_id' => $this->client_key,
'client_secret' => $this->client_secret,
'redirect_uri' => $this->redirect_uri,
'grant_type' => 'a... | Make POST calls to the API
@param string $path
@param boolean $authorization [Use access token query params]
@param array $parameters [Optional query parameters]
@return Array | entailment |
public function get($path, array $parameters)
{
try {
$response = $this->client->request('GET', $path, [
'query' => $parameters
]);
return $this->toArray($response);
}
catch (ClientException $e) {
return $this->toArray($e->getResponse());
}... | Make GET calls to the API
@param string $path
@param array $parameters [Query parameters]
@return Array | entailment |
public function handle(Dispatcher $events, ManagerRegistry $registry)
{
$class = $this->argument('model');
$em = $registry->getManagerForClass($class);
$repository = $em->getRepository($class);
if (!$repository instanceof SearchableRepository) {
$repository = new Sea... | Execute the console command.
@param \Illuminate\Contracts\Events\Dispatcher $events
@param ManagerRegistry $registry | entailment |
public function run( )
{
@set_time_limit( 600 );
\System::loadLanguageFile('tl_backupdb'); // Modultexte laden
$user = \BackendUser::getInstance(); // Backend-User
$filename = \Environment::get... | ------------------------- | entailment |
public function run( )
{
@set_time_limit( 600 );
$user = \BackendUser::getInstance();
$filepath = $GLOBALS['TL_CONFIG']['uploadPath'] . '/AutoBackupDB';
$pfad = TL_ROOT . '/' . $filepath;
if( file_exists( $pfad . '/' . BACKUPDB_RUN_LAST ) ) {
unlink( $pfad . '/' ... | ------------------------- | entailment |
public function makeAllSearchable()
{
$this->chunk(100, function (Collection $models) {
$models = $models->map(function (Searchable $model) {
$model->setSearchableAs($this->searchableAs());
$model->setClassMetaData($this->getClassMetadata());
retu... | Make all searchable | entailment |
public static function getHeaderInfo( $sql_mode, $savedby = 'Saved by Cron' )
{
$objDB = \Database::getInstance();
$instExt = array();
$bundles = array();
$result = "#================================================================================\r\n"
. "# Contao-W... | --------------------------------------- | entailment |
public static function getFromDB( )
{
$result = array();
$objDB = \Database::getInstance( );
$tables = $objDB->listTables( null, true );
if( empty($tables) ) {
return $result;
}
foreach( $tables as $table ) {
$keys = array();
$fie... | ------------------------------------------------ | entailment |
public static function get_table_structure( $table, $tablespec )
{
$result = "\r\n"
. "#---------------------------------------------------------\r\n"
. "# Table structure for table '$table'\r\n"
. "#---------------------------------------------------------\r\... | --------------------------------------- | entailment |
public static function get_table_content( $table, $datei=NULL, $sitetemplate=false )
{
$objDB = \Database::getInstance();
$objData = $objDB->executeUncached( "SELECT * FROM $table" );
$fields = $objDB->listFields( $table ); // Liste der Felder lesen
$fieldlist = ''... | ------------------------------------------------ | entailment |
public static function get_blacklist( )
{
$arrBlacklist = array(); // Default: alle Datentabellen werden gesichert
if( isset( $GLOBALS['TL_CONFIG']['backupdb_blacklist'] ) && (trim($GLOBALS['TL_CONFIG']['backupdb_blacklist']) != '') ) {
$arrBlacklist = trimsplit(',', strt... | ------------------------------------------------ | entailment |
public static function get_symlinks( )
{
Self::$arrSymlinks = array(); // leeres Array
$url = TL_ROOT . '/';
Self::iterateDir( $url ); // Symlinks suchen
asort( Self::$arrSymlinks ); // alphabetisch sortieren
$links = array();
... | ------------------------------------------------ | entailment |
public static function iterateDir( $startPath )
{
foreach( new \DirectoryIterator( $startPath ) as $objItem ) {
if( $objItem->isLink( ) ) {
Self::$arrSymlinks[] = $objItem->getPath( ) . '/' . $objItem->getFilename( );
continue;
}
if($objIte... | ------------------------------------------------ | entailment |
public static function getLinkData( $link )
{
$root = str_replace('\\', '/', TL_ROOT) . '/';
$sym = substr( str_replace('\\', '/', $link), strlen($root) );
$target = str_replace('\\', '/', readlink( $link ) );
if( substr($target, 0, strlen($root)) === $root ) { // ab... | ------------------------------------------------ | entailment |
protected function compile()
{
\System::loadLanguageFile('tl_backupdb');
switch( \Input::get('act') ) {
case 'backup': BackupDbRun::run( );
die( ); // Beenden, da Download rausgegangen ist
case 'webtemplate': $o... | Function compile | entailment |
public function checkCronExt( )
{
$result = 0; // kein Cron
$objDB = \Database::getInstance();
if( $objDB->tableExists('tl_crontab') ) {
$result = 1; // Cron vorhanden, kein Job
$objJob = $objDB->exec... | Function check cron job | entailment |
public function configureServers(array $servers): array
{
return array_map(
static function ($item) {
if ($item['basic']) {
$item['basic'] = base64_encode($item['basic']);
}
return $item;
},
$servers
... | Returns servers list with hash for basic auth computed if provided. | entailment |
public function AutoBackupAction()
{
$this->container->get('contao.framework')->initialize();
$controller = new \Softleister\BackupDB\AutoBackupDb();
return $controller->run();
} | Renders the alerts content.
@return Response
@Route("/autobackup", name="backupdb_autobackup") | entailment |
public function cacheAction(Request $request)
{
$parameters = $request->get('parameters', []);
if ($request->get('token') !== $this->computeHash($parameters)) {
throw new AccessDeniedHttpException('Invalid token');
}
$subRequest = Request::create('', 'get', $parameters,... | @throws AccessDeniedHttpException
@return mixed | entailment |
public function run( )
{
// Spamming-Schutz
if( \Config::get('backupdb_var') != '' ) {
if( \Input::get( \Config::get('backupdb_var') ) === NULL ) {
die( 'You cannot access this file directly!' ); // Variable nicht vorhanden => NULL
} ... | ------------------------- | entailment |
public function enqueue(Task $task): \Generator
{
if (!$this->context->isRunning()) {
throw new StatusError('The worker has not been started.');
}
if ($this->shutdown) {
throw new StatusError('The worker has been shut down.');
}
// If the worker is c... | {@inheritdoc} | entailment |
private function send(Task $task): \Generator
{
yield from $this->context->send($task);
return yield from $this->context->receive();
} | @coroutine
@param \Icicle\Concurrent\Worker\Task $task
@return \Generator
@resolve mixed | entailment |
public function shutdown(): \Generator
{
if (!$this->context->isRunning() || $this->shutdown) {
throw new StatusError('The worker is not running.');
}
$this->shutdown = true;
// Cancel any waiting tasks.
$this->cancelPending();
// If a task is currently... | {@inheritdoc} | entailment |
private function cancelPending()
{
if (!$this->busyQueue->isEmpty()) {
$exception = new WorkerException('Worker was shut down.');
do {
$this->busyQueue->dequeue()->cancel($exception);
} while (!$this->busyQueue->isEmpty());
}
} | Cancels all pending tasks. | entailment |
public function start()
{
$this->process->start();
$this->channel = new ChannelledStream($this->process->getStdOut(), $this->process->getStdIn());
} | {@inheritdoc} | entailment |
public function receive(): \Generator
{
if (null === $this->channel) {
throw new StatusError('The process has not been started.');
}
$data = yield from $this->channel->receive();
if ($data instanceof ExitStatus) {
$data = $data->getResult();
thro... | {@inheritdoc} | entailment |
protected function writeProgress($progress)
{
if($this->debug) {
return parent::writeProgress($progress);
}
$this->scoreboard->score($progress);
} | {@inheritdoc} | entailment |
protected function printHeader()
{
if (!$this->debug) {
if (!$this->scoreboard->isRunning()) {
$this->scoreboard->start();
}
$this->scoreboard->stop();
}
parent::printHeader();
} | {@inheritdoc} | entailment |
public function addFailure(Test $test, AssertionFailedError $e, $time)
{
if ($this->debug) {
return parent::addFailure($test, $e, $time);
}
$this->writeProgress('fail');
$this->lastTestFailed = TRUE;
} | {@inheritdoc} | entailment |
public function setPriority(float $priority): float
{
if ($priority < 0 || $priority > 1) {
throw new InvalidArgumentError('Priority value must be between 0.0 and 1.0.');
}
$nice = round(19 - ($priority * 39));
if (!pcntl_setpriority($nice, $this->pid, PRIO_PROCESS)) {
... | Sets the fork's scheduling priority as a percentage.
Note that on many systems, only the superuser can increase the priority of a process.
@param float $priority A priority value between 0 and 1.
@throws InvalidArgumentError If the given priority is an invalid value.
@throws ForkException If the operation fai... | entailment |
public function start()
{
if (0 !== $this->oid) {
throw new StatusError('The context has already been started.');
}
list($parent, $child) = Stream\pair();
switch ($pid = pcntl_fork()) {
case -1: // Failure
throw new ForkException('Could not f... | Starts the context execution.
@throws \Icicle\Concurrent\Exception\ForkException If forking fails.
@throws \Icicle\Stream\Exception\FailureException If creating a socket pair fails. | entailment |
private function execute(Channel $channel): \Generator
{
try {
if ($this->function instanceof \Closure) {
$function = $this->function->bindTo($channel, Channel::class);
}
if (empty($function)) {
$function = $this->function;
}
... | @coroutine
This method is run only on the child.
@param \Icicle\Concurrent\Sync\Channel $channel
@return \Generator
@codeCoverageIgnore Only executed in the child. | entailment |
public function kill()
{
if ($this->isRunning()) {
// Forcefully kill the process using SIGKILL.
posix_kill($this->pid, SIGKILL);
}
if (null !== $this->pipe && $this->pipe->isOpen()) {
$this->pipe->close();
}
// "Detach" from the process ... | {@inheritdoc} | entailment |
public function signal(int $signo)
{
if (0 === $this->pid) {
throw new StatusError('The fork has not been started or has already finished.');
}
posix_kill($this->pid, (int) $signo);
} | @param int $signo
@throws \Icicle\Concurrent\Exception\StatusError | entailment |
public function join(): \Generator
{
if (null === $this->channel) {
throw new StatusError('The fork has not been started or has already finished.');
}
try {
$response = yield from $this->channel->receive();
if (!$response instanceof ExitStatus) {
... | @coroutine
Gets a promise that resolves when the context ends and joins with the
parent context.
@return \Generator
@resolve mixed Resolved with the return or resolution value of the context once it has completed execution.
@throws \Icicle\Concurrent\Exception\StatusError Thrown if the context has not been... | entailment |
public function send($data): \Generator
{
if (null === $this->channel) {
throw new StatusError('The fork has not been started or has already finished.');
}
if ($data instanceof ExitStatus) {
throw new InvalidArgumentError('Cannot send exit status objects.');
... | {@inheritdoc} | entailment |
private function init($maxLocks, $permissions)
{
$maxLocks = (int) $maxLocks;
if ($maxLocks < 1) {
$maxLocks = 1;
}
$this->key = abs(crc32(spl_object_hash($this)));
$this->maxLocks = $maxLocks;
$this->queue = msg_get_queue($this->key, $permissions);
... | @param int $maxLocks The maximum number of locks that can be acquired from the semaphore.
@param int $permissions Permissions to access the semaphore.
@throws SemaphoreException If the semaphore could not be created due to an internal error. | entailment |
public function acquire(): \Generator
{
do {
// Attempt to acquire a lock from the semaphore.
if (@msg_receive($this->queue, 0, $type, 1, $chr, false, MSG_IPC_NOWAIT, $errno)) {
// A free lock was found, so resolve with a lock object that can
// be use... | {@inheritdoc} | entailment |
public function free()
{
if (is_resource($this->queue) && msg_queue_exists($this->key)) {
if (!msg_remove_queue($this->queue)) {
throw new SemaphoreException('Failed to free the semaphore.');
}
$this->queue = null;
}
} | Removes the semaphore if it still exists.
@throws SemaphoreException If the operation failed. | entailment |
public function unserialize($serialized)
{
// Get the semaphore key and attempt to re-connect to the semaphore in memory.
list($this->key, $this->maxLocks) = unserialize($serialized);
if (msg_queue_exists($this->key)) {
$this->queue = msg_get_queue($this->key);
}
} | Unserializes a serialized semaphore.
@param string $serialized The serialized semaphore. | entailment |
protected function release()
{
// Call send in non-blocking mode. If the call fails because the queue
// is full, then the number of locks configured is too large.
if (!@msg_send($this->queue, 1, "\0", false, false, $errno)) {
if ($errno === MSG_EAGAIN) {
throw ne... | Releases a lock from the semaphore.
@throws SemaphoreException If the operation failed. | entailment |
public function send($data): \Generator
{
// Serialize the data to send into the channel.
try {
$serialized = serialize($data);
} catch (\Throwable $exception) {
throw new SerializationException(
'The given data cannot be sent because it is not seriali... | {@inheritdoc} | entailment |
public function receive(): \Generator
{
// Read the message length first to determine how much needs to be read from the stream.
$length = self::HEADER_LENGTH;
$buffer = '';
$remaining = $length;
try {
do {
$buffer .= yield from $this->read->read(... | {@inheritdoc} | entailment |
public function start()
{
if (0 !== $this->oid) {
throw new StatusError('The thread has already been started.');
}
$this->oid = getmypid();
list($channel, $this->socket) = Stream\pair();
$this->thread = new Internal\Thread($this->socket, $this->function, $this-... | Spawns the thread and begins the thread's execution.
@throws \Icicle\Concurrent\Exception\StatusError If the thread has already been started.
@throws \Icicle\Concurrent\Exception\ThreadException If starting the thread was unsuccessful.
@throws \Icicle\Stream\Exception\FailureException If creating a socket pair fails. | entailment |
public function kill()
{
if (null !== $this->thread) {
try {
if ($this->thread->isRunning() && !$this->thread->kill()) {
throw new ThreadException('Could not kill thread.');
}
} finally {
$this->close();
... | Immediately kills the context.
@throws ThreadException If killing the thread was unsuccessful. | entailment |
private function close()
{
if (null !== $this->pipe && $this->pipe->isOpen()) {
$this->pipe->close();
}
if (is_resource($this->socket)) {
fclose($this->socket);
}
$this->thread = null;
$this->channel = null;
} | Closes channel and socket if still open. | entailment |
public function join(): \Generator
{
if (null === $this->channel || null === $this->thread) {
throw new StatusError('The thread has not been started or has already finished.');
}
try {
$response = yield from $this->channel->receive();
if (!$response inst... | @coroutine
Gets a promise that resolves when the context ends and joins with the
parent context.
@return \Generator
@resolve mixed Resolved with the return or resolution value of the context once it has completed execution.
@throws StatusError Thrown if the context has not been started.
@throws SynchronizationError... | entailment |
public function getException()
{
return new TaskException(
sprintf('Uncaught exception in worker of type "%s" with message "%s"', $this->type, $this->message),
$this->code,
$this->trace
);
} | {@inheritdoc} | entailment |
public function isFreed(): bool
{
// If we are no longer connected to the memory segment, check if it has
// been invalidated.
if ($this->handle !== null) {
$this->handleMovedMemory();
$header = $this->getHeader();
return $header['state'] === static::STATE... | Checks if the object has been freed.
Note that this does not check if the object has been destroyed; it only
checks if this handle has freed its reference to the object.
@return bool True if the object is freed, otherwise false. | entailment |
public function unwrap()
{
if ($this->isFreed()) {
throw new SharedMemoryException('The object has already been freed.');
}
$header = $this->getHeader();
// Make sure the header is in a valid state and format.
if ($header['state'] !== self::STATE_ALLOCATED || $h... | {@inheritdoc} | entailment |
protected function wrap($value)
{
if ($this->isFreed()) {
throw new SharedMemoryException('The object has already been freed.');
}
$serialized = serialize($value);
$size = strlen($serialized);
$header = $this->getHeader();
/* If we run out of space, we n... | If the value requires more memory to store than currently allocated, a
new shared memory segment will be allocated with a larger size to store
the value in. The previous memory segment will be cleaned up and marked
for deletion. Other processes and threads will be notified of the new
memory segment on the next read att... | entailment |
public function synchronized(callable $callback): \Generator
{
/** @var \Icicle\Concurrent\Sync\Lock $lock */
$lock = yield from $this->semaphore->acquire();
try {
$value = $this->unwrap();
$result = yield $callback($value);
$this->wrap(null === $result ?... | {@inheritdoc} | entailment |
public function free()
{
if (!$this->isFreed()) {
// Invalidate the memory block by setting its state to FREED.
$this->setHeader(static::STATE_FREED, 0, 0);
// Request the block to be deleted, then close our local handle.
$this->memDelete();
shmop... | Frees the shared object from memory.
The memory containing the shared value will be invalidated. When all
process disconnect from the object, the shared memory block will be
destroyed by the OS.
Calling `free()` on an object already freed will have no effect. | entailment |
public function unserialize($serialized)
{
list($this->key, $this->semaphore) = unserialize($serialized);
$this->memOpen($this->key, 'w', 0, 0);
} | Unserializes the local object handle.
@param string $serialized The serialized object handle. | entailment |
private function handleMovedMemory()
{
// Read from the memory block and handle moved blocks until we find the
// correct block.
while (true) {
$header = $this->getHeader();
// If the state is STATE_MOVED, the memory is stale and has been moved
// to a ne... | Updates the current memory segment handle, handling any moves made on the
data. | entailment |
private function setHeader(int $state, int $size, int $permissions)
{
$header = pack('CLS', $state, $size, $permissions);
$this->memSet(0, $header);
} | Sets the header data for the current memory segment.
@param int $state An object state.
@param int $size The size of the stored data, or other value.
@param int $permissions The permissions mask on the memory segment. | entailment |
private function memOpen(int $key, string $mode, int $permissions, int $size)
{
$this->handle = @shmop_open($key, $mode, $permissions, $size);
if ($this->handle === false) {
throw new SharedMemoryException('Failed to create shared memory block.');
}
} | Opens a shared memory handle.
@param int $key The shared memory key.
@param string $mode The mode to open the shared memory in.
@param int $permissions Process permissions on the shared memory.
@param int $size The size to crate the shared memory in bytes. | entailment |
public function acquire(): \Generator
{
// Try to create the lock file. If the file already exists, someone else
// has the lock, so set an asynchronous timer and try again.
while (($handle = @fopen($this->fileName, 'x')) === false) {
yield from Coroutine\sleep(self::LATENCY_TIME... | {@inheritdoc} | entailment |
private function close($resource)
{
if (is_resource($resource)) {
fclose($resource);
}
if (is_resource($this->process)) {
proc_close($this->process);
$this->process = null;
}
$this->stdin->close();
} | Closes the stream resource provided, the open process handle, and stdin.
@param resource $resource | entailment |
public function join(): \Generator
{
if (null === $this->delayed) {
throw new StatusError('The process has not been started.');
}
$this->poll->listen();
try {
return yield $this->delayed;
} finally {
$this->stdout->close();
$t... | @coroutine
@return \Generator
@throws \Icicle\Concurrent\Exception\StatusError If the process has not been started. | entailment |
public function kill()
{
if (is_resource($this->process)) {
// Forcefully kill the process using SIGKILL.
proc_terminate($this->process, 9);
// "Detach" from the process and let it die asynchronously.
$this->process = null;
}
} | {@inheritdoc} | entailment |
public function signal(int $signo)
{
if (!$this->isRunning()) {
throw new StatusError('The process is not running.');
}
proc_terminate($this->process, (int) $signo);
} | Sends the given signal to the process.
@param int $signo Signal number to send to process.
@throws \Icicle\Concurrent\Exception\StatusError If the process is not running. | entailment |
public function get(string $key)
{
if (isset($this->ttl[$key]) && 0 !== $this->ttl[$key]) {
$this->expire[$key] = time() + $this->ttl[$key];
$this->queue->insert($key, -$this->expire[$key]);
}
return isset($this->data[$key]) ? $this->data[$key] : null;
} | @param string $key
@return mixed|null Returns null if the key does not exist. | entailment |
public function clear()
{
$this->data = [];
$this->expire = [];
$this->ttl = [];
$this->timer->stop();
$this->queue = new \SplPriorityQueue();
} | Removes all values. | entailment |
private function init(int $locks)
{
$locks = (int) $locks;
if ($locks < 1) {
$locks = 1;
}
$this->semaphore = new Internal\Semaphore($locks);
$this->maxLocks = $locks;
} | Initializes the semaphore with a given number of locks.
@param int $locks | entailment |
public function release()
{
if ($this->released) {
throw new LockAlreadyReleasedError('The lock has already been released!');
}
// Invoke the releaser function given to us by the synchronization source
// to release the lock.
($this->releaser)($this);
$th... | Releases the lock.
@throws LockAlreadyReleasedError If the lock was already released. | entailment |
public function run()
{
/* First thing we need to do is re-initialize the class autoloader. If
* we don't do this first, any object of a class that was loaded after
* the thread started will just be garbage data and unserializable
* values (like resources) will be lost. This happe... | Runs the thread code and the initialized function.
@codeCoverageIgnore Only executed in thread. | entailment |
public function start()
{
if ($this->isRunning()) {
throw new StatusError('The worker pool has already been started.');
}
// Start up the pool with the minimum number of workers.
$count = $this->minSize;
while (--$count >= 0) {
$worker = $this->create... | Starts the worker pool execution.
When the worker pool starts up, the minimum number of workers will be created. This adds some overhead to
starting the pool, but allows for greater performance during runtime. | entailment |
public function enqueue(Task $task): \Generator
{
$worker = $this->get();
return yield from $worker->enqueue($task);
} | Enqueues a task to be executed by the worker pool.
@coroutine
@param Task $task The task to enqueue.
@return \Generator
@resolve mixed The return value of the task.
@throws \Icicle\Concurrent\Exception\StatusError If the pool has not been started.
@throws \Icicle\Concurrent\Exception\TaskException If the task thro... | entailment |
public function shutdown(): \Generator
{
if (!$this->isRunning()) {
throw new StatusError('The pool is not running.');
}
$this->running = false;
$shutdowns = [];
foreach ($this->workers as $worker) {
if ($worker->isRunning()) {
$shut... | Shuts down the pool and all workers in it.
@coroutine
@return \Generator
@throws \Icicle\Concurrent\Exception\StatusError If the pool has not been started. | entailment |
public function kill()
{
$this->running = false;
foreach ($this->workers as $worker) {
$worker->kill();
}
} | Kills all workers in the pool and halts the worker pool. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.