_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q251800 | I18nPlugin.setupTranslateLog | validation | private function setupTranslateLog()
{
$logger = Logger::getLogger('Wedeto.I18n.Translator.Translator');
$writer = new TranslationLogger($this->app->pathConfig->log . '/translate-%s-%s.pot');
$logger->addLogWriter($writer);
} | php | {
"resource": ""
} |
q251801 | Router.init | validation | public function init( array $config = [ ] )
{
foreach ( $config as $key => $value )
{
switch ( $key )
{
case 'default_controller':
$this->defaultController = $value;
break;
case 'default_action':
$this->defaultAction = $value;
break;
case 'namespaces':
$this->namespaces = $value;
break;
default:
// do nothing
break;
}
}
} | php | {
"resource": ""
} |
q251802 | Router.createController | validation | public function createController( $route, $params )
{
$control = NULL;
$route = ltrim( $route, '/' );
$route = rtrim( $route, '/' );
$vars = explode( '/', $route );
if ( 1 === count( $vars ) && '' == $vars[ 0 ] )
{
$control = $this->_buildControllerName( $this->defaultController . 'Controller' );
// build action
$aName = $this->_buildActionName( $control, $this->defaultAction );
}
else if ( 1 === count( $vars ) )
{
// controller /
$control = $this->_buildControllerName( $vars[ 0 ] . 'Controller' );
array_shift( $vars );
// build action
$aName = $this->_buildActionName( $control, $this->defaultAction );
}
else if ( 2 === count( $vars ) )
{
// controller / action
$control = $this->_buildControllerName( $vars[ 0 ] . 'Controller' );
array_shift( $vars );
// build action
$aName = $this->_buildActionName( $control, $vars[ 0 ] );
}
else if ( 2 < count( $vars ) )
{
// controller / action / params
$control = $this->_buildControllerName( $vars[ 0 ] . 'Controller' );
array_shift( $vars );
// build action
$aName = $this->_buildActionName( $control, $vars[ 0 ] );
array_shift( $vars );
}
else
{
$control = $this->_buildControllerName( $this->defaultController . 'Controller' );
$aName = $this->defaultAction . 'Action';
}
$action = new Action( $aName, $params );
/** @var IController $controller */
$controller = new $control( $this->config );
$controller->setAction( $action );
$controller->setDispatcher( $this->dispatcher );
$controller->addDefaultListeners();
return $controller;
} | php | {
"resource": ""
} |
q251803 | Router._buildControllerName | validation | private function _buildControllerName( $name )
{
$name = strtoupper( $name[ 0 ] ) . substr( $name, 1 );
$controller = $name;
$namespace = NULL;
foreach ( $this->namespaces as $ns )
{
if ( class_exists( $ns . $controller ) )
{
$namespace = $ns;
$controller = $ns . $controller;
break;
}
}
if ( NULL === $namespace )
{
return strtoupper( $this->defaultController[ 0 ] )
. substr( $this->defaultController, 1 ) . 'Controller';
}
else
{
return $controller;
}
} | php | {
"resource": ""
} |
q251804 | Router._buildActionName | validation | private function _buildActionName( $controllerName, $actionName )
{
$actionName = $actionName . 'Action';
if ( !method_exists( $controllerName, $actionName ) )
{
$actionName = $this->defaultAction . 'Action';
}
return $actionName;
} | php | {
"resource": ""
} |
q251805 | FileId.variant | validation | public function variant(array $attrs)
{
return new self($this->id, $attrs, null, $this->info->all());
} | php | {
"resource": ""
} |
q251806 | JsonResponseFormatter.formatJson | validation | protected function formatJson($response)
{
$response->getHeaders()->set('Content-Type', 'application/json; charset=UTF-8');
if ($response->data !== null) {
$options = $this->encodeOptions;
if ($this->prettyPrint) {
$options |= JSON_PRETTY_PRINT;
}
$response->content = Json::encode($response->data, $options);
}
} | php | {
"resource": ""
} |
q251807 | JsonResponseFormatter.formatJsonp | validation | protected function formatJsonp($response)
{
$response->getHeaders()->set('Content-Type', 'application/javascript; charset=UTF-8');
if (is_array($response->data) && isset($response->data['data'], $response->data['callback'])) {
$response->content = sprintf('%s(%s);', $response->data['callback'], Json::htmlEncode($response->data['data']));
} elseif ($response->data !== null) {
$response->content = '';
Yii::warning("The 'jsonp' response requires that the data be an array consisting of both 'data' and 'callback' elements.", __METHOD__);
}
} | php | {
"resource": ""
} |
q251808 | MediaController.newAction | validation | public function newAction()
{
$entity = new Media();
$form = $this->createCreateForm($entity);
return $this->render('MMMediaBundle:Media:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
} | php | {
"resource": ""
} |
q251809 | PaginationFactory.create | validation | public function create(\Psr\Http\Message\ServerRequestInterface $request, string $sortParameter = self::SORT, array $defaultSort = []): Pagination
{
$offset = 0;
$max = PHP_INT_MAX;
$params = $request->getQueryParams();
$range = $request->getHeaderLine(self::RANGE);
if ($range !== null && preg_match(self::REGEX_RANGE, $range, $rm)) {
// dojo.store.JsonRest style
$offset = (int)$rm[1];
$max = (int)$rm[2] - $offset + 1;
} else {
$max = $this->parse(self::$maxAlias, $params, PHP_INT_MAX);
// Grails, ExtJS, dojox.data.QueryReadStore, all zero-based
$offVal = $this->parse(self::$offsetAlias, $params, 0);
if ($offVal > 0) {
$offset = $offVal;
} elseif (isset($params[self::START_INDEX])) {
// OpenSearch style, 1-based
$startIdx = isset($params[self::START_INDEX]) ? (int)$params[self::START_INDEX] : 0;
if ($startIdx > 0) {
$offset = $startIdx - 1;
}
} elseif (isset($params[self::START_PAGE]) || isset($params[self::PAGE])) {
// OpenSearch or Spring Data style, 1-based
$startPage = $this->parse(self::$pageAlias, $params, 0);
if ($startPage > 0) {
$offset = ($max * ($startPage - 1));
}
}
}
return new Pagination($max, $offset, $this->getOrder($request, $sortParameter, $defaultSort));
} | php | {
"resource": ""
} |
q251810 | PaginationFactory.getOrder | validation | protected function getOrder(\Psr\Http\Message\ServerRequestInterface $request, string $sortParameter, array $default = []): array
{
$order = [];
$params = $request->getQueryParams();
if (isset($params[$sortParameter])) {
if (isset($params[self::ORDER])) {
// stupid Grails ordering
$order[$params[$sortParameter]] = strcasecmp(self::DESC, $params[self::ORDER]) !== 0;
} else {
$param = $params[$sortParameter];
foreach ((is_array($param) ? $param : [$param]) as $s) {
$this->parseSort($s, $order);
}
}
} else {
foreach (preg_grep(self::REGEX_DOJO_SORT, array_keys($params)) as $s) {
// sort(+foo,-bar)
$this->parseSort(substr($s, 5, -1), $order);
}
}
return empty($order) ? $default : $order;
} | php | {
"resource": ""
} |
q251811 | PaginationFactory.parseSort | validation | protected function parseSort(string $sort, array &$sorts)
{
if (strlen(trim($sort)) === 0) {
return;
}
if (substr($sort, 0, 1) == "[") {
// it might be the ridiculous JSON ExtJS sort format
$json = json_decode($sort);
if (is_array($json)) {
foreach ($json as $s) {
if (is_object($s)) {
$sorts[$s->property] = strcasecmp(self::DESC, $s->direction) !== 0;
}
}
return;
}
}
if (substr($sort, -4) == ",asc") {
// foo,asc
$sorts[substr($sort, 0, strlen($sort) - 4)] = true;
} elseif (substr($sort, -5) == ",desc") {
// foo,desc
$sorts[substr($sort, 0, strlen($sort) - 5)] = false;
} elseif (substr($sort, -10) == ":ascending") {
// foo:ascending
$sorts[substr($sort, 0, strlen($sort) - 10)] = true;
} elseif (substr($sort, -11) == ":descending") {
// foo:descending
$sorts[substr($sort, 0, strlen($sort) - 11)] = false;
} else {
foreach (explode(',', $sort) as $s) {
if (substr($s, 0, 1) === '-') {
// -foo
$sorts[substr($s, 1)] = false;
} elseif (substr($s, 0, 1) === '+') {
// +foo
$sorts[substr($s, 1)] = true;
} else {
// foo
$sorts[$s] = true;
}
}
}
} | php | {
"resource": ""
} |
q251812 | HttpCache.validateCache | validation | protected function validateCache($lastModified, $etag)
{
if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
// HTTP_IF_NONE_MATCH takes precedence over HTTP_IF_MODIFIED_SINCE
// http://tools.ietf.org/html/rfc7232#section-3.3
return $etag !== null && in_array($etag, Yii::$app->request->getEtags(), true);
} elseif (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
return $lastModified !== null && @strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModified;
} else {
return $etag === null && $lastModified === null;
}
} | php | {
"resource": ""
} |
q251813 | HttpCache.sendCacheControlHeader | validation | protected function sendCacheControlHeader()
{
if ($this->sessionCacheLimiter !== null) {
if ($this->sessionCacheLimiter === '' && !headers_sent() && Yii::$app->getSession()->getIsActive()) {
header_remove('Expires');
header_remove('Cache-Control');
header_remove('Last-Modified');
header_remove('Pragma');
}
session_cache_limiter($this->sessionCacheLimiter);
}
$headers = Yii::$app->getResponse()->getHeaders();
$headers->set('Pragma');
if ($this->cacheControlHeader !== null) {
$headers->set('Cache-Control', $this->cacheControlHeader);
}
} | php | {
"resource": ""
} |
q251814 | Session.registerSessionHandler | validation | protected function registerSessionHandler()
{
if ($this->handler !== null) {
if (!is_object($this->handler)) {
$this->handler = Yii::createObject($this->handler);
}
if (!$this->handler instanceof \SessionHandlerInterface) {
throw new InvalidConfigException('"' . get_class($this) . '::handler" must implement the SessionHandlerInterface.');
}
@session_set_save_handler($this->handler, false);
} elseif ($this->getUseCustomStorage()) {
@session_set_save_handler(
[$this, 'openSession'],
[$this, 'closeSession'],
[$this, 'readSession'],
[$this, 'writeSession'],
[$this, 'destroySession'],
[$this, 'gcSession']
);
}
} | php | {
"resource": ""
} |
q251815 | Session.remove | validation | public function remove($key)
{
$this->open();
if (isset($_SESSION[$key])) {
$value = $_SESSION[$key];
unset($_SESSION[$key]);
return $value;
} else {
return null;
}
} | php | {
"resource": ""
} |
q251816 | Style.apply | validation | public static function apply($text, $foreground = '', $background = '')
{
try {
$style = new OutputFormatterStyle();
if ($foreground != '') {
$style->setForeground($foreground);
}
if ($background != '') {
$style->setBackground($background);
}
return $style->apply($text);
} catch (\Exception $e) {
return $text;
}
} | php | {
"resource": ""
} |
q251817 | Style.applyStyle | validation | public static function applyStyle($text, $style)
{
$foreground = self::getForeground($style);
$background = self::getBackground($style);
return self::apply($text, $foreground, $background);
} | php | {
"resource": ""
} |
q251818 | Style.get | validation | private static function get($style, $setting, $defaultValue = '')
{
if (isset(self::$styles[$style])) {
$style = self::$styles[$style];
if (isset($style[$setting])) {
return $style[$setting];
}
}
return $defaultValue;
} | php | {
"resource": ""
} |
q251819 | ResourceAPIResponseDataFactory.multipleToAPIResponseData | validation | public function multipleToAPIResponseData(?array $resources): APIResponseData
{
if(is_null($resources)) {
return $this->toAPIResponseData(null);
}
return new APIResponseData(array_map(function(Resource $resource) {
return $this->toAPIResponseData($resource)->getData();
}, $resources));
} | php | {
"resource": ""
} |
q251820 | GoogleAuthenticator.codesEqual | validation | private function codesEqual(string $known, string $given): bool
{
if (strlen($given) !== strlen($known)) {
return false;
}
$res = 0;
$knownLen = strlen($known);
for ($i = 0; $i < $knownLen; ++$i) {
$res |= (ord($known[$i]) ^ ord($given[$i]));
}
return $res === 0;
} | php | {
"resource": ""
} |
q251821 | CreateDataStoreCapableTrait._createDataStore | validation | protected function _createDataStore($data = null)
{
// Default
if (is_null($data)) {
$data = [];
}
try {
// Constructor already throws in PHP 5+, but doesn't supply the value.
return new ArrayObject($data);
} catch (InvalidArgumentException $e) {
throw $this->_createInvalidArgumentException(
$this->__('Invalid type of store data'),
null,
$e,
$data
);
}
} | php | {
"resource": ""
} |
q251822 | HTTPServer.handleRequest | validation | public function handleRequest(ServerRequestInterface $serverRequest, ResponseInterface $response): ResponseInterface
{
$response = $response->withProtocolVersion($serverRequest->getProtocolVersion());
try {
try {
$APIRequest = $this->requestFactory->create($serverRequest);
} catch (UnableToCreateRequestException $exception) {
return $this->handleRequestFactoryException($exception, $response);
}
try {
$APIResponse = $this->server->handleRequest($APIRequest);
} catch (UnableToHandleRequestException $exception) {
return $this->handleServerException($exception, $response);
}
return $this->buildResponse($APIResponse, $response);
} catch (\Throwable $e) {
$this->logCaughtThrowableResultingInHTTPCode(500, $e, LogLevel::CRITICAL);
return $response->withStatus(500, "Internal Server Error");
}
} | php | {
"resource": ""
} |
q251823 | HTTPServer.buildResponse | validation | protected function buildResponse(APIResponse $APIResponse, ResponseInterface $response): ResponseInterface
{
$response = $response->withStatus(200, "200 OK");
$response = $response->withAddedHeader("Content-Type", $APIResponse->getMIMEType());
$response = $response->withAddedHeader("Content-Length", $APIResponse->getAsDataStream()->getSize());
$this->logger->debug("Responding to request successfully");
return $response->withBody($APIResponse->getAsDataStream());
} | php | {
"resource": ""
} |
q251824 | HTTPServer.dumpResponse | validation | public static function dumpResponse(ResponseInterface $response)
{
$statusLine = sprintf(
"HTTP/%s %d %s",
$response->getProtocolVersion(),
$response->getStatusCode(),
$response->getReasonPhrase()
);
header($statusLine, true, $response->getStatusCode());
foreach ($response->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
$body = $response->getBody();
while(!$body->eof()) {
echo $body->read(1024);
}
} | php | {
"resource": ""
} |
q251825 | Temp.createDir | validation | public static function createDir(
string $prefix = "tmp",
int $mode = 0777,
int $maxAttempts = 10
): entity\DirEntity
{
$tmpdir = static::getDir();
$prefix = \sndsgd\Fs::sanitizeName($prefix);
$attempts = 0;
do {
$attempts++;
if ($attempts > $maxAttempts) {
throw new \RuntimeException(
"failed to create temp directory; ".
"reached max number ($maxAttempts) of attempts"
);
}
$rand = \sndsgd\Str::random(10);
$path = "$tmpdir/$prefix-$rand";
}
while (@mkdir($path, $mode) === false);
$dir = new entity\DirEntity($path);
static::registerEntity($dir);
return $dir;
} | php | {
"resource": ""
} |
q251826 | Temp.createFile | validation | public static function createFile(
string $name,
int $maxAttempts = 10
): entity\FileEntity
{
$tmpdir = static::getDir();
$name = \sndsgd\Fs::sanitizeName($name);
$pos = strrpos($name, ".");
if ($pos === false) {
$extension = "";
} else {
$extension = substr($name, $pos);
$name = substr($name, 0, $pos);
}
$attempts = 1;
do {
if ($attempts > $maxAttempts) {
throw new \RuntimeException(
"failed to create temp file; ".
"reached max number ($maxAttempts) of attempts"
);
}
$rand = \sndsgd\Str::random(10);
$path = "$tmpdir/$name-$rand$extension";
$attempts++;
}
while (file_exists($path));
touch($path);
$file = new entity\FileEntity($path);
static::registerEntity($file);
return $file;
} | php | {
"resource": ""
} |
q251827 | Temp.registerEntity | validation | protected static function registerEntity(entity\EntityInterface $entity)
{
if (count(self::$entities) === 0) {
register_shutdown_function("sndsgd\\fs\\Temp::cleanup");
}
self::$entities[$entity->getPath()] = $entity;
} | php | {
"resource": ""
} |
q251828 | Temp.cleanup | validation | public static function cleanup(): bool
{
$ret = true;
foreach (self::$entities as $path => $entity) {
if (!$entity->remove()) {
$ret = false;
}
}
self::$entities = [];
return $ret;
} | php | {
"resource": ""
} |
q251829 | PaypalBridge.buildChargeFromTransaction | validation | public function buildChargeFromTransaction( $sTxnID ) {
$oCharge = new Freeagent\DataWrapper\ChargeVO();
try {
$oDets = $this->getTxnChargeDetails( $sTxnID );
$oCharge->setId( $sTxnID )
->setGateway( 'paypalexpress' )
->setPaymentTerms( 1 )
->setAmount_Gross( $oDets->GrossAmount->value )
->setAmount_Fee( $oDets->FeeAmount->value )
->setAmount_Net( $oDets->GrossAmount->value - $oDets->FeeAmount->value )
->setDate( strtotime( $oDets->PaymentDate ) )
->setCurrency( $oDets->GrossAmount->currencyID );
}
catch ( \Exception $oE ) {
}
return $oCharge;
} | php | {
"resource": ""
} |
q251830 | PaypalBridge.buildPayoutFromId | validation | public function buildPayoutFromId( $sPayoutId ) {
$oPayout = new Freeagent\DataWrapper\PayoutVO();
$oPayout->setId( $sPayoutId );
try {
$oDets = $this->getTxnChargeDetails( $sPayoutId );
$oPayout->setDateArrival( strtotime( $oDets->PaymentDate ) )
->setCurrency( $oDets->GrossAmount->currencyID );
$oPayout->addCharge(
$this->buildChargeFromTransaction( $sPayoutId )
);
}
catch ( \Exception $oE ) {
}
return $oPayout;
} | php | {
"resource": ""
} |
q251831 | CommonUtil.isTypeOf | validation | public static function isTypeOf(FormInterface $form, $typeName)
{
$typeNames = (array) $typeName;
$type = $form->getConfig()->getType();
while ($type) {
$actualTypeName = $type->getName();
if (in_array($actualTypeName, $typeNames, true)) {
return true;
}
$type = $type->getParent();
}
return false;
} | php | {
"resource": ""
} |
q251832 | ProductManager.findProduct | validation | protected function findProduct(int $id) : ProductInterface
{
$product = $this->repository->find($id);
if (!$product instanceof ProductInterface) {
throw new ProductNotFoundException($id);
}
return $product;
} | php | {
"resource": ""
} |
q251833 | Node.display | validation | public function display($level = 0)
{
$value = $this->getContent();
if (null === $value) {
$value = 'null';
} elseif (is_object($value)) {
$value = get_class($value);
} elseif (is_array($value)) {
$value = 'Array';
}
$ret = str_repeat(' ', $level * 4) . $value . "\n";
$children = $this->getChildren();
foreach ($children as $child) {
$ret .= $child->display($level + 1);
}
return $ret;
} | php | {
"resource": ""
} |
q251834 | LogEntry.toArray | validation | public function toArray()
{
return [
'level' => $this->level,
'datetime' => $this->datetime->format('Y-m-d H:i:s'),
'header' => $this->header,
'stack' => $this->stack,
];
} | php | {
"resource": ""
} |
q251835 | RoutingPanel.getViewData | validation | public function getViewData () {
if ($this->view !== NULL) return $this->view;
$this->view = new \stdClass;
try {
// complete basic \MvcCore core objects to complete other view data
$this->initMainApplicationProperties();
// those cases are only when request is redirected very soon
if ($this->router === NULL) return $this->view;
// complete panel title
$this->initViewPanelTitle();
// complete routes table items
$this->initViewPanelTableData();
// complete requested URL data under routes table
$this->initViewPanelRequestedUrlData();
} catch (\Exception $e) {
$this->_debug($e);
$this->_debug($e->getTrace());
}
// debug code
$this->view->_debugCode = $this->_debugCode;
return $this->view;
} | php | {
"resource": ""
} |
q251836 | RoutingPanel.initViewPanelTableData | validation | protected function initViewPanelTableData () {
$items = [];
$currentRouteName = $this->currentRoute ? $this->currentRoute->GetName() : NULL;
/** @var $route \MvcCore\IRoute */
foreach ($this->routes as & $route) {
$matched = FALSE;
if ($currentRouteName !== NULL && $route->GetName() === $currentRouteName) {
$matched = TRUE;
}
$items[] = $this->initViewPanelTableRow($route, $matched);
}
$this->view->items = $items;
} | php | {
"resource": ""
} |
q251837 | RoutingPanel.initViewPanelTableRow | validation | protected function initViewPanelTableRow (\MvcCore\IRoute & $route, $matched) {
$route->InitAll();
$row = new \stdClass;
// first column
$row->matched = $matched;
// second column
$row->method = $route->GetMethod();
$row->method = $row->method === NULL ? '*' : $row->method;
// third column
$row->className = htmlSpecialChars('\\'.get_class($route), ENT_QUOTES, 'UTF-8');
$routeMatch = $this->getRouteLocalizedRecord($route, 'GetMatch');
$routeMatch = rtrim($routeMatch, 'imsxeADSUXJu'); // remove all modifiers
$routeReverse = $this->getRouteLocalizedRecord($route, 'GetReverse');
$routeDefaults = $this->getRouteLocalizedRecord($route, 'GetDefaults');
$row->match = $this->completeFormatedPatternCharGroups($routeMatch, ['(', ')']);
if ($routeReverse !== NULL) {
$row->reverse = $this->completeFormatedPatternCharGroups($routeReverse, ['<', '>']);
} else {
$row->reverse = NULL;
}
// fourth column
$row->routeName = $route->GetName();
$row->ctrlActionName = $route->GetControllerAction();
if ($row->ctrlActionName !== ':') {
$row->ctrlActionLink = $this->completeCtrlActionLink($route->GetController(), $route->GetAction());
} else {
$row->ctrlActionName = NULL;
$row->ctrlActionLink = NULL;
}
$routeReverseParams = $route->GetReverseParams() ?: []; // route could NULL reverse params when redirect route defined
$paramsKeys = array_unique(array_merge($routeReverseParams, array_keys($routeDefaults)));
$row->defaults = $this->completeParams($route, $paramsKeys, TRUE);
// fifth column (only for matched route)
$row->params = [];
if ($matched) {
$paramsAndReqestParams = array_merge($routeDefaults, $this->requestParams);
$row->params = $this->completeParams($route, array_keys($paramsAndReqestParams), FALSE);
}
return $row;
} | php | {
"resource": ""
} |
q251838 | RoutingPanel.getRouteLocalizedRecord | validation | protected function getRouteLocalizedRecord (\MvcCore\IRoute & $route, $getter) {
$result = $route->$getter($this->requestLang);
if ($result === NULL && $this->defaultLang !== NULL)
$result = $route->$getter($this->defaultLang);
return $result;
} | php | {
"resource": ""
} |
q251839 | RoutingPanel.initViewPanelRequestedUrlData | validation | protected function initViewPanelRequestedUrlData () {
$req = & $this->request;
$this->view->requestedUrl = (object) [
'method' => htmlSpecialChars($req->GetMethod(), ENT_IGNORE, 'UTF-8'),
'baseUrl' => htmlSpecialChars($req->GetBaseUrl(), ENT_IGNORE, 'UTF-8'),
'path' => htmlSpecialChars($req->GetRequestPath(), ENT_IGNORE, 'UTF-8'),
];
} | php | {
"resource": ""
} |
q251840 | RoutingPanel._debug | validation | private function _debug ($var) {
$this->_debugCode .= \Tracy\Dumper::toHtml($var, [
\Tracy\Dumper::LIVE => TRUE
]);
} | php | {
"resource": ""
} |
q251841 | UrlBuilder.returnUrl | validation | public function returnUrl()
{
$return = '';
$return .= empty($this->_urlParts['scheme']) ? '' : $this->_urlParts['scheme'] . '://';
$return .= empty($this->_urlParts['user']) ? '' : $this->_urlParts['user'];
$return .= empty($this->_urlParts['pass']) || empty($this->_urlParts['user']) ? '' : ':' . $this->_urlParts['pass'];
$return .= empty($this->_urlParts['user']) ? '' : '@';
$return .= empty($this->_urlParts['host']) ? '' : $this->_urlParts['host'];
$return .= empty($this->_urlParts['port']) ? '' : ':' . $this->_urlParts['port'];
$return .= empty($this->_urlParts['path']) ? '' : '/' . ltrim($this->_urlParts['path'], '/');
$return .= empty($this->_urlParts['query']) ? '' : '?' . $this->_urlParts['query'];
$return .= empty($this->_urlParts['fragment']) ? '' : '#' . $this->_urlParts['fragment'];
return $return;
} | php | {
"resource": ""
} |
q251842 | UrlBuilder.editQuery | validation | public function editQuery($name, $value)
{
$parts = explode('&', $this->_urlParts['query']);
$return = [];
foreach ($parts as $p) {
$paramData = explode('=', $p);
if ($paramData[0] === $name) {
$paramData[1] = $value;
}
$return[] = implode('=', $paramData);
}
$this->_urlParts['query'] = implode('&', $return);
return $this;
} | php | {
"resource": ""
} |
q251843 | UrlBuilder.addQuery | validation | public function addQuery($name, $value)
{
$part = $name . '=' . $value;
$this->_urlParts['query'] .= empty($this->_urlParts['query']) ? $part : '&' . $part;
return $this;
} | php | {
"resource": ""
} |
q251844 | UrlBuilder.checkQuery | validation | public function checkQuery($name)
{
$parts = explode('&', $this->_urlParts['query']);
foreach ($parts as $p) {
$paramData = explode('=', $p);
if ($paramData[0] === $name) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q251845 | UrlBuilder.setQueryParam | validation | public function setQueryParam($name, $value)
{
if ($this->checkQuery($name)) {
$this->editQuery($name, $value);
} else {
$this->addQuery($name, $value);
}
return $this;
} | php | {
"resource": ""
} |
q251846 | AddHttpHeadersMiddleware.addHeaders | validation | public function addHeaders(array $headers):void
{
foreach ($headers as $name => $value) {
$this->addHeader((string)$name, $value);
}
} | php | {
"resource": ""
} |
q251847 | AddHttpHeadersMiddleware.addHeader | validation | public function addHeader(string $header, $value):void
{
if (is_iterable($value) || is_array($value)) {
$iterable = $value;
$value = [];
foreach ($iterable as $key => $entry) {
$value[$key] = (string)$entry;
}
}
else {
$value = (string)$value;
}
$this->headers[] = [$header, $value];
} | php | {
"resource": ""
} |
q251848 | UserController.checkLoggedInAction | validation | public function checkLoggedInAction()
{
$data = array('logged' => 0, 'data' => null);
if(!$this->zfcUserAuthentication()->hasIdentity()) {
return new JsonModel($data);
}
$identity = $this->zfcUserAuthentication()->getIdentity();
$data['logged'] = 1;
$userModel = $this->getServiceLocator()->get('user.model.user');
$data['data'] = $userModel->init($identity, $this->getServiceLocator());
return new JsonModel($data);
} | php | {
"resource": ""
} |
q251849 | UserController.passwordRecoveredAction | validation | public function passwordRecoveredAction()
{
$this->getResponse()
->setStatusCode(Response::STATUS_CODE_201);
$userService = $this->getServiceLocator()->get('user.service.user');
$id = $this->params()->fromRoute('id');
try {
$userService->passwordRecovered($id);
$returnData = array(
'status' => 'success',
'message' => 'Ti abbiamo inviato un\'email con la nuova password per il tuo account. Se vorrai potrai modificarla una volta connesso.'
);
} catch(\Exception $e) {
$this->getResponse()
->setStatusCode(Response::STATUS_CODE_500);
$returnData = @unserialize($e->getMessage());
if(!is_array($returnData)) {
$returnData = array(
'status' => 'danger',
'message' => $e->getMessage()
);
}
}
return new JsonModel($returnData);
} | php | {
"resource": ""
} |
q251850 | UserController.classifiedAnswerAction | validation | public function classifiedAnswerAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
// Accept only post request
if(!$request->isPost()) {
$response->setStatusCode(Response::STATUS_CODE_500);
return new JsonModel(array(
'status' => 'danger',
'message' => 'Invalid method call'
));
}
$userService = $this->getServiceLocator()->get('user.service.user');
$data = array_merge_recursive(
$this->params()->fromPost(),
Json::decode($request->getContent(), Json::TYPE_ARRAY)
);
try {
$response->setStatusCode(Response::STATUS_CODE_200);
$userService->classifiedAnswer($data);
$returnData = array(
'status' => 'success',
'message' => 'La tua risposta è stata inviata!'
);
} catch(\Exception $e) {
$response->setStatusCode(Response::STATUS_CODE_500);
$returnData = @unserialize($e->getMessage());
if(!is_array($returnData)) {
$returnData = array(
'status' => 'danger',
'message' => $e->getMessage()
);
}
}
return new JsonModel($returnData);
} | php | {
"resource": ""
} |
q251851 | RegistrationController.checkEmailAction | validation | public function checkEmailAction()
{
$email = $this->get('session')->get('fos_user_send_confirmation_email/email');
$this->get('session')->remove('fos_user_send_confirmation_email/email');
$user = $this->get('fos_user.user_manager')->findUserByEmail($email);
if (null === $user) {
throw new NotFoundHttpException(sprintf('The user with email "%s" does not exist', $email));
}
return $this->render('@MikyUser/Frontend/Registration/checkEmail.html.twig', array(
'user' => $user,
));
} | php | {
"resource": ""
} |
q251852 | RegistrationController.confirmAction | validation | public function confirmAction($token)
{
$user = $this->get('fos_user.user_manager')->findUserByConfirmationToken($token);
if (null === $user) {
throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token));
}
$user->setConfirmationToken(null);
$user->setEnabled(true);
$user->setLastLogin(new \DateTime());
$this->get('fos_user.user_manager')->updateUser($user);
$response = $this->redirect($this->generateUrl('miky_app_customer_registration_confirmed'));
$this->authenticateUser($user, $response);
return $response;
} | php | {
"resource": ""
} |
q251853 | RegistrationController.confirmedAction | validation | public function confirmedAction()
{
$user = $this->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw $this->createAccessDeniedException('This user does not have access to this section.');
}
return $this->render("@MikyUser/Frontend/Registration/confirmed.html.twig", array(
'user' => $user,
));
} | php | {
"resource": ""
} |
q251854 | RegistrationController.authenticateUser | validation | protected function authenticateUser(UserInterface $user, Response $response)
{
try {
$this->get('fos_user.security.login_manager')->loginUser(
$this->container->getParameter('fos_user.firewall_name'),
$user,
$response);
} catch (AccountStatusException $ex) {
// We simply do not authenticate users which do not pass the user
// checker (not enabled, expired, etc.).
}
} | php | {
"resource": ""
} |
q251855 | DBMigratePlugin.createMigrateRepository | validation | public function createMigrateRepository(array $args)
{
$db = $this->app->db;
$repo = new Repository($db);
// Add all module paths to the Migration object
$resolver = $this->app->resolver->getResolver("migrations");
$mods = [];
foreach ($resolver->getSearchPath() as $name => $path)
{
$module = new Module($name, $path, $db);
if ($name === "wedeto.db")
array_unshift($mods, $module);
else
array_push($mods, $module);
}
foreach ($mods as $module)
$repo->addModule($module);
return $repo;
} | php | {
"resource": ""
} |
q251856 | ResponseConfigurator.configure | validation | public function configure(Response $response, \DateTime $last_modified, $lifetime)
{
$request = $this->request_stack->getMasterRequest();
if (!($request instanceof Request)) {
return $response;
}
// order is important
$this
->setPrivateCache($response, $request)
->setLastModified($response, $last_modified)
->setLifetime($response, $lifetime)
->setEtag($response);
return $response;
} | php | {
"resource": ""
} |
q251857 | ResponseConfigurator.setLifetime | validation | protected function setLifetime(Response $response, $lifetime)
{
if ($lifetime >= 0) {
$date = clone $response->getDate();
$response
->setMaxAge($lifetime)
->setExpires($date->modify(sprintf('+%s seconds', $lifetime)));
if (!$response->headers->hasCacheControlDirective('private')) {
$response->setPublic()->setSharedMaxAge($lifetime);
}
}
return $this;
} | php | {
"resource": ""
} |
q251858 | ResponseConfigurator.setEtag | validation | protected function setEtag(Response $response)
{
if (!$response->getEtag()) {
$response->setEtag($this->key_builder->getEtag($response));
}
return $this;
} | php | {
"resource": ""
} |
q251859 | ContactController.steptwo | validation | public function steptwo() {
$input = Input::only(array('name', 'email', 'comment', 'to_email', 'to_name'));
$input['name'] = $this->quickSanitize($input['name']);
$input['email'] = $this->quickSanitize($input['email']);
$input['comment'] = $this->quickSanitize($input['comment']);
return view('lasallecmscontact::step_two_form', [
'input' => $input,
'message' => false,
]);
} | php | {
"resource": ""
} |
q251860 | ContactController.send | validation | public function send() {
$input = Input::only(array('name', 'email', 'comment', 'to_email', 'to_name', 'security-code'));
$input['security-code'] = $this->quickSanitize($input['security-code']);
if (strlen($input['security-code']) < 2) {
$message = "Please enter the security code again. Thank you!";
return view('lasallecmscontact::step_two_form', [
'input' => $input,
'message' => $message,
]);
}
// Guess it couldn't hurt to run inputs through the quick sanitize...
$input['name'] = $this->quickSanitize($input['name']);
$input['email'] = $this->quickSanitize($input['email']);
$input['comment'] = $this->quickSanitize($input['comment']);
// The "to_email" comes from the LaSalleCRMContact package. If it contains an email address,
// then the contact form was filled out in that package. So, let's figure out the "to" email
$to_email = Config::get('lasallecmscontact.to_email');
$to_name = Config::get('lasallecmscontact.to_name');
if ($input['to_email'] != "") {
$to_email = $input['to_email'];
$to_name = $input['to_name'];
}
Mail::send('lasallecmscontact::email', $input, function($message) use ($to_email, $to_name)
{
$message->from(Config::get('lasallecmscontact.from_email'), Config::get('lasallecmscontact.from_name'));
$message->to($to_email, $to_name)->subject(Config::get('lasallecmscontact.subject_email'));
});
// Redir to confirmation page
return Redirect::route('contact-processing.thankyou');
} | php | {
"resource": ""
} |
q251861 | Application.boot | validation | public function boot()
{
if (!$this->booted) {
foreach ($this->providers as $provider) {
$provider->boot($this);
}
}
$this->booted = true;
} | php | {
"resource": ""
} |
q251862 | Math.percentage | validation | public static function percentage($value, $from)
{
$value = floatval($value);
$from = floatval($from);
return floatval($value/$from*100);
} | php | {
"resource": ""
} |
q251863 | Whitelist.forThe | validation | public static function forThe(
MapsObjectsByIdentity $mapped,
string ...$allowedClasses
): MapsObjectsByIdentity {
foreach ($mapped->objects() as $object) {
if (Whitelist::doesNotHave($object, $allowedClasses)) {
$mapped = $mapped->removeThe($object);
}
}
return new Whitelist($allowedClasses, $mapped);
} | php | {
"resource": ""
} |
q251864 | Migrations.synchronizeMigrations | validation | public static function synchronizeMigrations(CommandEvent $event)
{
$packages = $event->getComposer()->getRepositoryManager()
->getLocalRepository()->getPackages();
$installer = $event->getComposer()->getInstallationManager();
$appMigrationDir = self::getDestinationDir($event->getComposer());
$io = $event->getIO();
$areFileMigrated = array();
//migrate for root package
$areFileMigrated[] = self::handlePackage('.',
$event->getComposer()->getPackage(),
$io,
$appMigrationDir);
foreach($packages as $package) {
$areFileMigrated[] = self::handlePackage($installer->getInstallPath($package),
$package,
$io,
$appMigrationDir);
}
if (in_array(true, $areFileMigrated)) {
$io->write("<warning>Some migration files have been imported. "
. "You should run `php app/console doctrine:migrations:status` and/or "
. "`php app/console doctrine:migrations:migrate` to apply them to your DB.");
}
} | php | {
"resource": ""
} |
q251865 | Migrations.checkAndMoveFile | validation | private static function checkAndMoveFile($sourceMigrationFile, $appMigrationDir, IOInterface $io)
{
//get the file name
$explodedPath = explode('/', $sourceMigrationFile);
$filename = array_pop($explodedPath);
if (file_exists($appMigrationDir.'/'.$filename)) {
if (md5_file($appMigrationDir.'/'.$filename) === md5_file($sourceMigrationFile)) {
if ($io->isVeryVerbose()) {
$io->write("<info>found that $sourceMigrationFile is equal"
. " to $appMigrationDir/$filename</info>");
}
$doTheMove = false;
} else {
$doTheMove = $io->askConfirmation("<question>The file \n"
. " \t$sourceMigrationFile\n has the same name than the previous "
. "migrated file located at \n\t$appMigrationDir/$filename\n "
. "but the content is not equal.\n Overwrite the file ?[y,N]", false);
}
} else {
$doTheMove = true;
}
//move the file
if ($doTheMove) {
$fs = new Filesystem();
$fs->copy($sourceMigrationFile, $appMigrationDir.'/'.$filename);
$io->write("<info>Importing '$filename' migration file</info>");
return true;
}
return false;
} | php | {
"resource": ""
} |
q251866 | CreateTable.beforeBuild | validation | protected function beforeBuild()
{
$this->type = 'CREATE';
if ($this->temporary) {
$this->type .= ' TEMPORARY';
}
$this->type .= ' TABLE';
if ($this->if_not_exists) {
$this->type .= ' IF NOT EXISTS';
}
$this->type .= ' ' . $this->quote($this->tbl_name);
return;
} | php | {
"resource": ""
} |
q251867 | Server.docroot | validation | public static function docroot()
{
if(!empty($_SERVER['DOCUMENT_ROOT'])){
$docroot = str_replace('\\','/',$_SERVER['DOCUMENT_ROOT']);
}else{
$docroot = str_replace('\\','/',dirname(__FILE__));
}
return $docroot;
} | php | {
"resource": ""
} |
q251868 | Server.cpuCoreInfo | validation | public static function cpuCoreInfo()
{
$cores = array();
if(false !== ($data = @file('/proc/stat'))){
foreach($data as $line ) {
if( preg_match('/^cpu[0-9]/', $line) ){
$info = explode(' ', $line);
$cores[]=array(
'user' => $info[1],
'nice' => $info[2],
'sys' => $info[3],
'idle' => $info[4],
'iowait' => $info[5],
'irq' => $info[6],
'softirq' => $info[7]
);
}
}
}
return $cores;
} | php | {
"resource": ""
} |
q251869 | Server.cpuPercentages | validation | public static function cpuPercentages($cpuCoreInfo1, $cpuCoreInfo2)
{
$cpus = array();
foreach($cpuCoreInfo1 as $idx => $core){
$dif = array();
$cpu = array();
$dif['user'] = $cpuCoreInfo2[$idx]['user'] - $cpuCoreInfo1[$idx]['user'];
$dif['nice'] = $cpuCoreInfo2[$idx]['nice'] - $cpuCoreInfo1[$idx]['nice'];
$dif['sys'] = $cpuCoreInfo2[$idx]['sys'] - $cpuCoreInfo1[$idx]['sys'];
$dif['idle'] = $cpuCoreInfo2[$idx]['idle'] - $cpuCoreInfo1[$idx]['idle'];
$dif['iowait'] = $cpuCoreInfo2[$idx]['iowait'] - $cpuCoreInfo1[$idx]['iowait'];
$dif['irq'] = $cpuCoreInfo2[$idx]['irq'] - $cpuCoreInfo1[$idx]['irq'];
$dif['softirq'] = $cpuCoreInfo2[$idx]['softirq'] - $cpuCoreInfo1[$idx]['softirq'];
$total = array_sum($dif);
foreach($dif as $x=>$y){
$cpu[$x] = round($y / $total * 100, 2);
}
$cpus['cpu' . $idx] = $cpu;
}
return $cpus;
} | php | {
"resource": ""
} |
q251870 | Server.hdd | validation | public static function hdd()
{
$hdd = new \StdClass();
$hdd->total = @disk_total_space(".");
$hdd->free = @disk_free_space(".");
return $hdd;
} | php | {
"resource": ""
} |
q251871 | Server.memory | validation | public static function memory()
{
$memory = new \StdClass();
$memory->real = new \StdClass();
$memory->swap = new \StdClass();
if(false !== ($data = @file('/proc/meminfo'))){
$data = implode("", $data);
//processing and stuff aka preg matching
preg_match_all("/MemTotal\s{0,}\:+\s{0,}([\d\.]+).+?MemFree\s{0,}\:+\s{0,}([\d\.]+).+?Cached\s{0,}\:+\s{0,}([\d\.]+).+?SwapTotal\s{0,}\:+\s{0,}([\d\.]+).+?SwapFree\s{0,}\:+\s{0,}([\d\.]+)/s", $data, $meminfo);
preg_match_all("/Buffers\s{0,}\:+\s{0,}([\d\.]+)/s", $data, $buffers);
$memory->total = $meminfo[1][0]*1024;
$memory->free = $meminfo[2][0]*1024;
$memory->used = $memory->total - $memory->free;
$memory->cached = $meminfo[3][0]*1024;
$memory->buffers = $buffers[1][0]*1024;
$memory->real->used = $memory->total - $memory->free - $memory->cached - $memory->buffers;
$memory->real->free = $memory->total - $memory->real->used;
$memory->swap->free = $meminfo[5][0]*1024;
$memory->swap->used = $meminfo[4][0]*1024 - $memory->swap->free;
}
return $memory;
} | php | {
"resource": ""
} |
q251872 | Server.avgload | validation | public static function avgload()
{
$avgload = new \StdClass();
if(false !== ($data = @file('/proc/loadavg'))){
$data = explode(" ", implode("", $data));
$data = array_chunk($data, 4);
$avgload->min1 = $data[0][0];
$avgload->min5 = $data[0][1];
$avgload->min15 = $data[0][2];
$fourth = explode('/',$data[0][3]);
$avgload->running = $fourth[0];
$avgload->exists = $fourth[1];
$avgload->recentPID = $data[1][0];
}
return $avgload;
} | php | {
"resource": ""
} |
q251873 | Filesystem.getFiles | validation | private function getFiles($pattern)
{
$files = $this->filesystem->glob(
$this->storagePath.DIRECTORY_SEPARATOR.$pattern, GLOB_BRACE
);
return array_filter(array_map('realpath', $files));
} | php | {
"resource": ""
} |
q251874 | File.getVars | validation | protected function getVars($content, $details = [])
{
// Build defaults
$defaults = [
'title' => Translate::t('file.title', [], 'filefield'),
'file' => false,
];
// Build defaults data
$vars = array_merge($defaults, $content);
// Update vars
$this->getModel()->setVars($vars);
} | php | {
"resource": ""
} |
q251875 | InputOutputFiles.getArrayFromJsonFile | validation | public function getArrayFromJsonFile($strFilePath, $strFileName)
{
$jSonContent = $this->getFileJsonContent($strFilePath, $strFileName);
$arrayToReturn = json_decode($jSonContent, true);
if (json_last_error() != JSON_ERROR_NONE) {
$fName = $this->gluePathWithFileName($strFilePath, $strFileName);
throw new \RuntimeException(sprintf('Unable to interpret JSON from %s file...', $fName));
}
return $arrayToReturn;
} | php | {
"resource": ""
} |
q251876 | EventObserver.update | validation | public function update(\SplSubject $eventManager) {
$this->isUpdate = true;
if ($eventManager->event->function !== NULL) {
$this->{$eventManager->event->function}($eventManager);
}
} | php | {
"resource": ""
} |
q251877 | Application.resolvePaths | validation | protected function resolvePaths(array $fixPaths) {
$this->rootDir = \realpath(isset($fixPaths['rootDir']) ? $fixPaths['rootDir'] : __DIR__ . '/../../../../');
$this->packageDir = \realpath(isset($fixPaths['packageDir']) ? $fixPaths['packageDir'] : __DIR__ . '/../');
$this->configPath = Utils::fixPath(isset($fixPaths['configPath']) ? $fixPaths['configPath'] : '/app/');
if($this->rootDir === false || $this->packageDir === false)
throw new \InvalidArgumentException('Bootstrap directories do not exists or are not accessible');
if($this['minion.usePropel']) {
$this->propelConfigPath = \realpath(isset($fixPaths['propelConfigPath']) ? $fixPaths['propelConfigPath']
: Utils::fixPath($this->packageDir . '/propel.php')
);
if($this->propelConfigPath === false)
throw new \InvalidArgumentException('Propel configuration file in vendor Minion not found');
}
} | php | {
"resource": ""
} |
q251878 | UploadController.uploadAction | validation | public function uploadAction(Request $request)
{
//return new JsonResponse($request);
#var_dump($request);
// process the filebag
$rawMedias = array_merge(
$this->processUploadedFiles($request->files),
$this->processUrls($request)
);
$em = $this->getDoctrine()->getManager();
$mtm = $this->get('mm_media.mediatype.manager');
$returnData = array();
foreach ($rawMedias as $rawmedia) {
if (null != ($mt = $mtm->getMediaTypeMatch($rawmedia))) {
/** @var MediaInterface $ms */
$ms = $mt->getEntity();
$em->persist($ms);
$em->flush();
$returnData[] = array(
'id' => $ms->getId(),
'path' => $rawmedia,
'mediatype' => (string) $ms->getMediaType(),
);
}
}
return new JsonResponse(
array(
'success' => true,
'data' => $returnData,
)
);
} | php | {
"resource": ""
} |
q251879 | UploadController.processUploadedFiles | validation | protected function processUploadedFiles(FileBag $filebag)
{
$adapter = new LocalAdapter($this->get('kernel')->getRootDir().'/../web/media');
$filesystem = new Filesystem($adapter);
$processed = array();
if ($filebag->get('files')) {
/*
* @var UploadedFile
*/
foreach ($filebag->get('files') as $file) {
// get the unique filepath
$dest = $this->createUniquePath($file);
if ($filesystem->write($dest['path'], file_get_contents($file->getPathname()))) {
$processed[] = $dest['path'];
};
}
}
return $processed;
} | php | {
"resource": ""
} |
q251880 | UploadController.processUrls | validation | protected function processUrls(Request $request)
{
$externalRawMediaUrls = array();
if ($request->get('urls')) {
foreach ($request->get('urls') as $url) {
$externalRawMediaUrls[] = $url;
}
}
return $externalRawMediaUrls;
} | php | {
"resource": ""
} |
q251881 | UploadController.createUniquePath | validation | protected function createUniquePath(UploadedFile $file)
{
$dir = 'mmmb/'.mb_substr(mb_strtolower((string) $file->getClientOriginalName()), 0, 2);
$filename = str_replace(array(' ', $file->getClientOriginalExtension()), '-', $file->getClientOriginalName());
$name = mb_strtolower($filename.uniqid().'.'.$file->getClientOriginalExtension());
return array(
'dir' => $dir,
'filename' => $name,
'path' => $dir.'/'.$name,
);
} | php | {
"resource": ""
} |
q251882 | Where.andWhere | validation | public function andWhere($column, $op, $value, $isParam = true)
{
$this->clauses[] = array("AND", $column, $op, $value, $isParam);
return $this;
} | php | {
"resource": ""
} |
q251883 | Where.orWhere | validation | public function orWhere($column, $op, $value, $isParam = true)
{
$this->clauses[] = array("OR", $column, $op, $value, $isParam);
return $this;
} | php | {
"resource": ""
} |
q251884 | EntityAbstract.getParent | validation | public function getParent()
{
if ($this->path === "/" || ($path = dirname($this->path)) === ".") {
return null;
}
return new DirEntity($path);
} | php | {
"resource": ""
} |
q251885 | EntityAbstract.getRelativePath | validation | public function getRelativePath(string $path): string
{
$from = $this->path;
$fromParts = explode("/", $from);
$toParts = explode("/", $path);
$max = max(count($fromParts), count($toParts));
for ($i=0; $i<$max; $i++) {
if (
!isset($fromParts[$i]) ||
!isset($toParts[$i]) ||
$fromParts[$i] !== $toParts[$i]
) {
break;
}
}
$len = count($fromParts) - $i - 1;
$path = array_slice($toParts, $i);
if ($len < 0) {
return implode("/", $path);
}
return str_repeat("../", $len).implode("/", $path);
} | php | {
"resource": ""
} |
q251886 | ContainerBuilder.bindInstance | validation | public function bindInstance(object $object): Binding
{
return $this->bind(\get_class($object))->instance($object);
} | php | {
"resource": ""
} |
q251887 | Api.execute | validation | public function execute()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->getURI());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->data);
$response = curl_exec($ch);
$result = json_decode($response);
curl_close($ch);
if (empty($result) || !$result->success) {
throw new \Exception("Pipedrive API error!");
}
return $result;
} | php | {
"resource": ""
} |
q251888 | SuperModel.buildMessages | validation | private function buildMessages( $scope = 'create' ){
$custom_messages = $this->messages['global'];
foreach($this->messages[$scope] as $key => $value){
$custom_messages[$key] = $value;
}
return $custom_messages;
} | php | {
"resource": ""
} |
q251889 | SuperModel.normalizeRules | validation | private function normalizeRules(){
foreach($this->rules as $scope => $rules){
foreach($rules as $field => $rule){
if(is_array($rule)){
$this->rules[$scope][$field] = implode('|', $rule);
}
}
}
} | php | {
"resource": ""
} |
q251890 | SuperModel.buildUniqueRules | validation | private function buildUniqueRules() {
$rulescopes = $this->rules;
foreach($rulescopes as $scope => &$rules){
foreach ($rules as $field => &$ruleset) {
// If $ruleset is a pipe-separated string, switch it to array
$ruleset = (is_string($ruleset))? explode('|', $ruleset) : $ruleset;
foreach ($ruleset as &$rule) {
if (str_contains($rule, 'unique') && str_contains($rule, '{id}') == false) {
$params = explode(',', $rule);
$uniqueRules = array();
// Append table name if needed
$table = explode(':', $params[0]);
if (count($table) == 1)
$uniqueRules[1] = $this->table;
else
$uniqueRules[1] = $table[1];
// Append field name if needed
if (count($params) == 1)
$uniqueRules[2] = $field;
else
$uniqueRules[2] = $params[1];
$uniqueRules[3] = $this->getKey();
$uniqueRules[4] = $this->getKeyName();
$rule = 'unique:' . implode(',', $uniqueRules);
}elseif(str_contains($rule, 'unique') && str_contains($rule, '{id}')){
$rule = str_replace('{id}', $this->getKey(), $rule);
} // end if str_contains
} // end foreach ruleset
}
}
$this->rules = $rulescopes;
} | php | {
"resource": ""
} |
q251891 | SuperModel.getValidator | validation | private function getValidator($scope = 'create'){
$rules = $this->buildValidationRules($scope);
$custom_messages = $this->buildMessages($scope);
$validation_values = $this->buildValidationValues();
return Validator::make($validation_values, $rules, $custom_messages);
} | php | {
"resource": ""
} |
q251892 | SuperModel.validateCreate | validation | public function validateCreate(){
$validator = $this->getValidator('create');
if($validator->fails()){
$this->errors = $validator->messages();
return false;
}
return true;
} | php | {
"resource": ""
} |
q251893 | UnsetManyCapableTrait._unsetMany | validation | protected function _unsetMany($keys)
{
$keys = $this->_normalizeIterable($keys);
$store = $this->_getDataStore();
try {
$this->_containerUnsetMany($store, $keys);
} catch (InvalidArgumentException $e) {
throw $this->_createOutOfRangeException($this->__('Invalid store'), null, $e, $store);
}
} | php | {
"resource": ""
} |
q251894 | pertyTrait.__propertyTraitHasProperty | validation | protected function __propertyTraitHasProperty($propertyName)
{
// Check if getter or setter method exists
if (method_exists($this, 'get'.$propertyName) || method_exists($this, 'set'.$propertyName)) {
return true;
}
// Check if property is public
try
{
$classReflection = new \ReflectionProperty(get_class($this), $propertyName);
return $classReflection->isPublic();
} catch (\ReflectionException $ex) {
return false;
}
} | php | {
"resource": ""
} |
q251895 | pertyTrait.__isset | validation | public function __isset($propertyName)
{
$methodName = 'get'.$propertyName;
if (method_exists($this, $methodName)) {
return ($this->$methodName() !== null);
} else {
return false;
}
} | php | {
"resource": ""
} |
q251896 | ArrayObject.groupBy | validation | public function groupBy($func)
{
$ret = array();
$it = $this->getIterator();
while ($it->valid()) {
if (is_object($it->current())) {
$key = call_user_func($func, $it->current());
} else {
// Pass scalar values by reference, too
$value = $it->current();
$key = call_user_func_array($func, array(&$value));
$it->offsetSet($it->key(), $value);
unset($value);
}
if (is_array($key)) {
$ref = &$ret;
foreach ($key as $subkey) {
if (!array_key_exists($subkey, $ref)) {
$ref[$subkey] = array();
}
$ref = &$ref[$subkey];
}
$ref[] = $it->current();
} else {
$ret[$key][] = $it->current();
}
$it->next();
}
unset($ref);
$ret = new self($ret);
$this->exchangeArray($ret->getArrayCopy());
return $this;
} | php | {
"resource": ""
} |
q251897 | ArrayObject.usort | validation | public function usort($cmp_function)
{
$tmp = $this->getArrayCopy();
$ret = usort($tmp, $cmp_function);
$tmp = new self($tmp);
$this->exchangeArray($tmp->getArrayCopy());
return $ret;
} | php | {
"resource": ""
} |
q251898 | ArrayObject.getArrayCopyRec | validation | public function getArrayCopyRec()
{
$ret = array();
$it = $this->getIterator();
while ($it->valid()) {
if ($it->current() instanceof self) {
$ret[$it->key()] = $it->current()->getArrayCopyRec();
} else {
$ret[$it->key()] = $it->current();
}
$it->next();
}
return $ret;
} | php | {
"resource": ""
} |
q251899 | ArrayObject._uxsortmRec | validation | private function _uxsortmRec(
ArrayObject $a,
array $sortFuncs,
$depth = 0,
$sortMode = ''
) {
$goOn = (count($sortFuncs) > $depth + 1);
$it = $a->getIterator();
while ($it->valid()) {
if (null !== $sortFuncs[$depth]) {
if ($sortMode == 'a') {
$it->current()->uasort($sortFuncs[$depth]);
} else if ($sortMode == 'k') {
$it->current()->uksort($sortFuncs[$depth]);
} else {
$it->current()->usort($sortFuncs[$depth]);
}
}
if ($goOn) {
$this->_uxsortmRec(
$it->current(),
$sortFuncs,
$depth + 1,
$sortMode
);
}
$it->next();
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.