func_code_string stringlengths 52 1.94M | func_documentation_string stringlengths 1 47.2k |
|---|---|
static function getDirSize($dir)
{
$size = 0;
$dirs = array_diff(scandir($dir), array('.', '..'));
foreach ($dirs as $d){
$d = $dir.'/'.$d;
$size+= filesize($d);
if (is_dir($d)){
$size+= self::getDirSize($d);
}
}
... | Размер директории в байтах
@param string $dir Путь на директорию
@return int |
static function makeDirName($id, $size=3, $depth=3)
{
$size = intval(max(1, $size));
$depth = intval(max(1,$depth));
$id = self::clearFileName($id);
$id = str_repeat('0',max(0, $size*$depth-strlen($id))).$id;
$dir = '';
for ($i=1; $i<$depth; $i++){
$dir = ... | Создание пути на директорию из идентификатора
@param string $id Идентификатор, который режится на имена директорий. При недостаточности длины добавляются нули.
@param int $size Длина для имен директорий
@param int $depth Вложенность директорий
@return string |
static function makeVirtualDir($dir, $mkdir = true)
{
if (self::$IS_WIN && mb_strlen($dir) > 248){
$dir = preg_replace('/\\\\/u','/', $dir);
$vdir = mb_substr($dir, 0, 248);
$vdir = F::splitRight('/', $vdir);
if ($vdir[0]){
$vdir = $vdir[0];
... | Создание виртуального диска в Windows, для увеличения лимита на длину пути к файлам
@param $dir
@param bool $mkdir
@return mixed|string |
static function deleteVirtualDir($vdir)
{
if (self::$IS_WIN && mb_substr($vdir,0,1) == self::VIRT_DISK){
system('subst '.self::VIRT_DISK.': /d');
}
} | Удаление виртуального диска в Windows
@param string $vdir Директория с виртуальным диском |
private function setBodyCurlOpt(RequestInterface $Request) : void
{
/*
* Some HTTP methods cannot have payload:
*
* - GET — cURL will automatically change method to PUT or POST if we set CURLOPT_UPLOAD or
* CURLOPT_POSTFIELDS.
* - HEAD — cURL treats HEAD as GET... | 设置body相关的curl option
@param RequestInterface $Request |
private function getCurloptHttpHeader(RequestInterface $Request) : array
{
$options = [];
$headers = $Request->getHeaders();
foreach ($headers as $name => $values) {
$header = strtolower($name);
if ('expect' === $header) {
// curl-client does not... | 返回curl option CURLOPT_HTTPHEADER
@param RequestInterface $Request
@return array |
private function getCurloptHttpVersion(RequestInterface $Request) : int
{
switch($Request->getProtocolVersion()){
case '1.0':
return CURL_HTTP_VERSION_1_0;
case '1.1':
return CURL_HTTP_VERSION_1_1;
case '2.0':
return CURL_HT... | 返回curl option CURLOPT_HTTP_VERSION
@param RequestInterface $Request
@return int |
private function getCurloptHeaderFunction() : callable
{
return function($ch, $data){
$str = trim($data);
if('' !== $str){
if(strpos(strtolower($str), 'http/') === 0){
$status_line = $str;
... | 返回curl option CURLOPT_HEADERFUNCTION
@return callable |
public function getTab()
{
if (headers_sent() && !session_id()) {
return;
}
ob_start();
$count = $this->count;
$queries = $this->queries;
require __DIR__ . '/templates/ConnectionPanel.tab.phtml';
return ob_get_clean();
} | Renders tab.
@return string |
public function getPanel()
{
ob_start();
if (!$this->count) {
return;
}
$count = $this->count;
$queries = $this->queries;
require __DIR__ . '/templates/ConnectionPanel.panel.phtml';
return ob_get_clean();
} | Renders panel.
@return string |
public function & SetView (\MvcCore\IView & $view) {
parent::SetView($view);
if (self::$appRoot === NULL) self::$appRoot = $this->request->GetAppRoot();
if (self::$basePath === NULL) self::$basePath = $this->request->GetBasePath();
if (self::$scriptName === NULL) self::$scriptName = ltrim($this->request->GetScr... | Insert a \MvcCore\View in each helper constructing
@param \MvcCore\View|\MvcCore\IView $view
@return \MvcCore\Ext\Views\Helpers\AbstractHelper |
public static function SetGlobalOptions ($options = []) {
self::$globalOptions = array_merge(self::$globalOptions, (array) $options);
if (isset($options['assetsUrl']) && !is_null($options['assetsUrl'])) {
self::$assetsUrlCompletion = (bool) $options['assetsUrl'];
}
} | Set global static options about minifying and joining together
which can bee overwritten by single settings throw calling for
example: append() method as another param.
@see \MvcCore\Ext\Views\Helpers\Assets::$globalOptions
@param array $options whether or not to auto escape output
@return void |
protected static function getFileImprint ($fullPath) {
$fileChecking = self::$globalOptions['fileChecking'];
if ($fileChecking == 'filemtime') {
return filemtime($fullPath);
} else {
return (string) call_user_func($fileChecking, $fullPath);
}
} | Returns file modification imprint by global settings -
by `md5_file()` or by `filemtime()` - always as a string
@param string $fullPath
@return string |
public function AssetUrl ($path = '') {
$result = '';
if (self::$assetsUrlCompletion) {
// for \MvcCore\Application::GetInstance()->GetCompiled() equal to: 'PHAR', 'SFU', 'PHP_STRICT_PACKAGE', 'PHP_PRESERVE_PACKAGE', 'PHP_PRESERVE_HDD'
$result = self::$scriptName . '?controller=controller&action=asset&path=' ... | Completes font or image file URL inside CSS/JS file content.
If application compile mode is in development state or packed in strict HDD mode,
there is generated standard URL with \MvcCore\Request::$BasePath (current app location)
plus called $path param. Because those application compile modes presume by default,
tha... |
public function CssJsFileUrl ($path = '') {
$result = '';
if (self::$assetsUrlCompletion) {
// for \MvcCore\Application::GetInstance()->GetCompiled() equal to: 'PHAR', 'SFU', 'PHP_STRICT_PACKAGE', 'PHP_PRESERVE_PACKAGE', 'PHP_PRESERVE_HDD'
$result = $this->view->AssetUrl($path);
} else {
// for \MvcCore\... | Completes CSS or JS file url.
If application compile mode is in development state or packed in strict HDD mode,
there is generated standard URL with \MvcCore\Request->GetBasePath() (current app location)
plus called $path param. Because those application compile modes presume by default,
that those files are placed be... |
protected function filterItemsForNotPossibleMinifiedAndPossibleMinifiedItems ($items) {
$itemsToRenderMinimized = [];
$itemsToRenderSeparately = []; // some configurations is not possible to render together and minimized
// go for every item to complete existing combinations in attributes
foreach ($items as & $... | Look for every item to render if there is any 'doNotMinify' record to render item separately
@param array $items
@return array[] $itemsToRenderMinimized $itemsToRenderSeparately |
protected function addFileModificationImprintToHrefUrl ($url, $path) {
$questionMarkPos = strpos($url, '?');
$separator = ($questionMarkPos === FALSE) ? '?' : '&';
$strippedUrl = $questionMarkPos !== FALSE ? substr($url, $questionMarkPos) : $url ;
$srcPath = $this->getAppRoot() . substr($strippedUrl, strlen(sel... | Add to href URL file modification param by original file
@param string $url
@param string $path
@return string |
protected function getIndentString($indent = 0) {
$indentStr = '';
if (is_numeric($indent)) {
$indInt = intval($indent);
if ($indInt > 0) {
$i = 0;
while ($i < $indInt) {
$indentStr .= "\t";
$i += 1;
}
}
} else if (is_string($indent)) {
$indentStr = $indent;
}
return $indentS... | Get indent string
@param string|int $indent
@return string |
protected function getTmpDir() {
if (!self::$tmpDir) {
$tmpDir = $this->getAppRoot() . self::$globalOptions['tmpDir'];
if (!\MvcCore\Application::GetInstance()->GetCompiled()) {
if (!is_dir($tmpDir)) mkdir($tmpDir, 0777, TRUE);
if (!is_writable($tmpDir)) {
try {
@chmod($tmpDir, 0777);
} ... | Return and store application document root from controller view request object
@throws \Exception
@return string |
protected function saveFileContent ($fullPath = '', & $fileContent = '') {
$toolClass = \MvcCore\Application::GetInstance()->GetToolClass();
$toolClass::SingleProcessWrite($fullPath, $fileContent);
@chmod($fullPath, 0766);
} | Save atomically file content in full path by 1 MB to not overflow any memory limits
@param string $fullPath
@param string $fileContent
@return void |
protected function log ($msg = '', $logType = 'debug') {
if (self::$loggingAndExceptions) {
\MvcCore\Debug::Log($msg, $logType);
}
} | Log any render messages with optional log file name
@param string $msg
@param string $logType
@return void |
protected function warning ($msg) {
if (self::$loggingAndExceptions) {
\MvcCore\Debug::BarDump('[' . get_class($this) . '] ' . $msg, \MvcCore\IDebug::DEBUG);
}
} | Throw exception with given message with actual helper class name before
@param string $msg
@return void |
protected function getTmpFileFullPathByPartFilesInfo ($filesGroupInfo = [], $minify = FALSE, $extension = '') {
return implode('', [
$this->getTmpDir(),
'/' . ($minify ? 'minified' : 'rendered') . '_' . $extension . '_',
md5(implode(',', $filesGroupInfo) . '_' . $minify),
'.' . $extension
]);
} | Complete items group tmp directory file name by group source files info
@param array $filesGroupInfo
@param boolean $minify
@return string |
private function validateFileStructure(array &$file)
{
if (false === array_key_exists(self::TODO_FINDER, $file)) {
throw new FileParserException(
sprintf(
'Provided YAML file does not compile with the required format. '
.'Expected \'%s\' ke... | @param array $file
@throws FileParserException |
private function assertYamlKey(array &$file, $key)
{
if (false === array_key_exists($key, $file)) {
throw new FileParserException(
sprintf(
'Provided YAML file does not compile with the required format. '
.'Expected \'%s\' key under \'%s\' ... | @param array $file
@param string $key
@throws FileParserException |
public function run($jobs)
{
$lenTab = count($jobs);
for ($i = 0 ; $i < $lenTab ; $i++) {
$jobID = rand(0, 100);
while (count($this->currentJobs) >= $this->maxProcesses) {
sleep($this->sleepTime);
}
$laun... | Run the Daemon |
protected function launchJob($jobID)
{
$pid = pcntl_fork();
if ($pid == -1) {
error_log('Could not launch new job, exiting');
echo 'Could not launch new job, exiting';
return false;
} else if ($pid) {
$this->curr... | Launch a job from the job queue |
protected function getTableNames(): array
{
$dbName = $this->config[DbItf::DB_CFG_DATABASE];
$resp = $this->dbRunQuery(sprintf('SHOW FULL TABLES FROM `%s`', $dbName));
$tableAndViewNames = [];
while ($row = $resp->fetch_assoc()) {
$tableAndViewNames[] = array_change_key_c... | Return table and view names form the database.
@throws DatabaseEx
@return array |
public function index()
{
$languages = $this->Languages->find('all');
$this->set(compact('languages'));
$this->set('_serialize', ['languages']);
} | Index method
@return \Cake\Http\Response|void |
public function add()
{
$language = $this->Languages->newEntity();
if ($this->request->is('post')) {
$data = is_array($this->request->getData()) ? $this->request->getData() : [];
$languageEntity = $this->Languages->addOrRestore($data);
if (!empty($languageEntity))... | Add method
@return \Cake\Http\Response|void|null Redirects on successful add, renders view otherwise. |
public function delete(string $id = null)
{
$this->request->allowMethod(['post', 'delete']);
$language = $this->Languages->get($id);
if ($this->Languages->delete($language)) {
$this->Flash->success((string)__('The language has been deleted.'));
} else {
$this-... | Delete method
@param string|null $id Language id.
@return \Cake\Http\Response|void|null Redirects to index.
@throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. |
public function buildStates(TokenStoreInterface $tokenStore)
{
$initial = new State($tokenStore, State::S_INITIAL_TOKENS);
$any = new State($tokenStore, State::S_ANY_TOKENS);
$inQuote = new State($tokenStore, State::S_IN_QUOTE_TOKENS);
$inEscape = new State($tokenStore, State::S_IN_E... | @param TokenStoreInterface $tokenStore
@return State The default starting state |
public static function slashDirname($dirname = null)
{
if (is_null($dirname) || empty($dirname)) {
return '';
}
return rtrim($dirname, '/ '.DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
} | Get a dirname with one and only trailing slash
@param string $dirname
@return string |
public static function isGitClone($path = null)
{
if (is_null($path) || empty($path)) {
return false;
}
$dir_path = self::slashDirname($path).'.git';
return (bool) (file_exists($dir_path) && is_dir($dir_path));
} | Test if a path seems to be a git clone
@param string $path
@return bool |
public static function isDotPath($path = null)
{
if (is_null($path) || empty($path)) {
return false;
}
return (bool) ('.'===substr(basename($path), 0, 1));
} | Test if a filename seems to have a dot as first character
@param string $path
@return bool |
public static function remove($path, $parent = true)
{
$ok = true;
if (true===self::ensureExists($path)) {
if (false===@is_dir($path) || true===is_link($path)) {
return @unlink($path);
}
$iterator = new \RecursiveIteratorIterator(
n... | Try to remove a path
@param string $path
@param bool $parent
@return bool |
public static function parseIni($path)
{
if (true===@file_exists($path)) {
$data = parse_ini_file($path, true);
if ($data && !empty($data)) {
return $data;
}
}
return false;
} | Read and parse a INI content file
@param $path
@return array|bool |
public static function parseJson($path)
{
if (true===@file_exists($path)) {
$ctt = file_get_contents($path);
if ($ctt!==false) {
$data = json_decode($ctt, true);
if ($data && !empty($data)) {
return $data;
}
... | Read and parse a JSON content file
@param $path
@return bool|mixed |
public function run(Array $argumentsList, int $argumentsCount)
{
$command = $argumentsList[0];
unset($argumentsList[0]);
$arguments = array_values($argumentsList);
$this->migrator->createMigrationsTable();
switch ($command) {
case 'create':
return $this->create();
break;
case 'run... | {@inheritDoc} |
protected function create(Array $arguments=[])
{
$migrationsDirectory = $this->cmd->getConfigOpt('migrations_storage');
$templateTags = [];
$migrationName = $this->cmd->question('Migration filename?');
$filename = trim($migrationName);
$path = $migrationsDirectory . '/' . $filename . '.php';
i... | Creates a migration.
@param $arguments <Array>
@access protected
@return <void> |
protected function processMigration(Array $arguments)
{
$migrationClass = $arguments[0];
$migration = Model::findByclass_name($migrationClass);
if (!$migration) {
throw new MigrationClassNotFoundException(
sprintf(
'Migration class [%s] does not exist',
$migrationClass
)
);
... | Processes a specific migration.
@param $arguments <Array>
@access protected
@return <void> |
public function isNew($file)
{
list($filemtime, $lastmodified) = $this->getCacheModificationDate($file);
return $filemtime > $lastmodified;
} | {@inheritDoc} |
public function write($data)
{
$this->storage->forget($this->getStorageKey() . '.lasmodified');
$this->storage->forget($this->getStorageKey());
$this->storage->forever($this->getStorageKey() . '.lasmodified', time());
$this->storage->forever($this->getStorageKey(), $data);
} | {@inheritDoc} |
protected function getCacheModificationDate($file)
{
$storageKey = $this->getStorageKey() . '.lasmodified';
$filemtime = filemtime($file);
$lastmodified = $this->storage->has($storageKey) ? $this->storage->get($storageKey) : $filemtime - 1;
return array($filemtime, $lastmodified... | Returns the modification date of a given file and the the
date of the last cache write.
@access protected
@return array |
public function create(array $metadata = array())
{
if (is_file($this->file)) {
return false;
}
$this->createTemporaryFolder();
file_put_contents($this->file, $this->placeholderContent($metadata), LOCK_EX);
return true;
} | Creates the file. It creates a placeholder file with some metadata on it and will
create all the temporary files and folders.
Writing without creating first will throw an exception. Creating twice will not throw an
exception but will return false. That means it is OK to call `create()` before calling
`write()`. Ideall... |
protected function createTemporaryFolder()
{
Util::mkdir($this->blocks);
Util::mkdir(dirname($this->file));
file_put_contents($this->tmp . '.lock', '', LOCK_EX);
} | Creates the needed temporary files and folders in prepartion for
the file writer. |
public function write($offset, $input, $limit = -1)
{
if (!is_dir($this->blocks)) {
throw new RuntimeException("Cannot write into the file");
}
$block = new BlockWriter($this->blocks . $offset, $this->tmp);
$wrote = $block->write($input, $limit);
$block->commit();... | Writes content to this file. This writer must provide the $offset where this data is going to
be written. The $content maybe a stream (the output of `fopen()`) or a string. Both type of `$content`
can have a `$limit` to limit the number of bytes that are written.
@param int $offset
@param string|stream $content
@param... |
public function getWroteBlocks()
{
if (!is_dir($this->blocks)) {
throw new RuntimeException("cannot obtain the blocks ({$this->blocks})");
}
$files = array_filter(array_map(function($file) {
$basename = basename($file);
if (!is_numeric($basename)) {
... | Returns all the wrote blocks of files. All the blocks are sorted by their offset.
@return array |
public function getMissingBlocks(Array $blocks = array())
{
$missing = array();
$blocks = $blocks ? $blocks : $this->getWroteBlocks();
$last = array_shift($blocks);
if ($last['offset'] !== 0) {
$missing[] = array('offset' => 0, 'size' => $last['offset']);
}
... | Returns the empty blocks in a file, if any gap is missing `finalize()`
will fail and will throw an exception.
@param $blocks Provides the list of blocks, otherwise `getWroteBlocks()` will
be called.
@return array |
public function finalize()
{
if (!is_file($this->tmp . '.lock')) {
throw new RuntimeException("File is already completed");
}
$lock = fopen($this->tmp . '.lock', 'r+');
if (!flock($lock, LOCK_EX | LOCK_NB)) {
return false;
}
$blocks = $this->g... | Finalizes writing a file. The finalization of a file means check that there are no gap or missing
block in a file, lock the file (so no other write may happen or another `finalize()`).
In here, after locking, all the blocks are merged into a single file. When the merging is ready,
we rename the temporary file as the f... |
public function run($user_email, $user_pass)
{
$result = [
'error' => true,
'message' => 'Неизвестная ошибка.',
];
$loginResult = $this->di->auth->login($user_email, $user_pass, false);
if ($loginResult['error'] === false) {
$user_id = $this->di-... | Выполним действие
@param string $user_email Адрес электронной почты
@param string $user_pass Пароль пользователя
@return array
@version 22.04.2017
@author Дмитрий Щербаков <atomcms@ya.ru> |
protected function execute(InputInterface $input, OutputInterface $output)
{
$plugins = $this->pluginManager->fetchPluginsAvailable();
if (!$plugins) {
$output->writeln('No available plugins could be found at the moment!');
return;
}
$rows = [];
foreac... | {@inheritdoc} |
public function isSection() {
if ($this->isCurrent()) {
return true;
}
$ancestors = $this->getAncestors();
if (Director::get_current_page() instanceof Page) {
$node = Director::get_current_page()->asMenuItem();
if ($node) {
$ancestors = $node->getAncestors();
return $ancestors && in_array($this... | Check if this page is in the currently active section (e.g. it is either current or one of its children is
currently being viewed).
@return bool |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.