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
iron-bound-designs/wp-notifications
src/Queue/Storage/Options.php
Options.get_notifications_strategy
public function get_notifications_strategy( $queue_id ) { $all = get_option( $this->bucket, array() ); if ( isset( $all[ $queue_id ]['strategy'] ) ) { return $all[ $queue_id ]['strategy']; } else { return null; } }
php
public function get_notifications_strategy( $queue_id ) { $all = get_option( $this->bucket, array() ); if ( isset( $all[ $queue_id ]['strategy'] ) ) { return $all[ $queue_id ]['strategy']; } else { return null; } }
Get the strategy for a set of notifications. @since 1.0 @param string $queue_id @return Strategy|null
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Queue/Storage/Options.php#L103-L112
iron-bound-designs/wp-notifications
src/Queue/Storage/Options.php
Options.clear_notifications
public function clear_notifications( $queue_id ) { $all = get_option( $this->bucket, array() ); if ( ! isset( $all[ $queue_id ] ) ) { return false; } unset( $all[ $queue_id ] ); if ( empty( $all ) ) { delete_option( $this->bucket ); } else { update_option( $this->bucket, $all ); } return true; }
php
public function clear_notifications( $queue_id ) { $all = get_option( $this->bucket, array() ); if ( ! isset( $all[ $queue_id ] ) ) { return false; } unset( $all[ $queue_id ] ); if ( empty( $all ) ) { delete_option( $this->bucket ); } else { update_option( $this->bucket, $all ); } return true; }
Clear a set of notifications. @since 1.0 @param string $queue_id @return bool
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Queue/Storage/Options.php#L123-L140
iron-bound-designs/wp-notifications
src/Queue/Storage/Options.php
Options.clear_notification
public function clear_notification( $queue_id, Notification $notification ) { $notifications = $this->get_notifications( $queue_id ); $notification = array_search( $notification, $notifications ); if ( false === $notification ) { return false; } unset( $notifications[ $notification ] ); return $this->store_notifications( $queue_id, $notifications ); }
php
public function clear_notification( $queue_id, Notification $notification ) { $notifications = $this->get_notifications( $queue_id ); $notification = array_search( $notification, $notifications ); if ( false === $notification ) { return false; } unset( $notifications[ $notification ] ); return $this->store_notifications( $queue_id, $notifications ); }
Clear a single notification from storage. @since 1.0 @param string $queue_id @param Notification $notification @return bool
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Queue/Storage/Options.php#L152-L165
mlocati/concrete5-translation-library
src/Gettext.php
Gettext.commandIsAvailable
public static function commandIsAvailable($command) { static $cache = array(); if (!isset($cache[$command])) { $cache[$command] = false; $safeMode = @ini_get('safe_mode'); if (empty($safeMode)) { if (function_exists('exec')) { if (!in_array('exec', array_map('trim', explode(',', strtolower(@ini_get('disable_functions')))), true)) { $rc = 1; $output = array(); @exec($command.' --version 2>&1', $output, $rc); if ($rc === 0) { $cache[$command] = true; } } } } } return $cache[$command]; }
php
public static function commandIsAvailable($command) { static $cache = array(); if (!isset($cache[$command])) { $cache[$command] = false; $safeMode = @ini_get('safe_mode'); if (empty($safeMode)) { if (function_exists('exec')) { if (!in_array('exec', array_map('trim', explode(',', strtolower(@ini_get('disable_functions')))), true)) { $rc = 1; $output = array(); @exec($command.' --version 2>&1', $output, $rc); if ($rc === 0) { $cache[$command] = true; } } } } } return $cache[$command]; }
Checks if a gettext command is available. @param string $command One of the gettext commands @return bool
https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Gettext.php#L17-L38
Tuna-CMS/tuna-bundle
src/Tuna/Bundle/FileBundle/Form/ImageType.php
ImageType.buildView
public function buildView(FormView $view, FormInterface $form, array $options) { parent::buildView($view, $form, $options); if ($options['scale_preview_thumbnail'] !== null) { @trigger_error(get_class($this) . ': The `scale_preview_thumbnail` option is deprecated. Use `image_filter` option instead (set it to `false` to disable use of filter).', E_USER_DEPRECATED); } $view->vars['scale_preview_thumbnail'] = $options['scale_preview_thumbnail']; $view->vars['image_filter'] = $options['image_filter']; }
php
public function buildView(FormView $view, FormInterface $form, array $options) { parent::buildView($view, $form, $options); if ($options['scale_preview_thumbnail'] !== null) { @trigger_error(get_class($this) . ': The `scale_preview_thumbnail` option is deprecated. Use `image_filter` option instead (set it to `false` to disable use of filter).', E_USER_DEPRECATED); } $view->vars['scale_preview_thumbnail'] = $options['scale_preview_thumbnail']; $view->vars['image_filter'] = $options['image_filter']; }
{@inheritdoc}
https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/FileBundle/Form/ImageType.php#L39-L47
bavix/laravel-helpers
src/Helpers/Corundum/Corundum.php
Corundum.imagePath
public function imagePath(string $basename): string { $path = 'image/' . PathBuilder::sharedInstance() ->generate($this->user(), $this->type(), $basename); return Storage::disk($this->disk) ->path($path); }
php
public function imagePath(string $basename): string { $path = 'image/' . PathBuilder::sharedInstance() ->generate($this->user(), $this->type(), $basename); return Storage::disk($this->disk) ->path($path); }
@param string $basename @return mixed
https://github.com/bavix/laravel-helpers/blob/a713460d2647a58b3eb8279d2a2726034ca79876/src/Helpers/Corundum/Corundum.php#L108-L115
bavix/laravel-helpers
src/Helpers/Corundum/Corundum.php
Corundum.contain
public function contain(string $path): DriverInterface { return new Adapters\Contain( $this, $this->imagePath($path) ); }
php
public function contain(string $path): DriverInterface { return new Adapters\Contain( $this, $this->imagePath($path) ); }
@param string $path @return DriverInterface
https://github.com/bavix/laravel-helpers/blob/a713460d2647a58b3eb8279d2a2726034ca79876/src/Helpers/Corundum/Corundum.php#L133-L139
bavix/laravel-helpers
src/Helpers/Corundum/Corundum.php
Corundum.cover
public function cover(string $path): DriverInterface { return new Adapters\Cover( $this, $this->imagePath($path) ); }
php
public function cover(string $path): DriverInterface { return new Adapters\Cover( $this, $this->imagePath($path) ); }
@param string $path @return DriverInterface
https://github.com/bavix/laravel-helpers/blob/a713460d2647a58b3eb8279d2a2726034ca79876/src/Helpers/Corundum/Corundum.php#L146-L152
bavix/laravel-helpers
src/Helpers/Corundum/Corundum.php
Corundum.fit
public function fit(string $path): DriverInterface { return new Adapters\Fit( $this, $this->imagePath($path) ); }
php
public function fit(string $path): DriverInterface { return new Adapters\Fit( $this, $this->imagePath($path) ); }
@param string $path @return DriverInterface
https://github.com/bavix/laravel-helpers/blob/a713460d2647a58b3eb8279d2a2726034ca79876/src/Helpers/Corundum/Corundum.php#L159-L165
bavix/laravel-helpers
src/Helpers/Corundum/Corundum.php
Corundum.resize
public function resize(string $path): DriverInterface { return new Adapters\Resize( $this, $this->imagePath($path) ); }
php
public function resize(string $path): DriverInterface { return new Adapters\Resize( $this, $this->imagePath($path) ); }
@param string $path @return DriverInterface
https://github.com/bavix/laravel-helpers/blob/a713460d2647a58b3eb8279d2a2726034ca79876/src/Helpers/Corundum/Corundum.php#L172-L178
bavix/laravel-helpers
src/Helpers/Corundum/Corundum.php
Corundum.none
public function none(string $path): DriverInterface { return new Adapters\None( $this, $this->imagePath($path) ); }
php
public function none(string $path): DriverInterface { return new Adapters\None( $this, $this->imagePath($path) ); }
@param string $path @return DriverInterface
https://github.com/bavix/laravel-helpers/blob/a713460d2647a58b3eb8279d2a2726034ca79876/src/Helpers/Corundum/Corundum.php#L185-L191
pilipinews/common
src/Scraper.php
Scraper.body
protected function body($element) { $body = $this->crawler->filter($element)->first()->html(); $body = trim(preg_replace('/\s+/', ' ', $body)); return new Crawler(str_replace('  ', ' ', $body)); }
php
protected function body($element) { $body = $this->crawler->filter($element)->first()->html(); $body = trim(preg_replace('/\s+/', ' ', $body)); return new Crawler(str_replace('  ', ' ', $body)); }
Returns the article content based on a given element. @param string $element @return \Pilipinews\Common\Crawler
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Scraper.php#L24-L31
pilipinews/common
src/Scraper.php
Scraper.html
protected function html(Crawler $crawler, $removables = array()) { $converter = new Converter; $html = trim($converter->convert($crawler->html())); foreach ((array) $removables as $keyword) { $html = str_replace($keyword, '', $html); } $html = str_replace(' ', ' ', (string) $html); return trim(preg_replace('/\s\s+/', "\n\n", $html)); }
php
protected function html(Crawler $crawler, $removables = array()) { $converter = new Converter; $html = trim($converter->convert($crawler->html())); foreach ((array) $removables as $keyword) { $html = str_replace($keyword, '', $html); } $html = str_replace(' ', ' ', (string) $html); return trim(preg_replace('/\s\s+/', "\n\n", $html)); }
Returns the HTML format of the body from the crawler. @param \Pilipinews\Common\Crawler $crawler @param string[] $removables @return string
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Scraper.php#L40-L54
pilipinews/common
src/Scraper.php
Scraper.prepare
protected function prepare($link) { $response = Client::request((string) $link); $response = str_replace('<strong> </strong>', ' ', $response); $this->crawler = new Crawler($response); }
php
protected function prepare($link) { $response = Client::request((string) $link); $response = str_replace('<strong> </strong>', ' ', $response); $this->crawler = new Crawler($response); }
Initializes the crawler instance. @param string $link @return void
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Scraper.php#L62-L69
pilipinews/common
src/Scraper.php
Scraper.remove
protected function remove($elements) { $callback = function ($crawler) { $node = $crawler->getNode((integer) 0); $node->parentNode->removeChild($node); }; foreach ((array) $elements as $removable) { $this->crawler->filter($removable)->each($callback); } }
php
protected function remove($elements) { $callback = function ($crawler) { $node = $crawler->getNode((integer) 0); $node->parentNode->removeChild($node); }; foreach ((array) $elements as $removable) { $this->crawler->filter($removable)->each($callback); } }
Removes specified HTML tags from body. @param string[] $elements @return void
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Scraper.php#L77-L90
pilipinews/common
src/Scraper.php
Scraper.replace
protected function replace(Crawler $crawler, $element, $callback) { $function = function (Crawler $crawler) use ($callback) { $node = $crawler->getNode(0); $html = $node->ownerDocument->saveHtml($node); $text = $callback($crawler, (string) $html); return array((string) $html, (string) $text); }; $items = $crawler->filter($element)->each($function); $html = (string) $crawler->html(); foreach ((array) $items as $item) { $html = str_replace($item[0], $item[1], $html); } return new Crawler((string) $html); }
php
protected function replace(Crawler $crawler, $element, $callback) { $function = function (Crawler $crawler) use ($callback) { $node = $crawler->getNode(0); $html = $node->ownerDocument->saveHtml($node); $text = $callback($crawler, (string) $html); return array((string) $html, (string) $text); }; $items = $crawler->filter($element)->each($function); $html = (string) $crawler->html(); foreach ((array) $items as $item) { $html = str_replace($item[0], $item[1], $html); } return new Crawler((string) $html); }
Replaces a specified HTML tag based from the given callback. @param \Pilipinews\Common\Crawler $crawler @param string $element @param callable $callback @return \Pilipinews\Common\Crawler
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Scraper.php#L100-L123
pilipinews/common
src/Scraper.php
Scraper.title
protected function title($element, $removable = '') { $converter = new Converter; $crawler = $this->crawler->filter($element); $html = $crawler->first()->html(); $html = str_replace($removable, '', $html); return $converter->convert((string) $html); }
php
protected function title($element, $removable = '') { $converter = new Converter; $crawler = $this->crawler->filter($element); $html = $crawler->first()->html(); $html = str_replace($removable, '', $html); return $converter->convert((string) $html); }
Returns the title text based from given HTML tag. @param string $element @param string $removable @return string
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Scraper.php#L132-L143
pilipinews/common
src/Scraper.php
Scraper.tweet
protected function tweet(Crawler $crawler) { $callback = function (Crawler $crawler) { $parsed = (string) $crawler->text(); $text = str_replace('📸: ', '', $parsed); return '<p>TWEET: ' . $text . '</p>'; }; $class = '.twitter-tweet'; return $this->replace($crawler, $class, $callback); }
php
protected function tweet(Crawler $crawler) { $callback = function (Crawler $crawler) { $parsed = (string) $crawler->text(); $text = str_replace('📸: ', '', $parsed); return '<p>TWEET: ' . $text . '</p>'; }; $class = '.twitter-tweet'; return $this->replace($crawler, $class, $callback); }
Parses embedded Twitter tweet in the HTML. @param \Pilipinews\Common\Crawler $crawler @return \Pilipinews\Common\Crawler
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Scraper.php#L151-L165
bavix/laravel-helpers
src/App/Admin/Form/Field/MultipleImage.php
MultipleImage.prepareForeach
protected function prepareForeach(UploadedFile $image = null) { $self = clone $this; $self->name = $self->getStoreName($image); $self->callInterventionMethods($image->getRealPath()); return tap($self->upload($image), function () use ($self) { $self->name = null; }); }
php
protected function prepareForeach(UploadedFile $image = null) { $self = clone $this; $self->name = $self->getStoreName($image); $self->callInterventionMethods($image->getRealPath()); return tap($self->upload($image), function () use ($self) { $self->name = null; }); }
Prepare for each file. @param UploadedFile $image @return mixed|string
https://github.com/bavix/laravel-helpers/blob/a713460d2647a58b3eb8279d2a2726034ca79876/src/App/Admin/Form/Field/MultipleImage.php#L16-L26
MovingImage24/VM6ApiClient
lib/ApiClient/AbstractCoreApiClient.php
AbstractCoreApiClient.makeRequest
protected function makeRequest($method, $uri, $options) { $logger = $this->getLogger(); try { $logger->info(sprintf('Making API %s request to %s', $method, $uri), [$options]); /** @var ResponseInterface $response */ $response = $this->_doRequest($method, $uri, $options); $logger->debug('Response from HTTP call was status code:', [$response->getStatusCode()]); $logger->debug('Response JSON was:', [$response->getBody()]); return $response; } catch (\Exception $e) { throw $e; // Just rethrow for now } }
php
protected function makeRequest($method, $uri, $options) { $logger = $this->getLogger(); try { $logger->info(sprintf('Making API %s request to %s', $method, $uri), [$options]); /** @var ResponseInterface $response */ $response = $this->_doRequest($method, $uri, $options); $logger->debug('Response from HTTP call was status code:', [$response->getStatusCode()]); $logger->debug('Response JSON was:', [$response->getBody()]); return $response; } catch (\Exception $e) { throw $e; // Just rethrow for now } }
Make a request to the API and serialize the result according to our serialization strategy. @param string $method @param string $uri @param array $options @return object|ResponseInterface
https://github.com/MovingImage24/VM6ApiClient/blob/84e6510fa0fb71cfbb42ea9f23775f681c266fac/lib/ApiClient/AbstractCoreApiClient.php#L75-L92
MovingImage24/VM6ApiClient
lib/ApiClient/AbstractCoreApiClient.php
AbstractCoreApiClient.buildJsonParameters
protected function buildJsonParameters(array $required, array $optional) { foreach ($required as $key => $value) { if (empty($value)) { throw new Exception(sprintf('Required parameter \'%s\' is missing..', $key)); } } $json = $required; foreach ($optional as $key => $value) { if (!empty($value) || $value === false) { $json[$key] = $value; } } return $json; }
php
protected function buildJsonParameters(array $required, array $optional) { foreach ($required as $key => $value) { if (empty($value)) { throw new Exception(sprintf('Required parameter \'%s\' is missing..', $key)); } } $json = $required; foreach ($optional as $key => $value) { if (!empty($value) || $value === false) { $json[$key] = $value; } } return $json; }
Helper method to build the JSON data array for making a request with ::makeRequest(). Optional parameters with empty or null value will be omitted from the return value. Examples: $this->buildJsonParameters(['title' => 'test'], ['description' => '', 'bla' => 'test']) Would result in: [ 'title' => 'test', 'bla' => 'test', ] @param array $required @param array $optional @return array
https://github.com/MovingImage24/VM6ApiClient/blob/84e6510fa0fb71cfbb42ea9f23775f681c266fac/lib/ApiClient/AbstractCoreApiClient.php#L128-L145
PHPColibri/framework
Database/AbstractDb/Driver/Connection.php
Connection.open
public function open() { if (self::$monitorQueries) { self::$strQueries .= "Before @mysqli_connect\n"; global $time; $curTime = microtime(true) - $time; self::$strQueries .= sprintf('%f', $curTime) . "\n"; } $this->connect(); }
php
public function open() { if (self::$monitorQueries) { self::$strQueries .= "Before @mysqli_connect\n"; global $time; $curTime = microtime(true) - $time; self::$strQueries .= sprintf('%f', $curTime) . "\n"; } $this->connect(); }
Открывает соединение с базой данных. Opens connection to database. @throws \Colibri\Database\DbException
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Database/AbstractDb/Driver/Connection.php#L47-L57
PHPColibri/framework
Database/AbstractDb/Driver/Connection.php
Connection.query
public function query(string $query) { if (self::$monitorQueries) { $queryStartTime = microtime(true); self::$strQueries .= $query . "\n"; } $result = $this->sendQuery($query); if (self::$monitorQueries) { global $time; $queryEndTime = microtime(true); $curScriptTime = $queryEndTime - $time; /** @var int $queryStartTime */ $queryExecTime = $queryEndTime - $queryStartTime; self::$strQueries .= ' Script time: ' . round($curScriptTime, 8) . "\n"; self::$strQueries .= ' Query time: ' . round($queryExecTime, 8) . "\n"; } return $result; }
php
public function query(string $query) { if (self::$monitorQueries) { $queryStartTime = microtime(true); self::$strQueries .= $query . "\n"; } $result = $this->sendQuery($query); if (self::$monitorQueries) { global $time; $queryEndTime = microtime(true); $curScriptTime = $queryEndTime - $time; /** @var int $queryStartTime */ $queryExecTime = $queryEndTime - $queryStartTime; self::$strQueries .= ' Script time: ' . round($curScriptTime, 8) . "\n"; self::$strQueries .= ' Query time: ' . round($queryExecTime, 8) . "\n"; } return $result; }
Выполняет запрос к базе данных. Executes given query. @param string $query @return bool|\Colibri\Database\AbstractDb\Driver\Query\ResultInterface @throws \Colibri\Database\Exception\SqlException @global int $time
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Database/AbstractDb/Driver/Connection.php#L76-L96
digipolisgent/robo-digipolis-deploy
src/Ssh.php
Ssh.exec
public function exec($command, $callback = null) { $this->commandStack[] = [ 'command' => new Command($this->receiveCommand($command)), 'callback' => $callback, ]; return $this; }
php
public function exec($command, $callback = null) { $this->commandStack[] = [ 'command' => new Command($this->receiveCommand($command)), 'callback' => $callback, ]; return $this; }
@param string|CommandInterface $command @param callable $callback @return $this
https://github.com/digipolisgent/robo-digipolis-deploy/blob/fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab/src/Ssh.php#L144-L152
digipolisgent/robo-digipolis-deploy
src/Ssh.php
Ssh.remoteDirectory
public function remoteDirectory($directory, $physical = false) { $this->remoteDir = $directory; $this->physicalRemoteDir = $physical; return $this; }
php
public function remoteDirectory($directory, $physical = false) { $this->remoteDir = $directory; $this->physicalRemoteDir = $physical; return $this; }
Sets the remote directory. @param string $directory The remote directory. @param bool $physical Use the physical directory structure without following symbolic links (-P argument for cd). @return $this
https://github.com/digipolisgent/robo-digipolis-deploy/blob/fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab/src/Ssh.php#L165-L171
digipolisgent/robo-digipolis-deploy
src/Ssh.php
Ssh.run
public function run() { try { $ssh = call_user_func( [$this->sshFactory, 'create'], $this->host, $this->port, $this->timeout ); $this->startTimer(); $ssh->login($this->auth); $errorMessage = ''; foreach ($this->commandStack as $command) { $command['command'] ->setDirectory($this->remoteDir) ->setPhysicalDirectory($this->physicalRemoteDir); $this->printTaskInfo(sprintf( '%s@%s:%s$ %s', $this->auth->getUser(), $this->host, $this->remoteDir ? $this->remoteDir : '~', $command['command']->getCommand() )); $result = call_user_func_array( [ $ssh, 'exec', ], [ (string) $command['command'], $this->commandCallback($command['callback']), ] ); $this->printTaskInfo($this->output); $this->output = ''; if ($result === false || $ssh->getExitStatus() !== 0) { $errorMessage .= sprintf( 'Could not execute %s on %s on port %s in folder %s with message: %s.', $command['command']->getCommand(), $this->host, $this->port, $this->remoteDir, $ssh->getStdError() ); if ($ssh->isTimeout()) { $errorMessage .= ' '; $errorMessage .= sprintf( 'Connection timed out. Execution took %s, timeout is set at %s seconds.', $this->getExecutionTime(), $this->timeout ); } if ($this->stopOnFail) { return Result::error($this, $errorMessage); } $errorMessage .= "\n"; } } } catch (\Exception $e) { $errorMessage = $e->getMessage(); } $this->stopTimer(); return $errorMessage ? Result::error($this, $errorMessage . ($this->verbose ? "\nVerbose log:\n" . $ssh->getLog() : '')) : Result::success($this, ($this->verbose ? "Verbose log:\n" . $ssh->getLog() : '')); }
php
public function run() { try { $ssh = call_user_func( [$this->sshFactory, 'create'], $this->host, $this->port, $this->timeout ); $this->startTimer(); $ssh->login($this->auth); $errorMessage = ''; foreach ($this->commandStack as $command) { $command['command'] ->setDirectory($this->remoteDir) ->setPhysicalDirectory($this->physicalRemoteDir); $this->printTaskInfo(sprintf( '%s@%s:%s$ %s', $this->auth->getUser(), $this->host, $this->remoteDir ? $this->remoteDir : '~', $command['command']->getCommand() )); $result = call_user_func_array( [ $ssh, 'exec', ], [ (string) $command['command'], $this->commandCallback($command['callback']), ] ); $this->printTaskInfo($this->output); $this->output = ''; if ($result === false || $ssh->getExitStatus() !== 0) { $errorMessage .= sprintf( 'Could not execute %s on %s on port %s in folder %s with message: %s.', $command['command']->getCommand(), $this->host, $this->port, $this->remoteDir, $ssh->getStdError() ); if ($ssh->isTimeout()) { $errorMessage .= ' '; $errorMessage .= sprintf( 'Connection timed out. Execution took %s, timeout is set at %s seconds.', $this->getExecutionTime(), $this->timeout ); } if ($this->stopOnFail) { return Result::error($this, $errorMessage); } $errorMessage .= "\n"; } } } catch (\Exception $e) { $errorMessage = $e->getMessage(); } $this->stopTimer(); return $errorMessage ? Result::error($this, $errorMessage . ($this->verbose ? "\nVerbose log:\n" . $ssh->getLog() : '')) : Result::success($this, ($this->verbose ? "Verbose log:\n" . $ssh->getLog() : '')); }
{@inheritdoc}
https://github.com/digipolisgent/robo-digipolis-deploy/blob/fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab/src/Ssh.php#L232-L298
digipolisgent/robo-digipolis-deploy
src/Ssh.php
Ssh.commandCallback
protected function commandCallback($callback) { return ( function ($output) use ($callback) { $this->output .= $output; if (is_callable($callback)) { return call_user_func($callback, $output); } } ); }
php
protected function commandCallback($callback) { return ( function ($output) use ($callback) { $this->output .= $output; if (is_callable($callback)) { return call_user_func($callback, $output); } } ); }
Wrap the callback so we can print the output. @param callable $callback The callback to wrap.
https://github.com/digipolisgent/robo-digipolis-deploy/blob/fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab/src/Ssh.php#L306-L316
thelia-modules/SmartyFilter
Handler/ConfigurationFileHandler.php
ConfigurationFileHandler.parseXml
protected function parseXml(SplFileInfo $file) { $dom = XmlUtils::loadFile($file, realpath(dirname(__DIR__) . DS . 'Schema' . DS . 'smarty_filter.xsd')); /** @var \Symfony\Component\DependencyInjection\SimpleXMLElement $xml */ $xml = simplexml_import_dom($dom, '\\Symfony\\Component\\DependencyInjection\\SimpleXMLElement'); $parsedConfig = []; /** @var \Symfony\Component\DependencyInjection\SimpleXMLElement $smartyFilterDefinition */ foreach ($xml->smartyfilter as $smartyFilterDefinition) { $descriptive = []; /** @var \Symfony\Component\DependencyInjection\SimpleXMLElement $descriptiveDefinition */ foreach ($smartyFilterDefinition->descriptive as $descriptiveDefinition) { $descriptive[] = [ 'locale' => $descriptiveDefinition->getAttributeAsPhp('locale'), 'title' => (string)$descriptiveDefinition->title, 'description' => (string)$descriptiveDefinition->description, 'type' => (string)$descriptiveDefinition->type ]; } $parsedConfig['smarty_filter'][] = [ 'code' => $smartyFilterDefinition->getAttributeAsPhp('code'), 'descriptive' => $descriptive ]; } return $parsedConfig; }
php
protected function parseXml(SplFileInfo $file) { $dom = XmlUtils::loadFile($file, realpath(dirname(__DIR__) . DS . 'Schema' . DS . 'smarty_filter.xsd')); /** @var \Symfony\Component\DependencyInjection\SimpleXMLElement $xml */ $xml = simplexml_import_dom($dom, '\\Symfony\\Component\\DependencyInjection\\SimpleXMLElement'); $parsedConfig = []; /** @var \Symfony\Component\DependencyInjection\SimpleXMLElement $smartyFilterDefinition */ foreach ($xml->smartyfilter as $smartyFilterDefinition) { $descriptive = []; /** @var \Symfony\Component\DependencyInjection\SimpleXMLElement $descriptiveDefinition */ foreach ($smartyFilterDefinition->descriptive as $descriptiveDefinition) { $descriptive[] = [ 'locale' => $descriptiveDefinition->getAttributeAsPhp('locale'), 'title' => (string)$descriptiveDefinition->title, 'description' => (string)$descriptiveDefinition->description, 'type' => (string)$descriptiveDefinition->type ]; } $parsedConfig['smarty_filter'][] = [ 'code' => $smartyFilterDefinition->getAttributeAsPhp('code'), 'descriptive' => $descriptive ]; } return $parsedConfig; }
Get config from xml file @param SplFileInfo $file XML file @return array Smarty Filter module configuration
https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Handler/ConfigurationFileHandler.php#L68-L96
thelia-modules/SmartyFilter
Handler/ConfigurationFileHandler.php
ConfigurationFileHandler.applyConfig
protected function applyConfig(array $moduleConfiguration) { foreach ($moduleConfiguration['smarty_filter'] as $smartyFilterData) { if (SmartyFilterQuery::create()->findOneByCode($smartyFilterData['code']) === null) { $smartyFilter = (new SmartyFilter()) ->setCode($smartyFilterData['code']); foreach ($smartyFilterData['descriptive'] as $descriptiveData) { $smartyFilter ->setLocale($descriptiveData['locale']) ->setTitle($descriptiveData['title']) ->setDescription($descriptiveData['description']) ->setFiltertype($descriptiveData['type']); } $smartyFilter->save(); } } }
php
protected function applyConfig(array $moduleConfiguration) { foreach ($moduleConfiguration['smarty_filter'] as $smartyFilterData) { if (SmartyFilterQuery::create()->findOneByCode($smartyFilterData['code']) === null) { $smartyFilter = (new SmartyFilter()) ->setCode($smartyFilterData['code']); foreach ($smartyFilterData['descriptive'] as $descriptiveData) { $smartyFilter ->setLocale($descriptiveData['locale']) ->setTitle($descriptiveData['title']) ->setDescription($descriptiveData['description']) ->setFiltertype($descriptiveData['type']); } $smartyFilter->save(); } } }
Save new smarty filter to database @param array $moduleConfiguration Smarty Filter module configuration
https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Handler/ConfigurationFileHandler.php#L117-L135
antaresproject/search
src/Response/QueryResponse.php
QueryResponse.isValid
protected function isValid() { if (!$this->request->ajax()) { return false; } $search = $this->request->input('search'); if (!is_string($search) or strlen($this->request->input('search')) <= 0) { return false; } $token = $this->request->header('search-protection'); if (!$this->validateToken($token)) { return false; } return true; }
php
protected function isValid() { if (!$this->request->ajax()) { return false; } $search = $this->request->input('search'); if (!is_string($search) or strlen($this->request->input('search')) <= 0) { return false; } $token = $this->request->header('search-protection'); if (!$this->validateToken($token)) { return false; } return true; }
validates submitted data from search form @return boolean
https://github.com/antaresproject/search/blob/3bcb994e69c03792d20dfa688a3281f80cd8dde8/src/Response/QueryResponse.php#L54-L68
antaresproject/search
src/Response/QueryResponse.php
QueryResponse.validateToken
private function validateToken($token = null) { if (is_null($token)) { return false; } $decrypted = Crypt::decrypt($token); $args = unserialize($decrypted); if (!isset($args['protection_string']) or $args['protection_string'] !== config('antares/search::protection_string')) { return false; } if (!isset($args['app_key']) or $args['app_key'] !== env('APP_KEY')) { return false; } return true; }
php
private function validateToken($token = null) { if (is_null($token)) { return false; } $decrypted = Crypt::decrypt($token); $args = unserialize($decrypted); if (!isset($args['protection_string']) or $args['protection_string'] !== config('antares/search::protection_string')) { return false; } if (!isset($args['app_key']) or $args['app_key'] !== env('APP_KEY')) { return false; } return true; }
validates protection token @param String $token @return boolean
https://github.com/antaresproject/search/blob/3bcb994e69c03792d20dfa688a3281f80cd8dde8/src/Response/QueryResponse.php#L76-L91
antaresproject/search
src/Response/QueryResponse.php
QueryResponse.boot
public function boot() { if (!$this->isValid()) { return false; } $serviceProvider = new \Antares\Customfields\CustomFieldsServiceProvider(app()); $serviceProvider->register(); $serviceProvider->boot(); $query = e($this->request->input('search')); $cacheKey = 'search_' . snake_case($query); $formated = []; try { //$formated = Cache::remember($cacheKey, 5, function() use($query) { $datatables = config('search.datatables', []); foreach ($datatables as $classname) { $datatable = $this->getDatatableInstance($classname); if (!$datatable) { continue; } request()->merge(['inline_search' => ['value' => $query, 'regex' => false]]); $formated = array_merge($formated, app('antares-search-row-decorator')->setDatatable($datatable)->getRows()); } if (empty($formated)) { $formated[] = [ 'content' => '<div class="type--datarow"><div class="datarow__left"><span>No results found...</span></div></div>', 'url' => '#', 'category' => '', 'total' => 0 ]; } $jsonResponse = new JsonResponse($formated, 200); } catch (Exception $e) { $jsonResponse = new JsonResponse(['message' => $e->getMessage()], 500); } $jsonResponse->send(); return exit(); }
php
public function boot() { if (!$this->isValid()) { return false; } $serviceProvider = new \Antares\Customfields\CustomFieldsServiceProvider(app()); $serviceProvider->register(); $serviceProvider->boot(); $query = e($this->request->input('search')); $cacheKey = 'search_' . snake_case($query); $formated = []; try { //$formated = Cache::remember($cacheKey, 5, function() use($query) { $datatables = config('search.datatables', []); foreach ($datatables as $classname) { $datatable = $this->getDatatableInstance($classname); if (!$datatable) { continue; } request()->merge(['inline_search' => ['value' => $query, 'regex' => false]]); $formated = array_merge($formated, app('antares-search-row-decorator')->setDatatable($datatable)->getRows()); } if (empty($formated)) { $formated[] = [ 'content' => '<div class="type--datarow"><div class="datarow__left"><span>No results found...</span></div></div>', 'url' => '#', 'category' => '', 'total' => 0 ]; } $jsonResponse = new JsonResponse($formated, 200); } catch (Exception $e) { $jsonResponse = new JsonResponse(['message' => $e->getMessage()], 500); } $jsonResponse->send(); return exit(); }
Boots search query in lucene indexes @return boolean
https://github.com/antaresproject/search/blob/3bcb994e69c03792d20dfa688a3281f80cd8dde8/src/Response/QueryResponse.php#L98-L136
antaresproject/search
src/Response/QueryResponse.php
QueryResponse.getDatatableInstance
protected function getDatatableInstance($classname) { if (!class_exists($classname)) { return false; } $datatable = app($classname); $reflection = new ReflectionClass($datatable); if (($filename = $reflection->getFileName()) && !str_contains($filename, 'core')) { if (!app('antares.extension')->getActiveExtensionByPath($filename)) { return false; } } return $datatable; }
php
protected function getDatatableInstance($classname) { if (!class_exists($classname)) { return false; } $datatable = app($classname); $reflection = new ReflectionClass($datatable); if (($filename = $reflection->getFileName()) && !str_contains($filename, 'core')) { if (!app('antares.extension')->getActiveExtensionByPath($filename)) { return false; } } return $datatable; }
Gets instance of datatable @param String $classname @return boolean
https://github.com/antaresproject/search/blob/3bcb994e69c03792d20dfa688a3281f80cd8dde8/src/Response/QueryResponse.php#L144-L157
RadialCorp/magento-core
src/app/code/community/Radial/Order/Model/Eav/Entity/Increment/Order.php
Radial_Order_Model_Eav_Entity_Increment_Order._removeKnownKeys
protected function _removeKnownKeys(array $initParams) { foreach (['core_helper', 'order_helper'] as $key) { if (isset($initParams[$key])) { unset($initParams[$key]); } } return $initParams; }
php
protected function _removeKnownKeys(array $initParams) { foreach (['core_helper', 'order_helper'] as $key) { if (isset($initParams[$key])) { unset($initParams[$key]); } } return $initParams; }
Remove the all the require and optional keys from the $initParams parameter. @param array @return array
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Order/Model/Eav/Entity/Increment/Order.php#L39-L47
RadialCorp/magento-core
src/app/code/community/Radial/Order/Model/Eav/Entity/Increment/Order.php
Radial_Order_Model_Eav_Entity_Increment_Order._getStoreId
protected function _getStoreId() { $storeEnv = Mage::app()->getStore(); if ($storeEnv->isAdmin()) { /** @var Mage_Adminhtml_Model_Session_Quote */ $quoteSession = $this->_orderHelper->getAdminQuoteSessionModel(); // when in the admin, the store id the order is actually being created // for should be used instead of the admin store id - should be // available in the session $storeEnv = $quoteSession->getStore(); } return $storeEnv->getId(); }
php
protected function _getStoreId() { $storeEnv = Mage::app()->getStore(); if ($storeEnv->isAdmin()) { /** @var Mage_Adminhtml_Model_Session_Quote */ $quoteSession = $this->_orderHelper->getAdminQuoteSessionModel(); // when in the admin, the store id the order is actually being created // for should be used instead of the admin store id - should be // available in the session $storeEnv = $quoteSession->getStore(); } return $storeEnv->getId(); }
Get the store id for the order. In non-admin stores, can use the current store. In admin stores, must get the order the quote is actually being created in. @return int
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Order/Model/Eav/Entity/Increment/Order.php#L82-L94
RadialCorp/magento-core
src/app/code/community/Radial/Order/Model/Eav/Entity/Increment/Order.php
Radial_Order_Model_Eav_Entity_Increment_Order.getNextId
public function getNextId() { // remove any order prefixes from the last increment id $last = $this->_orderHelper->removeOrderIncrementPrefix($this->getLastId()); // Using bcmath to avoid float/integer overflow. return $this->format(bcadd($last, 1)); }
php
public function getNextId() { // remove any order prefixes from the last increment id $last = $this->_orderHelper->removeOrderIncrementPrefix($this->getLastId()); // Using bcmath to avoid float/integer overflow. return $this->format(bcadd($last, 1)); }
Get the next increment id by incrementing the last id @return string
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Order/Model/Eav/Entity/Increment/Order.php#L99-L105
sellerlabs/injected
src/SellerLabs/Injected/InjectedTrait.php
InjectedTrait.getDependencyMapping
protected function getDependencyMapping() { $constructor = (new ReflectionClass($this->className)) ->getConstructor(); $dependencies = []; if (!is_null($constructor)) { foreach ($constructor->getParameters() as $param) { $dependencies[$param->getClass()->getName()] = $param->getName(); } } return $dependencies; }
php
protected function getDependencyMapping() { $constructor = (new ReflectionClass($this->className)) ->getConstructor(); $dependencies = []; if (!is_null($constructor)) { foreach ($constructor->getParameters() as $param) { $dependencies[$param->getClass()->getName()] = $param->getName(); } } return $dependencies; }
Get a mapping of class name => member name dependencies. Important: these must be ordered in the way the class accepts its dependencies. @return array @throws Exception
https://github.com/sellerlabs/injected/blob/89f90334ccc392c67c79fb1eba258b34cfa9edd6/src/SellerLabs/Injected/InjectedTrait.php#L32-L46
sellerlabs/injected
src/SellerLabs/Injected/InjectedTrait.php
InjectedTrait.make
protected function make(array $parameters = []) { $dependencies = $this->mockDependencies(); $dependencies = array_merge($dependencies, $parameters); // Note: Must be defined in trait-using class $className = $this->className; return new $className( ...array_values($dependencies) ); }
php
protected function make(array $parameters = []) { $dependencies = $this->mockDependencies(); $dependencies = array_merge($dependencies, $parameters); // Note: Must be defined in trait-using class $className = $this->className; return new $className( ...array_values($dependencies) ); }
Make an instance of $this->className @param array $parameters @return mixed @throws Exception
https://github.com/sellerlabs/injected/blob/89f90334ccc392c67c79fb1eba258b34cfa9edd6/src/SellerLabs/Injected/InjectedTrait.php#L57-L68
sellerlabs/injected
src/SellerLabs/Injected/InjectedTrait.php
InjectedTrait.mockDependencies
protected function mockDependencies() { $dependencies = $this->getDependencyMapping(); foreach ($dependencies as $interface => $memberName) { if (!isset($this->$memberName)) { $this->$memberName = Mockery::mock($interface); } // Update with the actual instance. $dependencies[$interface] = $this->$memberName; } return $dependencies; }
php
protected function mockDependencies() { $dependencies = $this->getDependencyMapping(); foreach ($dependencies as $interface => $memberName) { if (!isset($this->$memberName)) { $this->$memberName = Mockery::mock($interface); } // Update with the actual instance. $dependencies[$interface] = $this->$memberName; } return $dependencies; }
Mock all dependencies that were not set yet @return array @throws Exception
https://github.com/sellerlabs/injected/blob/89f90334ccc392c67c79fb1eba258b34cfa9edd6/src/SellerLabs/Injected/InjectedTrait.php#L77-L91
pmdevelopment/tool-bundle
Framework/Utilities/NumberUtility.php
NumberUtility.getPercentage
public static function getPercentage($base, $divider, $scale = 2, $string = false) { if (0 === $divider) { return '-'; } $value = round(($base / $divider) * 100, $scale); if (false === $string) { return $value; } return sprintf('%s%%', number_format($value, $scale)); }
php
public static function getPercentage($base, $divider, $scale = 2, $string = false) { if (0 === $divider) { return '-'; } $value = round(($base / $divider) * 100, $scale); if (false === $string) { return $value; } return sprintf('%s%%', number_format($value, $scale)); }
@param float $base @param float $divider @param int $scale @param bool $string @return float|string
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Framework/Utilities/NumberUtility.php#L28-L40
hal-platform/hal-core
src/VersionControl/GitHub/GitHubDownloader.php
GitHubDownloader.download
public function download(Application $application, string $commit, string $targetFile): bool { $username = $application->parameter('gh.owner'); $repository = $application->parameter('gh.repo'); if (!$username || !$repository) { throw new VCSException(self::ERR_APP_MISCONFIGURED); } $endpoint = implode('/', [ 'repos', rawurlencode($username), rawurlencode($repository), 'tarball', rawurlencode($commit), ]); $options = [ 'sink' => new LazyOpenStream($targetFile, 'w+'), ]; try { $response = $this->guzzle->request('GET', $endpoint, $options); } catch (Exception $e) { throw new VCSException($e->getMessage(), $e->getCode(), $e); } return ($response->getStatusCode() === 200); }
php
public function download(Application $application, string $commit, string $targetFile): bool { $username = $application->parameter('gh.owner'); $repository = $application->parameter('gh.repo'); if (!$username || !$repository) { throw new VCSException(self::ERR_APP_MISCONFIGURED); } $endpoint = implode('/', [ 'repos', rawurlencode($username), rawurlencode($repository), 'tarball', rawurlencode($commit), ]); $options = [ 'sink' => new LazyOpenStream($targetFile, 'w+'), ]; try { $response = $this->guzzle->request('GET', $endpoint, $options); } catch (Exception $e) { throw new VCSException($e->getMessage(), $e->getCode(), $e); } return ($response->getStatusCode() === 200); }
Get content of archives in a repository @link http://developer.github.com/v3/repos/contents/ @param Application $application @param string $commit @param string $targetFile @throws VCSException @return bool
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/VersionControl/GitHub/GitHubDownloader.php#L47-L75
VincentChalnot/SidusEAVVariantBundle
DependencyInjection/Configuration.php
Configuration.getConfigTreeBuilder
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('sidus_eav_variant'); $familyDefinition = $rootNode ->children() ->arrayNode('routes') ->children() ->scalarNode('select')->isRequired()->end() ->scalarNode('create')->isRequired()->end() ->scalarNode('edit')->isRequired()->end() ->scalarNode('delete')->isRequired()->end() ->end() ->end() ->arrayNode('families') ->prototype('array') ->children(); $this->appendFamilyDefinition($familyDefinition); $familyDefinition->end() ->end() ->end() ->end(); return $treeBuilder; }
php
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('sidus_eav_variant'); $familyDefinition = $rootNode ->children() ->arrayNode('routes') ->children() ->scalarNode('select')->isRequired()->end() ->scalarNode('create')->isRequired()->end() ->scalarNode('edit')->isRequired()->end() ->scalarNode('delete')->isRequired()->end() ->end() ->end() ->arrayNode('families') ->prototype('array') ->children(); $this->appendFamilyDefinition($familyDefinition); $familyDefinition->end() ->end() ->end() ->end(); return $treeBuilder; }
{@inheritdoc} @throws \RuntimeException
https://github.com/VincentChalnot/SidusEAVVariantBundle/blob/613222900c1608caf42db6576cb35215423b9127/DependencyInjection/Configuration.php#L20-L46
bavix/laravel-helpers
src/App/Http/Controllers/Controller.php
Controller.render
public function render($mixed, array $data = [], array $merge = []): Response { $view = view($mixed, $data, $merge); $response = new Response($view); if (!empty($this->cookies)) { foreach ($this->cookies as $cookie) { $response->withCookie($cookie); } } return $response; }
php
public function render($mixed, array $data = [], array $merge = []): Response { $view = view($mixed, $data, $merge); $response = new Response($view); if (!empty($this->cookies)) { foreach ($this->cookies as $cookie) { $response->withCookie($cookie); } } return $response; }
@param string $mixed @param array $data @param array $merge @return \Illuminate\Http\Response @throws \InvalidArgumentException
https://github.com/bavix/laravel-helpers/blob/a713460d2647a58b3eb8279d2a2726034ca79876/src/App/Http/Controllers/Controller.php#L31-L47
pmdevelopment/tool-bundle
Command/MigrationCommand.php
MigrationCommand.migrateAnnotationEncryption
private function migrateAnnotationEncryption(SymfonyStyle $helper) { $helper->note('The encrypted annotation uses mcrypt and therefore is deprecated. This migration will identify all entities using the old annotation, decrpyting with the old method and encrypt the value for the encryption annotation. After execution you have to replace the annotation.'); /** @var \ReflectionProperty[] $todo */ $todo = []; $classesWithoutNewAnnotation = []; $annotationsReader = $this->getContainer()->get('annotations.reader'); /* Get entites */ $classes = DoctrineHelper::getAllEntityClassNames($this->getDoctrineManager()); $helper->comment(sprintf('Found %d entities', count($classes))); /* Search for annotation */ foreach ($classes as $className) { $properties = DoctrineHelper::getPropertiesByAnnotation($className, Encrypted::class, $annotationsReader); if (0 < count($properties)) { $todo[$className] = $properties; } } if (0 === count($todo)) { $helper->success('Nothing to do.'); return true; } $helper->comment(sprintf('%d entities use the encrypted annotation', count($todo))); /* Disable Listener */ $subscriber = DoctrineHelper::getEventListener(EncryptionSubscriber::class, $this->getDoctrineManager()); if (null === $subscriber) { throw new \LogicException('Event Subscriber not found.'); } $this->getDoctrineManager()->getEventManager()->removeEventSubscriber($subscriber); $secret = $this->getContainer()->getParameter('pm__tool.configuration.doctrine.encryption'); $helper->comment(sprintf('Secret: %s', $secret)); $secretKey = substr(hash('sha256', $secret), 1, 32); /* Get Values */ foreach ($todo as $className => $properties) { $helper->section($className); $tableHeader = [ '#', ]; /** @var \ReflectionProperty $property */ foreach ($properties as $property) { $tableHeader[] = $property->getName(); if (false === DoctrineHelper::hasPropertyAnnotation($property, Encryption::class, $annotationsReader) && false === in_array($className, $classesWithoutNewAnnotation)) { $classesWithoutNewAnnotation[] = $className; } } $tableValues = []; $entites = $this->getDoctrine()->getRepository($className)->findAll(); foreach ($entites as $entity) { $tableRow = [ $entity->getId(), ]; foreach ($properties as $property) { $tableRow[] = CryptUtility::decrypt($property->getValue($entity), $secretKey); } $tableValues[] = $tableRow; } $helper->table($tableHeader, $tableValues); } /* Warnings for missing new annotation */ if (0 < count($classesWithoutNewAnnotation)) { $helper->warning( array_merge( [ 'The following classes have properties without the new annotation:', ], $classesWithoutNewAnnotation ) ); } /* Are you sure? */ if (false === $helper->confirm('Are you sure to reencrypt the shown values?', false)) { $helper->warning('Cancelled'); return false; } /* Encrypt values */ foreach ($todo as $className => $properties) { $entites = $this->getDoctrine()->getRepository($className)->findAll(); foreach ($entites as $entity) { foreach ($properties as $property) { /** @var Encryption|null $annotation */ $annotation = DoctrineHelper::getPropertyAnnotation($property, Encryption::class, $annotationsReader); if (null === $annotation) { $cipher = OpenSSLHelper::CIPHER_AES_256_CBC; } else { $cipher = $annotation->cipher; } $value = CryptUtility::decrypt($property->getValue($entity), $secretKey); $property->setValue($entity, OpenSSLHelper::encrypt($value, $secretKey, $cipher)); } $this->getDoctrineManager()->persist($entity); } } $this->getDoctrineManager()->flush(); $helper->success('Values changed. Please remove the old annotations now.'); return true; }
php
private function migrateAnnotationEncryption(SymfonyStyle $helper) { $helper->note('The encrypted annotation uses mcrypt and therefore is deprecated. This migration will identify all entities using the old annotation, decrpyting with the old method and encrypt the value for the encryption annotation. After execution you have to replace the annotation.'); /** @var \ReflectionProperty[] $todo */ $todo = []; $classesWithoutNewAnnotation = []; $annotationsReader = $this->getContainer()->get('annotations.reader'); /* Get entites */ $classes = DoctrineHelper::getAllEntityClassNames($this->getDoctrineManager()); $helper->comment(sprintf('Found %d entities', count($classes))); /* Search for annotation */ foreach ($classes as $className) { $properties = DoctrineHelper::getPropertiesByAnnotation($className, Encrypted::class, $annotationsReader); if (0 < count($properties)) { $todo[$className] = $properties; } } if (0 === count($todo)) { $helper->success('Nothing to do.'); return true; } $helper->comment(sprintf('%d entities use the encrypted annotation', count($todo))); /* Disable Listener */ $subscriber = DoctrineHelper::getEventListener(EncryptionSubscriber::class, $this->getDoctrineManager()); if (null === $subscriber) { throw new \LogicException('Event Subscriber not found.'); } $this->getDoctrineManager()->getEventManager()->removeEventSubscriber($subscriber); $secret = $this->getContainer()->getParameter('pm__tool.configuration.doctrine.encryption'); $helper->comment(sprintf('Secret: %s', $secret)); $secretKey = substr(hash('sha256', $secret), 1, 32); /* Get Values */ foreach ($todo as $className => $properties) { $helper->section($className); $tableHeader = [ '#', ]; /** @var \ReflectionProperty $property */ foreach ($properties as $property) { $tableHeader[] = $property->getName(); if (false === DoctrineHelper::hasPropertyAnnotation($property, Encryption::class, $annotationsReader) && false === in_array($className, $classesWithoutNewAnnotation)) { $classesWithoutNewAnnotation[] = $className; } } $tableValues = []; $entites = $this->getDoctrine()->getRepository($className)->findAll(); foreach ($entites as $entity) { $tableRow = [ $entity->getId(), ]; foreach ($properties as $property) { $tableRow[] = CryptUtility::decrypt($property->getValue($entity), $secretKey); } $tableValues[] = $tableRow; } $helper->table($tableHeader, $tableValues); } /* Warnings for missing new annotation */ if (0 < count($classesWithoutNewAnnotation)) { $helper->warning( array_merge( [ 'The following classes have properties without the new annotation:', ], $classesWithoutNewAnnotation ) ); } /* Are you sure? */ if (false === $helper->confirm('Are you sure to reencrypt the shown values?', false)) { $helper->warning('Cancelled'); return false; } /* Encrypt values */ foreach ($todo as $className => $properties) { $entites = $this->getDoctrine()->getRepository($className)->findAll(); foreach ($entites as $entity) { foreach ($properties as $property) { /** @var Encryption|null $annotation */ $annotation = DoctrineHelper::getPropertyAnnotation($property, Encryption::class, $annotationsReader); if (null === $annotation) { $cipher = OpenSSLHelper::CIPHER_AES_256_CBC; } else { $cipher = $annotation->cipher; } $value = CryptUtility::decrypt($property->getValue($entity), $secretKey); $property->setValue($entity, OpenSSLHelper::encrypt($value, $secretKey, $cipher)); } $this->getDoctrineManager()->persist($entity); } } $this->getDoctrineManager()->flush(); $helper->success('Values changed. Please remove the old annotations now.'); return true; }
Migrate Annotation Encrypted to Encryption @param SymfonyStyle $helper @return bool
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Command/MigrationCommand.php#L72-L197
phramework/phramework
src/Models/Cache.php
Cache.memcached
public static function memcached($key, $class, $function, $parameters = array(), $time = MEMCACHED_TIME_DEFAULT) { $data = false; $memcached = self::getInstance(); if ($memcached) { $key = self::$prefix . $key; $data = $memcached->get($key); if ($data) { return $data; } /* if( $memcached->getResultCode() != Memcached::RES_NOTSTORED ){ return $data; } */ } $data = call_user_func_array(array($class, $function), $parameters); if ($data && $memcached) { $memcached->set($key, $data, $time); // or die ("Failed to save data at the server"); } return $data; }
php
public static function memcached($key, $class, $function, $parameters = array(), $time = MEMCACHED_TIME_DEFAULT) { $data = false; $memcached = self::getInstance(); if ($memcached) { $key = self::$prefix . $key; $data = $memcached->get($key); if ($data) { return $data; } /* if( $memcached->getResultCode() != Memcached::RES_NOTSTORED ){ return $data; } */ } $data = call_user_func_array(array($class, $function), $parameters); if ($data && $memcached) { $memcached->set($key, $data, $time); // or die ("Failed to save data at the server"); } return $data; }
/* Access an memcached object using key if object is not available returns the data using the callback provided by $class, $function, $parameters @todo Rename @todo Use anonymous functions
https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/Models/Cache.php#L77-L100
4devs/serializer
Visibility/Version.php
Version.isVisibleProperty
public function isVisibleProperty($propertyName, array $options, array $context) { return !isset($context[$options['key']]) || Semver::satisfies($context[$options['key']], $options['version']); }
php
public function isVisibleProperty($propertyName, array $options, array $context) { return !isset($context[$options['key']]) || Semver::satisfies($context[$options['key']], $options['version']); }
{@inheritdoc}
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Visibility/Version.php#L21-L24
Tuna-CMS/tuna-bundle
src/Tuna/Bundle/FileBundle/Form/AttachmentType.php
AttachmentType.buildForm
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('position', HiddenType::class) ->add('file', FileType::class, [ 'button_label' => false, 'show_filename' => false, 'init_dropzone' => false, 'attr' => [ 'deletable' => false, ] ]) ->add('translations', GedmoTranslationsType::class, [ 'translatable_class' => Attachment::class, 'fields' => [ 'title' => [ 'required' => true, 'label' => false, 'attr' => [ 'placeholder' => 'ui.form.labels.attachment.title' ] ] ] ]); }
php
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('position', HiddenType::class) ->add('file', FileType::class, [ 'button_label' => false, 'show_filename' => false, 'init_dropzone' => false, 'attr' => [ 'deletable' => false, ] ]) ->add('translations', GedmoTranslationsType::class, [ 'translatable_class' => Attachment::class, 'fields' => [ 'title' => [ 'required' => true, 'label' => false, 'attr' => [ 'placeholder' => 'ui.form.labels.attachment.title' ] ] ] ]); }
{@inheritdoc}
https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/FileBundle/Form/AttachmentType.php#L17-L41
openclerk/users
src/UserOAuth2.php
UserOAuth2.tryLogin
static function tryLogin(\Db\Connection $db, OAuth2Providers $provider) { $user = UserOAuth2::auth($provider->getProvider()); if (!$user) { throw new UserAuthenticationException("Could not login user with OAuth2."); } $uid = $user->uid; if (!$uid) { throw new UserAuthenticationException("No UID found."); } // find the user with the uid $q = $db->prepare("SELECT users.* FROM users JOIN user_oauth2_identities ON users.id=user_oauth2_identities.user_id WHERE uid=? AND provider=? LIMIT 1"); $q->execute(array($uid, $provider->getKey())); if ($user_instance = $q->fetch()) { $result = new User($user_instance); $result->setIdentity($provider->getKey() . ":" . $uid); return $result; } else { // issue #266: If we are using Google, we might have an OpenID account that hasn't been connected yet, // in which case we can find it here and connect it if (isset($provider->getProvider()->id_token) && isset($provider->getProvider()->id_token['openid_id'])) { $id_token = $provider->getProvider()->id_token; $q = $db->prepare("SELECT * FROM user_openid_identities WHERE identity=?"); $q->execute(array($id_token['openid_id'])); if ($openid_identity = $q->fetch()) { // create a new identity $q = $db->prepare("INSERT INTO user_oauth2_identities SET user_id=?, provider=?, uid=?"); $q->execute(array($openid_identity['user_id'], $provider->getKey(), $uid)); return User::findUser($db, $openid_identity['user_id']); } } throw new UserAuthenticationMissingAccountException("No such '" . $provider->getKey() . "' user found."); } }
php
static function tryLogin(\Db\Connection $db, OAuth2Providers $provider) { $user = UserOAuth2::auth($provider->getProvider()); if (!$user) { throw new UserAuthenticationException("Could not login user with OAuth2."); } $uid = $user->uid; if (!$uid) { throw new UserAuthenticationException("No UID found."); } // find the user with the uid $q = $db->prepare("SELECT users.* FROM users JOIN user_oauth2_identities ON users.id=user_oauth2_identities.user_id WHERE uid=? AND provider=? LIMIT 1"); $q->execute(array($uid, $provider->getKey())); if ($user_instance = $q->fetch()) { $result = new User($user_instance); $result->setIdentity($provider->getKey() . ":" . $uid); return $result; } else { // issue #266: If we are using Google, we might have an OpenID account that hasn't been connected yet, // in which case we can find it here and connect it if (isset($provider->getProvider()->id_token) && isset($provider->getProvider()->id_token['openid_id'])) { $id_token = $provider->getProvider()->id_token; $q = $db->prepare("SELECT * FROM user_openid_identities WHERE identity=?"); $q->execute(array($id_token['openid_id'])); if ($openid_identity = $q->fetch()) { // create a new identity $q = $db->prepare("INSERT INTO user_oauth2_identities SET user_id=?, provider=?, uid=?"); $q->execute(array($openid_identity['user_id'], $provider->getKey(), $uid)); return User::findUser($db, $openid_identity['user_id']); } } throw new UserAuthenticationMissingAccountException("No such '" . $provider->getKey() . "' user found."); } }
Try logging in as a user with the given email and password. @param $redirect the registered redirect URI @return a valid {@link User} @throws UserAuthenticationException if the user could not be logged in, with a reason
https://github.com/openclerk/users/blob/550c7610c154a2f6655ce65a2df377ccb207bc6d/src/UserOAuth2.php#L20-L61
openclerk/users
src/UserOAuth2.php
UserOAuth2.auth
static function auth(ProviderInterface $provider) { if (!require_get("code", false)) { redirect($provider->getAuthorizationUrl()); return false; } else { // optionally check for abuse etc if (!\Openclerk\Events::trigger('oauth2_auth', $provider)) { throw new UserAuthenticationException("Login was cancelled by the system."); } $token = $provider->getAccessToken('authorization_code', array( 'code' => require_get("code"), )); // now find the relevant user return $provider->getUserDetails($token); } }
php
static function auth(ProviderInterface $provider) { if (!require_get("code", false)) { redirect($provider->getAuthorizationUrl()); return false; } else { // optionally check for abuse etc if (!\Openclerk\Events::trigger('oauth2_auth', $provider)) { throw new UserAuthenticationException("Login was cancelled by the system."); } $token = $provider->getAccessToken('authorization_code', array( 'code' => require_get("code"), )); // now find the relevant user return $provider->getUserDetails($token); } }
Execute OAuth2 authentication and return the user.
https://github.com/openclerk/users/blob/550c7610c154a2f6655ce65a2df377ccb207bc6d/src/UserOAuth2.php#L66-L83
openclerk/users
src/UserOAuth2.php
UserOAuth2.removeIdentity
static function removeIdentity(\Db\Connection $db, User $user, $provider, $uid) { if (!$user) { throw new \InvalidArgumentException("No user provided."); } $q = $db->prepare("DELETE FROM user_oauth2_identities WHERE user_id=? AND provider=? AND uid=? LIMIT 1"); return $q->execute(array($user->getId(), $provider, $uid)); }
php
static function removeIdentity(\Db\Connection $db, User $user, $provider, $uid) { if (!$user) { throw new \InvalidArgumentException("No user provided."); } $q = $db->prepare("DELETE FROM user_oauth2_identities WHERE user_id=? AND provider=? AND uid=? LIMIT 1"); return $q->execute(array($user->getId(), $provider, $uid)); }
Remove the given OAuth2 identity from the given user.
https://github.com/openclerk/users/blob/550c7610c154a2f6655ce65a2df377ccb207bc6d/src/UserOAuth2.php#L178-L186
heliopsis/ezforms-bundle
Heliopsis/eZFormsBundle/DependencyInjection/Compiler/ServiceAliasesPass.php
ServiceAliasesPass.process
public function process(ContainerBuilder $container) { $this->setServiceAlias( $container, HeliopsisEzFormsExtension::FACADE_SERVICE_ID ); $this->setServiceAlias( $container, HeliopsisEzFormsExtension::FORM_PROVIDER_SERVICE_ID ); $this->setServiceAlias( $container, HeliopsisEzFormsExtension::HANDLER_PROVIDER_SERVICE_ID ); $this->setServiceAlias( $container, HeliopsisEzFormsExtension::RESPONSE_PROVIDER_SERVICE_ID ); }
php
public function process(ContainerBuilder $container) { $this->setServiceAlias( $container, HeliopsisEzFormsExtension::FACADE_SERVICE_ID ); $this->setServiceAlias( $container, HeliopsisEzFormsExtension::FORM_PROVIDER_SERVICE_ID ); $this->setServiceAlias( $container, HeliopsisEzFormsExtension::HANDLER_PROVIDER_SERVICE_ID ); $this->setServiceAlias( $container, HeliopsisEzFormsExtension::RESPONSE_PROVIDER_SERVICE_ID ); }
You can modify the container here before it is dumped to PHP code. @param ContainerBuilder $container @api
https://github.com/heliopsis/ezforms-bundle/blob/ed87feeb76fcdcd4a4e355d4bc60b83077ba90b4/Heliopsis/eZFormsBundle/DependencyInjection/Compiler/ServiceAliasesPass.php#L28-L34
ddvphp/wechat
src/Wechat/PayLib/WxPayDataBase.php
WxPayDataBase.ToXml
public function ToXml() { if(!is_array($this->values) || count($this->values) <= 0) { throw new WxPayException("数组数据异常!"); } $xml = "<xml>"; foreach ($this->values as $key=>$val) { if (is_numeric($val)){ $xml.="<".$key.">".$val."</".$key.">"; }else{ $xml.="<".$key."><![CDATA[".$val."]]></".$key.">"; } } $xml.="</xml>"; return $xml; }
php
public function ToXml() { if(!is_array($this->values) || count($this->values) <= 0) { throw new WxPayException("数组数据异常!"); } $xml = "<xml>"; foreach ($this->values as $key=>$val) { if (is_numeric($val)){ $xml.="<".$key.">".$val."</".$key.">"; }else{ $xml.="<".$key."><![CDATA[".$val."]]></".$key.">"; } } $xml.="</xml>"; return $xml; }
输出xml字符 @throws WxPayException
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/src/Wechat/PayLib/WxPayDataBase.php#L52-L71
ddvphp/wechat
src/Wechat/PayLib/WxPayDataBase.php
WxPayDataBase.FromXml
public function FromXml($xml) { if(!$xml){ throw new WxPayException("xml数据异常!"); } //将XML转为array //禁止引用外部xml实体 libxml_disable_entity_loader(true); $this->values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $this->values; }
php
public function FromXml($xml) { if(!$xml){ throw new WxPayException("xml数据异常!"); } //将XML转为array //禁止引用外部xml实体 libxml_disable_entity_loader(true); $this->values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $this->values; }
将xml转为array @param string $xml @throws WxPayException
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/src/Wechat/PayLib/WxPayDataBase.php#L78-L88
ddvphp/wechat
src/Wechat/PayLib/WxPayDataBase.php
WxPayDataBase.ToUrlParams
public function ToUrlParams() { $buff = ""; foreach ($this->values as $k => $v) { if($k != "sign" && $v != "" && !is_array($v)){ $buff .= $k . "=" . $v . "&"; } } $buff = trim($buff, "&"); return $buff; }
php
public function ToUrlParams() { $buff = ""; foreach ($this->values as $k => $v) { if($k != "sign" && $v != "" && !is_array($v)){ $buff .= $k . "=" . $v . "&"; } } $buff = trim($buff, "&"); return $buff; }
格式化参数格式化成url参数
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/src/Wechat/PayLib/WxPayDataBase.php#L93-L105
ddvphp/wechat
src/Wechat/PayLib/WxPayDataBase.php
WxPayDataBase.MakeSign
public function MakeSign() { //签名步骤一:按字典序排序参数 ksort($this->values); $string = $this->ToUrlParams(); //签名步骤二:在string后加入KEY $string = $string . "&key=".WxPayConfig::$KEY; //签名步骤三:MD5加密 $string = md5($string); //签名步骤四:所有字符转为大写 $result = strtoupper($string); return $result; }
php
public function MakeSign() { //签名步骤一:按字典序排序参数 ksort($this->values); $string = $this->ToUrlParams(); //签名步骤二:在string后加入KEY $string = $string . "&key=".WxPayConfig::$KEY; //签名步骤三:MD5加密 $string = md5($string); //签名步骤四:所有字符转为大写 $result = strtoupper($string); return $result; }
生成签名 @return 签名,本函数不覆盖sign成员变量,如要设置签名需要调用SetSign方法赋值
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/src/Wechat/PayLib/WxPayDataBase.php#L111-L123
prooph/processing
library/Processor/LinearProcess.php
LinearProcess.perform
public function perform(WorkflowEngine $workflowEngine, WorkflowMessage $workflowMessage = null) { if (is_null($workflowMessage)) { $this->startWithoutMessage($workflowEngine); return; } $taskListEntry = $this->taskList->getNextNotStartedTaskListEntry(); if ($taskListEntry) { $this->recordThat(TaskEntryMarkedAsRunning::at($taskListEntry->taskListPosition())); if (! $this->isCorrectMessageFor($taskListEntry->task(), $workflowMessage)) { $this->receiveMessage( LogMessage::logWrongMessageReceivedFor( $taskListEntry->task(), $taskListEntry->taskListPosition(), $workflowMessage ), $workflowEngine ); return; } $this->performTask($taskListEntry->task(), $taskListEntry->taskListPosition(), $workflowEngine, $workflowMessage); return; } }
php
public function perform(WorkflowEngine $workflowEngine, WorkflowMessage $workflowMessage = null) { if (is_null($workflowMessage)) { $this->startWithoutMessage($workflowEngine); return; } $taskListEntry = $this->taskList->getNextNotStartedTaskListEntry(); if ($taskListEntry) { $this->recordThat(TaskEntryMarkedAsRunning::at($taskListEntry->taskListPosition())); if (! $this->isCorrectMessageFor($taskListEntry->task(), $workflowMessage)) { $this->receiveMessage( LogMessage::logWrongMessageReceivedFor( $taskListEntry->task(), $taskListEntry->taskListPosition(), $workflowMessage ), $workflowEngine ); return; } $this->performTask($taskListEntry->task(), $taskListEntry->taskListPosition(), $workflowEngine, $workflowMessage); return; } }
Start or continue the process with the help of given WorkflowEngine and optionally with given WorkflowMessage @param WorkflowEngine $workflowEngine @param WorkflowMessage $workflowMessage @return void
https://github.com/prooph/processing/blob/a2947bccbffeecc4ca93a15e38ab53814e3e53e5/library/Processor/LinearProcess.php#L37-L67
brainexe/core
src/Console/ClearCacheCommand.php
ClearCacheCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $output->write('Rebuild DIC...'); $this->rebuild->buildContainer(); $event = new ClearCacheEvent(); $this->dispatcher->dispatchEvent($event); @mkdir(ROOT . 'logs', 0744); @mkdir(ROOT . 'cache', 0744); $output->writeln('<info>done</info>'); }
php
protected function execute(InputInterface $input, OutputInterface $output) { $output->write('Rebuild DIC...'); $this->rebuild->buildContainer(); $event = new ClearCacheEvent(); $this->dispatcher->dispatchEvent($event); @mkdir(ROOT . 'logs', 0744); @mkdir(ROOT . 'cache', 0744); $output->writeln('<info>done</info>'); }
{@inheritdoc}
https://github.com/brainexe/core/blob/9ef69c6f045306abd20e271572386970db9b3e54/src/Console/ClearCacheCommand.php#L54-L66
open-orchestra/open-orchestra-display-bundle
DisplayBundle/Manager/NodeManager.php
NodeManager.getRouteDocumentName
public function getRouteDocumentName(array $parameters) { $siteId = array_key_exists('site', $parameters) && array_key_exists('siteId', $parameters['site']) ? $parameters['site']['siteId'] : $this->currentSiteManager->getSiteId(); $site = $this->siteRepository->findOneBySiteId($siteId); $siteAlias = array_key_exists('site', $parameters) && array_key_exists('aliasId', $parameters['site']) ? $site->getAliases()[$parameters['site']['aliasId']] : $site->getMainAlias(); $language = $siteAlias->getLanguage(); $node = $this->nodeRepository->findOnePublished($parameters['site']['nodeId'], $language, $siteId); if (!$node instanceof ReadNodeInterface) { throw new NodeNotFoundException(); } return $site->getAliases()->indexOf($siteAlias) . '_' . $node->getId(); }
php
public function getRouteDocumentName(array $parameters) { $siteId = array_key_exists('site', $parameters) && array_key_exists('siteId', $parameters['site']) ? $parameters['site']['siteId'] : $this->currentSiteManager->getSiteId(); $site = $this->siteRepository->findOneBySiteId($siteId); $siteAlias = array_key_exists('site', $parameters) && array_key_exists('aliasId', $parameters['site']) ? $site->getAliases()[$parameters['site']['aliasId']] : $site->getMainAlias(); $language = $siteAlias->getLanguage(); $node = $this->nodeRepository->findOnePublished($parameters['site']['nodeId'], $language, $siteId); if (!$node instanceof ReadNodeInterface) { throw new NodeNotFoundException(); } return $site->getAliases()->indexOf($siteAlias) . '_' . $node->getId(); }
@param array $parameters @return string @throw NodeNotFoundException
https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/Manager/NodeManager.php#L40-L54
PHPColibri/framework
Database/Query.php
Query.select
public static function select(array $columns = ['*'], ...$joinsColumns) { $query = new static(Query\Type::SELECT); $query->columns['t'] = $columns; $alias = 'j1'; foreach ($joinsColumns as $joinColumns) { $query->columns[$alias] = (array)$joinColumns; $alias++; } return $query; }
php
public static function select(array $columns = ['*'], ...$joinsColumns) { $query = new static(Query\Type::SELECT); $query->columns['t'] = $columns; $alias = 'j1'; foreach ($joinsColumns as $joinColumns) { $query->columns[$alias] = (array)$joinColumns; $alias++; } return $query; }
Creates instance of select-type Query. @param array $columns @param array $joinsColumns @return static
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Database/Query.php#L68-L80
PHPColibri/framework
Database/Query.php
Query.configureClauses
private static function configureClauses(array $where, $type = 'and') { if ( ! in_array($type, ['and', 'or'])) { throw new \InvalidArgumentException('where-type must be `and` or `or`'); } $whereClauses = []; foreach ($where as $name => $value) { $nameAndOp = explode(' ', $name, 2); $name = $nameAndOp[0]; $operator = $nameAndOp[1] ?? ($value === null ? 'is' : '='); $alias = self::cutAlias($name); $whereClauses[] = [$name, $value, $operator, $alias]; } return [$type => $whereClauses]; }
php
private static function configureClauses(array $where, $type = 'and') { if ( ! in_array($type, ['and', 'or'])) { throw new \InvalidArgumentException('where-type must be `and` or `or`'); } $whereClauses = []; foreach ($where as $name => $value) { $nameAndOp = explode(' ', $name, 2); $name = $nameAndOp[0]; $operator = $nameAndOp[1] ?? ($value === null ? 'is' : '='); $alias = self::cutAlias($name); $whereClauses[] = [$name, $value, $operator, $alias]; } return [$type => $whereClauses]; }
@param array $where array('column [op]' => value, ...) @param string $type one of 'and'|'or' @return array @throws \InvalidArgumentException
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Database/Query.php#L127-L143
PHPColibri/framework
Database/Query.php
Query.cutAlias
private static function cutAlias(string &$column): string { $aliasAndColumn = explode('.', $column); if (count($aliasAndColumn) === 2) { $alias = $aliasAndColumn[0]; $column = $aliasAndColumn[1]; } else { $alias = 't'; $column = $aliasAndColumn[0]; } return $alias; }
php
private static function cutAlias(string &$column): string { $aliasAndColumn = explode('.', $column); if (count($aliasAndColumn) === 2) { $alias = $aliasAndColumn[0]; $column = $aliasAndColumn[1]; } else { $alias = 't'; $column = $aliasAndColumn[0]; } return $alias; }
@param string $column @return string
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Database/Query.php#L150-L162
PHPColibri/framework
Database/Query.php
Query.count
public function count(string $column = '*', string $as = null) { $this->columns = [ '' => [Query\Aggregation::count($column, $as)], ]; return $this; }
php
public function count(string $column = '*', string $as = null) { $this->columns = [ '' => [Query\Aggregation::count($column, $as)], ]; return $this; }
@param string $column @param string|null $as @return $this
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Database/Query.php#L173-L180
PHPColibri/framework
Database/Query.php
Query.join
public function join(string $table, string $column, string $toColumn, string $type = Query\JoinType::LEFT) { $alias = $this->joinCurrentAlias++; $toAlias = self::cutAlias($toColumn); $this->joins[$alias] = [ 'type' => $type, 'table' => $table, 'column' => $column, 'to' => [$toAlias, $toColumn], ]; return $this; }
php
public function join(string $table, string $column, string $toColumn, string $type = Query\JoinType::LEFT) { $alias = $this->joinCurrentAlias++; $toAlias = self::cutAlias($toColumn); $this->joins[$alias] = [ 'type' => $type, 'table' => $table, 'column' => $column, 'to' => [$toAlias, $toColumn], ]; return $this; }
@param string $table @param string $column @param string $toColumn @param string $type @return $this
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Database/Query.php#L214-L228
PHPColibri/framework
Database/Query.php
Query.set
public function set(array $values) { foreach ($values as $column => &$value) { $value = [ 'alias' => self::cutAlias($column), 'column' => $column, 'value' => $value, ]; } $this->values = $this->values === null ? $values : array_replace($this->values, $values); return $this; }
php
public function set(array $values) { foreach ($values as $column => &$value) { $value = [ 'alias' => self::cutAlias($column), 'column' => $column, 'value' => $value, ]; } $this->values = $this->values === null ? $values : array_replace($this->values, $values); return $this; }
@param array $values @return $this
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Database/Query.php#L235-L248
PHPColibri/framework
Database/Query.php
Query.where
final public function where(array $where, $type = 'and') { $where = self::configureClauses($where, $type); if ($this->where === null) { $this->where = $where; return $this; } if (isset($this->where[$type])) { $this->where[$type] = array_merge($this->where[$type], $where[$type]); } else { $this->where = $type == 'or' ? ['and' => array_merge($this->where['and'], [['or', $where['or']]])] : ['and' => array_merge($where['and'], [['or', $this->where['or']]])]; } return $this; }
php
final public function where(array $where, $type = 'and') { $where = self::configureClauses($where, $type); if ($this->where === null) { $this->where = $where; return $this; } if (isset($this->where[$type])) { $this->where[$type] = array_merge($this->where[$type], $where[$type]); } else { $this->where = $type == 'or' ? ['and' => array_merge($this->where['and'], [['or', $where['or']]])] : ['and' => array_merge($where['and'], [['or', $this->where['or']]])]; } return $this; }
@param array $where array('column [op]' => value, ...) @param string $type one of 'and'|'or' @return $this @throws \InvalidArgumentException
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Database/Query.php#L258-L276
PHPColibri/framework
Database/Query.php
Query.limit
final public function limit(int $offsetOrCount, int $count = null) { if ($count === null) { $this->limit['offset'] = 0; $this->limit['count'] = $offsetOrCount; } else { $this->limit['offset'] = $offsetOrCount; $this->limit['count'] = $count; } return $this; }
php
final public function limit(int $offsetOrCount, int $count = null) { if ($count === null) { $this->limit['offset'] = 0; $this->limit['count'] = $offsetOrCount; } else { $this->limit['offset'] = $offsetOrCount; $this->limit['count'] = $count; } return $this; }
@param int $offsetOrCount @param int $count @return $this
https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Database/Query.php#L321-L332
valu-digital/valuso
src/ValuSo/Broker/ServicePluginManagerConfig.php
ServicePluginManagerConfig.configureServiceManager
public function configureServiceManager(ServiceManager $serviceManager) { foreach ($this->initializers as $name => $initializer) { $serviceManager->addInitializer($initializer); } foreach ($this->invokables as $name => $class) { $serviceManager->setInvokableClass($name, $class); } foreach ($this->factories as $name => $factoryClass) { $serviceManager->setFactory($name, $factoryClass); } foreach ($this->abstractFactories as $factoryClass) { $serviceManager->addAbstractFactory($factoryClass); } foreach ($this->aliases as $name => $service) { $serviceManager->setAlias($name, $service); } foreach ($this->shared as $name => $value) { $serviceManager->setShared($name, $value); } if ($this->cache && (is_array($this->cache) || $this->cache instanceof \Traversable)) { $cache = StorageFactory::factory($this->cache); $serviceManager->setCache($cache); } elseif ($this->cache && $this->cache instanceof StorageInterface) { $serviceManager->setCache($this->cache); } if ($this->proxyDir) { $serviceManager->setProxyDir($this->proxyDir); } if ($this->proxyNs) { $serviceManager->setProxyNs($this->proxyNs); } if ($this->proxyAutoCreateStrategy) { $serviceManager->setProxyAutoCreateStrategy($this->proxyAutoCreateStrategy); } }
php
public function configureServiceManager(ServiceManager $serviceManager) { foreach ($this->initializers as $name => $initializer) { $serviceManager->addInitializer($initializer); } foreach ($this->invokables as $name => $class) { $serviceManager->setInvokableClass($name, $class); } foreach ($this->factories as $name => $factoryClass) { $serviceManager->setFactory($name, $factoryClass); } foreach ($this->abstractFactories as $factoryClass) { $serviceManager->addAbstractFactory($factoryClass); } foreach ($this->aliases as $name => $service) { $serviceManager->setAlias($name, $service); } foreach ($this->shared as $name => $value) { $serviceManager->setShared($name, $value); } if ($this->cache && (is_array($this->cache) || $this->cache instanceof \Traversable)) { $cache = StorageFactory::factory($this->cache); $serviceManager->setCache($cache); } elseif ($this->cache && $this->cache instanceof StorageInterface) { $serviceManager->setCache($this->cache); } if ($this->proxyDir) { $serviceManager->setProxyDir($this->proxyDir); } if ($this->proxyNs) { $serviceManager->setProxyNs($this->proxyNs); } if ($this->proxyAutoCreateStrategy) { $serviceManager->setProxyAutoCreateStrategy($this->proxyAutoCreateStrategy); } }
Configure the provided service manager instance with the configuration in this class. In addition to using each of the internal properties to configure the service manager, also adds an initializer to inject ServiceManagerAware and ServiceLocatorAware classes with the service manager. @param ServiceManager $serviceManager @return void
https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServicePluginManagerConfig.php#L157-L201
Elephant418/Staq
src/Staq/App/BackOffice/Stack/Controller/Model.php
Model.actionList
public function actionList($type) { $view = $this->createView('list', $type); $fields = (new \Stack\Setting) ->parse('BackOffice') ->get('list.' . $type); if (empty($fields)) { $fields = ['name()']; } $view['fields'] = $fields; $view['models'] = $this->getNewEntity($type)->fetchAll(); return $view; }
php
public function actionList($type) { $view = $this->createView('list', $type); $fields = (new \Stack\Setting) ->parse('BackOffice') ->get('list.' . $type); if (empty($fields)) { $fields = ['name()']; } $view['fields'] = $fields; $view['models'] = $this->getNewEntity($type)->fetchAll(); return $view; }
/* ACTION METHODS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/App/BackOffice/Stack/Controller/Model.php#L13-L25
Elephant418/Staq
src/Staq/App/BackOffice/Stack/Controller/Model.php
Model.createView
protected function createView($action, $type) { $view = (new \Stack\View)->byName($type, 'Model_' . ucfirst($action)); $view['controller'] = $type; $view['controllerAction'] = $action; return $view; }
php
protected function createView($action, $type) { $view = (new \Stack\View)->byName($type, 'Model_' . ucfirst($action)); $view['controller'] = $type; $view['controllerAction'] = $action; return $view; }
/* PRIVATE METHODS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/App/BackOffice/Stack/Controller/Model.php#L77-L83
Elephant418/Staq
src/Staq/App/BackOffice/Stack/Controller/Model.php
Model.redirectPreview
protected function redirectPreview($type, $model) { $params = []; $params['type'] = $type; $params['id'] = $model->id; \Staq\Util::httpRedirectUri(\Staq::App()->getUri($this, 'preview', $params)); }
php
protected function redirectPreview($type, $model) { $params = []; $params['type'] = $type; $params['id'] = $model->id; \Staq\Util::httpRedirectUri(\Staq::App()->getUri($this, 'preview', $params)); }
/* REDIRECT METHODS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/App/BackOffice/Stack/Controller/Model.php#L114-L120
UnionOfRAD/li3_quality
qa/rules/syntax/HasCorrectInlineHTML.php
HasCorrectInlineHTML.apply
public function apply($testable, array $config = array()) { $message = 'Inline HTML should be in the following format: "<?=$var; ?>"'; $lines = $testable->lines(); $tokens = $testable->tokens(); $lineCache = $testable->lineCache(); $matches = array(); foreach ($lines as $lineNumber => $line) { $lineTokens = isset($lineCache[$lineNumber]) ? $lineCache[$lineNumber] : array(); if ($this->hasRequiredTokens($tokens, $lineTokens)) { preg_match_all($this->findPattern, $line, $matches); foreach ($matches as $match) { if (isset($match[0]) && preg_match($this->matchPattern, $match[0]) === 0) { $this->addViolation(array( 'message' => $message, 'line' => $lineNumber, )); } } } } }
php
public function apply($testable, array $config = array()) { $message = 'Inline HTML should be in the following format: "<?=$var; ?>"'; $lines = $testable->lines(); $tokens = $testable->tokens(); $lineCache = $testable->lineCache(); $matches = array(); foreach ($lines as $lineNumber => $line) { $lineTokens = isset($lineCache[$lineNumber]) ? $lineCache[$lineNumber] : array(); if ($this->hasRequiredTokens($tokens, $lineTokens)) { preg_match_all($this->findPattern, $line, $matches); foreach ($matches as $match) { if (isset($match[0]) && preg_match($this->matchPattern, $match[0]) === 0) { $this->addViolation(array( 'message' => $message, 'line' => $lineNumber, )); } } } } }
Will iterate the lines until it finds one with $requiredTokens Once found it will find all short tags using $findPattern and match against them using $matchedPattern @param Testable $testable The testable object @return void
https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/qa/rules/syntax/HasCorrectInlineHTML.php#L50-L70
UnionOfRAD/li3_quality
qa/rules/syntax/HasCorrectInlineHTML.php
HasCorrectInlineHTML.hasRequiredTokens
public function hasRequiredTokens(array $tokens, array $tokenIds) { foreach ($tokenIds as $id) { if (in_array($tokens[$id]['id'], $this->requiredTokens)) { return true; } } return false; }
php
public function hasRequiredTokens(array $tokens, array $tokenIds) { foreach ($tokenIds as $id) { if (in_array($tokens[$id]['id'], $this->requiredTokens)) { return true; } } return false; }
Will let me know if the given $line has one of the $requiredTokens in it @param array $tokens The tokens from $testable->tokens() @param array $tokenIds The ids of tokens for the line to search for @return boolean
https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/qa/rules/syntax/HasCorrectInlineHTML.php#L79-L86
schpill/thin
src/Temp.php
Temp.getTmpPath
protected function getTmpPath() { $tmpDir = sys_get_temp_dir(); if (!empty($this->prefix)) { $tmpDir .= DIRECTORY_SEPARATOR . $this->prefix; } $tmpDir .= DIRECTORY_SEPARATOR . uniqid('run-', true); return $tmpDir; }
php
protected function getTmpPath() { $tmpDir = sys_get_temp_dir(); if (!empty($this->prefix)) { $tmpDir .= DIRECTORY_SEPARATOR . $this->prefix; } $tmpDir .= DIRECTORY_SEPARATOR . uniqid('run-', true); return $tmpDir; }
Get path to temp directory @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Temp.php#L64-L75
schpill/thin
src/Temp.php
Temp.createTmpFile
public function createTmpFile($suffix = null, $preserve = false) { $this->initRunFolder(); $file = uniqid(); if ($suffix) { $file .= '-' . $suffix; } $fileInfo = new \SplFileInfo($this->tmpRunFolder . DIRECTORY_SEPARATOR . $file); $this->filesystem->touch($fileInfo); $this->files[] = array( 'file' => $fileInfo, 'preserve' => $preserve ); $this->filesystem->chmod($fileInfo, 0600); return $fileInfo; }
php
public function createTmpFile($suffix = null, $preserve = false) { $this->initRunFolder(); $file = uniqid(); if ($suffix) { $file .= '-' . $suffix; } $fileInfo = new \SplFileInfo($this->tmpRunFolder . DIRECTORY_SEPARATOR . $file); $this->filesystem->touch($fileInfo); $this->files[] = array( 'file' => $fileInfo, 'preserve' => $preserve ); $this->filesystem->chmod($fileInfo, 0600); return $fileInfo; }
Create empty file in TMP directory @param string $suffix filename suffix @param bool $preserve @throws \Exception @return \SplFileInfo
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Temp.php#L95-L116
schpill/thin
src/Temp.php
Temp.createFile
public function createFile($fileName, $preserve = false) { $this->initRunFolder(); $fileInfo = new \SplFileInfo($this->tmpRunFolder . DIRECTORY_SEPARATOR . $fileName); $this->filesystem->touch($fileInfo); $this->files[] = array( 'file' => $fileInfo, 'preserve' => $preserve ); $this->filesystem->chmod($fileInfo, 0600); return $fileInfo; }
php
public function createFile($fileName, $preserve = false) { $this->initRunFolder(); $fileInfo = new \SplFileInfo($this->tmpRunFolder . DIRECTORY_SEPARATOR . $fileName); $this->filesystem->touch($fileInfo); $this->files[] = array( 'file' => $fileInfo, 'preserve' => $preserve ); $this->filesystem->chmod($fileInfo, 0600); return $fileInfo; }
Creates named temporary file @param $fileName @param bool $preserve @return \SplFileInfo @throws \Exception
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Temp.php#L126-L142
Vyki/mva-dbm
src/Mva/Dbm/Query/QueryProcessor.php
QueryProcessor.processUpdate
public function processUpdate(array $data) { $set = $this->formatCmd('set'); $data[$set] = isset($data[$set]) ? $data[$set] : []; foreach ($data as $index => $value) { if (substr($index, 0, 1) !== $this->cmd) { $data[$set][$index] = $value; unset($data[$index]); continue; } $ckey = substr($index, 1); if ($ckey === 'unset') { $data[$index] = array_fill_keys(array_values((array) $value), ''); } elseif (in_array($ckey, ['setOnInsert', 'addToSet', 'push'])) { $data[$index] = $this->processData($value); } } if (empty($data[$set])) { unset($data[$set]); } else { $data[$set] = $this->processData($data[$set]); } return $data; }
php
public function processUpdate(array $data) { $set = $this->formatCmd('set'); $data[$set] = isset($data[$set]) ? $data[$set] : []; foreach ($data as $index => $value) { if (substr($index, 0, 1) !== $this->cmd) { $data[$set][$index] = $value; unset($data[$index]); continue; } $ckey = substr($index, 1); if ($ckey === 'unset') { $data[$index] = array_fill_keys(array_values((array) $value), ''); } elseif (in_array($ckey, ['setOnInsert', 'addToSet', 'push'])) { $data[$index] = $this->processData($value); } } if (empty($data[$set])) { unset($data[$set]); } else { $data[$set] = $this->processData($data[$set]); } return $data; }
Process update data @param array ['a' => 1, 'b%s' => 2, '$set' => ['c%i' => '3'], '$unset' => ['d', 'e'], ...] @return array ['$set' => ['a' => 1, 'b' => '2', 'c' => 3], '$unset' => ['d' => '', 'e' => ''], ...]
https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryProcessor.php#L98-L128
Vyki/mva-dbm
src/Mva/Dbm/Query/QueryProcessor.php
QueryProcessor.processCondition
public function processCondition(array $conditions, $depth = 0) { if (empty($conditions)) { return []; } $parsed = []; foreach ($conditions as $key => $condition) { if (is_int($key)) { if ($depth > 0 && is_array($condition)) { throw new InvalidArgumentException('Too deep sets of condition!'); } if (is_array($condition)) { $parsed = array_merge($parsed, $this->processCondition($condition, $depth + 1)); } else { $parsed[] = $this->parseCondition($condition); } } else { $parsed[] = $this->parseCondition($key, $condition); } } return $depth > 0 ? $parsed : (count($parsed) > 1 ? [$this->formatCmd('and') => $parsed] : $parsed[0]); }
php
public function processCondition(array $conditions, $depth = 0) { if (empty($conditions)) { return []; } $parsed = []; foreach ($conditions as $key => $condition) { if (is_int($key)) { if ($depth > 0 && is_array($condition)) { throw new InvalidArgumentException('Too deep sets of condition!'); } if (is_array($condition)) { $parsed = array_merge($parsed, $this->processCondition($condition, $depth + 1)); } else { $parsed[] = $this->parseCondition($condition); } } else { $parsed[] = $this->parseCondition($key, $condition); } } return $depth > 0 ? $parsed : (count($parsed) > 1 ? [$this->formatCmd('and') => $parsed] : $parsed[0]); }
Process sets of conditions and merges them by AND operator @param array in format [['a' => 1], ['b IN' => [1, 2]], [...]] or ['a' => 1, 'b IN' => [1, 2], ...] @param array single condition ['a' => 1] or multiple condition ['$and' => ['a' => 1, 'b' => ['$in' => [1, 2]]], ...]
https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryProcessor.php#L135-L159
Vyki/mva-dbm
src/Mva/Dbm/Query/QueryProcessor.php
QueryProcessor.parseCondition
private function parseCondition($condition, $parameters = []) { if (strpos($condition, ' ')) { $match = preg_match('~^ (.+)\s ## identifier ( (?:\$\w+) | ## $mongoOperator (?:[A-Z]+(?:_[A-Z]+)*) | ## NAMED_OPERATOR or (?:[\<\>\!]?\=|\>|\<\>?) ## logical operator ) (?: \s%(\w+(?:\[\])?) | ## modifier or \s(.+) ## value )?$~xs', $condition, $cond); //['cond IN' => [...]], ['cond = %s' => 'param'], ['cond $gt' => 20] if (!empty($match)) { if (substr($cond[1], 0, 1) === $this->cmd) { throw new InvalidArgumentException("Field name cannot start with '{$this->cmd}'"); } if ($parameters === [] && !isset($cond[4])) { throw new InvalidArgumentException("Missing value for item '{$cond[1]}'"); } return $this->formatCondition($cond[1], trim($cond[2], $this->cmd), isset($cond[4]) ? $cond[4] : $parameters, isset($cond[3]) ? $cond[3] : NULL); } } if ($parameters === []) { throw new InvalidArgumentException("Missing value for item '{$condition}'"); } if (is_array($parameters) && ($value = reset($parameters))) { //['$cond' => $param[]] if (substr($condition, 0, 1) === $this->cmd) { return [$condition => $this->parseDeepCondition($parameters, TRUE)]; } //['cond' => ['param', ...]] if (substr($key = key($parameters), 0, 1) !== $this->cmd) { return $this->formatCondition($condition, 'IN', $parameters); } //['cond' => ['$param' => [...]]] if (is_array($value)) { return [$condition => [$key => $this->parseDeepCondition($value)]]; } } // [cond => param] return [$condition => $parameters]; }
php
private function parseCondition($condition, $parameters = []) { if (strpos($condition, ' ')) { $match = preg_match('~^ (.+)\s ## identifier ( (?:\$\w+) | ## $mongoOperator (?:[A-Z]+(?:_[A-Z]+)*) | ## NAMED_OPERATOR or (?:[\<\>\!]?\=|\>|\<\>?) ## logical operator ) (?: \s%(\w+(?:\[\])?) | ## modifier or \s(.+) ## value )?$~xs', $condition, $cond); //['cond IN' => [...]], ['cond = %s' => 'param'], ['cond $gt' => 20] if (!empty($match)) { if (substr($cond[1], 0, 1) === $this->cmd) { throw new InvalidArgumentException("Field name cannot start with '{$this->cmd}'"); } if ($parameters === [] && !isset($cond[4])) { throw new InvalidArgumentException("Missing value for item '{$cond[1]}'"); } return $this->formatCondition($cond[1], trim($cond[2], $this->cmd), isset($cond[4]) ? $cond[4] : $parameters, isset($cond[3]) ? $cond[3] : NULL); } } if ($parameters === []) { throw new InvalidArgumentException("Missing value for item '{$condition}'"); } if (is_array($parameters) && ($value = reset($parameters))) { //['$cond' => $param[]] if (substr($condition, 0, 1) === $this->cmd) { return [$condition => $this->parseDeepCondition($parameters, TRUE)]; } //['cond' => ['param', ...]] if (substr($key = key($parameters), 0, 1) !== $this->cmd) { return $this->formatCondition($condition, 'IN', $parameters); } //['cond' => ['$param' => [...]]] if (is_array($value)) { return [$condition => [$key => $this->parseDeepCondition($value)]]; } } // [cond => param] return [$condition => $parameters]; }
Parses single condition @param $condition string @param $parameters mixed @throws InvalidArgumentException
https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryProcessor.php#L167-L219
Vyki/mva-dbm
src/Mva/Dbm/Query/QueryProcessor.php
QueryProcessor.parseDeepCondition
private function parseDeepCondition(array $parameters, $toArray = FALSE) { $opcond = []; foreach ($parameters as $key => $param) { $ccond = is_int($key) ? $this->parseCondition($param) : $this->parseCondition($key, $param); if ($toArray) { $opcond[] = $ccond; } else { reset($ccond); $opcond[key($ccond)] = current($ccond); } } return $opcond; }
php
private function parseDeepCondition(array $parameters, $toArray = FALSE) { $opcond = []; foreach ($parameters as $key => $param) { $ccond = is_int($key) ? $this->parseCondition($param) : $this->parseCondition($key, $param); if ($toArray) { $opcond[] = $ccond; } else { reset($ccond); $opcond[key($ccond)] = current($ccond); } } return $opcond; }
Parses inner conditions @param array @param bool indicates that output should be list
https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryProcessor.php#L226-L242
Vyki/mva-dbm
src/Mva/Dbm/Query/QueryProcessor.php
QueryProcessor.formatCondition
private function formatCondition($identifier, $operator, $value, $modifier = NULL) { $operator = strtolower($operator); if ($operator === 'like') { $value = $this->processLikeOperator($value); $modifier = 're'; } $value = $modifier ? $this->processModifier($modifier, $value) : $value; //tries to translate operator if (array_key_exists($operator, $this->operators)) { $operator = $this->operators[$operator]; } if ($operator === '=') { return [$identifier => $value]; } //$in and $nin need to reset keys if ($operator === 'in' || $operator === 'nin') { $value = array_values((array) $value); } //parses inner condition in $elemMatch if ($operator === 'elem_match' && is_array($value)) { $value = $this->parseDeepCondition($value); } //translates SQL like operator to mongo format ELEM_MATCH => $elemMatch if (strpos($operator, '_') !== FALSE) { $operator = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $operator)))); } return [(string) $identifier => [$this->formatCmd($operator) => $value]]; }
php
private function formatCondition($identifier, $operator, $value, $modifier = NULL) { $operator = strtolower($operator); if ($operator === 'like') { $value = $this->processLikeOperator($value); $modifier = 're'; } $value = $modifier ? $this->processModifier($modifier, $value) : $value; //tries to translate operator if (array_key_exists($operator, $this->operators)) { $operator = $this->operators[$operator]; } if ($operator === '=') { return [$identifier => $value]; } //$in and $nin need to reset keys if ($operator === 'in' || $operator === 'nin') { $value = array_values((array) $value); } //parses inner condition in $elemMatch if ($operator === 'elem_match' && is_array($value)) { $value = $this->parseDeepCondition($value); } //translates SQL like operator to mongo format ELEM_MATCH => $elemMatch if (strpos($operator, '_') !== FALSE) { $operator = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $operator)))); } return [(string) $identifier => [$this->formatCmd($operator) => $value]]; }
Formats condition @param string item identifier @param string operator @param mixed value @param string modifier
https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryProcessor.php#L251-L287
Vyki/mva-dbm
src/Mva/Dbm/Query/QueryProcessor.php
QueryProcessor.processData
public function processData(array $data, $expand = FALSE) { $return = []; foreach ($data as $key => $item) { list($modified, $key) = $this->doubledModifier($key, '%'); if ($modified && preg_match('#^(.*)%(\w+(?:\[\])?)$#', $key, $parts)) { $key = $parts[1]; $item = $this->processModifier($parts[2], $item); } elseif ($item instanceof \DateTime || $item instanceof \DateTimeImmutable) { $item = $this->processModifier('dt', $item); } elseif (is_array($item)) { $item = $this->processData($item); } if ($expand && strpos($key, '.') !== FALSE) { Helpers::expandRow($return, $key, $item); } else { $return[$key] = $item; } } return $return; }
php
public function processData(array $data, $expand = FALSE) { $return = []; foreach ($data as $key => $item) { list($modified, $key) = $this->doubledModifier($key, '%'); if ($modified && preg_match('#^(.*)%(\w+(?:\[\])?)$#', $key, $parts)) { $key = $parts[1]; $item = $this->processModifier($parts[2], $item); } elseif ($item instanceof \DateTime || $item instanceof \DateTimeImmutable) { $item = $this->processModifier('dt', $item); } elseif (is_array($item)) { $item = $this->processData($item); } if ($expand && strpos($key, '.') !== FALSE) { Helpers::expandRow($return, $key, $item); } else { $return[$key] = $item; } } return $return; }
Formats data types by modifiers @param array ['name' => 'roman', 'age%i' => '27', 'numbers%i[]' => ['1', 2, 2.3]] @return array
https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryProcessor.php#L294-L318
Vyki/mva-dbm
src/Mva/Dbm/Query/QueryProcessor.php
QueryProcessor.processModifier
public function processModifier($type, $value) { switch (gettype($value)) { case 'string': switch ($type) { case 'b': if (in_array($value, ['TRUE', 'FALSE'])) { return $value === 'TRUE'; } break; case 're': return $this->driver->convertToDriver($value, IDriver::TYPE_REGEXP); } case 'integer': case 'double': case 'boolean': switch ($type) { case 'any': case 's': return (string) $value; case 'i': return (int) ($value + 0); case 'f': return (float) $value; case 'dt': return $this->driver->convertToDriver(is_numeric($value) ? (int) $value : strtotime((string) $value), IDriver::TYPE_DATETIME); case 'ts': return $this->driver->convertToDriver(is_numeric($value) ? (int) $value : strtotime((string) $value), IDriver::TYPE_TIMESTAMP); case 'b': return (bool) $value; case 'oid': return $this->driver->convertToDriver((string) $value, IDriver::TYPE_OID); } break; case 'NULL': return NULL; case 'object': if ($value instanceof \DateTimeInterface) { switch ($type) { case 'dt': return $this->driver->convertToDriver((int) $value->format('U'), IDriver::TYPE_DATETIME); case 'ts': return $this->driver->convertToDriver((int) $value->format('U'), IDriver::TYPE_TIMESTAMP); case 'any': case 's': return $value->format('Y-m-d H:i:s'); case 'i': return (int) $value->format('U'); case 'f': return (float) $value->format('U'); } } if (($return = $this->driver->convertToDriver($value, $type)) !== $value) { return $return; } if (method_exists($value, '__toString')) { $str_value = (string) $value; switch ($type) { case 'any': case 's': return $str_value; case 'i': return (int) ($str_value + 0); case 'f': return (float) $str_value; case 'b': return (bool) $str_value; } } break; case 'array': if (substr($type, -1) === ']' || $type === 'any') { $this->processArray(trim($type, '[]'), $value); return $value; } break; default: return $value; } }
php
public function processModifier($type, $value) { switch (gettype($value)) { case 'string': switch ($type) { case 'b': if (in_array($value, ['TRUE', 'FALSE'])) { return $value === 'TRUE'; } break; case 're': return $this->driver->convertToDriver($value, IDriver::TYPE_REGEXP); } case 'integer': case 'double': case 'boolean': switch ($type) { case 'any': case 's': return (string) $value; case 'i': return (int) ($value + 0); case 'f': return (float) $value; case 'dt': return $this->driver->convertToDriver(is_numeric($value) ? (int) $value : strtotime((string) $value), IDriver::TYPE_DATETIME); case 'ts': return $this->driver->convertToDriver(is_numeric($value) ? (int) $value : strtotime((string) $value), IDriver::TYPE_TIMESTAMP); case 'b': return (bool) $value; case 'oid': return $this->driver->convertToDriver((string) $value, IDriver::TYPE_OID); } break; case 'NULL': return NULL; case 'object': if ($value instanceof \DateTimeInterface) { switch ($type) { case 'dt': return $this->driver->convertToDriver((int) $value->format('U'), IDriver::TYPE_DATETIME); case 'ts': return $this->driver->convertToDriver((int) $value->format('U'), IDriver::TYPE_TIMESTAMP); case 'any': case 's': return $value->format('Y-m-d H:i:s'); case 'i': return (int) $value->format('U'); case 'f': return (float) $value->format('U'); } } if (($return = $this->driver->convertToDriver($value, $type)) !== $value) { return $return; } if (method_exists($value, '__toString')) { $str_value = (string) $value; switch ($type) { case 'any': case 's': return $str_value; case 'i': return (int) ($str_value + 0); case 'f': return (float) $str_value; case 'b': return (bool) $str_value; } } break; case 'array': if (substr($type, -1) === ']' || $type === 'any') { $this->processArray(trim($type, '[]'), $value); return $value; } break; default: return $value; } }
Tries to find modifier and returns value in needed type @param string s, i, dt, oid... @param mixed object, string, number, bool... @return mixed
https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryProcessor.php#L326-L411
Vyki/mva-dbm
src/Mva/Dbm/Query/QueryProcessor.php
QueryProcessor.processLikeOperator
protected function processLikeOperator($value) { $value = preg_quote($value); $value = substr($value, 0, 1) === '%' ? (substr($value, -1, 1) === '%' ? substr($value, 1, -1) : substr($value, 1) . '$') : (substr($value, -1, 1) === '%' ? '^' . substr($value, 0, -1) : $value); return '/' . $value . '/i'; }
php
protected function processLikeOperator($value) { $value = preg_quote($value); $value = substr($value, 0, 1) === '%' ? (substr($value, -1, 1) === '%' ? substr($value, 1, -1) : substr($value, 1) . '$') : (substr($value, -1, 1) === '%' ? '^' . substr($value, 0, -1) : $value); return '/' . $value . '/i'; }
Converts SQL LIKE to MongoRegex @param string value with wildcard - %test, test%, %test%
https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryProcessor.php#L419-L425
Vyki/mva-dbm
src/Mva/Dbm/Query/QueryProcessor.php
QueryProcessor.processArray
protected function processArray($modifier, array &$values) { foreach ($values as &$item) { $item = $this->processModifier($modifier, $item); } }
php
protected function processArray($modifier, array &$values) { foreach ($values as &$item) { $item = $this->processModifier($modifier, $item); } }
Applies modifier to the inner array via reference @param string modifier @param array sets of values
https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryProcessor.php#L433-L438
Vyki/mva-dbm
src/Mva/Dbm/Query/QueryProcessor.php
QueryProcessor.doubledModifier
private function doubledModifier($value, $modifier) { if (($count = substr_count($value, $modifier)) > 0) { $value = $count > 1 ? str_replace($modifier . $modifier, $modifier, $value) : $value; if (($count % 2) > 0) { return [TRUE, $value]; } } return [FALSE, $value]; }
php
private function doubledModifier($value, $modifier) { if (($count = substr_count($value, $modifier)) > 0) { $value = $count > 1 ? str_replace($modifier . $modifier, $modifier, $value) : $value; if (($count % 2) > 0) { return [TRUE, $value]; } } return [FALSE, $value]; }
Evaluates that modifier could be applied %%test%% -> [FALSE, '%test%'], %test -> [TRUE, '%test'], %%%test -> [TRUE, '%%test'] @param string value with modifier %%test%% @param string modifier - %, ... @return array [bool, string]
https://github.com/Vyki/mva-dbm/blob/587d840e0620331a9f63a6867f3400a293a9d3c6/src/Mva/Dbm/Query/QueryProcessor.php#L448-L458
dotkernel/dot-session
src/ConfigProvider.php
ConfigProvider.getDependencyConfig
public function getDependencyConfig(): array { return [ 'aliases' => [ SessionManager::class => ManagerInterface::class, ], 'factories' => [ ConfigInterface::class => SessionConfigFactory::class, ManagerInterface::class => SessionManagerFactory::class, StorageInterface::class => StorageFactory::class, SessionOptions::class => SessionOptionsFactory::class, SessionMiddleware::class => SessionMiddlewareFactory::class, ], 'abstract_factories' => [ ContainerAbstractServiceFactory::class, ] ]; }
php
public function getDependencyConfig(): array { return [ 'aliases' => [ SessionManager::class => ManagerInterface::class, ], 'factories' => [ ConfigInterface::class => SessionConfigFactory::class, ManagerInterface::class => SessionManagerFactory::class, StorageInterface::class => StorageFactory::class, SessionOptions::class => SessionOptionsFactory::class, SessionMiddleware::class => SessionMiddlewareFactory::class, ], 'abstract_factories' => [ ContainerAbstractServiceFactory::class, ] ]; }
Merge our config with Zend Session dependencies @return array
https://github.com/dotkernel/dot-session/blob/9808072c807a9cc708a0cae5475a29f70e3f450e/src/ConfigProvider.php#L70-L88
Boolive/Core
file/File.php
File.create
static function create($content, $to, $append = false) { $to = self::makeVirtualDir($to); // Если папки нет, то создаем её $dir = dirname($to); if(!is_dir($dir)){ mkdir($dir, 0775, true); } $result = false; // Создание файла if (($f = fopen($to, $append?'a':'w'))) { stream_set_write_buffer($f, 20); fwrite($f, $content); fclose($f); $result = true; } self::deleteVirtualDir($to); return $result; }
php
static function create($content, $to, $append = false) { $to = self::makeVirtualDir($to); // Если папки нет, то создаем её $dir = dirname($to); if(!is_dir($dir)){ mkdir($dir, 0775, true); } $result = false; // Создание файла if (($f = fopen($to, $append?'a':'w'))) { stream_set_write_buffer($f, 20); fwrite($f, $content); fclose($f); $result = true; } self::deleteVirtualDir($to); return $result; }
Создание файла @param string $content Содержимое файла @param string $to Путь к создаваемому файлу @param bool $append Добавлять в файл или пересоздавать его. По умолчанию пересоздаётся. @return bool Признак, создан файл или нет
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/file/File.php#L28-L46
Boolive/Core
file/File.php
File.upload
static function upload($from, $to) { $result = false; if(is_uploaded_file($from)){ $to = self::makeVirtualDir($to); // Если папки нет, то создаем её $dir = dirname($to); if(!is_dir($dir)){ mkdir($dir, 0775, true); } if (is_file($to)){ unlink($to); } //Перемещаем файл если он загружен через POST $result = move_uploaded_file($from, $to); self::deleteVirtualDir($to); } return $result; }
php
static function upload($from, $to) { $result = false; if(is_uploaded_file($from)){ $to = self::makeVirtualDir($to); // Если папки нет, то создаем её $dir = dirname($to); if(!is_dir($dir)){ mkdir($dir, 0775, true); } if (is_file($to)){ unlink($to); } //Перемещаем файл если он загружен через POST $result = move_uploaded_file($from, $to); self::deleteVirtualDir($to); } return $result; }
Перемешщение загруженного файла по указанному пути @param string $from Путь к загружаемому файлу @param string $to Путь, куда файл копировать. Путь должен содерджать имя файла @return bool Признак, загружен файл или нет
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/file/File.php#L54-L72
Boolive/Core
file/File.php
File.copy
static function copy($from, $to) { $result = false; if (file_exists($from)){ $to = self::makeVirtualDir($to); // Если папки нет, то создаем её $dir = dirname($to); if(!is_dir($dir)){ mkdir($dir, 0775, true); } if (is_file($to)){ unlink($to); } $result = copy($from, $to); self::deleteVirtualDir($to); } return $result; }
php
static function copy($from, $to) { $result = false; if (file_exists($from)){ $to = self::makeVirtualDir($to); // Если папки нет, то создаем её $dir = dirname($to); if(!is_dir($dir)){ mkdir($dir, 0775, true); } if (is_file($to)){ unlink($to); } $result = copy($from, $to); self::deleteVirtualDir($to); } return $result; }
Копирование файла @param string $from Путь к копируемому файлу @param string $to Путь, куда файл копировать. Путь должен содерджать имя файла @return bool Признак, скопирован файл или нет
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/file/File.php#L80-L97
Boolive/Core
file/File.php
File.rename
static function rename($from, $to) { $result = false; if (file_exists($from)){ $to = self::makeVirtualDir($to); $dir = dirname($to); if (!is_dir($dir)) mkdir($dir, true); if (mb_strtoupper($from) != mb_strtoupper($to)){ if (is_dir($to)){ self::clear_dir($to, true); }else if (is_file($to)){ unlink($to); } } $result = rename($from, $to); self::deleteVirtualDir($to); } return $result; }
php
static function rename($from, $to) { $result = false; if (file_exists($from)){ $to = self::makeVirtualDir($to); $dir = dirname($to); if (!is_dir($dir)) mkdir($dir, true); if (mb_strtoupper($from) != mb_strtoupper($to)){ if (is_dir($to)){ self::clear_dir($to, true); }else if (is_file($to)){ unlink($to); } } $result = rename($from, $to); self::deleteVirtualDir($to); } return $result; }
Переименование или перемещение файла @param string $from Путь к переименовываемому файлу @param string $to Путь с новым именем @return bool Признак, переименован файл или нет
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/file/File.php#L105-L124
Boolive/Core
file/File.php
File.delete
static function delete($from) { $from = self::makeVirtualDir($from, false); $result = false; if (is_file($from)){ @unlink($from); $result = true; } self::deleteVirtualDir($from); return $result; }
php
static function delete($from) { $from = self::makeVirtualDir($from, false); $result = false; if (is_file($from)){ @unlink($from); $result = true; } self::deleteVirtualDir($from); return $result; }
Удаление файла @param string $from Путь к удаляемому файлу @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/file/File.php#L131-L141
Boolive/Core
file/File.php
File.delete_empty_dir
static function delete_empty_dir($dir) { $dir = self::makeVirtualDir($dir, false); if (is_dir($dir) && sizeof(scandir($dir)) == 2){ return @rmdir($dir); } self::deleteVirtualDir($dir); return false; }
php
static function delete_empty_dir($dir) { $dir = self::makeVirtualDir($dir, false); if (is_dir($dir) && sizeof(scandir($dir)) == 2){ return @rmdir($dir); } self::deleteVirtualDir($dir); return false; }
Удаление пустой директории @param $dir @return bool
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/file/File.php#L148-L156
Boolive/Core
file/File.php
File.clear_dir
static function clear_dir($dir, $delete_me = false) { $dir = self::makeVirtualDir($dir, false); $result = false; if (is_file($dir)){ $result = @unlink($dir); }else if (is_dir($dir)){ $scan = glob(rtrim($dir, '/').'/*'); foreach ($scan as $path){ self::clear_dir($path, true); } $result = $delete_me?@rmdir($dir):true; } self::deleteVirtualDir($dir); return $result; }
php
static function clear_dir($dir, $delete_me = false) { $dir = self::makeVirtualDir($dir, false); $result = false; if (is_file($dir)){ $result = @unlink($dir); }else if (is_dir($dir)){ $scan = glob(rtrim($dir, '/').'/*'); foreach ($scan as $path){ self::clear_dir($path, true); } $result = $delete_me?@rmdir($dir):true; } self::deleteVirtualDir($dir); return $result; }
Удаление всех файлов и поддиректорий в указанной директории @param string $dir Путь на очищаемому директорию @param bool $delete_me Удалить указанную директорию (true) или только её содержимое (false)? @return bool Признак, выполнено ли удаление
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/file/File.php#L164-L180
Boolive/Core
file/File.php
File.fileInfo
static function fileInfo($path, $key = null) { $path = str_replace('\\','/',$path); $list = F::explode('/', $path, -2); if (sizeof($list)<2){ array_unshift($list, ''); } $info = array('dir'=>$list[0], 'name'=>$list[1], 'base'=> '', 'ext'=>'', 'back'=>false); if (($len = mb_strlen($list[0]))>1 && mb_substr($list[0], $len-2)=='..'){ $info['back'] = true; } $list = F::explode('.', $info['name'], -2); // Если $list имеет один элемент, то это не расширение if (sizeof($list)>1){ $info['ext'] = strtolower($list[1]); }else{ $info['ext'] = ''; } $info['base'] = $list[0]; if ($key){ return $info[$key]; } return $info; }
php
static function fileInfo($path, $key = null) { $path = str_replace('\\','/',$path); $list = F::explode('/', $path, -2); if (sizeof($list)<2){ array_unshift($list, ''); } $info = array('dir'=>$list[0], 'name'=>$list[1], 'base'=> '', 'ext'=>'', 'back'=>false); if (($len = mb_strlen($list[0]))>1 && mb_substr($list[0], $len-2)=='..'){ $info['back'] = true; } $list = F::explode('.', $info['name'], -2); // Если $list имеет один элемент, то это не расширение if (sizeof($list)>1){ $info['ext'] = strtolower($list[1]); }else{ $info['ext'] = ''; } $info['base'] = $list[0]; if ($key){ return $info[$key]; } return $info; }
Возвращает имя и расширение файла из его пути Путь может быть относительным. Файл может отсутствовать @param string $path Путь к файлу @param null $key Какую информацию о файле возвратить? dir, name, base, ext. Если null, то возвращается всё в виде массива @return array|string Имя без расширения, расширение, полное имя файла и директория
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/file/File.php#L189-L212
Boolive/Core
file/File.php
File.changeExtention
static function changeExtention($path, $ext) { $dir = dirname($path).'/'; $f = self::fileInfo($path); return $dir.$f['base'].'.'.$ext; }
php
static function changeExtention($path, $ext) { $dir = dirname($path).'/'; $f = self::fileInfo($path); return $dir.$f['base'].'.'.$ext; }
Смена расширения в имени файла. Смена имени не касается самого файла! @param string $path Путь к файлу @param string $ext Новое расширение файла @return string Новое имя файла
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/file/File.php#L221-L226
Boolive/Core
file/File.php
File.changeName
static function changeName($path, $name) { $f = self::fileInfo($path); return $f['dir'].$name.'.'.$f['ext']; }
php
static function changeName($path, $name) { $f = self::fileInfo($path); return $f['dir'].$name.'.'.$f['ext']; }
Смена имени файла не меняя расширения. Смена имени не касается самого файла! @param string $path Путь к файлу @param string $name Новое имя файла без расширения @return string Новое имя файла
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/file/File.php#L235-L239
Boolive/Core
file/File.php
File.fileExtention
static function fileExtention($path) { $list = F::explode('.', $path, -2); if (sizeof($list)>1){ return strtolower($list[1]); }else{ return ''; } }
php
static function fileExtention($path) { $list = F::explode('.', $path, -2); if (sizeof($list)>1){ return strtolower($list[1]); }else{ return ''; } }
Расширение файла @param $path @return mixed
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/file/File.php#L257-L265
Boolive/Core
file/File.php
File.makeUniqueName
static function makeUniqueName($dir, $name, $ext, $start = 1) { self::makeVirtualDir($dir); $i = 0; $to = $dir.$name.$ext; while (file_exists($to) && $i<100){ $to = $dir.$name.(++$i+$start).$ext; } $result = ($i < 100+$start)? false : $to; self::deleteVirtualDir($dir); return $result; }
php
static function makeUniqueName($dir, $name, $ext, $start = 1) { self::makeVirtualDir($dir); $i = 0; $to = $dir.$name.$ext; while (file_exists($to) && $i<100){ $to = $dir.$name.(++$i+$start).$ext; } $result = ($i < 100+$start)? false : $to; self::deleteVirtualDir($dir); return $result; }
Создание уникального имени для файла или директории @param string $dir Директория со слэшем на конце, в которой подобрать уникальное имя @param string $name Базовое имя, к которому будут добавляться числовые префиксы для уникальности @param string $ext Расширение с точкой, присваиваемое к имени после подбора @param int $start Начальное значение для префикса @return string|bool Уникальное имя вместе с путём или false, если не удалось подобрать
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/file/File.php#L275-L286
Boolive/Core
file/File.php
File.makeUniqueDir
static function makeUniqueDir($dir, $name, $start = 1, $find = true) { self::makeVirtualDir($dir); $max = $start + 1000; $i = $start; $path = $dir.$name; do { try{ if ($result = mkdir($path, 0775, true)){ $result = $path; } }catch (\Exception $e){ $result = false; } $path = $dir . $name . $i; $i++; }while($find && !$result && $i < $max); self::deleteVirtualDir($dir); return $result; }
php
static function makeUniqueDir($dir, $name, $start = 1, $find = true) { self::makeVirtualDir($dir); $max = $start + 1000; $i = $start; $path = $dir.$name; do { try{ if ($result = mkdir($path, 0775, true)){ $result = $path; } }catch (\Exception $e){ $result = false; } $path = $dir . $name . $i; $i++; }while($find && !$result && $i < $max); self::deleteVirtualDir($dir); return $result; }
Создание уникальной директории @param string $dir Директория со слэшем на конце, в которой подобрать уникальное имя @param string $name Базовое имя, к которому будут добавляться числовые префиксы для уникальности @param int $start Начальное значение для префикса @param bool $find Признак подбирать уникальное имя @return string|bool Уникальное имя вместе с путём или false, если не удалось подобрать
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/file/File.php#L296-L315
Boolive/Core
file/File.php
File.uploadErrorMmessage
static function uploadErrorMmessage($error_code) { switch ($error_code) { case UPLOAD_ERR_INI_SIZE: return 'Превышен максимально допустимый размер файла'; case UPLOAD_ERR_FORM_SIZE: return 'Превышен максимально допустимый размер, указанный в html форме'; case UPLOAD_ERR_PARTIAL: return 'Файл загружен не полностью'; case UPLOAD_ERR_NO_TMP_DIR: return 'Файл не сохранен во временной директории'; case UPLOAD_ERR_CANT_WRITE: return 'Ошибка записи файла на диск'; case UPLOAD_ERR_EXTENSION: return 'Загрузка файла прервана сервером'; case UPLOAD_ERR_NO_FILE: default: return 'Файл не загружен'; } }
php
static function uploadErrorMmessage($error_code) { switch ($error_code) { case UPLOAD_ERR_INI_SIZE: return 'Превышен максимально допустимый размер файла'; case UPLOAD_ERR_FORM_SIZE: return 'Превышен максимально допустимый размер, указанный в html форме'; case UPLOAD_ERR_PARTIAL: return 'Файл загружен не полностью'; case UPLOAD_ERR_NO_TMP_DIR: return 'Файл не сохранен во временной директории'; case UPLOAD_ERR_CANT_WRITE: return 'Ошибка записи файла на диск'; case UPLOAD_ERR_EXTENSION: return 'Загрузка файла прервана сервером'; case UPLOAD_ERR_NO_FILE: default: return 'Файл не загружен'; } }
Текст ошибки загрзки файла @param int $error_code Код ошибки @return string
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/file/File.php#L322-L341