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
|
---|---|---|---|---|---|---|---|
Wedeto/Util | src/Cache/Item.php | Item.unserialize | public function unserialize($data)
{
$data = unserialize($data);
$this->key = $data['key'];
$this->value = $data['value'];
$this->expires = $data['expires'];
$this->hit = $data['hit'];
} | php | public function unserialize($data)
{
$data = unserialize($data);
$this->key = $data['key'];
$this->value = $data['value'];
$this->expires = $data['expires'];
$this->hit = $data['hit'];
} | Unserialize the item. Required for storing in the containing cache
@param string $data The data to unserialize | https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Cache/Item.php#L204-L211 |
chee-commerce/CheeModule | src/Chee/Module/ModuleServiceProvider.php | ModuleServiceProvider.boot | public function boot()
{
$this->package('chee/module');
$this->bootCommands();
$this->app['chee-module']->start();
$this->app['chee-module']->register();
} | php | public function boot()
{
$this->package('chee/module');
$this->bootCommands();
$this->app['chee-module']->start();
$this->app['chee-module']->register();
} | Bootstrap the application events.
@return void | https://github.com/chee-commerce/CheeModule/blob/ccfff426f4ecf8f13687f5acd49246ba4997deee/src/Chee/Module/ModuleServiceProvider.php#L20-L29 |
chee-commerce/CheeModule | src/Chee/Module/ModuleServiceProvider.php | ModuleServiceProvider.register | public function register()
{
$this->app['chee-module'] = $this->app->share(function($app)
{
return new CheeModule($app, $app['config'], $app['files']);
});
} | php | public function register()
{
$this->app['chee-module'] = $this->app->share(function($app)
{
return new CheeModule($app, $app['config'], $app['files']);
});
} | Register the service provider.
@return void | https://github.com/chee-commerce/CheeModule/blob/ccfff426f4ecf8f13687f5acd49246ba4997deee/src/Chee/Module/ModuleServiceProvider.php#L36-L42 |
Linkvalue-Interne/MajoraOrientDBBundle | src/Majora/Bundle/OrientDbGraphBundle/DependencyInjection/Compiler/GraphClientCompilerPass.php | GraphClientCompilerPass.process | public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('majora.orient_db.graph_engine')) {
return;
}
$graphTags = $container->findTaggedServiceIds('majora.graph_client');
$graphEngineDefinition = $container->getDefinition('majora.orient_db.graph_engine');
foreach ($graphTags as $id => $tags) {
foreach ($tags as $tag) {
if (!isset($tag['vertex'])) {
throw new \InvalidArgumentException(sprintf(
'Missing "vertex" mandatory key into "%s" service "majora.graph_client" tag definition.',
$id
));
}
$serviceDefinition = $container->getDefinition($id);
$serviceDefinition->addMethodCall(
'setGraphDatabase',
array(
$tag['vertex'],
new Reference('majora.orient_db.graph_engine'),
$connection = isset($tag['connection']) ? $tag['connection'] : 'default'
)
);
$graphEngineDefinition->addMethodCall(
'registerVertex',
array($connection, $tag['vertex'])
);
}
}
} | php | public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('majora.orient_db.graph_engine')) {
return;
}
$graphTags = $container->findTaggedServiceIds('majora.graph_client');
$graphEngineDefinition = $container->getDefinition('majora.orient_db.graph_engine');
foreach ($graphTags as $id => $tags) {
foreach ($tags as $tag) {
if (!isset($tag['vertex'])) {
throw new \InvalidArgumentException(sprintf(
'Missing "vertex" mandatory key into "%s" service "majora.graph_client" tag definition.',
$id
));
}
$serviceDefinition = $container->getDefinition($id);
$serviceDefinition->addMethodCall(
'setGraphDatabase',
array(
$tag['vertex'],
new Reference('majora.orient_db.graph_engine'),
$connection = isset($tag['connection']) ? $tag['connection'] : 'default'
)
);
$graphEngineDefinition->addMethodCall(
'registerVertex',
array($connection, $tag['vertex'])
);
}
}
} | {@inheritdoc} | https://github.com/Linkvalue-Interne/MajoraOrientDBBundle/blob/9fc9a409604472b558319c274442f75bbd055435/src/Majora/Bundle/OrientDbGraphBundle/DependencyInjection/Compiler/GraphClientCompilerPass.php#L18-L52 |
ekyna/Table | Extension/Core/Source/ArrayAdapter.php | ArrayAdapter.buildFilterClosure | public function buildFilterClosure($propertyPath, $operator, $value)
{
$rowValue = function ($data) use ($propertyPath) {
return $this->propertyAccessor->getValue($data, $propertyPath);
};
switch ($operator) {
case Util\FilterOperator::EQUAL:
return function ($row) use ($value, $rowValue) {
return $value == $rowValue($row);
};
case Util\FilterOperator::NOT_EQUAL:
return function ($row) use ($value, $rowValue) {
return $value != $rowValue($row);
};
case Util\FilterOperator::LOWER_THAN:
return function ($row) use ($value, $rowValue) {
return $value < $rowValue($row);
};
case Util\FilterOperator::LOWER_THAN_OR_EQUAL:
return function ($row) use ($value, $rowValue) {
return $value <= $rowValue($row);
};
case Util\FilterOperator::GREATER_THAN:
return function ($row) use ($value, $rowValue) {
return $value > $rowValue($row);
};
case Util\FilterOperator::GREATER_THAN_OR_EQUAL:
return function ($row) use ($value, $rowValue) {
return $value >= $rowValue($row);
};
case Util\FilterOperator::IN:
case Util\FilterOperator::MEMBER:
return function ($row) use ($value, $rowValue) {
return in_array($value, (array)$rowValue($row));
};
case Util\FilterOperator::NOT_IN:
case Util\FilterOperator::NOT_MEMBER:
return function ($row) use ($value, $rowValue) {
return !in_array($value, (array)$rowValue($row));
};
case Util\FilterOperator::LIKE:
$value = strtolower($value);
return function ($row) use ($value, $rowValue) {
return false !== strpos(strtolower((string)$rowValue($row)), $value);
};
case Util\FilterOperator::NOT_LIKE:
$value = strtolower($value);
return function ($row) use ($value, $rowValue) {
return false === strpos(strtolower((string)$rowValue($row)), $value);
};
case Util\FilterOperator::START_WITH:
$value = strtolower($value);
$length = strlen($value);
return function ($row) use ($value, $length, $rowValue) {
return (substr(strtolower((string)$rowValue($row)), 0, $length) === $value);
};
case Util\FilterOperator::NOT_START_WITH:
$value = strtolower($value);
$length = strlen($value);
return function ($row) use ($value, $length, $rowValue) {
return !(substr(strtolower((string)$rowValue($row)), 0, $length) === $value);
};
case Util\FilterOperator::END_WITH:
$value = strtolower($value);
$length = strlen($value);
return function ($row) use ($value, $length, $rowValue) {
return (substr(strtolower((string)$rowValue($row)), -$length) === $value);
};
case Util\FilterOperator::NOT_END_WITH:
$value = strtolower($value);
$length = strlen($value);
return function ($row) use ($value, $length, $rowValue) {
return !(substr(strtolower((string)$rowValue($row)), -$length) === $value);
};
case Util\FilterOperator::IS_NULL:
return function ($row) use ($rowValue) {
return is_null($rowValue($row));
};
case Util\FilterOperator::IS_NOT_NULL:
return function ($row) use ($rowValue) {
return !is_null($rowValue($row));
};
}
throw new Exception\InvalidArgumentException("Unexpected filter operator.");
} | php | public function buildFilterClosure($propertyPath, $operator, $value)
{
$rowValue = function ($data) use ($propertyPath) {
return $this->propertyAccessor->getValue($data, $propertyPath);
};
switch ($operator) {
case Util\FilterOperator::EQUAL:
return function ($row) use ($value, $rowValue) {
return $value == $rowValue($row);
};
case Util\FilterOperator::NOT_EQUAL:
return function ($row) use ($value, $rowValue) {
return $value != $rowValue($row);
};
case Util\FilterOperator::LOWER_THAN:
return function ($row) use ($value, $rowValue) {
return $value < $rowValue($row);
};
case Util\FilterOperator::LOWER_THAN_OR_EQUAL:
return function ($row) use ($value, $rowValue) {
return $value <= $rowValue($row);
};
case Util\FilterOperator::GREATER_THAN:
return function ($row) use ($value, $rowValue) {
return $value > $rowValue($row);
};
case Util\FilterOperator::GREATER_THAN_OR_EQUAL:
return function ($row) use ($value, $rowValue) {
return $value >= $rowValue($row);
};
case Util\FilterOperator::IN:
case Util\FilterOperator::MEMBER:
return function ($row) use ($value, $rowValue) {
return in_array($value, (array)$rowValue($row));
};
case Util\FilterOperator::NOT_IN:
case Util\FilterOperator::NOT_MEMBER:
return function ($row) use ($value, $rowValue) {
return !in_array($value, (array)$rowValue($row));
};
case Util\FilterOperator::LIKE:
$value = strtolower($value);
return function ($row) use ($value, $rowValue) {
return false !== strpos(strtolower((string)$rowValue($row)), $value);
};
case Util\FilterOperator::NOT_LIKE:
$value = strtolower($value);
return function ($row) use ($value, $rowValue) {
return false === strpos(strtolower((string)$rowValue($row)), $value);
};
case Util\FilterOperator::START_WITH:
$value = strtolower($value);
$length = strlen($value);
return function ($row) use ($value, $length, $rowValue) {
return (substr(strtolower((string)$rowValue($row)), 0, $length) === $value);
};
case Util\FilterOperator::NOT_START_WITH:
$value = strtolower($value);
$length = strlen($value);
return function ($row) use ($value, $length, $rowValue) {
return !(substr(strtolower((string)$rowValue($row)), 0, $length) === $value);
};
case Util\FilterOperator::END_WITH:
$value = strtolower($value);
$length = strlen($value);
return function ($row) use ($value, $length, $rowValue) {
return (substr(strtolower((string)$rowValue($row)), -$length) === $value);
};
case Util\FilterOperator::NOT_END_WITH:
$value = strtolower($value);
$length = strlen($value);
return function ($row) use ($value, $length, $rowValue) {
return !(substr(strtolower((string)$rowValue($row)), -$length) === $value);
};
case Util\FilterOperator::IS_NULL:
return function ($row) use ($rowValue) {
return is_null($rowValue($row));
};
case Util\FilterOperator::IS_NOT_NULL:
return function ($row) use ($rowValue) {
return !is_null($rowValue($row));
};
}
throw new Exception\InvalidArgumentException("Unexpected filter operator.");
} | Builds a filter closure from the active filter.
@param string $propertyPath
@param string $operator
@param string $value
@return \Closure | https://github.com/ekyna/Table/blob/6f06e8fd8a3248d52f3a91f10508471344db311a/Extension/Core/Source/ArrayAdapter.php#L65-L151 |
ekyna/Table | Extension/Core/Source/ArrayAdapter.php | ArrayAdapter.buildSortClosure | public function buildSortClosure($propertyPath, $direction)
{
$value = function ($data) use ($propertyPath) {
return $this->propertyAccessor->getValue($data, $propertyPath);
};
if ($direction === Util\ColumnSort::ASC) {
return function ($rowA, $rowB) use ($value) {
$a = $value($rowA);
$b = $value($rowB);
if ($a == $b) {
return 0;
}
return $a < $b ? -1 : 1;
};
} elseif ($direction === Util\ColumnSort::DESC) {
return function ($rowA, $rowB) use ($value) {
$a = $value($rowA);
$b = $value($rowB);
if ($a == $b) {
return 0;
}
return $a > $b ? -1 : 1;
};
}
throw new Exception\InvalidArgumentException("Unexpected column sort direction.");
} | php | public function buildSortClosure($propertyPath, $direction)
{
$value = function ($data) use ($propertyPath) {
return $this->propertyAccessor->getValue($data, $propertyPath);
};
if ($direction === Util\ColumnSort::ASC) {
return function ($rowA, $rowB) use ($value) {
$a = $value($rowA);
$b = $value($rowB);
if ($a == $b) {
return 0;
}
return $a < $b ? -1 : 1;
};
} elseif ($direction === Util\ColumnSort::DESC) {
return function ($rowA, $rowB) use ($value) {
$a = $value($rowA);
$b = $value($rowB);
if ($a == $b) {
return 0;
}
return $a > $b ? -1 : 1;
};
}
throw new Exception\InvalidArgumentException("Unexpected column sort direction.");
} | Builds the sort closure.
@param string $propertyPath
@param string $direction
@return \Closure | https://github.com/ekyna/Table/blob/6f06e8fd8a3248d52f3a91f10508471344db311a/Extension/Core/Source/ArrayAdapter.php#L161-L192 |
ekyna/Table | Extension/Core/Source/ArrayAdapter.php | ArrayAdapter.applyClosures | private function applyClosures($data)
{
if (!empty($this->filterClosures)) {
$data = array_filter($data, function ($datum) {
foreach ($this->filterClosures as $closure) {
if (!$closure($datum)) {
return false;
}
}
return true;
});
}
if (!empty($this->sortClosures)) {
uasort($data, function($rowA, $rowB) {
foreach ($this->sortClosures as $closure) {
if (0 != $result = $closure($rowA, $rowB)) {
return $result;
}
}
return 0;
});
}
if ($this->identifiersClosures) {
$data = array_filter($data, $this->identifiersClosures, ARRAY_FILTER_USE_KEY);
}
return $data;
} | php | private function applyClosures($data)
{
if (!empty($this->filterClosures)) {
$data = array_filter($data, function ($datum) {
foreach ($this->filterClosures as $closure) {
if (!$closure($datum)) {
return false;
}
}
return true;
});
}
if (!empty($this->sortClosures)) {
uasort($data, function($rowA, $rowB) {
foreach ($this->sortClosures as $closure) {
if (0 != $result = $closure($rowA, $rowB)) {
return $result;
}
}
return 0;
});
}
if ($this->identifiersClosures) {
$data = array_filter($data, $this->identifiersClosures, ARRAY_FILTER_USE_KEY);
}
return $data;
} | Applies the filters and sort closures.
@param array $data
@return array | https://github.com/ekyna/Table/blob/6f06e8fd8a3248d52f3a91f10508471344db311a/Extension/Core/Source/ArrayAdapter.php#L280-L311 |
rednose-public/RednoseComboHandlerBundle | Controller/MinifyController.php | MinifyController.comboAction | public function comboAction($root = null)
{
$roots = $this->getRoots();
if ($root && !array_key_exists($root, $roots)) {
return new Response('', 400);
}
\Minify::$uploaderHoursBehind = 0;
if ($this->get('kernel')->isDebug()) {
\Minify_Logger::setLogger(new MinifyLogger());
} else {
\Minify::setCache('', true);
}
// Hook into the GET request and format it according to Minify standards.
// We can't use the PHP $_GET variable as PHP parses GET keys to PHP variables,
// meaning characters like dots are replaced by underscores.
$_GET['f'] = implode(',', $this->tokenizeQuery($_SERVER['QUERY_STRING']));
$response = \Minify::serve(
new \Minify_Controller_MinApp(),
$this->getOptions($root && isset($roots[$root]) ? $roots[$root] : null)
);
return new Response($response['content'], $response['statusCode'], $response['headers']);
} | php | public function comboAction($root = null)
{
$roots = $this->getRoots();
if ($root && !array_key_exists($root, $roots)) {
return new Response('', 400);
}
\Minify::$uploaderHoursBehind = 0;
if ($this->get('kernel')->isDebug()) {
\Minify_Logger::setLogger(new MinifyLogger());
} else {
\Minify::setCache('', true);
}
// Hook into the GET request and format it according to Minify standards.
// We can't use the PHP $_GET variable as PHP parses GET keys to PHP variables,
// meaning characters like dots are replaced by underscores.
$_GET['f'] = implode(',', $this->tokenizeQuery($_SERVER['QUERY_STRING']));
$response = \Minify::serve(
new \Minify_Controller_MinApp(),
$this->getOptions($root && isset($roots[$root]) ? $roots[$root] : null)
);
return new Response($response['content'], $response['statusCode'], $response['headers']);
} | Minify a request of JavaScript/CSS files
@param string $root
@return Response
@Route("/combo/{root}", name="rednose_combo_handler_combo", defaults={"root" = null})
@Method({"GET"}) | https://github.com/rednose-public/RednoseComboHandlerBundle/blob/44b55dbd6653cebcf280822156cff8b850bdae00/Controller/MinifyController.php#L38-L66 |
rednose-public/RednoseComboHandlerBundle | Controller/MinifyController.php | MinifyController.rewriteUris | public static function rewriteUris($css, $options = array())
{
// Prepend the base URL and symlink schema so the proper root path gets prepended.
$symlinks = array();
if (is_link($_SERVER['DOCUMENT_ROOT'])) {
$symlinks = array(
'/'.$options['baseUrl'] => readlink($_SERVER['DOCUMENT_ROOT'])
);
}
return \Minify_CSS_UriRewriter::rewrite($css, $options['currentDir'], $_SERVER['DOCUMENT_ROOT'], $symlinks);
} | php | public static function rewriteUris($css, $options = array())
{
// Prepend the base URL and symlink schema so the proper root path gets prepended.
$symlinks = array();
if (is_link($_SERVER['DOCUMENT_ROOT'])) {
$symlinks = array(
'/'.$options['baseUrl'] => readlink($_SERVER['DOCUMENT_ROOT'])
);
}
return \Minify_CSS_UriRewriter::rewrite($css, $options['currentDir'], $_SERVER['DOCUMENT_ROOT'], $symlinks);
} | Rewrite CSS URIs.
@param string $css
@param array $options
@return string | https://github.com/rednose-public/RednoseComboHandlerBundle/blob/44b55dbd6653cebcf280822156cff8b850bdae00/Controller/MinifyController.php#L76-L88 |
rednose-public/RednoseComboHandlerBundle | Controller/MinifyController.php | MinifyController.getOptions | protected function getOptions($root = null)
{
$_SERVER['DOCUMENT_ROOT'] .= $this->getBaseUrl();
if ($root) {
$_SERVER['DOCUMENT_ROOT'] .= $root;
}
return array(
// Output an array of data instead of returning headers/content.
'quiet' => true,
// In debug mode, allow access to all files, in case assets are symlinked to Bower repos for example.
'minApp' => array('allowDirs' => $this->get('kernel')->isDebug() ? array('/') : array(
// Allow all files inside the Symfony root folder to be accessed, in case asset files are symlinked to it.
__DIR__ . '/../../../../../../',
// Allow files in the configured combo-root to be accessed.
$_SERVER['DOCUMENT_ROOT']
)),
// CSS URIs are rewritten. Don't minify JavaScript, we're just providing a combo service.
'minifiers' => array(
\Minify::TYPE_CSS => array('Rednose\ComboHandlerBundle\Controller\MinifyController', 'rewriteUris'),
\Minify::TYPE_JS => '',
),
'minifierOptions' => array(
\Minify::TYPE_CSS => array('baseUrl' => $this->getBaseUrl().$root)
)
);
} | php | protected function getOptions($root = null)
{
$_SERVER['DOCUMENT_ROOT'] .= $this->getBaseUrl();
if ($root) {
$_SERVER['DOCUMENT_ROOT'] .= $root;
}
return array(
// Output an array of data instead of returning headers/content.
'quiet' => true,
// In debug mode, allow access to all files, in case assets are symlinked to Bower repos for example.
'minApp' => array('allowDirs' => $this->get('kernel')->isDebug() ? array('/') : array(
// Allow all files inside the Symfony root folder to be accessed, in case asset files are symlinked to it.
__DIR__ . '/../../../../../../',
// Allow files in the configured combo-root to be accessed.
$_SERVER['DOCUMENT_ROOT']
)),
// CSS URIs are rewritten. Don't minify JavaScript, we're just providing a combo service.
'minifiers' => array(
\Minify::TYPE_CSS => array('Rednose\ComboHandlerBundle\Controller\MinifyController', 'rewriteUris'),
\Minify::TYPE_JS => '',
),
'minifierOptions' => array(
\Minify::TYPE_CSS => array('baseUrl' => $this->getBaseUrl().$root)
)
);
} | @param string $root
@return array | https://github.com/rednose-public/RednoseComboHandlerBundle/blob/44b55dbd6653cebcf280822156cff8b850bdae00/Controller/MinifyController.php#L95-L126 |
rednose-public/RednoseComboHandlerBundle | Controller/MinifyController.php | MinifyController.getBaseUrl | protected function getBaseUrl()
{
$baseUrl = $this->container->get('router')->getContext()->getBaseUrl();
if ($baseUrl === '/') {
return '';
}
return rtrim(str_replace('app_dev.php', '', $this->container->get('router')->getContext()->getBaseUrl()), '/').'/';
} | php | protected function getBaseUrl()
{
$baseUrl = $this->container->get('router')->getContext()->getBaseUrl();
if ($baseUrl === '/') {
return '';
}
return rtrim(str_replace('app_dev.php', '', $this->container->get('router')->getContext()->getBaseUrl()), '/').'/';
} | Returns the normalized base URL.
@return string | https://github.com/rednose-public/RednoseComboHandlerBundle/blob/44b55dbd6653cebcf280822156cff8b850bdae00/Controller/MinifyController.php#L133-L142 |
polusphp/polus-middleware | src/UserAgent.php | UserAgent.determineClientUserAgent | protected function determineClientUserAgent($request)
{
$userAgent = null;
$serverParams = $request->getServerParams();
$userAgent = $serverParams['HTTP_USER_AGENT'];
$checkProxyHeaders = $this->checkProxyHeaders;
if ($checkProxyHeaders && !empty($this->trustedProxies)) {
if (!in_array($userAgent, $this->trustedProxies)) {
$checkProxyHeaders = false;
}
}
if ($checkProxyHeaders) {
foreach ($this->headersToInspect as $header) {
if ($request->hasHeader($header)) {
$userAgent = trim(current(explode(',', $request->getHeaderLine($header))));
break;
}
}
}
return $userAgent;
} | php | protected function determineClientUserAgent($request)
{
$userAgent = null;
$serverParams = $request->getServerParams();
$userAgent = $serverParams['HTTP_USER_AGENT'];
$checkProxyHeaders = $this->checkProxyHeaders;
if ($checkProxyHeaders && !empty($this->trustedProxies)) {
if (!in_array($userAgent, $this->trustedProxies)) {
$checkProxyHeaders = false;
}
}
if ($checkProxyHeaders) {
foreach ($this->headersToInspect as $header) {
if ($request->hasHeader($header)) {
$userAgent = trim(current(explode(',', $request->getHeaderLine($header))));
break;
}
}
}
return $userAgent;
} | Find out the client's UserAgent from the headers available to us
@param ServerRequestInterface $request PSR-7 Request
@return string | https://github.com/polusphp/polus-middleware/blob/c265c51fbdf6b2c5ed85686415b47a1fbf720c57/src/UserAgent.php#L85-L107 |
wb-crowdfusion/crowdfusion | system/core/classes/mvc/renderer/Renderer.php | Renderer.renderView | public function renderView(View $view, $contentType, $cacheEnabled = true, $pushCache = false)
{
$this->view = $view;
$this->contentType = $contentType;
$this->cacheEnabled = $cacheEnabled;
$this->pushCache = $pushCache;
$this->noTemplatesCalled = true;
//VIEW DATA (MODEL) IS USED AS GLOBAL VARIABLES DURING TEMPLATE RENDER
$globals = $view->getData() == null ? array() : $view->getData();
$templateEngine = $this->getTemplateEngine($view->getName());
$this->Logger->debug("Starting render [{$view->getName()}] - ".($cacheEnabled==true?'WITH':'WITHOUT')." CACHING");
if($this->benchmarkRendering) $this->Benchmark->start('render-'. $view->getName());
$content = $templateEngine->firstPass($view->getName(), $contentType, $globals, $this);
foreach ($this->invokedTemplateEngines as $te) {
$this->Logger->debug("Starting finalPass for [".get_class($te)."]");
$content = $te->finalPass($content, $contentType, $globals, $this);
}
$this->Logger->debug("Completed rendering view [{$view->getName()}]");
if($this->benchmarkRendering) $this->Benchmark->end('render-'. $view->getName());
$this->noTemplatesCalled = true;
return array($content, $globals);
} | php | public function renderView(View $view, $contentType, $cacheEnabled = true, $pushCache = false)
{
$this->view = $view;
$this->contentType = $contentType;
$this->cacheEnabled = $cacheEnabled;
$this->pushCache = $pushCache;
$this->noTemplatesCalled = true;
//VIEW DATA (MODEL) IS USED AS GLOBAL VARIABLES DURING TEMPLATE RENDER
$globals = $view->getData() == null ? array() : $view->getData();
$templateEngine = $this->getTemplateEngine($view->getName());
$this->Logger->debug("Starting render [{$view->getName()}] - ".($cacheEnabled==true?'WITH':'WITHOUT')." CACHING");
if($this->benchmarkRendering) $this->Benchmark->start('render-'. $view->getName());
$content = $templateEngine->firstPass($view->getName(), $contentType, $globals, $this);
foreach ($this->invokedTemplateEngines as $te) {
$this->Logger->debug("Starting finalPass for [".get_class($te)."]");
$content = $te->finalPass($content, $contentType, $globals, $this);
}
$this->Logger->debug("Completed rendering view [{$view->getName()}]");
if($this->benchmarkRendering) $this->Benchmark->end('render-'. $view->getName());
$this->noTemplatesCalled = true;
return array($content, $globals);
} | @param string $contentType The name of the handler that the template engine should use to render the output.
Types: XHTML, RSS, XML, JSON, JSONp, JavaScript, SerializedPHP, PlainText, HTTPGET
A template engine may or may not support all of these handlers.
@throws Exception If template engine doesn't support requested content type (thrown from TemplateEngine)
@throws Exception If no template engine is capable of rendering the view template supplied
@throws Exception If the template engine doesn't support the handler type. | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/renderer/Renderer.php#L106-L137 |
horntell/php-sdk | lib/guzzle/GuzzleHttp/Event/ErrorEvent.php | ErrorEvent.intercept | public function intercept(ResponseInterface $response)
{
$this->stopPropagation();
$this->getTransaction()->setResponse($response);
$this->exception->setThrowImmediately(false);
RequestEvents::emitComplete($this->getTransaction());
} | php | public function intercept(ResponseInterface $response)
{
$this->stopPropagation();
$this->getTransaction()->setResponse($response);
$this->exception->setThrowImmediately(false);
RequestEvents::emitComplete($this->getTransaction());
} | Intercept the exception and inject a response
@param ResponseInterface $response Response to set | https://github.com/horntell/php-sdk/blob/e5205e9396a21b754d5651a8aa5898da5922a1b7/lib/guzzle/GuzzleHttp/Event/ErrorEvent.php#L39-L45 |
MindyPHP/FormBundle | Form/Extension/QuerySetExtension.php | QuerySetExtension.buildForm | public function buildForm(FormBuilderInterface $builder, array $options)
{
if (isset($options['multiple']) && $options['multiple']) {
$builder->addModelTransformer($this->querySetTransformer);
}
} | php | public function buildForm(FormBuilderInterface $builder, array $options)
{
if (isset($options['multiple']) && $options['multiple']) {
$builder->addModelTransformer($this->querySetTransformer);
}
} | {@inheritdoc} | https://github.com/MindyPHP/FormBundle/blob/566cc965cc4e44c6ee491059c050346c7fa9c76d/Form/Extension/QuerySetExtension.php#L48-L53 |
MinyFramework/Miny-Core | src/Controller/ControllerDispatcher.php | ControllerDispatcher.runController | public function runController(Request $request)
{
/** @var $response Response */
$response = $this->container->get('\\Miny\\HTTP\\Response', [], true);
$oldResponse = $this->container->setInstance($response);
$response = $this->doRun($request, $response);
if ($oldResponse) {
return $this->container->setInstance($oldResponse);
}
return $response;
} | php | public function runController(Request $request)
{
/** @var $response Response */
$response = $this->container->get('\\Miny\\HTTP\\Response', [], true);
$oldResponse = $this->container->setInstance($response);
$response = $this->doRun($request, $response);
if ($oldResponse) {
return $this->container->setInstance($oldResponse);
}
return $response;
} | @param Request $request
@throws InvalidControllerException
@return Response | https://github.com/MinyFramework/Miny-Core/blob/a1bfe801a44a49cf01f16411cb4663473e9c827c/src/Controller/ControllerDispatcher.php#L46-L59 |
ARCANESOFT/SEO | src/Http/Requests/Admin/Footers/FooterFormRequest.php | FooterFormRequest.getPageRule | protected function getPageRule()
{
$existsRule = Rule::exists($this->getTablePrefix().'pages', 'id')->using(function ($query) {
if ($this->has('locale'))
$query->where('locale', $this->get('locale', config('app.locale')));
});
return ['required', 'integer', $existsRule];
} | php | protected function getPageRule()
{
$existsRule = Rule::exists($this->getTablePrefix().'pages', 'id')->using(function ($query) {
if ($this->has('locale'))
$query->where('locale', $this->get('locale', config('app.locale')));
});
return ['required', 'integer', $existsRule];
} | Get the page validation rule.
@return array | https://github.com/ARCANESOFT/SEO/blob/ce6d6135d55e8b2fd43cf7923839b4791b7c7ad2/src/Http/Requests/Admin/Footers/FooterFormRequest.php#L39-L47 |
helsingborg-stad/better-post-UI | source/php/Components/InternalLinks.php | InternalLinks.updateLinkInfo | public function updateLinkInfo($results, $query)
{
$results = array_map(function ($result) {
// Get post type
$post_type = get_post_type($result['ID']);
$obj = get_post_type_object($post_type);
// Add post type to result info
$result['info'] = '<strong>' . $obj->labels->singular_name . '</strong>';
// Get post parents
$ancestors = get_post_ancestors($result['ID']);
$ancestors = array_reverse($ancestors);
// Add post parents path to info string
if (is_array($ancestors) && !empty($ancestors)) {
$parent_string = implode(' / ', array_map(function ($ancestor) {
return get_the_title($ancestor);
}, $ancestors)) . ' / '. $result['title'];
$result['info'] = $result['info'] . ': ' . $parent_string;
}
return $result;
}, $results);
return $results;
} | php | public function updateLinkInfo($results, $query)
{
$results = array_map(function ($result) {
// Get post type
$post_type = get_post_type($result['ID']);
$obj = get_post_type_object($post_type);
// Add post type to result info
$result['info'] = '<strong>' . $obj->labels->singular_name . '</strong>';
// Get post parents
$ancestors = get_post_ancestors($result['ID']);
$ancestors = array_reverse($ancestors);
// Add post parents path to info string
if (is_array($ancestors) && !empty($ancestors)) {
$parent_string = implode(' / ', array_map(function ($ancestor) {
return get_the_title($ancestor);
}, $ancestors)) . ' / '. $result['title'];
$result['info'] = $result['info'] . ': ' . $parent_string;
}
return $result;
}, $results);
return $results;
} | Get the post type and its parents
@param array $results An associative array of query results
@param array $query An array of WP_Query arguments
@return array | https://github.com/helsingborg-stad/better-post-UI/blob/0454e8d6f42787244d02f0e976825ed8dca579f0/source/php/Components/InternalLinks.php#L34-L59 |
helsingborg-stad/better-post-UI | source/php/Components/InternalLinks.php | InternalLinks.limitLinkSearch | public function limitLinkSearch($search, $wp_query)
{
global $wpdb;
if (empty($search)) {
return $search;
}
$query_vars = $wp_query->query_vars;
$search = '';
$and = '';
foreach((array)$query_vars['search_terms'] as $term) {
$search .= "{$searchand}(($wpdb->posts.post_title LIKE '%{$wpdb->esc_like($term)}%'))";
$and = ' AND ';
}
$search = (!empty($search)) ? " AND ({$search}) " : $search;
return $search;
} | php | public function limitLinkSearch($search, $wp_query)
{
global $wpdb;
if (empty($search)) {
return $search;
}
$query_vars = $wp_query->query_vars;
$search = '';
$and = '';
foreach((array)$query_vars['search_terms'] as $term) {
$search .= "{$searchand}(($wpdb->posts.post_title LIKE '%{$wpdb->esc_like($term)}%'))";
$and = ' AND ';
}
$search = (!empty($search)) ? " AND ({$search}) " : $search;
return $search;
} | Limits internal link search to "post title" field
@param string $search Search SQL for WHERE clause
@param obj $wp_query The current WP_Query object
@return string Modified search string | https://github.com/helsingborg-stad/better-post-UI/blob/0454e8d6f42787244d02f0e976825ed8dca579f0/source/php/Components/InternalLinks.php#L67-L87 |
SlabPHP/debug | src/Benchmark.php | Benchmark.end | public function end()
{
$this->timeEnd = microtime(true);
$this->cpuEnd = 0;
$this->memoryEnd = memory_get_usage(false);
$this->memoryEndReal = memory_get_usage(true);
} | php | public function end()
{
$this->timeEnd = microtime(true);
$this->cpuEnd = 0;
$this->memoryEnd = memory_get_usage(false);
$this->memoryEndReal = memory_get_usage(true);
} | end benchmark | https://github.com/SlabPHP/debug/blob/4fa79fd62f5528a10f3bdca2bd36c9f8e0b816aa/src/Benchmark.php#L75-L81 |
Linkvalue-Interne/MajoraFrameworkExtraBundle | src/Majora/Framework/Model/TranslatableTrait.php | TranslatableTrait.getTranslation | protected function getTranslation(array $translationData, $default = '')
{
// undefined locale
if (empty($translationData)) {
return $default;
}
// current locale matched
if ($this->locale && isset($translationData[$this->locale])) {
return $translationData[$this->locale];
}
// default locale matched
return $this->defaultLocale && isset($translationData[$this->defaultLocale]) ?
$translationData[$this->defaultLocale] :
$default
;
} | php | protected function getTranslation(array $translationData, $default = '')
{
// undefined locale
if (empty($translationData)) {
return $default;
}
// current locale matched
if ($this->locale && isset($translationData[$this->locale])) {
return $translationData[$this->locale];
}
// default locale matched
return $this->defaultLocale && isset($translationData[$this->defaultLocale]) ?
$translationData[$this->defaultLocale] :
$default
;
} | return translation matching current locale from given translation data
@param array $translationData
@param string $default
@return string | https://github.com/Linkvalue-Interne/MajoraFrameworkExtraBundle/blob/6f368380cfc39d27fafb0844e9a53b4d86d7c034/src/Majora/Framework/Model/TranslatableTrait.php#L48-L65 |
FuzeWorks/Core | src/Database/DB_cache.php | FW_DB_Cache.check_path | public function check_path($path = '')
{
$path = ($path === '' ? Core::$tempDir . DS . 'Database' : $path);
// Add a trailing slash to the path if needed
$path = realpath($path)
? rtrim(realpath($path), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR
: rtrim($path, '/').'/';
if ( ! is_dir($path))
{
if (!mkdir($path, 0777, false))
{
Logger::logDebug('DB cache path error: '.$path);
// If the path is wrong we'll turn off caching
return $this->db->cache_off();
}
}
if ( ! Core::isReallyWritable($path))
{
Logger::logDebug('DB cache dir not writable: '.$path);
// If the path is not really writable we'll turn off caching
return $this->db->cache_off();
}
$this->db->cachedir = $path;
return TRUE;
} | php | public function check_path($path = '')
{
$path = ($path === '' ? Core::$tempDir . DS . 'Database' : $path);
// Add a trailing slash to the path if needed
$path = realpath($path)
? rtrim(realpath($path), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR
: rtrim($path, '/').'/';
if ( ! is_dir($path))
{
if (!mkdir($path, 0777, false))
{
Logger::logDebug('DB cache path error: '.$path);
// If the path is wrong we'll turn off caching
return $this->db->cache_off();
}
}
if ( ! Core::isReallyWritable($path))
{
Logger::logDebug('DB cache dir not writable: '.$path);
// If the path is not really writable we'll turn off caching
return $this->db->cache_off();
}
$this->db->cachedir = $path;
return TRUE;
} | Set Cache Directory Path
@param string $path Path to the cache directory
@return bool | https://github.com/FuzeWorks/Core/blob/051c64fdaa3a648174cbd54557d05ad553dd826b/src/Database/DB_cache.php#L92-L122 |
agentmedia/phine-builtin | src/BuiltIn/Modules/Backend/BlockForm.php | BlockForm.InitForm | protected function InitForm()
{
$this->block = $this->LoadElement();
$this->AddTagNameField();
$this->AddCssClassField();
$this->AddCssIDField();
$this->AddSubmit();
} | php | protected function InitForm()
{
$this->block = $this->LoadElement();
$this->AddTagNameField();
$this->AddCssClassField();
$this->AddCssIDField();
$this->AddSubmit();
} | Initializes the form | https://github.com/agentmedia/phine-builtin/blob/4dd05bc406a71e997bd4eaa16b12e23dbe62a456/src/BuiltIn/Modules/Backend/BlockForm.php#L42-L49 |
NukaCode/html | src/NukaCode/Html/BBCode.php | BBCode.parse | public function parse($data)
{
$this->table();
$this->images();
$this->text();
$this->html();
// Replace everything that has been found
foreach ($this->matches as $key => $val) {
$data = preg_replace_callback($key, $val, $data);
}
// Replace line-breaks
return preg_replace_callback("/\n\r?/", function () {
return '<br />';
}, $data
);
} | php | public function parse($data)
{
$this->table();
$this->images();
$this->text();
$this->html();
// Replace everything that has been found
foreach ($this->matches as $key => $val) {
$data = preg_replace_callback($key, $val, $data);
}
// Replace line-breaks
return preg_replace_callback("/\n\r?/", function () {
return '<br />';
}, $data
);
} | Parse a text and replace the BBCodes
@access public
@param string $data
@return string | https://github.com/NukaCode/html/blob/7288161fb6711b1f9889e31bacb32d0d14b46e85/src/NukaCode/Html/BBCode.php#L31-L48 |
agentmedia/phine-core | src/Core/Logic/Tree/LayoutContentTreeProvider.php | LayoutContentTreeProvider.AttachContent | public function AttachContent($item, Content $content)
{
$item->SetContent($content);
$item->Save();
$content->SetLayoutContent($item);
$content->Save();
} | php | public function AttachContent($item, Content $content)
{
$item->SetContent($content);
$item->Save();
$content->SetLayoutContent($item);
$content->Save();
} | Attaches item and content
@param LayoutContent $item
@param Content $content | https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Tree/LayoutContentTreeProvider.php#L118-L124 |
hiqdev/yii2-error-notifier | src/targets/EmailTarget.php | EmailTarget.export | public function export()
{
// moved initialization of subject here because of the following issue
// https://github.com/yiisoft/yii2/issues/1446
if (empty($this->message['subject'])) {
$this->message['subject'] = 'Application Log';
}
$module = Module::getInstance();
$this->message['from'] = $module->flagEmail($this->message['from']);
$this->message['subject'] = $module->flagText($this->message['subject']);
$messages = array_map([$this, 'formatMessage'], $this->messages);
$body = $this->getDebugLogLink();
$body .= implode("\n", $messages);
$this->composeMessage($body)->send($this->mailer);
} | php | public function export()
{
// moved initialization of subject here because of the following issue
// https://github.com/yiisoft/yii2/issues/1446
if (empty($this->message['subject'])) {
$this->message['subject'] = 'Application Log';
}
$module = Module::getInstance();
$this->message['from'] = $module->flagEmail($this->message['from']);
$this->message['subject'] = $module->flagText($this->message['subject']);
$messages = array_map([$this, 'formatMessage'], $this->messages);
$body = $this->getDebugLogLink();
$body .= implode("\n", $messages);
$this->composeMessage($body)->send($this->mailer);
} | Sends log messages to specified email addresses. | https://github.com/hiqdev/yii2-error-notifier/blob/21badc2285fc5353626e1abcaf14af496777ab16/src/targets/EmailTarget.php#L22-L38 |
aegis-security/JSON | src/Encoder.php | Encoder.encode | public static function encode($value, $cycleCheck = false, $options = array())
{
$encoder = new static($cycleCheck, $options);
return $encoder->_encodeValue($value);
} | php | public static function encode($value, $cycleCheck = false, $options = array())
{
$encoder = new static($cycleCheck, $options);
return $encoder->_encodeValue($value);
} | Use the JSON encoding scheme for the value specified
@param mixed $value The value to be encoded
@param bool $cycleCheck Whether or not to check for possible object recursion when encoding
@param array $options Additional options used during encoding
@return string The encoded value | https://github.com/aegis-security/JSON/blob/7bc8e442e9e570ecbc480053d9aaa42a52910fbc/src/Encoder.php#L59-L64 |
aegis-security/JSON | src/Encoder.php | Encoder._encodeObject | protected function _encodeObject(&$value)
{
if ($this->cycleCheck) {
if ($this->_wasVisited($value)) {
if (isset($this->options['silenceCyclicalExceptions'])
&& $this->options['silenceCyclicalExceptions']===true) {
return '"* RECURSION (' . str_replace('\\', '\\\\', get_class($value)) . ') *"';
} else {
throw new RecursionException(
'Cycles not supported in JSON encoding, cycle introduced by '
. 'class "' . get_class($value) . '"'
);
}
}
$this->visited[] = $value;
}
if ($value instanceof \JsonSerializable || $value instanceof JsonSerializable) {
$valueToSerialize = $value->jsonSerialize();
return $this->_encodeValue($valueToSerialize);
} else {
$props = '';
if ($value instanceof \IteratorAggregate) {
$propCollection = $value->getIterator();
} elseif ($value instanceof \Iterator) {
$propCollection = $value;
} else {
$propCollection = get_object_vars($value);
}
foreach ($propCollection as $name => $propValue) {
if (isset($propValue)) {
$props .= ','
. $this->_encodeValue($name)
. ':'
. $this->_encodeValue($propValue);
}
}
}
$className = get_class($value);
return '{"__className":'
. $this->_encodeString($className)
. $props . '}';
} | php | protected function _encodeObject(&$value)
{
if ($this->cycleCheck) {
if ($this->_wasVisited($value)) {
if (isset($this->options['silenceCyclicalExceptions'])
&& $this->options['silenceCyclicalExceptions']===true) {
return '"* RECURSION (' . str_replace('\\', '\\\\', get_class($value)) . ') *"';
} else {
throw new RecursionException(
'Cycles not supported in JSON encoding, cycle introduced by '
. 'class "' . get_class($value) . '"'
);
}
}
$this->visited[] = $value;
}
if ($value instanceof \JsonSerializable || $value instanceof JsonSerializable) {
$valueToSerialize = $value->jsonSerialize();
return $this->_encodeValue($valueToSerialize);
} else {
$props = '';
if ($value instanceof \IteratorAggregate) {
$propCollection = $value->getIterator();
} elseif ($value instanceof \Iterator) {
$propCollection = $value;
} else {
$propCollection = get_object_vars($value);
}
foreach ($propCollection as $name => $propValue) {
if (isset($propValue)) {
$props .= ','
. $this->_encodeValue($name)
. ':'
. $this->_encodeValue($propValue);
}
}
}
$className = get_class($value);
return '{"__className":'
. $this->_encodeString($className)
. $props . '}';
} | Encode an object to JSON by encoding each of the public properties
A special property is added to the JSON object called '__className'
that contains the name of the class of $value. This is used to decode
the object on the client into a specific class.
@param $value object
@return string
@throws RecursionException If recursive checks are enabled and the
object has been serialized previously | https://github.com/aegis-security/JSON/blob/7bc8e442e9e570ecbc480053d9aaa42a52910fbc/src/Encoder.php#L99-L147 |
aegis-security/JSON | src/Encoder.php | Encoder._encodeString | protected function _encodeString(&$string)
{
// Escape these characters with a backslash or unicode escape:
// " \ / \n \r \t \b \f
$search = array('\\', "\n", "\t", "\r", "\b", "\f", '"', '\'', '&', '<', '>', '/');
$replace = array('\\\\', '\\n', '\\t', '\\r', '\\b', '\\f', '\\u0022', '\\u0027', '\\u0026', '\\u003C', '\\u003E', '\\/');
$string = str_replace($search, $replace, $string);
// Escape certain ASCII characters:
// 0x08 => \b
// 0x0c => \f
$string = str_replace(array(chr(0x08), chr(0x0C)), array('\b', '\f'), $string);
$string = self::encodeUnicodeString($string);
return '"' . $string . '"';
} | php | protected function _encodeString(&$string)
{
// Escape these characters with a backslash or unicode escape:
// " \ / \n \r \t \b \f
$search = array('\\', "\n", "\t", "\r", "\b", "\f", '"', '\'', '&', '<', '>', '/');
$replace = array('\\\\', '\\n', '\\t', '\\r', '\\b', '\\f', '\\u0022', '\\u0027', '\\u0026', '\\u003C', '\\u003E', '\\/');
$string = str_replace($search, $replace, $string);
// Escape certain ASCII characters:
// 0x08 => \b
// 0x0c => \f
$string = str_replace(array(chr(0x08), chr(0x0C)), array('\b', '\f'), $string);
$string = self::encodeUnicodeString($string);
return '"' . $string . '"';
} | JSON encode a string value by escaping characters as necessary
@param string $string
@return string | https://github.com/aegis-security/JSON/blob/7bc8e442e9e570ecbc480053d9aaa42a52910fbc/src/Encoder.php#L238-L253 |
aegis-security/JSON | src/Encoder.php | Encoder._encodeConstants | private static function _encodeConstants(\ReflectionClass $cls)
{
$result = "constants : {";
$constants = $cls->getConstants();
$tmpArray = array();
if (!empty($constants)) {
foreach ($constants as $key => $value) {
$tmpArray[] = "$key: " . self::encode($value);
}
$result .= implode(', ', $tmpArray);
}
return $result . "}";
} | php | private static function _encodeConstants(\ReflectionClass $cls)
{
$result = "constants : {";
$constants = $cls->getConstants();
$tmpArray = array();
if (!empty($constants)) {
foreach ($constants as $key => $value) {
$tmpArray[] = "$key: " . self::encode($value);
}
$result .= implode(', ', $tmpArray);
}
return $result . "}";
} | Encode the constants associated with the \ReflectionClass
parameter. The encoding format is based on the class2 format
@param \ReflectionClass $cls
@return string Encoded constant block in class2 format | https://github.com/aegis-security/JSON/blob/7bc8e442e9e570ecbc480053d9aaa42a52910fbc/src/Encoder.php#L262-L277 |
aegis-security/JSON | src/Encoder.php | Encoder.encodeUnicodeString | public static function encodeUnicodeString($value)
{
$strlenVar = strlen($value);
$ascii = "";
/**
* Iterate over every character in the string,
* escaping with a slash or encoding to UTF-8 where necessary
*/
for ($i = 0; $i < $strlenVar; $i++) {
$ordVarC = ord($value[$i]);
switch (true) {
case (($ordVarC >= 0x20) && ($ordVarC <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ascii .= $value[$i];
break;
case (($ordVarC & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110XXXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ordVarC, ord($value[$i + 1]));
$i += 1;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ordVarC & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack(
'C*',
$ordVarC,
ord($value[$i + 1]),
ord($value[$i + 2])
);
$i += 2;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ordVarC & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack(
'C*',
$ordVarC,
ord($value[$i + 1]),
ord($value[$i + 2]),
ord($value[$i + 3])
);
$i += 3;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ordVarC & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack(
'C*',
$ordVarC,
ord($value[$i + 1]),
ord($value[$i + 2]),
ord($value[$i + 3]),
ord($value[$i + 4])
);
$i += 4;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ordVarC & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack(
'C*',
$ordVarC,
ord($value[$i + 1]),
ord($value[$i + 2]),
ord($value[$i + 3]),
ord($value[$i + 4]),
ord($value[$i + 5])
);
$i += 5;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
}
}
return $ascii;
} | php | public static function encodeUnicodeString($value)
{
$strlenVar = strlen($value);
$ascii = "";
/**
* Iterate over every character in the string,
* escaping with a slash or encoding to UTF-8 where necessary
*/
for ($i = 0; $i < $strlenVar; $i++) {
$ordVarC = ord($value[$i]);
switch (true) {
case (($ordVarC >= 0x20) && ($ordVarC <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ascii .= $value[$i];
break;
case (($ordVarC & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110XXXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ordVarC, ord($value[$i + 1]));
$i += 1;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ordVarC & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack(
'C*',
$ordVarC,
ord($value[$i + 1]),
ord($value[$i + 2])
);
$i += 2;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ordVarC & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack(
'C*',
$ordVarC,
ord($value[$i + 1]),
ord($value[$i + 2]),
ord($value[$i + 3])
);
$i += 3;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ordVarC & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack(
'C*',
$ordVarC,
ord($value[$i + 1]),
ord($value[$i + 2]),
ord($value[$i + 3]),
ord($value[$i + 4])
);
$i += 4;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ordVarC & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack(
'C*',
$ordVarC,
ord($value[$i + 1]),
ord($value[$i + 2]),
ord($value[$i + 3]),
ord($value[$i + 4]),
ord($value[$i + 5])
);
$i += 5;
$utf16 = self::_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
}
}
return $ascii;
} | Encode Unicode Characters to \u0000 ASCII syntax.
This algorithm was originally developed for the
Solar Framework by Paul M. Jones
@link http://solarphp.com/
@link https://github.com/solarphp/core/blob/master/Solar/Json.php
@param string $value
@return string | https://github.com/aegis-security/JSON/blob/7bc8e442e9e570ecbc480053d9aaa42a52910fbc/src/Encoder.php#L426-L518 |
rollerworks-graveyard/metadata | src/NullClassMetadata.php | NullClassMetadata.merge | public function merge(ClassMetadata $object)
{
$createdAt = $this->createdAt;
if (($otherCreatedAt = $object->getCreatedAt()) > $createdAt) {
$createdAt = $otherCreatedAt;
}
return new self($this->className, $createdAt);
} | php | public function merge(ClassMetadata $object)
{
$createdAt = $this->createdAt;
if (($otherCreatedAt = $object->getCreatedAt()) > $createdAt) {
$createdAt = $otherCreatedAt;
}
return new self($this->className, $createdAt);
} | Returns a new NullClassMetadata with the highest createdAt.
No actual merging is performed as NullClassMetadata can't hold
any data and it's not possible to determine which ClassMetadata
implementation must be used.
Only the createdAt of the object is used if it's higher then
the current createdAt value.
@param ClassMetadata $object Another MergeableClassMetadata object.
@return NullClassMetadata | https://github.com/rollerworks-graveyard/metadata/blob/5b07f564aad87709ca0d0b3e140e4dc4edf9d375/src/NullClassMetadata.php#L131-L140 |
ezra-obiwale/dSCore | src/Stdlib/Email.php | Email.addAttachment | public function addAttachment($filePath) {
if (!$file = fopen($filePath, 'r')) {
throw new Exception('Cannot open file "' . $filePath . '"');
}
$this->attachments[$filePath] = chunk_split(base64_encode(fread($file, filesize($filePath))));
return $this;
} | php | public function addAttachment($filePath) {
if (!$file = fopen($filePath, 'r')) {
throw new Exception('Cannot open file "' . $filePath . '"');
}
$this->attachments[$filePath] = chunk_split(base64_encode(fread($file, filesize($filePath))));
return $this;
} | Attach a file to the email
@param string $filePath Path to the file
@return \Email
@throws Exception | https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/Email.php#L46-L53 |
ezra-obiwale/dSCore | src/Stdlib/Email.php | Email.setHTML | public function setHTML($content, array $options = array()) {
$this->html = $content;
$this->htmlCharset = (isset($options['charset'])) ? $options['charset'] : 'utf-8';
if (@$options['autoSetText']) {
$this->setText(strip_tags($this->html), $this->htmlCharset);
}
return $this;
} | php | public function setHTML($content, array $options = array()) {
$this->html = $content;
$this->htmlCharset = (isset($options['charset'])) ? $options['charset'] : 'utf-8';
if (@$options['autoSetText']) {
$this->setText(strip_tags($this->html), $this->htmlCharset);
}
return $this;
} | Set html content
@param string $content
@param array $options Keys may include [(string) charset [= "utf-8"], (boolean) autoSetText]
@return \Email | https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/Email.php#L74-L81 |
ezra-obiwale/dSCore | src/Stdlib/Email.php | Email.setText | public function setText($content, $charset = 'utf-8') {
$this->text = $content;
$this->textCharset = $charset;
return $this;
} | php | public function setText($content, $charset = 'utf-8') {
$this->text = $content;
$this->textCharset = $charset;
return $this;
} | Set text content
@param string $content
@return \Email | https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/Email.php#L88-L92 |
ezra-obiwale/dSCore | src/Stdlib/Email.php | Email.send | public function send($subject, array $options = array()) {
$to = $this->to;
$from = $this->from;
$cc = $this->cc;
$bcc = $this->bcc;
$replyTo = $this->replyTo;
foreach ($options as $key => $value) {
$$key = $value;
}
$this->createHeaders($from, $cc, $bcc, $replyTo);
if (!empty($this->html)) {
$message = $this->html;
$endWithSeparator = false;
if ($this->text || $this->attachments) {
$this->headers("Content-type: multipart/" . (($this->attachments) ? 'mixed' : 'alternative') . "; charset=" . $this->htmlCharset);
$endWithSeparator = true;
}
else {
$this->headers("Content-type: text/html; charset=" . $this->htmlCharset);
$this->headers('Content-Transfer-Encoding:8bit');
}
$this->headers("MIME-Version: 1.0");
if (!empty($this->text)) {
$this->separateHeaders();
$this->headers("Content-type: text/plain; charset=" . $this->htmlCharset);
$this->headers('Content-Transfer-Encoding:8bit');
$this->headers($this->text);
$this->separateHeaders();
$this->headers("Content-type: text/html; charset=" . $this->htmlCharset);
$this->headers('Content-Transfer-Encoding:8bit');
$this->headers($message);
}
}
elseif (!empty($this->text)) {
$message = $this->text;
}
else {
throw new Exception('Email content not set! Use either/both of setText() and setHTML()');
}
if (!empty($this->attachments)) {
$this->setAttachmentHeader();
}
if ($endWithSeparator)
$this->separateHeaders();
return mail($to, $subject, $message, $this->headers);
} | php | public function send($subject, array $options = array()) {
$to = $this->to;
$from = $this->from;
$cc = $this->cc;
$bcc = $this->bcc;
$replyTo = $this->replyTo;
foreach ($options as $key => $value) {
$$key = $value;
}
$this->createHeaders($from, $cc, $bcc, $replyTo);
if (!empty($this->html)) {
$message = $this->html;
$endWithSeparator = false;
if ($this->text || $this->attachments) {
$this->headers("Content-type: multipart/" . (($this->attachments) ? 'mixed' : 'alternative') . "; charset=" . $this->htmlCharset);
$endWithSeparator = true;
}
else {
$this->headers("Content-type: text/html; charset=" . $this->htmlCharset);
$this->headers('Content-Transfer-Encoding:8bit');
}
$this->headers("MIME-Version: 1.0");
if (!empty($this->text)) {
$this->separateHeaders();
$this->headers("Content-type: text/plain; charset=" . $this->htmlCharset);
$this->headers('Content-Transfer-Encoding:8bit');
$this->headers($this->text);
$this->separateHeaders();
$this->headers("Content-type: text/html; charset=" . $this->htmlCharset);
$this->headers('Content-Transfer-Encoding:8bit');
$this->headers($message);
}
}
elseif (!empty($this->text)) {
$message = $this->text;
}
else {
throw new Exception('Email content not set! Use either/both of setText() and setHTML()');
}
if (!empty($this->attachments)) {
$this->setAttachmentHeader();
}
if ($endWithSeparator)
$this->separateHeaders();
return mail($to, $subject, $message, $this->headers);
} | Send the email
@param string $subject
@param array $options Keys may include [to, from, cc, bcc, replyTo].<br />
If any is not set, the default is assumed.
@return boolean
@throws Exception | https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/Email.php#L102-L156 |
ezra-obiwale/dSCore | src/Stdlib/Email.php | Email.addBcc | public function addBcc($bcc) {
$this->bcc = (!empty($this->bcc)) ? $this->bcc . ',' . $bcc : $bcc;
return $this;
} | php | public function addBcc($bcc) {
$this->bcc = (!empty($this->bcc)) ? $this->bcc . ',' . $bcc : $bcc;
return $this;
} | Adds a best carbon copy
@param string $bcc Email address to send to
@return \Email | https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/Email.php#L200-L203 |
ezra-obiwale/dSCore | src/Stdlib/Email.php | Email.createHeaders | private function createHeaders($from, $cc = array(), $bcc = array(), $replyTo = null) {
if ($from)
$this->headers('From: ' . $from);
if (!is_array($cc)) {
$cc = ($cc) ? array($cc) : array();
}
if (!is_array($bcc)) {
$bcc = ($bcc) ? array($bcc) : array();
}
foreach ($cc as $c) {
$this->headers("Cc: " . $c);
}
foreach ($bcc as $b) {
$this->headers("Bcc: " . $b);
}
if ($replyTo)
$this->headers("Reply-To: " . $replyTo);
return $this;
} | php | private function createHeaders($from, $cc = array(), $bcc = array(), $replyTo = null) {
if ($from)
$this->headers('From: ' . $from);
if (!is_array($cc)) {
$cc = ($cc) ? array($cc) : array();
}
if (!is_array($bcc)) {
$bcc = ($bcc) ? array($bcc) : array();
}
foreach ($cc as $c) {
$this->headers("Cc: " . $c);
}
foreach ($bcc as $b) {
$this->headers("Bcc: " . $b);
}
if ($replyTo)
$this->headers("Reply-To: " . $replyTo);
return $this;
} | -------------- private methods --------------------- | https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/Email.php#L217-L240 |
thomasez/BisonLabSakonninBundle | Service/Messages.php | Messages.getMessagesForContext | public function getMessagesForContext($criterias)
{
if (!isset($criterias['context'])) {
$criterias['context'] = [
'system' => $criterias['system'],
'object_name' => $criterias['object_name'],
'external_id' => $criterias['external_id'],
];
}
return $this->getMessages($criterias);
} | php | public function getMessagesForContext($criterias)
{
if (!isset($criterias['context'])) {
$criterias['context'] = [
'system' => $criterias['system'],
'object_name' => $criterias['object_name'],
'external_id' => $criterias['external_id'],
];
}
return $this->getMessages($criterias);
} | /*
Get and list messsag(es) functions. | https://github.com/thomasez/BisonLabSakonninBundle/blob/45ca7ce9874c4a2be7b503d7067b3d11d2b518cb/Service/Messages.php#L218-L228 |
wearenolte/wp-acf | src/Acf.php | Acf.get_post_field | public static function get_post_field( $post_id = 0, $include_wp_fields = true, $field = '' ) {
if ( $include_wp_fields && ! $field ) {
$wp_fields = [
'post_id' => $post_id,
'permalink' => get_permalink( $post_id ),
'title' => get_the_title( $post_id ),
'content' => apply_filters( 'the_content', get_post_field( 'post_content', $post_id ) ),
];
return array_merge( $wp_fields, self::get_field( $post_id ) );
}
return self::get_field( $post_id, $field );
} | php | public static function get_post_field( $post_id = 0, $include_wp_fields = true, $field = '' ) {
if ( $include_wp_fields && ! $field ) {
$wp_fields = [
'post_id' => $post_id,
'permalink' => get_permalink( $post_id ),
'title' => get_the_title( $post_id ),
'content' => apply_filters( 'the_content', get_post_field( 'post_content', $post_id ) ),
];
return array_merge( $wp_fields, self::get_field( $post_id ) );
}
return self::get_field( $post_id, $field );
} | Get the field value for a post.
@param int $post_id The target post's id. Or leave blank for he current post if in the loop.
@param bool $include_wp_fields Whether or not to include the default WP fields.
@param string $field The ACF field id or name. Return all fields if blank.
@return array | https://github.com/wearenolte/wp-acf/blob/2f5093438d637fa0eca42ad6d10f6b433ec078b2/src/Acf.php#L26-L37 |
wearenolte/wp-acf | src/Acf.php | Acf.get_taxonomy_field | public static function get_taxonomy_field( $taxonomy_term, $field = '' ) {
if ( is_a( $taxonomy_term, 'WP_Term' ) ) {
return self::get_field( $taxonomy_term, $field );
} elseif ( is_array( $taxonomy_term ) && count( $taxonomy_term ) >= 2 ) {
return self::get_field( "{$taxonomy_term[0]}_{$taxonomy_term[1]}", $field );
}
throw new \Exception( '$taxonomy_term must be either a term object or an array of [$taxonomy, $term_id]' );
} | php | public static function get_taxonomy_field( $taxonomy_term, $field = '' ) {
if ( is_a( $taxonomy_term, 'WP_Term' ) ) {
return self::get_field( $taxonomy_term, $field );
} elseif ( is_array( $taxonomy_term ) && count( $taxonomy_term ) >= 2 ) {
return self::get_field( "{$taxonomy_term[0]}_{$taxonomy_term[1]}", $field );
}
throw new \Exception( '$taxonomy_term must be either a term object or an array of [$taxonomy, $term_id]' );
} | Get the fields for a taxonomy term.
@param array|\WP_Term $taxonomy_term The target term's [taxonomy, $term_id] or term object.
@param string $field The ACF field id or name. Return all fields if blank.
@return mixed
@throws \Exception | https://github.com/wearenolte/wp-acf/blob/2f5093438d637fa0eca42ad6d10f6b433ec078b2/src/Acf.php#L69-L76 |
wearenolte/wp-acf | src/Acf.php | Acf.get_field | private static function get_field( $target_id = 0, $field = '' ) {
if ( self::is_active() ) {
if ( $field ) {
return self::get_single_field( $target_id, $field );
} else {
return self::get_all_fields( $target_id );
}
}
return $field ? null : [];
} | php | private static function get_field( $target_id = 0, $field = '' ) {
if ( self::is_active() ) {
if ( $field ) {
return self::get_single_field( $target_id, $field );
} else {
return self::get_all_fields( $target_id );
}
}
return $field ? null : [];
} | Get all field values.
@param int $target_id The target object's id.
@param string $field The ACF field id or name. Return all fields if blank.
@return array | https://github.com/wearenolte/wp-acf/blob/2f5093438d637fa0eca42ad6d10f6b433ec078b2/src/Acf.php#L117-L126 |
wearenolte/wp-acf | src/Acf.php | Acf.get_all_fields | private static function get_all_fields( $target_id = 0 ) {
$data = [];
$field_objs = get_field_objects( $target_id );
if ( $field_objs ) {
foreach ( $field_objs as $field_name => $field_obj ) {
$value = self::get_single_field( $target_id, $field_obj );
$group_slug = self::get_group_slug( $field_obj['parent'] );
if ( $group_slug ) {
$data[ $group_slug ][ $field_name ] = $value;
} else {
$data[ $field_name ] = $value;
}
}
}
return $data;
} | php | private static function get_all_fields( $target_id = 0 ) {
$data = [];
$field_objs = get_field_objects( $target_id );
if ( $field_objs ) {
foreach ( $field_objs as $field_name => $field_obj ) {
$value = self::get_single_field( $target_id, $field_obj );
$group_slug = self::get_group_slug( $field_obj['parent'] );
if ( $group_slug ) {
$data[ $group_slug ][ $field_name ] = $value;
} else {
$data[ $field_name ] = $value;
}
}
}
return $data;
} | Get all the fields for the target object.
@param int $target_id The id of the target object.
@return array | https://github.com/wearenolte/wp-acf/blob/2f5093438d637fa0eca42ad6d10f6b433ec078b2/src/Acf.php#L134-L154 |
wearenolte/wp-acf | src/Acf.php | Acf.get_single_field | private static function get_single_field( $target_id = 0, $field = '' ) {
$field_obj = is_array( $field ) ? $field : get_field_object( $field, $target_id );
$field_key = isset( $field_obj['key'] ) ? $field_obj['key'] : '';
$filter_name = Filter::create_name( Filter::DEFAULT_TRANSFORMS, $field_key );
$apply_default_transforms = apply_filters( $filter_name, $target_id, $field_obj );
$value = $apply_default_transforms ? self::apply_default_transform( $field_obj ) : $field_obj['value'];
$filter_name = Filter::create_name( Filter::FIELD, $field_key );
return apply_filters( $filter_name, $value, $target_id, $field_obj );
} | php | private static function get_single_field( $target_id = 0, $field = '' ) {
$field_obj = is_array( $field ) ? $field : get_field_object( $field, $target_id );
$field_key = isset( $field_obj['key'] ) ? $field_obj['key'] : '';
$filter_name = Filter::create_name( Filter::DEFAULT_TRANSFORMS, $field_key );
$apply_default_transforms = apply_filters( $filter_name, $target_id, $field_obj );
$value = $apply_default_transforms ? self::apply_default_transform( $field_obj ) : $field_obj['value'];
$filter_name = Filter::create_name( Filter::FIELD, $field_key );
return apply_filters( $filter_name, $value, $target_id, $field_obj );
} | Gat a single field value for a target object.
@param int $target_id The id of the target object.
@param string $field The field id or name.
@return mixed | https://github.com/wearenolte/wp-acf/blob/2f5093438d637fa0eca42ad6d10f6b433ec078b2/src/Acf.php#L163-L175 |
wearenolte/wp-acf | src/Acf.php | Acf.get_group_slug | private static function get_group_slug( $group_id ) {
global $acf_local;
if ( isset( $acf_local->groups[ $group_id ] ) ) {
// First try the local groups (added by PHP).
$title = $acf_local->groups[ $group_id ]['title'];
} else {
$title = '';
if ( is_numeric( $group_id ) ) {
$args = [
'post_type' => 'acf-field-group',
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'fields' => 'ids',
'post__in' => [ $group_id ],
];
$groups = new \WP_Query( $args );
$acf_groups = is_array( $groups->posts ) ? $groups->posts : [];
$acf_id = empty( $acf_groups ) ? 0 : $acf_groups[0];
$title = get_the_title( $acf_id );
} else {
$group = acf_get_local_field_group( $group_id );
$title = empty( $group['title'] ) ? $group['title'] : '';
}
// Patch for the new version of ACF Fields plugins >= 5.4.*.
if ( ! $title ) {
$groups = acf_get_field_group( $group_id );
$title = empty( $groups ) ? false : $groups['title'];
}
}
if ( $title ) {
return strtolower( str_replace( ' ', '_', $title ) );
}
return false;
} | php | private static function get_group_slug( $group_id ) {
global $acf_local;
if ( isset( $acf_local->groups[ $group_id ] ) ) {
// First try the local groups (added by PHP).
$title = $acf_local->groups[ $group_id ]['title'];
} else {
$title = '';
if ( is_numeric( $group_id ) ) {
$args = [
'post_type' => 'acf-field-group',
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'fields' => 'ids',
'post__in' => [ $group_id ],
];
$groups = new \WP_Query( $args );
$acf_groups = is_array( $groups->posts ) ? $groups->posts : [];
$acf_id = empty( $acf_groups ) ? 0 : $acf_groups[0];
$title = get_the_title( $acf_id );
} else {
$group = acf_get_local_field_group( $group_id );
$title = empty( $group['title'] ) ? $group['title'] : '';
}
// Patch for the new version of ACF Fields plugins >= 5.4.*.
if ( ! $title ) {
$groups = acf_get_field_group( $group_id );
$title = empty( $groups ) ? false : $groups['title'];
}
}
if ( $title ) {
return strtolower( str_replace( ' ', '_', $title ) );
}
return false;
} | Get an ACF group slug
@param $group_id
@return string|bool | https://github.com/wearenolte/wp-acf/blob/2f5093438d637fa0eca42ad6d10f6b433ec078b2/src/Acf.php#L211-L250 |
Vectrex/vxPHP | src/Form/FormElement/FileInputElement.php | FileInputElement.getValue | public function getValue()
{
$file = $this->getFile();
if($file instanceof UploadedFile) {
return $file->getOriginalName();
}
if(is_array($file) && $file[0] instanceof UploadedFile) {
return $file[0]->getOriginalName();
}
return null;
} | php | public function getValue()
{
$file = $this->getFile();
if($file instanceof UploadedFile) {
return $file->getOriginalName();
}
if(is_array($file) && $file[0] instanceof UploadedFile) {
return $file[0]->getOriginalName();
}
return null;
} | get original name of an uploaded file associated with this element
if attribute multiple is set the name of the first file is returned
@return string | https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Form/FormElement/FileInputElement.php#L44-L57 |
wb-crowdfusion/crowdfusion | system/core/classes/mvc/filters/NonceFilterer.php | NonceFilterer.nonce | protected function nonce()
{
$action = ($this->getParameter('action') == null) ?
$this->RequestContext->getControls()->getControl('action')
: $this->getParameter('action');
return $this->Nonces->create($action);
} | php | protected function nonce()
{
$action = ($this->getParameter('action') == null) ?
$this->RequestContext->getControls()->getControl('action')
: $this->getParameter('action');
return $this->Nonces->create($action);
} | Creates a nonce for the current or specified action
Expected Param:
action string (optional) The action that the nonce will be valid for.
If not specified, the current action will be used
@return string | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/filters/NonceFilterer.php#L50-L57 |
flipbox/spark | src/services/traits/ElementByString.php | ElementByString.findCacheByString | public function findCacheByString(string $string, int $siteId = null)
{
// Check if already in cache
if ($this->isCachedByString($string, $siteId)) {
return $this->cacheByString[$siteId][$string];
}
return null;
} | php | public function findCacheByString(string $string, int $siteId = null)
{
// Check if already in cache
if ($this->isCachedByString($string, $siteId)) {
return $this->cacheByString[$siteId][$string];
}
return null;
} | Find an existing cache by Handle
@param string $string
@param int|null $siteId
@return BaseElement|ElementInterface|null | https://github.com/flipbox/spark/blob/9d75fd3d95744b9c9187921c4f3b9eea42c035d4/src/services/traits/ElementByString.php#L125-L134 |
flipbox/spark | src/services/traits/ElementByString.php | ElementByString.isCachedByString | protected function isCachedByString($string, int $siteId = null)
{
// Resolve siteId
$siteId = SiteHelper::resolveSiteId($siteId);
if (!isset($this->cacheByString[$siteId])) {
$this->cacheByString[$siteId] = [];
}
return array_key_exists($string, $this->cacheByString[$siteId]);
} | php | protected function isCachedByString($string, int $siteId = null)
{
// Resolve siteId
$siteId = SiteHelper::resolveSiteId($siteId);
if (!isset($this->cacheByString[$siteId])) {
$this->cacheByString[$siteId] = [];
}
return array_key_exists($string, $this->cacheByString[$siteId]);
} | Identify whether in cached by string
@param $string
@param int|null $siteId
@return bool | https://github.com/flipbox/spark/blob/9d75fd3d95744b9c9187921c4f3b9eea42c035d4/src/services/traits/ElementByString.php#L143-L154 |
maddoger/yii2-datetime-behavior | DateTimeAttribute.php | DateTimeAttribute.parseDateValue | protected static function parseDateValue($value, $format, $timeZone)
{
$date = DateTime::createFromFormat($format, $value, new DateTimeZone($timeZone));
$errors = DateTime::getLastErrors();
if ($date === false || $errors['error_count'] || $errors['warning_count']) {
return false;
} else {
// if no time was provided in the format string set time to 0 to get a simple date timestamp
if (strpbrk($format, 'UHhGgis') === false) {
$date->setTime(0, 0, 0);
}
return $date;
}
} | php | protected static function parseDateValue($value, $format, $timeZone)
{
$date = DateTime::createFromFormat($format, $value, new DateTimeZone($timeZone));
$errors = DateTime::getLastErrors();
if ($date === false || $errors['error_count'] || $errors['warning_count']) {
return false;
} else {
// if no time was provided in the format string set time to 0 to get a simple date timestamp
if (strpbrk($format, 'UHhGgis') === false) {
$date->setTime(0, 0, 0);
}
return $date;
}
} | Parses date string into DateTime object
@param string $value string representing date
@param string $format string representing date
@param string $timeZone string representing date
@return boolean|DateTime DateTime object or false on failure | https://github.com/maddoger/yii2-datetime-behavior/blob/3fd04ab1b2c3b10e620ae4c7971e3d9ef8084db3/DateTimeAttribute.php#L145-L158 |
Eden-PHP/Registry | src/Index.php | Index.get | public function get($modified = true)
{
//get args
$args = func_get_args();
if (count($args) == 0) {
return null;
}
$last = array_pop($args);
$pointer = &$this->data;
foreach ($args as $step) {
if (!isset($pointer[$step])) {
return null;
}
$pointer = &$pointer[$step];
}
if (!isset($pointer[$last])) {
return null;
}
return $pointer[$last];
} | php | public function get($modified = true)
{
//get args
$args = func_get_args();
if (count($args) == 0) {
return null;
}
$last = array_pop($args);
$pointer = &$this->data;
foreach ($args as $step) {
if (!isset($pointer[$step])) {
return null;
}
$pointer = &$pointer[$step];
}
if (!isset($pointer[$last])) {
return null;
}
return $pointer[$last];
} | Gets a value given the path in the registry.
@param scalar[, scalar..] $modified The registry path; yea i know this is wierd
@return mixed | https://github.com/Eden-PHP/Registry/blob/4ec72e314a65372fdf30b6dff772db6ff21dd11a/src/Index.php#L40-L64 |
Eden-PHP/Registry | src/Index.php | Index.getDot | public function getDot($notation, $separator = '.')
{
Argument::i()
//argument 1 must be a string
->test(1, 'string')
//argument 2 must be a string
->test(2, 'string');
$args = explode($separator, $notation);
return call_user_func_array(array($this, 'get'), $args);
} | php | public function getDot($notation, $separator = '.')
{
Argument::i()
//argument 1 must be a string
->test(1, 'string')
//argument 2 must be a string
->test(2, 'string');
$args = explode($separator, $notation);
return call_user_func_array(array($this, 'get'), $args);
} | Gets a value given the path in the registry.
@param *string $notation Name space string notation
@param string $separator If you want to specify a different separator other than dot
@return mixed | https://github.com/Eden-PHP/Registry/blob/4ec72e314a65372fdf30b6dff772db6ff21dd11a/src/Index.php#L86-L97 |
Eden-PHP/Registry | src/Index.php | Index.isKey | public function isKey()
{
$args = func_get_args();
if (count($args) == 0) {
return $this;
}
$last = array_pop($args);
$pointer = &$this->data;
foreach ($args as $i => $step) {
if (!isset($pointer[$step])
|| !is_array($pointer[$step])
) {
return false;
}
$pointer = &$pointer[$step];
}
if (!isset($pointer[$last])) {
return false;
}
return true;
} | php | public function isKey()
{
$args = func_get_args();
if (count($args) == 0) {
return $this;
}
$last = array_pop($args);
$pointer = &$this->data;
foreach ($args as $i => $step) {
if (!isset($pointer[$step])
|| !is_array($pointer[$step])
) {
return false;
}
$pointer = &$pointer[$step];
}
if (!isset($pointer[$last])) {
return false;
}
return true;
} | Checks to see if a key is set
@return bool | https://github.com/Eden-PHP/Registry/blob/4ec72e314a65372fdf30b6dff772db6ff21dd11a/src/Index.php#L125-L151 |
Eden-PHP/Registry | src/Index.php | Index.remove | public function remove()
{
$args = func_get_args();
if (count($args) == 0) {
return $this;
}
$last = array_pop($args);
$pointer = &$this->data;
foreach ($args as $i => $step) {
if (!isset($pointer[$step])
|| !is_array($pointer[$step])
) {
return $this;
}
$pointer = &$pointer[$step];
}
unset($pointer[$last]);
return $this;
} | php | public function remove()
{
$args = func_get_args();
if (count($args) == 0) {
return $this;
}
$last = array_pop($args);
$pointer = &$this->data;
foreach ($args as $i => $step) {
if (!isset($pointer[$step])
|| !is_array($pointer[$step])
) {
return $this;
}
$pointer = &$pointer[$step];
}
unset($pointer[$last]);
return $this;
} | Removes a key and everything associated with it
@return Eden\Registry\Index | https://github.com/Eden-PHP/Registry/blob/4ec72e314a65372fdf30b6dff772db6ff21dd11a/src/Index.php#L158-L182 |
Eden-PHP/Registry | src/Index.php | Index.set | public function set($value = null)
{
//get args
$args = func_get_args();
if (count($args) < 2) {
return $this;
}
$value = array_pop($args);
$last = array_pop($args);
$pointer = &$this->data;
foreach ($args as $i => $step) {
if (!isset($pointer[$step])
|| !is_array($pointer[$step])
) {
$pointer[$step] = array();
}
$pointer = &$pointer[$step];
}
$pointer[$last] = $value;
return $this;
} | php | public function set($value = null)
{
//get args
$args = func_get_args();
if (count($args) < 2) {
return $this;
}
$value = array_pop($args);
$last = array_pop($args);
$pointer = &$this->data;
foreach ($args as $i => $step) {
if (!isset($pointer[$step])
|| !is_array($pointer[$step])
) {
$pointer[$step] = array();
}
$pointer = &$pointer[$step];
}
$pointer[$last] = $value;
return $this;
} | Creates the name space given the space
and sets the value to that name space
@param scalar[, scalar..],*mixed $value The registry path; yea i know this is wierd
@return Eden\Registry\Index | https://github.com/Eden-PHP/Registry/blob/4ec72e314a65372fdf30b6dff772db6ff21dd11a/src/Index.php#L192-L218 |
Eden-PHP/Registry | src/Index.php | Index.setDot | public function setDot($notation, $value, $separator = '.')
{
Argument::i()
//argument 1 must be a string
->test(1, 'string')
//argument 3 must be a string
->test(3, 'string');
$args = explode($separator, $notation);
$args[] = $value;
return call_user_func_array(array($this, 'set'), $args);
} | php | public function setDot($notation, $value, $separator = '.')
{
Argument::i()
//argument 1 must be a string
->test(1, 'string')
//argument 3 must be a string
->test(3, 'string');
$args = explode($separator, $notation);
$args[] = $value;
return call_user_func_array(array($this, 'set'), $args);
} | Creates the name space given the space
and sets the value to that name space
@param *string $notation Name space string notation
@param *mixed $value Value to set on this namespace
@param string $separator If you want to specify a different separator other than dot
@return mixed | https://github.com/Eden-PHP/Registry/blob/4ec72e314a65372fdf30b6dff772db6ff21dd11a/src/Index.php#L230-L243 |
dann95/ts3-php | TeamSpeak3/Node/Channel.php | Channel.delete | public function delete($force = false)
{
$this->getParent()->channelDelete($this->getId(), $force);
unset($this);
} | php | public function delete($force = false)
{
$this->getParent()->channelDelete($this->getId(), $force);
unset($this);
} | Deletes the channel.
@param boolean $force
@return void | https://github.com/dann95/ts3-php/blob/d4693d78b54be0177a2b5fab316c0ff9d036238d/TeamSpeak3/Node/Channel.php#L451-L456 |
JBZoo/Console | src/App.php | App._registerCommands | protected function _registerCommands($commandsDir)
{
$files = FS::ls($commandsDir);
if (empty($files)) {
return false;
}
foreach ($files as $file) {
require_once $file;
$reflection = new \ReflectionClass(__NAMESPACE__ . '\\Command\\' . FS::filename($file));
if ($reflection->isSubclassOf('Symfony\\Component\\Console\\Command\\Command') &&
!$reflection->isAbstract()
) {
$this->add($reflection->newInstance());
}
}
return true;
} | php | protected function _registerCommands($commandsDir)
{
$files = FS::ls($commandsDir);
if (empty($files)) {
return false;
}
foreach ($files as $file) {
require_once $file;
$reflection = new \ReflectionClass(__NAMESPACE__ . '\\Command\\' . FS::filename($file));
if ($reflection->isSubclassOf('Symfony\\Component\\Console\\Command\\Command') &&
!$reflection->isAbstract()
) {
$this->add($reflection->newInstance());
}
}
return true;
} | Register commands
@param $commandsDir
@return bool | https://github.com/JBZoo/Console/blob/21ddc5d59214d8efa80ff178a48a327cf809b11b/src/App.php#L61-L82 |
zodream/database | src/Model/Model.php | Model.find | public static function find($param, $field = '*', $parameters = array()) {
if (empty($param)) {
return false;
}
$model = new static;
if (is_numeric($param)) {
$param = [$model->getKeyName() => $param];
}
if (!is_array($param) || !array_key_exists('where', $param)) {
$param = [
'where' => $param
];
}
return static::query()
->load($param)
->select($field)
->addBinding($parameters)
->one();
} | php | public static function find($param, $field = '*', $parameters = array()) {
if (empty($param)) {
return false;
}
$model = new static;
if (is_numeric($param)) {
$param = [$model->getKeyName() => $param];
}
if (!is_array($param) || !array_key_exists('where', $param)) {
$param = [
'where' => $param
];
}
return static::query()
->load($param)
->select($field)
->addBinding($parameters)
->one();
} | SELECT ONE BY QUERY
查询一条数据
@access public
@param array|string $param 条件
@param string $field
@param array $parameters
@return static|boolean
@throws \Exception | https://github.com/zodream/database/blob/03712219c057799d07350a3a2650c55bcc92c28e/src/Model/Model.php#L139-L157 |
zodream/database | src/Model/Model.php | Model.findOrNew | public static function findOrNew($param, $field = '*', $parameters = array()) {
if (empty($param)) {
return new static();
}
$model = static::find($param, $field, $parameters);
if (empty($model)) {
return new static();
}
return $model;
} | php | public static function findOrNew($param, $field = '*', $parameters = array()) {
if (empty($param)) {
return new static();
}
$model = static::find($param, $field, $parameters);
if (empty($model)) {
return new static();
}
return $model;
} | 查找或新增
@param $param
@param string $field
@param array $parameters
@return bool|Model|static
@throws \Exception | https://github.com/zodream/database/blob/03712219c057799d07350a3a2650c55bcc92c28e/src/Model/Model.php#L177-L186 |
zodream/database | src/Model/Model.php | Model.findOrDefault | public static function findOrDefault($param, array $attributes) {
$model = self::findOrNew($param);
if ($model->isNewRecord) {
$model->set($attributes);
}
return $model;
} | php | public static function findOrDefault($param, array $attributes) {
$model = self::findOrNew($param);
if ($model->isNewRecord) {
$model->set($attributes);
}
return $model;
} | Set not found default data
@param $param
@param array $attributes
@return bool|Model
@throws \Exception | https://github.com/zodream/database/blob/03712219c057799d07350a3a2650c55bcc92c28e/src/Model/Model.php#L195-L201 |
zodream/database | src/Model/Model.php | Model.findWithReplace | public static function findWithReplace($param, array $attributes) {
$model = self::findOrNew($param);
$model->set($attributes);
return $model;
} | php | public static function findWithReplace($param, array $attributes) {
$model = self::findOrNew($param);
$model->set($attributes);
return $model;
} | Set new attr
@param $param
@param array $attributes
@return bool|Model
@throws \Exception | https://github.com/zodream/database/blob/03712219c057799d07350a3a2650c55bcc92c28e/src/Model/Model.php#L210-L214 |
zodream/database | src/Model/Model.php | Model.findOrThrow | public static function findOrThrow($param, $field = '*', $parameters = array()) {
$model = static::find($param, $field, $parameters);
if (empty($model)) {
throw new \InvalidArgumentException($param);
}
return $model;
} | php | public static function findOrThrow($param, $field = '*', $parameters = array()) {
$model = static::find($param, $field, $parameters);
if (empty($model)) {
throw new \InvalidArgumentException($param);
}
return $model;
} | 查找或报错
@param $param
@param string $field
@param array $parameters
@return bool|Model
@throws \Exception | https://github.com/zodream/database/blob/03712219c057799d07350a3a2650c55bcc92c28e/src/Model/Model.php#L224-L230 |
stubbles/stubbles-peer | src/main/php/Stream.php | Stream.setTimeout | public function setTimeout(int $seconds, int $microseconds = 0): self
{
$this->timeout = (float) ($seconds . '.' . $microseconds);
stream_set_timeout($this->resource, $seconds, $microseconds);
return $this;
} | php | public function setTimeout(int $seconds, int $microseconds = 0): self
{
$this->timeout = (float) ($seconds . '.' . $microseconds);
stream_set_timeout($this->resource, $seconds, $microseconds);
return $this;
} | set timeout for connections
@param int $seconds timeout for connection in seconds
@param int $microseconds optional timeout for connection in microseconds
@return $this | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/Stream.php#L96-L101 |
stubbles/stubbles-peer | src/main/php/Stream.php | Stream.read | public function read(int $length = null): string
{
// can not call fgets with null when not specified
$data = null === $length ? fgets($this->resource) : fgets($this->resource, $length);
if (false === $data) {
// fgets() returns false on eof while feof() returned false before
// but will now return true
if ($this->eof()) {
return '';
}
if (stream_get_meta_data($this->resource)['timed_out']) {
throw new Timeout(
'Reading of ' . $length . ' bytes failed: timeout of '
. $this->timeout . ' seconds exceeded'
);
}
throw new ConnectionFailure(
'Reading of ' . $length . ' bytes failed.'
);
}
return $data;
} | php | public function read(int $length = null): string
{
// can not call fgets with null when not specified
$data = null === $length ? fgets($this->resource) : fgets($this->resource, $length);
if (false === $data) {
// fgets() returns false on eof while feof() returned false before
// but will now return true
if ($this->eof()) {
return '';
}
if (stream_get_meta_data($this->resource)['timed_out']) {
throw new Timeout(
'Reading of ' . $length . ' bytes failed: timeout of '
. $this->timeout . ' seconds exceeded'
);
}
throw new ConnectionFailure(
'Reading of ' . $length . ' bytes failed.'
);
}
return $data;
} | read from socket
@param int $length optional length of data to read
@return string data read from socket
@throws \stubbles\peer\ConnectionFailure
@throws \stubbles\peer\Timeout | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/Stream.php#L121-L145 |
stubbles/stubbles-peer | src/main/php/Stream.php | Stream.readBinary | public function readBinary(int $length = 1024): string
{
$data = fread($this->resource, $length);
if (false === $data) {
if (stream_get_meta_data($this->resource)['timed_out']) {
throw new Timeout(
'Reading of ' . $length . ' bytes failed: timeout of '
. $this->timeout . ' seconds exceeded'
);
}
throw new ConnectionFailure(
'Reading of ' . $length . ' bytes failed.'
);
}
return $data;
} | php | public function readBinary(int $length = 1024): string
{
$data = fread($this->resource, $length);
if (false === $data) {
if (stream_get_meta_data($this->resource)['timed_out']) {
throw new Timeout(
'Reading of ' . $length . ' bytes failed: timeout of '
. $this->timeout . ' seconds exceeded'
);
}
throw new ConnectionFailure(
'Reading of ' . $length . ' bytes failed.'
);
}
return $data;
} | read binary data from socket
@param int $length length of data to read
@return string data read from socket
@throws \stubbles\peer\ConnectionFailure
@throws \stubbles\peer\Timeout | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/Stream.php#L165-L182 |
stubbles/stubbles-peer | src/main/php/Stream.php | Stream.write | public function write(string $data): int
{
$length = fputs($this->resource, $data, strlen($data));
if (false === $length) {
if (stream_get_meta_data($this->resource)['timed_out']) {
throw new Timeout(
'Writing of ' . strlen($data) . ' bytes failed:'
. ' timeout of ' . $this->timeout . ' seconds exceeded'
);
}
throw new ConnectionFailure(
'Writing of ' . strlen($data) . ' bytes failed.'
);
}
return $length;
} | php | public function write(string $data): int
{
$length = fputs($this->resource, $data, strlen($data));
if (false === $length) {
if (stream_get_meta_data($this->resource)['timed_out']) {
throw new Timeout(
'Writing of ' . strlen($data) . ' bytes failed:'
. ' timeout of ' . $this->timeout . ' seconds exceeded'
);
}
throw new ConnectionFailure(
'Writing of ' . strlen($data) . ' bytes failed.'
);
}
return $length;
} | write data to socket
@param string $data data to write
@return int amount of bytes written to socket
@throws \stubbles\peer\ConnectionFailure
@throws \stubbles\peer\Timeout | https://github.com/stubbles/stubbles-peer/blob/dc8b0a517dc4c84b615cc3c88f0d64a2b742f9cc/src/main/php/Stream.php#L192-L209 |
sil-project/VarietyBundle | src/Controller/VarietyCRUDController.php | VarietyCRUDController.strainAction | public function strainAction()
{
$id = $this->getRequest()->get($this->admin->getIdParameter());
$object = $this->admin->getObject($id);
$strain = clone $object;
$strain->setIsStrain(true);
$strain->setParent($object);
$fieldSets = ['Professional', 'Amateur', 'Production', 'Commercial', 'Plant', 'Culture', 'Inner'];
foreach ($fieldSets as $label) {
$getter = 'get' . $label . 'Descriptions';
$adder = 'add' . $label . 'Description';
$collection = $object->$getter();
$collection->initialize();
foreach ($collection as $desc) {
$new = clone $desc;
$strain->$adder($new);
}
}
$this->duplicateFiles($object, $strain);
foreach ($object->getPlantCategories() as $cat) {
$strain->addPlantCategory($cat);
}
return $this->createAction($strain);
} | php | public function strainAction()
{
$id = $this->getRequest()->get($this->admin->getIdParameter());
$object = $this->admin->getObject($id);
$strain = clone $object;
$strain->setIsStrain(true);
$strain->setParent($object);
$fieldSets = ['Professional', 'Amateur', 'Production', 'Commercial', 'Plant', 'Culture', 'Inner'];
foreach ($fieldSets as $label) {
$getter = 'get' . $label . 'Descriptions';
$adder = 'add' . $label . 'Description';
$collection = $object->$getter();
$collection->initialize();
foreach ($collection as $desc) {
$new = clone $desc;
$strain->$adder($new);
}
}
$this->duplicateFiles($object, $strain);
foreach ($object->getPlantCategories() as $cat) {
$strain->addPlantCategory($cat);
}
return $this->createAction($strain);
} | Creates a strain from a variety and passes it to create action.
@return Response | https://github.com/sil-project/VarietyBundle/blob/e9508ce13a4bb277d10bdcd925fdb84bc01f453f/src/Controller/VarietyCRUDController.php#L52-L82 |
sil-project/VarietyBundle | src/Controller/VarietyCRUDController.php | VarietyCRUDController.getFilterWidgetAction | public function getFilterWidgetAction(Request $request)
{
$translator = $this->get('translator');
$fieldSet = $request->get('fieldset');
$field = $request->get('field');
$config = $this->admin->getConfigurationPool()->getContainer()->getParameter('librinfo_varieties');
$fieldConfig = $config['variety_descriptions'][$fieldSet][$field];
$choiceType = CustomChoiceType::class;
$options = $fieldConfig['options'];
$type = $fieldConfig['type'] != 'textarea' ? $fieldConfig['type'] : 'text';
if ($type == 'blast_custom_checkbox') {
$type = 'choice';
$options = array_merge($options, array(
'choices' => array('1' => $translator->trans('yes'), '0' => $translator->trans('no')),
));
}
if ($type == $choiceType) {
$options['is_filter'] = true;
if (isset($options['expanded'])) {
unset($options['expanded']);
}
if (isset($options['multiple'])) {
unset($options['multiple']);
}
}
if ($type == 'blast_tinymce') {
$type = 'text';
}
if (isset($options['choices']) && empty($options['choices'])) {
unset($options['choices']);
}
if (isset($options['choices_class']) && $type != $choiceType) {
unset($options['choices_class']);
}
if (isset($options['blast_choices']) && $type != $choiceType) {
unset($options['blast_choices']);
}
if (isset($options['help'])) {
unset($options['help']);
}
$view = $this->createFormBuilder()
->add('value', $type, $options)
->getForm()
->createView()
;
return $this->render(
'LibrinfoVarietiesBundle:Form:filter_widget.html.twig',
array(
'form' => $view,
),
null
);
} | php | public function getFilterWidgetAction(Request $request)
{
$translator = $this->get('translator');
$fieldSet = $request->get('fieldset');
$field = $request->get('field');
$config = $this->admin->getConfigurationPool()->getContainer()->getParameter('librinfo_varieties');
$fieldConfig = $config['variety_descriptions'][$fieldSet][$field];
$choiceType = CustomChoiceType::class;
$options = $fieldConfig['options'];
$type = $fieldConfig['type'] != 'textarea' ? $fieldConfig['type'] : 'text';
if ($type == 'blast_custom_checkbox') {
$type = 'choice';
$options = array_merge($options, array(
'choices' => array('1' => $translator->trans('yes'), '0' => $translator->trans('no')),
));
}
if ($type == $choiceType) {
$options['is_filter'] = true;
if (isset($options['expanded'])) {
unset($options['expanded']);
}
if (isset($options['multiple'])) {
unset($options['multiple']);
}
}
if ($type == 'blast_tinymce') {
$type = 'text';
}
if (isset($options['choices']) && empty($options['choices'])) {
unset($options['choices']);
}
if (isset($options['choices_class']) && $type != $choiceType) {
unset($options['choices_class']);
}
if (isset($options['blast_choices']) && $type != $choiceType) {
unset($options['blast_choices']);
}
if (isset($options['help'])) {
unset($options['help']);
}
$view = $this->createFormBuilder()
->add('value', $type, $options)
->getForm()
->createView()
;
return $this->render(
'LibrinfoVarietiesBundle:Form:filter_widget.html.twig',
array(
'form' => $view,
),
null
);
} | Get field widget for filter form.
@param string $fieldName the name of the field to get the form widget for
@return JsonResponse | https://github.com/sil-project/VarietyBundle/blob/e9508ce13a4bb277d10bdcd925fdb84bc01f453f/src/Controller/VarietyCRUDController.php#L91-L155 |
covex-nn/JooS_Stream | src/JooS/Stream/Entity/Deleted.php | Entity_Deleted.newInstance | public static function newInstance(Entity_Interface $realEntity)
{
$basename = $realEntity->basename();
$path = $realEntity->path();
$instance = new static($basename, $path);
/* @var $instance Entity_Deleted */
$instance->_realEntity = $realEntity;
return $instance;
} | php | public static function newInstance(Entity_Interface $realEntity)
{
$basename = $realEntity->basename();
$path = $realEntity->path();
$instance = new static($basename, $path);
/* @var $instance Entity_Deleted */
$instance->_realEntity = $realEntity;
return $instance;
} | Create new virtual stream entity
@param Entity_Interface $realEntity Real stream entity
@return Entity_Deleted | https://github.com/covex-nn/JooS_Stream/blob/e9841b804190a9f624b9e44caa0af7a18f3816d1/src/JooS/Stream/Entity/Deleted.php#L29-L39 |
phuria/under-query | src/QueryCompiler/ClausesCompiler.php | ClausesCompiler.compileWhere | public function compileWhere(CompilerPayload $payload)
{
$builder = $payload->getBuilder();
if ($builder instanceof Clause\WhereInterface && $builder->getWhereClauses()) {
$newSQL = 'WHERE ' . implode(' AND ', $builder->getWhereClauses());
$payload = $payload->appendSQL($newSQL);
}
return $payload;
} | php | public function compileWhere(CompilerPayload $payload)
{
$builder = $payload->getBuilder();
if ($builder instanceof Clause\WhereInterface && $builder->getWhereClauses()) {
$newSQL = 'WHERE ' . implode(' AND ', $builder->getWhereClauses());
$payload = $payload->appendSQL($newSQL);
}
return $payload;
} | @param CompilerPayload $payload
@return CompilerPayload | https://github.com/phuria/under-query/blob/f5e733808c1f109fa73fd95a1fbc5c78fb4b8793/src/QueryCompiler/ClausesCompiler.php#L26-L36 |
phuria/under-query | src/QueryCompiler/ClausesCompiler.php | ClausesCompiler.compileGroupBy | public function compileGroupBy(CompilerPayload $payload)
{
$builder = $payload->getBuilder();
if ($builder instanceof Clause\GroupByInterface && $builder->getGroupByClauses()) {
$newSQL = 'GROUP BY ' . implode(', ', $builder->getGroupByClauses());
$payload = $payload->appendSQL($newSQL);
}
if ($builder instanceof Clause\GroupByInterface && $builder->isGroupByWithRollUp()) {
$payload = $payload->appendSQL('WITH ROLLUP');
}
return $payload;
} | php | public function compileGroupBy(CompilerPayload $payload)
{
$builder = $payload->getBuilder();
if ($builder instanceof Clause\GroupByInterface && $builder->getGroupByClauses()) {
$newSQL = 'GROUP BY ' . implode(', ', $builder->getGroupByClauses());
$payload = $payload->appendSQL($newSQL);
}
if ($builder instanceof Clause\GroupByInterface && $builder->isGroupByWithRollUp()) {
$payload = $payload->appendSQL('WITH ROLLUP');
}
return $payload;
} | @param CompilerPayload $payload
@return CompilerPayload | https://github.com/phuria/under-query/blob/f5e733808c1f109fa73fd95a1fbc5c78fb4b8793/src/QueryCompiler/ClausesCompiler.php#L43-L57 |
phuria/under-query | src/QueryCompiler/ClausesCompiler.php | ClausesCompiler.compileHaving | public function compileHaving(CompilerPayload $payload)
{
$builder = $payload->getBuilder();
if ($builder instanceof Clause\HavingInterface && $builder->getHavingClauses()) {
$newSQL = 'HAVING ' . implode(' AND ', $builder->getHavingClauses());
$payload = $payload->appendSQL($newSQL);
}
return $payload;
} | php | public function compileHaving(CompilerPayload $payload)
{
$builder = $payload->getBuilder();
if ($builder instanceof Clause\HavingInterface && $builder->getHavingClauses()) {
$newSQL = 'HAVING ' . implode(' AND ', $builder->getHavingClauses());
$payload = $payload->appendSQL($newSQL);
}
return $payload;
} | @param CompilerPayload $payload
@return CompilerPayload | https://github.com/phuria/under-query/blob/f5e733808c1f109fa73fd95a1fbc5c78fb4b8793/src/QueryCompiler/ClausesCompiler.php#L64-L74 |
phuria/under-query | src/QueryCompiler/ClausesCompiler.php | ClausesCompiler.compileOrderBy | public function compileOrderBy(CompilerPayload $payload)
{
$builder = $payload->getBuilder();
if ($builder instanceof Clause\OrderByInterface && $builder->getOrderByClauses()) {
$newSQL = 'ORDER BY ' . implode(', ', $builder->getOrderByClauses());
$payload = $payload->appendSQL($newSQL);
}
return $payload;
} | php | public function compileOrderBy(CompilerPayload $payload)
{
$builder = $payload->getBuilder();
if ($builder instanceof Clause\OrderByInterface && $builder->getOrderByClauses()) {
$newSQL = 'ORDER BY ' . implode(', ', $builder->getOrderByClauses());
$payload = $payload->appendSQL($newSQL);
}
return $payload;
} | @param CompilerPayload $payload
@return CompilerPayload | https://github.com/phuria/under-query/blob/f5e733808c1f109fa73fd95a1fbc5c78fb4b8793/src/QueryCompiler/ClausesCompiler.php#L81-L91 |
phuria/under-query | src/QueryCompiler/ClausesCompiler.php | ClausesCompiler.compileLimit | public function compileLimit(CompilerPayload $payload)
{
$builder = $payload->getBuilder();
if ($builder instanceof Clause\LimitInterface && $builder->getLimitClause()) {
$newSQL = 'LIMIT ' . $builder->getLimitClause();
$payload = $payload->appendSQL($newSQL);
}
return $payload;
} | php | public function compileLimit(CompilerPayload $payload)
{
$builder = $payload->getBuilder();
if ($builder instanceof Clause\LimitInterface && $builder->getLimitClause()) {
$newSQL = 'LIMIT ' . $builder->getLimitClause();
$payload = $payload->appendSQL($newSQL);
}
return $payload;
} | @param CompilerPayload $payload
@return CompilerPayload | https://github.com/phuria/under-query/blob/f5e733808c1f109fa73fd95a1fbc5c78fb4b8793/src/QueryCompiler/ClausesCompiler.php#L98-L108 |
phuria/under-query | src/QueryCompiler/ClausesCompiler.php | ClausesCompiler.compileSet | public function compileSet(CompilerPayload $payload)
{
$builder = $payload->getBuilder();
if ($builder instanceof Clause\SetInterface && $builder->getSetClauses()) {
$newSQL = 'SET ' . implode(', ', $builder->getSetClauses());
$payload = $payload->appendSQL($newSQL);
}
return $payload;
} | php | public function compileSet(CompilerPayload $payload)
{
$builder = $payload->getBuilder();
if ($builder instanceof Clause\SetInterface && $builder->getSetClauses()) {
$newSQL = 'SET ' . implode(', ', $builder->getSetClauses());
$payload = $payload->appendSQL($newSQL);
}
return $payload;
} | @param CompilerPayload $payload
@return CompilerPayload | https://github.com/phuria/under-query/blob/f5e733808c1f109fa73fd95a1fbc5c78fb4b8793/src/QueryCompiler/ClausesCompiler.php#L115-L125 |
phuria/under-query | src/QueryCompiler/ClausesCompiler.php | ClausesCompiler.compileSelect | public function compileSelect(CompilerPayload $payload)
{
$builder = $payload->getBuilder();
if ($builder instanceof Clause\SelectInterface && $builder->getSelectClauses()) {
$actualSQL = 'SELECT ' . implode(', ', $builder->getSelectClauses());
$payload = $payload->updateSQL($actualSQL);
}
return $payload;
} | php | public function compileSelect(CompilerPayload $payload)
{
$builder = $payload->getBuilder();
if ($builder instanceof Clause\SelectInterface && $builder->getSelectClauses()) {
$actualSQL = 'SELECT ' . implode(', ', $builder->getSelectClauses());
$payload = $payload->updateSQL($actualSQL);
}
return $payload;
} | @param CompilerPayload $payload
@return CompilerPayload | https://github.com/phuria/under-query/blob/f5e733808c1f109fa73fd95a1fbc5c78fb4b8793/src/QueryCompiler/ClausesCompiler.php#L132-L142 |
siriusSupreme/sirius-queue | src/Connectors/SqsConnector.php | SqsConnector.connect | public function connect(array $config)
{
$config = $this->getDefaultConfiguration($config);
if ($config['key'] && $config['secret']) {
$config['credentials'] = Arr::only($config, ['key', 'secret']);
}
return new SqsQueue(
new SqsClient($config), $config['queue'], $config['prefix'] ?? ''
);
} | php | public function connect(array $config)
{
$config = $this->getDefaultConfiguration($config);
if ($config['key'] && $config['secret']) {
$config['credentials'] = Arr::only($config, ['key', 'secret']);
}
return new SqsQueue(
new SqsClient($config), $config['queue'], $config['prefix'] ?? ''
);
} | Establish a queue connection.
@param array $config
@return \Sirius\Queue\Contracts\Queue | https://github.com/siriusSupreme/sirius-queue/blob/11c9ca563e6142b1bf0c788418f87948b0d4dc50/src/Connectors/SqsConnector.php#L18-L29 |
t3v/t3v_core | Classes/ViewHelpers/PageViewHelper.php | PageViewHelper.render | public function render(int $uid, bool $languageOverlay = true, int $sysLanguageUid = -1) {
return $this->pageService->getPageByUid($uid, $languageOverlay, $sysLanguageUid);
} | php | public function render(int $uid, bool $languageOverlay = true, int $sysLanguageUid = -1) {
return $this->pageService->getPageByUid($uid, $languageOverlay, $sysLanguageUid);
} | The view helper render function.
@param int $uid The UID of the page
@param bool $languageOverlay If set, the language record (overlay) will be applied, defaults to `true`
@param int $sysLanguageUid The optional system language UID, defaults to the current system language UID
@return array The page object | https://github.com/t3v/t3v_core/blob/8c04b7688cc2773f11fcc87fda3f7cd53d80a980/Classes/ViewHelpers/PageViewHelper.php#L28-L30 |
rafrsr/lib-array2object | src/Writer/AccessorWriter.php | AccessorWriter.setValue | public function setValue(&$object, $propertyPath, $value)
{
$this->accessor->setValue($object, $propertyPath, $value);
} | php | public function setValue(&$object, $propertyPath, $value)
{
$this->accessor->setValue($object, $propertyPath, $value);
} | {@inheritdoc} | https://github.com/rafrsr/lib-array2object/blob/d15db63b5f5740dbc7c2213373320445785856ef/src/Writer/AccessorWriter.php#L51-L54 |
cmsgears/module-community | admin/controllers/ChatController.php | ChatController.init | public function init() {
parent::init();
// Permissions
$this->crudPermission = CmnGlobal::PERM_GROUP_ADMIN;
// Config
$this->apixBase = 'community/chat';
// Services
$this->modelService = Yii::$app->factory->get( 'chatService' );
// Sidebar
$this->sidebar = [ 'parent' => 'sidebar-community', 'child' => 'chat' ];
// Return Url
$this->returnUrl = Url::previous( 'chats' );
$this->returnUrl = isset( $this->returnUrl ) ? $this->returnUrl : Url::toRoute( [ '/community/chat/all' ], true );
// Breadcrumbs
$this->breadcrumbs = [
'base' => [
[ 'label' => 'Home', 'url' => Url::toRoute( '/dashboard' ) ]
],
'all' => [ [ 'label' => 'Chat Sessions' ] ],
'create' => [ [ 'label' => 'Chat Sessions', 'url' => $this->returnUrl ], [ 'label' => 'Add' ] ],
'update' => [ [ 'label' => 'Chat Sessions', 'url' => $this->returnUrl ], [ 'label' => 'Update' ] ],
'delete' => [ [ 'label' => 'Chat Sessions', 'url' => $this->returnUrl ], [ 'label' => 'Delete' ] ]
];
} | php | public function init() {
parent::init();
// Permissions
$this->crudPermission = CmnGlobal::PERM_GROUP_ADMIN;
// Config
$this->apixBase = 'community/chat';
// Services
$this->modelService = Yii::$app->factory->get( 'chatService' );
// Sidebar
$this->sidebar = [ 'parent' => 'sidebar-community', 'child' => 'chat' ];
// Return Url
$this->returnUrl = Url::previous( 'chats' );
$this->returnUrl = isset( $this->returnUrl ) ? $this->returnUrl : Url::toRoute( [ '/community/chat/all' ], true );
// Breadcrumbs
$this->breadcrumbs = [
'base' => [
[ 'label' => 'Home', 'url' => Url::toRoute( '/dashboard' ) ]
],
'all' => [ [ 'label' => 'Chat Sessions' ] ],
'create' => [ [ 'label' => 'Chat Sessions', 'url' => $this->returnUrl ], [ 'label' => 'Add' ] ],
'update' => [ [ 'label' => 'Chat Sessions', 'url' => $this->returnUrl ], [ 'label' => 'Update' ] ],
'delete' => [ [ 'label' => 'Chat Sessions', 'url' => $this->returnUrl ], [ 'label' => 'Delete' ] ]
];
} | Constructor and Initialisation ------------------------------ | https://github.com/cmsgears/module-community/blob/0ca9cf0aa0cee395a4788bd6085f291e10728555/admin/controllers/ChatController.php#L37-L67 |
cmsgears/module-community | admin/controllers/ChatController.php | ChatController.actionAll | public function actionAll( $config = [] ) {
$modelClass = $this->modelService->getModelClass();
$dataProvider = $this->modelService->getPage();
return $this->render( 'all', [
'dataProvider' => $dataProvider,
'statusMap' => $modelClass::$statusMap
]);
} | php | public function actionAll( $config = [] ) {
$modelClass = $this->modelService->getModelClass();
$dataProvider = $this->modelService->getPage();
return $this->render( 'all', [
'dataProvider' => $dataProvider,
'statusMap' => $modelClass::$statusMap
]);
} | ChatController ------------------------ | https://github.com/cmsgears/module-community/blob/0ca9cf0aa0cee395a4788bd6085f291e10728555/admin/controllers/ChatController.php#L100-L110 |
wb-crowdfusion/crowdfusion | system/core/classes/libraries/errors/ErrorHandler.php | ErrorHandler.handleErrors | public function handleErrors($severity, $message, $filepath, $line)
{
if (error_reporting() == 0 || $severity == E_STRICT)
return;
if (false !== strpos($filepath, '/')) {
$x = explode('/', $filepath);
$filepath = $x[count($x)-3].'/'.$x[count($x)-2].'/'.end($x);
}
$mess = $this->getLevel($severity).'('.$severity.'): '.$message. ' in '.$filepath.' on line '.$line;
/*
* shouldn't need to log the error here as the exception will handle the logging.
*/
/*
$context = (isset($_SERVER['CONTEXT']) ? $_SERVER['CONTEXT'] : 'none');
if (array_key_exists('SITE', $_SERVER)) {
$appName = (string) $_SERVER['SITE']['slug'];
if ($appName === $context) {
$appName = $this->SiteService->getAnchoredSite()->Slug;
}
} else {
$appName = $_SERVER['SERVER_NAME'];
}
error_log("[{$this->environment}][$appName][$context][PHP_ERROR] " . $mess);
*/
if($severity == E_RECOVERABLE_ERROR)
throw new Exception($mess);
if (($severity & error_reporting()) == $severity) {
if($this->redeployOnError && isset($this->ApplicationContext))
$this->ApplicationContext->clearContextFiles();
throw new Exception($mess);
}
return true;
} | php | public function handleErrors($severity, $message, $filepath, $line)
{
if (error_reporting() == 0 || $severity == E_STRICT)
return;
if (false !== strpos($filepath, '/')) {
$x = explode('/', $filepath);
$filepath = $x[count($x)-3].'/'.$x[count($x)-2].'/'.end($x);
}
$mess = $this->getLevel($severity).'('.$severity.'): '.$message. ' in '.$filepath.' on line '.$line;
/*
* shouldn't need to log the error here as the exception will handle the logging.
*/
/*
$context = (isset($_SERVER['CONTEXT']) ? $_SERVER['CONTEXT'] : 'none');
if (array_key_exists('SITE', $_SERVER)) {
$appName = (string) $_SERVER['SITE']['slug'];
if ($appName === $context) {
$appName = $this->SiteService->getAnchoredSite()->Slug;
}
} else {
$appName = $_SERVER['SERVER_NAME'];
}
error_log("[{$this->environment}][$appName][$context][PHP_ERROR] " . $mess);
*/
if($severity == E_RECOVERABLE_ERROR)
throw new Exception($mess);
if (($severity & error_reporting()) == $severity) {
if($this->redeployOnError && isset($this->ApplicationContext))
$this->ApplicationContext->clearContextFiles();
throw new Exception($mess);
}
return true;
} | Defines the error handler that will be used when this class is created.
Using error_log, this function will record the error.
@param string $severity The severity of the error
@param string $message The error message
@param string $filepath The file where the error was encountered
@param string $line The line number where the error occured
@return void|boolean | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/errors/ErrorHandler.php#L140-L179 |
wb-crowdfusion/crowdfusion | system/core/classes/libraries/errors/ErrorHandler.php | ErrorHandler.handleExceptions | public function handleExceptions($exception)
{
$this->displayError($exception);
$this->sendErrorNotification($exception);
if(isset($this->ApplicationContext) && ($this->ApplicationContext->isOneOffRedeploy() || $this->redeployOnError))
$this->ApplicationContext->clearContextFiles();
} | php | public function handleExceptions($exception)
{
$this->displayError($exception);
$this->sendErrorNotification($exception);
if(isset($this->ApplicationContext) && ($this->ApplicationContext->isOneOffRedeploy() || $this->redeployOnError))
$this->ApplicationContext->clearContextFiles();
} | Defines the exception handler to use.
@param Exception $exception The exception to handle
@return void | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/errors/ErrorHandler.php#L234-L241 |
wb-crowdfusion/crowdfusion | system/core/classes/libraries/errors/ErrorHandler.php | ErrorHandler.sendErrorNotification | public function sendErrorNotification($message, $subject = null, $customMessage = false, $extraRecipients = null) {
$this->_sendErrorNotification('ERROR', $message, $subject, $customMessage, $extraRecipients);
} | php | public function sendErrorNotification($message, $subject = null, $customMessage = false, $extraRecipients = null) {
$this->_sendErrorNotification('ERROR', $message, $subject, $customMessage, $extraRecipients);
} | Facing error notification methods. Send the error notification specified by {@link $message}
@param string $message The message of the email. Can be instance of Exception or string
@param string $subject If specified, use this as the subject for the email.
@param string $customMessage Any message you'd like to appear in the email
@return void | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/errors/ErrorHandler.php#L355-L357 |
wb-crowdfusion/crowdfusion | system/core/classes/libraries/errors/ErrorHandler.php | ErrorHandler._sendErrorNotification | protected function _sendErrorNotification($prefix, $message, $subject = null, $customMessage = false, $extraRecipients = null)
{
$c = '';
if ($customMessage) {
$c .= $customMessage."\n\n";
}
if ($message instanceof Exception) {
$c .= get_class($message).": ".$message->getMessage()."\n";
if($message instanceof SQLException)
$c .= "SQL: ".$message->getSQL()."\n";
$c .= "Code: ".$message->getCode()."\n";
$c .= "File: ".$message->getFile()."\n";
$c .= "Line: ".$message->getLine()."\n";
$c .= "Stack Trace: ".$message->getTraceAsString()."\n\n";
} else {
$c .= str_replace("\t", " ", $message)."\n\n";
}
$c .= "\nURL: ".URLUtils::fullUrl()."\n\n";
if ($this->verbose) {
$debugServerVars = array_intersect_key($_SERVER,array_flip(array(
'SCRIPT_URL',
'SCRIPT_URI',
'ENVIRONMENT',
// 'HTTP_X_FORWARDED_FOR',
// 'HTTP_CLIENT_IP',
// 'HTTP_HOST',
// 'HTTP_REFERER',
// 'HTTP_USER_AGENT',
// 'HTTP_ACCEPT',
// 'HTTP_ACCEPT_LANGUAGE',
// 'HTTP_ACCEPT_ENCODING',
// 'HTTP_COOKIE',
// 'HTTP_CONNECTION',
'PATH',
'SERVER_SIGNATURE',
'SERVER_SOFTWARE',
'SERVER_NAME',
'SERVER_ADDR',
'SERVER_PORT',
'REMOTE_ADDR',
'DOCUMENT_ROOT',
'SERVER_ADMIN',
'SCRIPT_FILENAME',
'REMOTE_PORT',
'GATEWAY_INTERFACE',
'SERVER_PROTOCOL',
'REQUEST_METHOD',
'QUERY_STRING',
'REQUEST_URI',
'SCRIPT_NAME',
'PHP_SELF',
'REQUEST_TIME',
'DEVICE_VIEW',
'DESIGN',
'DOMAIN',
'CONTEXT',
'ROUTER_BASE',
'MATCHED_ALIAS',
'REWRITE_BASE',
'DEPLOYMENT_BASE_PATH',
'SITE',
'SYSTEM_VERSION'
)));
$c .= "SERVER: ".print_r($this->Security->filterLoggedParameters($debugServerVars), true)."\n\n";
$headers = array();
foreach($_SERVER as $name => $value)
if(strpos($name, 'HTTP_') === 0)
$headers[$name] = $value;
if (!empty($headers))
$c .= "HEADERS: ".print_r($this->Security->filterLoggedParameters($headers), true)."\n\n";
if (isset($_FILES))
$c .= "FILES: ".print_r($_FILES, true)."\n\n";
if (isset($_POST))
$c .= "POST: ".print_r($this->Security->filterLoggedParameters($_POST), true)."\n\n";
if (isset($_GET))
$c .= "GET: ".print_r($this->Security->filterLoggedParameters($_GET), true)."\n\n";
if (isset($_SESSION))
$c .= "SESSION: ".print_r($this->Security->filterLoggedParameters($_SESSION), true)."\n\n";
}
if ($message instanceof Exception) {
if (!$subject) { $subject = '%k: %.100m'; }
$subject = preg_replace_callback(
'/%(\.(\d+))?([kmcfl%])/',
function($match) use ($message) {
switch ($match[3]) {
case 'k': $out = get_class($message); break;
case 'm': $out = $message->getMessage(); break;
case 'c': $out = $message->getCode(); break;
case 'f': $out = $message->getFile(); break;
case 'l': $out = $message->getLine(); break;
default: $out = $match[3];
}
if (!empty($match[2])) {
$out = substr($out, 0, $match[2]);
}
return $out;
},
$subject
);
} else {
if (!$subject) {
$subject = substr($message, 0, 100);
}
}
// don't send email about post max or missing boundary errors
// there's nothing we can do code wise to fix those anyways
$isPostContentLengthError = false;
if (false !== strpos($c, 'POST Content-Length of')
|| false !== strpos($c, 'Missing boundary in multipart/form-data')) {
$isPostContentLengthError = true;
$prefix = 'WARN';
}
$context = (isset($_SERVER['CONTEXT']) ? $_SERVER['CONTEXT'] : 'none');
if (array_key_exists('SITE', $_SERVER)) {
$appName = (string) $_SERVER['SITE']['slug'];
if ($appName === $context) {
$appName = $this->SiteService->getAnchoredSite()->Slug;
}
} else {
$appName = $_SERVER['SERVER_NAME'];
}
$deviceView = (isset($_SERVER['DEVICE_VIEW']) ? $_SERVER['DEVICE_VIEW'] : '');
$design = (isset($_SERVER['DESIGN']) ? $_SERVER['DESIGN'] : '');
$viewerCountry = (isset($_SERVER['VIEWER_COUNTRY']) ? $_SERVER['VIEWER_COUNTRY'] : 'US');
if (!empty($deviceView) && !empty($design)) {
$errorPrefix = "[{$this->environment}][$appName][$viewerCountry][$context][$deviceView:$design][$prefix]";
} else {
$errorPrefix = "[{$this->environment}][$appName][$viewerCountry][$context][$prefix]";
}
$subject = "$errorPrefix $subject";
if (!$this->multiline) {
$c = str_replace("\n", "<br/>", $c);
}
// Do standard PHP error logging
error_log("$errorPrefix $c");
// Bail out if we shouldn't be sending emails.
if (!$this->sendEmails
|| empty($this->systemEmailAddress)
|| empty($this->Email)
|| $isPostContentLengthError)
{
return;
}
$recipients = array($this->systemEmailAddress);
if (!empty($extraRecipients)) {
if (!is_array($extraRecipients)) {
$recipients[] = $extraRecipients;
} else {
$recipients = array_merge($recipients, $extraRecipients);
}
}
// emails always need line breaks replaced
if ($this->multiline) {
$c = str_replace("\n", "<br/>", $c);
}
$body = '<p><font face="'courier new', monospace">' . $c . '</font></p>';
$this->Email->clear();
$this->Email->from($this->sendEmailsFrom);
foreach ($recipients as $recipient) {
$this->Email->to($recipient);
}
$this->Email->subject($subject);
$this->Email->body($body);
$this->Email->altMessage($c);
if (is_a($this->Email, 'EmailTagInterface')) {
$this->Email->tag('error');
}
$this->Email->send();
} | php | protected function _sendErrorNotification($prefix, $message, $subject = null, $customMessage = false, $extraRecipients = null)
{
$c = '';
if ($customMessage) {
$c .= $customMessage."\n\n";
}
if ($message instanceof Exception) {
$c .= get_class($message).": ".$message->getMessage()."\n";
if($message instanceof SQLException)
$c .= "SQL: ".$message->getSQL()."\n";
$c .= "Code: ".$message->getCode()."\n";
$c .= "File: ".$message->getFile()."\n";
$c .= "Line: ".$message->getLine()."\n";
$c .= "Stack Trace: ".$message->getTraceAsString()."\n\n";
} else {
$c .= str_replace("\t", " ", $message)."\n\n";
}
$c .= "\nURL: ".URLUtils::fullUrl()."\n\n";
if ($this->verbose) {
$debugServerVars = array_intersect_key($_SERVER,array_flip(array(
'SCRIPT_URL',
'SCRIPT_URI',
'ENVIRONMENT',
// 'HTTP_X_FORWARDED_FOR',
// 'HTTP_CLIENT_IP',
// 'HTTP_HOST',
// 'HTTP_REFERER',
// 'HTTP_USER_AGENT',
// 'HTTP_ACCEPT',
// 'HTTP_ACCEPT_LANGUAGE',
// 'HTTP_ACCEPT_ENCODING',
// 'HTTP_COOKIE',
// 'HTTP_CONNECTION',
'PATH',
'SERVER_SIGNATURE',
'SERVER_SOFTWARE',
'SERVER_NAME',
'SERVER_ADDR',
'SERVER_PORT',
'REMOTE_ADDR',
'DOCUMENT_ROOT',
'SERVER_ADMIN',
'SCRIPT_FILENAME',
'REMOTE_PORT',
'GATEWAY_INTERFACE',
'SERVER_PROTOCOL',
'REQUEST_METHOD',
'QUERY_STRING',
'REQUEST_URI',
'SCRIPT_NAME',
'PHP_SELF',
'REQUEST_TIME',
'DEVICE_VIEW',
'DESIGN',
'DOMAIN',
'CONTEXT',
'ROUTER_BASE',
'MATCHED_ALIAS',
'REWRITE_BASE',
'DEPLOYMENT_BASE_PATH',
'SITE',
'SYSTEM_VERSION'
)));
$c .= "SERVER: ".print_r($this->Security->filterLoggedParameters($debugServerVars), true)."\n\n";
$headers = array();
foreach($_SERVER as $name => $value)
if(strpos($name, 'HTTP_') === 0)
$headers[$name] = $value;
if (!empty($headers))
$c .= "HEADERS: ".print_r($this->Security->filterLoggedParameters($headers), true)."\n\n";
if (isset($_FILES))
$c .= "FILES: ".print_r($_FILES, true)."\n\n";
if (isset($_POST))
$c .= "POST: ".print_r($this->Security->filterLoggedParameters($_POST), true)."\n\n";
if (isset($_GET))
$c .= "GET: ".print_r($this->Security->filterLoggedParameters($_GET), true)."\n\n";
if (isset($_SESSION))
$c .= "SESSION: ".print_r($this->Security->filterLoggedParameters($_SESSION), true)."\n\n";
}
if ($message instanceof Exception) {
if (!$subject) { $subject = '%k: %.100m'; }
$subject = preg_replace_callback(
'/%(\.(\d+))?([kmcfl%])/',
function($match) use ($message) {
switch ($match[3]) {
case 'k': $out = get_class($message); break;
case 'm': $out = $message->getMessage(); break;
case 'c': $out = $message->getCode(); break;
case 'f': $out = $message->getFile(); break;
case 'l': $out = $message->getLine(); break;
default: $out = $match[3];
}
if (!empty($match[2])) {
$out = substr($out, 0, $match[2]);
}
return $out;
},
$subject
);
} else {
if (!$subject) {
$subject = substr($message, 0, 100);
}
}
// don't send email about post max or missing boundary errors
// there's nothing we can do code wise to fix those anyways
$isPostContentLengthError = false;
if (false !== strpos($c, 'POST Content-Length of')
|| false !== strpos($c, 'Missing boundary in multipart/form-data')) {
$isPostContentLengthError = true;
$prefix = 'WARN';
}
$context = (isset($_SERVER['CONTEXT']) ? $_SERVER['CONTEXT'] : 'none');
if (array_key_exists('SITE', $_SERVER)) {
$appName = (string) $_SERVER['SITE']['slug'];
if ($appName === $context) {
$appName = $this->SiteService->getAnchoredSite()->Slug;
}
} else {
$appName = $_SERVER['SERVER_NAME'];
}
$deviceView = (isset($_SERVER['DEVICE_VIEW']) ? $_SERVER['DEVICE_VIEW'] : '');
$design = (isset($_SERVER['DESIGN']) ? $_SERVER['DESIGN'] : '');
$viewerCountry = (isset($_SERVER['VIEWER_COUNTRY']) ? $_SERVER['VIEWER_COUNTRY'] : 'US');
if (!empty($deviceView) && !empty($design)) {
$errorPrefix = "[{$this->environment}][$appName][$viewerCountry][$context][$deviceView:$design][$prefix]";
} else {
$errorPrefix = "[{$this->environment}][$appName][$viewerCountry][$context][$prefix]";
}
$subject = "$errorPrefix $subject";
if (!$this->multiline) {
$c = str_replace("\n", "<br/>", $c);
}
// Do standard PHP error logging
error_log("$errorPrefix $c");
// Bail out if we shouldn't be sending emails.
if (!$this->sendEmails
|| empty($this->systemEmailAddress)
|| empty($this->Email)
|| $isPostContentLengthError)
{
return;
}
$recipients = array($this->systemEmailAddress);
if (!empty($extraRecipients)) {
if (!is_array($extraRecipients)) {
$recipients[] = $extraRecipients;
} else {
$recipients = array_merge($recipients, $extraRecipients);
}
}
// emails always need line breaks replaced
if ($this->multiline) {
$c = str_replace("\n", "<br/>", $c);
}
$body = '<p><font face="'courier new', monospace">' . $c . '</font></p>';
$this->Email->clear();
$this->Email->from($this->sendEmailsFrom);
foreach ($recipients as $recipient) {
$this->Email->to($recipient);
}
$this->Email->subject($subject);
$this->Email->body($body);
$this->Email->altMessage($c);
if (is_a($this->Email, 'EmailTagInterface')) {
$this->Email->tag('error');
}
$this->Email->send();
} | /*
Internal error email method | https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/libraries/errors/ErrorHandler.php#L412-L609 |
irfantoor/engine | src/Http/Stream.php | Stream.seek | public function seek($offset, $whence = SEEK_SET)
{
if ($this->isSeekable()) {
if (fseek($this->stream, $offset, $whence) !== 0) {
throw new Exception('seek failure');
}
return true;
}
return false;
} | php | public function seek($offset, $whence = SEEK_SET)
{
if ($this->isSeekable()) {
if (fseek($this->stream, $offset, $whence) !== 0) {
throw new Exception('seek failure');
}
return true;
}
return false;
} | Seek to a position in the stream.
@link http://www.php.net/manual/en/function.fseek.php
@param int $offset Stream offset
@param int $whence Specifies how the cursor position will be calculated
based on the seek offset. Valid values are identical to the built-in
PHP $whence values for `fseek()`. SEEK_SET: Set position equal to
offset bytes SEEK_CUR: Set position to current location plus offset
SEEK_END: Set position to end-of-stream plus offset.
@throws \RuntimeException on failure. | https://github.com/irfantoor/engine/blob/4d2d221add749f75100d0b4ffe1488cdbf7af5d3/src/Http/Stream.php#L212-L221 |
irfantoor/engine | src/Http/Stream.php | Stream.write | public function write($string)
{
if ($this->isWritable()) {
$size = $this->getSize();
$count = fwrite($this->stream, $string);
$this->setSize($size + $count);
return $count;
} else {
return false;
}
} | php | public function write($string)
{
if ($this->isWritable()) {
$size = $this->getSize();
$count = fwrite($this->stream, $string);
$this->setSize($size + $count);
return $count;
} else {
return false;
}
} | Write data to the stream.
@param string $string The string that is to be written.
@return int Returns the number of bytes written to the stream.
@throws \RuntimeException on failure. | https://github.com/irfantoor/engine/blob/4d2d221add749f75100d0b4ffe1488cdbf7af5d3/src/Http/Stream.php#L262-L272 |
irfantoor/engine | src/Http/Stream.php | Stream.getMetadata | public function getMetadata($key = null)
{
if (!is_resource($this->stream)) {
return null;
}
$fstat = fstat($this->stream);
$fstat = array_merge(array_slice($fstat, 13), $this->metadata);
if ($key) {
return isset($fstat[$key]) ? $fstat[$key] : null;
}
return $fstat;
} | php | public function getMetadata($key = null)
{
if (!is_resource($this->stream)) {
return null;
}
$fstat = fstat($this->stream);
$fstat = array_merge(array_slice($fstat, 13), $this->metadata);
if ($key) {
return isset($fstat[$key]) ? $fstat[$key] : null;
}
return $fstat;
} | Get stream metadata as an associative array or retrieve a specific key.
The keys returned are identical to the keys returned from PHP's
stream_get_meta_data() function.
@link http://php.net/manual/en/function.stream-get-meta-data.php
@param string $key Specific metadata to retrieve.
@return array|mixed|null Returns an associative array if no key is
provided. Returns a specific key value if a key is provided and the
value is found, or null if the key is not found. | https://github.com/irfantoor/engine/blob/4d2d221add749f75100d0b4ffe1488cdbf7af5d3/src/Http/Stream.php#L332-L346 |
lasallecms/lasallecms-l5-lasallecmsapi-pkg | src/Repositories/Traits/Sanitation.php | Sanitation.getSanitize | public function getSanitize($data, $rules)
{
// iterate through each field
foreach ($rules as $field => $rule)
{
// turn the listing of rules with a "|" separator into an array
// yeah, $rule can contain multiple rules (ie, multiple php functions)
$phpFunctions = explode('|', $rule);
// iterate through each rule
foreach($phpFunctions as $phpFunction)
{
$data[$field] = call_user_func_array($phpFunction, [$data[$field] ]);
// debug
//echo "<br>The field ".$field." is now = ".$data[$field]." (".$singleFunction.")";
}
}
return $data;
} | php | public function getSanitize($data, $rules)
{
// iterate through each field
foreach ($rules as $field => $rule)
{
// turn the listing of rules with a "|" separator into an array
// yeah, $rule can contain multiple rules (ie, multiple php functions)
$phpFunctions = explode('|', $rule);
// iterate through each rule
foreach($phpFunctions as $phpFunction)
{
$data[$field] = call_user_func_array($phpFunction, [$data[$field] ]);
// debug
//echo "<br>The field ".$field." is now = ".$data[$field]." (".$singleFunction.")";
}
}
return $data;
} | Sanitize
@param array $data
@param array $rules
@return array | https://github.com/lasallecms/lasallecms-l5-lasallecmsapi-pkg/blob/05083be19645d52be86d8ba4f322773db348a11d/src/Repositories/Traits/Sanitation.php#L104-L124 |
johnkrovitch/Sam | File/Normalizer.php | Normalizer.normalize | public function normalize($source)
{
$fileSystem = new Filesystem();
// if the source is a file info, it must exists and be readable
if ($source instanceof SplFileInfo) {
if (!$fileSystem->exists($source->getRealPath())) {
throw new Exception('Unable to find '.$source.' during normalization process');
}
// the source is already normalized
return $source;
}
// if the source is not an instance of SplInfo, it should be a string
if (!is_string($source)) {
throw new Exception(
'The source should be a string if it is not an instance of SplInfo (instead of '.gettype($source).')'
);
}
$path = $source;
// if the file does not exists, try to add the application path before
if (!$fileSystem->exists($source)) {
if (!$fileSystem->exists($this->applicationPath.'/'.$source)) {
throw new Exception(
'File '.$source.' not found, searched in '
.implode(', ', [$source, $this->applicationPath.'/'.$source])
);
}
$path = $this->applicationPath.'/'.$source;
}
// normalize source using SplInfo
$source = new SplFileInfo($path);
return $source;
} | php | public function normalize($source)
{
$fileSystem = new Filesystem();
// if the source is a file info, it must exists and be readable
if ($source instanceof SplFileInfo) {
if (!$fileSystem->exists($source->getRealPath())) {
throw new Exception('Unable to find '.$source.' during normalization process');
}
// the source is already normalized
return $source;
}
// if the source is not an instance of SplInfo, it should be a string
if (!is_string($source)) {
throw new Exception(
'The source should be a string if it is not an instance of SplInfo (instead of '.gettype($source).')'
);
}
$path = $source;
// if the file does not exists, try to add the application path before
if (!$fileSystem->exists($source)) {
if (!$fileSystem->exists($this->applicationPath.'/'.$source)) {
throw new Exception(
'File '.$source.' not found, searched in '
.implode(', ', [$source, $this->applicationPath.'/'.$source])
);
}
$path = $this->applicationPath.'/'.$source;
}
// normalize source using SplInfo
$source = new SplFileInfo($path);
return $source;
} | Normalize a source (string or SplInfo) into an instance of SplInfo.
@param mixed $source
@return SplFileInfo
@throws Exception | https://github.com/johnkrovitch/Sam/blob/fbd3770c11eecc0a6d8070f439f149062316f606/File/Normalizer.php#L35-L73 |
pluf/geo | src/Geo/Form/Tag.php | Geo_Form_Tag.initFields | public function initFields ($extra = array())
{
if (array_key_exists('tag', $extra)) {
$this->tag = $extra['tag'];
}
$this->tag = Geo_Shortcuts_tagFactory($this->tag);
$this->fields['tag_key'] = new Pluf_Form_Field_Varchar(
array(
'required' => false,
'label' => __('tag key'),
'initial' => $this->tag->tag_key
));
$this->fields['tag_value'] = new Pluf_Form_Field_Varchar(
array(
'required' => false,
'label' => __('tag value'),
'initial' => $this->tag->tag_value
));
$this->fields['description'] = new Pluf_Form_Field_Varchar(
array(
'required' => false,
'label' => __('location description'),
'initial' => $this->tag->description
));
} | php | public function initFields ($extra = array())
{
if (array_key_exists('tag', $extra)) {
$this->tag = $extra['tag'];
}
$this->tag = Geo_Shortcuts_tagFactory($this->tag);
$this->fields['tag_key'] = new Pluf_Form_Field_Varchar(
array(
'required' => false,
'label' => __('tag key'),
'initial' => $this->tag->tag_key
));
$this->fields['tag_value'] = new Pluf_Form_Field_Varchar(
array(
'required' => false,
'label' => __('tag value'),
'initial' => $this->tag->tag_value
));
$this->fields['description'] = new Pluf_Form_Field_Varchar(
array(
'required' => false,
'label' => __('location description'),
'initial' => $this->tag->description
));
} | مقدار دهی فیلدها.
@see Pluf_Form::initFields() | https://github.com/pluf/geo/blob/53413e06627d12ab0e4239eeb72a7a146c4fb820/src/Geo/Form/Tag.php#L20-L46 |
pluf/geo | src/Geo/Form/Tag.php | Geo_Form_Tag.save | function save ($commit = true)
{
if (! $this->isValid()) {
throw new Pluf_Exception(
__('cannot save the tag from an invalid form'));
}
// Set attributes
$this->tag->setFromFormData($this->cleaned_data);
if ($commit) {
if (! $this->tag->create()) {
throw new Pluf_Exception(__('fail to create the tag'));
}
}
return $this->tag;
} | php | function save ($commit = true)
{
if (! $this->isValid()) {
throw new Pluf_Exception(
__('cannot save the tag from an invalid form'));
}
// Set attributes
$this->tag->setFromFormData($this->cleaned_data);
if ($commit) {
if (! $this->tag->create()) {
throw new Pluf_Exception(__('fail to create the tag'));
}
}
return $this->tag;
} | دادههای مکان را ایجاد میکند.
از این فراخوانی برای ایجاد یک مکان جدید باید استفاده شود.
@param string $commit
@throws Pluf_Exception | https://github.com/pluf/geo/blob/53413e06627d12ab0e4239eeb72a7a146c4fb820/src/Geo/Form/Tag.php#L56-L70 |
pluf/geo | src/Geo/Form/Tag.php | Geo_Form_Tag.update | function update ($commit = true)
{
if (! $this->isValid()) {
throw new Pluf_Exception(
__('cannot save the tag from an invalid form'));
}
// Set attributes
$this->tag->setFromFormData($this->cleaned_data);
if ($commit) {
if (! $this->tag->update()) {
throw new Pluf_Exception(
sprintf(__('fail to update the tag %s'),
$this->tag->tag_key.":".$this->tag->tag_value));
}
}
return $this->tag;
} | php | function update ($commit = true)
{
if (! $this->isValid()) {
throw new Pluf_Exception(
__('cannot save the tag from an invalid form'));
}
// Set attributes
$this->tag->setFromFormData($this->cleaned_data);
if ($commit) {
if (! $this->tag->update()) {
throw new Pluf_Exception(
sprintf(__('fail to update the tag %s'),
$this->tag->tag_key.":".$this->tag->tag_value));
}
}
return $this->tag;
} | دادههای یک مکان را به روز می کند.
از این فراخوانی تنها برای به روز کردن دادهها باید استفاده شود.
@param string $commit
@throws Pluf_Exception | https://github.com/pluf/geo/blob/53413e06627d12ab0e4239eeb72a7a146c4fb820/src/Geo/Form/Tag.php#L80-L96 |
translationexchange/tml-php-clientsdk | library/Tr8n/Utils/BrowserUtils.php | BrowserUtils.matchLanguage | public static function matchLanguage($a, $b) {
$a = explode('-', $a);
$b = explode('-', $b);
for ($i=0, $n=min(count($a), count($b)); $i<$n; $i++) {
if ($a[$i] !== $b[$i]) break;
}
return $i === 0 ? 0 : (float) $i / count($a);
} | php | public static function matchLanguage($a, $b) {
$a = explode('-', $a);
$b = explode('-', $b);
for ($i=0, $n=min(count($a), count($b)); $i<$n; $i++) {
if ($a[$i] !== $b[$i]) break;
}
return $i === 0 ? 0 : (float) $i / count($a);
} | compare two language tags and distinguish the degree of matching | https://github.com/translationexchange/tml-php-clientsdk/blob/fe51473824e62cfd883c6aa0c6a3783a16ce8425/library/Tr8n/Utils/BrowserUtils.php#L69-L76 |
Polosa/shade-framework-core | app/Response.php | Response.output | public function output()
{
foreach ($this->headers as $header) {
header($header, false);
}
if ($this->code) {
http_response_code($this->code);
}
echo $this->content;
} | php | public function output()
{
foreach ($this->headers as $header) {
header($header, false);
}
if ($this->code) {
http_response_code($this->code);
}
echo $this->content;
} | Output response | https://github.com/Polosa/shade-framework-core/blob/d735d3e8e0616fb9cf4ffc25b8425762ed07940f/app/Response.php#L44-L53 |
ekyna/MediaBundle | DependencyInjection/AsseticConfiguration.php | AsseticConfiguration.build | public function build($outputDir)
{
// Fix output dir trailing slash
if (strlen($outputDir) > 0 && '/' !== substr($outputDir, -1)) {
$outputDir .= '/';
}
$output['fancytree_css'] = $this->buildFancyTreeCss($outputDir);
$output['fancytree_js'] = $this->buildFancyTreeJs($outputDir);
$output['media_thumb_js'] = $this->buildMediaThumbJs($outputDir);
return $output;
} | php | public function build($outputDir)
{
// Fix output dir trailing slash
if (strlen($outputDir) > 0 && '/' !== substr($outputDir, -1)) {
$outputDir .= '/';
}
$output['fancytree_css'] = $this->buildFancyTreeCss($outputDir);
$output['fancytree_js'] = $this->buildFancyTreeJs($outputDir);
$output['media_thumb_js'] = $this->buildMediaThumbJs($outputDir);
return $output;
} | Builds the assetic configuration.
@param string $outputDir
@return array | https://github.com/ekyna/MediaBundle/blob/512cf86c801a130a9f17eba8b48d646d23acdbab/DependencyInjection/AsseticConfiguration.php#L18-L30 |
Beotie/Beotie-PSR7-stream | src/Stream/Factory/FileInfoStreamFactory.php | FileInfoStreamFactory.getStream | public function getStream(array $params = []) : StreamInterface
{
$this->paramHasContent($params);
$this->contentIsFileInfo($params[self::ARRAY_KEY]);
$openMode = 'r';
if (!empty($params[self::OPEN_MODE])) {
$openMode = $params[self::OPEN_MODE];
}
return new FileInfoStreamAdapter($params[self::ARRAY_KEY], $openMode);
} | php | public function getStream(array $params = []) : StreamInterface
{
$this->paramHasContent($params);
$this->contentIsFileInfo($params[self::ARRAY_KEY]);
$openMode = 'r';
if (!empty($params[self::OPEN_MODE])) {
$openMode = $params[self::OPEN_MODE];
}
return new FileInfoStreamAdapter($params[self::ARRAY_KEY], $openMode);
} | Get stream
This method return a stream instance. The optional params parameter can be used to provide constructor or
setter arguments during the instanciation.
@param array $params [required] the instanciation parameters
@throws \RuntimeException If the given parameters does not have a 'inner_content' key
@throws \RuntimeException If the given content does not match the expected SplFileInfo type
@return StreamInterface | https://github.com/Beotie/Beotie-PSR7-stream/blob/8f4f4bfb8252e392fc17eed2a2b0682c4e9d08ca/src/Stream/Factory/FileInfoStreamFactory.php#L68-L79 |
Beotie/Beotie-PSR7-stream | src/Stream/Factory/FileInfoStreamFactory.php | FileInfoStreamFactory.paramHasContent | protected function paramHasContent(array $params, string $method = 'getStream') : bool
{
if (!array_key_exists(self::ARRAY_KEY, $params)) {
throw new \RuntimeException(
sprintf(
'The "%s::%s" expect a file array key to build an instance of FileInfoStreamAdapter',
static::class,
$method
)
);
}
return true;
} | php | protected function paramHasContent(array $params, string $method = 'getStream') : bool
{
if (!array_key_exists(self::ARRAY_KEY, $params)) {
throw new \RuntimeException(
sprintf(
'The "%s::%s" expect a file array key to build an instance of FileInfoStreamAdapter',
static::class,
$method
)
);
}
return true;
} | Param has content
This method aim to validate the existance of a 'inner_content' key into the parameters array.
@param array $params The original method parameters validated by the function
@param string $method The original method name. This parameter is used to build the exception message
@throws \RuntimeException If the given parameters does not have a 'inner_content' key
@return bool | https://github.com/Beotie/Beotie-PSR7-stream/blob/8f4f4bfb8252e392fc17eed2a2b0682c4e9d08ca/src/Stream/Factory/FileInfoStreamFactory.php#L92-L105 |
Beotie/Beotie-PSR7-stream | src/Stream/Factory/FileInfoStreamFactory.php | FileInfoStreamFactory.contentIsFileInfo | protected function contentIsFileInfo($file, string $method = 'getStream') : bool
{
if (! $file instanceof \SplFileInfo) {
$message = 'The "%s::%s" expect the file array key to be an instance of "%s". "%s" given';
$givenType = (is_object($file) ? get_class($file) : gettype($file));
throw new \RuntimeException(sprintf($message, static::class, $method, \SplFileInfo::class, $givenType));
}
return true;
} | php | protected function contentIsFileInfo($file, string $method = 'getStream') : bool
{
if (! $file instanceof \SplFileInfo) {
$message = 'The "%s::%s" expect the file array key to be an instance of "%s". "%s" given';
$givenType = (is_object($file) ? get_class($file) : gettype($file));
throw new \RuntimeException(sprintf($message, static::class, $method, \SplFileInfo::class, $givenType));
}
return true;
} | Content is FileInfo
This method validate the instance of the given content parameter. This type is expected to be SplFileInfo.
@param mixed $file The file which the method aim to validate the type
@param string $method The original method name. This parameter is used to define the exception message
@throws \RuntimeException If the given content does not match the expected type
@return bool | https://github.com/Beotie/Beotie-PSR7-stream/blob/8f4f4bfb8252e392fc17eed2a2b0682c4e9d08ca/src/Stream/Factory/FileInfoStreamFactory.php#L118-L128 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.