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
|
---|---|---|---|---|---|---|---|
akumar2-velsof/guzzlehttp | src/RingBridge.php | RingBridge.fromRingRequest | public static function fromRingRequest(array $request)
{
$options = [];
if (isset($request['version'])) {
$options['protocol_version'] = $request['version'];
}
if (!isset($request['http_method'])) {
throw new \InvalidArgumentException('No http_method');
}
return new Request(
$request['http_method'],
Core::url($request),
isset($request['headers']) ? $request['headers'] : [],
isset($request['body']) ? Stream::factory($request['body']) : null,
$options
);
} | php | public static function fromRingRequest(array $request)
{
$options = [];
if (isset($request['version'])) {
$options['protocol_version'] = $request['version'];
}
if (!isset($request['http_method'])) {
throw new \InvalidArgumentException('No http_method');
}
return new Request(
$request['http_method'],
Core::url($request),
isset($request['headers']) ? $request['headers'] : [],
isset($request['body']) ? Stream::factory($request['body']) : null,
$options
);
} | Creates a Guzzle request object using a ring request array.
@param array $request Ring request
@return Request
@throws \InvalidArgumentException for incomplete requests. | https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/RingBridge.php#L127-L145 |
seeren/cache | src/Item/CacheItem.php | CacheItem.last | public final function last(int $timeStamp = null): string
{
if ($timeStamp) {
$this->lastModification = gmdate(
"D, d M Y H:i:s",
$timeStamp) . " GMT";
}
return $this->lastModification;
} | php | public final function last(int $timeStamp = null): string
{
if ($timeStamp) {
$this->lastModification = gmdate(
"D, d M Y H:i:s",
$timeStamp) . " GMT";
}
return $this->lastModification;
} | {@inheritDoc}
@see \Seeren\Cache\Item\ModifiedItemInterface::last() | https://github.com/seeren/cache/blob/0ccf1e08b5ed55f704a02c1911f82456a5b15d79/src/Item/CacheItem.php#L80-L88 |
seeren/cache | src/Item/CacheItem.php | CacheItem.expiresAt | public final function expiresAt($expiration)
{
$this->timeToLive = $expiration instanceof DateTime
? $expiration->getTimestamp() - time()
: (int) $expiration;
return $this;
} | php | public final function expiresAt($expiration)
{
$this->timeToLive = $expiration instanceof DateTime
? $expiration->getTimestamp() - time()
: (int) $expiration;
return $this;
} | {@inheritDoc}
@see \Psr\Cache\CacheItemInterface::expiresAt() | https://github.com/seeren/cache/blob/0ccf1e08b5ed55f704a02c1911f82456a5b15d79/src/Item/CacheItem.php#L131-L137 |
seeren/cache | src/Item/CacheItem.php | CacheItem.expiresAfter | public final function expiresAfter($time)
{
$this->timeToLive = $time instanceof DateInterval
? (new DateTime())->add($time)->getTimestamp()
- time()
: (int) $time;
return $this;
} | php | public final function expiresAfter($time)
{
$this->timeToLive = $time instanceof DateInterval
? (new DateTime())->add($time)->getTimestamp()
- time()
: (int) $time;
return $this;
} | {@inheritDoc}
@see \Psr\Cache\CacheItemInterface::expiresAfter() | https://github.com/seeren/cache/blob/0ccf1e08b5ed55f704a02c1911f82456a5b15d79/src/Item/CacheItem.php#L143-L150 |
mlocati/concrete5-translation-library | src/Parser/DynamicItem/AuthenticationType.php | AuthenticationType.parseManual | public function parseManual(\Gettext\Translations $translations, $concrete5version)
{
if (class_exists('\Concrete\Core\Authentication\AuthenticationType', true) && method_exists('\Concrete\Core\Authentication\AuthenticationType', 'getList')) {
foreach (\Concrete\Core\Authentication\AuthenticationType::getList() as $at) {
$this->addTranslation($translations, $at->getAuthenticationTypeName(), 'AuthenticationType');
}
}
} | php | public function parseManual(\Gettext\Translations $translations, $concrete5version)
{
if (class_exists('\Concrete\Core\Authentication\AuthenticationType', true) && method_exists('\Concrete\Core\Authentication\AuthenticationType', 'getList')) {
foreach (\Concrete\Core\Authentication\AuthenticationType::getList() as $at) {
$this->addTranslation($translations, $at->getAuthenticationTypeName(), 'AuthenticationType');
}
}
} | {@inheritdoc}
@see \C5TL\Parser\DynamicItem\DynamicItem::parseManual() | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser/DynamicItem/AuthenticationType.php#L25-L32 |
rackberg/para | src/Package/StablePackageFinder.php | StablePackageFinder.findByNewestReleaseDate | public function findByNewestReleaseDate(array $packages): ?CompletePackageInterface
{
$foundPackage = null;
foreach ($packages as $package) {
if (!$foundPackage ||
($foundPackage->getReleaseDate() <= $package->getReleaseDate()
&& $package->getStability() === 'stable')
) {
$foundPackage = $package;
}
}
return $foundPackage;
} | php | public function findByNewestReleaseDate(array $packages): ?CompletePackageInterface
{
$foundPackage = null;
foreach ($packages as $package) {
if (!$foundPackage ||
($foundPackage->getReleaseDate() <= $package->getReleaseDate()
&& $package->getStability() === 'stable')
) {
$foundPackage = $package;
}
}
return $foundPackage;
} | {@inheritdoc} | https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Package/StablePackageFinder.php#L17-L31 |
loevgaard/dandomain-api | src/Api.php | Api.doRequest | public function doRequest(string $method, string $uri, $body = null, array $options = [])
{
$parsedResponse = [];
try {
// merge all options
// the priority is
// 1. options supplied by the user
// 2. options supplied by the method calling
// 3. the default options
$options = $this->resolveOptions($this->defaultOptions, $options, $this->options);
if (!empty($body)) {
$body = $this->objectToArray($body);
Assert::that($body)->notEmpty('The body of the request cannot be empty');
// the body will always override any other data sent
$options['json'] = $body;
}
// save the resolved options
$this->lastOptions = $options;
// replace the {KEY} placeholder with the api key
$url = $this->host . str_replace('{KEY}', $this->apiKey, $uri);
// do request
$this->response = $this->getClient()->request($method, $url, $options);
// parse response and create error object if the json decode throws an exception
try {
$parsedResponse = \GuzzleHttp\json_decode((string)$this->response->getBody(), true);
} catch (\InvalidArgumentException $e) {
$parsedResponse['errors'][] = [
'status' => $this->response->getStatusCode(),
'title' => 'JSON parse error',
'detail' => $e->getMessage()
];
}
$statusCode = $this->response->getStatusCode();
if ($statusCode > 299 || $statusCode < 200) {
if (!is_array($parsedResponse)) {
$parsedResponse = [];
}
$parsedResponse['errors'] = [];
$parsedResponse['errors'][] = [
'status' => $this->response->getStatusCode(),
'detail' => 'See Api::$response for details'
];
}
} catch (GuzzleException $e) {
$parsedResponse['errors'] = [];
$parsedResponse['errors'][] = [
'title' => 'Unexpected error',
'detail' => $e->getMessage()
];
} finally {
// reset request options
$this->options = [];
}
return $parsedResponse;
} | php | public function doRequest(string $method, string $uri, $body = null, array $options = [])
{
$parsedResponse = [];
try {
// merge all options
// the priority is
// 1. options supplied by the user
// 2. options supplied by the method calling
// 3. the default options
$options = $this->resolveOptions($this->defaultOptions, $options, $this->options);
if (!empty($body)) {
$body = $this->objectToArray($body);
Assert::that($body)->notEmpty('The body of the request cannot be empty');
// the body will always override any other data sent
$options['json'] = $body;
}
// save the resolved options
$this->lastOptions = $options;
// replace the {KEY} placeholder with the api key
$url = $this->host . str_replace('{KEY}', $this->apiKey, $uri);
// do request
$this->response = $this->getClient()->request($method, $url, $options);
// parse response and create error object if the json decode throws an exception
try {
$parsedResponse = \GuzzleHttp\json_decode((string)$this->response->getBody(), true);
} catch (\InvalidArgumentException $e) {
$parsedResponse['errors'][] = [
'status' => $this->response->getStatusCode(),
'title' => 'JSON parse error',
'detail' => $e->getMessage()
];
}
$statusCode = $this->response->getStatusCode();
if ($statusCode > 299 || $statusCode < 200) {
if (!is_array($parsedResponse)) {
$parsedResponse = [];
}
$parsedResponse['errors'] = [];
$parsedResponse['errors'][] = [
'status' => $this->response->getStatusCode(),
'detail' => 'See Api::$response for details'
];
}
} catch (GuzzleException $e) {
$parsedResponse['errors'] = [];
$parsedResponse['errors'][] = [
'title' => 'Unexpected error',
'detail' => $e->getMessage()
];
} finally {
// reset request options
$this->options = [];
}
return $parsedResponse;
} | Will always return a JSON result contrary to Dandomains API
Errors are formatted as described here: http://jsonapi.org/format/#errors
@param string $method
@param string $uri
@param array|\stdClass $body The body is sent as JSON
@param array $options
@return mixed | https://github.com/loevgaard/dandomain-api/blob/cd420d5f92a78eece4201ab57a5f6356537ed371/src/Api.php#L172-L235 |
loevgaard/dandomain-api | src/Api.php | Api.objectToArray | protected function objectToArray($obj) : array
{
if ($obj instanceof \stdClass) {
$obj = json_decode(json_encode($obj), true);
}
return (array)$obj;
} | php | protected function objectToArray($obj) : array
{
if ($obj instanceof \stdClass) {
$obj = json_decode(json_encode($obj), true);
}
return (array)$obj;
} | Helper method to convert a \stdClass into an array
@param $obj
@return array | https://github.com/loevgaard/dandomain-api/blob/cd420d5f92a78eece4201ab57a5f6356537ed371/src/Api.php#L307-L314 |
ZhukV/LanguageDetector | src/Ideea/LanguageDetector/Alphabet/Alphabet.php | Alphabet.serialize | public function serialize()
{
return serialize(array(
$this->language,
$this->charCodes,
$this->multipleCharCodes,
$this->commonCharCodes
));
} | php | public function serialize()
{
return serialize(array(
$this->language,
$this->charCodes,
$this->multipleCharCodes,
$this->commonCharCodes
));
} | {@inheritDoc} | https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/Alphabet/Alphabet.php#L130-L138 |
ZhukV/LanguageDetector | src/Ideea/LanguageDetector/Alphabet/Alphabet.php | Alphabet.unserialize | public function unserialize($serialized)
{
list (
$this->language,
$this->charCodes,
$this->multipleCharCodes,
$this->commonCharCodes
) = unserialize($serialized);
} | php | public function unserialize($serialized)
{
list (
$this->language,
$this->charCodes,
$this->multipleCharCodes,
$this->commonCharCodes
) = unserialize($serialized);
} | {@inheritDoc} | https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/Alphabet/Alphabet.php#L143-L151 |
bennybi/yii2-cza-base | components/actions/common/AttachmentSortAction.php | AttachmentSortAction.run | public function run($ids) {
if (!empty($ids)) {
$attachementClass = $this->attachementClass;
$sortIds = explode(',', $ids);
$count = count($sortIds);
for ($i = 0; $i < $count; $i++) {
$positon = $count - $i;
$model = $attachementClass::findOne(['id' => $sortIds[$i]]);
if ($model) {
$model->updateAttributes(['position' => $positon]);
}
}
if ($this->onComplete) {
return call_user_func($this->onComplete, $sortIds);
}
}
$responseData = ResponseDatum::getSuccessDatum(['message' => Yii::t('cza', 'Operation completed successfully!')], $ids);
return $this->controller->asJson($responseData);
} | php | public function run($ids) {
if (!empty($ids)) {
$attachementClass = $this->attachementClass;
$sortIds = explode(',', $ids);
$count = count($sortIds);
for ($i = 0; $i < $count; $i++) {
$positon = $count - $i;
$model = $attachementClass::findOne(['id' => $sortIds[$i]]);
if ($model) {
$model->updateAttributes(['position' => $positon]);
}
}
if ($this->onComplete) {
return call_user_func($this->onComplete, $sortIds);
}
}
$responseData = ResponseDatum::getSuccessDatum(['message' => Yii::t('cza', 'Operation completed successfully!')], $ids);
return $this->controller->asJson($responseData);
} | Runs the action.
This method displays the view requested by the user.
@throws HttpException if the view is invalid | https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/components/actions/common/AttachmentSortAction.php#L37-L58 |
ivansabik/dom-hunter | src/Ivansabik/DomHunter/presas/SelectOptions.php | SelectOptions._limpiaStr | private function _limpiaStr($strTexto) {
$cur_encoding = mb_detect_encoding($strTexto);
if ($cur_encoding == 'UTF-8' && mb_check_encoding($strTexto, 'UTF-8')) {
return strip_tags(trim(str_replace(' ', '', $strTexto)));
} else {
return strip_tags(trim(str_replace(' ', '', utf8_encode($strTexto))));
}
} | php | private function _limpiaStr($strTexto) {
$cur_encoding = mb_detect_encoding($strTexto);
if ($cur_encoding == 'UTF-8' && mb_check_encoding($strTexto, 'UTF-8')) {
return strip_tags(trim(str_replace(' ', '', $strTexto)));
} else {
return strip_tags(trim(str_replace(' ', '', utf8_encode($strTexto))));
}
} | # Funcion se repite en DomHunter.php, refactor? | https://github.com/ivansabik/dom-hunter/blob/dad5a6b3bc9146b6e1f7f0b98e299ec83cfd75a6/src/Ivansabik/DomHunter/presas/SelectOptions.php#L77-L84 |
PHPColibri/framework | Routing/Route.php | Route.parseRequestedFile | private static function parseRequestedFile(string $file): array
{
$file = ltrim($file, '/');
$moduleConfig = Config::application('module');
$parts = explode('/', $file);
$partsCnt = count($parts);
if ($partsCnt > 0 && in_array($parts[0], Config::get('divisions'))) {
$_division = $parts[0];
$parts = array_slice($parts, 1);
} else {
$_division = '';
}
$_module = empty($parts[0])
? $moduleConfig['default']
: $parts[0];
$_method = $partsCnt < 2 || empty($parts[1])
? $moduleConfig['defaultViewsControllerAction']
: Str::camel($parts[1]);
$_params = $partsCnt > 2
? array_slice($parts, 2)
: [];
return [$_division, $_module, $_method, $_params];
} | php | private static function parseRequestedFile(string $file): array
{
$file = ltrim($file, '/');
$moduleConfig = Config::application('module');
$parts = explode('/', $file);
$partsCnt = count($parts);
if ($partsCnt > 0 && in_array($parts[0], Config::get('divisions'))) {
$_division = $parts[0];
$parts = array_slice($parts, 1);
} else {
$_division = '';
}
$_module = empty($parts[0])
? $moduleConfig['default']
: $parts[0];
$_method = $partsCnt < 2 || empty($parts[1])
? $moduleConfig['defaultViewsControllerAction']
: Str::camel($parts[1]);
$_params = $partsCnt > 2
? array_slice($parts, 2)
: [];
return [$_division, $_module, $_method, $_params];
} | @param string $file requested file name
@return array
@throws \InvalidArgumentException | https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Routing/Route.php#L46-L75 |
PHPColibri/framework | Routing/Route.php | Route.applyRewrites | private static function applyRewrites(string $requestedUri, array $rewrites): string
{
foreach ($rewrites as $route) {
$pattern = $route['pattern'];
$replacement = $route['replacement'];
$requestedUri = preg_replace($pattern, $replacement, $requestedUri);
if (isset($route['last'])) {
break;
}
}
return $requestedUri;
} | php | private static function applyRewrites(string $requestedUri, array $rewrites): string
{
foreach ($rewrites as $route) {
$pattern = $route['pattern'];
$replacement = $route['replacement'];
$requestedUri = preg_replace($pattern, $replacement, $requestedUri);
if (isset($route['last'])) {
break;
}
}
return $requestedUri;
} | @param string $requestedUri
@param array $rewrites
@return string | https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Routing/Route.php#L83-L96 |
vudaltsov-legacy/twig-extensions | src/SymfonyIntlExtension.php | SymfonyIntlExtension.getFilters | public function getFilters()
{
return [
new TwigFilter('intl_country', function ($country, string $locale = null) {
if (is_string($country)) {
return Intl::getRegionBundle()->getCountryName($country, $locale);
}
return array_map(function ($country) use ($locale) {
return Intl::getRegionBundle()->getCountryName($country, $locale);
}, Helper::iterableToArray($country));
}),
new TwigFilter('intl_currency', function ($currency, string $locale = null) {
if (is_string($currency)) {
return Intl::getCurrencyBundle()->getCurrencyName($currency, $locale);
}
return array_map(function ($currency) use ($locale) {
return Intl::getCurrencyBundle()->getCurrencyName($currency, $locale);
}, Helper::iterableToArray($currency));
}),
new TwigFilter('intl_currency_symbol', function ($currency, string $locale = null) {
if (is_string($currency)) {
return Intl::getCurrencyBundle()->getCurrencySymbol($currency, $locale);
}
return array_map(function ($currency) use ($locale) {
return Intl::getCurrencyBundle()->getCurrencySymbol($currency, $locale);
}, Helper::iterableToArray($currency));
}),
new TwigFilter('intl_language', function ($language, string $region = null, string $locale = null) {
if (is_string($language)) {
return Intl::getLanguageBundle()->getLanguageName($language, $region, $locale);
}
return array_map(function ($language) use ($region, $locale) {
return Intl::getLanguageBundle()->getLanguageName($language, $region, $locale);
}, Helper::iterableToArray($language));
}),
new TwigFilter('intl_locale', function ($locale, string $displayLocale = null) {
if (is_string($locale)) {
return Intl::getLocaleBundle()->getLocaleName($locale, $displayLocale);
}
return array_map(function ($locale) use ($displayLocale) {
return Intl::getLocaleBundle()->getLocaleName($locale, $displayLocale);
}, Helper::iterableToArray($locale));
}),
new TwigFilter('intl_script', function ($script, string $language = null, string $locale = null) {
if (is_string($script)) {
return Intl::getLanguageBundle()->getScriptName($script, $language, $locale);
}
return array_map(function ($script) use ($language, $locale) {
return Intl::getLanguageBundle()->getScriptName($script, $language, $locale);
}, Helper::iterableToArray($script));
}),
];
} | php | public function getFilters()
{
return [
new TwigFilter('intl_country', function ($country, string $locale = null) {
if (is_string($country)) {
return Intl::getRegionBundle()->getCountryName($country, $locale);
}
return array_map(function ($country) use ($locale) {
return Intl::getRegionBundle()->getCountryName($country, $locale);
}, Helper::iterableToArray($country));
}),
new TwigFilter('intl_currency', function ($currency, string $locale = null) {
if (is_string($currency)) {
return Intl::getCurrencyBundle()->getCurrencyName($currency, $locale);
}
return array_map(function ($currency) use ($locale) {
return Intl::getCurrencyBundle()->getCurrencyName($currency, $locale);
}, Helper::iterableToArray($currency));
}),
new TwigFilter('intl_currency_symbol', function ($currency, string $locale = null) {
if (is_string($currency)) {
return Intl::getCurrencyBundle()->getCurrencySymbol($currency, $locale);
}
return array_map(function ($currency) use ($locale) {
return Intl::getCurrencyBundle()->getCurrencySymbol($currency, $locale);
}, Helper::iterableToArray($currency));
}),
new TwigFilter('intl_language', function ($language, string $region = null, string $locale = null) {
if (is_string($language)) {
return Intl::getLanguageBundle()->getLanguageName($language, $region, $locale);
}
return array_map(function ($language) use ($region, $locale) {
return Intl::getLanguageBundle()->getLanguageName($language, $region, $locale);
}, Helper::iterableToArray($language));
}),
new TwigFilter('intl_locale', function ($locale, string $displayLocale = null) {
if (is_string($locale)) {
return Intl::getLocaleBundle()->getLocaleName($locale, $displayLocale);
}
return array_map(function ($locale) use ($displayLocale) {
return Intl::getLocaleBundle()->getLocaleName($locale, $displayLocale);
}, Helper::iterableToArray($locale));
}),
new TwigFilter('intl_script', function ($script, string $language = null, string $locale = null) {
if (is_string($script)) {
return Intl::getLanguageBundle()->getScriptName($script, $language, $locale);
}
return array_map(function ($script) use ($language, $locale) {
return Intl::getLanguageBundle()->getScriptName($script, $language, $locale);
}, Helper::iterableToArray($script));
}),
];
} | {@inheritdoc} | https://github.com/vudaltsov-legacy/twig-extensions/blob/a86574b17d7e77e8d8c79ae34702c5acfbc87861/src/SymfonyIntlExtension.php#L21-L79 |
IftekherSunny/Planet-Framework | src/Sun/Database/Schema.php | Schema.bootstrap | public function bootstrap()
{
$this->app->bind('phpmig.adapter', function() {
return new Adapter\Illuminate\Database($this->app['Sun\Contracts\Database\Database']->getCapsuleInstance(), 'migrations');
});
$this->app->bind('phpmig.migrations_path', function() {
return $this->app->migrations_path();
});
$this->app->bind('phpmig.migrations_template_path', function() {
return __DIR__ . '/../Console/stubs/MigrateGenerate.txt';
});
$this->app->bind('schema', function() {
return $this->app['Sun\Contracts\Database\Database']->getCapsuleInstance()->schema();
});
} | php | public function bootstrap()
{
$this->app->bind('phpmig.adapter', function() {
return new Adapter\Illuminate\Database($this->app['Sun\Contracts\Database\Database']->getCapsuleInstance(), 'migrations');
});
$this->app->bind('phpmig.migrations_path', function() {
return $this->app->migrations_path();
});
$this->app->bind('phpmig.migrations_template_path', function() {
return __DIR__ . '/../Console/stubs/MigrateGenerate.txt';
});
$this->app->bind('schema', function() {
return $this->app['Sun\Contracts\Database\Database']->getCapsuleInstance()->schema();
});
} | Bootstrap PHP Mig | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Database/Schema.php#L28-L45 |
selikhovleonid/nadir | src/core/ViewFactory.php | ViewFactory.createView | public static function createView($sCtrlName = null, $sActionName)
{
$sViewsRoot = AppHelper::getInstance()->getComponentRoot('views');
$sAddPath = '';
if (!empty($sCtrlName)) {
$sAddPath .= DIRECTORY_SEPARATOR.strtolower($sCtrlName);
}
$sViewFile = $sViewsRoot.$sAddPath.DIRECTORY_SEPARATOR
.strtolower($sActionName).'.php';
if (is_readable($sViewFile)) {
return new View($sViewFile);
}
return null;
} | php | public static function createView($sCtrlName = null, $sActionName)
{
$sViewsRoot = AppHelper::getInstance()->getComponentRoot('views');
$sAddPath = '';
if (!empty($sCtrlName)) {
$sAddPath .= DIRECTORY_SEPARATOR.strtolower($sCtrlName);
}
$sViewFile = $sViewsRoot.$sAddPath.DIRECTORY_SEPARATOR
.strtolower($sActionName).'.php';
if (is_readable($sViewFile)) {
return new View($sViewFile);
}
return null;
} | The method creates a view object assigned with the specific controller and
action in it. If controller name is empty it means a markup file determined
only with action name. It doesn't physically consist into the direcory named
as controller, it's in the root of the view directory.
@param string $sCtrlName|null The controller name (as optional)
@param string $sActionName The action name.
@return \nadir\core\View|null It returns null if view file isn't readable. | https://github.com/selikhovleonid/nadir/blob/47545fccd8516c8f0a20c02ba62f68269c7199da/src/core/ViewFactory.php#L29-L42 |
selikhovleonid/nadir | src/core/ViewFactory.php | ViewFactory.createLayout | public static function createLayout($sLayoutName, View $oView)
{
$sLayoutsRoot = AppHelper::getInstance()->getComponentRoot('layouts');
$sLayoutFile = $sLayoutsRoot.DIRECTORY_SEPARATOR
.strtolower($sLayoutName).'.php';
if (is_readable($sLayoutFile)) {
return new Layout($sLayoutFile, $oView);
}
return null;
} | php | public static function createLayout($sLayoutName, View $oView)
{
$sLayoutsRoot = AppHelper::getInstance()->getComponentRoot('layouts');
$sLayoutFile = $sLayoutsRoot.DIRECTORY_SEPARATOR
.strtolower($sLayoutName).'.php';
if (is_readable($sLayoutFile)) {
return new Layout($sLayoutFile, $oView);
}
return null;
} | It creates a layout object.
@param type $sLayoutName The layout name.
@param \nadir\core\View $oView The object of view.
@return \nadir\core\Layout|null | https://github.com/selikhovleonid/nadir/blob/47545fccd8516c8f0a20c02ba62f68269c7199da/src/core/ViewFactory.php#L50-L59 |
selikhovleonid/nadir | src/core/ViewFactory.php | ViewFactory.createSnippet | public static function createSnippet($sSnptName)
{
$sSnptRoot = AppHelper::getInstance()->getComponentRoot('snippets');
$SnptFile = $sSnptRoot.DIRECTORY_SEPARATOR
.strtolower($sSnptName).'.php';
if (is_readable($SnptFile)) {
return new Snippet($SnptFile);
}
return null;
} | php | public static function createSnippet($sSnptName)
{
$sSnptRoot = AppHelper::getInstance()->getComponentRoot('snippets');
$SnptFile = $sSnptRoot.DIRECTORY_SEPARATOR
.strtolower($sSnptName).'.php';
if (is_readable($SnptFile)) {
return new Snippet($SnptFile);
}
return null;
} | The method creates a snippet-object.
@param type $sSnptName The snippet name.
@return \nadir\core\Snippet|null. | https://github.com/selikhovleonid/nadir/blob/47545fccd8516c8f0a20c02ba62f68269c7199da/src/core/ViewFactory.php#L66-L75 |
fxpio/fxp-gluon | Twig/Extension/GoogleFontsExtension.php | GoogleFontsExtension.addStylesheetGoogleFonts | public function addStylesheetGoogleFonts()
{
$str = '';
foreach ($this->fonts as $url) {
$str .= sprintf('<link href="%s" rel="stylesheet">', $url);
}
return $str;
} | php | public function addStylesheetGoogleFonts()
{
$str = '';
foreach ($this->fonts as $url) {
$str .= sprintf('<link href="%s" rel="stylesheet">', $url);
}
return $str;
} | Build the stylesheet links of google fonts.
@return string | https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Twig/Extension/GoogleFontsExtension.php#L51-L60 |
rackberg/para | src/Factory/ShellFactory.php | ShellFactory.create | public function create(InputInterface $input, OutputInterface $output): InteractiveShellInterface
{
return new GroupShell(
$this->logger,
$this->application,
$this->processFactory,
$this->dispatcher,
$this->historyShellManager,
$input,
$output
);
} | php | public function create(InputInterface $input, OutputInterface $output): InteractiveShellInterface
{
return new GroupShell(
$this->logger,
$this->application,
$this->processFactory,
$this->dispatcher,
$this->historyShellManager,
$input,
$output
);
} | {@inheritdoc} | https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Factory/ShellFactory.php#L82-L93 |
alex-oleshkevich/classnames | src/ClassNames.php | ClassNames.parse | public function parse($filename)
{
$tokens = token_get_all(file_get_contents($filename));
$classNames = [];
$interfaceNames = [];
$traitNames = [];
$namespace = [];
$curleys = 0;
$isInNamespace = false;
$totalTokens = count($tokens);
for ($i = 0; $i <= $totalTokens; $i++) {
if (!isset($tokens[$i])) {
break;
}
$token = $tokens[$i];
if (is_string($token)) {
if (in_array($token[0], ['{'])) {
$curleys++;
}
if (in_array($token[0], ['}'])) {
$curleys--;
}
$token = [0 => $token];
}
// iterate until space to get FQ NS name.
if ($token[0] == T_NAMESPACE) {
$namespace = [];
$i = $i + 2;
for (; $i <= $totalTokens; $i++) {
if (!isset($tokens[$i])) {
break;
}
$token = $tokens[$i];
if ($token[0] == T_STRING) {
$namespace[] = $token[1];
}
if ($token[0] == ';') {
$isInNamespace = true;
break;
}
if ($token[0] == '{') {
$curleys++;
break;
}
if ($token[0] == '{') {
$curleys--;
}
}
}
if ($token[0] == T_CLASS) {
$prevToken = $tokens[$i - 1];
if (is_array($prevToken) && $prevToken[0] == T_DOUBLE_COLON) {
continue;
}
$i = $i + 2;
for (; $i <= count($tokens); $i++) {
$token = $tokens[$i];
if ($token[0] == T_STRING) {
if ($curleys == 0 && !$isInNamespace) {
$namespace = [];
}
$classParts = array_merge($namespace, [$token[1]]);
$classNames[] = join('\\', $classParts);
break;
}
}
}
if ($token[0] == T_INTERFACE) {
$i = $i + 2;
for (; $i <= count($tokens); $i++) {
$token = $tokens[$i];
if ($token[0] == T_STRING) {
if ($curleys == 0 && !$isInNamespace) {
$namespace = [];
}
$interfaceParts = array_merge($namespace, [$token[1]]);
$interfaceNames[] = join('\\', $interfaceParts);
break;
}
}
}
if ($token[0] == T_TRAIT) {
$i = $i + 2;
for (; $i <= count($tokens); $i++) {
$token = $tokens[$i];
if ($token[0] == T_STRING) {
if ($curleys == 0 && !$isInNamespace) {
$namespace = [];
}
$traitParts = array_merge($namespace, [$token[1]]);
$traitNames[] = join('\\', $traitParts);
break;
}
}
}
}
return [
'classes' => $classNames,
'interfaces' => $interfaceNames,
'traits' => $traitNames
];
} | php | public function parse($filename)
{
$tokens = token_get_all(file_get_contents($filename));
$classNames = [];
$interfaceNames = [];
$traitNames = [];
$namespace = [];
$curleys = 0;
$isInNamespace = false;
$totalTokens = count($tokens);
for ($i = 0; $i <= $totalTokens; $i++) {
if (!isset($tokens[$i])) {
break;
}
$token = $tokens[$i];
if (is_string($token)) {
if (in_array($token[0], ['{'])) {
$curleys++;
}
if (in_array($token[0], ['}'])) {
$curleys--;
}
$token = [0 => $token];
}
// iterate until space to get FQ NS name.
if ($token[0] == T_NAMESPACE) {
$namespace = [];
$i = $i + 2;
for (; $i <= $totalTokens; $i++) {
if (!isset($tokens[$i])) {
break;
}
$token = $tokens[$i];
if ($token[0] == T_STRING) {
$namespace[] = $token[1];
}
if ($token[0] == ';') {
$isInNamespace = true;
break;
}
if ($token[0] == '{') {
$curleys++;
break;
}
if ($token[0] == '{') {
$curleys--;
}
}
}
if ($token[0] == T_CLASS) {
$prevToken = $tokens[$i - 1];
if (is_array($prevToken) && $prevToken[0] == T_DOUBLE_COLON) {
continue;
}
$i = $i + 2;
for (; $i <= count($tokens); $i++) {
$token = $tokens[$i];
if ($token[0] == T_STRING) {
if ($curleys == 0 && !$isInNamespace) {
$namespace = [];
}
$classParts = array_merge($namespace, [$token[1]]);
$classNames[] = join('\\', $classParts);
break;
}
}
}
if ($token[0] == T_INTERFACE) {
$i = $i + 2;
for (; $i <= count($tokens); $i++) {
$token = $tokens[$i];
if ($token[0] == T_STRING) {
if ($curleys == 0 && !$isInNamespace) {
$namespace = [];
}
$interfaceParts = array_merge($namespace, [$token[1]]);
$interfaceNames[] = join('\\', $interfaceParts);
break;
}
}
}
if ($token[0] == T_TRAIT) {
$i = $i + 2;
for (; $i <= count($tokens); $i++) {
$token = $tokens[$i];
if ($token[0] == T_STRING) {
if ($curleys == 0 && !$isInNamespace) {
$namespace = [];
}
$traitParts = array_merge($namespace, [$token[1]]);
$traitNames[] = join('\\', $traitParts);
break;
}
}
}
}
return [
'classes' => $classNames,
'interfaces' => $interfaceNames,
'traits' => $traitNames
];
} | Parse .php file.
@param string $filename
@return array | https://github.com/alex-oleshkevich/classnames/blob/2640603475cb5c95945920e4466561c3e30d6676/src/ClassNames.php#L23-L136 |
IftekherSunny/Planet-Framework | src/Sun/Console/Commands/AppName.php | AppName.handle | public function handle()
{
$oldNamespace = rtrim($this->app->getNamespace(),'\\');
$newNamespace = ucfirst($this->input->getArgument('name'));
$this->setAppNamespace($oldNamespace, $newNamespace);
$this->setBootstrapNamespace($oldNamespace, $newNamespace);
$this->setConfigNamespace($oldNamespace, $newNamespace);
$this->setComposerNamespace($oldNamespace, $newNamespace);
$this->composerDumpAutoload();
} | php | public function handle()
{
$oldNamespace = rtrim($this->app->getNamespace(),'\\');
$newNamespace = ucfirst($this->input->getArgument('name'));
$this->setAppNamespace($oldNamespace, $newNamespace);
$this->setBootstrapNamespace($oldNamespace, $newNamespace);
$this->setConfigNamespace($oldNamespace, $newNamespace);
$this->setComposerNamespace($oldNamespace, $newNamespace);
$this->composerDumpAutoload();
} | To handle console command | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Commands/AppName.php#L42-L56 |
IftekherSunny/Planet-Framework | src/Sun/Console/Commands/AppName.php | AppName.setAppNamespace | private function setAppNamespace($oldNamespace, $newNamespace)
{
$files = $this->filesystem->files(app_path());
foreach ($files as $file) {
$content = $this->filesystem->get($file);
$this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content));
}
} | php | private function setAppNamespace($oldNamespace, $newNamespace)
{
$files = $this->filesystem->files(app_path());
foreach ($files as $file) {
$content = $this->filesystem->get($file);
$this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content));
}
} | To set app directory files namespace
@param $oldNamespace
@param $newNamespace | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Commands/AppName.php#L88-L96 |
IftekherSunny/Planet-Framework | src/Sun/Console/Commands/AppName.php | AppName.setBootstrapNamespace | private function setBootstrapNamespace($oldNamespace, $newNamespace)
{
$files = $this->filesystem->files(base_path() . '/bootstrap');
foreach ($files as $file) {
$content = $this->filesystem->get($file);
$this->filesystem->create($file, str_replace($oldNamespace . '\Controllers', $newNamespace . '\Controllers', $content));
}
} | php | private function setBootstrapNamespace($oldNamespace, $newNamespace)
{
$files = $this->filesystem->files(base_path() . '/bootstrap');
foreach ($files as $file) {
$content = $this->filesystem->get($file);
$this->filesystem->create($file, str_replace($oldNamespace . '\Controllers', $newNamespace . '\Controllers', $content));
}
} | To set bootstrap file namespace
@param $oldNamespace
@param $newNamespace
@return array | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Commands/AppName.php#L106-L114 |
IftekherSunny/Planet-Framework | src/Sun/Console/Commands/AppName.php | AppName.setConfigNamespace | private function setConfigNamespace($oldNamespace, $newNamespace)
{
$files = $this->filesystem->files(base_path() . '/config');
foreach ($files as $file) {
$content = $this->filesystem->get($file);
$this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content));
}
} | php | private function setConfigNamespace($oldNamespace, $newNamespace)
{
$files = $this->filesystem->files(base_path() . '/config');
foreach ($files as $file) {
$content = $this->filesystem->get($file);
$this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content));
}
} | To set config directory files namespace
@param $oldNamespace
@param $newNamespace
@return array | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Commands/AppName.php#L124-L132 |
IftekherSunny/Planet-Framework | src/Sun/Console/Commands/AppName.php | AppName.setComposerNamespace | private function setComposerNamespace($oldNamespace, $newNamespace)
{
$files = $this->filesystem->files(base_path() . '/vendor/composer');
foreach ($files as $file) {
$content = $this->filesystem->get($file);
$this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content));
}
$file = base_path() . '/composer.json';
$content = $this->filesystem->get($file);
$this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content));
} | php | private function setComposerNamespace($oldNamespace, $newNamespace)
{
$files = $this->filesystem->files(base_path() . '/vendor/composer');
foreach ($files as $file) {
$content = $this->filesystem->get($file);
$this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content));
}
$file = base_path() . '/composer.json';
$content = $this->filesystem->get($file);
$this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content));
} | To set composer namespace
@param $oldNamespace
@param $newNamespace | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Commands/AppName.php#L140-L152 |
inhere/php-library-plus | libs/Task/Worker/OptionAndConfigTrait.php | OptionAndConfigTrait.parseCommandAndConfig | protected function parseCommandAndConfig()
{
$this->parseCliOptions();
$command = $this->command;
$supported = ['start', 'stop', 'restart', 'reload', 'status'];
if (!\in_array($command, $supported, true)) {
$this->showHelp("The command [{$command}] is don't supported!");
}
// load CLI Options
$this->loadCliOptions($this->cliOpts);
// init Config And Properties
$this->initConfigAndProperties($this->config);
// Debug option to dump the config and exit
if (isset($result['D']) || isset($result['dump'])) {
$val = isset($result['D']) ? $result['D'] : (isset($result['dump']) ? $result['dump'] : '');
$this->dumpInfo($val === 'all');
}
} | php | protected function parseCommandAndConfig()
{
$this->parseCliOptions();
$command = $this->command;
$supported = ['start', 'stop', 'restart', 'reload', 'status'];
if (!\in_array($command, $supported, true)) {
$this->showHelp("The command [{$command}] is don't supported!");
}
// load CLI Options
$this->loadCliOptions($this->cliOpts);
// init Config And Properties
$this->initConfigAndProperties($this->config);
// Debug option to dump the config and exit
if (isset($result['D']) || isset($result['dump'])) {
$val = isset($result['D']) ? $result['D'] : (isset($result['dump']) ? $result['dump'] : '');
$this->dumpInfo($val === 'all');
}
} | handle CLI command and load options | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Task/Worker/OptionAndConfigTrait.php#L42-L64 |
inhere/php-library-plus | libs/Task/Worker/OptionAndConfigTrait.php | OptionAndConfigTrait.parseCliOptions | protected function parseCliOptions()
{
$result = Cli::parseOptArgs([
'd', 'daemon', 'w', 'watch', 'h', 'help', 'V', 'version', 'no-test', 'watch-status'
]);
$this->fullScript = implode(' ', $GLOBALS['argv']);
$this->script = strpos($result[0], '.php') ? "php {$result[0]}" : $result[0];
$this->command = $command = isset($result[1]) ? $result[1] : 'start';
unset($result[0], $result[1]);
$this->cliOpts = $result;
} | php | protected function parseCliOptions()
{
$result = Cli::parseOptArgs([
'd', 'daemon', 'w', 'watch', 'h', 'help', 'V', 'version', 'no-test', 'watch-status'
]);
$this->fullScript = implode(' ', $GLOBALS['argv']);
$this->script = strpos($result[0], '.php') ? "php {$result[0]}" : $result[0];
$this->command = $command = isset($result[1]) ? $result[1] : 'start';
unset($result[0], $result[1]);
$this->cliOpts = $result;
} | parseCliOptions | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Task/Worker/OptionAndConfigTrait.php#L69-L81 |
inhere/php-library-plus | libs/Task/Worker/OptionAndConfigTrait.php | OptionAndConfigTrait.loadCliOptions | protected function loadCliOptions(array $opts)
{
$map = [
'c' => 'conf_file', // config file
's' => 'servers', // server address
'n' => 'workerNum', // worker number do all tasks
'u' => 'user',
'g' => 'group',
'l' => 'logFile',
'p' => 'pidFile',
'r' => 'maxRunTasks', // max run tasks for a worker
'x' => 'maxLifetime',// max lifetime for a worker
't' => 'timeout',
];
// show help
if (isset($opts['h']) || isset($opts['help'])) {
$this->showHelp();
}
// show version
if (isset($opts['V']) || isset($opts['version'])) {
$this->showVersion();
}
// load opts values to config
foreach ($map as $k => $v) {
if (isset($opts[$k]) && $opts[$k]) {
$this->config[$v] = $opts[$k];
}
}
// load Custom Config File
if ($file = $this->config['conf_file']) {
if (!file_exists($file)) {
$this->showHelp("Custom config file {$file} not found.");
}
$config = require $file;
$this->setConfig($config);
}
// watch modify
if (isset($opts['w']) || isset($opts['watch'])) {
$this->config['watch_modify'] = $opts['w'];
}
// run as daemon
if (isset($opts['d']) || isset($opts['daemon'])) {
$this->config['daemon'] = true;
}
// no test
if (isset($opts['no-test'])) {
$this->config['no_test'] = true;
}
// only added tasks
if (isset($opts['tasks']) && ($added = trim($opts['tasks'], ','))) {
$this->config['added_tasks'] = strpos($added, ',') ? explode(',', $added) : [$added];
}
if (isset($opts['v'])) {
$opts['v'] = $opts['v'] === true ? '' : $opts['v'];
switch ($opts['v']) {
case '':
$this->config['logLevel'] = self::LOG_INFO;
break;
case 'v':
$this->config['logLevel'] = self::LOG_PROC_INFO;
break;
case 'vv':
$this->config['logLevel'] = self::LOG_WORKER_INFO;
break;
case 'vvv':
$this->config['logLevel'] = self::LOG_DEBUG;
break;
case 'vvvv':
$this->config['logLevel'] = self::LOG_CRAZY;
break;
default:
// $this->config['logLevel'] = self::LOG_INFO;
break;
}
}
} | php | protected function loadCliOptions(array $opts)
{
$map = [
'c' => 'conf_file', // config file
's' => 'servers', // server address
'n' => 'workerNum', // worker number do all tasks
'u' => 'user',
'g' => 'group',
'l' => 'logFile',
'p' => 'pidFile',
'r' => 'maxRunTasks', // max run tasks for a worker
'x' => 'maxLifetime',// max lifetime for a worker
't' => 'timeout',
];
// show help
if (isset($opts['h']) || isset($opts['help'])) {
$this->showHelp();
}
// show version
if (isset($opts['V']) || isset($opts['version'])) {
$this->showVersion();
}
// load opts values to config
foreach ($map as $k => $v) {
if (isset($opts[$k]) && $opts[$k]) {
$this->config[$v] = $opts[$k];
}
}
// load Custom Config File
if ($file = $this->config['conf_file']) {
if (!file_exists($file)) {
$this->showHelp("Custom config file {$file} not found.");
}
$config = require $file;
$this->setConfig($config);
}
// watch modify
if (isset($opts['w']) || isset($opts['watch'])) {
$this->config['watch_modify'] = $opts['w'];
}
// run as daemon
if (isset($opts['d']) || isset($opts['daemon'])) {
$this->config['daemon'] = true;
}
// no test
if (isset($opts['no-test'])) {
$this->config['no_test'] = true;
}
// only added tasks
if (isset($opts['tasks']) && ($added = trim($opts['tasks'], ','))) {
$this->config['added_tasks'] = strpos($added, ',') ? explode(',', $added) : [$added];
}
if (isset($opts['v'])) {
$opts['v'] = $opts['v'] === true ? '' : $opts['v'];
switch ($opts['v']) {
case '':
$this->config['logLevel'] = self::LOG_INFO;
break;
case 'v':
$this->config['logLevel'] = self::LOG_PROC_INFO;
break;
case 'vv':
$this->config['logLevel'] = self::LOG_WORKER_INFO;
break;
case 'vvv':
$this->config['logLevel'] = self::LOG_DEBUG;
break;
case 'vvvv':
$this->config['logLevel'] = self::LOG_CRAZY;
break;
default:
// $this->config['logLevel'] = self::LOG_INFO;
break;
}
}
} | load the command line options
@param array $opts | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Task/Worker/OptionAndConfigTrait.php#L134-L222 |
chilimatic/chilimatic-framework | lib/request/CLI.php | CLI._transform | public function _transform(array $array = null)
{
if (empty($array)) return;
foreach ($array as $param) {
if (strpos($param, '=') > 0) {
$tmp = explode(Generic::ASSIGNMENT_OPERATOR, $param);
$this->$tmp[0] = $tmp[1];
}
}
return;
} | php | public function _transform(array $array = null)
{
if (empty($array)) return;
foreach ($array as $param) {
if (strpos($param, '=') > 0) {
$tmp = explode(Generic::ASSIGNMENT_OPERATOR, $param);
$this->$tmp[0] = $tmp[1];
}
}
return;
} | adapted "transform" method for the argv we
need a different approach ofc
@param array $array
@return void | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/request/CLI.php#L72-L85 |
bruno-barros/w.eloquent-framework | src/weloquent/Core/Console/WelConsole.php | WelConsole.make | public static function make($app)
{
$app->boot();
$console = with($console = new static('WEL. A w.eloquent console by artisan.', $app::VERSION))
->setLaravel($app)
->setExceptionHandler($app['exception'])
->setAutoExit(false);
$app->instance('artisan', $console);
return $console;
} | php | public static function make($app)
{
$app->boot();
$console = with($console = new static('WEL. A w.eloquent console by artisan.', $app::VERSION))
->setLaravel($app)
->setExceptionHandler($app['exception'])
->setAutoExit(false);
$app->instance('artisan', $console);
return $console;
} | Create a new Console application.
@param \Weloquent\Core\Application $app
@return \Illuminate\Console\Application | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Core/Console/WelConsole.php#L20-L32 |
bruno-barros/w.eloquent-framework | src/weloquent/Core/Console/WelConsole.php | WelConsole.boot | public function boot()
{
$path = $this->laravel['path'].'/config/wel.php';
if (file_exists($path))
{
require $path;
}
// If the event dispatcher is set on the application, we will fire an event
// with the Artisan instance to provide each listener the opportunity to
// register their commands on this application before it gets started.
if (isset($this->laravel['events']))
{
$this->laravel['events']
->fire('artisan.start', array($this));
}
return $this;
} | php | public function boot()
{
$path = $this->laravel['path'].'/config/wel.php';
if (file_exists($path))
{
require $path;
}
// If the event dispatcher is set on the application, we will fire an event
// with the Artisan instance to provide each listener the opportunity to
// register their commands on this application before it gets started.
if (isset($this->laravel['events']))
{
$this->laravel['events']
->fire('artisan.start', array($this));
}
return $this;
} | Boot the Console application.
@return $this | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Core/Console/WelConsole.php#L39-L58 |
Napp/aclcore | src/Role/HasRole.php | HasRole.getMergedPermissions | public function getMergedPermissions(): array
{
$permissions = [];
foreach ($this->getRoles() as $role) {
$permissions = \array_merge($permissions, $role->getPermissions() ?? []);
}
// merge with users own permissions
return \array_merge($permissions, $this->getPermissions());
} | php | public function getMergedPermissions(): array
{
$permissions = [];
foreach ($this->getRoles() as $role) {
$permissions = \array_merge($permissions, $role->getPermissions() ?? []);
}
// merge with users own permissions
return \array_merge($permissions, $this->getPermissions());
} | Returns an array of merged permissions for each group the user is in.
@return array | https://github.com/Napp/aclcore/blob/9f2f48fe0af4c50ed7cbbafe653761da42e39596/src/Role/HasRole.php#L71-L80 |
Scriber/js-translation-bundle | DependencyInjection/Configuration.php | Configuration.getConfigTreeBuilder | public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('scriber_js_translation');
$rootNode
->fixXmlConfig('page')
->children()
->arrayNode('pages')
->useAttributeAsKey('name')
->arrayPrototype()
->useAttributeAsKey('name')
->arrayPrototype()
->scalarPrototype()->end()
->end()
->end()
->end()
->end();
return $treeBuilder;
} | php | public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('scriber_js_translation');
$rootNode
->fixXmlConfig('page')
->children()
->arrayNode('pages')
->useAttributeAsKey('name')
->arrayPrototype()
->useAttributeAsKey('name')
->arrayPrototype()
->scalarPrototype()->end()
->end()
->end()
->end()
->end();
return $treeBuilder;
} | {@inheritdoc} | https://github.com/Scriber/js-translation-bundle/blob/94cbbc2c7f5965175bd693afcbb63bc2eda5299d/DependencyInjection/Configuration.php#L17-L37 |
danhanly/signalert | src/Signalert/Renderer/FoundationRenderer.php | FoundationRenderer.render | public function render(array $notifications, $type = 'info')
{
// Ensure Type is Supported
if (in_array($type, $this->supportedTypes) === false) {
// If not, fall back to default
$type = 'info';
}
// If there aren't any notifications, then return an empty string
if (empty($notifications) === true) {
return '';
}
$html = $this->createHtmlByType($notifications, $type);
return $html;
} | php | public function render(array $notifications, $type = 'info')
{
// Ensure Type is Supported
if (in_array($type, $this->supportedTypes) === false) {
// If not, fall back to default
$type = 'info';
}
// If there aren't any notifications, then return an empty string
if (empty($notifications) === true) {
return '';
}
$html = $this->createHtmlByType($notifications, $type);
return $html;
} | Renders all messages as part of the notification stack, beneath the defined identifier, as HTML
@param array $notifications
@param string $type
@return string|void | https://github.com/danhanly/signalert/blob/21ee50e3fc0352306a2966b555984b5c9eada582/src/Signalert/Renderer/FoundationRenderer.php#L23-L38 |
danhanly/signalert | src/Signalert/Renderer/FoundationRenderer.php | FoundationRenderer.createHtmlByType | private function createHtmlByType(array $notifications, $type)
{
$html = "<div class='alert-box {$type} radius' data-alert>";
foreach ($notifications as $notification) {
$html .= "{$notification}";
// If it's not the last notification, add a line break for the next one
if (end($notifications) !== $notification) {
$html .= "<br />";
}
}
$html .= "<a href='#' class='close'>×</a>";
$html .= "</div>";
return $html;
} | php | private function createHtmlByType(array $notifications, $type)
{
$html = "<div class='alert-box {$type} radius' data-alert>";
foreach ($notifications as $notification) {
$html .= "{$notification}";
// If it's not the last notification, add a line break for the next one
if (end($notifications) !== $notification) {
$html .= "<br />";
}
}
$html .= "<a href='#' class='close'>×</a>";
$html .= "</div>";
return $html;
} | Create and return html string.
@param array $notifications
@param string $type
@return string | https://github.com/danhanly/signalert/blob/21ee50e3fc0352306a2966b555984b5c9eada582/src/Signalert/Renderer/FoundationRenderer.php#L47-L61 |
RadialCorp/magento-core | src/app/code/community/Radial/Order/Model/Observer.php | Radial_Order_Model_Observer.handleSalesConvertQuoteItemToOrderItem | public function handleSalesConvertQuoteItemToOrderItem(Varien_Event_Observer $observer)
{
$quote = $observer->getEvent()->getQuote();
$orderC = Mage::getModel('sales/order')->getCollection()
->addFieldToFilter('quote_id', array('eq' => $quote->getId()))->getAllIds();
foreach( $quote->getAllItems() as $quoteItem )
{
$itemC = Mage::getModel('sales/order_item')->getCollection()
->addFieldToFilter('product_id', array('eq' => $quoteItem->getProductId()))
->addFieldToFilter('order_id', array('in' => $orderC));
if( $itemC->getSize() > 0 )
{
$discountData = $quoteItem->getData('ebayenterprise_order_discount_data');
if($discountData)
{
foreach( $itemC as $item )
{
$item->setData('ebayenterprise_order_discount_data', $discountData);
$item->save();
}
}
}
}
} | php | public function handleSalesConvertQuoteItemToOrderItem(Varien_Event_Observer $observer)
{
$quote = $observer->getEvent()->getQuote();
$orderC = Mage::getModel('sales/order')->getCollection()
->addFieldToFilter('quote_id', array('eq' => $quote->getId()))->getAllIds();
foreach( $quote->getAllItems() as $quoteItem )
{
$itemC = Mage::getModel('sales/order_item')->getCollection()
->addFieldToFilter('product_id', array('eq' => $quoteItem->getProductId()))
->addFieldToFilter('order_id', array('in' => $orderC));
if( $itemC->getSize() > 0 )
{
$discountData = $quoteItem->getData('ebayenterprise_order_discount_data');
if($discountData)
{
foreach( $itemC as $item )
{
$item->setData('ebayenterprise_order_discount_data', $discountData);
$item->save();
}
}
}
}
} | Copy discount data from Quote Item to Order Item (when quote converts to order)
@param Varien_Event_Observer
@return self | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Order/Model/Observer.php#L48-L74 |
schpill/thin | src/Mock.php | Mock.resolveFacadeInstance | protected static function resolveFacadeInstance($name)
{
if (is_object($name)) {
return $name;
}
if (isset(static::$resolvedInstance[$name])) {
return static::$resolvedInstance[$name];
}
return false;
} | php | protected static function resolveFacadeInstance($name)
{
if (is_object($name)) {
return $name;
}
if (isset(static::$resolvedInstance[$name])) {
return static::$resolvedInstance[$name];
}
return false;
} | Resolve the facade root instance from the container.
@param string $name
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Mock.php#L125-L136 |
zhenggg/easy-ihuyi | src/HasHttpRequest.php | HasHttpRequest.getBaseOptions | protected function getBaseOptions()
{
$options = [
'base_uri' => method_exists($this, 'getBaseUri') ? $this->getBaseUri() : '',
'timeout' => property_exists($this, 'timeout') ? $this->timeout : 5.0,
];
return $options;
} | php | protected function getBaseOptions()
{
$options = [
'base_uri' => method_exists($this, 'getBaseUri') ? $this->getBaseUri() : '',
'timeout' => property_exists($this, 'timeout') ? $this->timeout : 5.0,
];
return $options;
} | Return base Guzzle options.
@return array | https://github.com/zhenggg/easy-ihuyi/blob/90ff0da31de3974e2a7b6e59f76f8f1ccec06aca/src/HasHttpRequest.php#L73-L81 |
IftekherSunny/Planet-Framework | src/Sun/Support/Str.php | Str.random | public static function random($size = 32)
{
$bytes = openssl_random_pseudo_bytes($size, $strong);
if ($bytes !== false && $strong !== false) {
$string = '';
while (($len = strlen($string)) < $size) {
$length = $size - $len;
$string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $length);
}
return $string;
}
} | php | public static function random($size = 32)
{
$bytes = openssl_random_pseudo_bytes($size, $strong);
if ($bytes !== false && $strong !== false) {
$string = '';
while (($len = strlen($string)) < $size) {
$length = $size - $len;
$string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $length);
}
return $string;
}
} | To generate random string
@param int $size
@return string | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Support/Str.php#L14-L28 |
syzygypl/remote-media-bundle | src/MediaHandler/RemoteImageHandler.php | RemoteImageHandler.getImageUrl | public function getImageUrl(Media $media, $basepath)
{
if ($media->getUrl() === parse_url($media->getUrl(), PHP_URL_PATH)) {
return $basepath . $media->getUrl();
}
return $media->getUrl();
} | php | public function getImageUrl(Media $media, $basepath)
{
if ($media->getUrl() === parse_url($media->getUrl(), PHP_URL_PATH)) {
return $basepath . $media->getUrl();
}
return $media->getUrl();
} | @param Media $media The media entity
@param string $basepath The base path
@return string | https://github.com/syzygypl/remote-media-bundle/blob/2be3284d5baf8a12220ecbaf63043eb105eb87ef/src/MediaHandler/RemoteImageHandler.php#L82-L89 |
znframework/package-helpers | Rounder.php | Rounder.down | public static function down(Float $number, Int $count = 0) : Float
{
if( $count === 0 )
{
return floor($number);
}
$numbers = explode(".", $number);
$edit = 0;
if( ! empty($numbers[1]) )
{
$edit = substr($numbers[1], 0, $count);
return (float) $numbers[0].".".$edit;
}
else
{
throw new LogicException('[Rounder::down()] -> Decimal values can not be specified for the integer! Check 2.($count) parameter!');
}
} | php | public static function down(Float $number, Int $count = 0) : Float
{
if( $count === 0 )
{
return floor($number);
}
$numbers = explode(".", $number);
$edit = 0;
if( ! empty($numbers[1]) )
{
$edit = substr($numbers[1], 0, $count);
return (float) $numbers[0].".".$edit;
}
else
{
throw new LogicException('[Rounder::down()] -> Decimal values can not be specified for the integer! Check 2.($count) parameter!');
}
} | Down
@param float $number
@param int $count = 0
@return float | https://github.com/znframework/package-helpers/blob/c78502263cdda5c14626a1abf7fc7e02dd2bd57d/Rounder.php#L37-L58 |
znframework/package-helpers | Rounder.php | Rounder.up | public static function up(Float $number, Int $count = 0) : Float
{
if( $count === 0 )
{
return ceil($number);
}
$numbers = explode(".", $number);
$edit = 0;
if( ! empty($numbers[1]) )
{
$edit = substr($numbers[1], 0, $count);
return (float) $numbers[0].".".($edit + 1);
}
else
{
throw new LogicException('[Rounder::up()] -> Decimal values can not be specified for the integer! Check 2.($count) parameter!');
}
} | php | public static function up(Float $number, Int $count = 0) : Float
{
if( $count === 0 )
{
return ceil($number);
}
$numbers = explode(".", $number);
$edit = 0;
if( ! empty($numbers[1]) )
{
$edit = substr($numbers[1], 0, $count);
return (float) $numbers[0].".".($edit + 1);
}
else
{
throw new LogicException('[Rounder::up()] -> Decimal values can not be specified for the integer! Check 2.($count) parameter!');
}
} | Up
@param float $number
@param int $count = 0
@return float | https://github.com/znframework/package-helpers/blob/c78502263cdda5c14626a1abf7fc7e02dd2bd57d/Rounder.php#L68-L89 |
yii2lab/yii2-rbac | src/console/controllers/RoleController.php | RoleController.actionUpdate | public function actionUpdate() {
try {
\App::$domain->rbac->role->update();
} catch(NotAuthenticatedException $e) {
\App::$domain->account->auth->breakSession();
echo 'NotAuthenticatedException';
return;
} catch(UnauthorizedHttpException $e) {
\App::$domain->account->auth->breakSession();
echo 'UnauthorizedHttpException';
return;
}
echo 'success';
} | php | public function actionUpdate() {
try {
\App::$domain->rbac->role->update();
} catch(NotAuthenticatedException $e) {
\App::$domain->account->auth->breakSession();
echo 'NotAuthenticatedException';
return;
} catch(UnauthorizedHttpException $e) {
\App::$domain->account->auth->breakSession();
echo 'UnauthorizedHttpException';
return;
}
echo 'success';
} | Search and add RBAC rules | https://github.com/yii2lab/yii2-rbac/blob/e72ac0359af660690c161451f864208b2d20919d/src/console/controllers/RoleController.php#L21-L35 |
nekudo/shiny_gears | src/Worker.php | Worker.getJobInfo | public function getJobInfo($Job) : void
{
$uptimeSeconds = time() - $this->startupTime;
$uptimeSeconds = ($uptimeSeconds === 0) ? 1 : $uptimeSeconds;
$avgJobsMin = $this->jobsTotal / ($uptimeSeconds / 60);
$avgJobsMin = round($avgJobsMin, 2);
$response = [
'jobs_total' => $this->jobsTotal,
'avg_jobs_min' => $avgJobsMin,
'uptime_seconds' => $uptimeSeconds,
];
$Job->sendData(json_encode($response));
} | php | public function getJobInfo($Job) : void
{
$uptimeSeconds = time() - $this->startupTime;
$uptimeSeconds = ($uptimeSeconds === 0) ? 1 : $uptimeSeconds;
$avgJobsMin = $this->jobsTotal / ($uptimeSeconds / 60);
$avgJobsMin = round($avgJobsMin, 2);
$response = [
'jobs_total' => $this->jobsTotal,
'avg_jobs_min' => $avgJobsMin,
'uptime_seconds' => $uptimeSeconds,
];
$Job->sendData(json_encode($response));
} | Returns information about jobs handled.
@param \GearmanJob $Job
@return void | https://github.com/nekudo/shiny_gears/blob/5cb72e1efc7df1c9d97c8bf14ef1d8ba6d44df9a/src/Worker.php#L154-L166 |
nekudo/shiny_gears | src/Worker.php | Worker.updatePidFile | public function updatePidFile() : void
{
$pidFolder = $this->getRunPath($this->poolName);
if (!file_exists($pidFolder)) {
mkdir($pidFolder, 0755, true);
}
$pidFile = $pidFolder . '/' . $this->workerName . '.pid';
$pid = getmypid();
if (file_put_contents($pidFile, $pid) === false) {
throw new WorkerException('Could not create PID file.');
}
} | php | public function updatePidFile() : void
{
$pidFolder = $this->getRunPath($this->poolName);
if (!file_exists($pidFolder)) {
mkdir($pidFolder, 0755, true);
}
$pidFile = $pidFolder . '/' . $this->workerName . '.pid';
$pid = getmypid();
if (file_put_contents($pidFile, $pid) === false) {
throw new WorkerException('Could not create PID file.');
}
} | Updates PID file for the worker.
@return void
@throws WorkerException | https://github.com/nekudo/shiny_gears/blob/5cb72e1efc7df1c9d97c8bf14ef1d8ba6d44df9a/src/Worker.php#L174-L185 |
LapaLabs/YoutubeHelper | Resource/VideoResource.php | VideoResource.setId | public function setId($id)
{
$this->id = (string)$id;
if (!$this->isIdValid($this->id)) {
throw new InvalidIdException($this);
}
return $this;
} | php | public function setId($id)
{
$this->id = (string)$id;
if (!$this->isIdValid($this->id)) {
throw new InvalidIdException($this);
}
return $this;
} | @param string $id
@return $this
@throws InvalidIdException | https://github.com/LapaLabs/YoutubeHelper/blob/b94fd4700881494d24f14fb39ed8093215d0b25b/Resource/VideoResource.php#L79-L88 |
mlocati/concrete5-translation-library | src/Parser/Dynamic.php | Dynamic.parseRunningConcrete5Do | protected function parseRunningConcrete5Do(\Gettext\Translations $translations, $concrete5version, $subParsersFilter)
{
foreach ($this->getSubParsers() as $dynamicItemParser) {
if ((!is_array($subParsersFilter)) || in_array($dynamicItemParser->getDynamicItemsParserHandler(), $subParsersFilter, true)) {
$dynamicItemParser->parse($translations, $concrete5version);
}
}
} | php | protected function parseRunningConcrete5Do(\Gettext\Translations $translations, $concrete5version, $subParsersFilter)
{
foreach ($this->getSubParsers() as $dynamicItemParser) {
if ((!is_array($subParsersFilter)) || in_array($dynamicItemParser->getDynamicItemsParserHandler(), $subParsersFilter, true)) {
$dynamicItemParser->parse($translations, $concrete5version);
}
}
} | {@inheritdoc}
@see \C5TL\Parser::parseRunningConcrete5Do() | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser/Dynamic.php#L35-L42 |
mlocati/concrete5-translation-library | src/Parser/Dynamic.php | Dynamic.getSubParsers | public function getSubParsers()
{
$result = array();
$dir = __DIR__.'/DynamicItem';
if (is_dir($dir) && is_readable($dir)) {
$matches = null;
foreach (scandir($dir) as $item) {
if (($item[0] !== '.') && preg_match('/^(.+)\.php$/i', $item, $matches) && ($matches[1] !== 'DynamicItem')) {
$fqClassName = '\\'.__NAMESPACE__.'\\DynamicItem\\'.$matches[1];
$instance = new $fqClassName();
/* @var $instance \C5TL\Parser\DynamicItem\DynamicItem */
$result[$instance->getDynamicItemsParserHandler()] = $instance;
}
}
}
return $result;
} | php | public function getSubParsers()
{
$result = array();
$dir = __DIR__.'/DynamicItem';
if (is_dir($dir) && is_readable($dir)) {
$matches = null;
foreach (scandir($dir) as $item) {
if (($item[0] !== '.') && preg_match('/^(.+)\.php$/i', $item, $matches) && ($matches[1] !== 'DynamicItem')) {
$fqClassName = '\\'.__NAMESPACE__.'\\DynamicItem\\'.$matches[1];
$instance = new $fqClassName();
/* @var $instance \C5TL\Parser\DynamicItem\DynamicItem */
$result[$instance->getDynamicItemsParserHandler()] = $instance;
}
}
}
return $result;
} | Returns the fully-qualified class names of all the sub-parsers.
@return array[\C5TL\Parser\DynamicItem\DynamicItem] | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser/Dynamic.php#L49-L66 |
hummer2k/ConLayout | src/Listener/ActionHandlesListener.php | ActionHandlesListener.injectActionHandles | public function injectActionHandles(EventInterface $event)
{
$handles = $this->getActionHandles($event);
foreach ($handles as $handle) {
$this->updater->addHandle($handle);
}
} | php | public function injectActionHandles(EventInterface $event)
{
$handles = $this->getActionHandles($event);
foreach ($handles as $handle) {
$this->updater->addHandle($handle);
}
} | Callback handler invoked when the dispatch event is triggered.
@param EventInterface $event
@return void | https://github.com/hummer2k/ConLayout/blob/15e472eaabc9b23ec6a5547524874e30d95e8d3e/src/Listener/ActionHandlesListener.php#L102-L108 |
hummer2k/ConLayout | src/Listener/ActionHandlesListener.php | ActionHandlesListener.getActionHandles | protected function getActionHandles(EventInterface $event)
{
/* @var $routeMatch MvcEvent */
$routeMatch = $event->getRouteMatch();
$controller = $event->getTarget();
if (is_object($controller)) {
$controller = get_class($controller);
}
$routeMatchController = $routeMatch->getParam('controller', '');
if (!$controller || ($this->preferRouteMatchController && $routeMatchController)) {
$controller = $routeMatchController;
}
$template = $this->mapController($controller);
if (!$template) {
$module = $this->deriveModuleNamespace($controller);
if ($namespace = $routeMatch->getParam(ModuleRouteListener::MODULE_NAMESPACE)) {
$controllerSubNs = $this->deriveControllerSubNamespace($namespace);
if (!empty($controllerSubNs)) {
if (!empty($module)) {
$module .= self::TEMPLATE_SEPARATOR . $controllerSubNs;
} else {
$module = $controllerSubNs;
}
}
}
$controller = $this->deriveControllerClass($controller);
$template = $this->inflectName($module);
if (!empty($template)) {
$template .= self::TEMPLATE_SEPARATOR;
}
$template .= $this->inflectName($controller);
}
$action = $routeMatch->getParam('action');
if (null !== $action) {
$template .= self::TEMPLATE_SEPARATOR . $this->inflectName($action);
}
$priority = 0;
$actionHandles = [];
$previousHandle = '';
$templateParts = explode(self::TEMPLATE_SEPARATOR, $template);
foreach ($templateParts as $name) {
$priority += 10;
$actionHandles[] = new Handle($previousHandle.$name, $priority);
$previousHandle .= $name.self::TEMPLATE_SEPARATOR;
}
return $actionHandles;
} | php | protected function getActionHandles(EventInterface $event)
{
/* @var $routeMatch MvcEvent */
$routeMatch = $event->getRouteMatch();
$controller = $event->getTarget();
if (is_object($controller)) {
$controller = get_class($controller);
}
$routeMatchController = $routeMatch->getParam('controller', '');
if (!$controller || ($this->preferRouteMatchController && $routeMatchController)) {
$controller = $routeMatchController;
}
$template = $this->mapController($controller);
if (!$template) {
$module = $this->deriveModuleNamespace($controller);
if ($namespace = $routeMatch->getParam(ModuleRouteListener::MODULE_NAMESPACE)) {
$controllerSubNs = $this->deriveControllerSubNamespace($namespace);
if (!empty($controllerSubNs)) {
if (!empty($module)) {
$module .= self::TEMPLATE_SEPARATOR . $controllerSubNs;
} else {
$module = $controllerSubNs;
}
}
}
$controller = $this->deriveControllerClass($controller);
$template = $this->inflectName($module);
if (!empty($template)) {
$template .= self::TEMPLATE_SEPARATOR;
}
$template .= $this->inflectName($controller);
}
$action = $routeMatch->getParam('action');
if (null !== $action) {
$template .= self::TEMPLATE_SEPARATOR . $this->inflectName($action);
}
$priority = 0;
$actionHandles = [];
$previousHandle = '';
$templateParts = explode(self::TEMPLATE_SEPARATOR, $template);
foreach ($templateParts as $name) {
$priority += 10;
$actionHandles[] = new Handle($previousHandle.$name, $priority);
$previousHandle .= $name.self::TEMPLATE_SEPARATOR;
}
return $actionHandles;
} | Retrieve the action handles from the matched route.
@param EventInterface $event
@return array | https://github.com/hummer2k/ConLayout/blob/15e472eaabc9b23ec6a5547524874e30d95e8d3e/src/Listener/ActionHandlesListener.php#L127-L183 |
mover-io/belt | lib/Trace.php | Trace._stack | public function _stack($depth=5,$start=0,$formatter=null) {
if($formatter == null) {
$formatter = function($item, $index) {
if(isset($item['file'])) {
$file = basename($item['file']);
return "{$file}:{$item['line']}";
} else {
return "{$item['function']}";
}
};
}
$bt = array_slice(debug_backtrace(),$start,$depth);
$result = array();
foreach($bt as $index=>$item) {
$result[] = $formatter($item,$index);
}
return array_filter($result);
} | php | public function _stack($depth=5,$start=0,$formatter=null) {
if($formatter == null) {
$formatter = function($item, $index) {
if(isset($item['file'])) {
$file = basename($item['file']);
return "{$file}:{$item['line']}";
} else {
return "{$item['function']}";
}
};
}
$bt = array_slice(debug_backtrace(),$start,$depth);
$result = array();
foreach($bt as $index=>$item) {
$result[] = $formatter($item,$index);
}
return array_filter($result);
} | ################ | https://github.com/mover-io/belt/blob/c966a70aa0f4eb51be55bbb86c89b1e85b773d68/lib/Trace.php#L69-L86 |
mover-io/belt | lib/Trace.php | Trace.writeLn | protected function writeLn($string)
{
$printer = $this->options['printer'];
if ($printer === 'error_log') {
error_log($string);
} elseif (is_string($printer) && Text::startsWith($printer, 'file://')) {
file_put_contents(Text::ensureNoPrefix($printer, 'file://'), $string."\n", FILE_APPEND);
} elseif (is_callable($this->options['printer'])) {
call_user_func($this->options['printer'], $string);
}
} | php | protected function writeLn($string)
{
$printer = $this->options['printer'];
if ($printer === 'error_log') {
error_log($string);
} elseif (is_string($printer) && Text::startsWith($printer, 'file://')) {
file_put_contents(Text::ensureNoPrefix($printer, 'file://'), $string."\n", FILE_APPEND);
} elseif (is_callable($this->options['printer'])) {
call_user_func($this->options['printer'], $string);
}
} | ############### | https://github.com/mover-io/belt/blob/c966a70aa0f4eb51be55bbb86c89b1e85b773d68/lib/Trace.php#L95-L105 |
mover-io/belt | lib/Trace.php | Trace._generateLine | public function _generateLine($string, $start=5) {
if($this->options['trace']['enabled']) {
$trace = $this->_stackString($this->options['trace']['depth'], $start+$this->options['trace']['offset'], $this->options['separator']);
} else {
$trace = "";
}
$result = "";
if($this->options['timestamp']['enabled']) {
$result .= date('c').' ';
}
$result .= implode($this->options['separator'],array_filter(array($trace,$string)));
if($this->options['banner']['enabled']) {
$result = $this->_generateBanner($result);
}
return $result;
} | php | public function _generateLine($string, $start=5) {
if($this->options['trace']['enabled']) {
$trace = $this->_stackString($this->options['trace']['depth'], $start+$this->options['trace']['offset'], $this->options['separator']);
} else {
$trace = "";
}
$result = "";
if($this->options['timestamp']['enabled']) {
$result .= date('c').' ';
}
$result .= implode($this->options['separator'],array_filter(array($trace,$string)));
if($this->options['banner']['enabled']) {
$result = $this->_generateBanner($result);
}
return $result;
} | Common method for generating the main logging line. | https://github.com/mover-io/belt/blob/c966a70aa0f4eb51be55bbb86c89b1e85b773d68/lib/Trace.php#L149-L169 |
mover-io/belt | lib/Trace.php | Trace._toFile | public function _toFile($file = null) {
$file = $file ?: sys_get_temp_dir() . '/belt_trace.log';
$this->options['printer'] = 'file://'.$file;
return $this;
} | php | public function _toFile($file = null) {
$file = $file ?: sys_get_temp_dir() . '/belt_trace.log';
$this->options['printer'] = 'file://'.$file;
return $this;
} | Use file based output. Useful to work around nginx's log swallowing
annoyingness.
@fluent | https://github.com/mover-io/belt/blob/c966a70aa0f4eb51be55bbb86c89b1e85b773d68/lib/Trace.php#L190-L194 |
phpcq/autoload-validation | src/ClassMapGenerator.php | ClassMapGenerator.scan | public function scan($path, $whitelist = null, $namespace = null, &$messages = null)
{
return static::createMap($path, $whitelist, $namespace, $messages, $this->blackListRegex);
} | php | public function scan($path, $whitelist = null, $namespace = null, &$messages = null)
{
return static::createMap($path, $whitelist, $namespace, $messages, $this->blackListRegex);
} | Iterate over all files in the given directory searching for classes.
@param \Iterator|string $path The path to search in or an iterator.
@param string $whitelist Regex that matches against the file path.
@param string $namespace Optional namespace prefix to filter by.
@param string[] $messages The error message list to which errors shall be appended to.
@return array A class map array
@throws \RuntimeException When the path could not be scanned.
@SuppressWarnings(PHPMD.CyclomaticComplexity)
@SuppressWarnings(PHPMD.NPathComplexity) | https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/ClassMapGenerator.php#L66-L69 |
phpcq/autoload-validation | src/ClassMapGenerator.php | ClassMapGenerator.dump | public static function dump($dirs, $file, $blackList = null)
{
$maps = array();
foreach ($dirs as $dir) {
$maps = array_merge($maps, static::createMap($dir, null, null, $blackList));
}
file_put_contents($file, sprintf('<?php return %s;', var_export($maps, true)));
} | php | public static function dump($dirs, $file, $blackList = null)
{
$maps = array();
foreach ($dirs as $dir) {
$maps = array_merge($maps, static::createMap($dir, null, null, $blackList));
}
file_put_contents($file, sprintf('<?php return %s;', var_export($maps, true)));
} | Generate a class map file.
@param \Traversable $dirs Directories or a single path to search in.
@param string $file The name of the class map file.
@param string[] $blackList Optional list of blacklist regex for files to exclude.
@return void | https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/ClassMapGenerator.php#L82-L91 |
phpcq/autoload-validation | src/ClassMapGenerator.php | ClassMapGenerator.createMap | public static function createMap($path, $whitelist = null, $namespace = null, &$messages = null, $blackList = null)
{
if (is_string($path)) {
if (is_file($path)) {
$path = array(new \SplFileInfo($path));
} elseif (is_dir($path)) {
$path = Finder::create()->files()->followLinks()->name('/\.(php|inc|hh)$/')->in($path);
} else {
throw new \RuntimeException(
'Could not scan for classes inside "'.$path.
'" which does not appear to be a file nor a folder'
);
}
}
$map = array();
foreach ($path as $file) {
$filePath = $file->getRealPath();
if ($blackList && self::pathMatchesRegex($filePath, $blackList)) {
continue;
}
if (!in_array(pathinfo($filePath, PATHINFO_EXTENSION), array('php', 'inc', 'hh'))) {
continue;
}
if ($whitelist && !preg_match($whitelist, strtr($filePath, '\\', '/'))) {
continue;
}
$classes = self::findClasses($filePath);
foreach ($classes as $class) {
// skip classes not within the given namespace prefix
if (null !== $namespace && 0 !== strpos($class, $namespace)) {
continue;
}
if (!isset($map[$class])) {
$map[$class] = $filePath;
} elseif (null !== $messages
&& ($map[$class] !== $filePath)
&& !preg_match('{/(test|fixture|example)s?/}i', strtr($map[$class].' '.$filePath, '\\', '/'))
) {
$messages[] = '<warning>Warning: Ambiguous class resolution, "'.$class.'"'.
' was found in both "'.$map[$class].'" and "'.$filePath.'", the first will be used.</warning>';
}
}
}
return $map;
} | php | public static function createMap($path, $whitelist = null, $namespace = null, &$messages = null, $blackList = null)
{
if (is_string($path)) {
if (is_file($path)) {
$path = array(new \SplFileInfo($path));
} elseif (is_dir($path)) {
$path = Finder::create()->files()->followLinks()->name('/\.(php|inc|hh)$/')->in($path);
} else {
throw new \RuntimeException(
'Could not scan for classes inside "'.$path.
'" which does not appear to be a file nor a folder'
);
}
}
$map = array();
foreach ($path as $file) {
$filePath = $file->getRealPath();
if ($blackList && self::pathMatchesRegex($filePath, $blackList)) {
continue;
}
if (!in_array(pathinfo($filePath, PATHINFO_EXTENSION), array('php', 'inc', 'hh'))) {
continue;
}
if ($whitelist && !preg_match($whitelist, strtr($filePath, '\\', '/'))) {
continue;
}
$classes = self::findClasses($filePath);
foreach ($classes as $class) {
// skip classes not within the given namespace prefix
if (null !== $namespace && 0 !== strpos($class, $namespace)) {
continue;
}
if (!isset($map[$class])) {
$map[$class] = $filePath;
} elseif (null !== $messages
&& ($map[$class] !== $filePath)
&& !preg_match('{/(test|fixture|example)s?/}i', strtr($map[$class].' '.$filePath, '\\', '/'))
) {
$messages[] = '<warning>Warning: Ambiguous class resolution, "'.$class.'"'.
' was found in both "'.$map[$class].'" and "'.$filePath.'", the first will be used.</warning>';
}
}
}
return $map;
} | Iterate over all files in the given directory searching for classes.
@param \Iterator|string $path The path to search in or an iterator.
@param string $whitelist Regex that matches against the file path.
@param string $namespace Optional namespace prefix to filter by.
@param string[] $messages The error message list to which errors shall be appended to.
@param string[] $blackList Optional list of blacklist regex for files to exclude.
@return array A class map array
@throws \RuntimeException When the path could not be scanned.
@SuppressWarnings(PHPMD.CyclomaticComplexity)
@SuppressWarnings(PHPMD.NPathComplexity) | https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/ClassMapGenerator.php#L113-L166 |
phpcq/autoload-validation | src/ClassMapGenerator.php | ClassMapGenerator.pathMatchesRegex | private static function pathMatchesRegex($path, $blackList)
{
foreach ($blackList as $item) {
$match = '#' . strtr($item, '#', '\#') . '#';
if (preg_match($match, $path)) {
return true;
}
}
return false;
} | php | private static function pathMatchesRegex($path, $blackList)
{
foreach ($blackList as $item) {
$match = '#' . strtr($item, '#', '\#') . '#';
if (preg_match($match, $path)) {
return true;
}
}
return false;
} | Test path against blacklist regex list.
@param string $path The path to check.
@param string[] $blackList List of blacklist regexes.
@return bool | https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/ClassMapGenerator.php#L177-L187 |
phpcq/autoload-validation | src/ClassMapGenerator.php | ClassMapGenerator.findClasses | private static function findClasses($path)
{
$extraTypes = self::determineExtraTypes();
// @codingStandardsIgnoreStart
$contents = @php_strip_whitespace($path);
// @codingStandardsIgnoreEnd
if (!$contents) {
if (!file_exists($path)) {
$message = 'File at "%s" does not exist, check your classmap definitions';
} elseif (!is_readable($path)) {
$message = 'File at "%s" is not readable, check its permissions';
} elseif ('' === trim(file_get_contents($path))) {
// The input file was really empty and thus contains no classes
return array();
} else {
$message = 'File at "%s" could not be parsed as PHP, it may be binary or corrupted';
}
$error = error_get_last();
if (isset($error['message'])) {
$message .= PHP_EOL . 'The following message may be helpful:' . PHP_EOL . $error['message'];
}
throw new \RuntimeException(sprintf($message, $path));
}
// return early if there is no chance of matching anything in this file
if (!preg_match('{\b(?:class|interface'.$extraTypes.')\s}i', $contents)) {
return array();
}
$matches = self::extractClasses($contents, $extraTypes);
$classes = self::buildClassList($matches);
return $classes;
} | php | private static function findClasses($path)
{
$extraTypes = self::determineExtraTypes();
// @codingStandardsIgnoreStart
$contents = @php_strip_whitespace($path);
// @codingStandardsIgnoreEnd
if (!$contents) {
if (!file_exists($path)) {
$message = 'File at "%s" does not exist, check your classmap definitions';
} elseif (!is_readable($path)) {
$message = 'File at "%s" is not readable, check its permissions';
} elseif ('' === trim(file_get_contents($path))) {
// The input file was really empty and thus contains no classes
return array();
} else {
$message = 'File at "%s" could not be parsed as PHP, it may be binary or corrupted';
}
$error = error_get_last();
if (isset($error['message'])) {
$message .= PHP_EOL . 'The following message may be helpful:' . PHP_EOL . $error['message'];
}
throw new \RuntimeException(sprintf($message, $path));
}
// return early if there is no chance of matching anything in this file
if (!preg_match('{\b(?:class|interface'.$extraTypes.')\s}i', $contents)) {
return array();
}
$matches = self::extractClasses($contents, $extraTypes);
$classes = self::buildClassList($matches);
return $classes;
} | Extract the classes in the given file.
@param string $path The file to check.
@throws \RuntimeException When the file does not exist or is not accessible.
@return array The found classes. | https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/ClassMapGenerator.php#L198-L232 |
phpcq/autoload-validation | src/ClassMapGenerator.php | ClassMapGenerator.extractClasses | private static function extractClasses($contents, $extraTypes)
{
// strip heredocs/nowdocs
$contents = preg_replace(
'{<<<\s*(\'?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\2(?=\r\n|\n|\r|;)}s',
'null',
$contents
);
// strip strings
$contents = preg_replace(
'{"[^"\\\\]*+(\\\\.[^"\\\\]*+)*+"|\'[^\'\\\\]*+(\\\\.[^\'\\\\]*+)*+\'}s',
'null',
$contents
);
// strip leading non-php code if needed
if (substr($contents, 0, 2) !== '<?') {
$contents = preg_replace('{^.+?<\?}s', '<?', $contents, 1, $replacements);
if ($replacements === 0) {
return array();
}
}
// strip non-php blocks in the file
$contents = preg_replace('{\?>.+<\?}s', '?><?', $contents);
// strip trailing non-php code if needed
$pos = strrpos($contents, '?>');
if (false !== $pos && false === strpos(substr($contents, $pos), '<?')) {
$contents = substr($contents, 0, $pos);
}
preg_match_all(
'{
(?:
\b(?<![\$:>])(?P<type>class|interface' . $extraTypes .
') \s+ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*)
| \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*' .
'(?:\s*\\\\\s*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*)? \s*[\{;]
)
}ix',
$contents,
$matches
);
return $matches;
} | php | private static function extractClasses($contents, $extraTypes)
{
// strip heredocs/nowdocs
$contents = preg_replace(
'{<<<\s*(\'?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\2(?=\r\n|\n|\r|;)}s',
'null',
$contents
);
// strip strings
$contents = preg_replace(
'{"[^"\\\\]*+(\\\\.[^"\\\\]*+)*+"|\'[^\'\\\\]*+(\\\\.[^\'\\\\]*+)*+\'}s',
'null',
$contents
);
// strip leading non-php code if needed
if (substr($contents, 0, 2) !== '<?') {
$contents = preg_replace('{^.+?<\?}s', '<?', $contents, 1, $replacements);
if ($replacements === 0) {
return array();
}
}
// strip non-php blocks in the file
$contents = preg_replace('{\?>.+<\?}s', '?><?', $contents);
// strip trailing non-php code if needed
$pos = strrpos($contents, '?>');
if (false !== $pos && false === strpos(substr($contents, $pos), '<?')) {
$contents = substr($contents, 0, $pos);
}
preg_match_all(
'{
(?:
\b(?<![\$:>])(?P<type>class|interface' . $extraTypes .
') \s+ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*)
| \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*' .
'(?:\s*\\\\\s*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*)? \s*[\{;]
)
}ix',
$contents,
$matches
);
return $matches;
} | Prepare the file contents.
@param string $contents The file contents.
@param string $extraTypes The extra types to match.
@return array | https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/ClassMapGenerator.php#L260-L303 |
phpcq/autoload-validation | src/ClassMapGenerator.php | ClassMapGenerator.buildClassList | private static function buildClassList($matches)
{
if (array() === $matches) {
return array();
}
$classes = array();
$namespace = '';
for ($i = 0, $len = count($matches['type']); $i < $len; $i++) {
if (!empty($matches['ns'][$i])) {
$namespace = str_replace(array(' ', "\t", "\r", "\n"), '', $matches['nsname'][$i]) . '\\';
} else {
$name = $matches['name'][$i];
// skip anon classes extending/implementing
if ($name === 'extends' || $name === 'implements') {
continue;
}
if ($name[0] === ':') {
// This is an XHP class, https://github.com/facebook/xhp
$name = 'xhp' . substr(str_replace(array('-', ':'), array('_', '__'), $name), 1);
} elseif ($matches['type'][$i] === 'enum') {
// In Hack, something like:
// enum Foo: int { HERP = '123'; }
// The regex above captures the colon, which isn't part of
// the class name.
$name = rtrim($name, ':');
}
$classes[] = ltrim($namespace . $name, '\\');
}
}
return $classes;
} | php | private static function buildClassList($matches)
{
if (array() === $matches) {
return array();
}
$classes = array();
$namespace = '';
for ($i = 0, $len = count($matches['type']); $i < $len; $i++) {
if (!empty($matches['ns'][$i])) {
$namespace = str_replace(array(' ', "\t", "\r", "\n"), '', $matches['nsname'][$i]) . '\\';
} else {
$name = $matches['name'][$i];
// skip anon classes extending/implementing
if ($name === 'extends' || $name === 'implements') {
continue;
}
if ($name[0] === ':') {
// This is an XHP class, https://github.com/facebook/xhp
$name = 'xhp' . substr(str_replace(array('-', ':'), array('_', '__'), $name), 1);
} elseif ($matches['type'][$i] === 'enum') {
// In Hack, something like:
// enum Foo: int { HERP = '123'; }
// The regex above captures the colon, which isn't part of
// the class name.
$name = rtrim($name, ':');
}
$classes[] = ltrim($namespace . $name, '\\');
}
}
return $classes;
} | Build the class list from the passed matches.
@param array $matches The matches from extractClasses().
@return array | https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/ClassMapGenerator.php#L312-L345 |
inhere/php-library-plus | libs/Files/Captcha.php | Captcha.drawLine | public function drawLine()
{
for ($i = 1; $i <= $this->lineNum; $i++) {
$lineColor = imagecolorallocate($this->img, random_int(150, 250), random_int(150, 250), random_int(150, 250));
//($this->img,起点坐标x.y,终点坐标x.y,颜色)
imageline(
$this->img, random_int(0, $this->width), random_int(0, $this->height),
random_int(0, $this->width), random_int(0, $this->height), $lineColor
);
}
return $this;
} | php | public function drawLine()
{
for ($i = 1; $i <= $this->lineNum; $i++) {
$lineColor = imagecolorallocate($this->img, random_int(150, 250), random_int(150, 250), random_int(150, 250));
//($this->img,起点坐标x.y,终点坐标x.y,颜色)
imageline(
$this->img, random_int(0, $this->width), random_int(0, $this->height),
random_int(0, $this->width), random_int(0, $this->height), $lineColor
);
}
return $this;
} | 画干扰直线-可选
@return $this | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Files/Captcha.php#L140-L152 |
inhere/php-library-plus | libs/Files/Captcha.php | Captcha.drawAec | public function drawAec()
{
for ($i = 1; $i <= $this->aecNum; $i++) {
$arcColor = imagecolorallocate($this->img, random_int(150, 250), random_int(150, 250), random_int(150, 250));
imagearc(
$this->img, random_int(0, $this->width), random_int(0, $this->height), random_int(0, 100),
random_int(0, 100), random_int(-90, 90), random_int(70, 360), $arcColor
);
}
return $this;
} | php | public function drawAec()
{
for ($i = 1; $i <= $this->aecNum; $i++) {
$arcColor = imagecolorallocate($this->img, random_int(150, 250), random_int(150, 250), random_int(150, 250));
imagearc(
$this->img, random_int(0, $this->width), random_int(0, $this->height), random_int(0, 100),
random_int(0, 100), random_int(-90, 90), random_int(70, 360), $arcColor
);
}
return $this;
} | 画干扰弧线-可选
@return $this | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Files/Captcha.php#L158-L169 |
inhere/php-library-plus | libs/Files/Captcha.php | Captcha.drawChar | public function drawChar()
{
$x = ($this->width - 10) / $this->charNum;
$captchaStr = '';//保存产生的字符串
for ($i = 0; $i < $this->charNum; $i++) {
$char = $this->codeStr[random_int(0, \strlen($this->codeStr) - 1)];
$captchaStr .= $char;
$fontColor = imagecolorallocate($this->img, random_int(80, 200), random_int(80, 200), random_int(80, 200));
imagefttext(
$this->img, $this->fontSize, random_int(-30, 30), $i * $x + random_int(6, 10),
random_int($this->height / 1.3, $this->height - 5), $fontColor,
$this->font, $char
);
}
$this->captcha = strtolower($captchaStr);
//把纯的验证码字符串放置到SESSION中进行保存,便于后面进行验证对比
$_SESSION[static::$sessionKey] = md5($this->captcha);
//设置cookie到前端浏览器,可用于前端验证
setcookie(static::$sessionKey, md5($this->captcha));
} | php | public function drawChar()
{
$x = ($this->width - 10) / $this->charNum;
$captchaStr = '';//保存产生的字符串
for ($i = 0; $i < $this->charNum; $i++) {
$char = $this->codeStr[random_int(0, \strlen($this->codeStr) - 1)];
$captchaStr .= $char;
$fontColor = imagecolorallocate($this->img, random_int(80, 200), random_int(80, 200), random_int(80, 200));
imagefttext(
$this->img, $this->fontSize, random_int(-30, 30), $i * $x + random_int(6, 10),
random_int($this->height / 1.3, $this->height - 5), $fontColor,
$this->font, $char
);
}
$this->captcha = strtolower($captchaStr);
//把纯的验证码字符串放置到SESSION中进行保存,便于后面进行验证对比
$_SESSION[static::$sessionKey] = md5($this->captcha);
//设置cookie到前端浏览器,可用于前端验证
setcookie(static::$sessionKey, md5($this->captcha));
} | 产生随机字符,验证码,并写入图像 | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Files/Captcha.php#L172-L195 |
inhere/php-library-plus | libs/Files/Captcha.php | Captcha.drawChars | public function drawChars()
{
for ($i = 0; $i < $this->fontNum; $i++) {
$char = $this->codeStr[random_int(0, \strlen($this->codeStr) - 1)];
$fontColor = imagecolorallocate($this->img, random_int(180, 240), random_int(180, 240), random_int(180, 240));
imagefttext(
$this->img, random_int(4, 8), random_int(-30, 40), random_int(8, $this->width - 10),
random_int(10, $this->height - 10), $fontColor, $this->font, $char
);
}
} | php | public function drawChars()
{
for ($i = 0; $i < $this->fontNum; $i++) {
$char = $this->codeStr[random_int(0, \strlen($this->codeStr) - 1)];
$fontColor = imagecolorallocate($this->img, random_int(180, 240), random_int(180, 240), random_int(180, 240));
imagefttext(
$this->img, random_int(4, 8), random_int(-30, 40), random_int(8, $this->width - 10),
random_int(10, $this->height - 10), $fontColor, $this->font, $char
);
}
} | 填充干扰字符-可选 | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Files/Captcha.php#L198-L208 |
inhere/php-library-plus | libs/Files/Captcha.php | Captcha.create | public function create()
{
if ($this->bgImage && is_file($this->bgImage)) {
// 从背景图片建立背景画布
$this->img = imagecreatefrompng($this->bgImage);
} else {
// 手动建立背景画布,图像资源
$this->img = imagecreatetruecolor($this->width, $this->height);
//给画布填充矩形的背景色rgb(230, 255, 230);
$bgColor = $this->bgColor;
//背景色
$bgColor = imagecolorallocate(
$this->img, hexdec(substr($bgColor, 1, 2)),
hexdec(substr($bgColor, 3, 2)), hexdec(substr($bgColor, 5, 2))
);
imagefilledrectangle($this->img, 0, 0, $this->width, $this->height, $bgColor);
}
//给资源画上边框-可选 rgb(153, 153, 255)
// $borderColor = imagecolorallocate($this->img, 153, 153, 255); // 0-255
// imagerectangle($this->img, 0, 0, $this->width-1, $this->height-1,$borderColor);
$this->drawLine();
$this->drawChar();
$this->drawPixel();
$this->drawChars();
return $this;
} | php | public function create()
{
if ($this->bgImage && is_file($this->bgImage)) {
// 从背景图片建立背景画布
$this->img = imagecreatefrompng($this->bgImage);
} else {
// 手动建立背景画布,图像资源
$this->img = imagecreatetruecolor($this->width, $this->height);
//给画布填充矩形的背景色rgb(230, 255, 230);
$bgColor = $this->bgColor;
//背景色
$bgColor = imagecolorallocate(
$this->img, hexdec(substr($bgColor, 1, 2)),
hexdec(substr($bgColor, 3, 2)), hexdec(substr($bgColor, 5, 2))
);
imagefilledrectangle($this->img, 0, 0, $this->width, $this->height, $bgColor);
}
//给资源画上边框-可选 rgb(153, 153, 255)
// $borderColor = imagecolorallocate($this->img, 153, 153, 255); // 0-255
// imagerectangle($this->img, 0, 0, $this->width-1, $this->height-1,$borderColor);
$this->drawLine();
$this->drawChar();
$this->drawPixel();
$this->drawChars();
return $this;
} | 生成图像资源,Captcha-验证码 | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Files/Captcha.php#L211-L242 |
inhere/php-library-plus | libs/Files/Captcha.php | Captcha.show | public function show()
{
$this->create();
header('Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate');
header('Content-type: image/png;charset=utf8');//生成图片格式png jpeg 。。。
ob_clean();
//生成图片,在浏览器中进行显示-格式png,与上面的header声明对应
$success = imagepng($this->img);
// 已经显示图片后,可销毁,释放内存(可选)
imagedestroy($this->img);
return $success;
} | php | public function show()
{
$this->create();
header('Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate');
header('Content-type: image/png;charset=utf8');//生成图片格式png jpeg 。。。
ob_clean();
//生成图片,在浏览器中进行显示-格式png,与上面的header声明对应
$success = imagepng($this->img);
// 已经显示图片后,可销毁,释放内存(可选)
imagedestroy($this->img);
return $success;
} | 显示
@return bool | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Files/Captcha.php#L248-L262 |
mlocati/concrete5-translation-library | src/Parser/DynamicItem/GroupSet.php | GroupSet.parseManual | public function parseManual(\Gettext\Translations $translations, $concrete5version)
{
if (class_exists('\GroupSet', true)) {
foreach (\GroupSet::getList() as $gs) {
$this->addTranslation($translations, $gs->getGroupSetName(), 'GroupSetName');
}
}
} | php | public function parseManual(\Gettext\Translations $translations, $concrete5version)
{
if (class_exists('\GroupSet', true)) {
foreach (\GroupSet::getList() as $gs) {
$this->addTranslation($translations, $gs->getGroupSetName(), 'GroupSetName');
}
}
} | {@inheritdoc}
@see \C5TL\Parser\DynamicItem\DynamicItem::parseManual() | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser/DynamicItem/GroupSet.php#L35-L42 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceModels.php | HCServiceModels.optimize | public function optimize (stdClass $data)
{
$data->modelDirectory = str_replace ('/http/controllers', '/models', $data->controllerDestination);
$data->modelNamespace = str_replace ('\\http\\controllers', '\\models', $data->controllerNamespace);
foreach ($data->database as $dbItem) {
$dbItem->columns = $this->getTableColumns ($dbItem->tableName);
$dbItem->modelLocation = $data->modelDirectory . '/' . $dbItem->modelName . '.php';
if (isset($dbItem->default) && $dbItem->default)
if (isset($dbItem->multiLanguage)) {
$dbItem->multiLanguage->columns = $this->getTableColumns ($dbItem->multiLanguage->tableName);
$dbItem->multiLanguage->modelName = $dbItem->modelName . 'Translations';
$dbItem->multiLanguage->modelLocation = $data->modelDirectory . '/' . $dbItem->modelName . 'Translations.php';
}
}
//TODO get default model, there can be only one
$data->mainModel = $data->database[0];
return $data;
} | php | public function optimize (stdClass $data)
{
$data->modelDirectory = str_replace ('/http/controllers', '/models', $data->controllerDestination);
$data->modelNamespace = str_replace ('\\http\\controllers', '\\models', $data->controllerNamespace);
foreach ($data->database as $dbItem) {
$dbItem->columns = $this->getTableColumns ($dbItem->tableName);
$dbItem->modelLocation = $data->modelDirectory . '/' . $dbItem->modelName . '.php';
if (isset($dbItem->default) && $dbItem->default)
if (isset($dbItem->multiLanguage)) {
$dbItem->multiLanguage->columns = $this->getTableColumns ($dbItem->multiLanguage->tableName);
$dbItem->multiLanguage->modelName = $dbItem->modelName . 'Translations';
$dbItem->multiLanguage->modelLocation = $data->modelDirectory . '/' . $dbItem->modelName . 'Translations.php';
}
}
//TODO get default model, there can be only one
$data->mainModel = $data->database[0];
return $data;
} | Optimizing configuration for models
@param $data
@internal param $item
@internal param $modelData
@return stdClass | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceModels.php#L25-L46 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceModels.php | HCServiceModels.getTableColumns | private function getTableColumns (string $tableName)
{
$columns = DB::getSchemaBuilder ()->getColumnListing ($tableName);
if (!count ($columns))
$this->abort ("Table not found: " . $tableName);
else
$columns = DB::select (DB::raw ('SHOW COLUMNS FROM ' . $tableName));
return $columns;
} | php | private function getTableColumns (string $tableName)
{
$columns = DB::getSchemaBuilder ()->getColumnListing ($tableName);
if (!count ($columns))
$this->abort ("Table not found: " . $tableName);
else
$columns = DB::select (DB::raw ('SHOW COLUMNS FROM ' . $tableName));
return $columns;
} | Getting table columns
@param $tableName
@return mixed | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceModels.php#L54-L65 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceModels.php | HCServiceModels.generate | public function generate (stdClass $service)
{
$modelData = $service->database;
$this->tableNames = [];
$files = [];
foreach ($modelData as $tableName => $model) {
$this->tableNames[] = $model->tableName;
$template = __DIR__ . '/../templates/service/model/basic.hctpl';
if (isset($model->multiLanguage)) {
$template = __DIR__ . '/../templates/service/model/translations.hctpl';
$this->createFileFromTemplate ([
"destination" => $model->multiLanguage->modelLocation,
"templateDestination" => $template,
"content" => [
"modelNameSpace" => $service->modelNamespace,
"modelName" => $model->multiLanguage->modelName,
"columnsFillable" => $this->getColumnsFillable ($model->multiLanguage->columns, true),
"modelTable" => $model->multiLanguage->tableName,
],
]);
$files[] = $model->multiLanguage->modelLocation;
$this->tableNames[] = $model->multiLanguage->tableName;
$template = __DIR__ . '/../templates/service/model/multiLanguage.hctpl';
}
$this->createFileFromTemplate ([
"destination" => $model->modelLocation,
"templateDestination" => $template,
"content" => [
"modelNameSpace" => $service->modelNamespace,
"modelName" => $model->modelName,
"columnsFillable" => $this->getColumnsFillable ($model->columns),
"modelTable" => $model->tableName,
],
]);
$files[] = $model->modelLocation;
}
return $files;
} | php | public function generate (stdClass $service)
{
$modelData = $service->database;
$this->tableNames = [];
$files = [];
foreach ($modelData as $tableName => $model) {
$this->tableNames[] = $model->tableName;
$template = __DIR__ . '/../templates/service/model/basic.hctpl';
if (isset($model->multiLanguage)) {
$template = __DIR__ . '/../templates/service/model/translations.hctpl';
$this->createFileFromTemplate ([
"destination" => $model->multiLanguage->modelLocation,
"templateDestination" => $template,
"content" => [
"modelNameSpace" => $service->modelNamespace,
"modelName" => $model->multiLanguage->modelName,
"columnsFillable" => $this->getColumnsFillable ($model->multiLanguage->columns, true),
"modelTable" => $model->multiLanguage->tableName,
],
]);
$files[] = $model->multiLanguage->modelLocation;
$this->tableNames[] = $model->multiLanguage->tableName;
$template = __DIR__ . '/../templates/service/model/multiLanguage.hctpl';
}
$this->createFileFromTemplate ([
"destination" => $model->modelLocation,
"templateDestination" => $template,
"content" => [
"modelNameSpace" => $service->modelNamespace,
"modelName" => $model->modelName,
"columnsFillable" => $this->getColumnsFillable ($model->columns),
"modelTable" => $model->tableName,
],
]);
$files[] = $model->modelLocation;
}
return $files;
} | Creating models
@param $service
@internal param $modelData
@return array|string | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceModels.php#L74-L121 |
interactivesolutions/honeycomb-scripts | src/app/commands/service/HCServiceModels.php | HCServiceModels.getColumnsFillable | private function getColumnsFillable (array $columns, bool $translations = false)
{
$names = [];
foreach ($columns as $column) {
if ($translations) {
if (!in_array ($column->Field, $this->getTranslationsAutoFill ()))
array_push ($names, $column->Field);
} else
if (!in_array ($column->Field, $this->getAutoFill ()))
array_push ($names, $column->Field);
}
return '[\'' . implode ('\', \'', $names) . '\']';
} | php | private function getColumnsFillable (array $columns, bool $translations = false)
{
$names = [];
foreach ($columns as $column) {
if ($translations) {
if (!in_array ($column->Field, $this->getTranslationsAutoFill ()))
array_push ($names, $column->Field);
} else
if (!in_array ($column->Field, $this->getAutoFill ()))
array_push ($names, $column->Field);
}
return '[\'' . implode ('\', \'', $names) . '\']';
} | Get models fillable fields
@param array $columns
@param bool $translations
@return string | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceModels.php#L130-L144 |
newup/core | src/Templates/BasePackageTemplate.php | BasePackageTemplate.shareData | public function shareData($key, $value= null)
{
if (is_array($key)) {
foreach ($key as $variableName => $variableValue) {
$this->templateRenderer->setData($variableName, $variableValue);
}
return $this;
}
$this->templateRenderer->setData($key, $value);
return $this;
} | php | public function shareData($key, $value= null)
{
if (is_array($key)) {
foreach ($key as $variableName => $variableValue) {
$this->templateRenderer->setData($variableName, $variableValue);
}
return $this;
}
$this->templateRenderer->setData($key, $value);
return $this;
} | Shares data with package template files.
@param $key The name of the variable to share.
@param null $value The value of the variable to share.
@return $this | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Templates/BasePackageTemplate.php#L225-L236 |
newup/core | src/Templates/BasePackageTemplate.php | BasePackageTemplate.ignorePath | public function ignorePath($path)
{
if (is_array($path)) {
foreach ($path as $pathToIgnore) {
$this->ignorePath($pathToIgnore);
}
return $this;
}
$this->ignoredPaths[] = $path;
return $this;
} | php | public function ignorePath($path)
{
if (is_array($path)) {
foreach ($path as $pathToIgnore) {
$this->ignorePath($pathToIgnore);
}
return $this;
}
$this->ignoredPaths[] = $path;
return $this;
} | Adds a path to the ignore list.
@param $path
@return $this | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Templates/BasePackageTemplate.php#L256-L268 |
mover-io/belt | lib/Stack.php | Stack.filtered | public static function filtered($classes = array(), $files = array(), &$stack = null)
{
$skip_self_trace = 0;
if ($stack === null) {
$stack = debug_backtrace();
}
$classes = array_merge((array) $classes, array(__CLASS__));
// Note: in a php backtrace, the class refers to the target of
// invocation, whereas the file and line indicate where the invocation
// happened.
// E.g.
// [file] => /mover/backend/test/Belt/Support/TracePrinter.php
// [line] => 18
// [function] => debug
// [class] => Belt\Trace
// Here, one might expect class to be 'Belt\Trace'
$files = array_merge((array) $files, array(__FILE__));
$filtered_stack = array();
foreach ($stack as $index => $item) {
$file = Arrays::get($item, 'file', null);
// So given the long comment above, we cheat by looking
// at our caller's class.
$class = Arrays::get($stack, ($index).'.class', null);
if (
(in_array($file, $files))
// ||
// ($index != 0 && in_array($class, $classes))
) {
$skip_self_trace++;
continue;
} else {
$filtered_stack[] = $item;
}
}
return $filtered_stack;
} | php | public static function filtered($classes = array(), $files = array(), &$stack = null)
{
$skip_self_trace = 0;
if ($stack === null) {
$stack = debug_backtrace();
}
$classes = array_merge((array) $classes, array(__CLASS__));
// Note: in a php backtrace, the class refers to the target of
// invocation, whereas the file and line indicate where the invocation
// happened.
// E.g.
// [file] => /mover/backend/test/Belt/Support/TracePrinter.php
// [line] => 18
// [function] => debug
// [class] => Belt\Trace
// Here, one might expect class to be 'Belt\Trace'
$files = array_merge((array) $files, array(__FILE__));
$filtered_stack = array();
foreach ($stack as $index => $item) {
$file = Arrays::get($item, 'file', null);
// So given the long comment above, we cheat by looking
// at our caller's class.
$class = Arrays::get($stack, ($index).'.class', null);
if (
(in_array($file, $files))
// ||
// ($index != 0 && in_array($class, $classes))
) {
$skip_self_trace++;
continue;
} else {
$filtered_stack[] = $item;
}
}
return $filtered_stack;
} | Generates a stack trace while skipping internal and self calls.
@return array | https://github.com/mover-io/belt/blob/c966a70aa0f4eb51be55bbb86c89b1e85b773d68/lib/Stack.php#L11-L48 |
headzoo/web-tools | src/Headzoo/Web/Tools/AbstractHttp.php | AbstractHttp.setValues | public function setValues(array $values)
{
$this->getValidator()->validateRequired($values, $this->required);
$this->values = array_merge($this->values, $values);
return $this;
} | php | public function setValues(array $values)
{
$this->getValidator()->validateRequired($values, $this->required);
$this->values = array_merge($this->values, $values);
return $this;
} | Sets the request/response values
@param array $values The request/response values
@return $this | https://github.com/headzoo/web-tools/blob/305ce78029b86fa1fadaf8341d8fc737c84eab87/src/Headzoo/Web/Tools/AbstractHttp.php#L84-L90 |
imatic/controller-bundle | Controller/Feature/Data/DataFeature.php | DataFeature.query | public function query($name, QueryObjectInterface $queryObject, DisplayCriteriaInterface $displayCriteria = null)
{
$result = $this->doQuery($queryObject, $displayCriteria);
$this->data[$name] = $result;
return $result;
} | php | public function query($name, QueryObjectInterface $queryObject, DisplayCriteriaInterface $displayCriteria = null)
{
$result = $this->doQuery($queryObject, $displayCriteria);
$this->data[$name] = $result;
return $result;
} | @param string $name
@param QueryObjectInterface $queryObject
@param DisplayCriteriaInterface $displayCriteria
@return mixed | https://github.com/imatic/controller-bundle/blob/df71c12166928f9d4f1548d4ee1e09a183a68eb6/Controller/Feature/Data/DataFeature.php#L27-L33 |
imatic/controller-bundle | Controller/Feature/Data/DataFeature.php | DataFeature.count | public function count($name, QueryObjectInterface $queryObject, DisplayCriteriaInterface $displayCriteria = null)
{
$count = $this->doCount($queryObject, $displayCriteria);
$this->data[$name] = $count;
return $count;
} | php | public function count($name, QueryObjectInterface $queryObject, DisplayCriteriaInterface $displayCriteria = null)
{
$count = $this->doCount($queryObject, $displayCriteria);
$this->data[$name] = $count;
return $count;
} | @param string $name
@param QueryObjectInterface $queryObject
@param DisplayCriteriaInterface $displayCriteria
@return int | https://github.com/imatic/controller-bundle/blob/df71c12166928f9d4f1548d4ee1e09a183a68eb6/Controller/Feature/Data/DataFeature.php#L42-L48 |
imatic/controller-bundle | Controller/Feature/Data/DataFeature.php | DataFeature.queryAndCount | public function queryAndCount($resultName, $countName, QueryObjectInterface $queryObject, DisplayCriteriaInterface $displayCriteria = null)
{
list($result, $count) = $this->doQueryAndCount($queryObject, $displayCriteria);
$this->data[$resultName] = $result;
$this->data[$countName] = $count;
return [$result, $count];
} | php | public function queryAndCount($resultName, $countName, QueryObjectInterface $queryObject, DisplayCriteriaInterface $displayCriteria = null)
{
list($result, $count) = $this->doQueryAndCount($queryObject, $displayCriteria);
$this->data[$resultName] = $result;
$this->data[$countName] = $count;
return [$result, $count];
} | @param string $resultName
@param string $countName
@param QueryObjectInterface $queryObject
@param DisplayCriteriaInterface $displayCriteria
@return array result, count | https://github.com/imatic/controller-bundle/blob/df71c12166928f9d4f1548d4ee1e09a183a68eb6/Controller/Feature/Data/DataFeature.php#L58-L66 |
praxisnetau/silverware-navigation | src/Components/LevelNavigation.php | LevelNavigation.getCMSFields | public function getCMSFields()
{
// Obtain Field Objects (from parent):
$fields = parent::getCMSFields();
// Create Field Objects:
$fields->fieldByName('Root.Options.TitleOptions')->push(
CheckboxField::create(
'UseLevelTitle',
$this->fieldLabel('UseLevelTitle')
)
);
// Create Options Fields:
$fields->addFieldToTab(
'Root.Options',
FieldSection::create(
'NavigationOptions',
$this->fieldLabel('NavigationOptions'),
[
DropdownField::create(
'SortBy',
$this->fieldLabel('SortBy'),
$this->getSortByOptions()
),
CheckboxField::create(
'ShowCount',
$this->fieldLabel('ShowCount')
)
]
)
);
// Answer Field Objects:
return $fields;
} | php | public function getCMSFields()
{
// Obtain Field Objects (from parent):
$fields = parent::getCMSFields();
// Create Field Objects:
$fields->fieldByName('Root.Options.TitleOptions')->push(
CheckboxField::create(
'UseLevelTitle',
$this->fieldLabel('UseLevelTitle')
)
);
// Create Options Fields:
$fields->addFieldToTab(
'Root.Options',
FieldSection::create(
'NavigationOptions',
$this->fieldLabel('NavigationOptions'),
[
DropdownField::create(
'SortBy',
$this->fieldLabel('SortBy'),
$this->getSortByOptions()
),
CheckboxField::create(
'ShowCount',
$this->fieldLabel('ShowCount')
)
]
)
);
// Answer Field Objects:
return $fields;
} | Answers a list of field objects for the CMS interface.
@return FieldList | https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/LevelNavigation.php#L139-L178 |
praxisnetau/silverware-navigation | src/Components/LevelNavigation.php | LevelNavigation.getTitleText | public function getTitleText()
{
if ($this->UseLevelTitle && ($level = $this->getLevel())) {
return $level->MenuTitle;
}
return parent::getTitleText();
} | php | public function getTitleText()
{
if ($this->UseLevelTitle && ($level = $this->getLevel())) {
return $level->MenuTitle;
}
return parent::getTitleText();
} | Answers the title of the component for the template.
@return string | https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/LevelNavigation.php#L210-L217 |
praxisnetau/silverware-navigation | src/Components/LevelNavigation.php | LevelNavigation.getLevel | public function getLevel()
{
if ($page = $this->getCurrentPage(Page::class)) {
if (!$page->Children()->exists()) {
$parent = $page->getParent();
while ($parent && !$parent->Children()->exists()) {
$parent = $parent->getParent();
}
return $parent;
}
return $page;
}
} | php | public function getLevel()
{
if ($page = $this->getCurrentPage(Page::class)) {
if (!$page->Children()->exists()) {
$parent = $page->getParent();
while ($parent && !$parent->Children()->exists()) {
$parent = $parent->getParent();
}
return $parent;
}
return $page;
}
} | Answers the page object at the current level.
@return SiteTree | https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/LevelNavigation.php#L264-L283 |
praxisnetau/silverware-navigation | src/Components/LevelNavigation.php | LevelNavigation.isDisabled | public function isDisabled()
{
if ($page = $this->getCurrentPage(Page::class)) {
if ($this->getLevel()) {
return parent::isDisabled();
}
}
return true;
} | php | public function isDisabled()
{
if ($page = $this->getCurrentPage(Page::class)) {
if ($this->getLevel()) {
return parent::isDisabled();
}
}
return true;
} | Answers true if the object is disabled within the template.
@return boolean | https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/LevelNavigation.php#L302-L313 |
Etenil/assegai | src/assegai/modules/ModuleContainer.php | ModuleContainer.addModule | public function addModule($module, array $options = NULL) {
// We need to try the user's modules first, so they can override built-in ones.
$full_module = '\\modules\\' . strtolower($module) . '\\' . ucwords($module);
if(!class_exists($full_module)) {
$full_module = 'assegai\\modules\\' . $module . '\\' . ucwords($module);
if(!class_exists($full_module)) { // Very last chance.
$full_module = 'Module_' . $module;
}
}
if($full_module::instanciate())
{
$module_instance = null;
$module_injector = new injector\Container($this->injector);
$deps = array();
if(method_exists($full_module, 'dependencies')) {
$deps = $full_module::dependencies();
} else { // We'll make up a dependency for you.
$deps = array(
array(
'name' => 'module_' . $module,
'class' => $full_module,
'mother' => 'module',
),
);
}
$module_injector->loadConf($deps);
$module_instance = $module_injector->give('module_' . $module);
$module_instance->setDependencies($this->server, $this);
$module_instance->setOptions($options);
$this->add_to_list($module, $module_instance);
}
} | php | public function addModule($module, array $options = NULL) {
// We need to try the user's modules first, so they can override built-in ones.
$full_module = '\\modules\\' . strtolower($module) . '\\' . ucwords($module);
if(!class_exists($full_module)) {
$full_module = 'assegai\\modules\\' . $module . '\\' . ucwords($module);
if(!class_exists($full_module)) { // Very last chance.
$full_module = 'Module_' . $module;
}
}
if($full_module::instanciate())
{
$module_instance = null;
$module_injector = new injector\Container($this->injector);
$deps = array();
if(method_exists($full_module, 'dependencies')) {
$deps = $full_module::dependencies();
} else { // We'll make up a dependency for you.
$deps = array(
array(
'name' => 'module_' . $module,
'class' => $full_module,
'mother' => 'module',
),
);
}
$module_injector->loadConf($deps);
$module_instance = $module_injector->give('module_' . $module);
$module_instance->setDependencies($this->server, $this);
$module_instance->setOptions($options);
$this->add_to_list($module, $module_instance);
}
} | Adds a module to the list.
@param string $module is the module's name to instanciate.
@param array $options is an array of options to be passed to
the module's constructor. Default is none. | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/ModuleContainer.php#L77-L112 |
Etenil/assegai | src/assegai/modules/ModuleContainer.php | ModuleContainer.batchRun | public function batchRun($is_hook, $method_name, array $params = NULL)
{
// Prevents annoying notices.
if($params == NULL) {
$params = array();
}
// We collect the results into an array.
$results = array();
if(!$this->modules) $this->modules = array();
foreach($this->modules as $name => $module) {
if(method_exists($module, $method_name)) {
$result = call_user_func_array(array($module, $method_name), $params);
if($is_hook) { // Hooks are pre-emptive if they return something.
if($result) {
return $result;
}
} else { // Collecting
$results[$name] = $result;
}
}
}
return $is_hook? false : $results;
} | php | public function batchRun($is_hook, $method_name, array $params = NULL)
{
// Prevents annoying notices.
if($params == NULL) {
$params = array();
}
// We collect the results into an array.
$results = array();
if(!$this->modules) $this->modules = array();
foreach($this->modules as $name => $module) {
if(method_exists($module, $method_name)) {
$result = call_user_func_array(array($module, $method_name), $params);
if($is_hook) { // Hooks are pre-emptive if they return something.
if($result) {
return $result;
}
} else { // Collecting
$results[$name] = $result;
}
}
}
return $is_hook? false : $results;
} | Batch runs a method on all modules.
@param bool $is_hook specifies that this is a hook call.
@param string $method_name is the method to be used on all modules.
@param array $params is an array of parameters to pass to all methods. | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/ModuleContainer.php#L149-L173 |
RadialCorp/magento-core | src/lib/Radial/RiskService/Sdk/Payload.php | Radial_RiskService_Sdk_Payload.deserialize | public function deserialize($serializedPayload)
{
$xpath = $this->_helper->getPayloadAsXPath($serializedPayload, $this->_getXmlNamespace());
$this->_deserializeExtractionPaths($xpath)
->_deserializeOptionalExtractionPaths($xpath)
->_deserializeBooleanExtractionPaths($xpath)
->_deserializeLineItems($serializedPayload)
->_deserializeSubpayloadExtractionPaths($xpath)
->_deserializeDateTimeExtractionPaths($xpath)
->_deserializeExtra($serializedPayload);
return $this;
} | php | public function deserialize($serializedPayload)
{
$xpath = $this->_helper->getPayloadAsXPath($serializedPayload, $this->_getXmlNamespace());
$this->_deserializeExtractionPaths($xpath)
->_deserializeOptionalExtractionPaths($xpath)
->_deserializeBooleanExtractionPaths($xpath)
->_deserializeLineItems($serializedPayload)
->_deserializeSubpayloadExtractionPaths($xpath)
->_deserializeDateTimeExtractionPaths($xpath)
->_deserializeExtra($serializedPayload);
return $this;
} | Fill out this payload object with data from the supplied string.
@throws Radial_RiskService_Sdk_Exception_Invalid_Payload_Exception
@param string
@return $this | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L93-L104 |
RadialCorp/magento-core | src/lib/Radial/RiskService/Sdk/Payload.php | Radial_RiskService_Sdk_Payload._deserializeOptionalExtractionPaths | protected function _deserializeOptionalExtractionPaths(DOMXPath $xpath)
{
foreach ($this->_optionalExtractionPaths as $setter => $path) {
$foundNode = $xpath->query($path)->item(0);
if ($foundNode) {
$this->$setter($foundNode->nodeValue);
}
}
return $this;
} | php | protected function _deserializeOptionalExtractionPaths(DOMXPath $xpath)
{
foreach ($this->_optionalExtractionPaths as $setter => $path) {
$foundNode = $xpath->query($path)->item(0);
if ($foundNode) {
$this->$setter($foundNode->nodeValue);
}
}
return $this;
} | When optional nodes are not included in the serialized data,
they should not be set in the payload. Fortunately, these
are all string values so no additional type conversion is necessary.
@param DOMXPath
@return self | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L126-L135 |
RadialCorp/magento-core | src/lib/Radial/RiskService/Sdk/Payload.php | Radial_RiskService_Sdk_Payload._deserializeBooleanExtractionPaths | protected function _deserializeBooleanExtractionPaths(DOMXPath $xpath)
{
foreach ($this->_booleanExtractionPaths as $setter => $path) {
$value = $xpath->evaluate($path);
$this->$setter($this->_helper->convertStringToBoolean($value));
}
return $this;
} | php | protected function _deserializeBooleanExtractionPaths(DOMXPath $xpath)
{
foreach ($this->_booleanExtractionPaths as $setter => $path) {
$value = $xpath->evaluate($path);
$this->$setter($this->_helper->convertStringToBoolean($value));
}
return $this;
} | boolean values have to be handled specially
@param DOMXPath
@return self | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L143-L150 |
RadialCorp/magento-core | src/lib/Radial/RiskService/Sdk/Payload.php | Radial_RiskService_Sdk_Payload._deserializeDateTimeExtractionPaths | protected function _deserializeDateTimeExtractionPaths(DOMXPath $xpath)
{
foreach ($this->_dateTimeExtractionPaths as $setter => $path) {
$value = $xpath->evaluate($path);
if ($value) {
$this->$setter(new DateTime($value));
}
}
return $this;
} | php | protected function _deserializeDateTimeExtractionPaths(DOMXPath $xpath)
{
foreach ($this->_dateTimeExtractionPaths as $setter => $path) {
$value = $xpath->evaluate($path);
if ($value) {
$this->$setter(new DateTime($value));
}
}
return $this;
} | Ensure any date time string is instantiate
@param DOMXPath
@return self | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L174-L183 |
RadialCorp/magento-core | src/lib/Radial/RiskService/Sdk/Payload.php | Radial_RiskService_Sdk_Payload.serialize | public function serialize()
{
$xmlString = sprintf(
'<%s %s>%s</%1$s>',
$this->_getRootNodeName(),
$this->_serializeRootAttributes(),
$this->_serializeContents()
);
$canonicalXml = $this->_helper->getPayloadAsDoc($xmlString)->C14N();
return $this->_canSerialize() ? $canonicalXml : '';
} | php | public function serialize()
{
$xmlString = sprintf(
'<%s %s>%s</%1$s>',
$this->_getRootNodeName(),
$this->_serializeRootAttributes(),
$this->_serializeContents()
);
$canonicalXml = $this->_helper->getPayloadAsDoc($xmlString)->C14N();
return $this->_canSerialize() ? $canonicalXml : '';
} | Return the string form of the payload data for transmission.
Validation is implied.
@throws Radial_RiskService_Sdk_Exception_Invalid_Payload_Exception
@return string | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L192-L202 |
RadialCorp/magento-core | src/lib/Radial/RiskService/Sdk/Payload.php | Radial_RiskService_Sdk_Payload._serializeRootAttributes | protected function _serializeRootAttributes()
{
$rootAttributes = $this->_getRootAttributes();
$qualifyAttributes = function ($name) use ($rootAttributes) {
return sprintf('%s="%s"', $name, $rootAttributes[$name]);
};
$qualifiedAttributes = array_map($qualifyAttributes, array_keys($rootAttributes));
return implode(' ', $qualifiedAttributes);
} | php | protected function _serializeRootAttributes()
{
$rootAttributes = $this->_getRootAttributes();
$qualifyAttributes = function ($name) use ($rootAttributes) {
return sprintf('%s="%s"', $name, $rootAttributes[$name]);
};
$qualifiedAttributes = array_map($qualifyAttributes, array_keys($rootAttributes));
return implode(' ', $qualifiedAttributes);
} | Serialize Root Attributes
@return string | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L277-L285 |
RadialCorp/magento-core | src/lib/Radial/RiskService/Sdk/Payload.php | Radial_RiskService_Sdk_Payload._serializeNode | protected function _serializeNode($nodeName, $value)
{
return sprintf('<%s>%s</%1$s>', $nodeName, $this->xmlEncode($this->_helper->escapeHtml($value)));
} | php | protected function _serializeNode($nodeName, $value)
{
return sprintf('<%s>%s</%1$s>', $nodeName, $this->xmlEncode($this->_helper->escapeHtml($value)));
} | Serialize the value as an xml element with the given node name.
@param string
@param mixed
@return string | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L318-L321 |
RadialCorp/magento-core | src/lib/Radial/RiskService/Sdk/Payload.php | Radial_RiskService_Sdk_Payload._serializeBooleanNode | protected function _serializeBooleanNode($nodeName, $value)
{
if(!$this->_helper->convertStringToBoolean($value))
{
return sprintf('<%s>0</%1$s>', $nodeName);
} else {
return sprintf('<%s>%s</%1$s>', $nodeName, $this->_helper->convertStringToBoolean($value));
}
} | php | protected function _serializeBooleanNode($nodeName, $value)
{
if(!$this->_helper->convertStringToBoolean($value))
{
return sprintf('<%s>0</%1$s>', $nodeName);
} else {
return sprintf('<%s>%s</%1$s>', $nodeName, $this->_helper->convertStringToBoolean($value));
}
} | Serialize the boolean value as an xml element with the given node name.
@param string
@param mixed
@return string | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L330-L338 |
RadialCorp/magento-core | src/lib/Radial/RiskService/Sdk/Payload.php | Radial_RiskService_Sdk_Payload._serializeOptionalValue | protected function _serializeOptionalValue($nodeName, $value)
{
return (!is_null($value) && $value !== '') ? $this->_serializeNode($nodeName, $value) : '';
} | php | protected function _serializeOptionalValue($nodeName, $value)
{
return (!is_null($value) && $value !== '') ? $this->_serializeNode($nodeName, $value) : '';
} | Serialize the value as an xml element with the given node name. When
given an empty value, returns an empty string instead of an empty
element.
@param string
@param mixed
@return string | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L359-L362 |
RadialCorp/magento-core | src/lib/Radial/RiskService/Sdk/Payload.php | Radial_RiskService_Sdk_Payload._serializeOptionalAmount | protected function _serializeOptionalAmount($nodeName, $amount, $currencyCode=null)
{
if( $currencyCode)
{
return (!is_null($amount) && !is_nan($amount)) ? "<$nodeName currencyCode=\"$currencyCode\">{$this->_helper->formatAmount($amount)}</$nodeName>" : '';
} else {
return (!is_null($amount) && !is_nan($amount)) ? "<$nodeName>{$this->_helper->formatAmount($amount)}</$nodeName>" : '';
}
} | php | protected function _serializeOptionalAmount($nodeName, $amount, $currencyCode=null)
{
if( $currencyCode)
{
return (!is_null($amount) && !is_nan($amount)) ? "<$nodeName currencyCode=\"$currencyCode\">{$this->_helper->formatAmount($amount)}</$nodeName>" : '';
} else {
return (!is_null($amount) && !is_nan($amount)) ? "<$nodeName>{$this->_helper->formatAmount($amount)}</$nodeName>" : '';
}
} | Serialize the currency amount as an XML node with the provided name.
When the amount is not set, returns an empty string.
@param string
@param float
@param string
@return string | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L373-L381 |
brainexe/core | src/Console/ClearSessionsCommand.php | ClearSessionsCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$redis = $this->getRedis();
$sessionIds = $redis->keys('sessions:*');
foreach ($sessionIds as $sessionId) {
$redis->del($sessionId);
}
$output->writeln(sprintf('Deleted <info>%d</info> sessions', count($sessionIds)));
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$redis = $this->getRedis();
$sessionIds = $redis->keys('sessions:*');
foreach ($sessionIds as $sessionId) {
$redis->del($sessionId);
}
$output->writeln(sprintf('Deleted <info>%d</info> sessions', count($sessionIds)));
} | {@inheritdoc} | https://github.com/brainexe/core/blob/9ef69c6f045306abd20e271572386970db9b3e54/src/Console/ClearSessionsCommand.php#L31-L42 |
iron-bound-designs/wp-notifications | src/Queue/Storage/Options.php | Options.store_notifications | public function store_notifications( $queue_id, array $notifications, Strategy $strategy = null ) {
$all = get_option( $this->bucket, array() );
$found = empty( $all ) ? false : true;
if ( empty( $notifications ) ) {
return $this->clear_notifications( $queue_id );
}
$all[ $queue_id ] = array(
'notifications' => $notifications
);
if ( isset( $strategy ) ) {
$all[ $queue_id ]['strategy'] = $strategy;
}
if ( $found ) {
return update_option( $this->bucket, $all );
} else {
return add_option( $this->bucket, $all, '', 'no' );
}
} | php | public function store_notifications( $queue_id, array $notifications, Strategy $strategy = null ) {
$all = get_option( $this->bucket, array() );
$found = empty( $all ) ? false : true;
if ( empty( $notifications ) ) {
return $this->clear_notifications( $queue_id );
}
$all[ $queue_id ] = array(
'notifications' => $notifications
);
if ( isset( $strategy ) ) {
$all[ $queue_id ]['strategy'] = $strategy;
}
if ( $found ) {
return update_option( $this->bucket, $all );
} else {
return add_option( $this->bucket, $all, '', 'no' );
}
} | Store a set of notifications.
If notifications is empty, it will clear the set.
@since 1.0
@param string $queue_id
@param Notification[] $notifications
@param Strategy $strategy If null, previously set strategy will be used.
@return bool | https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Queue/Storage/Options.php#L49-L72 |
iron-bound-designs/wp-notifications | src/Queue/Storage/Options.php | Options.get_notifications | public function get_notifications( $queue_id ) {
$all = get_option( $this->bucket, array() );
if ( isset( $all[ $queue_id ]['notifications'] ) ) {
return $all[ $queue_id ]['notifications'];
} else {
return null;
}
} | php | public function get_notifications( $queue_id ) {
$all = get_option( $this->bucket, array() );
if ( isset( $all[ $queue_id ]['notifications'] ) ) {
return $all[ $queue_id ]['notifications'];
} else {
return null;
}
} | Get a set of notifications.
@since 1.0
@param string $queue_id
@return Notification[]|null | https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Queue/Storage/Options.php#L83-L92 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.