repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
as3io/modlr | src/Models/Collections/ModelCollection.php | ModelCollection.loadFromStore | protected function loadFromStore()
{
if (false === $this->isLoaded()) {
// Loads collection from the database on iteration.
$models = $this->store->loadCollection($this);
$this->setModels($models);
$this->loaded = true;
}
} | php | protected function loadFromStore()
{
if (false === $this->isLoaded()) {
// Loads collection from the database on iteration.
$models = $this->store->loadCollection($this);
$this->setModels($models);
$this->loaded = true;
}
} | Loads this collection from the store. | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/ModelCollection.php#L103-L111 |
as3io/modlr | src/Models/Collections/ModelCollection.php | ModelCollection.validateAdd | protected function validateAdd(AbstractModel $model)
{
$this->validateModelClass($model);
$this->store->validateRelationshipSet($this->getMetadata(), $model->getType());
} | php | protected function validateAdd(AbstractModel $model)
{
$this->validateModelClass($model);
$this->store->validateRelationshipSet($this->getMetadata(), $model->getType());
} | {@inheritdoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Models/Collections/ModelCollection.php#L116-L120 |
acacha/forge-publish | src/Console/Commands/PublishSSL.php | PublishSSL.handle | public function handle()
{
$this->abortCommandExecution();
$this->info("Obtaining Lets Encrypt Certificate on production...");
$this->url = $this->obtainAPIURLEndpoint();
$this->http->post($this->url,
[
'form_params' => [
'domains' => [$this->domain]
],
'headers' => [
'X-Requested-With' => 'XMLHttpRequest',
'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
]
]
);
} | php | public function handle()
{
$this->abortCommandExecution();
$this->info("Obtaining Lets Encrypt Certificate on production...");
$this->url = $this->obtainAPIURLEndpoint();
$this->http->post($this->url,
[
'form_params' => [
'domains' => [$this->domain]
],
'headers' => [
'X-Requested-With' => 'XMLHttpRequest',
'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
]
]
);
} | Execute the console command. | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishSSL.php#L82-L101 |
eloquent/endec | src/Base64/Base64UrlDecodeTransform.php | Base64UrlDecodeTransform.transform | public function transform($data, &$context, $isEnd = false)
{
$consume = $this->blocksSize(strlen($data), 4, $isEnd);
if (!$consume) {
return array('', 0, null);
}
$consumedData = substr($data, 0, $consume);
if (1 === $consume % 4) {
return array(
'',
0,
new InvalidEncodedDataException('base64url', $consumedData),
);
}
$outputBuffer = base64_decode(
str_pad(
strtr($consumedData, '-_', '+/'),
$consume % 4,
'=',
STR_PAD_RIGHT
),
true
);
if (false === $outputBuffer) {
return array(
'',
0,
new InvalidEncodedDataException('base64url', $consumedData),
);
}
return array($outputBuffer, $consume, null);
} | php | public function transform($data, &$context, $isEnd = false)
{
$consume = $this->blocksSize(strlen($data), 4, $isEnd);
if (!$consume) {
return array('', 0, null);
}
$consumedData = substr($data, 0, $consume);
if (1 === $consume % 4) {
return array(
'',
0,
new InvalidEncodedDataException('base64url', $consumedData),
);
}
$outputBuffer = base64_decode(
str_pad(
strtr($consumedData, '-_', '+/'),
$consume % 4,
'=',
STR_PAD_RIGHT
),
true
);
if (false === $outputBuffer) {
return array(
'',
0,
new InvalidEncodedDataException('base64url', $consumedData),
);
}
return array($outputBuffer, $consume, null);
} | Transform the supplied data.
This method may transform only part of the supplied data. The return
value includes information about how much data was actually consumed. The
transform can be forced to consume all data by passing a boolean true as
the $isEnd argument.
The $context argument will initially be null, but any value assigned to
this variable will persist until the stream transformation is complete.
It can be used as a place to store state, such as a buffer.
It is guaranteed that this method will be called with $isEnd = true once,
and only once, at the end of the stream transformation.
@param string $data The data to transform.
@param mixed &$context An arbitrary context value.
@param boolean $isEnd True if all supplied data must be transformed.
@return tuple<string,integer,mixed> A 3-tuple of the transformed data, the number of bytes consumed, and any resulting error. | https://github.com/eloquent/endec/blob/90043a26439739d6bac631cc57dab3ecf5cafdc3/src/Base64/Base64UrlDecodeTransform.php#L61-L95 |
YiMAproject/yimaWidgetator | src/yimaWidgetator/View/Renderer/PhpRenderer.php | PhpRenderer.__renderWidgets | protected function __renderWidgets($region, array $widgets, ModelInterface $viewModel)
{
foreach($widgets as $widget) {
if (!$widget instanceof WidgetInterface)
$widget = $this->___attainWidgetInstance($widget);
// Render Widget
$content = $widget->render();
// TODO maybe we want to add filter or event on rendering widget contents
$viewModel->{$region} .= $content;
}
} | php | protected function __renderWidgets($region, array $widgets, ModelInterface $viewModel)
{
foreach($widgets as $widget) {
if (!$widget instanceof WidgetInterface)
$widget = $this->___attainWidgetInstance($widget);
// Render Widget
$content = $widget->render();
// TODO maybe we want to add filter or event on rendering widget contents
$viewModel->{$region} .= $content;
}
} | Render Widget From Container Result
@param array $widgets Container Widget Entity
@param ModelInterface $viewModel View Model
@return bool | https://github.com/YiMAproject/yimaWidgetator/blob/332bc9318e6ceaec918147b30317da2f5b3d2636/src/yimaWidgetator/View/Renderer/PhpRenderer.php#L45-L57 |
YiMAproject/yimaWidgetator | src/yimaWidgetator/View/Renderer/PhpRenderer.php | PhpRenderer.___attainWidgetInstance | protected function ___attainWidgetInstance($widget)
{
/** @var $widgetManager WidgetManager */
$widgetManager = $this->sm->get('yimaWidgetator.WidgetManager');
$options = [];
if (is_array($widget)) {
$wArg = $widget;
$widget = $wArg['widget'];
$options = (isset($wArg['params'])) ? $wArg['params'] : $options;
}
$instance = $widgetManager->get($widget, $options);
return $instance;
} | php | protected function ___attainWidgetInstance($widget)
{
/** @var $widgetManager WidgetManager */
$widgetManager = $this->sm->get('yimaWidgetator.WidgetManager');
$options = [];
if (is_array($widget)) {
$wArg = $widget;
$widget = $wArg['widget'];
$options = (isset($wArg['params'])) ? $wArg['params'] : $options;
}
$instance = $widgetManager->get($widget, $options);
return $instance;
} | @param mixed $widget
@return WidgetInterface | https://github.com/YiMAproject/yimaWidgetator/blob/332bc9318e6ceaec918147b30317da2f5b3d2636/src/yimaWidgetator/View/Renderer/PhpRenderer.php#L64-L79 |
alphacomm/alpharpc | src/AlphaRPC/Worker/WorkerCommunication.php | WorkerCommunication.setDelay | public function setDelay($delay)
{
if (!ctype_digit((string) $delay)) {
throw new \InvalidArgumentException('Delay must be a number.');
}
$this->delay = $delay;
return $this;
} | php | public function setDelay($delay)
{
if (!ctype_digit((string) $delay)) {
throw new \InvalidArgumentException('Delay must be a number.');
}
$this->delay = $delay;
return $this;
} | The time it takes for the handler to respond.
@param int $delay
@throws \InvalidArgumentException
@return WorkerCommunication | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Worker/WorkerCommunication.php#L115-L123 |
alphacomm/alpharpc | src/AlphaRPC/Worker/WorkerCommunication.php | WorkerCommunication.start | public function start()
{
$this->workerHandlerReady = true;
$this->serviceStreamReady = true;
$this->sendToService(new ActionListRequest());
} | php | public function start()
{
$this->workerHandlerReady = true;
$this->serviceStreamReady = true;
$this->sendToService(new ActionListRequest());
} | Initializes the worker. | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Worker/WorkerCommunication.php#L128-L133 |
alphacomm/alpharpc | src/AlphaRPC/Worker/WorkerCommunication.php | WorkerCommunication.process | public function process()
{
if ($this->worker->getState() == Worker::INVALID) {
throw new \RuntimeException('Invalid state to process.');
}
$expiry = 5000 + $this->delay;
if ($this->worker->isExpired($expiry)) {
$this->getLogger()->debug('Worker is expired, no longer registered to workerhandler.');
$this->worker->setState(Worker::INVALID);
return;
}
try {
$read = $write = array();
$this->getPoller()->poll($read, $write, 100);
} catch (\ZMQPollException $ex) {
pcntl_signal_dispatch();
return;
}
$this->workerHandlerStream->handle();
$this->serviceStream->handle();
$this->handleResult();
$this->heartbeat();
pcntl_signal_dispatch();
} | php | public function process()
{
if ($this->worker->getState() == Worker::INVALID) {
throw new \RuntimeException('Invalid state to process.');
}
$expiry = 5000 + $this->delay;
if ($this->worker->isExpired($expiry)) {
$this->getLogger()->debug('Worker is expired, no longer registered to workerhandler.');
$this->worker->setState(Worker::INVALID);
return;
}
try {
$read = $write = array();
$this->getPoller()->poll($read, $write, 100);
} catch (\ZMQPollException $ex) {
pcntl_signal_dispatch();
return;
}
$this->workerHandlerStream->handle();
$this->serviceStream->handle();
$this->handleResult();
$this->heartbeat();
pcntl_signal_dispatch();
} | Perform one service cycle.
This method checks whether there are any new requests to be handled,
either from the Worker Handler or from the Service. | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Worker/WorkerCommunication.php#L140-L168 |
alphacomm/alpharpc | src/AlphaRPC/Worker/WorkerCommunication.php | WorkerCommunication.createWorkerHandlerStream | protected function createWorkerHandlerStream(Socket $socket)
{
$socket->setId('manager');
$this->getPoller()->add($socket, ZMQ::POLL_IN);
$that = $this;
$this->workerHandlerStream = $socket->getStream();
$this->workerHandlerStream->addListener(StreamInterface::MESSAGE, function (MessageEvent $event) use ($that) {
if (null === $event->getProtocolMessage()) {
$message = $event->getMessage();
$that->getLogger()->error('Non-protocol message detected in worker-handler stream: '.$message);
return;
}
$that->onWorkerHandlerMessage($event->getProtocolMessage());
});
} | php | protected function createWorkerHandlerStream(Socket $socket)
{
$socket->setId('manager');
$this->getPoller()->add($socket, ZMQ::POLL_IN);
$that = $this;
$this->workerHandlerStream = $socket->getStream();
$this->workerHandlerStream->addListener(StreamInterface::MESSAGE, function (MessageEvent $event) use ($that) {
if (null === $event->getProtocolMessage()) {
$message = $event->getMessage();
$that->getLogger()->error('Non-protocol message detected in worker-handler stream: '.$message);
return;
}
$that->onWorkerHandlerMessage($event->getProtocolMessage());
});
} | Creates a socket to communicate with the worker handler.
@param Socket $socket
@return null | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Worker/WorkerCommunication.php#L177-L195 |
alphacomm/alpharpc | src/AlphaRPC/Worker/WorkerCommunication.php | WorkerCommunication.createServiceStream | protected function createServiceStream(Socket $socket)
{
$socket->setId('worker_service');
$this->getPoller()->add($socket, ZMQ::POLL_IN);
$that = $this;
$this->serviceStream = $socket->getStream();
$this->serviceStream->addListener(StreamInterface::MESSAGE, function (MessageEvent $event) use ($that) {
if (null === $event->getProtocolMessage()) {
$message = $event->getMessage();
$that->getLogger()->error('Non-protocol message detected in service stream: '.$message);
return;
}
$that->onServiceMessage($event->getProtocolMessage());
});
} | php | protected function createServiceStream(Socket $socket)
{
$socket->setId('worker_service');
$this->getPoller()->add($socket, ZMQ::POLL_IN);
$that = $this;
$this->serviceStream = $socket->getStream();
$this->serviceStream->addListener(StreamInterface::MESSAGE, function (MessageEvent $event) use ($that) {
if (null === $event->getProtocolMessage()) {
$message = $event->getMessage();
$that->getLogger()->error('Non-protocol message detected in service stream: '.$message);
return;
}
$that->onServiceMessage($event->getProtocolMessage());
});
} | Creates a socket to communicate with the service.
@param Socket $socket
@return null | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Worker/WorkerCommunication.php#L204-L222 |
alphacomm/alpharpc | src/AlphaRPC/Worker/WorkerCommunication.php | WorkerCommunication.onWorkerHandlerMessage | public function onWorkerHandlerMessage(MessageInterface $msg)
{
$this->workerHandlerReady = true;
$this->worker->touch();
if ($msg instanceof Destroy) {
$this->worker->setState(Worker::INVALID);
return;
}
if ($msg instanceof ExecuteJobRequest) {
$this->startJob($msg);
return;
}
if ($msg instanceof HeartbeatResponseWorkerhandler) {
$this->handleHeartbeatResponse();
return;
}
$this->getLogger()->error('Unknown worker-handler response: '.get_class($msg).'.');
} | php | public function onWorkerHandlerMessage(MessageInterface $msg)
{
$this->workerHandlerReady = true;
$this->worker->touch();
if ($msg instanceof Destroy) {
$this->worker->setState(Worker::INVALID);
return;
}
if ($msg instanceof ExecuteJobRequest) {
$this->startJob($msg);
return;
}
if ($msg instanceof HeartbeatResponseWorkerhandler) {
$this->handleHeartbeatResponse();
return;
}
$this->getLogger()->error('Unknown worker-handler response: '.get_class($msg).'.');
} | Handles a Message from the Worker Handler.
@param MessageInterface $msg | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Worker/WorkerCommunication.php#L243-L267 |
alphacomm/alpharpc | src/AlphaRPC/Worker/WorkerCommunication.php | WorkerCommunication.handleHeartbeatResponse | private function handleHeartbeatResponse()
{
$state = $this->worker->getState();
if (Worker::BUSY == $state) {
/**
* We should only reply in the following cases:
* - A heartbeat is about to expire.
* - We have a result.
*/
return;
}
if (Worker::RESULT_AVAILABLE == $state) {
// A result is available send it to the worker handler.
$this->handleResult();
return;
}
if (in_array($state, array(Worker::READY, Worker::RESULT, Worker::REGISTER))) {
// Update the state to ready and forget about the last job.
$this->worker->cleanup();
// Request a new job
$this->sendToWorkerHandler(new GetJobRequest());
return;
}
if (Worker::SHUTDOWN != $state) {
// The worker did not request a shutdown, however all other states should be handled at this point.
$this->getLogger()->error('Invalid worker state: '.$this->worker->getState().'.');
}
// Worker is completely shutdown, because there is no open connection to the worker handler.
$this->worker->setState(Worker::INVALID);
} | php | private function handleHeartbeatResponse()
{
$state = $this->worker->getState();
if (Worker::BUSY == $state) {
/**
* We should only reply in the following cases:
* - A heartbeat is about to expire.
* - We have a result.
*/
return;
}
if (Worker::RESULT_AVAILABLE == $state) {
// A result is available send it to the worker handler.
$this->handleResult();
return;
}
if (in_array($state, array(Worker::READY, Worker::RESULT, Worker::REGISTER))) {
// Update the state to ready and forget about the last job.
$this->worker->cleanup();
// Request a new job
$this->sendToWorkerHandler(new GetJobRequest());
return;
}
if (Worker::SHUTDOWN != $state) {
// The worker did not request a shutdown, however all other states should be handled at this point.
$this->getLogger()->error('Invalid worker state: '.$this->worker->getState().'.');
}
// Worker is completely shutdown, because there is no open connection to the worker handler.
$this->worker->setState(Worker::INVALID);
} | Handles the heartbeat response from the worker handler. | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Worker/WorkerCommunication.php#L272-L308 |
alphacomm/alpharpc | src/AlphaRPC/Worker/WorkerCommunication.php | WorkerCommunication.onServiceMessage | public function onServiceMessage(MessageInterface $msg)
{
$this->serviceStreamReady = true;
$this->getLogger()->debug('Received Service Message of Type: '.get_class($msg));
if ($msg instanceof ActionListResponse) {
$actions = $msg->getActions();
$this->getLogger()->debug('The action list is: '.implode(', ', $actions).'.');
$this->worker->setActions($actions);
$reply = new Register();
$reply->setActions($actions);
$this->sendToWorkerHandler($reply);
unset($reply);
return;
}
if ($msg instanceof ExecuteJobResponse) {
$requestId = $msg->getRequestId();
$result = $msg->getResult();
$this->getLogger()->debug('Result for: '.$requestId.': '.$result);
$this->worker->setResult($requestId, $result);
return;
}
$this->getLogger()->error('Unknown service response: '.get_class($msg).'.');
} | php | public function onServiceMessage(MessageInterface $msg)
{
$this->serviceStreamReady = true;
$this->getLogger()->debug('Received Service Message of Type: '.get_class($msg));
if ($msg instanceof ActionListResponse) {
$actions = $msg->getActions();
$this->getLogger()->debug('The action list is: '.implode(', ', $actions).'.');
$this->worker->setActions($actions);
$reply = new Register();
$reply->setActions($actions);
$this->sendToWorkerHandler($reply);
unset($reply);
return;
}
if ($msg instanceof ExecuteJobResponse) {
$requestId = $msg->getRequestId();
$result = $msg->getResult();
$this->getLogger()->debug('Result for: '.$requestId.': '.$result);
$this->worker->setResult($requestId, $result);
return;
}
$this->getLogger()->error('Unknown service response: '.get_class($msg).'.');
} | Handles a Message from the Service Handler.
@param MessageInterface $msg | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Worker/WorkerCommunication.php#L315-L344 |
alphacomm/alpharpc | src/AlphaRPC/Worker/WorkerCommunication.php | WorkerCommunication.startJob | public function startJob(ExecuteJobRequest $request)
{
$this->worker->setState(Worker::BUSY);
$requestId = $request->getRequestId();
$action = $request->getAction();
if (!$this->worker->hasAction($action)) {
$this->getLogger()->debug('Action '.$action.' not found.');
$this->sendToWorkerHandler(new ActionNotFound($requestId, $action));
return;
}
$this->getLogger()->debug('Sending new request ('.$requestId.') to action '.$action);
$this->serviceStream->send($request);
} | php | public function startJob(ExecuteJobRequest $request)
{
$this->worker->setState(Worker::BUSY);
$requestId = $request->getRequestId();
$action = $request->getAction();
if (!$this->worker->hasAction($action)) {
$this->getLogger()->debug('Action '.$action.' not found.');
$this->sendToWorkerHandler(new ActionNotFound($requestId, $action));
return;
}
$this->getLogger()->debug('Sending new request ('.$requestId.') to action '.$action);
$this->serviceStream->send($request);
} | Starts a Job.
@param ExecuteJobRequest $request | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Worker/WorkerCommunication.php#L351-L366 |
alphacomm/alpharpc | src/AlphaRPC/Worker/WorkerCommunication.php | WorkerCommunication.heartbeat | public function heartbeat()
{
$state = $this->worker->getState();
if (!in_array($state, array(Worker::BUSY, Worker::READY))) {
return;
}
// Detect manager crash.
$timeout = 2500;
if (!$this->worker->isExpired($timeout)) {
// Worker is pretty active no heartbeat required.
return;
}
if ($this->isWorkerHandlerReady()) {
// Send a heartbeat.
$this->sendToWorkerHandler(new Protocol\Heartbeat());
return;
}
$expiry = 5000 + $this->delay;
if (!$this->worker->isExpired($expiry)) {
return;
}
// Expired, manager already destroyed this instance.
$this->worker->setState(Worker::INVALID);
} | php | public function heartbeat()
{
$state = $this->worker->getState();
if (!in_array($state, array(Worker::BUSY, Worker::READY))) {
return;
}
// Detect manager crash.
$timeout = 2500;
if (!$this->worker->isExpired($timeout)) {
// Worker is pretty active no heartbeat required.
return;
}
if ($this->isWorkerHandlerReady()) {
// Send a heartbeat.
$this->sendToWorkerHandler(new Protocol\Heartbeat());
return;
}
$expiry = 5000 + $this->delay;
if (!$this->worker->isExpired($expiry)) {
return;
}
// Expired, manager already destroyed this instance.
$this->worker->setState(Worker::INVALID);
} | Performs a heartbeat with the Worker Handler. | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Worker/WorkerCommunication.php#L371-L399 |
alphacomm/alpharpc | src/AlphaRPC/Worker/WorkerCommunication.php | WorkerCommunication.handleResult | public function handleResult()
{
// No result
$result = $this->worker->getResult();
if ($result === null) {
return;
}
// Invalid worker state, wait for a response first.
if (!$this->isWorkerHandlerReady()) {
return;
}
$this->sendToWorkerHandler(new Protocol\JobResult($this->worker->getRequestId(), $result));
$this->worker->setState(Worker::RESULT);
} | php | public function handleResult()
{
// No result
$result = $this->worker->getResult();
if ($result === null) {
return;
}
// Invalid worker state, wait for a response first.
if (!$this->isWorkerHandlerReady()) {
return;
}
$this->sendToWorkerHandler(new Protocol\JobResult($this->worker->getRequestId(), $result));
$this->worker->setState(Worker::RESULT);
} | Sends when the Service is done working, this sends the result to the Worker Handler. | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Worker/WorkerCommunication.php#L404-L419 |
alphacomm/alpharpc | src/AlphaRPC/Worker/WorkerCommunication.php | WorkerCommunication.sendToWorkerHandler | public function sendToWorkerHandler(MessageInterface $msg)
{
if (!$this->isWorkerHandlerReady()) {
$this->getLogger()->debug('WorkerHandler socket not ready to send.');
return;
}
$this->workerHandlerReady = false;
$this->workerHandlerStream->send($msg);
} | php | public function sendToWorkerHandler(MessageInterface $msg)
{
if (!$this->isWorkerHandlerReady()) {
$this->getLogger()->debug('WorkerHandler socket not ready to send.');
return;
}
$this->workerHandlerReady = false;
$this->workerHandlerStream->send($msg);
} | Send the given Message to the Worker Handler.
@param MessageInterface $msg | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Worker/WorkerCommunication.php#L426-L436 |
alphacomm/alpharpc | src/AlphaRPC/Worker/WorkerCommunication.php | WorkerCommunication.sendToService | public function sendToService(MessageInterface $msg)
{
if (!$this->isServiceStreamReady()) {
$this->getLogger()->debug('Service socket not ready to send.');
return;
}
$this->getLogger()->debug('Sending to service.');
$this->serviceStreamReady = false;
$this->serviceStream->send($msg);
} | php | public function sendToService(MessageInterface $msg)
{
if (!$this->isServiceStreamReady()) {
$this->getLogger()->debug('Service socket not ready to send.');
return;
}
$this->getLogger()->debug('Sending to service.');
$this->serviceStreamReady = false;
$this->serviceStream->send($msg);
} | Send the given Message to the Service.
@param MessageInterface $msg | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Worker/WorkerCommunication.php#L443-L454 |
alphacomm/alpharpc | src/AlphaRPC/Worker/WorkerCommunication.php | WorkerCommunication.setLogger | public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
if ($this->serviceStream instanceof LoggerAwareInterface) {
$this->serviceStream->setLogger($this->getLogger());
}
if ($this->workerHandlerStream instanceof LoggerAwareInterface) {
$this->workerHandlerStream->setLogger($this->getLogger());
}
return $this;
} | php | public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
if ($this->serviceStream instanceof LoggerAwareInterface) {
$this->serviceStream->setLogger($this->getLogger());
}
if ($this->workerHandlerStream instanceof LoggerAwareInterface) {
$this->workerHandlerStream->setLogger($this->getLogger());
}
return $this;
} | Set the logger.
The logger should be a callable that accepts 2 parameters, a
string $message and an integer $priority.
@param LoggerInterface $logger
@return AlphaRPC | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Worker/WorkerCommunication.php#L486-L499 |
plumphp/plum-excel | src/ExcelWriter.php | ExcelWriter.writeItem | public function writeItem($item)
{
if ($this->autoDetectHeader && $this->header === null) {
$this->handleAutoDetectHeaders($item);
}
if (is_array($item)) {
$keys = array_keys($item);
} elseif ($this->header && is_object($item)) {
$keys = $this->header;
} else {
throw new \InvalidArgumentException(sprintf(
'Plum\PlumExcel\ExcelWriter currently only supports array items or objects if headers are set using '.
'the setHeader() method. You have passed an item of type "%s" to writeItem().',
gettype($item)
));
}
$column = 0;
foreach ($keys as $key) {
$value = Vale::get($item, $key);
$this->excel->getActiveSheet()->setCellValueByColumnAndRow($column, $this->currentRow, $value);
++$column;
}
++$this->currentRow;
} | php | public function writeItem($item)
{
if ($this->autoDetectHeader && $this->header === null) {
$this->handleAutoDetectHeaders($item);
}
if (is_array($item)) {
$keys = array_keys($item);
} elseif ($this->header && is_object($item)) {
$keys = $this->header;
} else {
throw new \InvalidArgumentException(sprintf(
'Plum\PlumExcel\ExcelWriter currently only supports array items or objects if headers are set using '.
'the setHeader() method. You have passed an item of type "%s" to writeItem().',
gettype($item)
));
}
$column = 0;
foreach ($keys as $key) {
$value = Vale::get($item, $key);
$this->excel->getActiveSheet()->setCellValueByColumnAndRow($column, $this->currentRow, $value);
++$column;
}
++$this->currentRow;
} | Write the given item.
@param mixed $item | https://github.com/plumphp/plum-excel/blob/cc1dd308901b836676e077b13f01c0c87845c5f6/src/ExcelWriter.php#L112-L137 |
plumphp/plum-excel | src/ExcelWriter.php | ExcelWriter.prepare | public function prepare()
{
if ($this->excel === null) {
$this->excel = new PHPExcel();
}
if ($this->header !== null) {
$this->writeItem($this->header);
}
} | php | public function prepare()
{
if ($this->excel === null) {
$this->excel = new PHPExcel();
}
if ($this->header !== null) {
$this->writeItem($this->header);
}
} | Prepare the writer. | https://github.com/plumphp/plum-excel/blob/cc1dd308901b836676e077b13f01c0c87845c5f6/src/ExcelWriter.php#L142-L151 |
plumphp/plum-excel | src/ExcelWriter.php | ExcelWriter.finish | public function finish()
{
$writer = $this->writer;
if (!$writer) {
$writer = PHPExcel_IOFactory::createWriter($this->excel, $this->format);
}
$writer->save($this->filename);
} | php | public function finish()
{
$writer = $this->writer;
if (!$writer) {
$writer = PHPExcel_IOFactory::createWriter($this->excel, $this->format);
}
$writer->save($this->filename);
} | Finish the writer. | https://github.com/plumphp/plum-excel/blob/cc1dd308901b836676e077b13f01c0c87845c5f6/src/ExcelWriter.php#L156-L163 |
strident/Aegis | src/Aegis/Authentication/Authenticator/DelegatingAuthenticator.php | DelegatingAuthenticator.authenticate | public function authenticate(TokenInterface $token)
{
$authenticator = $this->delegateAuthenticator($token);
return $authenticator->authenticate($token);
} | php | public function authenticate(TokenInterface $token)
{
$authenticator = $this->delegateAuthenticator($token);
return $authenticator->authenticate($token);
} | {@inheritDoc} | https://github.com/strident/Aegis/blob/954bd3d24808d77271844276ae31b41f4f039bd5/src/Aegis/Authentication/Authenticator/DelegatingAuthenticator.php#L85-L90 |
strident/Aegis | src/Aegis/Authentication/Authenticator/DelegatingAuthenticator.php | DelegatingAuthenticator.present | public function present()
{
foreach ($this->authenticators as $authenticator) {
$token = $authenticator->present();
if ($token instanceof TokenInterface) {
return $token;
}
}
return false;
} | php | public function present()
{
foreach ($this->authenticators as $authenticator) {
$token = $authenticator->present();
if ($token instanceof TokenInterface) {
return $token;
}
}
return false;
} | {@inheritDoc} | https://github.com/strident/Aegis/blob/954bd3d24808d77271844276ae31b41f4f039bd5/src/Aegis/Authentication/Authenticator/DelegatingAuthenticator.php#L95-L106 |
strident/Aegis | src/Aegis/Authentication/Authenticator/DelegatingAuthenticator.php | DelegatingAuthenticator.delegateAuthenticator | private function delegateAuthenticator(TokenInterface $token)
{
if ( ! $authenticator = $this->resolveAuthenticator($token)) {
throw new \RuntimeException(sprintf(
'No authentication authenticator found for token: "%s".',
get_class($token)
));
}
return $authenticator;
} | php | private function delegateAuthenticator(TokenInterface $token)
{
if ( ! $authenticator = $this->resolveAuthenticator($token)) {
throw new \RuntimeException(sprintf(
'No authentication authenticator found for token: "%s".',
get_class($token)
));
}
return $authenticator;
} | Delegate a authenticator for a token.
@param TokenInterface $token
@return DelegatingAuthenticator | https://github.com/strident/Aegis/blob/954bd3d24808d77271844276ae31b41f4f039bd5/src/Aegis/Authentication/Authenticator/DelegatingAuthenticator.php#L123-L133 |
strident/Aegis | src/Aegis/Authentication/Authenticator/DelegatingAuthenticator.php | DelegatingAuthenticator.resolveAuthenticator | private function resolveAuthenticator(TokenInterface $token)
{
foreach ($this->authenticators as $authenticator) {
if ($authenticator->supports($token)) {
return $authenticator;
}
}
return false;
} | php | private function resolveAuthenticator(TokenInterface $token)
{
foreach ($this->authenticators as $authenticator) {
if ($authenticator->supports($token)) {
return $authenticator;
}
}
return false;
} | Resolve a token to its authenticator.
@param TokenInterface $token
@return mixed | https://github.com/strident/Aegis/blob/954bd3d24808d77271844276ae31b41f4f039bd5/src/Aegis/Authentication/Authenticator/DelegatingAuthenticator.php#L142-L151 |
Tuna-CMS/tuna-bundle | src/Tuna/Bundle/MenuBundle/Factory/MenuFactory.php | MenuFactory.getTypeConfig | protected function getTypeConfig($type = null)
{
if ($type == null) {
$type = static::BASE_TYPE;
}
if (is_object($type)) {
$type = $this->getTypeName($type);
}
if (!$this->types->containsKey($type)) {
$this->throwInvalidTypeException($type);
}
return $this->types->get($type);
} | php | protected function getTypeConfig($type = null)
{
if ($type == null) {
$type = static::BASE_TYPE;
}
if (is_object($type)) {
$type = $this->getTypeName($type);
}
if (!$this->types->containsKey($type)) {
$this->throwInvalidTypeException($type);
}
return $this->types->get($type);
} | @param string $type
@return TypeConfig
@throws \Exception | https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/MenuBundle/Factory/MenuFactory.php#L91-L106 |
tigron/skeleton-error | lib/Skeleton/Error/Handler/Basic.php | Basic.handle | public function handle() {
// If this is a reqular exception, always quit, else check the type
if (!($this->exception instanceof \ErrorException)) {
$this->quit = true;
} else {
// Only quit after specific error types
switch ($this->exception->getSeverity()) {
case E_ERROR:
case E_CORE_ERROR:
case E_USER_ERROR:
$this->quit = true;
}
}
return self::get_html($this->exception);
} | php | public function handle() {
// If this is a reqular exception, always quit, else check the type
if (!($this->exception instanceof \ErrorException)) {
$this->quit = true;
} else {
// Only quit after specific error types
switch ($this->exception->getSeverity()) {
case E_ERROR:
case E_CORE_ERROR:
case E_USER_ERROR:
$this->quit = true;
}
}
return self::get_html($this->exception);
} | Handle an error with the most basic handler
@return string | https://github.com/tigron/skeleton-error/blob/c0671ad52a4386d95179f1c47bedfdf754ee3611/lib/Skeleton/Error/Handler/Basic.php#L24-L39 |
tigron/skeleton-error | lib/Skeleton/Error/Handler/Basic.php | Basic.get_subject | public static function get_subject($exception) {
$application = null;
try {
$application = \Skeleton\Core\Application::get();
} catch (\Exception $e) {}
if ($application === null) {
$hostname = 'unknown';
$name = 'unknown';
} else {
$hostname = $application->hostname;
$name = $application->name;
}
if ($exception instanceof \ErrorException) {
$subject = get_class($exception) . ' (' . \Skeleton\Error\Util\Misc::translate_error_code($exception->getSeverity()) . ') on ' . $hostname . ' (' . $name . ')';
} else {
$subject = get_class($exception) . ' on ' . $hostname . ' (' . $name . ')';
}
return $subject;
} | php | public static function get_subject($exception) {
$application = null;
try {
$application = \Skeleton\Core\Application::get();
} catch (\Exception $e) {}
if ($application === null) {
$hostname = 'unknown';
$name = 'unknown';
} else {
$hostname = $application->hostname;
$name = $application->name;
}
if ($exception instanceof \ErrorException) {
$subject = get_class($exception) . ' (' . \Skeleton\Error\Util\Misc::translate_error_code($exception->getSeverity()) . ') on ' . $hostname . ' (' . $name . ')';
} else {
$subject = get_class($exception) . ' on ' . $hostname . ' (' . $name . ')';
}
return $subject;
} | Produce a subject based on the error
@param $exception (can be \Throwable or \Exception)
@return string | https://github.com/tigron/skeleton-error/blob/c0671ad52a4386d95179f1c47bedfdf754ee3611/lib/Skeleton/Error/Handler/Basic.php#L61-L83 |
tigron/skeleton-error | lib/Skeleton/Error/Handler/Basic.php | Basic.get_html | public static function get_html($exception) {
$subject = self::get_subject($exception);
if ($exception instanceof \ErrorException) {
$error_type = \Skeleton\Error\Util\Misc::translate_error_code($exception->getSeverity());
} else {
$error_type = 'Exception';
}
$error_info = '';
$error_info .= 'Error: ' . $exception->getMessage() . "\n";
$error_info .= 'Type: ' . $error_type . "\n";
$error_info .= 'File: ' . $exception->getFile() . "\n";
$error_info .= 'Line: ' . $exception->getLine() . "\n\n";
$error_info .= 'Time: ' . date('Y-m-d H:i:s') . "\n";
$html =
'<html>' .
' <head>' .
' <title>' . $subject . '</title>' .
' <style type="text/css">' .
' body { font-family: sans-serif; background: #eee; } ' .
' pre { border: 1px solid #1b2582; background: #ccc; padding: 5px; }' .
' h1 { width: 100%; background: #183452; font-weight: bold; color: #fff; padding: 2px; font-size: 16px;} ' .
' h2 { font-size: 15px; } ' .
' </style>' .
' </head>' .
' <body>' .
' <h1>' . $subject . '</h1>';
$html .= '<h2>Message</h2> <pre>' . $exception->getMessage() . '</pre>';
$html .= '<h2>Info</h2> <pre>' . $error_info . '</pre>';
// Backtraces are not very useful for anything else but real exceptions
if (!($exception instanceof \ErrorException)) {
ob_start();
debug_print_backtrace();
$backtrace = ob_get_contents();
ob_end_clean();
$html .= '<h2>Backtrace</h2> <pre>' . $backtrace . '</pre>';
}
$vartrace = [
'_GET' => isset($_GET) ? $_GET : null,
'_POST' => isset($_POST) ? $_POST : null,
'_COOKIE' => isset($_COOKIE) ? $_COOKIE : null,
'_SESSION' => isset($_SESSION) ? $_SESSION : null,
'_SERVER' => isset($_SERVER) ? $_SERVER : null
];
$html .= '<h2>Vartrace</h2> <pre> ' . print_r($vartrace, true) . '</pre>';
$html .=
' </body>' .
'</html>';
return $html;
} | php | public static function get_html($exception) {
$subject = self::get_subject($exception);
if ($exception instanceof \ErrorException) {
$error_type = \Skeleton\Error\Util\Misc::translate_error_code($exception->getSeverity());
} else {
$error_type = 'Exception';
}
$error_info = '';
$error_info .= 'Error: ' . $exception->getMessage() . "\n";
$error_info .= 'Type: ' . $error_type . "\n";
$error_info .= 'File: ' . $exception->getFile() . "\n";
$error_info .= 'Line: ' . $exception->getLine() . "\n\n";
$error_info .= 'Time: ' . date('Y-m-d H:i:s') . "\n";
$html =
'<html>' .
' <head>' .
' <title>' . $subject . '</title>' .
' <style type="text/css">' .
' body { font-family: sans-serif; background: #eee; } ' .
' pre { border: 1px solid #1b2582; background: #ccc; padding: 5px; }' .
' h1 { width: 100%; background: #183452; font-weight: bold; color: #fff; padding: 2px; font-size: 16px;} ' .
' h2 { font-size: 15px; } ' .
' </style>' .
' </head>' .
' <body>' .
' <h1>' . $subject . '</h1>';
$html .= '<h2>Message</h2> <pre>' . $exception->getMessage() . '</pre>';
$html .= '<h2>Info</h2> <pre>' . $error_info . '</pre>';
// Backtraces are not very useful for anything else but real exceptions
if (!($exception instanceof \ErrorException)) {
ob_start();
debug_print_backtrace();
$backtrace = ob_get_contents();
ob_end_clean();
$html .= '<h2>Backtrace</h2> <pre>' . $backtrace . '</pre>';
}
$vartrace = [
'_GET' => isset($_GET) ? $_GET : null,
'_POST' => isset($_POST) ? $_POST : null,
'_COOKIE' => isset($_COOKIE) ? $_COOKIE : null,
'_SESSION' => isset($_SESSION) ? $_SESSION : null,
'_SERVER' => isset($_SERVER) ? $_SERVER : null
];
$html .= '<h2>Vartrace</h2> <pre> ' . print_r($vartrace, true) . '</pre>';
$html .=
' </body>' .
'</html>';
return $html;
} | Produce some HTML around the error
@param $exception (can be \Throwable or \Exception)
@return string | https://github.com/tigron/skeleton-error/blob/c0671ad52a4386d95179f1c47bedfdf754ee3611/lib/Skeleton/Error/Handler/Basic.php#L91-L150 |
harp-orm/harp | src/Repo.php | Repo.loadRelFor | public function loadRelFor(Models $models, $relName, $flags = null)
{
$rel = $this->getRelOrError($relName);
$foreign = $rel->loadModelsIfAvailable($models, $flags);
$rel->linkModels($models, $foreign, function (AbstractLink $link) {
$class = get_class($link->getModel());
$class::getRepo()->addLink($link);
});
return $foreign;
} | php | public function loadRelFor(Models $models, $relName, $flags = null)
{
$rel = $this->getRelOrError($relName);
$foreign = $rel->loadModelsIfAvailable($models, $flags);
$rel->linkModels($models, $foreign, function (AbstractLink $link) {
$class = get_class($link->getModel());
$class::getRepo()->addLink($link);
});
return $foreign;
} | Load models for a given relation.
@param Models $models
@param string $relName
@return Models
@throws InvalidArgumentException If $relName does not belong to repo | https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Repo.php#L137-L149 |
harp-orm/harp | src/Repo.php | Repo.loadAllRelsFor | public function loadAllRelsFor(Models $models, array $rels, $flags = null)
{
$rels = Arr::toAssoc($rels);
foreach ($rels as $relName => $childRels) {
$foreign = $this->loadRelFor($models, $relName, $flags);
if ($childRels) {
$rel = $this->getRel($relName);
$rel->getRepo()->loadAllRelsFor($foreign, $childRels, $flags);
}
}
return $this;
} | php | public function loadAllRelsFor(Models $models, array $rels, $flags = null)
{
$rels = Arr::toAssoc($rels);
foreach ($rels as $relName => $childRels) {
$foreign = $this->loadRelFor($models, $relName, $flags);
if ($childRels) {
$rel = $this->getRel($relName);
$rel->getRepo()->loadAllRelsFor($foreign, $childRels, $flags);
}
}
return $this;
} | Load all the models for the provided relations. This is the meat of the eager loading
@param Models $models
@param array $rels
@param int $flags
@return Repo $this | https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Repo.php#L159-L173 |
harp-orm/harp | src/Repo.php | Repo.updateModels | public function updateModels(Models $models)
{
foreach ($models as $model) {
if ($model->isSoftDeleted()) {
$this->dispatchBeforeEvent($model, Event::DELETE);
} else {
$this->dispatchBeforeEvent($model, Event::UPDATE);
$this->dispatchBeforeEvent($model, Event::SAVE);
}
}
$this->updateAll()->executeModels($models);
foreach ($models as $model) {
$model->resetOriginals();
if ($model->isSoftDeleted()) {
$this->dispatchAfterEvent($model, Event::DELETE);
} else {
$this->dispatchAfterEvent($model, Event::UPDATE);
$this->dispatchAfterEvent($model, Event::SAVE);
}
}
return $this;
} | php | public function updateModels(Models $models)
{
foreach ($models as $model) {
if ($model->isSoftDeleted()) {
$this->dispatchBeforeEvent($model, Event::DELETE);
} else {
$this->dispatchBeforeEvent($model, Event::UPDATE);
$this->dispatchBeforeEvent($model, Event::SAVE);
}
}
$this->updateAll()->executeModels($models);
foreach ($models as $model) {
$model->resetOriginals();
if ($model->isSoftDeleted()) {
$this->dispatchAfterEvent($model, Event::DELETE);
} else {
$this->dispatchAfterEvent($model, Event::UPDATE);
$this->dispatchAfterEvent($model, Event::SAVE);
}
}
return $this;
} | Call all the events associated with model updates. Perform the update itself.
@param Models $models
@return Repo $this | https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Repo.php#L181-L207 |
harp-orm/harp | src/Repo.php | Repo.deleteModels | public function deleteModels(Models $models)
{
foreach ($models as $model) {
$this->dispatchBeforeEvent($model, Event::DELETE);
}
$this->deleteAll()->executeModels($models);
foreach ($models as $model) {
$this->dispatchAfterEvent($model, Event::DELETE);
}
return $this;
} | php | public function deleteModels(Models $models)
{
foreach ($models as $model) {
$this->dispatchBeforeEvent($model, Event::DELETE);
}
$this->deleteAll()->executeModels($models);
foreach ($models as $model) {
$this->dispatchAfterEvent($model, Event::DELETE);
}
return $this;
} | Call all the events associated with model deletion. Perform the deletion itself.
@param Models $models
@return Repo $this | https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Repo.php#L215-L228 |
harp-orm/harp | src/Repo.php | Repo.insertModels | public function insertModels(Models $models)
{
foreach ($models as $model) {
$this->dispatchBeforeEvent($model, Event::INSERT);
$this->dispatchBeforeEvent($model, Event::SAVE);
}
$this->insertAll()->executeModels($models);
foreach ($models as $model) {
$model
->resetOriginals()
->setState(State::SAVED);
$this->dispatchAfterEvent($model, Event::INSERT);
$this->dispatchAfterEvent($model, Event::SAVE);
}
return $this;
} | php | public function insertModels(Models $models)
{
foreach ($models as $model) {
$this->dispatchBeforeEvent($model, Event::INSERT);
$this->dispatchBeforeEvent($model, Event::SAVE);
}
$this->insertAll()->executeModels($models);
foreach ($models as $model) {
$model
->resetOriginals()
->setState(State::SAVED);
$this->dispatchAfterEvent($model, Event::INSERT);
$this->dispatchAfterEvent($model, Event::SAVE);
}
return $this;
} | Call all the events associated with model insertion. Perform the insertion itself.
@param Models $models
@return Repo $this | https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Repo.php#L236-L255 |
aaronadal/twig-list-loop | src/Twig/ListNode.php | ListNode.compile | public function compile(Twig_Compiler $compiler)
{
$compiler
->addDebugInfo($this);
// Store the loop result in the listTarget variable.
$compiler
->write("\n")
->subcompile($this->getNode('listTarget'))
->raw(" = array();\n")
->subcompile($this->getNode('listLoop'))
->raw("\n");
// Store the else result in the $else variable.
if($this->hasNode('else')) {
$compiler
->write("ob_start();\n")
->subcompile($this->getNode('else'))
->write("\n")
->write("\$else = ob_get_clean();\n\n");
}
else {
$compiler
->write("\$else = '';\n\n");
}
// Store the additional arguments in the $args variable.
if($this->hasNode('args')) {
$compiler
->write("\$args = ")
->subcompile($this->getNode('args'))
->raw(";\n\n");
}
else {
$compiler
->write("\$args = array();\n\n");
}
// Put the additional args in the $context.
$compiler
->write("foreach(\$args as \$argKey => \$argVal):\n")
->indent()
->write("\$context[\$argKey] = \$argVal;\n")
->outdent()
->write("endforeach;\n\n");
// Put the list and the else in the context.
$compiler
->write("\$context['list'] = ")
->subcompile($this->getNode('listTarget'))
->raw(";\n")
->write("\$context['else'] = \$else;\n\n");
// Render the list template.
$compiler
->write('$this->loadTemplate(')
->subcompile($this->getNode('template'))
->raw(', ')
->repr($this->getTemplateName())
->raw(', ')
->repr($this->getTemplateLine())
->raw(')')
->write("->display(\$context);\n\n");
// Unset the additional arguments from the context.
$compiler
->write("foreach(\$args as \$argKey => \$argVal):\n")
->indent()
->write("unset(\$context[\$argKey]);\n")
->outdent()
->write("endforeach;\n\n");
// Unset the rest of variables.
$compiler
->write("unset(\$args);\n")
->write("unset(")
->subcompile($this->getNode('listTarget'))
->raw(", \$context['list']);\n")
->write("unset(\$else, \$context['else']);\n");
} | php | public function compile(Twig_Compiler $compiler)
{
$compiler
->addDebugInfo($this);
// Store the loop result in the listTarget variable.
$compiler
->write("\n")
->subcompile($this->getNode('listTarget'))
->raw(" = array();\n")
->subcompile($this->getNode('listLoop'))
->raw("\n");
// Store the else result in the $else variable.
if($this->hasNode('else')) {
$compiler
->write("ob_start();\n")
->subcompile($this->getNode('else'))
->write("\n")
->write("\$else = ob_get_clean();\n\n");
}
else {
$compiler
->write("\$else = '';\n\n");
}
// Store the additional arguments in the $args variable.
if($this->hasNode('args')) {
$compiler
->write("\$args = ")
->subcompile($this->getNode('args'))
->raw(";\n\n");
}
else {
$compiler
->write("\$args = array();\n\n");
}
// Put the additional args in the $context.
$compiler
->write("foreach(\$args as \$argKey => \$argVal):\n")
->indent()
->write("\$context[\$argKey] = \$argVal;\n")
->outdent()
->write("endforeach;\n\n");
// Put the list and the else in the context.
$compiler
->write("\$context['list'] = ")
->subcompile($this->getNode('listTarget'))
->raw(";\n")
->write("\$context['else'] = \$else;\n\n");
// Render the list template.
$compiler
->write('$this->loadTemplate(')
->subcompile($this->getNode('template'))
->raw(', ')
->repr($this->getTemplateName())
->raw(', ')
->repr($this->getTemplateLine())
->raw(')')
->write("->display(\$context);\n\n");
// Unset the additional arguments from the context.
$compiler
->write("foreach(\$args as \$argKey => \$argVal):\n")
->indent()
->write("unset(\$context[\$argKey]);\n")
->outdent()
->write("endforeach;\n\n");
// Unset the rest of variables.
$compiler
->write("unset(\$args);\n")
->write("unset(")
->subcompile($this->getNode('listTarget'))
->raw(", \$context['list']);\n")
->write("unset(\$else, \$context['else']);\n");
} | {@inheritdoc} | https://github.com/aaronadal/twig-list-loop/blob/266d650bab1673e08a2b71df3fd1f285feccc8a9/src/Twig/ListNode.php#L49-L128 |
ekyna/AdminBundle | Dashboard/Widget/Type/AbstractWidgetType.php | AbstractWidgetType.buildWidget | public function buildWidget(WidgetInterface $widget, array $options)
{
$attr = ['name' => $options['name']];
$classes = [];
foreach (array('xs', 'sm', 'md', 'lg') as $sizing) {
$size = $options['col_'.$sizing];
if (0 < $size && $size < 12) {
$classes[] = 'col-'. $sizing. '-' . $options['col_'.$sizing];
}
}
if (empty($classes)) {
$classes[] = 'col-md-12';
}
$attr['class'] = implode(' ', $classes);
$widget->setOptions(array_merge($options, array('attr' => $attr)));
} | php | public function buildWidget(WidgetInterface $widget, array $options)
{
$attr = ['name' => $options['name']];
$classes = [];
foreach (array('xs', 'sm', 'md', 'lg') as $sizing) {
$size = $options['col_'.$sizing];
if (0 < $size && $size < 12) {
$classes[] = 'col-'. $sizing. '-' . $options['col_'.$sizing];
}
}
if (empty($classes)) {
$classes[] = 'col-md-12';
}
$attr['class'] = implode(' ', $classes);
$widget->setOptions(array_merge($options, array('attr' => $attr)));
} | {@inheritdoc} | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Dashboard/Widget/Type/AbstractWidgetType.php#L19-L35 |
ekyna/AdminBundle | Dashboard/Widget/Type/AbstractWidgetType.php | AbstractWidgetType.configureOptions | public function configureOptions(OptionsResolver $resolver)
{
/**
* Validates the column min size.
*
* @param int $value
* @return bool
*/
$minSizeValidator = function ($value) {
return 0 < $value && $value < 13;
};
/**
* Normalizes the column size.
*
* @param $min
* @param $value
* @return mixed
*/
$sizeNormalizer = function ($min, $value) {
return $min > $value ? $min : $value;
};
/** @noinspection PhpUnusedParameterInspection */
$resolver
->setDefaults(array(
'name' => null,
'title' => null,
'col_xs_min' => 12,
'col_sm_min' => 12,
'col_md_min' => 6,
'col_lg_min' => 6,
'col_xs' => 12,
'col_sm' => 12,
'col_md' => 12,
'col_lg' => 12,
'position' => 0,
'css_path' => null,
'js_path' => null,
))
->setRequired(array('name', 'title'))
->setAllowedTypes(array(
'name' => 'string',
'title' => 'string',
'col_xs_min' => 'int',
'col_sm_min' => 'int',
'col_md_min' => 'int',
'col_lg_min' => 'int',
'col_xs' => 'int',
'col_sm' => 'int',
'col_md' => 'int',
'col_lg' => 'int',
'position' => 'int',
'css_path' => array('null', 'string'),
'js_path' => array('null', 'string'),
))
->setAllowedValues(array(
'col_xs_min' => $minSizeValidator,
'col_sm_min' => $minSizeValidator,
'col_md_min' => $minSizeValidator,
'col_lg_min' => $minSizeValidator,
))
->setNormalizer('col_xs', function (Options $options, $value) use ($sizeNormalizer) {
return $sizeNormalizer($options['col_xs_min'], $value);
})
->setNormalizer('col_sm', function (Options $options, $value) use ($sizeNormalizer) {
return $sizeNormalizer($options['col_sm_min'], $value);
})
->setNormalizer('col_md', function (Options $options, $value) use ($sizeNormalizer) {
return $sizeNormalizer($options['col_md_min'], $value);
})
->setNormalizer('col_lg', function (Options $options, $value) use ($sizeNormalizer) {
return $sizeNormalizer($options['col_lg_min'], $value);
})
->setNormalizer('position', function (Options $options, $value) use ($sizeNormalizer) {
return 0 > $value ? 0 : $value;
})
;
} | php | public function configureOptions(OptionsResolver $resolver)
{
/**
* Validates the column min size.
*
* @param int $value
* @return bool
*/
$minSizeValidator = function ($value) {
return 0 < $value && $value < 13;
};
/**
* Normalizes the column size.
*
* @param $min
* @param $value
* @return mixed
*/
$sizeNormalizer = function ($min, $value) {
return $min > $value ? $min : $value;
};
/** @noinspection PhpUnusedParameterInspection */
$resolver
->setDefaults(array(
'name' => null,
'title' => null,
'col_xs_min' => 12,
'col_sm_min' => 12,
'col_md_min' => 6,
'col_lg_min' => 6,
'col_xs' => 12,
'col_sm' => 12,
'col_md' => 12,
'col_lg' => 12,
'position' => 0,
'css_path' => null,
'js_path' => null,
))
->setRequired(array('name', 'title'))
->setAllowedTypes(array(
'name' => 'string',
'title' => 'string',
'col_xs_min' => 'int',
'col_sm_min' => 'int',
'col_md_min' => 'int',
'col_lg_min' => 'int',
'col_xs' => 'int',
'col_sm' => 'int',
'col_md' => 'int',
'col_lg' => 'int',
'position' => 'int',
'css_path' => array('null', 'string'),
'js_path' => array('null', 'string'),
))
->setAllowedValues(array(
'col_xs_min' => $minSizeValidator,
'col_sm_min' => $minSizeValidator,
'col_md_min' => $minSizeValidator,
'col_lg_min' => $minSizeValidator,
))
->setNormalizer('col_xs', function (Options $options, $value) use ($sizeNormalizer) {
return $sizeNormalizer($options['col_xs_min'], $value);
})
->setNormalizer('col_sm', function (Options $options, $value) use ($sizeNormalizer) {
return $sizeNormalizer($options['col_sm_min'], $value);
})
->setNormalizer('col_md', function (Options $options, $value) use ($sizeNormalizer) {
return $sizeNormalizer($options['col_md_min'], $value);
})
->setNormalizer('col_lg', function (Options $options, $value) use ($sizeNormalizer) {
return $sizeNormalizer($options['col_lg_min'], $value);
})
->setNormalizer('position', function (Options $options, $value) use ($sizeNormalizer) {
return 0 > $value ? 0 : $value;
})
;
} | {@inheritdoc} | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Dashboard/Widget/Type/AbstractWidgetType.php#L40-L118 |
Phpillip/phpillip | src/Console/Command/WatchCommand.php | WatchCommand.initialize | protected function initialize(InputInterface $input, OutputInterface $output)
{
$this->command = $this->getApplication()->get('phpillip:build');
$this->input = new ArrayInput(['command' => $this->command->getName()]);
} | php | protected function initialize(InputInterface $input, OutputInterface $output)
{
$this->command = $this->getApplication()->get('phpillip:build');
$this->input = new ArrayInput(['command' => $this->command->getName()]);
} | {@inheritdoc} | https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Console/Command/WatchCommand.php#L54-L58 |
Phpillip/phpillip | src/Console/Command/WatchCommand.php | WatchCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$period = $input->getOption('period');
$source = $this->getApplication()->getKernel()['root'];
$this->build($output);
$output->writeln(sprintf('[ Watching for changes in <comment>%s</comment> ]', $source));
while (true) {
$finder = new Finder();
if ($finder->in($source)->date(sprintf('since %s', $this->lastBuild->format('c')))->count()) {
$this->build($output);
}
sleep($period);
}
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$period = $input->getOption('period');
$source = $this->getApplication()->getKernel()['root'];
$this->build($output);
$output->writeln(sprintf('[ Watching for changes in <comment>%s</comment> ]', $source));
while (true) {
$finder = new Finder();
if ($finder->in($source)->date(sprintf('since %s', $this->lastBuild->format('c')))->count()) {
$this->build($output);
}
sleep($period);
}
} | {@inheritdoc} | https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Console/Command/WatchCommand.php#L63-L81 |
Phpillip/phpillip | src/Console/Command/WatchCommand.php | WatchCommand.build | protected function build(OutputInterface $output)
{
$this->command->run($this->input, $output);
$this->lastBuild = new DateTime();
} | php | protected function build(OutputInterface $output)
{
$this->command->run($this->input, $output);
$this->lastBuild = new DateTime();
} | Run the build command
@param OutputInterface $output | https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Console/Command/WatchCommand.php#L88-L93 |
smalldb/libSmalldb | class/JsonDirBackend.php | JsonDirBackend.initializeBackend | public function initializeBackend(array $config, JsonDirReader $custom_json_dir_reader = null)
{
parent::initializeBackend($config);
// Get base dir (constants are available)
$base_dir = $custom_json_dir_reader ? $custom_json_dir_reader->getBaseDir()
: Utils::filename_format($config['base_dir'], array());
$machine_type_table = null;
// Load machine definitions from APC cache
if (!empty($config['cache_disabled']) || !function_exists('apcu_fetch')) {
$cache_disabled = true;
$cache_loaded = false;
$cache_mtime = 0;
} else {
$cache_disabled = false;
$cache_key = get_class($this).':'.$base_dir;
$cache_data = apcu_fetch($cache_key, $cache_loaded);
if ($cache_loaded) {
list($machine_type_table, $cache_mtime) = $cache_data;
//debug_dump($this->machine_type_table, 'Cached @ '.strftime('%F %T', $cache_mtime));
} else {
$cache_mtime = 0;
}
}
// Prepare configuration reader
$config_reader = $custom_json_dir_reader ?? new JsonDirReader($base_dir);
$config_reader->detectConfiguration();
$latest_mtime = $config_reader->getLatestMTime();
// Load data if cache is obsolete
if (!$cache_loaded || $latest_mtime >= $cache_mtime) {
//debug_msg('Machine type table cache miss. Reloading...');
$machine_type_table = $config_reader->loadConfiguration();
if (!$cache_disabled) {
apcu_store($cache_key, array($machine_type_table, $latest_mtime));
}
}
if ($machine_type_table !== null) {
$this->registerAllMachineTypes($machine_type_table);
} else {
throw new RuntimeException("Caching logic failed when loading backend configuration.");
}
} | php | public function initializeBackend(array $config, JsonDirReader $custom_json_dir_reader = null)
{
parent::initializeBackend($config);
// Get base dir (constants are available)
$base_dir = $custom_json_dir_reader ? $custom_json_dir_reader->getBaseDir()
: Utils::filename_format($config['base_dir'], array());
$machine_type_table = null;
// Load machine definitions from APC cache
if (!empty($config['cache_disabled']) || !function_exists('apcu_fetch')) {
$cache_disabled = true;
$cache_loaded = false;
$cache_mtime = 0;
} else {
$cache_disabled = false;
$cache_key = get_class($this).':'.$base_dir;
$cache_data = apcu_fetch($cache_key, $cache_loaded);
if ($cache_loaded) {
list($machine_type_table, $cache_mtime) = $cache_data;
//debug_dump($this->machine_type_table, 'Cached @ '.strftime('%F %T', $cache_mtime));
} else {
$cache_mtime = 0;
}
}
// Prepare configuration reader
$config_reader = $custom_json_dir_reader ?? new JsonDirReader($base_dir);
$config_reader->detectConfiguration();
$latest_mtime = $config_reader->getLatestMTime();
// Load data if cache is obsolete
if (!$cache_loaded || $latest_mtime >= $cache_mtime) {
//debug_msg('Machine type table cache miss. Reloading...');
$machine_type_table = $config_reader->loadConfiguration();
if (!$cache_disabled) {
apcu_store($cache_key, array($machine_type_table, $latest_mtime));
}
}
if ($machine_type_table !== null) {
$this->registerAllMachineTypes($machine_type_table);
} else {
throw new RuntimeException("Caching logic failed when loading backend configuration.");
}
} | Constructor.
Options:
- `machine_global_config`: Config wich will be merged into all state machines
- `cache_disabled`: Don't use caching
- `file_readers`: File readers map (regexp -> class name)
@param array $config Backend configuration.
@param JsonDirReader|null $custom_json_dir_reader | https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/JsonDirBackend.php#L55-L102 |
prooph/processing | library/Processor/Process.php | Process.setUp | public static function setUp(NodeName $nodeName, array $tasks, array $config = array())
{
/** @var $instance Process */
$instance = new static();
$instance->assertConfig($config);
$processId = ProcessId::generate();
$taskList = TaskList::scheduleTasks(TaskListId::linkWith($nodeName, $processId), $tasks);
$instance->recordThat(ProcessWasSetUp::with($processId, $taskList, $config));
return $instance;
} | php | public static function setUp(NodeName $nodeName, array $tasks, array $config = array())
{
/** @var $instance Process */
$instance = new static();
$instance->assertConfig($config);
$processId = ProcessId::generate();
$taskList = TaskList::scheduleTasks(TaskListId::linkWith($nodeName, $processId), $tasks);
$instance->recordThat(ProcessWasSetUp::with($processId, $taskList, $config));
return $instance;
} | Creates new process from given tasks and config
@param NodeName $nodeName
@param Task[] $tasks
@param array $config
@return static | https://github.com/prooph/processing/blob/a2947bccbffeecc4ca93a15e38ab53814e3e53e5/library/Processor/Process.php#L102-L116 |
prooph/processing | library/Processor/Process.php | Process.receiveMessage | public function receiveMessage($message, WorkflowEngine $workflowEngine)
{
if ($message instanceof WorkflowMessage) {
if (MessageNameUtils::isProcessingCommand($message->messageName())) {
$this->perform($workflowEngine, $message);
return;
}
$this->assertTaskEntryExists($message->processTaskListPosition());
$this->recordThat(TaskEntryMarkedAsDone::at($message->processTaskListPosition()));
$this->perform($workflowEngine, $message);
return;
}
if ($message instanceof LogMessage) {
$this->assertTaskEntryExists($message->processTaskListPosition());
$this->recordThat(LogMessageReceived::record($message));
if ($message->isError()) {
$this->recordThat(TaskEntryMarkedAsFailed::at($message->processTaskListPosition()));
} elseif ($this->isSubProcess() && $this->syncLogMessages) {
//We only sync non error messages, because errors are always synced and then they would be received twice
$messageForParent = $message->reconnectToProcessTask($this->parentTaskListPosition);
$workflowEngine->dispatch($messageForParent);
}
}
} | php | public function receiveMessage($message, WorkflowEngine $workflowEngine)
{
if ($message instanceof WorkflowMessage) {
if (MessageNameUtils::isProcessingCommand($message->messageName())) {
$this->perform($workflowEngine, $message);
return;
}
$this->assertTaskEntryExists($message->processTaskListPosition());
$this->recordThat(TaskEntryMarkedAsDone::at($message->processTaskListPosition()));
$this->perform($workflowEngine, $message);
return;
}
if ($message instanceof LogMessage) {
$this->assertTaskEntryExists($message->processTaskListPosition());
$this->recordThat(LogMessageReceived::record($message));
if ($message->isError()) {
$this->recordThat(TaskEntryMarkedAsFailed::at($message->processTaskListPosition()));
} elseif ($this->isSubProcess() && $this->syncLogMessages) {
//We only sync non error messages, because errors are always synced and then they would be received twice
$messageForParent = $message->reconnectToProcessTask($this->parentTaskListPosition);
$workflowEngine->dispatch($messageForParent);
}
}
} | A Process can start or continue with the next step after it has received a message
@param WorkflowMessage|LogMessage $message
@param WorkflowEngine $workflowEngine
@throws \RuntimeException
@return void | https://github.com/prooph/processing/blob/a2947bccbffeecc4ca93a15e38ab53814e3e53e5/library/Processor/Process.php#L168-L197 |
phPoirot/Client-OAuth2 | mod/Actions/ServiceAssertTokenAction.php | ServiceAssertTokenAction.newService | function newService()
{
# Check Debug Mode:
if ( $this->debugMode )
// Mock Debug Mode
return new AssertDebugTokenAction($this->debugToken);
if ($this->tokenAssertion)
$assertion = $this->tokenAssertion;
else throw new \RuntimeException('Token Assertion Provider Not Injected.');
$assertAction = new AssertTokenAction($assertion);
return $assertAction;
} | php | function newService()
{
# Check Debug Mode:
if ( $this->debugMode )
// Mock Debug Mode
return new AssertDebugTokenAction($this->debugToken);
if ($this->tokenAssertion)
$assertion = $this->tokenAssertion;
else throw new \RuntimeException('Token Assertion Provider Not Injected.');
$assertAction = new AssertTokenAction($assertion);
return $assertAction;
} | Create Service
@return callable | https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/mod/Actions/ServiceAssertTokenAction.php#L33-L49 |
antaresproject/sample_module | src/SampleModuleServiceProvider.php | SampleModuleServiceProvider.bootExtensionComponents | protected function bootExtensionComponents()
{
$path = __DIR__ . '/../resources';
$this->addConfigComponent('antares/sample_module', 'antares/sample_module', "{$path}/config");
$this->addLanguageComponent('antares/sample_module', 'antares/sample_module', "{$path}/lang");
$this->addViewComponent('antares/sample_module', 'antares/sample_module', "{$path}/views");
$this->attachMenu(ModuleBreadcrumbMenu::class);
$this->bootMemory();
listen('datatables:admin/users/index:after.status', function($datatables) {
if ($datatables instanceof \Antares\Datatables\Html\Builder) {
$datatables->collection->push(new \Yajra\Datatables\Html\Column([
'data' => 'sample_module',
'name' => 'sample_module',
'title' => 'Sample Module Items'
]));
}
});
listen("datatables.value.*", function($name, array $params = []) {
if (empty($params)) {
return;
}
$datatables = $params[0];
$datatables->editColumn('sample_module', function($model) {
if (!$model instanceof \Antares\Model\User) {
return;
}
return Model\ModuleRow::query()->where('user_id', $model->id)->count();
});
});
view()->composer('antares/sample_module::admin.configuration', ControlPane::class);
listen('antares.ready: menu.after.general-settings', ModulePaneMenu::class);
listen('breadcrumb.before.render.user-view', function($menu) {
$attributes = $menu->getAttributes();
$childs = [
'sample-module-user' => new \Antares\Support\Fluent([
"icon" => 'zmdi-plus',
"link" => handles('antares::sample_module/index/create'),
"title" => 'Add Item (Sample Module)',
"id" => 'sample-module-add',
"childs" => []])
];
array_set($attributes, 'childs', array_merge($childs, $attributes['childs']));
$menu->offsetSet('attributes', $attributes);
});
$this->app->make('antares.notifications')->push([
'antaresproject/module-sample_module' => [
'variables' => [
'items' => [
'dataProvider' => 'Antares\SampleModule\Model\ModuleRow@items'
],
]
]
]);
listen('after.activated.antaresproject/module-sample_module', function() {
\Illuminate\Support\Facades\Artisan::call('automation:sync');
});
} | php | protected function bootExtensionComponents()
{
$path = __DIR__ . '/../resources';
$this->addConfigComponent('antares/sample_module', 'antares/sample_module', "{$path}/config");
$this->addLanguageComponent('antares/sample_module', 'antares/sample_module', "{$path}/lang");
$this->addViewComponent('antares/sample_module', 'antares/sample_module', "{$path}/views");
$this->attachMenu(ModuleBreadcrumbMenu::class);
$this->bootMemory();
listen('datatables:admin/users/index:after.status', function($datatables) {
if ($datatables instanceof \Antares\Datatables\Html\Builder) {
$datatables->collection->push(new \Yajra\Datatables\Html\Column([
'data' => 'sample_module',
'name' => 'sample_module',
'title' => 'Sample Module Items'
]));
}
});
listen("datatables.value.*", function($name, array $params = []) {
if (empty($params)) {
return;
}
$datatables = $params[0];
$datatables->editColumn('sample_module', function($model) {
if (!$model instanceof \Antares\Model\User) {
return;
}
return Model\ModuleRow::query()->where('user_id', $model->id)->count();
});
});
view()->composer('antares/sample_module::admin.configuration', ControlPane::class);
listen('antares.ready: menu.after.general-settings', ModulePaneMenu::class);
listen('breadcrumb.before.render.user-view', function($menu) {
$attributes = $menu->getAttributes();
$childs = [
'sample-module-user' => new \Antares\Support\Fluent([
"icon" => 'zmdi-plus',
"link" => handles('antares::sample_module/index/create'),
"title" => 'Add Item (Sample Module)',
"id" => 'sample-module-add',
"childs" => []])
];
array_set($attributes, 'childs', array_merge($childs, $attributes['childs']));
$menu->offsetSet('attributes', $attributes);
});
$this->app->make('antares.notifications')->push([
'antaresproject/module-sample_module' => [
'variables' => [
'items' => [
'dataProvider' => 'Antares\SampleModule\Model\ModuleRow@items'
],
]
]
]);
listen('after.activated.antaresproject/module-sample_module', function() {
\Illuminate\Support\Facades\Artisan::call('automation:sync');
});
} | {@inheritdoc} | https://github.com/antaresproject/sample_module/blob/aceab14f392c25e32729018518e9d6b4e6fe23db/src/SampleModuleServiceProvider.php#L68-L127 |
oliwierptak/Everon1 | src/Everon/Helper/Asserts/IsEmpty.php | IsEmpty.assertIsEmpty | public function assertIsEmpty($value, $message='%s must not be empty', $exception='Asserts')
{
if (isset($value) === false || empty($value)) {
$this->throwException($exception, $message, $value);
}
} | php | public function assertIsEmpty($value, $message='%s must not be empty', $exception='Asserts')
{
if (isset($value) === false || empty($value)) {
$this->throwException($exception, $message, $value);
}
} | Verifies that the specified condition is not empty.
The assertion fails if the condition is empty.
@param mixed $value
@param string $message
@param string $exception
@throws \Everon\Exception\Asserts | https://github.com/oliwierptak/Everon1/blob/ac93793d1fa517a8394db5f00062f1925dc218a3/src/Everon/Helper/Asserts/IsEmpty.php#L23-L28 |
rackberg/para | src/Command/OpenShellCommand.php | OpenShellCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
// Check if the group the user wants to use exists.
$groupName = $input->getArgument('group');
$group = $this->groupConfiguration->getGroup($groupName);
if (!$group) {
$this->logger->warning('The group the user tries to use is not configured.', [
'arguments' => $input->getArguments(),
'options' => $input->getOptions()
]);
$output->writeln('<error>The group you are trying to use is not configured.</error>', 1);
return false;
}
$excludedProjects = $input->getOption('exclude-project');
$shell = $this->shellFactory->create($input, $output);
$shell->run($groupName, $excludedProjects, $this->historyFile);
// Persist the shell commands to the history file.
if ($this->historyFile) {
$shell
->getHistoryShellManager()
->getHistory()
->saveHistory($this->historyFile);
}
$output->writeln('<info>Finished para shell.</info>');
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
// Check if the group the user wants to use exists.
$groupName = $input->getArgument('group');
$group = $this->groupConfiguration->getGroup($groupName);
if (!$group) {
$this->logger->warning('The group the user tries to use is not configured.', [
'arguments' => $input->getArguments(),
'options' => $input->getOptions()
]);
$output->writeln('<error>The group you are trying to use is not configured.</error>', 1);
return false;
}
$excludedProjects = $input->getOption('exclude-project');
$shell = $this->shellFactory->create($input, $output);
$shell->run($groupName, $excludedProjects, $this->historyFile);
// Persist the shell commands to the history file.
if ($this->historyFile) {
$shell
->getHistoryShellManager()
->getHistory()
->saveHistory($this->historyFile);
}
$output->writeln('<info>Finished para shell.</info>');
} | {@inheritdoc} | https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Command/OpenShellCommand.php#L97-L128 |
haldayne/fox | src/Expression.php | Expression.makeCallable | private static function makeCallable($expression)
{
if (! array_key_exists($expression, static::$map)) {
$return = "return ($expression);";
try {
$lambda = create_function(static::$signature, $return);
} catch (\ParseError $ex) {
$lambda = false;
} finally {
if (false === $lambda) {
throw new \LogicException(sprintf(
'Expression is not valid PHP code: given=[%s], becomes=[%s]',
$expression,
$return
));
} else {
static::$map[$expression] = $lambda;
}
}
}
return static::$map[$expression];
} | php | private static function makeCallable($expression)
{
if (! array_key_exists($expression, static::$map)) {
$return = "return ($expression);";
try {
$lambda = create_function(static::$signature, $return);
} catch (\ParseError $ex) {
$lambda = false;
} finally {
if (false === $lambda) {
throw new \LogicException(sprintf(
'Expression is not valid PHP code: given=[%s], becomes=[%s]',
$expression,
$return
));
} else {
static::$map[$expression] = $lambda;
}
}
}
return static::$map[$expression];
} | Given a string expression, turn that into an anonymous function.
Cache the result, so as to keep memory impacts low.
@throw \LogicException | https://github.com/haldayne/fox/blob/f5dcc3798cca0fdbfc6f448c5cb5a174eaab60eb/src/Expression.php#L124-L145 |
stonedz/pff2 | src/modules/cookies/Cookies.php | Cookies.setCookie | public function setCookie($cookieName, $value = null, $expire = null) {
if ($expire !== null) {
$expire = time() + (60 * 60 * $expire);
}
if (setcookie($cookieName, $this->encodeCookie($value), $expire, "/")) {
return true;
} else {
return false;
}
} | php | public function setCookie($cookieName, $value = null, $expire = null) {
if ($expire !== null) {
$expire = time() + (60 * 60 * $expire);
}
if (setcookie($cookieName, $this->encodeCookie($value), $expire, "/")) {
return true;
} else {
return false;
}
} | Sets a cookie in the user's browser
@param string $cookieName
@param string|null $value The value to store in the cookie
@param int|null $expire how many HOURS the cookie will be valid (set to 0 for session time)
@return bool | https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/modules/cookies/Cookies.php#L41-L51 |
stonedz/pff2 | src/modules/cookies/Cookies.php | Cookies.getCookie | public function getCookie($cookieName) {
if (isset($_COOKIE[$cookieName])) {
return $this->decodeCookie($_COOKIE[$cookieName]);
} else {
return false;
}
} | php | public function getCookie($cookieName) {
if (isset($_COOKIE[$cookieName])) {
return $this->decodeCookie($_COOKIE[$cookieName]);
} else {
return false;
}
} | Check if a cookie is set and returns its content
@param string $cookieName
@return bool
@retrurn string | https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/modules/cookies/Cookies.php#L76-L82 |
stonedz/pff2 | src/modules/cookies/Cookies.php | Cookies.deleteCookie | public function deleteCookie($cookieName) {
if (isset($_COOKIE[$cookieName])) {
if (setcookie($cookieName, null, time() - 6000, '/')) {
return true;
} else {
return false;
}
} else {
return false;
}
} | php | public function deleteCookie($cookieName) {
if (isset($_COOKIE[$cookieName])) {
if (setcookie($cookieName, null, time() - 6000, '/')) {
return true;
} else {
return false;
}
} else {
return false;
}
} | Deletes a cookie
@param string $cookieName Name of the cookie to delete
@return bool | https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/modules/cookies/Cookies.php#L90-L100 |
openclerk/users | src/OAuth2Providers.php | OAuth2Providers.loadProvider | static function loadProvider($key, $redirect) {
if (!$redirect) {
throw new \InvalidArgumentException("No redirect provided.");
}
switch ($key) {
case "google":
return new GoogleWithOpenID(array(
'clientId' =>\Openclerk\Config::get("oauth2_google_client_id"),
'clientSecret' => \Openclerk\Config::get("oauth2_google_client_secret"),
'redirectUri' => $redirect,
'scopes' => array('email', 'openid'),
'openid.realm' => \Openclerk\Config::get('openid_host'),
));
case "facebook":
return new \League\OAuth2\Client\Provider\Facebook(array(
'clientId' =>\Openclerk\Config::get("oauth2_facebook_app_id"),
'clientSecret' => \Openclerk\Config::get("oauth2_facebook_app_secret"),
'redirectUri' => $redirect,
'scopes' => array('email'),
));
case "github":
return new \League\OAuth2\Client\Provider\Github(array(
'clientId' =>\Openclerk\Config::get("oauth2_github_client_id"),
'clientSecret' => \Openclerk\Config::get("oauth2_github_client_secret"),
'redirectUri' => $redirect,
'scopes' => array('email'),
));
default:
throw new UserAuthenticationException("No such known OAuth2 provider '$key'");
}
} | php | static function loadProvider($key, $redirect) {
if (!$redirect) {
throw new \InvalidArgumentException("No redirect provided.");
}
switch ($key) {
case "google":
return new GoogleWithOpenID(array(
'clientId' =>\Openclerk\Config::get("oauth2_google_client_id"),
'clientSecret' => \Openclerk\Config::get("oauth2_google_client_secret"),
'redirectUri' => $redirect,
'scopes' => array('email', 'openid'),
'openid.realm' => \Openclerk\Config::get('openid_host'),
));
case "facebook":
return new \League\OAuth2\Client\Provider\Facebook(array(
'clientId' =>\Openclerk\Config::get("oauth2_facebook_app_id"),
'clientSecret' => \Openclerk\Config::get("oauth2_facebook_app_secret"),
'redirectUri' => $redirect,
'scopes' => array('email'),
));
case "github":
return new \League\OAuth2\Client\Provider\Github(array(
'clientId' =>\Openclerk\Config::get("oauth2_github_client_id"),
'clientSecret' => \Openclerk\Config::get("oauth2_github_client_secret"),
'redirectUri' => $redirect,
'scopes' => array('email'),
));
default:
throw new UserAuthenticationException("No such known OAuth2 provider '$key'");
}
} | Load the {@link ProviderInterface} with the given key, from {@link #getProviders()}.
@param $redirect the `redirectUri` to provide the provider.
@return A {@link ProviderInterface} | https://github.com/openclerk/users/blob/550c7610c154a2f6655ce65a2df377ccb207bc6d/src/OAuth2Providers.php#L79-L113 |
openclerk/users | src/OAuth2Providers.php | OAuth2Providers.createProvider | static function createProvider($key, $redirect) {
switch ($key) {
case "google":
return self::google($redirect);
case "facebook":
return self::facebook($redirect);
case "github":
return self::github($redirect);
break;
throw new UserAuthenticationException("No such known OAuth2 provider '$key'");
}
} | php | static function createProvider($key, $redirect) {
switch ($key) {
case "google":
return self::google($redirect);
case "facebook":
return self::facebook($redirect);
case "github":
return self::github($redirect);
break;
throw new UserAuthenticationException("No such known OAuth2 provider '$key'");
}
} | Allows instances to be created based on {@link #getProviders()}. | https://github.com/openclerk/users/blob/550c7610c154a2f6655ce65a2df377ccb207bc6d/src/OAuth2Providers.php#L118-L130 |
mpaleo/view-tags | src/ViewTags/TagsContainer.php | TagsContainer.taggedWith | public function taggedWith($tag)
{
$results = [];
if (isset($this->tags[$tag]))
{
foreach ($this->tags[$tag] as $view)
{
$results[] = $view;
}
}
return $results;
} | php | public function taggedWith($tag)
{
$results = [];
if (isset($this->tags[$tag]))
{
foreach ($this->tags[$tag] as $view)
{
$results[] = $view;
}
}
return $results;
} | Return all the views for a given tag.
@param $tag
@return array | https://github.com/mpaleo/view-tags/blob/7ca3308b616738e744a0435f581bbd705e59cad6/src/ViewTags/TagsContainer.php#L41-L55 |
zhengb302/LumengPHP | src/LumengPHP/Http/Request.php | Request.createFromGlobals | public static function createFromGlobals() {
$request = new Request($_GET, $_POST, $_REQUEST, $_COOKIE, $_FILES, $_SERVER);
//设置session实例
$request->setSession(new SimpleSession());
return $request;
} | php | public static function createFromGlobals() {
$request = new Request($_GET, $_POST, $_REQUEST, $_COOKIE, $_FILES, $_SERVER);
//设置session实例
$request->setSession(new SimpleSession());
return $request;
} | 从超全局变量中创建一个<b>Request</b>实例
@return Request | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Http/Request.php#L81-L88 |
soliphp/web | src/Web/App.php | App.handle | public function handle($uri = null)
{
try {
$returnedResponse = parent::handle($uri);
return $this->handleWeb($returnedResponse);
} catch (Throwable $e) {
/** @noinspection PhpUnhandledExceptionInspection */
return $this->handleException($e);
}
} | php | public function handle($uri = null)
{
try {
$returnedResponse = parent::handle($uri);
return $this->handleWeb($returnedResponse);
} catch (Throwable $e) {
/** @noinspection PhpUnhandledExceptionInspection */
return $this->handleException($e);
}
} | 应用程序启动方法
@noinspection PhpDocMissingThrowsInspection
@param string $uri
@return \Soli\Web\Response | https://github.com/soliphp/web/blob/40c884ef06afa5739c94f0bffdcc69d3c6c44e96/src/Web/App.php#L43-L52 |
soliphp/web | src/Web/App.php | App.viewRender | protected function viewRender()
{
if (!$this->container->has('view')) {
return null;
}
// 视图实例
$view = $this->view;
// 禁止自动渲染视图
if ($view->isDisabled()) {
return null;
}
// 获取模版文件路径
$controller = $this->dispatcher->getHandlerName();
$action = $this->dispatcher->getActionName();
$template = "$controller/$action";
// 将 Flash 服务添加到 View
$view->setVar('flash', $this->flash);
// 自动渲染视图
return $view->render($template);
} | php | protected function viewRender()
{
if (!$this->container->has('view')) {
return null;
}
// 视图实例
$view = $this->view;
// 禁止自动渲染视图
if ($view->isDisabled()) {
return null;
}
// 获取模版文件路径
$controller = $this->dispatcher->getHandlerName();
$action = $this->dispatcher->getActionName();
$template = "$controller/$action";
// 将 Flash 服务添加到 View
$view->setVar('flash', $this->flash);
// 自动渲染视图
return $view->render($template);
} | 获取视图自动渲染内容
@codeCoverageIgnore
@return string | https://github.com/soliphp/web/blob/40c884ef06afa5739c94f0bffdcc69d3c6c44e96/src/Web/App.php#L84-L108 |
brainexe/core | src/DependencyInjection/CompilerPass/MiddlewareCompilerPass.php | MiddlewareCompilerPass.process | public function process(ContainerBuilder $container)
{
$appKernel = $container->findDefinition(AppKernel::class);
$middlewares = $container->getParameter('application.middlewares');
$references = [];
foreach ($middlewares as $serviceId) {
$references[] = new Reference($serviceId);
}
$appKernel->addArgument($references);
$container->getParameterBag()->remove('application.middlewares');
} | php | public function process(ContainerBuilder $container)
{
$appKernel = $container->findDefinition(AppKernel::class);
$middlewares = $container->getParameter('application.middlewares');
$references = [];
foreach ($middlewares as $serviceId) {
$references[] = new Reference($serviceId);
}
$appKernel->addArgument($references);
$container->getParameterBag()->remove('application.middlewares');
} | {@inheritdoc} | https://github.com/brainexe/core/blob/9ef69c6f045306abd20e271572386970db9b3e54/src/DependencyInjection/CompilerPass/MiddlewareCompilerPass.php#L22-L34 |
newup/core | src/Templates/Renderers/TemplateRenderer.php | TemplateRenderer.registerFilters | private function registerFilters()
{
$filters = config('app.render_filters', []);
foreach ($filters as $filter) {
$filter = app($filter);
if ($filter instanceof FilterContract) {
$this->twigEnvironment->addFilter(new \Twig_SimpleFilter($filter->getName(), $filter->getFilter()));
$this->twigStringEnvironment->addFilter(new \Twig_SimpleFilter($filter->getName(),
$filter->getFilter()));
}
}
} | php | private function registerFilters()
{
$filters = config('app.render_filters', []);
foreach ($filters as $filter) {
$filter = app($filter);
if ($filter instanceof FilterContract) {
$this->twigEnvironment->addFilter(new \Twig_SimpleFilter($filter->getName(), $filter->getFilter()));
$this->twigStringEnvironment->addFilter(new \Twig_SimpleFilter($filter->getName(),
$filter->getFilter()));
}
}
} | Registers the template filters. | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Templates/Renderers/TemplateRenderer.php#L112-L125 |
newup/core | src/Templates/Renderers/TemplateRenderer.php | TemplateRenderer.addPath | public function addPath($path)
{
try {
$this->twigFileLoader->addPath($path);
} catch (\Twig_Error_Loader $e) {
throw new InvalidPathException($e->getMessage());
}
} | php | public function addPath($path)
{
try {
$this->twigFileLoader->addPath($path);
} catch (\Twig_Error_Loader $e) {
throw new InvalidPathException($e->getMessage());
}
} | Adds a path to the template environment.
@param $path
@throws InvalidPathException | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Templates/Renderers/TemplateRenderer.php#L148-L155 |
newup/core | src/Templates/Renderers/TemplateRenderer.php | TemplateRenderer.getData | public function getData()
{
$systemInformation = [];
$systemInformation['newup_version'] = Application::VERSION;
return $this->dataArray + $systemInformation + $this->collectData();
} | php | public function getData()
{
$systemInformation = [];
$systemInformation['newup_version'] = Application::VERSION;
return $this->dataArray + $systemInformation + $this->collectData();
} | Gets the environment data.
@return array | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Templates/Renderers/TemplateRenderer.php#L203-L209 |
newup/core | src/Templates/Renderers/TemplateRenderer.php | TemplateRenderer.render | public function render($templateName)
{
try {
return $this->twigEnvironment->render($templateName, $this->getData());
} catch (SecurityException $e) {
throw new SecurityException($e->getMessage(), $e->getCode(), $e);
} catch (\Twig_Error_Runtime $e) {
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
} catch (\Twig_Error_Syntax $e) {
throw new InvalidSyntaxException($e->getMessage(), $e->getCode(), $e);
} catch (\Twig_Error_Loader $e) {
if ($this->ignoreUndefinedTemplateErrors && Str::contains($e->getMessage(), 'is not defined'))
{
return;
}
throw new InvalidTemplateException($e->getMessage(), $e->getCode(), $e);
}
} | php | public function render($templateName)
{
try {
return $this->twigEnvironment->render($templateName, $this->getData());
} catch (SecurityException $e) {
throw new SecurityException($e->getMessage(), $e->getCode(), $e);
} catch (\Twig_Error_Runtime $e) {
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
} catch (\Twig_Error_Syntax $e) {
throw new InvalidSyntaxException($e->getMessage(), $e->getCode(), $e);
} catch (\Twig_Error_Loader $e) {
if ($this->ignoreUndefinedTemplateErrors && Str::contains($e->getMessage(), 'is not defined'))
{
return;
}
throw new InvalidTemplateException($e->getMessage(), $e->getCode(), $e);
}
} | Renders a template by name.
@param $templateName
@return string
@throws InvalidTemplateException
@throws InvalidSyntaxException
@throws RuntimeException
@throws SecurityException | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Templates/Renderers/TemplateRenderer.php#L232-L251 |
newup/core | src/Templates/Renderers/TemplateRenderer.php | TemplateRenderer.renderString | public function renderString($templateString)
{
try {
return $this->twigStringEnvironment->render($templateString, $this->getData());
} catch (SecurityException $e) {
throw new SecurityException($e->getMessage(), $e->getCode(), $e);
} catch (\Twig_Error_Runtime $e) {
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
} catch (\Twig_Error_Syntax $e) {
throw new InvalidSyntaxException($e->getMessage(), $e->getCode(), $e);
} catch (\Twig_Error_Loader $e) {
if ($this->ignoreUndefinedTemplateErrors && Str::contains($e->getMessage(), 'is not defined'))
{
return;
}
throw new InvalidTemplateException($e->getMessage(), $e->getCode(), $e);
}
} | php | public function renderString($templateString)
{
try {
return $this->twigStringEnvironment->render($templateString, $this->getData());
} catch (SecurityException $e) {
throw new SecurityException($e->getMessage(), $e->getCode(), $e);
} catch (\Twig_Error_Runtime $e) {
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
} catch (\Twig_Error_Syntax $e) {
throw new InvalidSyntaxException($e->getMessage(), $e->getCode(), $e);
} catch (\Twig_Error_Loader $e) {
if ($this->ignoreUndefinedTemplateErrors && Str::contains($e->getMessage(), 'is not defined'))
{
return;
}
throw new InvalidTemplateException($e->getMessage(), $e->getCode(), $e);
}
} | Renders a string as a template.
@param $templateString
@return string
@throws InvalidTemplateException
@throws InvalidSyntaxException
@throws RuntimeException
@throws SecurityException | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Templates/Renderers/TemplateRenderer.php#L263-L282 |
newup/core | src/Templates/Renderers/TemplateRenderer.php | TemplateRenderer.collectData | public function collectData()
{
$collectedData = [];
foreach ($this->dataCollectors as $collector) {
$collectedData = $collectedData + $collector->collect();
}
return $collectedData;
} | php | public function collectData()
{
$collectedData = [];
foreach ($this->dataCollectors as $collector) {
$collectedData = $collectedData + $collector->collect();
}
return $collectedData;
} | Collects all data from data collectors.
@return array | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Templates/Renderers/TemplateRenderer.php#L309-L318 |
tarsana/syntax | src/NumberSyntax.php | NumberSyntax.instance | public static function instance() : NumberSyntax
{
if (self::$instance === null)
self::$instance = new NumberSyntax;
return self::$instance;
} | php | public static function instance() : NumberSyntax
{
if (self::$instance === null)
self::$instance = new NumberSyntax;
return self::$instance;
} | Returns the NumberSyntax instance.
@return Tarsana\Syntax\NumberSyntax | https://github.com/tarsana/syntax/blob/fd3f8a25e3be0e391c8fd486ccfcffe913ade534/src/NumberSyntax.php#L20-L25 |
tarsana/syntax | src/NumberSyntax.php | NumberSyntax.parse | public function parse(string $text)
{
if (! is_numeric($text))
throw new ParseException($this, $text, 0, self::ERROR);
return $text + 0;
} | php | public function parse(string $text)
{
if (! is_numeric($text))
throw new ParseException($this, $text, 0, self::ERROR);
return $text + 0;
} | Parses the `$text` and returns the
result or throws a `ParseException`.
@param string $text
@return float
@throws Tarsana\Syntax\Exceptions\ParseException | https://github.com/tarsana/syntax/blob/fd3f8a25e3be0e391c8fd486ccfcffe913ade534/src/NumberSyntax.php#L38-L43 |
tarsana/syntax | src/NumberSyntax.php | NumberSyntax.dump | public function dump($value) : string
{
if (! is_numeric($value))
throw new DumpException($this, $value, self::ERROR);
return ''. $value;
} | php | public function dump($value) : string
{
if (! is_numeric($value))
throw new DumpException($this, $value, self::ERROR);
return ''. $value;
} | Dumps the `$value` and returns the
result or throws a `DumpException`.
@param int|float $value
@return string
@throws Tarsana\Syntax\Exceptions\DumpException | https://github.com/tarsana/syntax/blob/fd3f8a25e3be0e391c8fd486ccfcffe913ade534/src/NumberSyntax.php#L54-L60 |
Etenil/assegai | src/assegai/modules/mail/services/ses/sdk.class.php | CFRuntime.init | public static function init($key = null, $secret_key = null, $account_id = null, $assoc_id = null)
{
if (version_compare(PHP_VERSION, '5.3.0', '<'))
{
throw new Exception('PHP 5.3 or newer is required to instantiate a new class with CLASS::init().');
}
$self = get_called_class();
return new $self($key, $secret_key, $account_id, $assoc_id);
} | php | public static function init($key = null, $secret_key = null, $account_id = null, $assoc_id = null)
{
if (version_compare(PHP_VERSION, '5.3.0', '<'))
{
throw new Exception('PHP 5.3 or newer is required to instantiate a new class with CLASS::init().');
}
$self = get_called_class();
return new $self($key, $secret_key, $account_id, $assoc_id);
} | Alternate approach to constructing a new instance. Supports chaining.
@param string $key (Optional) Your Amazon API Key. If blank, it will look for the <AWS_KEY> constant.
@param string $secret_key (Optional) Your Amazon API Secret Key. If blank, it will look for the <AWS_SECRET_KEY> constant.
@param string $account_id (Optional) Your Amazon account ID without the hyphens. Required for EC2. If blank, it will look for the <AWS_ACCOUNT_ID> constant.
@param string $assoc_id (Optional) Your Amazon Associates ID. Required for AAWS. If blank, it will look for the <AWS_ASSOC_ID> constant.
@return boolean A value of `false` if no valid values are set, otherwise `true`. | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/sdk.class.php#L406-L415 |
Etenil/assegai | src/assegai/modules/mail/services/ses/sdk.class.php | CFRuntime.set_hostname | public function set_hostname($hostname, $port_number = null)
{
if ($this->override_hostname)
{
$this->hostname = $hostname;
if ($port_number)
{
$this->port_number = $port_number;
$this->hostname .= ':' . (string) $this->port_number;
}
}
return $this;
} | php | public function set_hostname($hostname, $port_number = null)
{
if ($this->override_hostname)
{
$this->hostname = $hostname;
if ($port_number)
{
$this->port_number = $port_number;
$this->hostname .= ':' . (string) $this->port_number;
}
}
return $this;
} | Set the hostname to connect to. This is useful for alternate services that are API-compatible with
AWS, but run from a different hostname.
@param string $hostname (Required) The alternate hostname to use in place of the default one. Useful for mock or test applications living on different hostnames.
@param integer $port_number (Optional) The alternate port number to use in place of the default one. Useful for mock or test applications living on different port numbers.
@return $this A reference to the current instance. | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/sdk.class.php#L478-L492 |
Etenil/assegai | src/assegai/modules/mail/services/ses/sdk.class.php | CFRuntime.set_cache_config | public function set_cache_config($location, $gzip = true)
{
// If we have an array, we're probably passing in Memcached servers and ports.
if (is_array($location))
{
$this->cache_class = 'CacheMC';
}
else
{
// I would expect locations like `/tmp/cache`, `pdo.mysql://user:pass@hostname:port`, `pdo.sqlite:memory:`, and `apc`.
$type = strtolower(substr($location, 0, 3));
switch ($type)
{
case 'apc':
$this->cache_class = 'CacheAPC';
break;
case 'xca': // First three letters of `xcache`
$this->cache_class = 'CacheXCache';
break;
case 'pdo':
$this->cache_class = 'CachePDO';
$location = substr($location, 4);
break;
default:
$this->cache_class = 'CacheFile';
break;
}
}
// Set the remaining cache information.
$this->cache_location = $location;
$this->cache_compress = $gzip;
return $this;
} | php | public function set_cache_config($location, $gzip = true)
{
// If we have an array, we're probably passing in Memcached servers and ports.
if (is_array($location))
{
$this->cache_class = 'CacheMC';
}
else
{
// I would expect locations like `/tmp/cache`, `pdo.mysql://user:pass@hostname:port`, `pdo.sqlite:memory:`, and `apc`.
$type = strtolower(substr($location, 0, 3));
switch ($type)
{
case 'apc':
$this->cache_class = 'CacheAPC';
break;
case 'xca': // First three letters of `xcache`
$this->cache_class = 'CacheXCache';
break;
case 'pdo':
$this->cache_class = 'CachePDO';
$location = substr($location, 4);
break;
default:
$this->cache_class = 'CacheFile';
break;
}
}
// Set the remaining cache information.
$this->cache_location = $location;
$this->cache_compress = $gzip;
return $this;
} | Set the caching configuration to use for response caching.
@param string $location (Required) <p>The location to store the cache object in. This may vary by cache method.</p><ul><li>File - The local file system paths such as <code>./cache</code> (relative) or <code>/tmp/cache/</code> (absolute). The location must be server-writable.</li><li>APC - Pass in <code>apc</code> to use this lightweight cache. You must have the <a href="http://php.net/apc">APC extension</a> installed.</li><li>XCache - Pass in <code>xcache</code> to use this lightweight cache. You must have the <a href="http://xcache.lighttpd.net">XCache</a> extension installed.</li><li>Memcached - Pass in an indexed array of associative arrays. Each associative array should have a <code>host</code> and a <code>port</code> value representing a <a href="http://php.net/memcached">Memcached</a> server to connect to.</li><li>PDO - A URL-style string (e.g. <code>pdo.mysql://user:pass@localhost/cache</code>) or a standard DSN-style string (e.g. <code>pdo.sqlite:/sqlite/cache.db</code>). MUST be prefixed with <code>pdo.</code>. See <code>CachePDO</code> and <a href="http://php.net/pdo">PDO</a> for more details.</li></ul>
@param boolean $gzip (Optional) Whether or not data should be gzipped before being stored. A value of `true` will compress the contents before caching them. A value of `false` will leave the contents uncompressed. Defaults to `true`.
@return $this A reference to the current instance. | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/sdk.class.php#L562-L599 |
Etenil/assegai | src/assegai/modules/mail/services/ses/sdk.class.php | CFRuntime.authenticate | public function authenticate($action, $opt = null, $domain = null, $signature_version = 2, $redirects = 0)
{
// Handle nulls
if (is_null($signature_version))
{
$signature_version = 2;
}
$method_arguments = func_get_args();
$headers = array();
$signed_headers = array();
// Use the caching flow to determine if we need to do a round-trip to the server.
if ($this->use_cache_flow)
{
// Generate an identifier specific to this particular set of arguments.
$cache_id = $this->key . '_' . get_class($this) . '_' . $action . '_' . sha1(serialize($method_arguments));
// Instantiate the appropriate caching object.
$this->cache_object = new $this->cache_class($cache_id, $this->cache_location, $this->cache_expires, $this->cache_compress);
if ($this->delete_cache)
{
$this->use_cache_flow = false;
$this->delete_cache = false;
return $this->cache_object->delete();
}
// Invoke the cache callback function to determine whether to pull data from the cache or make a fresh request.
$data = $this->cache_object->response_manager(array($this, 'cache_callback'), $method_arguments);
// Parse the XML body
$data = $this->parse_callback($data);
// End!
return $data;
}
$return_curl_handle = false;
$x_amz_target = null;
// Do we have a custom resource prefix?
if ($this->resource_prefix)
{
$domain .= $this->resource_prefix;
}
// Determine signing values
$current_time = time() + $this->adjust_offset;
$date = gmdate(CFUtilities::DATE_FORMAT_RFC2616, $current_time);
$timestamp = gmdate(CFUtilities::DATE_FORMAT_ISO8601, $current_time);
$nonce = $this->util->generate_guid();
// Manage the key-value pairs that are used in the query.
if (stripos($action, 'x-amz-target') !== false)
{
$x_amz_target = trim(str_ireplace('x-amz-target:', '', $action));
}
else
{
$query['Action'] = $action;
}
$query['Version'] = $this->api_version;
// Only Signature v2
if ($signature_version === 2)
{
$query['AWSAccessKeyId'] = $this->key;
$query['SignatureMethod'] = 'HmacSHA256';
$query['SignatureVersion'] = 2;
$query['Timestamp'] = $timestamp;
}
// Merge in any options that were passed in
if (is_array($opt))
{
$query = array_merge($query, $opt);
}
$return_curl_handle = isset($query['returnCurlHandle']) ? $query['returnCurlHandle'] : false;
unset($query['returnCurlHandle']);
// Do a case-sensitive, natural order sort on the array keys.
uksort($query, 'strcmp');
// Normalize JSON input
if (isset($query['body']) && $query['body'] === '[]')
{
$query['body'] = '{}';
}
if ($this->use_aws_query)
{
// Create the string that needs to be hashed.
$canonical_query_string = $this->util->to_signable_string($query);
}
else
{
// Create the string that needs to be hashed.
$canonical_query_string = $this->util->encode_signature2($query['body']);
}
// Remove the default scheme from the domain.
$domain = str_replace(array('http://', 'https://'), '', $domain);
// Parse our request.
$parsed_url = parse_url('http://' . $domain);
// Set the proper host header.
if (isset($parsed_url['port']) && (integer) $parsed_url['port'] !== 80 && (integer) $parsed_url['port'] !== 443)
{
$host_header = strtolower($parsed_url['host']) . ':' . $parsed_url['port'];
}
else
{
$host_header = strtolower($parsed_url['host']);
}
// Set the proper request URI.
$request_uri = isset($parsed_url['path']) ? $parsed_url['path'] : '/';
if ($signature_version === 2)
{
// Prepare the string to sign
$string_to_sign = "POST\n$host_header\n$request_uri\n$canonical_query_string";
// Hash the AWS secret key and generate a signature for the request.
$query['Signature'] = base64_encode(hash_hmac('sha256', $string_to_sign, $this->secret_key, true));
}
// Generate the querystring from $query
$querystring = $this->util->to_query_string($query);
// Gather information to pass along to other classes.
$helpers = array(
'utilities' => $this->utilities_class,
'request' => $this->request_class,
'response' => $this->response_class,
);
// Compose the request.
$request_url = ($this->use_ssl ? 'https://' : 'http://') . $domain;
$request_url .= !isset($parsed_url['path']) ? '/' : '';
// Instantiate the request class
$request = new $this->request_class($request_url, $this->proxy, $helpers);
$request->set_method('POST');
$request->set_body($querystring);
$headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
// Do we have an authentication token?
if ($this->auth_token)
{
$headers['X-Amz-Security-Token'] = $this->auth_token;
}
// Signing using X-Amz-Target is handled differently.
if ($signature_version === 3 && $x_amz_target)
{
$headers['X-Amz-Target'] = $x_amz_target;
$headers['Content-Type'] = 'application/json; amzn-1.0';
$headers['Content-Encoding'] = 'amz-1.0';
$request->set_body($query['body']);
$querystring = $query['body'];
}
// Pass along registered stream callbacks
if ($this->registered_streaming_read_callback)
{
$request->register_streaming_read_callback($this->registered_streaming_read_callback);
}
if ($this->registered_streaming_write_callback)
{
$request->register_streaming_write_callback($this->registered_streaming_write_callback);
}
// Add authentication headers
if ($signature_version === 3)
{
$headers['X-Amz-Nonce'] = $nonce;
$headers['Date'] = $date;
$headers['Content-Length'] = strlen($querystring);
$headers['Content-MD5'] = $this->util->hex_to_base64(md5($querystring));
$headers['Host'] = $host_header;
}
// Sort headers
uksort($headers, 'strnatcasecmp');
if ($signature_version === 3 && $this->use_ssl)
{
// Prepare the string to sign (HTTPS)
$string_to_sign = $date . $nonce;
}
elseif ($signature_version === 3 && !$this->use_ssl)
{
// Prepare the string to sign (HTTP)
$string_to_sign = "POST\n$request_uri\n\n";
}
// Add headers to request and compute the string to sign
foreach ($headers as $header_key => $header_value)
{
// Strip linebreaks from header values as they're illegal and can allow for security issues
$header_value = str_replace(array("\r", "\n"), '', $header_value);
// Add the header if it has a value
if ($header_value !== '')
{
$request->add_header($header_key, $header_value);
}
// Signature v3 over HTTP
if ($signature_version === 3 && !$this->use_ssl)
{
// Generate the string to sign
if (
substr(strtolower($header_key), 0, 8) === 'content-' ||
strtolower($header_key) === 'date' ||
strtolower($header_key) === 'expires' ||
strtolower($header_key) === 'host' ||
substr(strtolower($header_key), 0, 6) === 'x-amz-'
)
{
$string_to_sign .= strtolower($header_key) . ':' . $header_value . "\n";
$signed_headers[] = $header_key;
}
}
}
if ($signature_version === 3)
{
if (!$this->use_ssl)
{
$string_to_sign .= "\n";
if (isset($query['body']) && $query['body'] !== '')
{
$string_to_sign .= $query['body'];
}
// Convert from string-to-sign to bytes-to-sign
$bytes_to_sign = hash('sha256', $string_to_sign, true);
// Hash the AWS secret key and generate a signature for the request.
$signature = base64_encode(hash_hmac('sha256', $bytes_to_sign, $this->secret_key, true));
}
else
{
// Hash the AWS secret key and generate a signature for the request.
$signature = base64_encode(hash_hmac('sha256', $string_to_sign, $this->secret_key, true));
}
$headers['X-Amzn-Authorization'] = 'AWS3' . ($this->use_ssl ? '-HTTPS' : '')
. ' AWSAccessKeyId=' . $this->key
. ',Algorithm=HmacSHA256'
. ',SignedHeaders=' . implode(';', $signed_headers)
. ',Signature=' . $signature;
$request->add_header('X-Amzn-Authorization', $headers['X-Amzn-Authorization']);
}
// Update RequestCore settings
$request->request_class = $this->request_class;
$request->response_class = $this->response_class;
$curlopts = array();
// Set custom CURLOPT settings
if (is_array($opt) && isset($opt['curlopts']))
{
$curlopts = $opt['curlopts'];
unset($opt['curlopts']);
}
// Debug mode
if ($this->debug_mode)
{
$request->debug_mode = $this->debug_mode;
}
if (count($curlopts))
{
$request->set_curlopts($curlopts);
}
// Manage the (newer) batch request API or the (older) returnCurlHandle setting.
if ($this->use_batch_flow)
{
$handle = $request->prep_request();
$this->batch_object->add($handle);
$this->use_batch_flow = false;
return $handle;
}
elseif ($return_curl_handle)
{
return $request->prep_request();
}
// Send!
$request->send_request();
$request_headers = $headers;
// Prepare the response.
$headers = $request->get_response_header();
$headers['x-aws-stringtosign'] = $string_to_sign;
$headers['x-aws-request-headers'] = $request_headers;
$headers['x-aws-body'] = $querystring;
$data = new $this->response_class($headers, $this->parse_callback($request->get_response_body(), $headers), $request->get_response_code());
// Was it Amazon's fault the request failed? Retry the request until we reach $max_retries.
if ((integer) $request->get_response_code() === 500 || (integer) $request->get_response_code() === 503)
{
if ($redirects <= $this->max_retries)
{
// Exponential backoff
$delay = (integer) (pow(4, $redirects) * 100000);
usleep($delay);
$data = $this->authenticate($action, $opt, $domain, $signature_version, ++$redirects);
}
}
return $data;
} | php | public function authenticate($action, $opt = null, $domain = null, $signature_version = 2, $redirects = 0)
{
// Handle nulls
if (is_null($signature_version))
{
$signature_version = 2;
}
$method_arguments = func_get_args();
$headers = array();
$signed_headers = array();
// Use the caching flow to determine if we need to do a round-trip to the server.
if ($this->use_cache_flow)
{
// Generate an identifier specific to this particular set of arguments.
$cache_id = $this->key . '_' . get_class($this) . '_' . $action . '_' . sha1(serialize($method_arguments));
// Instantiate the appropriate caching object.
$this->cache_object = new $this->cache_class($cache_id, $this->cache_location, $this->cache_expires, $this->cache_compress);
if ($this->delete_cache)
{
$this->use_cache_flow = false;
$this->delete_cache = false;
return $this->cache_object->delete();
}
// Invoke the cache callback function to determine whether to pull data from the cache or make a fresh request.
$data = $this->cache_object->response_manager(array($this, 'cache_callback'), $method_arguments);
// Parse the XML body
$data = $this->parse_callback($data);
// End!
return $data;
}
$return_curl_handle = false;
$x_amz_target = null;
// Do we have a custom resource prefix?
if ($this->resource_prefix)
{
$domain .= $this->resource_prefix;
}
// Determine signing values
$current_time = time() + $this->adjust_offset;
$date = gmdate(CFUtilities::DATE_FORMAT_RFC2616, $current_time);
$timestamp = gmdate(CFUtilities::DATE_FORMAT_ISO8601, $current_time);
$nonce = $this->util->generate_guid();
// Manage the key-value pairs that are used in the query.
if (stripos($action, 'x-amz-target') !== false)
{
$x_amz_target = trim(str_ireplace('x-amz-target:', '', $action));
}
else
{
$query['Action'] = $action;
}
$query['Version'] = $this->api_version;
// Only Signature v2
if ($signature_version === 2)
{
$query['AWSAccessKeyId'] = $this->key;
$query['SignatureMethod'] = 'HmacSHA256';
$query['SignatureVersion'] = 2;
$query['Timestamp'] = $timestamp;
}
// Merge in any options that were passed in
if (is_array($opt))
{
$query = array_merge($query, $opt);
}
$return_curl_handle = isset($query['returnCurlHandle']) ? $query['returnCurlHandle'] : false;
unset($query['returnCurlHandle']);
// Do a case-sensitive, natural order sort on the array keys.
uksort($query, 'strcmp');
// Normalize JSON input
if (isset($query['body']) && $query['body'] === '[]')
{
$query['body'] = '{}';
}
if ($this->use_aws_query)
{
// Create the string that needs to be hashed.
$canonical_query_string = $this->util->to_signable_string($query);
}
else
{
// Create the string that needs to be hashed.
$canonical_query_string = $this->util->encode_signature2($query['body']);
}
// Remove the default scheme from the domain.
$domain = str_replace(array('http://', 'https://'), '', $domain);
// Parse our request.
$parsed_url = parse_url('http://' . $domain);
// Set the proper host header.
if (isset($parsed_url['port']) && (integer) $parsed_url['port'] !== 80 && (integer) $parsed_url['port'] !== 443)
{
$host_header = strtolower($parsed_url['host']) . ':' . $parsed_url['port'];
}
else
{
$host_header = strtolower($parsed_url['host']);
}
// Set the proper request URI.
$request_uri = isset($parsed_url['path']) ? $parsed_url['path'] : '/';
if ($signature_version === 2)
{
// Prepare the string to sign
$string_to_sign = "POST\n$host_header\n$request_uri\n$canonical_query_string";
// Hash the AWS secret key and generate a signature for the request.
$query['Signature'] = base64_encode(hash_hmac('sha256', $string_to_sign, $this->secret_key, true));
}
// Generate the querystring from $query
$querystring = $this->util->to_query_string($query);
// Gather information to pass along to other classes.
$helpers = array(
'utilities' => $this->utilities_class,
'request' => $this->request_class,
'response' => $this->response_class,
);
// Compose the request.
$request_url = ($this->use_ssl ? 'https://' : 'http://') . $domain;
$request_url .= !isset($parsed_url['path']) ? '/' : '';
// Instantiate the request class
$request = new $this->request_class($request_url, $this->proxy, $helpers);
$request->set_method('POST');
$request->set_body($querystring);
$headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
// Do we have an authentication token?
if ($this->auth_token)
{
$headers['X-Amz-Security-Token'] = $this->auth_token;
}
// Signing using X-Amz-Target is handled differently.
if ($signature_version === 3 && $x_amz_target)
{
$headers['X-Amz-Target'] = $x_amz_target;
$headers['Content-Type'] = 'application/json; amzn-1.0';
$headers['Content-Encoding'] = 'amz-1.0';
$request->set_body($query['body']);
$querystring = $query['body'];
}
// Pass along registered stream callbacks
if ($this->registered_streaming_read_callback)
{
$request->register_streaming_read_callback($this->registered_streaming_read_callback);
}
if ($this->registered_streaming_write_callback)
{
$request->register_streaming_write_callback($this->registered_streaming_write_callback);
}
// Add authentication headers
if ($signature_version === 3)
{
$headers['X-Amz-Nonce'] = $nonce;
$headers['Date'] = $date;
$headers['Content-Length'] = strlen($querystring);
$headers['Content-MD5'] = $this->util->hex_to_base64(md5($querystring));
$headers['Host'] = $host_header;
}
// Sort headers
uksort($headers, 'strnatcasecmp');
if ($signature_version === 3 && $this->use_ssl)
{
// Prepare the string to sign (HTTPS)
$string_to_sign = $date . $nonce;
}
elseif ($signature_version === 3 && !$this->use_ssl)
{
// Prepare the string to sign (HTTP)
$string_to_sign = "POST\n$request_uri\n\n";
}
// Add headers to request and compute the string to sign
foreach ($headers as $header_key => $header_value)
{
// Strip linebreaks from header values as they're illegal and can allow for security issues
$header_value = str_replace(array("\r", "\n"), '', $header_value);
// Add the header if it has a value
if ($header_value !== '')
{
$request->add_header($header_key, $header_value);
}
// Signature v3 over HTTP
if ($signature_version === 3 && !$this->use_ssl)
{
// Generate the string to sign
if (
substr(strtolower($header_key), 0, 8) === 'content-' ||
strtolower($header_key) === 'date' ||
strtolower($header_key) === 'expires' ||
strtolower($header_key) === 'host' ||
substr(strtolower($header_key), 0, 6) === 'x-amz-'
)
{
$string_to_sign .= strtolower($header_key) . ':' . $header_value . "\n";
$signed_headers[] = $header_key;
}
}
}
if ($signature_version === 3)
{
if (!$this->use_ssl)
{
$string_to_sign .= "\n";
if (isset($query['body']) && $query['body'] !== '')
{
$string_to_sign .= $query['body'];
}
// Convert from string-to-sign to bytes-to-sign
$bytes_to_sign = hash('sha256', $string_to_sign, true);
// Hash the AWS secret key and generate a signature for the request.
$signature = base64_encode(hash_hmac('sha256', $bytes_to_sign, $this->secret_key, true));
}
else
{
// Hash the AWS secret key and generate a signature for the request.
$signature = base64_encode(hash_hmac('sha256', $string_to_sign, $this->secret_key, true));
}
$headers['X-Amzn-Authorization'] = 'AWS3' . ($this->use_ssl ? '-HTTPS' : '')
. ' AWSAccessKeyId=' . $this->key
. ',Algorithm=HmacSHA256'
. ',SignedHeaders=' . implode(';', $signed_headers)
. ',Signature=' . $signature;
$request->add_header('X-Amzn-Authorization', $headers['X-Amzn-Authorization']);
}
// Update RequestCore settings
$request->request_class = $this->request_class;
$request->response_class = $this->response_class;
$curlopts = array();
// Set custom CURLOPT settings
if (is_array($opt) && isset($opt['curlopts']))
{
$curlopts = $opt['curlopts'];
unset($opt['curlopts']);
}
// Debug mode
if ($this->debug_mode)
{
$request->debug_mode = $this->debug_mode;
}
if (count($curlopts))
{
$request->set_curlopts($curlopts);
}
// Manage the (newer) batch request API or the (older) returnCurlHandle setting.
if ($this->use_batch_flow)
{
$handle = $request->prep_request();
$this->batch_object->add($handle);
$this->use_batch_flow = false;
return $handle;
}
elseif ($return_curl_handle)
{
return $request->prep_request();
}
// Send!
$request->send_request();
$request_headers = $headers;
// Prepare the response.
$headers = $request->get_response_header();
$headers['x-aws-stringtosign'] = $string_to_sign;
$headers['x-aws-request-headers'] = $request_headers;
$headers['x-aws-body'] = $querystring;
$data = new $this->response_class($headers, $this->parse_callback($request->get_response_body(), $headers), $request->get_response_code());
// Was it Amazon's fault the request failed? Retry the request until we reach $max_retries.
if ((integer) $request->get_response_code() === 500 || (integer) $request->get_response_code() === 503)
{
if ($redirects <= $this->max_retries)
{
// Exponential backoff
$delay = (integer) (pow(4, $redirects) * 100000);
usleep($delay);
$data = $this->authenticate($action, $opt, $domain, $signature_version, ++$redirects);
}
}
return $data;
} | Default, shared method for authenticating a connection to AWS. Overridden on a class-by-class basis
as necessary.
@param string $action (Required) Indicates the action to perform.
@param array $opt (Optional) An associative array of parameters for authenticating. See the individual methods for allowed keys.
@param string $domain (Optional) The URL of the queue to perform the action on.
@param integer $signature_version (Optional) The signature version to use. Defaults to 2.
@param integer $redirects (Do Not Use) Used internally by this function on occasions when Amazon S3 returns a redirect code and it needs to call itself recursively.
@return CFResponse Object containing a parsed HTTP response. | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/sdk.class.php#L743-L1071 |
Etenil/assegai | src/assegai/modules/mail/services/ses/sdk.class.php | CFRuntime.batch | public function batch(CFBatchRequest &$queue = null)
{
if ($queue)
{
$this->batch_object = $queue;
}
elseif ($this->internal_batch_object)
{
$this->batch_object = &$this->internal_batch_object;
}
else
{
$this->internal_batch_object = new $this->batch_class();
$this->batch_object = &$this->internal_batch_object;
}
$this->use_batch_flow = true;
return $this;
} | php | public function batch(CFBatchRequest &$queue = null)
{
if ($queue)
{
$this->batch_object = $queue;
}
elseif ($this->internal_batch_object)
{
$this->batch_object = &$this->internal_batch_object;
}
else
{
$this->internal_batch_object = new $this->batch_class();
$this->batch_object = &$this->internal_batch_object;
}
$this->use_batch_flow = true;
return $this;
} | Specifies that the intended request should be queued for a later batch request.
@param CFBatchRequest $queue (Optional) The <CFBatchRequest> instance to use for managing batch requests. If not available, it generates a new instance of <CFBatchRequest>.
@return $this A reference to the current instance. | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/sdk.class.php#L1083-L1102 |
Etenil/assegai | src/assegai/modules/mail/services/ses/sdk.class.php | CFRuntime.send | public function send($clear_after_send = true)
{
if ($this->use_batch_flow)
{
// When we send the request, disable batch flow.
$this->use_batch_flow = false;
// If we're not caching, simply send the request.
if (!$this->use_cache_flow)
{
$response = $this->batch_object->send();
$parsed_data = array_map(array($this, 'parse_callback'), $response);
$parsed_data = new CFArray($parsed_data);
// Clear the queue
if ($clear_after_send)
{
$this->batch_object->queue = array();
}
return $parsed_data;
}
// Generate an identifier specific to this particular set of arguments.
$cache_id = $this->key . '_' . get_class($this) . '_' . sha1(serialize($this->batch_object));
// Instantiate the appropriate caching object.
$this->cache_object = new $this->cache_class($cache_id, $this->cache_location, $this->cache_expires, $this->cache_compress);
if ($this->delete_cache)
{
$this->use_cache_flow = false;
$this->delete_cache = false;
return $this->cache_object->delete();
}
// Invoke the cache callback function to determine whether to pull data from the cache or make a fresh request.
$data_set = $this->cache_object->response_manager(array($this, 'cache_callback_batch'), array($this->batch_object));
$parsed_data = array_map(array($this, 'parse_callback'), $data_set);
$parsed_data = new CFArray($parsed_data);
// Clear the queue
if ($clear_after_send)
{
$this->batch_object->queue = array();
}
// End!
return $parsed_data;
}
// Load the class
$null = new CFBatchRequest();
unset($null);
throw new CFBatchRequest_Exception('You must use $object->batch()->send()');
} | php | public function send($clear_after_send = true)
{
if ($this->use_batch_flow)
{
// When we send the request, disable batch flow.
$this->use_batch_flow = false;
// If we're not caching, simply send the request.
if (!$this->use_cache_flow)
{
$response = $this->batch_object->send();
$parsed_data = array_map(array($this, 'parse_callback'), $response);
$parsed_data = new CFArray($parsed_data);
// Clear the queue
if ($clear_after_send)
{
$this->batch_object->queue = array();
}
return $parsed_data;
}
// Generate an identifier specific to this particular set of arguments.
$cache_id = $this->key . '_' . get_class($this) . '_' . sha1(serialize($this->batch_object));
// Instantiate the appropriate caching object.
$this->cache_object = new $this->cache_class($cache_id, $this->cache_location, $this->cache_expires, $this->cache_compress);
if ($this->delete_cache)
{
$this->use_cache_flow = false;
$this->delete_cache = false;
return $this->cache_object->delete();
}
// Invoke the cache callback function to determine whether to pull data from the cache or make a fresh request.
$data_set = $this->cache_object->response_manager(array($this, 'cache_callback_batch'), array($this->batch_object));
$parsed_data = array_map(array($this, 'parse_callback'), $data_set);
$parsed_data = new CFArray($parsed_data);
// Clear the queue
if ($clear_after_send)
{
$this->batch_object->queue = array();
}
// End!
return $parsed_data;
}
// Load the class
$null = new CFBatchRequest();
unset($null);
throw new CFBatchRequest_Exception('You must use $object->batch()->send()');
} | Executes the batch request queue by sending all queued requests.
@param boolean $clear_after_send (Optional) Whether or not to clear the batch queue after sending a request. Defaults to `true`. Set this to `false` if you are caching batch responses and want to retrieve results later.
@return array An array of <CFResponse> objects. | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/sdk.class.php#L1110-L1166 |
Etenil/assegai | src/assegai/modules/mail/services/ses/sdk.class.php | CFRuntime.parse_callback | public function parse_callback($response, $headers = null)
{
// Shorten this so we have a (mostly) single code path
if (isset($response->body))
{
if (is_string($response->body))
{
$body = $response->body;
}
else
{
return $response;
}
}
elseif (is_string($response))
{
$body = $response;
}
else
{
return $response;
}
// Decompress gzipped content
if (isset($headers['content-encoding']))
{
switch (strtolower(trim($headers['content-encoding'], "\x09\x0A\x0D\x20")))
{
case 'gzip':
case 'x-gzip':
if (strpos($headers['_info']['url'], 'monitoring.') !== false)
{
// CloudWatch incorrectly uses the deflate algorithm when they say gzip.
if (($uncompressed = gzuncompress($body)) !== false)
{
$body = $uncompressed;
}
elseif (($uncompressed = gzinflate($body)) !== false)
{
$body = $uncompressed;
}
break;
}
else
{
// Everyone else uses gzip correctly.
$decoder = new CFGzipDecode($body);
if ($decoder->parse())
{
$body = $decoder->data;
}
break;
}
case 'deflate':
if (strpos($headers['_info']['url'], 'monitoring.') !== false)
{
// CloudWatch incorrectly does nothing when they say deflate.
continue;
}
else
{
// Everyone else uses deflate correctly.
if (($uncompressed = gzuncompress($body)) !== false)
{
$body = $uncompressed;
}
elseif (($uncompressed = gzinflate($body)) !== false)
{
$body = $uncompressed;
}
}
break;
}
}
// Look for XML cues
if (
(isset($headers['content-type']) && ($headers['content-type'] === 'text/xml' || $headers['content-type'] === 'application/xml')) || // We know it's XML
(!isset($headers['content-type']) && (stripos($body, '<?xml') === 0 || strpos($body, '<Error>') === 0) || preg_match('/^<(\w*) xmlns="http(s?):\/\/(\w*).amazon(aws)?.com/im', $body)) // Sniff for XML
)
{
// Strip the default XML namespace to simplify XPath expressions
$body = str_replace("xmlns=", "ns=", $body);
// Parse the XML body
$body = new $this->parser_class($body);
}
// Look for JSON cues
elseif (
(isset($headers['content-type']) && $headers['content-type'] === 'application/json') || // We know it's JSON
(!isset($headers['content-type']) && $this->util->is_json($body)) // Sniff for JSON
)
{
// Normalize JSON to a CFSimpleXML object
$body = CFJSON::to_xml($body);
}
// Put the parsed data back where it goes
if (isset($response->body))
{
$response->body = $body;
}
else
{
$response = $body;
}
return $response;
} | php | public function parse_callback($response, $headers = null)
{
// Shorten this so we have a (mostly) single code path
if (isset($response->body))
{
if (is_string($response->body))
{
$body = $response->body;
}
else
{
return $response;
}
}
elseif (is_string($response))
{
$body = $response;
}
else
{
return $response;
}
// Decompress gzipped content
if (isset($headers['content-encoding']))
{
switch (strtolower(trim($headers['content-encoding'], "\x09\x0A\x0D\x20")))
{
case 'gzip':
case 'x-gzip':
if (strpos($headers['_info']['url'], 'monitoring.') !== false)
{
// CloudWatch incorrectly uses the deflate algorithm when they say gzip.
if (($uncompressed = gzuncompress($body)) !== false)
{
$body = $uncompressed;
}
elseif (($uncompressed = gzinflate($body)) !== false)
{
$body = $uncompressed;
}
break;
}
else
{
// Everyone else uses gzip correctly.
$decoder = new CFGzipDecode($body);
if ($decoder->parse())
{
$body = $decoder->data;
}
break;
}
case 'deflate':
if (strpos($headers['_info']['url'], 'monitoring.') !== false)
{
// CloudWatch incorrectly does nothing when they say deflate.
continue;
}
else
{
// Everyone else uses deflate correctly.
if (($uncompressed = gzuncompress($body)) !== false)
{
$body = $uncompressed;
}
elseif (($uncompressed = gzinflate($body)) !== false)
{
$body = $uncompressed;
}
}
break;
}
}
// Look for XML cues
if (
(isset($headers['content-type']) && ($headers['content-type'] === 'text/xml' || $headers['content-type'] === 'application/xml')) || // We know it's XML
(!isset($headers['content-type']) && (stripos($body, '<?xml') === 0 || strpos($body, '<Error>') === 0) || preg_match('/^<(\w*) xmlns="http(s?):\/\/(\w*).amazon(aws)?.com/im', $body)) // Sniff for XML
)
{
// Strip the default XML namespace to simplify XPath expressions
$body = str_replace("xmlns=", "ns=", $body);
// Parse the XML body
$body = new $this->parser_class($body);
}
// Look for JSON cues
elseif (
(isset($headers['content-type']) && $headers['content-type'] === 'application/json') || // We know it's JSON
(!isset($headers['content-type']) && $this->util->is_json($body)) // Sniff for JSON
)
{
// Normalize JSON to a CFSimpleXML object
$body = CFJSON::to_xml($body);
}
// Put the parsed data back where it goes
if (isset($response->body))
{
$response->body = $body;
}
else
{
$response = $body;
}
return $response;
} | Parses a response body into a PHP object if appropriate.
@param CFResponse|string $response (Required) The <CFResponse> object to parse, or an XML string that would otherwise be a response body.
@param string $content_type (Optional) The content-type to use when determining how to parse the content.
@return CFResponse|string A parsed <CFResponse> object, or parsed XML. | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/sdk.class.php#L1175-L1284 |
Etenil/assegai | src/assegai/modules/mail/services/ses/sdk.class.php | CFRuntime.cache | public function cache($expires)
{
// Die if they haven't used set_cache_config().
if (!$this->cache_class)
{
throw new CFRuntime_Exception('Must call set_cache_config() before using cache()');
}
if (is_string($expires))
{
$expires = strtotime($expires);
$this->cache_expires = $expires - time();
}
elseif (is_int($expires))
{
$this->cache_expires = $expires;
}
$this->use_cache_flow = true;
return $this;
} | php | public function cache($expires)
{
// Die if they haven't used set_cache_config().
if (!$this->cache_class)
{
throw new CFRuntime_Exception('Must call set_cache_config() before using cache()');
}
if (is_string($expires))
{
$expires = strtotime($expires);
$this->cache_expires = $expires - time();
}
elseif (is_int($expires))
{
$this->cache_expires = $expires;
}
$this->use_cache_flow = true;
return $this;
} | Specifies that the resulting <CFResponse> object should be cached according to the settings from
<set_cache_config()>.
@param string|integer $expires (Required) The time the cache is to expire. Accepts a number of seconds as an integer, or an amount of time, as a string, that is understood by <php:strtotime()> (e.g. "1 hour").
@param $this A reference to the current instance.
@return $this | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/sdk.class.php#L1298-L1319 |
Etenil/assegai | src/assegai/modules/mail/services/ses/sdk.class.php | CFRuntime.cache_callback | public function cache_callback($action, $opt = null, $domain = null, $signature_version = 2)
{
// Disable the cache flow since it's already been handled.
$this->use_cache_flow = false;
// Make the request
$response = $this->authenticate($action, $opt, $domain, $signature_version);
// If this is an XML document, convert it back to a string.
if (isset($response->body) && ($response->body instanceof SimpleXMLElement))
{
$response->body = $response->body->asXML();
}
return $response;
} | php | public function cache_callback($action, $opt = null, $domain = null, $signature_version = 2)
{
// Disable the cache flow since it's already been handled.
$this->use_cache_flow = false;
// Make the request
$response = $this->authenticate($action, $opt, $domain, $signature_version);
// If this is an XML document, convert it back to a string.
if (isset($response->body) && ($response->body instanceof SimpleXMLElement))
{
$response->body = $response->body->asXML();
}
return $response;
} | The callback function that is executed when the cache doesn't exist or has expired. The response of
this method is cached. Accepts identical parameters as the <authenticate()> method. Never call this
method directly -- it is used internally by the caching system.
@param string $action (Required) Indicates the action to perform.
@param array $opt (Optional) An associative array of parameters for authenticating. See the individual methods for allowed keys.
@param string $domain (Optional) The URL of the queue to perform the action on.
@param integer $signature_version (Optional) The signature version to use. Defaults to 2.
@return CFResponse A parsed HTTP response. | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/sdk.class.php#L1332-L1347 |
Etenil/assegai | src/assegai/modules/mail/services/ses/sdk.class.php | CFLoader.autoloader | public static function autoloader($class)
{
$path = dirname(__FILE__) . DIRECTORY_SEPARATOR;
// Amazon SDK classes
if (strstr($class, 'Amazon'))
{
$path .= 'services' . DIRECTORY_SEPARATOR . str_ireplace('Amazon', '', strtolower($class)) . '.class.php';
}
// Utility classes
elseif (strstr($class, 'CF'))
{
$path .= 'utilities' . DIRECTORY_SEPARATOR . str_ireplace('CF', '', strtolower($class)) . '.class.php';
}
// Load CacheCore
elseif (strstr($class, 'Cache'))
{
if (file_exists($ipath = 'lib' . DIRECTORY_SEPARATOR . 'cachecore' . DIRECTORY_SEPARATOR . 'icachecore.interface.php'))
{
require_once($ipath);
}
$path .= 'lib' . DIRECTORY_SEPARATOR . 'cachecore' . DIRECTORY_SEPARATOR . strtolower($class) . '.class.php';
}
// Load RequestCore
elseif (strstr($class, 'RequestCore') || strstr($class, 'ResponseCore'))
{
$path .= 'lib' . DIRECTORY_SEPARATOR . 'requestcore' . DIRECTORY_SEPARATOR . 'requestcore.class.php';
}
// Load Symfony YAML classes
elseif (strstr($class, 'sfYaml'))
{
$path .= 'lib' . DIRECTORY_SEPARATOR . 'yaml' . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'sfYaml.php';
}
// Fall back to the 'extensions' directory.
elseif (defined('AWS_ENABLE_EXTENSIONS') && AWS_ENABLE_EXTENSIONS)
{
$path .= 'extensions' . DIRECTORY_SEPARATOR . strtolower($class) . '.class.php';
}
if (file_exists($path) && !is_dir($path))
{
require_once($path);
}
} | php | public static function autoloader($class)
{
$path = dirname(__FILE__) . DIRECTORY_SEPARATOR;
// Amazon SDK classes
if (strstr($class, 'Amazon'))
{
$path .= 'services' . DIRECTORY_SEPARATOR . str_ireplace('Amazon', '', strtolower($class)) . '.class.php';
}
// Utility classes
elseif (strstr($class, 'CF'))
{
$path .= 'utilities' . DIRECTORY_SEPARATOR . str_ireplace('CF', '', strtolower($class)) . '.class.php';
}
// Load CacheCore
elseif (strstr($class, 'Cache'))
{
if (file_exists($ipath = 'lib' . DIRECTORY_SEPARATOR . 'cachecore' . DIRECTORY_SEPARATOR . 'icachecore.interface.php'))
{
require_once($ipath);
}
$path .= 'lib' . DIRECTORY_SEPARATOR . 'cachecore' . DIRECTORY_SEPARATOR . strtolower($class) . '.class.php';
}
// Load RequestCore
elseif (strstr($class, 'RequestCore') || strstr($class, 'ResponseCore'))
{
$path .= 'lib' . DIRECTORY_SEPARATOR . 'requestcore' . DIRECTORY_SEPARATOR . 'requestcore.class.php';
}
// Load Symfony YAML classes
elseif (strstr($class, 'sfYaml'))
{
$path .= 'lib' . DIRECTORY_SEPARATOR . 'yaml' . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'sfYaml.php';
}
// Fall back to the 'extensions' directory.
elseif (defined('AWS_ENABLE_EXTENSIONS') && AWS_ENABLE_EXTENSIONS)
{
$path .= 'extensions' . DIRECTORY_SEPARATOR . strtolower($class) . '.class.php';
}
if (file_exists($path) && !is_dir($path))
{
require_once($path);
}
} | Automatically load classes that aren't included.
@param string $class (Required) The classname to load.
@return void | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mail/services/ses/sdk.class.php#L1391-L1440 |
liufee/cms-core | common/helpers/StringHelper.php | StringHelper.encodingWithUtf8 | public static function encodingWithUtf8($str)
{
$cur_encoding = mb_detect_encoding($str);
if ($cur_encoding == "UTF-8" && mb_check_encoding($str, "UTF-8")) {
return $str;
} else {
return utf8_encode($str);
}
} | php | public static function encodingWithUtf8($str)
{
$cur_encoding = mb_detect_encoding($str);
if ($cur_encoding == "UTF-8" && mb_check_encoding($str, "UTF-8")) {
return $str;
} else {
return utf8_encode($str);
}
} | 返回utf8编码的字符串
@param $str
@return string | https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/common/helpers/StringHelper.php#L21-L29 |
IftekherSunny/Planet-Framework | src/Sun/Http/Response.php | Response.html | public function html($data)
{
if(is_array($data)) {
echo $this->json($data);
} else {
echo $data;
}
if($this->app->config('session.enable')) {
$this->session->create('previous_uri', $_SERVER['REQUEST_URI']);
$this->session->create('planet_oldInput', null);
}
} | php | public function html($data)
{
if(is_array($data)) {
echo $this->json($data);
} else {
echo $data;
}
if($this->app->config('session.enable')) {
$this->session->create('previous_uri', $_SERVER['REQUEST_URI']);
$this->session->create('planet_oldInput', null);
}
} | To response with html
@param string $data | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Http/Response.php#L39-L51 |
IftekherSunny/Planet-Framework | src/Sun/Http/Response.php | Response.json | public function json($data, $status = 200)
{
$this->header('Content-Type: application/json');
$this->statusCode($status);
return json_encode($data);
} | php | public function json($data, $status = 200)
{
$this->header('Content-Type: application/json');
$this->statusCode($status);
return json_encode($data);
} | To response with json
@param string $data
@param int $status
@return string | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Http/Response.php#L61-L68 |
IftekherSunny/Planet-Framework | src/Sun/Http/Response.php | Response.download | public function download($path, $removeDownloadedFile = false)
{
if(!file_exists($path)) {
throw new Exception("File [ $path ] not found.");
}
$filename = pathinfo($path, PATHINFO_BASENAME );
header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");
@readfile($path);
if($removeDownloadedFile) {
@unlink($path);
}
} | php | public function download($path, $removeDownloadedFile = false)
{
if(!file_exists($path)) {
throw new Exception("File [ $path ] not found.");
}
$filename = pathinfo($path, PATHINFO_BASENAME );
header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");
@readfile($path);
if($removeDownloadedFile) {
@unlink($path);
}
} | Http Response to download file
@param string $path
@param bool $removeDownloadedFile
@throws Exception | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Http/Response.php#L78-L95 |
acacha/forge-publish | src/Console/Commands/PublishDeploymentScript.php | PublishDeploymentScript.handle | public function handle()
{
$this->abortCommandExecution();
if ($this->file = $this->argument('file')) {
$this->updateDeploymentScript();
} else {
$this->showDeploymentScript();
}
} | php | public function handle()
{
$this->abortCommandExecution();
if ($this->file = $this->argument('file')) {
$this->updateDeploymentScript();
} else {
$this->showDeploymentScript();
}
} | Execute the console command. | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishDeploymentScript.php#L77-L86 |
acacha/forge-publish | src/Console/Commands/PublishDeploymentScript.php | PublishDeploymentScript.updateDeploymentScript | protected function updateDeploymentScript()
{
$this->info('Updating deployment script for site ' . $this->site . '...');
$this->url = $this->obtainAPIURLEndpoint('update_deployment_script_uri');
if (! File::exists($this->file)) {
$this->error("File " . $this->file . " doesn't exists");
die();
}
$this->http->put($this->url, [
'form_params' => [
'content' => file_get_contents($this->file)
],
'headers' => [
'X-Requested-With' => 'XMLHttpRequest',
'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
]
]
);
} | php | protected function updateDeploymentScript()
{
$this->info('Updating deployment script for site ' . $this->site . '...');
$this->url = $this->obtainAPIURLEndpoint('update_deployment_script_uri');
if (! File::exists($this->file)) {
$this->error("File " . $this->file . " doesn't exists");
die();
}
$this->http->put($this->url, [
'form_params' => [
'content' => file_get_contents($this->file)
],
'headers' => [
'X-Requested-With' => 'XMLHttpRequest',
'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
]
]
);
} | Update deployment script. | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishDeploymentScript.php#L109-L130 |
acacha/forge-publish | src/Console/Commands/PublishDeploymentScript.php | PublishDeploymentScript.obtainAPIURLEndpoint | protected function obtainAPIURLEndpoint($type)
{
$uri = str_replace('{forgeserver}', $this->server, config('forge-publish.' . $type));
$uri = str_replace('{forgesite}', $this->site, $uri);
return config('forge-publish.url') . $uri;
} | php | protected function obtainAPIURLEndpoint($type)
{
$uri = str_replace('{forgeserver}', $this->server, config('forge-publish.' . $type));
$uri = str_replace('{forgesite}', $this->site, $uri);
return config('forge-publish.url') . $uri;
} | Obtain API URL endpoint.
@return string | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishDeploymentScript.php#L137-L142 |
acacha/forge-publish | src/Console/Commands/PublishDeploymentScript.php | PublishDeploymentScript.abortCommandExecution | protected function abortCommandExecution()
{
$this->server = $this->checkEnv('server', 'ACACHA_FORGE_SERVER');
$this->site = $this->checkEnv('site', 'ACACHA_FORGE_SITE');
$this->dieIfEnvVarIsNotInstalled('ACACHA_FORGE_ACCESS_TOKEN');
} | php | protected function abortCommandExecution()
{
$this->server = $this->checkEnv('server', 'ACACHA_FORGE_SERVER');
$this->site = $this->checkEnv('site', 'ACACHA_FORGE_SITE');
$this->dieIfEnvVarIsNotInstalled('ACACHA_FORGE_ACCESS_TOKEN');
} | Abort command execution. | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishDeploymentScript.php#L147-L152 |
makinacorpus/drupal-calista | src/EventDispatcher/ViewEventSubscriber.php | ViewEventSubscriber.onTwigView | public function onTwigView(ViewEvent $event)
{
$view = $event->getView();
if (function_exists('drupal_add_library') && $view instanceof TwigView) {
drupal_add_library('calista', 'calista_page');
/*
if ($event->getView()->visualSearchIsEnabled()) {
drupal_add_library('calista', 'calista_search');
}
*/
}
} | php | public function onTwigView(ViewEvent $event)
{
$view = $event->getView();
if (function_exists('drupal_add_library') && $view instanceof TwigView) {
drupal_add_library('calista', 'calista_page');
/*
if ($event->getView()->visualSearchIsEnabled()) {
drupal_add_library('calista', 'calista_search');
}
*/
}
} | Add JS libraries
@param ViewEvent $event | https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/EventDispatcher/ViewEventSubscriber.php#L31-L43 |
schpill/thin | src/Cachedb.php | Cachedb.get | public function get($key, $default = null)
{
return (!is_null($item = $this->retrieve($key))) ? $item : value($default);
} | php | public function get($key, $default = null)
{
return (!is_null($item = $this->retrieve($key))) ? $item : value($default);
} | Get an item from the cache.
<code>
// Get an item from the cache driver
$name = Cache::driver('name');
// Return a default value if the requested item isn't cached
$name = Cache::get('name', 'Taylor');
</code>
@param string $key
@param mixed $default
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Cachedb.php#L58-L61 |
schpill/thin | src/Cachedb.php | Cachedb.retrieve | protected function retrieve($key)
{
$cache = $this->db()->select("entity_name = '" . md5($this->_namespace) . "' AND table_name = '" . md5($key) . "'", true);
if (!empty($cache)) {
$data = unserialize($cache->getData());
$infos = explode('%%%%%:::::', $data);
if (time() >= current($infos)) {
return $this->forget($key);
}
return end($infos);
}
return null;
} | php | protected function retrieve($key)
{
$cache = $this->db()->select("entity_name = '" . md5($this->_namespace) . "' AND table_name = '" . md5($key) . "'", true);
if (!empty($cache)) {
$data = unserialize($cache->getData());
$infos = explode('%%%%%:::::', $data);
if (time() >= current($infos)) {
return $this->forget($key);
}
return end($infos);
}
return null;
} | Retrieve an item from the cache driver.
@param string $key
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Cachedb.php#L69-L83 |
schpill/thin | src/Cachedb.php | Cachedb.put | public function put($key, $value, $minutes)
{
$cache = $this->db()->select("entity_name = '" . md5($this->_namespace) . "' AND table_name = '" . md5($key) . "'", true);
if (empty($cache)) {
$cache = em($this->config->entity, $this->config->table);
} else {
$cache->delete();
$cache = em($this->config->entity, $this->config->table);
}
$data = serialize(($this->expiration($minutes) + time()) . '%%%%%:::::' . $value);
$cache->setDateAdd(date('Y-m-d H:i:s'))->setEntityName(md5($this->_namespace))->setTableName(md5($key))->setTableId(999)->setData($data);
$newCache = $cache->save();
return $this;
} | php | public function put($key, $value, $minutes)
{
$cache = $this->db()->select("entity_name = '" . md5($this->_namespace) . "' AND table_name = '" . md5($key) . "'", true);
if (empty($cache)) {
$cache = em($this->config->entity, $this->config->table);
} else {
$cache->delete();
$cache = em($this->config->entity, $this->config->table);
}
$data = serialize(($this->expiration($minutes) + time()) . '%%%%%:::::' . $value);
$cache->setDateAdd(date('Y-m-d H:i:s'))->setEntityName(md5($this->_namespace))->setTableName(md5($key))->setTableId(999)->setData($data);
$newCache = $cache->save();
return $this;
} | Write an item to the cache for a given number of minutes.
<code>
// Put an item in the cache for 15 minutes
Cachedb::put('name', 'Taylor', 15);
</code>
@param string $key
@param mixed $value
@param int $minutes
@return Thin\Cachedb | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Cachedb.php#L98-L112 |
schpill/thin | src/Cachedb.php | Cachedb.forget | public function forget($key)
{
$cache = $this->db()->select("entity_name = '" . md5($this->_namespace) . "' AND table_name = '" . md5($key) . "'", true);
if (!empty($cache)) {
$cache->delete();
}
} | php | public function forget($key)
{
$cache = $this->db()->select("entity_name = '" . md5($this->_namespace) . "' AND table_name = '" . md5($key) . "'", true);
if (!empty($cache)) {
$cache->delete();
}
} | Delete an item from the cache.
@param string $key
@return void | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Cachedb.php#L132-L138 |
Elephant418/Staq | src/Staq/Util.php | Util.dirname | public static function dirname($path, $level = 1)
{
for ($i = 0; $i < $level; $i++) {
$path = \dirname($path);
}
return $path;
} | php | public static function dirname($path, $level = 1)
{
for ($i = 0; $i < $level; $i++) {
$path = \dirname($path);
}
return $path;
} | PATH FUNCTIONS | https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Util.php#L15-L21 |
Elephant418/Staq | src/Staq/Util.php | Util.httpRedirect | public static function httpRedirect($url, $code=NULL)
{
if ($code == 301) {
header('HTTP/1.1 301 Moved Permanently');
} else {
header('HTTP/1.1 302 Moved Temporarily');
}
header('Location: ' . $url);
die();
} | php | public static function httpRedirect($url, $code=NULL)
{
if ($code == 301) {
header('HTTP/1.1 301 Moved Permanently');
} else {
header('HTTP/1.1 302 Moved Temporarily');
}
header('Location: ' . $url);
die();
} | /* HTTP METHODS
*********************************************************************** | https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Util.php#L47-L56 |
Elephant418/Staq | src/Staq/Util.php | Util.popStackQuery | public static function popStackQuery($string)
{
if (\Staq\Util::isStackQueryPopable($string)) {
$string = \UString::substrBeforeLast($string, '\\');
} else {
$string = NULL;
}
return $string;
} | php | public static function popStackQuery($string)
{
if (\Staq\Util::isStackQueryPopable($string)) {
$string = \UString::substrBeforeLast($string, '\\');
} else {
$string = NULL;
}
return $string;
} | STACK QUERY | https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Util.php#L87-L95 |
MovingImage24/guzzle-service-builder | src/ServiceFactory.php | ServiceFactory.factory | public function factory($config)
{
$class = $config['class'];
$desc = new Description($config['description']);
/** @var GuzzleClient $service */
$service = new $class($this->client, $desc);
$service->getEmitter()->attach(new ClassResponse($desc, $this->serializer));
return $service;
} | php | public function factory($config)
{
$class = $config['class'];
$desc = new Description($config['description']);
/** @var GuzzleClient $service */
$service = new $class($this->client, $desc);
$service->getEmitter()->attach(new ClassResponse($desc, $this->serializer));
return $service;
} | {@inheritdoc} | https://github.com/MovingImage24/guzzle-service-builder/blob/3ddc4ae4a433084f03e0f9e10c1f8db834e97740/src/ServiceFactory.php#L32-L42 |
apitude/user | src/OAuth/Storage/ScopeStorage.php | ScopeStorage.get | public function get($scope, $grantType = null, $clientId = null)
{
foreach ($this->getDbConnection()->fetchAll(
'SELECT * from oauth_scope WHERE id = :scope',
['scope' => $scope]
) as $row) {
if ($row) {
return (new ScopeEntity($this->server))
->hydrate([
'id' => $row['id'],
'description' => $row['description']
]);
}
}
return null;
} | php | public function get($scope, $grantType = null, $clientId = null)
{
foreach ($this->getDbConnection()->fetchAll(
'SELECT * from oauth_scope WHERE id = :scope',
['scope' => $scope]
) as $row) {
if ($row) {
return (new ScopeEntity($this->server))
->hydrate([
'id' => $row['id'],
'description' => $row['description']
]);
}
}
return null;
} | Return information about a scope
@param string $scope The scope
@param string $grantType The grant type used in the request (default = "null")
@param string $clientId The client sending the request (default = "null")
@return \League\OAuth2\Server\Entity\ScopeEntity | null | https://github.com/apitude/user/blob/24adf733cf628d321c2bcae328c383113928d019/src/OAuth/Storage/ScopeStorage.php#L38-L53 |
igorwanbarros/autenticacao-laravel | src/Managers/DashboardManager.php | DashboardManager.add | public function add($alias, $name = null, $className = null, $method = null)
{
if (is_array($alias)) {
$this->dashboards = array_merge($this->dashboards, $alias);
return $this;
}
$this->dashboards[] = [
'alias' => $alias,
'name' => $name,
'class' => $className,
'method' => $method,
];
return $this;
} | php | public function add($alias, $name = null, $className = null, $method = null)
{
if (is_array($alias)) {
$this->dashboards = array_merge($this->dashboards, $alias);
return $this;
}
$this->dashboards[] = [
'alias' => $alias,
'name' => $name,
'class' => $className,
'method' => $method,
];
return $this;
} | @param mixed $className
@param mixed $name
@param mixed $alias
@param mixed $method
@return $this | https://github.com/igorwanbarros/autenticacao-laravel/blob/e7e8217dae433934fe46c34516fb2f6f5f932fc1/src/Managers/DashboardManager.php#L18-L34 |
infusephp/auth | src/Jobs/GarbageCollection.php | GarbageCollection.run | public function run()
{
$res1 = $this->gcPersistent();
$res2 = $this->gcUserLinks();
$res3 = $this->gcActive();
return $res1 && $res2 && $res3;
} | php | public function run()
{
$res1 = $this->gcPersistent();
$res2 = $this->gcUserLinks();
$res3 = $this->gcActive();
return $res1 && $res2 && $res3;
} | Runs the auth garbage collection.
@return array | https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Jobs/GarbageCollection.php#L33-L40 |
infusephp/auth | src/Jobs/GarbageCollection.php | GarbageCollection.gcPersistent | private function gcPersistent()
{
return (bool) $this->app['database']->getDefault()
->delete('PersistentSessions')
->where('created_at', U::unixToDb(time() - PersistentSession::$sessionLength), '<')
->execute();
} | php | private function gcPersistent()
{
return (bool) $this->app['database']->getDefault()
->delete('PersistentSessions')
->where('created_at', U::unixToDb(time() - PersistentSession::$sessionLength), '<')
->execute();
} | Clears out expired persistent sessions.
@return bool | https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Jobs/GarbageCollection.php#L60-L66 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.