sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public static function url($url = '', $echo = true) { $return = ''; // 解析URL if (empty($url)) { throw new \InvalidArgumentException(Lang::get('_NOT_ALLOW_EMPTY_', 'url')); //'U方法参数出错' } // URL组装 $delimiter = Config::get('url_pathinfo_depr'); $url = ltrim($url, '/'); $url = implode($delimiter, explode('/', $url)); if (Config::get('url_model') == 1) { $return = $_SERVER['SCRIPT_NAME'] . '/' . $url; } elseif (Config::get('url_model') == 2) { $return = Cml::getContainer()->make('cml_route')->getSubDirName() . $url; } elseif (Config::get('url_model') == 3) { $return = $_SERVER['SCRIPT_NAME'] . '?' . Config::get('var_pathinfo') . '=/' . $url; } $return .= (Config::get('url_model') == 2 ? Config::get('url_html_suffix') : ''); $return = Secure::filterScript($return); if ($echo) { echo $return; return ''; } else { return $return; } }
URL组装 支持不同URL模式 eg: \Cml\Http\Response::url('Home/Blog/cate/id/1') @param string $url URL表达式 路径/控制器/操作/参数1/参数1值/..... @param bool $echo 是否输出 true输出 false return @return string
entailment
public static function sendContentTypeBySubFix($subFix = 'html') { $mines = [ 'html' => 'text/html', 'htm' => 'text/html', 'shtml' => 'text/html', 'css' => 'text/css', 'xml' => 'text/xml', 'gif' => 'image/gif', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'js' => 'application/x-javascript', 'atom' => 'application/atom+xml', 'rss' => 'application/rss+xml', 'mml' => 'text/mathml', 'txt' => 'text/plain', 'wml' => 'text/vnd.wap.wml', 'jad' => 'text/vnd.sun.j2me.app-descriptor', 'htc' => 'text/x-component', 'png' => 'image/png', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'wbmp' => 'image/vnd.wap.wbmp', 'ico' => 'image/x-icon', 'jng' => 'image/x-jng', 'bmp' => 'image/x-ms-bmp', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', 'webp' => 'image/webp', 'doc' => 'application/msword', 'pdf' => 'application/pdf', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'rar' => 'application/x-rar-compressed', 'swf' => 'application/x-shockwave-flash', 'zip' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'mp3' => 'audio/mpeg', 'ogg' => 'audio/ogg', 'm4a' => 'audio/ogg', 'mp4' => 'video/mp4 ', 'wmv' => 'video/x-ms-wmv', 'avi' => 'video/x-msvideo', 'woff' => 'application/font-woff', 'eot' => 'application/vnd.ms-fontobject' ]; $mine = isset($mines[$subFix]) ? $mines[$subFix] : 'text/html'; header("Content-Type:{$mine};charset=utf-8"); return $mine; }
通过后缀名输出contentType并返回 @param string $subFix @return string
entailment
public function generateContentType($extension) { if (!in_array($extension, InvalidExtensionException::getValidExtensions())) { throw InvalidExtensionException::fromExtension($extension); } return sprintf('image/%s', $extension == self::DEFAULT_EXTENSION ? 'jpeg' : $extension); }
Generates the content-type corresponding to the provided extension @param $extension @return string @throws InvalidExtensionException
entailment
public function getQrCodeContent($messageOrParams, $extension = null, $size = null, $padding = null) { if ($messageOrParams instanceof Params) { $extension = $messageOrParams->fromRoute('extension', $this->options->getExtension()); $size = $messageOrParams->fromRoute('size', $this->options->getSize()); $padding = $messageOrParams->fromRoute('padding', $this->options->getPadding()); $messageOrParams = $messageOrParams->fromRoute('message'); } else { $extension = isset($extension) ? $extension : $this->options->getExtension(); $size = isset($size) ? $size : $this->options->getSize(); $padding = isset($padding) ? $padding : $this->options->getPadding(); } $qrCode = new QrCode($messageOrParams); $qrCode->setImageType($extension); $qrCode->setSize($size); $qrCode->setPadding($padding); return $qrCode->get(); }
Returns a QrCode content to be rendered or saved If the first argument is a Params object, all the information will be tried to be fetched for it, ignoring any other argument @param string|Params $messageOrParams @param string $extension @param int $size @param int $padding @return mixed
entailment
public static function init() { $cmlSession = new Session(); $cmlSession->lifeTime = ini_get('session.gc_maxlifetime'); if (Config::get('session_user_loc') == 'db') { $cmlSession->handler = Model::getInstance()->db(); } else { $cmlSession->handler = Model::getInstance()->cache(); } ini_set('session.save_handler', 'user'); session_module_name('user'); session_set_save_handler( [$cmlSession, 'open'], //运行session_start()时执行 [$cmlSession, 'close'], //在脚本执行结束或调用session_write_close(),或session_destroy()时被执行,即在所有session操作完后被执行 [$cmlSession, 'read'], //在执行session_start()时执行,因为在session_start时会去read当前session数据 [$cmlSession, 'write'], //此方法在脚本结束和session_write_close强制提交SESSION数据时执行 [$cmlSession, 'destroy'], //在执行session_destroy()时执行 [$cmlSession, 'gc'] //执行概率由session.gc_probability和session.gc_divisor的值决定,时机是在open,read之后,session_start会相继执行open,read和gc ); ini_get('session.auto_start') || session_start(); //自动开启session,必须在session_set_save_handler后面执行 }
初始化
entailment
public function read($sessionId) { if (Config::get('session_user_loc') == 'db') { $result = $this->handler->get(Config::get('session_user_loc_table') . '-id-' . $sessionId, true, true, Config::get('session_user_loc_tableprefix')); return $result ? $result[0]['value'] : null; } else { $result = $this->handler->get(Config::get('session_user_loc_tableprefix') . Config::get('session_user_loc_table') . '-id-' . $sessionId); return $result ? $result : null; } }
session读取 @param string $sessionId @return array|null
entailment
public function write($sessionId, $value) { if (Config::get('session_user_loc') == 'db') { $this->handler->set(Config::get('session_user_loc_table'), [ 'id' => $sessionId, 'value' => $value, 'ctime' => Cml::$nowTime ], Config::get('session_user_loc_tableprefix')); } else { $this->handler->set(Config::get('session_user_loc_tableprefix') . Config::get('session_user_loc_table') . '-id-' . $sessionId, $value, $this->lifeTime); } return true; }
session 写入 @param string $sessionId @param string $value @return bool
entailment
public function destroy($sessionId) { if (Config::get('session_user_loc') == 'db') { $this->handler->delete(Config::get('session_user_loc_table') . '-id-' . $sessionId, true, Config::get('session_user_loc_tableprefix')); } else { $this->handler->delete(Config::get('session_user_loc_tableprefix') . Config::get('session_user_loc_table') . '-id-' . $sessionId); } return true; }
session 销毁 @param string $sessionId @return bool
entailment
public function gc($lifeTime = 0) { if (Config::get('session_user_loc') == 'db') { $lifeTime || $lifeTime = $this->lifeTime; $this->handler->whereLt('ctime', Cml::$nowTime - $lifeTime) ->delete(Config::get('session_user_loc_table'), true, Config::get('session_user_loc_tableprefix')); } else { //cache 本身会回收 } return true; }
session gc回收 @param int $lifeTime @return bool
entailment
protected function initHaltHooks() { // error handler set_error_handler(function ($level, $message, $file = null, $line = null) { /** @var $this Application|Console */ $event = $this->getApplicationEvent(); $this->emit($event->setName($this::EVENT_HANDLE_ERROR), $level, $message, $file, $line); }); // exception handler set_exception_handler(function ($exception) { /** @var $this Application|Console */ /** @var \Exception|\Throwable $exception */ // Convert throwable to exception for backwards compatibility if (!($exception instanceof \Exception)) { $throwable = $exception; $exception = new \ErrorException( $throwable->getMessage(), $throwable->getCode(), E_ERROR, $throwable->getFile(), $throwable->getLine() ); } $event = $this->getApplicationEvent(); $this->emit($event->setName($this::EVENT_SYSTEM_EXCEPTION), $exception); }); if (method_exists($this, 'shutdown')) { // shutdown function register_shutdown_function([$this, 'shutdown']); } }
Init all hooks which will be execute on system shutdown or error
entailment
public function get($key) { if ($value = $this->memcache->get($this->prefix.$key)) { return $value; } }
Retrieve an item from the cache by key. @param string $key @return mixed
entailment
public function put($key, $value, $minutes) { $this->memcache->set($this->prefix.$key, $value, false, $minutes * 60); }
Store an item in the cache for a given number of minutes. @param string $key @param mixed $value @param int $minutes @return void
entailment
public function add($key, $value, $minutes) { return $this->memcache->add($this->prefix.$key, $value, false, $minutes * 60); }
Store an item in the cache if the key doesn't exist. @param string $key @param mixed $value @param int $minutes @return bool
entailment
public function increment($key, $value = 1) { return $this->memcache->increment($this->prefix.$key, $value); }
Increment the value of an item in the cache. @param string $key @param mixed $value @return int|bool
entailment
public function decrement($key, $value = 1) { return $this->memcache->decrement($this->prefix.$key, $value); }
Decrement the value of an item in the cache. @param string $key @param mixed $value @return int|bool
entailment
public function handle($request, Closure $next) { $this->kernel->setClosure($next); return $this->middleware->handle($request); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param Closure $next @return mixed
entailment
public function shutdown() { // dispatch shutdown event $applicationEvent = $this->getApplicationEvent(); $applicationEvent->setName(self::EVENT_SYSTEM_SHUTDOWN); $this->emit($applicationEvent); exit((int)$this->isError()); }
Shutdown application lifecycle @return void
entailment
public function map($name, $callback, array $arguments = []) { $command = new Command($name, $callback, $arguments); $this->commands[$name] = $command; return $command; }
Map first argument to callback - callable - [class, method], including __invoke Argument matching full integrated from climate http://climate.thephpleague.com/arguments/ @param $name @param $callback @param array $arguments @return Command
entailment
public function handle(array $args = []) { // remove source file name from argv $source = array_shift($args); /** @var ConsoleEvent $applicationEvent */ $applicationEvent = $this->getApplicationEvent(); $applicationEvent->setName(self::EVENT_REQUEST_RECEIVED); $applicationEvent->setSourceFile($source); $applicationEvent->setArguments($args); $this->emit($applicationEvent); // init dispatcher $dispatcher = new Dispatcher($this->commands, $this->container); $middlewareRunner = new MiddlewareRunner($this->getMiddlewares()); $middlewareRunner->run([$applicationEvent->getArguments()], function ($args) use ($applicationEvent, $dispatcher) { // dispatch command with args from cli $dispatcher->dispatch($args); }); }
Dispatch command from given args @param array $args
entailment
public function run(array $argv = null) { // If no $argv is provided then use the global PHP defined $argv. if (is_null($argv)) { global $argv; } // handle call $this->handle($argv); // exit cli with code 0 or even 1 for error $this->shutdown(); }
execute console lifecycle @param array|null $argv
entailment
public function setup(Model $model, $settings = array()) { if ($settings) { foreach ($settings as $field => $options) { $this->settings[$model->alias][$field] = (array) $options + array('required' => true); } } }
Setup the validation and model settings. @param Model $model @param array $settings
entailment
public function filesize(Model $model, $data, $size = 5242880) { return $this->_validate($model, $data, 'size', array($size)); }
Validates an image file size. Default max size is 5 MB. @param Model $model @param array $data @param int $size @return bool
entailment
public function height(Model $model, $data, $size) { return $this->_validate($model, $data, 'height', array($size)); }
Checks that the image height is exact. @param Model $model @param array $data @param int $size @return bool
entailment
public function width(Model $model, $data, $size) { return $this->_validate($model, $data, 'width', array($size)); }
Checks that the image width is exact. @param Model $model @param array $data @param int $size @return bool
entailment
public function maxHeight(Model $model, $data, $size) { return $this->_validate($model, $data, 'maxHeight', array($size)); }
Checks the maximum image height. @param Model $model @param array $data @param int $size @return bool
entailment
public function maxWidth(Model $model, $data, $size) { return $this->_validate($model, $data, 'maxWidth', array($size)); }
Checks the maximum image width. @param Model $model @param array $data @param int $size @return bool
entailment
public function minHeight(Model $model, $data, $size) { return $this->_validate($model, $data, 'minHeight', array($size)); }
Checks the minimum image height. @param Model $model @param array $data @param int $size @return bool
entailment
public function minWidth(Model $model, $data, $size) { return $this->_validate($model, $data, 'minWidth', array($size)); }
Checks the minimum image width. @param Model $model @param array $data @param int $size @return bool
entailment
public function extension(Model $model, $data, array $allowed = array()) { return $this->_validate($model, $data, 'ext', array($allowed)); }
Validates the extension. @param Model $model @param array $data @param array $allowed @return bool
entailment
public function type(Model $model, $data, array $allowed = array()) { return $this->_validate($model, $data, 'type', array($allowed)); }
Validates the type, e.g., image. @param Model $model @param array $data @param array $allowed @return bool
entailment
public function mimeType(Model $model, $data, $mimeType) { return $this->_validate($model, $data, 'mimeType', array($mimeType)); }
Validates the mime type, e.g., image/jpeg. @param Model $model @param array $data @param array|string $mimeType @return bool
entailment
public function required(Model $model, $data, $required = true) { foreach ($data as $value) { if ($required && $this->_isEmpty($value)) { return false; } } return true; }
Makes sure a file field is required and not optional. @param Model $model @param array $data @param bool $required @return bool
entailment
public function beforeValidate(Model $model, $options = array()) { if (empty($this->settings[$model->alias])) { return true; } foreach ($this->settings[$model->alias] as $field => $rules) { $validations = array(); foreach ($rules as $rule => $setting) { $set = $this->_defaults[$rule]; // Parse out values if (!is_array($setting) || !isset($setting['value'])) { $setting = array('value' => $setting); } switch ($rule) { case 'required': $arg = (bool) $setting['value']; break; case 'type': case 'mimeType': case 'extension': $arg = (array) $setting['value']; break; default: $arg = (int) $setting['value']; break; } if (!isset($setting['rule'])) { $setting['rule'] = array($rule, $arg); } if (isset($setting['error'])) { $setting['message'] = $setting['error']; unset($setting['error']); } unset($setting['value']); // Merge settings $set = array_merge($set, $setting); // Apply validations if (is_array($arg)) { $arg = implode(', ', $arg); } $set['message'] = __d('uploader', $set['message'], $arg); $validations[$rule] = $set; } if ($validations) { if (!empty($model->validate[$field])) { $currentRules = $model->validate[$field]; // Fix single rule validate if (isset($currentRules['rule'])) { $currentRules = array( $currentRules['rule'] => $currentRules ); } $validations = $currentRules + $validations; } // Remove notEmpty for uploads if (isset($model->data[$model->alias][$field]['tmp_name']) && isset($validations['notEmpty'])) { unset($validations['notEmpty']); } $this->_validations[$field] = $validations; $model->validate[$field] = $validations; } } return true; }
Build the validation rules and validate. @param Model $model @param array $options @return bool
entailment
public function afterValidate(Model $model) { if (!empty($this->_tempFiles)) { foreach ($this->_tempFiles as $file) { $file->delete(); } $this->_tempFiles = array(); } return true; }
Delete the temporary file. @param Model $model @return bool
entailment
protected function _allowEmpty(Model $model, $field, $value) { if (isset($this->_validations[$field]['required'])) { $rule = $this->_validations[$field]['required']; $required = isset($rule['rule'][1]) ? $rule['rule'][1] : true; if ($this->_isEmpty($value)) { if ($rule['allowEmpty']) { return true; } else if ($required) { return false; } } } return false; }
Allow empty file uploads to circumvent file validations. @param Model $model @param string $field @param array $value @return bool
entailment
protected function _validate(Model $model, $data, $method, array $params) { foreach ($data as $field => $value) { if ($this->_allowEmpty($model, $field, $value)) { return true; } else if ($this->_isEmpty($value)) { return false; } $file = null; // Upload, use temp file if (is_array($value)) { $file = new File($value); // Import, copy file for validation } else if (!empty($value)) { $target = md5($value); $transit = new Transit($value); $transit->setDirectory(TMP); // Already imported from previous validation if (isset($this->_tempFiles[$target])) { $file = $this->_tempFiles[$target]; // Local file } else if (file_exists($value)) { if ($transit->importFromLocal()) { $file = $transit->getOriginalFile(); $file->rename($target); } // Attempt to copy from remote } else if (preg_match('/^http/i', $value)) { if ($transit->importFromRemote()) { $file = $transit->getOriginalFile(); $file->rename($target); } // Or from stream } else { if ($transit->importFromStream()) { $file = $transit->getOriginalFile(); $file->rename($target); } } // Save temp so we can delete later if ($file && !isset($this->_tempFiles[$target])) { $this->_tempFiles[$target] = $file; } } if (!$file) { $this->log(sprintf('Invalid upload or import for validation: %s', json_encode($value)), LOG_DEBUG); return false; } $validator = new ImageValidator(); $validator->setFile($file); return call_user_func_array(array($validator, $method), $params); } return false; }
Validate the field against the validation rules. @uses Transit\Transit @uses Transit\File @uses Transit\Validator\ImageValidator @param Model $model @param array $data @param string $method @param array $params @return bool @throws UnexpectedValueException
entailment
public function setContainer(ContainerInterface $container) { $application = $this; $container->share(ApplicationInterface::class, $application); $container->share(\Interop\Container\ContainerInterface::class, $container); $this->container = $container; return $this; }
Set a container. @param \League\Container\ContainerInterface $container @return $this
entailment
public function getConfigurator() { if (!$this->getContainer()->has(Configuration::class)) { $this->getContainer()->share(Configuration::class, (new Configuration([], true))); } return $this->getContainer()->get(Configuration::class); }
Get configuration container @return \Hawkbit\Configuration
entailment
public function setConfig($key, $value = null) { $configurator = $this->getConfigurator(); if(!is_scalar($key)){ $configuratorClass = get_class($configurator); $configurator->merge(new $configuratorClass($key, true)); }else{ $configurator[$key] = $value; } return $this; }
Set a config item. Add recursive if key is traversable. @param string|array|\Traversable $key @param mixed $value @return $this
entailment
public function getConfig($key = null, $default = null) { $configurator = $this->getConfigurator(); if (null === $key) { return $configurator; } return $configurator->get($key, $default); }
Get a config key's value @param string $key @param mixed $default @return mixed
entailment
public function getEventEmitter() { if (!$this->getContainer()->has(EmitterInterface::class)) { $this->getContainer()->share(EmitterInterface::class, new Emitter()); } /** @var EmitterInterface $validateContract */ $validateContract = $this->validateContract($this->getContainer()->get(EmitterInterface::class), EmitterInterface::class); return $validateContract; }
Return the event emitter. @return \League\Event\Emitter|\League\Event\EmitterInterface
entailment
public function getLogger($channel = 'default') { if (isset($this->loggers[$channel])) { return $this->loggers[$channel]; } /** @var Logger $logger */ $logger = $this->getContainer()->get(LoggerInterface::class, [$channel]); $this->loggers[$channel] = $logger; /** @var LoggerInterface $contract */ $contract = $this->validateContract($this->loggers[$channel], LoggerInterface::class); return $contract; }
Return a logger @param string $channel @return \Psr\Log\LoggerInterface
entailment
public function validateContract($class, $contract) { $validateObject = function ($object) { //does need trigger when calling *_exists with object $condition = is_string($object) ? class_exists($object) || interface_exists($object) : is_object($object); if (false === $condition) { $this->throwException(new \InvalidArgumentException('Class not exists ' . $object)); } }; $convertClassToString = function ($object) { if (is_object($object)) { $object = get_class($object); } return is_string($object) ? $object : false; }; $validateObject($class); $validateObject($contract); if (!($class instanceof $contract)) { if (is_object($class)) { $class = get_class($class); } $this->throwException(new \LogicException($convertClassToString($class) . ' needs to be an instance of ' . $convertClassToString($contract))); } return $class; }
Validates that class is instance of contract @param $class @param $contract @return string|object @throws \InvalidArgumentException|\LogicException
entailment
protected function bindClosureToInstance($closure, $instance) { if ($closure instanceof \Closure) { $closure = $closure->bind($closure, $instance, get_class($instance)); } return $closure; }
Bind any closure to application instance @param $closure @param $instance @return mixed
entailment
public function setup(Model $model, $settings = array()) { if (!$settings) { return; } if (!isset($this->_columns[$model->alias])) { $this->_columns[$model->alias] = array(); } foreach ($settings as $field => $attachment) { $attachment = Set::merge($this->_defaultSettings, $attachment + array( 'dbColumn' => $field )); // Fix dbColumn if they set it to empty if (!$attachment['dbColumn']) { $attachment['dbColumn'] = $field; } $columns = array($attachment['dbColumn'] => $field); // Set defaults if not defined if (!$attachment['tempDir']) { $attachment['tempDir'] = TMP; } if (!$attachment['uploadDir']) { $attachment['finalPath'] = $attachment['finalPath'] ?: '/files/uploads/'; $attachment['uploadDir'] = WWW_ROOT . $attachment['finalPath']; } // Merge transform settings with defaults if ($attachment['transforms']) { foreach ($attachment['transforms'] as $dbColumn => $transform) { $transform = Set::merge($this->_transformSettings, $transform + array( 'uploadDir' => $attachment['uploadDir'], 'finalPath' => $attachment['finalPath'], 'dbColumn' => $dbColumn )); if ($transform['self']) { $transform['dbColumn'] = $attachment['dbColumn']; } $columns[$transform['dbColumn']] = $field; $attachment['transforms'][$dbColumn] = $transform; } } $this->settings[$model->alias][$field] = $attachment; $this->_columns[$model->alias] += $columns; } }
Save attachment settings. @param Model $model @param array $settings
entailment
public function cleanup(Model $model) { parent::cleanup($model); $this->_uploads = array(); $this->_columns = array(); }
Cleanup and reset the behavior when its detached. @param Model $model @return void
entailment
public function afterFind(Model $model, $results, $primary=false) { $alias = $model->alias; foreach ($results as $i => $data) { if (empty($data[$alias])) { continue; } foreach ($data[$alias] as $field => $value) { if (empty($this->settings[$alias][$field]) || !empty($value)) { continue; } $attachment = $this->_settingsCallback($model, $this->settings[$alias][$field]); if ($attachment['defaultPath']) { $results[$i][$alias][$attachment['dbColumn']] = $attachment['defaultPath']; } if ($attachment['transforms']) { foreach ($attachment['transforms'] as $transform) { if ($transform['defaultPath']) { $results[$i][$alias][$transform['dbColumn']] = $transform['defaultPath']; } } } } } return $results; }
After a find, replace any empty fields with the default path. @param Model $model @param array $results @param bool $primary @return array
entailment
public function beforeDelete(Model $model, $cascade = true) { if (empty($model->id)) { return false; } return $this->deleteFiles($model, $model->id, array(), true); }
Deletes any files that have been attached to this model. @param Model $model @param bool $cascade @return bool
entailment
public function beforeSave(Model $model, $options = array()) { $alias = $model->alias; if (empty($model->data[$alias])) { return true; } // Loop through the data and upload the file foreach ($model->data[$alias] as $field => $file) { if (empty($this->settings[$alias][$field])) { continue; } // Gather attachment settings $attachment = $this->_settingsCallback($model, $this->settings[$alias][$field]); $data = array(); // Initialize Transit $transit = new Transit($file); $transit->setDirectory($attachment['tempDir']); $this->_uploads[$alias] = $transit; // Set transformers and transporter $this->_addTransformers($model, $transit, $attachment); $this->_setTransporter($model, $transit, $attachment); // Attempt upload or import try { $overwrite = $attachment['overwrite']; $response = null; // File upload if (is_array($file)) { $response = $transit->upload($overwrite); // Remote import } else if (preg_match('/^http/i', $file)) { $response = $transit->importFromRemote($overwrite, $attachment['curl']); // Local import } else if (file_exists($file)) { $response = $transit->importFromLocal($overwrite); // Stream import } else if (!empty($file)) { $response = $transit->importFromStream($overwrite); } // Successful upload or import if ($response) { $dbColumnMap = array($attachment['dbColumn']); $transportConfig = array($this->_prepareTransport($attachment)); // Rename and move file $data[$attachment['dbColumn']] = $this->_renameAndMove($model, $transit->getOriginalFile(), $attachment); // Fetch exif data before transforming $metaData = array(); foreach ($transit->getOriginalFile()->toArray() as $key => $value) { if (substr($key, 0, 4) === 'exif' && $value) { $metaData[$key] = $value; } } // Transform the files and save their path if ($attachment['transforms']) { $transit->transform(); $transformedFiles = $transit->getTransformedFiles(); $count = 0; foreach ($attachment['transforms'] as $transform) { if ($transform['self']) { $tempFile = $transit->getOriginalFile(); $dbColumnMap[0] = $transform['dbColumn']; } else { $tempFile = $transformedFiles[$count]; $dbColumnMap[] = $transform['dbColumn']; $count++; $transportConfig[] = $this->_prepareTransport($transform); } $data[$transform['dbColumn']] = $this->_renameAndMove($model, $tempFile, $transform); } } $metaData = array_merge($transit->getOriginalFile()->toArray(), $metaData); // Transport the files and save their remote path if ($attachment['transport']) { if ($transportedFiles = $transit->transport($transportConfig)) { foreach ($transportedFiles as $i => $transportedFile) { $data[$dbColumnMap[$i]] = $transportedFile; } } } } // Trigger form errors if validation fails } catch (ValidationException $e) { $dbColumns = array_merge(array($attachment['dbColumn']), array_keys($attachment['transforms'])); foreach ($dbColumns as $dbCol) { unset($model->data[$alias][$dbCol]); } // Allow empty uploads if ($attachment['allowEmpty']) { continue; } // Invalidate and stop $model->invalidate($field, __d('uploader', $e->getMessage())); if ($attachment['stopSave']) { return false; } // Log exceptions that shouldn't be shown to the client } catch (Exception $e) { $model->invalidate($field, __d('uploader', $e->getMessage())); $this->log($e->getMessage(), LOG_DEBUG); // Rollback the files since it threw errors $transit->rollback(); if ($attachment['stopSave']) { return false; } } // Save file meta data $cleanup = $data; if ($attachment['metaColumns'] && $data && !empty($metaData)) { foreach ($attachment['metaColumns'] as $method => $column) { if (isset($metaData[$method]) && $column) { $data[$column] = $metaData[$method]; } } } // Merge upload data with model data if ($data) { $model->data[$alias] = $data + $model->data[$alias]; } // Keep it in a loop, so it will delete all files // If we are doing an update, delete the previous files that are being replaced if ($model->id && $cleanup) { $this->_cleanupOldFiles($model, $cleanup); } } return true; }
Before saving the data, try uploading the file, if successful save to database. @uses Transit\Transit @param Model $model @param array $options @return bool
entailment
public function deleteFiles(Model $model, $id, array $filter = array(), $isDelete = false) { $columns = $this->_columns[$model->alias]; $data = $this->_doFind($model, array($model->alias . '.' . $model->primaryKey => $id)); if (empty($data[$model->alias])) { return false; } // Set data in case $this->data is used in callbacks $model->set($data); $save = array(); foreach ($data[$model->alias] as $column => $value) { if (empty($columns[$column]) || empty($value)) { continue; } else if ($filter && !in_array($column, $filter)) { continue; } if ($this->_deleteFile($model, $columns[$column], $value, $column)) { $save[$column] = ''; // Reset meta data also foreach ($this->settings[$model->alias][$columns[$column]]['metaColumns'] as $metaKey => $fieldKey) { $save[$fieldKey] = ''; } } } // Set the fields to empty if ($save && !$isDelete) { $model->id = $id; $model->save($save, array( 'validate' => false, 'callbacks' => false, 'fieldList' => array_keys($save) )); } return true; }
Delete all files associated with a record but do not delete the record. @param Model $model @param int $id @param array $filter @param bool $isDelete @return bool
entailment
public function getUploadedFile(Model $model) { if (isset($this->_uploads[$model->alias])) { return $this->_uploads[$model->alias]->getOriginalFile(); } return null; }
Return the uploaded original File object. @param Model $model @return \Transit\File
entailment
public function getTransformedFiles(Model $model) { if (isset($this->_uploads[$model->alias])) { return $this->_uploads[$model->alias]->getTransformedFiles(); } return array(); }
Return the transformed File objects. @param Model $model @return \Transit\File[]
entailment
protected function _settingsCallback(Model $model, array $options) { if (method_exists($model, 'beforeUpload')) { $options = $model->beforeUpload($options); } if ($options['transforms'] && method_exists($model, 'beforeTransform')) { foreach ($options['transforms'] as $i => $transform) { $options['transforms'][$i] = $model->beforeTransform($transform); } } if ($options['transport'] && method_exists($model, 'beforeTransport')) { $options['transport'] = $model->beforeTransport($options['transport']); } return $options; }
Trigger callback methods to modify attachment settings before uploading. @param Model $model @param array $options @return array
entailment
protected function _addTransformers(Model $model, Transit $transit, array $attachment) { if (empty($attachment['transforms'])) { return; } foreach ($attachment['transforms'] as $options) { $transformer = $this->_getTransformer($attachment, $options); if ($options['self']) { $transit->addSelfTransformer($transformer); } else { $transit->addTransformer($transformer); } } }
Add Transit Transformers based on the attachment settings. @param Model $model @param \Transit\Transit $transit @param array $attachment
entailment
protected function _setTransporter(Model $model, Transit $transit, array $attachment) { if (empty($attachment['transport'])) { return; } $transit->setTransporter($this->_getTransporter($attachment, $attachment['transport'])); }
Set the Transit Transporter to use based on the attachment settings. @param Model $model @param \Transit\Transit $transit @param array $attachment
entailment
protected function _getTransformer(array $attachment, array $options) { $class = isset($options['method']) ? $options['method'] : $options['class']; switch ($class) { case self::CROP: return new CropTransformer($options); break; case self::FLIP: return new FlipTransformer($options); break; case self::RESIZE: return new ResizeTransformer($options); break; case self::SCALE: return new ScaleTransformer($options); break; case self::ROTATE: return new RotateTransformer($options); break; case self::EXIF: return new ExifTransformer($options); break; case self::FIT: return new FitTransformer($options); break; default: if (isset($attachment['transformers'][$class])) { return new $attachment['transformers'][$class]($options); } break; } throw new InvalidArgumentException(sprintf('Invalid transform class %s', $class)); }
Return a Transformer based on the options. @uses Transit\Transformer\Image\CropTransformer @uses Transit\Transformer\Image\FlipTransformer @uses Transit\Transformer\Image\ResizeTransformer @uses Transit\Transformer\Image\ScaleTransformer @uses Transit\Transformer\Image\RotateTransformer @uses Transit\Transformer\Image\ExifTransformer @uses Transit\Transformer\Image\FitTransformer @param array $attachment @param array $options @return \Transit\Transformer @throws \InvalidArgumentException
entailment
protected function _getTransporter(array $attachment, array $options) { $class = $options['class']; switch ($class) { case self::S3: return new S3Transporter($options['accessKey'], $options['secretKey'], $options); break; case self::GLACIER: return new GlacierTransporter($options['accessKey'], $options['secretKey'], $options); break; case self::CLOUD_FILES: return new CloudFilesTransporter($options['username'], $options['apiKey'], $options); break; default: if (isset($attachment['transporters'][$class])) { return new $attachment['transporters'][$class]($options); } break; } throw new InvalidArgumentException(sprintf('Invalid transport class %s', $class)); }
Return a Transporter based on the options. @uses Transit\Transporter\Aws\S3Transporter @uses Transit\Transporter\Aws\GlacierTransporter @param array $attachment @param array $options @return \Transit\Transporter @throws \InvalidArgumentException
entailment
protected function _renameAndMove(Model $model, File $file, array $options) { $nameCallback = null; if ($options['nameCallback'] && method_exists($model, $options['nameCallback'])) { $nameCallback = array($model, $options['nameCallback']); } if ($options['uploadDir']) { $file->move($options['uploadDir'], $options['overwrite']); } $file->rename($nameCallback, $options['append'], $options['prepend'], $options['overwrite']); return (string) $options['finalPath'] . $file->basename(); }
Rename or move the file and return its relative path. @param Model $model @param \Transit\File $file @param array $options @return string
entailment
protected function _doFind(Model $model, array $where, $type = 'first') { $virtual = $model->virtualFields; $model->virtualFields = array(); $results = $model->find($type, array( 'conditions' => $where, 'contain' => false, 'recursive' => -1, 'order' => '' )); $model->virtualFields = $virtual; return $results; }
Trigger a find() call but disable virtual fields before doing so. @param Model $model @param array $where @param string $type @return array
entailment
protected function _deleteFile(Model $model, $field, $path, $column) { if (empty($this->settings[$model->alias][$field])) { return false; } $attachment = $this->_settingsCallback($model, $this->settings[$model->alias][$field]); $basePath = $attachment['uploadDir'] ?: $attachment['tempDir']; // Get uploadDir from transform if ($attachment['transforms']) { foreach ($attachment['transforms'] as $transform) { if ($transform['dbColumn'] === $column) { $basePath = $transform['uploadDir']; } } } try { // Delete remote file if ($attachment['transport']) { $transporter = $this->_getTransporter($attachment, $attachment['transport']); return $transporter->delete($path); // Delete local file } else { $file = new File($basePath . basename($path)); return $file->delete(); } } catch (Exception $e) { $this->log($e->getMessage(), LOG_DEBUG); } return false; }
Attempt to delete a file using the attachment settings. @uses Transit\File @param Model $model @param string $field @param string $path @param string $column @return bool
entailment
protected function _cleanupOldFiles(Model $model, array $fields) { $columns = $this->_columns[$model->alias]; $data = $this->_doFind($model, array($model->alias . '.' . $model->primaryKey => $model->id)); if (empty($data[$model->alias])) { return; } foreach ($fields as $column => $value) { if (empty($data[$model->alias][$column])) { continue; } if (!empty($this->settings[$model->alias][$columns[$column]])) { $attachment = $this->_settingsCallback($model, $this->settings[$model->alias][$columns[$column]]); if (!$attachment['cleanup']) { continue; } } // Delete if previous value doesn't match new value $previous = $data[$model->alias][$column]; if ($previous !== $value) { $this->_deleteFile($model, $columns[$column], $previous, $column); } } }
Delete previous files if a record is being overwritten. @param Model $model @param array $fields @return void
entailment
protected function _prepareTransport(array $settings) { $config = array(); if (!empty($settings['transportDir'])) { $config['folder'] = $settings['transportDir']; } if (!empty($settings['returnUrl'])) { $config['returnUrl'] = $settings['returnUrl']; } return $config; }
Prepare transport configuration. @param array $settings @return array
entailment
public function getErrorMessage($exception) { $application = $this->application; $errorHandler = $this->runner; // quit if error occured $shouldQuit = $application->isError(); // if($application instanceof Application){ // if request type ist not strict e.g. xml or json consider error config if (!$application->isXmlRequest() && !$application->isJsonRequest()) { $shouldQuit = $shouldQuit && $application->getConfig(ApplicationInterface::KEY_ERROR, ApplicationInterface::DEFAULT_ERROR); } } $errorHandler->allowQuit($shouldQuit); $method = $errorHandler::EXCEPTION_HANDLER; ob_start(); $errorHandler->$method($exception); $message = ob_get_clean(); return $message; }
Determine error message by error configuration @param \Throwable|\Exception $exception @return string
entailment
public function decorateException($error) { $application = $this->application; if (is_callable($error)) { $error = $application->getContainer()->call($error, [$application]); } if (is_object($error) && !($error instanceof \Exception)) { $error = method_exists($error, '__toString') ? $error->__toString() : 'Error with object ' . get_class($error); } if (is_resource($error)) { $error = 'Error with resource type ' . get_resource_type($error); } if (is_array($error)) { $error = implode("\n", $error); } if (!($error instanceof \Exception)) { $error = new \Exception(is_scalar($error) ? $error : 'Error with ' . gettype($error)); } return $error; }
Convert any type into an exception @param $error @return \Exception|string
entailment
public function connect(array $servers) { $memcache = $this->getMemcache(); // For each server in the array, we'll just extract the configuration and add // the server to the Memcached connection. Once we have added all of these // servers we'll verify the connection is successful and return it back. foreach ($servers as $server) { $memcache->addServer( $server['host'], $server['port'], $server['weight'] ); } if ($memcache->getVersion() === false) { throw new RuntimeException("Could not establish Memcache connection."); } return $memcache; }
Create a new Memcache connection. @param array $servers @return \Memcache @throws \RuntimeException
entailment
public function run(array $args = [], callable $final = null, callable $fail = null) { $result = null; // declare default final middleware if (!is_callable($final)) { $final = function ($command) { return $command; }; } // declare default error middleware if (!is_callable($fail)) { $fail = function ($exception) { throw $exception; }; } try { $result = $this->handle($args, $final); } catch (\Exception $exception) { $result = $this->handleError($args, $fail, $exception, $result); } return $result; }
Execute middlewares @param callable $final @param callable|null $fail @param array $args Arguments for middleware @return mixed
entailment
public function resolve($middlewares) { $last = function ($request, $response) { // no op }; while ($middleware = array_pop($middlewares)) { if (is_object($middleware)) { if (method_exists($middleware, '__invoke')) { $middleware = [$middleware, '__invoke']; } } if (!is_callable($middleware)) { throw new \InvalidArgumentException('Middle needs to be callable'); } $last = function () use ($middleware, $last) { $args = func_get_args(); $args[] = $last; return call_user_func_array($middleware, $args); }; } return $last; }
Resolve middleware queue @param $middlewares @return \Closure
entailment
public function isAttributeChanged($name, $identical = true) { if (parent::isAttributeChanged($name, $identical) === true) { return true; } $attributeName = $this->getTranslateAttributeName($name); return $this->getTranslation()->isAttributeChanged($attributeName, $identical); }
Returns a value indicating whether the named attribute has been changed or attribute has been changed in translation relation model. @param string $name the name of the attribute. @param boolean $identical whether the comparison of new and old value is made for identical values using `===`, defaults to `true`. Otherwise `==` is used for comparison. @return boolean whether the attribute has been changed
entailment
public function dispatch($argv){ $name = reset($argv); if(!$this->hasCommand($name)){ throw new \InvalidArgumentException('Command not found'); } // load command $command = $this->commands[$name]; // parse arguments $arguments = $command->getArguments(); $arguments->parse($argv); // execute command $handler = $command->getHandler(); if(is_array($handler)){ $class = $handler[0]; // if($this->container->has($class)){ // $this->container->add($class); // } $obj = $this->container->get($class); $handler[0] = $obj; } call_user_func_array($handler, [$arguments]); }
Dispatch handler for given command @param $argv
entailment
public function wrap($callable, $params = []) { $kernel = new ClosureHttpKernel(); if (is_callable($callable)) { $middleware = $callable($kernel); } else { // Add kernel as 'app' parameter $params = ['app' => $kernel] + $params; $makeMethod = method_exists($this->container, 'makeWith') ? 'makeWith' : 'make'; $middleware = $this->container->$makeMethod($callable, $params); } if ($middleware instanceof TerminableInterface) { return new TerminableClosureMiddleware($kernel, $middleware); } return new ClosureMiddleware($kernel, $middleware); }
Wrap the StackPHP Middleware in a Laravel Middleware. @param callable|string $callable @param array $params @return ClosureMiddleware
entailment
public function request($method, $params = []) { $response = $this->client->post($this->getUrl($method), ['query' => $params]); if ($response->getStatusCode() === 200) { return (string)$response->getBody(); } else { throw new Exception(sprintf('Sms.ru problem. Status code is %s', $response->getStatusCode()), $response->getStatusCode()); } }
@param string $method @param array $params @return string @throws Exception
entailment
private function mkdir($path, $mode = 0775, $recursive = true) { if (is_dir($path)) { return true; } $parentDir = dirname($path); // recurse if parent dir does not exist and we are not at the root of the file system. if ($recursive && !is_dir($parentDir) && $parentDir !== $path) { $this->mkdir($parentDir, $mode, true); } try { if (!mkdir($path, $mode)) { return false; } } catch (\Exception $e) { if (!is_dir($path)) { throw new Exception(sprintf('Failed to create directory "%s": %s', $path, $e->getMessage()), $e->getCode(), $e); } } try { return chmod($path, $mode); } catch (\Exception $e) { throw new Exception(sprintf('Failed to change permissions for directory "%s": %s', $path, $e->getMessage()), $e->getCode(), $e); } }
@param string $path @param integer $mode @param bool $recursive @return bool @throws Exception
entailment
public function getRouter() { if (!isset($this->router)) { $container = clone $this->getContainer(); $container->delegate(new ReflectionContainer); $this->router = (new RouteCollection($container)); } /** @var RouteCollection $router */ $router = $this->validateContract($this->router, RouteCollection::class); return $router; }
Return the router. @return \League\Route\RouteCollection
entailment
public function getRequest() { if (!$this->getContainer()->has(ServerRequestInterface::class)) { $this->getContainer()->share(ServerRequestInterface::class,function(){ $beforeIndexPosition = strpos($_SERVER['PHP_SELF'],'/index.php'); /** * If there is some string before /index.php then remove this string from REQUEST_URI */ if(false !== $beforeIndexPosition && $beforeIndexPosition > 0){ $scriptUrl = substr($_SERVER['PHP_SELF'],0,$beforeIndexPosition); $_SERVER['REQUEST_URI'] = str_replace(['/index.php',$scriptUrl],'',$_SERVER['REQUEST_URI']); } return ServerRequestFactory::fromGlobals()->withHeader('content-type', $this->getContentType()); }); } /** @var ServerRequestInterface $request */ $request = $this->validateContract($this->getContainer()->get(ServerRequestInterface::class), ServerRequestInterface::class); return $request; }
Get the request @return \Psr\Http\Message\ServerRequestInterface
entailment
public function getResponse($content = '') { //transform content by content type if ($this->isJsonRequest()) { if ($content instanceof Response\JsonResponse) { $content = json_decode($content->getBody()); } elseif (!is_array($content)) { $content = [$content]; } } else { if (is_array($content)) { $content = implode('', $content); } elseif ($content instanceof ResponseInterface) { $content = $content->getBody()->__toString(); } } if (!$this->getContainer()->has(ResponseInterface::class)) { if ($this->isCli()) { $class = Response\TextResponse::class; } elseif ($this->isJsonRequest()) { $class = Response\JsonResponse::class; } else { $class = Response\HtmlResponse::class; } $this->getContainer()->add(ResponseInterface::class, $class); } /** @var ResponseInterface $response */ $response = $this->validateContract($this->getContainer()->get(ResponseInterface::class, [$content]), ResponseInterface::class); //inject request content type $request = $this->getRequest(); $contentTypeKey = 'content-type'; foreach ($request->getHeader($contentTypeKey) as $contentType) { $response = $response->withHeader($contentTypeKey, $contentType); } return $response; }
Get the response @param string $content @return \Psr\Http\Message\ResponseInterface
entailment
public function getResponseEmitter() { if (!$this->getContainer()->has(Response\EmitterInterface::class)) { $this->getContainer()->share(Response\EmitterInterface::class, new Response\SapiEmitter()); } /** @var Response\EmitterInterface $contract */ $contract = $this->validateContract($this->getContainer()->get(Response\EmitterInterface::class), Response\EmitterInterface::class); return $contract; }
Get response emitter @return \Zend\Diactoros\Response\EmitterInterface
entailment
public function isAjaxRequest() { return false !== strpos( strtolower(ServerRequestFactory::getHeader('x-requested-with', $this->getRequest()->getHeaders(), '')), 'xmlhttprequest' ) && $this->isHttpRequest(); }
Check if request is a ajax request @return bool
entailment
public function map($method, $route, $action) { return $this->getRouter()->map($method, $route, $this->bindClosureToInstance($action, $this)); }
Add a route to the map. @param $method @param $route @param $action @return \League\Route\Route
entailment
public function group($prefix, callable $group) { return $this->getRouter()->group($prefix, $this->bindClosureToInstance($group, $this)); }
Add a group of routes to the collection. Binds $this to app instance @param $prefix @param callable $group @return \League\Route\RouteGroup
entailment
public function handle( ServerRequestInterface $request, ResponseInterface $response = null, $catch = self::DEFAULT_ERROR_CATCH ) { /** @var ResponseInterface $response */ // Passes the request to the container if (!$this->getContainer()->has(ServerRequestInterface::class)) { $this->getContainer()->share(ServerRequestInterface::class, $request); } //inject request content type $contentType = ServerRequestFactory::getHeader('content-type', $this->getRequest()->getHeaders(), ''); $this->setContentType($contentType); if ($response === null) { $response = $this->getResponse(); } $applicationEvent = $this->getApplicationEvent(); $applicationEvent->setRequest($request); $applicationEvent->setResponse($response); try { $response = $this->handleResponse($this->handleRequest($request), $response); }catch (\Exception $exception){ $notFoundException = $exception instanceof NotFoundException; $response = $this->handleError($exception, $request, $response, $catch) ->withStatus($notFoundException ? 404 : 500); } // validate response $response = $this->validateContract($response, ResponseInterface::class); // update content type $this->setContentType(ServerRequestFactory::getHeader('content-type', $response->getHeaders(), '')); return $response; }
Convert request into response. If an error occurs, Hawkbit tries to handle error as response. @param ServerRequestInterface $request @param ResponseInterface $response @param bool $catch @return ResponseInterface @throws \Throwable
entailment
public function handleRequest(ServerRequestInterface $request) { $applicationEvent = $this->getApplicationEvent(); $applicationEvent->setName(self::EVENT_REQUEST_RECEIVED); $this->emit($applicationEvent, $request); return $applicationEvent->getRequest(); }
Convert request into response. @param ServerRequestInterface $request @return ServerRequestInterface
entailment
public function handleResponse(ServerRequestInterface $request, ResponseInterface $response) { $applicationEvent = $this->getApplicationEvent(); $applicationEvent->setName(self::EVENT_RESPONSE_CREATED); $applicationEvent->setResponse($this->getRouter()->dispatch( $request, $response )); $this->emit($applicationEvent, $request, $response); return $applicationEvent->getResponse(); }
Handle Response @param ServerRequestInterface $request @param ResponseInterface $response @return ResponseInterface
entailment
public function handleError( $exception, ServerRequestInterface $request, ResponseInterface $response, $catch = self::DEFAULT_ERROR_CATCH ) { // notify app that an error occurs $this->error = true; $errorHandler = $this->getErrorHandler(); // if delivered value of $catch, then configured value, then default value $catch = self::DEFAULT_ERROR_CATCH !== $catch ? $catch : $this->getConfig(self::KEY_ERROR_CATCH, $catch); $showError = $this->getConfig(self::KEY_ERROR, static::DEFAULT_ERROR); $this->pushException($errorHandler->decorateException($exception)); //execute application middlewares try { $middlewares = $this->getRouter()->getMiddlewareStack(); $middlewareRunner = new ExecutionChain(); foreach ($middlewares as $middleware) { $middlewareRunner->middleware($middleware); } $response = $middlewareRunner->execute($request, $response); }catch (\Exception $e){ $this->pushException($e); } // get last occured exception $exception = $this->getLastException(); $message = $errorHandler->getErrorMessage($exception); $errorResponse = $this->determineErrorResponse($exception, $message, $response, $request); if ( false === $catch && true === $showError ) { $this->throwException($exception); } return $errorResponse; }
Handle error and return response of error message or throw error if error.catch is disabled. @param \Throwable|\Exception $exception @param \Psr\Http\Message\ServerRequestInterface $request @param ResponseInterface $response @param bool $catch @return \Psr\Http\Message\ResponseInterface @throws string
entailment
public function run(ServerRequestInterface $request = null, ResponseInterface $response = null) { if ($request === null) { $request = $this->getRequest(); } $response = $this->handle($request, $response); $this->emitResponse($request, $response); if ($this->canTerminate()) { $this->terminate($request, $response); } $this->shutdown($response); return $this; }
Handle response / request lifecycle When $callable is a valid callable, callable will executed before emit response @param \Psr\Http\Message\ServerRequestInterface $request A Request instance @param \Psr\Http\Message\ResponseInterface $response A response instance @return $this
entailment
public function emitResponse(ServerRequestInterface $request, ResponseInterface $response) { try { $this->getResponseEmitter()->emit($response); } catch (\Exception $e) { if ($this->canForceResponseEmitting()) { // flush buffers $maxBufferLevel = ob_get_level(); while (ob_get_level() > $maxBufferLevel) { ob_end_flush(); } // print response echo $response->getBody(); } else { throw $e; } } $applicationEvent = $this->getApplicationEvent(); $applicationEvent->setName(self::EVENT_RESPONSE_SENT); $applicationEvent->setRequest($request); $applicationEvent->setResponse($response); $this->emit($applicationEvent); }
Emit a response @param \Psr\Http\Message\ServerRequestInterface $request @param \Psr\Http\Message\ResponseInterface $response @throws \Exception
entailment
public function terminate(ServerRequestInterface $request, ResponseInterface $response) { $applicationEvent = $this->getApplicationEvent(); $applicationEvent->setRequest($request); $applicationEvent->setResponse($response); $applicationEvent->setName(self::EVENT_LIFECYCLE_COMPLETE); $this->emit($applicationEvent); }
Terminates a request/response cycle. @param \Psr\Http\Message\ServerRequestInterface $request @param \Psr\Http\Message\ResponseInterface $response @return void
entailment
public function shutdown($response = null) { $this->collectGarbage(); $applicationEvent = $this->getApplicationEvent(); $applicationEvent->setResponse($response); $applicationEvent->setName(self::EVENT_SYSTEM_SHUTDOWN); $this->emit($applicationEvent, $this->terminateOutputBuffering(1, $response)); }
Finish request. Collect garbage and terminate output buffering @param \Psr\Http\Message\ResponseInterface $response @return void
entailment
public function terminateOutputBuffering($level = 0, $response = null) { // close response stream before terminating output buffer // and only if response is an instance of // \Psr\Http\ResponseInterface if ($response instanceof ResponseInterface) { $body = $response->getBody(); if ($body->isReadable()) { $body->close(); } } // Command line output buffering is disabled in cli by default if ($this->isCli()) { return []; } // $level needs to be a numeric value if (!is_numeric($level)) { $level = 0; } // force type casting to an integer value if (!is_int($level)) { $level = (int)$level; } // avoid infinite loop on clearing // output buffer by set level to 0 // if $level is smaller if (-1 > $level) { $level = 0; } // terminate all output buffers until $level is 0 or desired level // collect all contents and return $content = []; while (ob_get_level() > $level) { $content[] = ob_get_clean(); } return $content; }
Close response stream and terminate output buffering @param int $level @param null|\Psr\Http\Message\ResponseInterface $response @return array
entailment
private function determineErrorResponse( $exception, $message, ResponseInterface $response, ServerRequestInterface $request ) { $applicationEvent = $this->getApplicationEvent(); $applicationEvent->setName(self::EVENT_LIFECYCLE_ERROR); $applicationEvent->setRequest($request); $applicationEvent->setResponse($response); $applicationEvent->setErrorResponse($this->getResponse()); $this->emit($applicationEvent, $exception); $errorResponse = $applicationEvent->getErrorResponse(); if (!$errorResponse->getBody()->isWritable()) { return $errorResponse; } $content = $errorResponse->getBody()->__toString(); if (empty($content)) { $errorResponse->getBody()->write($message); } return $errorResponse; }
Determines response for error. Emits `lifecycle.error` event. @param \Throwable $exception @param string $message @param ResponseInterface $response @param ServerRequestInterface $request @return ResponseInterface
entailment
public function smsSend(AbstractSms $sms) { $params = []; if ($sms instanceof Sms) { $params['to'] = $sms->to; $params['text'] = $sms->text; } elseif ($sms instanceof SmsPool) { foreach ($sms->messages as $message) { $params['multi'][$message->to] = $message->text; } } else { throw new Exception('Only Sms or SmsPool instances'); } if ($sms->from) { $params['from'] = $sms->from; } if ($sms->time && $sms->time < (time() + 7 * 24 * 60 * 60)) { $params['time'] = $sms->time; } if ($sms->translit) { $params['translit'] = 1; } if ($sms->test) { $params['test'] = 1; } if ($sms->partner_id) { $params['partner_id'] = $sms->partner_id; } elseif ($this->getAuth()->getPartnerId()) { $params['partner_id'] = $this->getAuth()->getPartnerId(); } $response = $this->request('sms/send', $params); $response = explode("\n", $response); $smsResponse = new SmsResponse(array_shift($response)); if ($smsResponse->code == 100) { foreach ($response as $id) { if (!preg_match('/=/', $id)) { $smsResponse->ids[] = $id; } // else { // $result = explode('=', $id); // $response[$result[0]] = $result[1]; // } } } return $smsResponse; }
@param AbstractSms $sms @return SmsResponse @throws Exception
entailment
public function smsStatus($id) { $response = $this->request( 'sms/status', [ 'id' => $id, ] ); $response = explode("\n", $response); return new SmsStatusResponse(array_shift($response)); }
@param string $id @return SmsStatusResponse
entailment
public function smsCost(Sms $sms) { $params = [ 'to' => $sms->to, 'text' => $sms->text, ]; $response = $this->request('sms/cost', $params); $response = explode("\n", $response); $smsCostResponse = new SmsCostResponse(array_shift($response)); $smsCostResponse->price = (float)$response[0]; $smsCostResponse->length = (int)$response[1]; return $smsCostResponse; }
@param Sms $sms @return SmsCostResponse
entailment
public function stoplistAdd($stoplistPhone, $stoplistText) { $response = $this->request( 'stoplist/add', [ 'stoplist_phone' => $stoplistPhone, 'stoplist_text' => $stoplistText, ] ); $response = explode("\n", $response); return new StoplistAddResponse(array_shift($response)); }
@param string $stoplistPhone @param string $stoplistText @return StoplistAddResponse
entailment
public function stoplistDel($stoplistPhone) { $response = $this->request( 'stoplist/del', [ 'stoplist_phone' => $stoplistPhone, ] ); $response = explode("\n", $response); return new StoplistDelResponse(array_shift($response)); }
@param string $stoplistPhone @return StoplistDelResponse
entailment
public function request($method, $params = []) { return $this->getClient()->request($method, array_merge($params, $this->getAuth()->getAuthParams())); }
@param string $method @param array $params @return string
entailment
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { $closure = $this->closure; return $closure($request); }
@param Request $request A Request instance @param int $type @param bool $catch @return Response A Response instance
entailment
public function register() { $this->app->bind('dadata_suggest', function () { return new ClientSuggest(); }); $this->app->bind('dadata_clean', function () { return new ClientClean(); }); $this->mergeConfigFrom(__DIR__.'/../config/dadata.php', 'dadata'); }
Register the application services. @return void
entailment
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true) { $response = $this->getApplication()->handle($this->getDiactorosFactory()->createRequest($request), null, $catch); return $this->getHttpFoundationFactory()->createResponse($response); }
Handles a Request to convert it to a Response. Bridging between PSR-7 and Symfony HTTP When $catch is true, the implementation must catch all exceptions and do its best to convert them to a Response instance. @param Request $request A Request instance @param int $type The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST) @param bool $catch Whether to catch exceptions or not @return Response A Response instance @throws \Exception When an Exception occurs during processing
entailment
public function terminate(Request $request, Response $response) { $diactorosFactory = $this->getDiactorosFactory(); $this->getApplication()->terminate($diactorosFactory->createRequest($this->recomposeSymfonyRequest($request)), $diactorosFactory->createResponse($response)); }
Terminates a request/response cycle. Should be called after sending the response and before shutting down the kernel. @param Request $request A Request instance @param Response $response A Response instance
entailment
private function recomposeSymfonyRequest(Request $request) { try{ try { $content = $request->getContent(true); } catch (\LogicException $e) { $content = $request->getContent(); } }catch(\LogicException $e){ $content = file_get_contents('php://input'); } return $request::create( $request->getUri(), $request->getMethod(), $request->getMethod() === 'PATCH' ? $request->request->all() : $request->query->all(), $request->cookies->all(), $request->files->all(), $request->server->all(), $content ); }
Avoid exception throw when request content is null @param Request $request @return Request
entailment