_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q247500 | SimpleRbacAuthorize._isAllowedRole | validation | protected function _isAllowedRole($userRoles, array $allowedRoles) {
if (in_array('*', $allowedRoles)) {
return true;
}
if (is_string($userRoles)) {
$userRoles = [$userRoles];
}
foreach ($userRoles as $userRole) {
if (in_array($userRole, $allowedRoles)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q247501 | SimpleRbacAuthorize.getControllerNameAndAction | validation | public function getControllerNameAndAction(Request $request) {
$controller = $this->_registry->getController();
$name = $controller->name;
$action = $request->action;
if (!empty($request->params['plugin'])) {
$name = Inflector::camelize($request->params['plugin']) . '.' . $name;
}
return compact('name', 'action');
} | php | {
"resource": ""
} |
q247502 | SimpleRbacAuthorize.getActionMap | validation | public function getActionMap() {
$actionMap = (array) Configure::read('SimpleRbac.actionMap');
if (empty($actionMap) && $this->_config['allowEmptyActionMap'] === false) {
throw new \RuntimeException('SimpleRbac.actionMap configuration is empty!');
}
return $actionMap;
} | php | {
"resource": ""
} |
q247503 | SimpleRbacAuthorize.getPrefixMap | validation | public function getPrefixMap() {
$prefixMap = (array) Configure::read('SimpleRbac.prefixMap');
if (empty($prefixMap) && $this->_config['allowEmptyPrefixMap'] === false) {
throw new \RuntimeException('SimpleRbac.prefixMap configuration is empty!');
}
return $prefixMap;
} | php | {
"resource": ""
} |
q247504 | Hash.nextkey | validation | public function nextkey() {
if ( $this->keys === null ) {
return $this->firstkey();
}
return empty( $this->keys ) ? false : array_shift( $this->keys );
} | php | {
"resource": ""
} |
q247505 | Promise.then | validation | public function then(callable $onFulfilled = null, callable $onRejected = null)
{
$newPromise = new self($this->loop);
$onFulfilled = null !== $onFulfilled ? $onFulfilled : function (ResponseInterface $response) {
return $response;
};
$onRejected = null !== $onRejected ? $onRejected : function (Exception $exception) {
throw $exception;
};
$this->onFulfilled = function (ResponseInterface $response) use ($onFulfilled, $newPromise) {
try {
$return = $onFulfilled($response);
$newPromise->resolve(null !== $return ? $return : $response);
} catch (Exception $exception) {
$newPromise->reject($exception);
}
};
$this->onRejected = function (Exception $exception) use ($onRejected, $newPromise) {
try {
$newPromise->resolve($onRejected($exception));
} catch (Exception $exception) {
$newPromise->reject($exception);
}
};
if (HttpPromise::FULFILLED === $this->state) {
$this->doResolve($this->response);
}
if (HttpPromise::REJECTED === $this->state) {
$this->doReject($this->exception);
}
return $newPromise;
} | php | {
"resource": ""
} |
q247506 | Promise.resolve | validation | public function resolve(ResponseInterface $response)
{
if (HttpPromise::PENDING !== $this->state) {
throw new \RuntimeException('Promise is already resolved');
}
$this->state = HttpPromise::FULFILLED;
$this->response = $response;
$this->doResolve($response);
} | php | {
"resource": ""
} |
q247507 | Promise.reject | validation | public function reject(Exception $exception)
{
if (HttpPromise::PENDING !== $this->state) {
throw new \RuntimeException('Promise is already resolved');
}
$this->state = HttpPromise::REJECTED;
$this->exception = $exception;
$this->doReject($exception);
} | php | {
"resource": ""
} |
q247508 | Writer.open | validation | public static function open( $fileName ) {
return Reader::haveExtension() ?
new Writer\DBA( $fileName ) :
new Writer\PHP( $fileName );
} | php | {
"resource": ""
} |
q247509 | Swot.isAcademic | validation | public function isAcademic($text)
{
if (empty($text)) {
return false;
}
$domain = $this->getDomain($text);
if ($domain === null) {
return false;
}
foreach ($this->getBlacklistedTopLevelDomains() as $blacklistedDomain) {
$name = (string) $domain['host'];
if (preg_match('/' . preg_quote($blacklistedDomain) . '$/', $name)) {
return false;
}
}
if (in_array($domain['tld'], $this->getAcademicTopLevelDomains())) {
return true;
}
if ($this->matchesAcademicDomain($domain)) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q247510 | Swot.nameFromAcademicDomain | validation | private function nameFromAcademicDomain($domain)
{
$path = $this->getPath($domain);
if ( ! file_exists($path)) {
return null;
}
return trim(file_get_contents($path));
} | php | {
"resource": ""
} |
q247511 | Swot.matchesAcademicDomain | validation | private function matchesAcademicDomain($domain)
{
if (empty($domain['tld']) or empty($domain['sld'])) {
return false;
}
return file_exists($this->getPath($domain));
} | php | {
"resource": ""
} |
q247512 | PHP.throwException | validation | protected function throwException( $msg ) {
if ( $this->handle ) {
fclose( $this->handle );
unlink( $this->tmpFileName );
}
throw new Exception( $msg );
} | php | {
"resource": ""
} |
q247513 | Reader.open | validation | public static function open( $fileName ) {
return self::haveExtension() ?
new Reader\DBA( $fileName ) :
new Reader\PHP( $fileName );
} | php | {
"resource": ""
} |
q247514 | Reader.haveExtension | validation | public static function haveExtension() {
if ( !function_exists( 'dba_handlers' ) ) {
return false;
}
$handlers = dba_handlers();
if ( !in_array( 'cdb', $handlers ) || !in_array( 'cdb_make', $handlers ) ) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q247515 | PHP.get | validation | public function get( $key ) {
// strval is required
if ( $this->find( strval( $key ) ) ) {
return $this->read( $this->dataPos, $this->dataLen );
}
return false;
} | php | {
"resource": ""
} |
q247516 | PHP.read | validation | protected function read( $start, $len ) {
$end = $start + $len;
// The first 2048 bytes are the lookup table, which is read into
// memory on initialization.
if ( $end <= 2048 ) {
return substr( $this->index, $start, $len );
}
// Read data from the internal buffer first.
$bytes = '';
if ( $this->buf && $start >= $this->bufStart ) {
$bytes .= substr( $this->buf, $start - $this->bufStart, $len );
$bytesRead = strlen( $bytes );
$len -= $bytesRead;
$start += $bytesRead;
} else {
$bytesRead = 0;
}
if ( !$len ) {
return $bytes;
}
// Many reads are sequential, so the file position indicator may
// already be in the right place, in which case we can avoid the
// call to fseek().
if ( $start !== $this->filePos ) {
if ( fseek( $this->handle, $start ) === -1 ) {
// This can easily happen if the internal pointers are incorrect
throw new Exception(
'Seek failed, file "' . $this->fileName . '" may be corrupted.' );
}
}
$buf = fread( $this->handle, max( $len, 1024 ) );
if ( $buf === false ) {
$buf = '';
}
$bytes .= substr( $buf, 0, $len );
if ( strlen( $bytes ) !== $len + $bytesRead ) {
throw new Exception(
'Read from CDB file failed, file "' . $this->fileName . '" may be corrupted.' );
}
$this->filePos = $end;
$this->bufStart = $start;
$this->buf = $buf;
return $bytes;
} | php | {
"resource": ""
} |
q247517 | PHP.readInt31 | validation | protected function readInt31( $pos = 0 ) {
$uint31 = $this->readInt32( $pos );
if ( $uint31 > 0x7fffffff ) {
throw new Exception(
'Error in CDB file "' . $this->fileName . '", integer too big.' );
}
return $uint31;
} | php | {
"resource": ""
} |
q247518 | PHP.readInt32 | validation | protected function readInt32( $pos = 0 ) {
static $lookups;
if ( !$lookups ) {
$lookups = [];
for ( $i = 1; $i < 256; $i++ ) {
$lookups[ chr( $i ) ] = $i;
}
}
$buf = $this->read( $pos, 4 );
$rv = 0;
if ( $buf[0] !== "\x0" ) {
$rv = $lookups[ $buf[0] ];
}
if ( $buf[1] !== "\x0" ) {
$rv |= ( $lookups[ $buf[1] ] << 8 );
}
if ( $buf[2] !== "\x0" ) {
$rv |= ( $lookups[ $buf[2] ] << 16 );
}
if ( $buf[3] !== "\x0" ) {
$rv |= ( $lookups[ $buf[3] ] << 24 );
}
return $rv;
} | php | {
"resource": ""
} |
q247519 | PHP.find | validation | protected function find( $key ) {
$keyLen = strlen( $key );
$u = Util::hash( $key );
$upos = ( $u << 3 ) & 2047;
$hashSlots = $this->readInt31( $upos + 4 );
if ( !$hashSlots ) {
return false;
}
$hashPos = $this->readInt31( $upos );
$keyHash = $u;
$u = Util::unsignedShiftRight( $u, 8 );
$u = Util::unsignedMod( $u, $hashSlots );
$u <<= 3;
$keyPos = $hashPos + $u;
for ( $i = 0; $i < $hashSlots; $i++ ) {
$hash = $this->readInt32( $keyPos );
$pos = $this->readInt31( $keyPos + 4 );
if ( !$pos ) {
return false;
}
$keyPos += 8;
if ( $keyPos == $hashPos + ( $hashSlots << 3 ) ) {
$keyPos = $hashPos;
}
if ( $hash === $keyHash ) {
if ( $keyLen === $this->readInt31( $pos ) ) {
$dataLen = $this->readInt31( $pos + 4 );
$dataPos = $pos + 8 + $keyLen;
$foundKey = $this->read( $pos + 8, $keyLen );
if ( $foundKey === $key ) {
// Found
$this->dataLen = $dataLen;
$this->dataPos = $dataPos;
return true;
}
}
}
}
return false;
} | php | {
"resource": ""
} |
q247520 | PHP.firstkey | validation | public function firstkey() {
$this->keyIterPos = 4;
if ( !$this->keyIterStop ) {
$pos = INF;
for ( $i = 0; $i < 2048; $i += 8 ) {
$pos = min( $this->readInt31( $i ), $pos );
}
$this->keyIterStop = $pos;
}
$this->keyIterPos = 2048;
return $this->nextkey();
} | php | {
"resource": ""
} |
q247521 | PHP.nextkey | validation | public function nextkey() {
if ( $this->keyIterPos >= $this->keyIterStop ) {
return false;
}
$keyLen = $this->readInt31( $this->keyIterPos );
$dataLen = $this->readInt31( $this->keyIterPos + 4 );
$key = $this->read( $this->keyIterPos + 8, $keyLen );
$this->keyIterPos += 8 + $keyLen + $dataLen;
return $key;
} | php | {
"resource": ""
} |
q247522 | ReactFactory.buildDnsResolver | validation | public static function buildDnsResolver(
LoopInterface $loop,
$dns = '8.8.8.8'
) {
$factory = new DnsResolverFactory();
return $factory->createCached($dns, $loop);
} | php | {
"resource": ""
} |
q247523 | ReactFactory.buildHttpClient | validation | public static function buildHttpClient(
LoopInterface $loop,
$connector = null
) {
if (class_exists(HttpClientFactory::class)) {
// if HttpClientFactory class exists, use old behavior for backwards compatibility
return static::buildHttpClient04($loop, $connector);
} else {
return static::buildHttpClient05($loop, $connector);
}
} | php | {
"resource": ""
} |
q247524 | ReactFactory.buildHttpClient04 | validation | protected static function buildHttpClient04(
LoopInterface $loop,
$dns = null
) {
// create dns resolver if one isn't provided
if (null === $dns) {
$dns = static::buildDnsResolver($loop);
}
// validate connector instance for proper error reporting
if (!$dns instanceof DnsResolver) {
throw new \InvalidArgumentException('For react http client v0.4, $dns must be an instance of DnsResolver');
}
$factory = new HttpClientFactory();
return $factory->create($loop, $dns);
} | php | {
"resource": ""
} |
q247525 | ReactFactory.buildHttpClient05 | validation | protected static function buildHttpClient05(
LoopInterface $loop,
$connector = null
) {
// build a connector with given DnsResolver if provided (old deprecated behavior)
if ($connector instanceof DnsResolver) {
@trigger_error(
sprintf(
'Passing a %s to buildHttpClient is deprecated since version 2.1.0 and will be removed in 3.0. If you need no specific behaviour, omit the $dns argument, otherwise pass a %s',
DnsResolver::class,
ConnectorInterface::class
),
E_USER_DEPRECATED
);
$connector = static::buildConnector($loop, $connector);
}
// validate connector instance for proper error reporting
if (null !== $connector && !$connector instanceof ConnectorInterface) {
throw new \InvalidArgumentException(
'$connector must be an instance of DnsResolver or ConnectorInterface'
);
}
return new HttpClient($loop, $connector);
} | php | {
"resource": ""
} |
q247526 | Util.unsignedShiftRight | validation | public static function unsignedShiftRight( $a, $b ) {
if ( $b == 0 ) {
return $a;
}
if ( $a & 0x80000000 ) {
return ( ( $a & 0x7fffffff ) >> $b ) | ( 0x40000000 >> ( $b - 1 ) );
} else {
return $a >> $b;
}
} | php | {
"resource": ""
} |
q247527 | Util.hash | validation | public static function hash( $s ) {
$h = 5381;
$len = strlen( $s );
for ( $i = 0; $i < $len; $i++ ) {
$h5 = ( $h << 5 ) & 0xffffffff;
// Do a 32-bit sum
// Inlined here for speed
$sum = ( $h & 0x3fffffff ) + ( $h5 & 0x3fffffff );
$h =
(
( $sum & 0x40000000 ? 1 : 0 )
+ ( $h & 0x80000000 ? 2 : 0 )
+ ( $h & 0x40000000 ? 1 : 0 )
+ ( $h5 & 0x80000000 ? 2 : 0 )
+ ( $h5 & 0x40000000 ? 1 : 0 )
) << 30
| ( $sum & 0x3fffffff );
$h ^= ord( $s[$i] );
$h &= 0xffffffff;
}
return $h;
} | php | {
"resource": ""
} |
q247528 | Client.buildReactRequest | validation | private function buildReactRequest(RequestInterface $request)
{
$headers = [];
foreach ($request->getHeaders() as $name => $value) {
$headers[$name] = (is_array($value) ? $value[0] : $value);
}
$reactRequest = $this->client->request(
$request->getMethod(),
(string) $request->getUri(),
$headers,
$request->getProtocolVersion()
);
return $reactRequest;
} | php | {
"resource": ""
} |
q247529 | Client.buildResponse | validation | private function buildResponse(
ReactResponse $response,
StreamInterface $body
) {
$body->rewind();
return $this->responseFactory->createResponse(
$response->getCode(),
$response->getReasonPhrase(),
$response->getHeaders(),
$body,
$response->getVersion()
);
} | php | {
"resource": ""
} |
q247530 | Theme.set | validation | public function set($theme)
{
if (!$this->has($theme)) {
throw new ThemeNotFoundException($theme);
}
$this->loadTheme($theme);
} | php | {
"resource": ""
} |
q247531 | Theme.get | validation | public function get($theme = null)
{
if (is_null($theme)) {
return $this->themes[$this->activeTheme];
}
return $this->themes[$theme];
} | php | {
"resource": ""
} |
q247532 | Theme.loadTheme | validation | private function loadTheme($theme)
{
if (!isset($theme)) {
return;
}
$th = $this->findThemeByDirectory($theme);
if (isset($th)) {
$viewFinder = $this->view->getFinder();
$viewFinder->prependPath($th->getPath());
if (!is_null($th->getParent())) {
$this->loadTheme($th->getParent());
}
$this->activeTheme = $theme;
}
} | php | {
"resource": ""
} |
q247533 | Theme.findThemeByDirectory | validation | private function findThemeByDirectory($directory)
{
if (isset($this->themes[$directory])) {
return $this->themes[$directory];
}
return null;
} | php | {
"resource": ""
} |
q247534 | Theme.scanThemes | validation | private function scanThemes()
{
$themeDirectories = glob($this->basePath . '/*', GLOB_ONLYDIR);
$themes = [];
foreach ($themeDirectories as $themePath) {
$json = $themePath . '/theme.json';
if (file_exists($json)) {
$contents = file_get_contents($json);
if (!$contents === false) {
$th = $this->parseThemeInfo(json_decode($contents, true));
$themes[$th->getDirectory()] = $th;
}
}
}
$this->themes = $themes;
// if no active theme & if found 1+ theme, set first as default
if (count($themes) && !$this->activeTheme) {
$this->set(array_keys($themes)[0]);
}
} | php | {
"resource": ""
} |
q247535 | Theme.findPath | validation | private function findPath($directory)
{
$path = [];
$path[] = $this->basePath;
$path[] = $directory;
$path[] = 'views';
return implode(DIRECTORY_SEPARATOR, $path);
} | php | {
"resource": ""
} |
q247536 | Theme.parseThemeInfo | validation | private function parseThemeInfo(array $info)
{
$themeInfo = new ThemeInfo();
$required = ['name', 'author', 'directory'];
foreach ($required as $key) {
if (!array_key_exists($key, $info)) {
throw new ThemeInfoAttributeException($key);
}
}
$themeInfo->setName($info['name']);
$themeInfo->setAuthor($info['author']);
$themeInfo->setDirectory(strtolower($info['directory']));
if (isset($info['description'])) {
$themeInfo->setDescription($info['description']);
}
if (isset($info['version'])) {
$themeInfo->setVersion($info['version']);
}
if (isset($info['parent'])) {
$themeInfo->setParent($info['parent']);
}
$themeInfo->setPath($this->findPath($info['directory']));
return $themeInfo;
} | php | {
"resource": ""
} |
q247537 | AssetFactory.migrateConfig | validation | private static function migrateConfig(array $config): array
{
// if old format "type" and "class" is set, migrate.
if (isset($config['class'])) {
do_action(
'inpsyde.assets.debug',
'The asset config-format with "type" and "class" is deprecated.',
$config
);
$config['location'] = $config['type'] ?? Asset::FRONTEND;
$config['type'] = $config['class'];
unset($config['class']);
}
return $config;
} | php | {
"resource": ""
} |
q247538 | NavigationServiceProvider.registerNavigation | validation | protected function registerNavigation()
{
$this->app->singleton('navigation', function ($app) {
$request = $app['request'];
$events = $app['events'];
$url = $app['url'];
$view = $app['view'];
$name = 'navigation::bootstrap';
$navigation = new Navigation($request, $events, $url, $view, $name);
$app->refresh('request', $navigation, 'setRequest');
return $navigation;
});
$this->app->alias('navigation', Navigation::class);
} | php | {
"resource": ""
} |
q247539 | Navigation.addToMain | validation | public function addToMain(array $item, $name = 'default', $first = false)
{
// check if the name exists in the main array
if (!array_key_exists($name, $this->main)) {
// add it if it doesn't exists
$this->main[$name] = [];
}
// check if we are forcing the item to the start
if ($first) {
// add the item to the start of the array
$this->main[$name] = array_merge([$item], $this->main[$name]);
} else {
// add the item to the end of the array
$this->main[$name][] = $item;
}
return $this;
} | php | {
"resource": ""
} |
q247540 | Navigation.addToBar | validation | public function addToBar(array $item, $name = 'default', $first = false)
{
// check if the name exists in the bar array
if (!array_key_exists($name, $this->bar)) {
// add it if it doesn't exists
$this->bar[$name] = [];
}
// check if we are forcing the item to the start
if ($first) {
// add the item to the start of the array
$this->bar[$name] = array_merge([$item], $this->bar[$name]);
} else {
// add the item to the end of the array
$this->bar[$name][] = $item;
}
return $this;
} | php | {
"resource": ""
} |
q247541 | Navigation.render | validation | public function render($mainName = 'default', $barName = false, array $data = null)
{
// set the default value if nothing was passed
if ($data === null) {
$data = ['title' => 'Navigation', 'side' => 'dropdown', 'inverse' => true];
}
// get the nav bar arrays
$main = $this->getMain($mainName);
if (is_string($barName)) {
$bar = $this->getBar($barName);
if (empty($bar)) {
$bar = false;
}
} else {
$bar = false;
}
// return the html nav bar
return $this->view->make($this->name, array_merge($data, ['main' => $main, 'bar' => $bar]))->render();
} | php | {
"resource": ""
} |
q247542 | Navigation.getMain | validation | protected function getMain($name = 'default')
{
// fire event that can be hooked to add items to the nav bar
$this->events->fire('navigation.main', [['name' => $name]]);
// check if the name exists in the main array
if ($name !== 'default' && !array_key_exists($name, $this->main)) {
// use the default name
$name = 'default';
}
if (!array_key_exists($name, $this->main)) {
// add it if it doesn't exists
$this->main[$name] = [];
}
// apply active keys
$nav = $this->active($this->main[$name]);
// fix up and spit out the nav bar
return $this->process($nav);
} | php | {
"resource": ""
} |
q247543 | Navigation.getBar | validation | protected function getBar($name = 'default')
{
// fire event that can be hooked to add items to the nav bar
$this->events->fire('navigation.bar', [['name' => $name]]);
// check if the name exists in the bar array
if ($name !== 'default' && !array_key_exists($name, $this->bar)) {
// use the default name
$name = 'default';
}
if (!array_key_exists($name, $this->bar)) {
// add it if it doesn't exists
$this->bar[$name] = [];
}
// don't apply active keys
$nav = $this->bar[$name];
// fix up and spit out the nav bar
return $this->process($nav);
} | php | {
"resource": ""
} |
q247544 | Navigation.active | validation | protected function active(array $nav)
{
// check if each item is active
foreach ($nav as $key => $value) {
// check if it is local
if (isset($value['slug'])) {
// if the request starts with the slug
if ($this->request->is($value['slug']) || $this->request->is($value['slug'].'/*')) {
// then the navigation item is active, or selected
$nav[$key]['active'] = true;
} else {
// then the navigation item is not active or selected
$nav[$key]['active'] = false;
}
} else {
// then the navigation item is not active or selected
$nav[$key]['active'] = false;
}
}
// spit out the nav bar array at the end
return $nav;
} | php | {
"resource": ""
} |
q247545 | Navigation.process | validation | protected function process(array $nav)
{
// convert slugs to urls
foreach ($nav as $key => $value) {
// if the url is not set
if (!isset($value['url'])) {
// set the url based on the slug
$nav[$key]['url'] = $this->url->to($value['slug']);
}
// remove any remaining slugs
unset($nav[$key]['slug']);
}
// spit out the nav bar array at the end
return $nav;
} | php | {
"resource": ""
} |
q247546 | Point.getDistance | validation | public function getDistance(Point $point, DistanceInterface $calculator = null)
{
$calculator = $calculator ? : static::getCalculator();
return $calculator->getDistance(
new Coordinate($this->latitude, $this->longitude),
new Coordinate($point->latitude, $point->longitude)
);
} | php | {
"resource": ""
} |
q247547 | Container.register | validation | private function register(array $providers, array $values)
{
foreach ($providers as $provider) {
$factories = $provider->getFactories();
foreach ($factories as $key => $callable) {
$this[$key] = function (ContainerInterface $c) use ($callable) {
return call_user_func($callable, $c);
};
}
}
foreach ($providers as $provider) {
$extensions = $provider->getExtensions();
foreach ($extensions as $key => $callable) {
if (isset($this->keys[$key])) {
// Extend a previous entry
$this[$key] = $this->extend($key, function ($previous, ContainerInterface $c) use ($callable) {
return call_user_func($callable, $c, $previous);
});
} else {
$this[$key] = function (ContainerInterface $c) use ($callable) {
return call_user_func($callable, $c);
};
}
}
}
foreach ($values as $key => $value) {
$this[$key] = $value;
}
} | php | {
"resource": ""
} |
q247548 | Toastr.success | validation | public function success($message, $title = null, $options = [])
{
return $this->add('success', $message, $title, $options);
} | php | {
"resource": ""
} |
q247549 | AttributionSettable.setA | validation | public function setA(StringType $name, Attribute $attribute)
{
if ($this->hasA($name)) {
$this->attributes = $this->attributes->kDiff(
new AttributeMap([$name() => $attribute])
);
}
$this->attributes = $this->attributes->append([$name() => $attribute]);
return $this;
} | php | {
"resource": ""
} |
q247550 | Manipulation.drop | validation | public function drop(DatabaseObjectInterface $databaseObject, $cascade = false)
{
$command = $this->getCommand($databaseObject, false);
if ($cascade) {
$command->cascade();
}
return $command->execute();
} | php | {
"resource": ""
} |
q247551 | Manipulation.getCommand | validation | private function getCommand(DatabaseObjectInterface $databaseObject, $isCreate = true)
{
if ($databaseObject instanceof Column) {
$command = $this->container
->get($isCreate ? 'rentgen.add_column' : 'rentgen.drop_column')
->setColumn($databaseObject);
} elseif ($databaseObject instanceof ConstraintInterface) {
$command = $this->container
->get($isCreate ? 'rentgen.add_constraint' : 'rentgen.drop_constraint')
->setConstraint($databaseObject);
} elseif ($databaseObject instanceof Index) {
$command = $this->container
->get($isCreate ? 'rentgen.create_index' : 'rentgen.drop_index')
->setIndex($databaseObject);
} elseif ($databaseObject instanceof Schema) {
$command = $this->container
->get($isCreate ? 'rentgen.create_schema' : 'rentgen.drop_schema')
->setSchema($databaseObject);
} elseif ($databaseObject instanceof Table) {
$command = $this->container
->get($isCreate ? 'rentgen.create_table' : 'rentgen.drop_table')
->setTable($databaseObject);
} else {
throw new \Exception(sprintf("Class %s is not supported", get_class($databaseObject)));
}
return $command;
} | php | {
"resource": ""
} |
q247552 | Info.getTable | validation | public function getTable(Table $table)
{
return $this->container
->get('rentgen.get_table')
->setTableName($table->getName())
->execute();
} | php | {
"resource": ""
} |
q247553 | Info.getTables | validation | public function getTables($schemaName = null)
{
$getTablesCommand = $this->container->get('rentgen.get_tables');
if (null !== $schemaName) {
$getTablesCommand->setSchemaName($schemaName);
}
return $getTablesCommand->execute();
} | php | {
"resource": ""
} |
q247554 | GetTableCommand.loadConstraints | validation | private function loadConstraints(Table $table)
{
foreach ($this->getConstraints() as $constraint) {
switch ($constraint['constraint_type']) {
case 'FOREIGN KEY':
// TODO Find a better way to define foreign key
$foreignKey = new ForeignKey(new Table($constraint['table_name']), new Table($constraint['column_name']));
$foreignKey->setColumns($constraint['references_table']);
$foreignKey->setReferencedColumns($constraint['references_field']);
$table->addConstraint($foreignKey);
break;
case 'PRIMARY KEY':
$table->addConstraint(new PrimaryKey($constraint['column_name'], $table));
break;
case 'UNIQUE':
$table->addConstraint(new Unique($constraint['column_name'], new Table($constraint['table_name'])));
break;
}
}
} | php | {
"resource": ""
} |
q247555 | ForeignKey.setReferencedColumns | validation | public function setReferencedColumns($columns)
{
if (!is_array($columns)) {
$columns = array($columns);
}
$this->referencedColumns = $columns;
return $this;
} | php | {
"resource": ""
} |
q247556 | ForeignKey.setUpdateAction | validation | public function setUpdateAction($updateAction)
{
$updateAction = strtoupper($updateAction);
if (!in_array($updateAction, $this->getAvailableActions())) {
throw new \InvalidArgumentException(sprintf('Action %s does not exist.', $updateAction));
}
$this->updateAction = $updateAction;
} | php | {
"resource": ""
} |
q247557 | ForeignKey.setDeleteAction | validation | public function setDeleteAction($deleteAction)
{
$deleteAction = strtoupper($deleteAction);
if (!in_array($deleteAction, $this->getAvailableActions())) {
throw new \InvalidArgumentException(sprintf('Action %s does not exist.', $deleteAction));
}
$this->deleteAction = $deleteAction;
} | php | {
"resource": ""
} |
q247558 | Connection.execute | validation | public function execute($sql)
{
$this->dispatcher->dispatch('rentgen.sql_executed', new SqlEvent($sql));
return $this->getConnection()->exec($sql);
} | php | {
"resource": ""
} |
q247559 | Connection.query | validation | public function query($sql)
{
$rows = array();
foreach ($this->getConnection()->query($sql) as $row) {
$rows[] = $row;
}
return $rows;
} | php | {
"resource": ""
} |
q247560 | Command.execute | validation | public function execute()
{
$this->preExecute();
$result = $this->connection->execute($this->getSql());
$this->postExecute();
return $result;
} | php | {
"resource": ""
} |
q247561 | Table.getColumn | validation | public function getColumn($name)
{
foreach ($this->columns as $column) {
if ($column->getName() == $name) {
return $column;
}
}
return null;
} | php | {
"resource": ""
} |
q247562 | Table.addConstraint | validation | public function addConstraint(ConstraintInterface $constraint)
{
$constraint->setTable($this);
$this->constraints[] = $constraint;
return $this;
} | php | {
"resource": ""
} |
q247563 | ConnectionConfig.parseConfiguration | validation | private function parseConfiguration(array $config)
{
$this->currentEnvironment = 'dev';
foreach($config as $environment => $connection) {
if (isset($connection['dsn'])) {
$this->dsn[$environment] = $connection['dsn'];
} else {
$this->dsn[$environment]= sprintf('pgsql:host=%s; port=%s; dbname=%s;'
, $connection['host']
, $connection['port']
, $connection['database']);
}
//$this->adapter[$environment] = $connection['adapter'];
$this->username[$environment] = $connection['username'];
$this->password[$environment] = $connection['password'];
}
} | php | {
"resource": ""
} |
q247564 | Attribution.getA | validation | public function getA(StringType $name)
{
if (!$this->hasA($name)) {
throw new AttributesException("Attribute: {$name} does not exist");
}
return $this->attributes[$name()];
} | php | {
"resource": ""
} |
q247565 | Cache.start | validation | public function start()
{
if (!isset($this->_dir)) {
return false;
}
$this->_page = $this->url; // Requested page
$this->_file = $this->_dir . md5($this->_page) . '.' . $this->_ext; // Cache file to either load or create
$ignore_page = false;
for ($i = 0; $i < count($this->_ignoreList); $i++) {
$ignore_page = (strpos($this->_page, $this->_ignoreList[$i]) !== false) ? true : $ignore_page;
}
$cachefile_created = (file_exists($this->_file) && ($ignore_page === false)) ? filemtime($this->_file) : 0;
clearstatcache();
// Show file from cache if still valid
if (time() - $this->_time < $cachefile_created) {
ob_start('ob_gzhandler');
readfile($this->_file);
//$time_end = microtime(true);
//$time = $time_end - $time_start;
//echo '<!-- generated in ' . $time . ' cached page - '.date('l jS \of F Y h:i:s A', filemtime($cachefile)).', Page : '.$page.' -->';
ob_end_flush();
exit();
}
// If we're still here, we need to generate a cache file
//Turn on output buffering with gzip compression.
ob_start('ob_gzhandler');
} | php | {
"resource": ""
} |
q247566 | Cache.stop | validation | public function stop()
{
// Now the script has run, generate a new cache file
$fp = @fopen($this->_file, 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
} | php | {
"resource": ""
} |
q247567 | ObjectHelper.getClassNameWithoutNamespace | validation | public static function getClassNameWithoutNamespace($object)
{
$className = get_class($object);
if (preg_match('@\\\\([\w]+)$@', $className, $matches)) {
$className = $matches[1];
}
return $className;
} | php | {
"resource": ""
} |
q247568 | CreateTableCommand.getConstraintsSql | validation | private function getConstraintsSql()
{
$sql = '';
foreach ($this->table->getConstraints() as $constraint) {
$sql .= ',';
if ($constraint instanceof PrimaryKey) {
$sql .= (string) $constraint ;
} elseif ($constraint instanceof ForeignKey) {
$sql .= sprintf('CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s) MATCH SIMPLE ON UPDATE %s ON DELETE %s'
, $constraint->getName()
, implode(',', $constraint->getColumns())
, $constraint->getReferencedTable()->getQualifiedName()
, implode(',', $constraint->getReferencedColumns())
, $constraint->getUpdateAction()
, $constraint->getDeleteAction());
} elseif ($constraint instanceof Unique) {
$sql .= sprintf('CONSTRAINT %s UNIQUE (%s)'
, $constraint->getName()
, implode(',', $constraint->getColumns()));
}
}
return rtrim($sql, ',');
} | php | {
"resource": ""
} |
q247569 | CreateTableCommand.getColumnsSql | validation | private function getColumnsSql()
{
$columnTypeMapper = new ColumnTypeMapper();
foreach ($this->table->getConstraints() as $constraint) {
if ($constraint instanceof PrimaryKey) {
$primaryKey = $constraint;
}
}
if (!isset($primaryKey)) { // TODO find better solution
$primaryKey = new PrimaryKey();
$primaryKey->setTable($this->table);
$this->table->addConstraint($primaryKey);
}
$sql = '';
if (!$primaryKey->isMulti() && $primaryKey->isAutoCreateColumn()) {
$sql = sprintf('%s %s NOT NULL,', $primaryKey->getColumns(), $primaryKey->isAutoIncrement() ? 'serial' : 'integer');
}
foreach ($this->table->getColumns() as $column) {
if ($column instanceof CustomColumn) {
$columnType = $column->getType();
} else {
$columnType = $columnTypeMapper->getNative($column->getType());
}
$sql .= sprintf('%s %s%s %s %s,'
, $column->getName()
, $columnType
, $this->getTypeConstraints($column)
, $column->isNotNull() ? 'NOT NULL' : ''
, null === $column->getDefault() ? '' : 'DEFAULT'. ' ' . $this->addQuotesIfNeeded($column, $column->getDefault())
);
}
return rtrim($sql, ',');
} | php | {
"resource": ""
} |
q247570 | CreateTableCommand.getColumnComments | validation | private function getColumnComments()
{
$escapement = new Escapement();
$comments = '';
foreach ($this->table->getColumns() as $column) {
$columnDescription = $column->getDescription();
if (!empty($columnDescription)) {
$comments .= sprintf("COMMENT ON COLUMN %s.%s IS '%s';",
$escapement->escape($this->table->getQualifiedName()),
$escapement->escape($column->getName()),
$columnDescription);
}
}
return $comments;
} | php | {
"resource": ""
} |
q247571 | Config.registerEffect | validation | private function registerEffect(string $type, string $class) : void
{
if (\class_exists($class)) {
$interfaces = \class_implements($class);
if (\in_array(Effect::class, $interfaces, true)) {
$this->effectsMap[$type] = $class;
} else {
throw new ConfigException("Class {$class} don't implement interface " . Effect::class);
}
} else {
throw new ConfigException("Class {$class} not found");
}
} | php | {
"resource": ""
} |
q247572 | Config.registerPostProcessor | validation | private function registerPostProcessor(string $type, string $class) : void
{
if (\class_exists($class)) {
$interfaces = \class_implements($class);
if (\in_array(PostProcessor::class, $interfaces, true)) {
$this->postProcessorsMap[$type] = $class;
} else {
throw new ConfigException("Class {$class} don't implement interface " . PostProcessor::class);
}
} else {
throw new ConfigException("Class {$class} not found");
}
} | php | {
"resource": ""
} |
q247573 | CompletePurchaseRequest.createResponse | validation | public function createResponse($status, $errorCode, $errorDescription)
{
$document = new \DOMDocument('1.0', 'utf-8');
$document->formatOutput = false;
$response = $document->appendChild(
$document->createElement('SVSPurchaseStatusNotificationResponse')
);
$result = $response->appendChild(
$document->createElement('TransactionResult')
);
$result->appendChild(
$document->createElement('Description', $errorDescription)
);
$result->appendChild(
$document->createElement('Code', $errorCode)
);
$response->appendChild(
$document->createElement('Status', $status)
);
$authentication = $response->appendChild(
$document->createElement('Authentication')
);
$checksum = $authentication->appendChild(
$document->createElement('Checksum', $this->getMerchantPassword())
);
$checksum->nodeValue = $this->calculateXmlChecksum($document->saveXML());
return $document->saveXML();
} | php | {
"resource": ""
} |
q247574 | CompletePurchaseRequest.validateChecksum | validation | public function validateChecksum($string)
{
$xml = new \SimpleXMLElement($string);
$checksum = (string) $xml->Authentication->Checksum;
$original = str_replace($checksum, $this->getMerchantPassword(), $string);
return md5($original) == $checksum;
} | php | {
"resource": ""
} |
q247575 | AbstractSaxHandler.attachHandlers | validation | private function attachHandlers($parser)
{
$onElementStart = \Closure::bind(function ($parser, $name, $attributes) {
$name = $this->normalize($name);
$this->currentElement = $name;
$this->dataBuffer = null;
$this->stackSize++;
$this->onElementStart($parser, $name, $attributes);
}, $this);
$onElementEnd = \Closure::bind(function ($parser, $name) {
$name = $this->normalize($name);
$this->currentElement = null;
$this->stackSize--;
if (null !== $this->dataBuffer) {
$this->onElementData($parser, $this->dataBuffer);
}
$this->dataBuffer = null;
$this->onElementEnd($parser, $name);
}, $this);
$onElementData = \Closure::bind(function ($parser, $data) {
$this->dataBuffer .= $data;
}, $this);
$onNamespaceDeclarationStart = \Closure::bind(function ($parser, $prefix, $uri) {
$this->namespaces[$prefix] = rtrim($uri, '/');
$this->onNamespaceDeclarationStart($parser, $prefix, $uri);
}, $this);
$onNamespaceDeclarationEnd = \Closure::bind(function ($parser, $prefix) {
$this->onNamespaceDeclarationEnd($parser, $prefix);
}, $this);
xml_set_element_handler($parser, $onElementStart, $onElementEnd);
xml_set_character_data_handler($parser, $onElementData);
xml_set_start_namespace_decl_handler($parser, $onNamespaceDeclarationStart);
xml_set_end_namespace_decl_handler($parser, $onNamespaceDeclarationEnd);
return $this;
} | php | {
"resource": ""
} |
q247576 | Flash.create | validation | public function create($title, $message, $level = 'info', $key = 'flash_message')
{
$this->session->flash($key, [
'title' => $title,
'message' => $message,
'level' => $level,
]);
return $this;
} | php | {
"resource": ""
} |
q247577 | Flash.overlay | validation | public function overlay($title, $message, $level = 'info', $key = 'flash_message')
{
return $this->create($title, $message, $level, $key.'_overlay');
} | php | {
"resource": ""
} |
q247578 | SaxParser.parse | validation | public function parse(SaxHandlerInterface $saxHandler, $xmlDocument)
{
$xmlDocument = ($xmlDocument instanceof StreamInterface) ? $xmlDocument : $this->getDocumentStream($xmlDocument);
return $saxHandler->parse($xmlDocument);
} | php | {
"resource": ""
} |
q247579 | SaxParser.factory | validation | public static function factory($streamClass = 'GuzzleHttp\\Psr7\\Stream')
{
return new static([
new ResourceAdapter($streamClass),
new DomDocumentAdapter($streamClass),
new SimpleXmlAdapter($streamClass),
new StringAdapter($streamClass),
]);
} | php | {
"resource": ""
} |
q247580 | SaxParser.getDocumentStream | validation | private function getDocumentStream($xmlDocument)
{
/**
* @var StreamAdapterInterface $streamAdapter
*/
foreach ($this->streamAdapters as $streamAdapter) {
if ($streamAdapter->supports($xmlDocument)) {
return $streamAdapter->convert($xmlDocument);
}
}
throw new RuntimeException(sprintf('Suitable XML document stream adapter is not registered for XML document of type "%s".', is_object($xmlDocument) ? get_class($xmlDocument) : gettype($xmlDocument)));
} | php | {
"resource": ""
} |
q247581 | ControllerExtension.SearchForm | validation | public function SearchForm()
{
// If we have setup objects to search
if (count(Searchable::config()->objects)) {
$searchText = "";
if ($this->owner->request && $this->owner->request->getVar('Search')) {
$searchText = $this->owner->request->getVar('Search');
}
$fields = FieldList::create(
TextField::create('Search', false, $searchText)
->setAttribute("placeholder", _t('Searchable.Search', 'Search'))
);
$actions = FieldList::create(
FormAction::create('results', _t('Searchable.Go', 'Go'))
);
$template_class = Searchable::config()->template_class;
$results_page = Injector::inst()->create($template_class);
$form = Form::create(
$this->owner,
'SearchForm',
$fields,
$actions
)->setFormMethod('get')
->setFormAction($results_page->Link())
->setTemplate('ilateral\SilverStripe\Searchable\Includes\SearchForm')
->disableSecurityToken();
$this->owner->extend("updateSearchForm", $form);
return $form;
}
} | php | {
"resource": ""
} |
q247582 | Enum.init | validation | final public static function init() : void
{
$className = static::class;
self::$cache[$className] = [];
$reflectionClass = self::objectClass();
$constructorParams = static::constructorArgs();
$ordinal = 0;
foreach ($reflectionClass->getProperties(ReflectionProperty::IS_STATIC) as $property) {
if ($property->isPublic()) {
$name = $property->getName();
$instance = self::newInstance($name, $constructorParams);
$property->setValue($instance);
self::$cache[$className][$name] = $instance;
self::$ordinals[$className][$name] = $ordinal++;
}
}
} | php | {
"resource": ""
} |
q247583 | Enum.valueOf | validation | final public static function valueOf($name) : self
{
$className = static::class;
Preconditions::checkArgument(
array_key_exists($className, self::$cache) && array_key_exists($name, self::$cache[$className]),
"The enum '%s' type has no constant with name '%s'",
$className,
$name
);
return self::$cache[$className][$name];
} | php | {
"resource": ""
} |
q247584 | Enum.equals | validation | public function equals(ObjectInterface $object = null) : bool
{
return $object instanceof static && $object->name === $this->name;
} | php | {
"resource": ""
} |
q247585 | Iterators.from | validation | public static function from(Traversable $traversable) : Iterator
{
Preconditions::checkArgument($traversable instanceof Iterator || $traversable instanceof IteratorAggregate);
return $traversable instanceof Iterator
? $traversable
: Iterators::from($traversable->getIterator());
} | php | {
"resource": ""
} |
q247586 | Iterators.filterBy | validation | public static function filterBy(Iterator $unfiltered, string $className) : Iterator
{
return self::filter($unfiltered, Predicates::instance($className));
} | php | {
"resource": ""
} |
q247587 | Iterators.concat | validation | public static function concat(Iterator $a, Iterator $b) : Iterator
{
return self::concatIterators(new ArrayIterator([$a, $b]));
} | php | {
"resource": ""
} |
q247588 | Iterators.all | validation | public static function all(Iterator $iterator, callable $predicate) : bool
{
while ($iterator->valid()) {
if (!Predicates::call($predicate, $iterator->current())) {
return false;
}
$iterator->next();
}
return true;
} | php | {
"resource": ""
} |
q247589 | Iterators.indexOf | validation | public static function indexOf(Iterator $iterator, callable $predicate) : int
{
$i = 0;
while ($iterator->valid()) {
if (Predicates::call($predicate, $iterator->current())) {
return $i;
}
$i++;
$iterator->next();
}
return -1;
} | php | {
"resource": ""
} |
q247590 | Iterators.limit | validation | public static function limit(Iterator $iterator, int $limitSize) : Iterator
{
Preconditions::checkArgument(0 <= $limitSize);
return new NoRewindNecessaryLimitIterator($iterator, $limitSize);
} | php | {
"resource": ""
} |
q247591 | Iterators.get | validation | public static function get(Iterator $iterator, int $position)
{
Iterators::advance($iterator, $position);
if (!$iterator->valid()) {
throw new OutOfBoundsException("The requested index '{$position}' is invalid");
}
return $iterator->current();
} | php | {
"resource": ""
} |
q247592 | Iterators.size | validation | public static function size(Iterator $iterator)
{
$result = 0;
Iterators::each($iterator, function () use (&$result) {
$result++;
});
return $result;
} | php | {
"resource": ""
} |
q247593 | Iterators.paddedPartition | validation | public static function paddedPartition(Iterator $iterator, int $size) : Iterator
{
Preconditions::checkArgument(0 < $size);
return new PartitionIterator($iterator, $size, true);
} | php | {
"resource": ""
} |
q247594 | Iterators.tryFind | validation | public static function tryFind(Iterator $iterator, callable $predicate) : Optional
{
return Optional::ofNullable(self::find($iterator, $predicate));
} | php | {
"resource": ""
} |
q247595 | ConvertibleTimestamp.setFakeTime | validation | public static function setFakeTime( $fakeTime ) {
if ( is_string( $fakeTime ) ) {
$fakeTime = (int)static::convert( TS_UNIX, $fakeTime );
}
if ( is_int( $fakeTime ) ) {
$fakeTime = function () use ( $fakeTime ) {
return $fakeTime;
};
}
$old = static::$fakeTimeCallback;
static::$fakeTimeCallback = $fakeTime ? $fakeTime : null;
return $old;
} | php | {
"resource": ""
} |
q247596 | ConvertibleTimestamp.setTimestamp | validation | public function setTimestamp( $ts = false ) {
$m = [];
$da = [];
$strtime = '';
// We want to catch 0, '', null... but not date strings starting with a letter.
if ( !$ts || $ts === "\0\0\0\0\0\0\0\0\0\0\0\0\0\0" ) {
$uts = self::time();
$strtime = "@$uts";
} elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
# TS_DB
} elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
# TS_EXIF
} elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
# TS_MW
} elseif ( preg_match( '/^(-?\d{1,13})$/D', $ts, $m ) ) {
# TS_UNIX
$strtime = "@{$m[1]}"; // http://php.net/manual/en/datetime.formats.compound.php
} elseif ( preg_match( '/^(-?\d{1,13})(\.\d+)$/D', $ts, $m ) ) {
# TS_UNIX_MICRO
// Not supported with @, so we need a hack
$strtime = 'unixmicro';
} elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
# TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
$strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
str_replace( '+00:00', 'UTC', $ts ) );
} elseif ( preg_match(
'/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z?$/',
$ts,
$da
) ) {
# TS_ISO_8601
} elseif ( preg_match(
'/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z?$/',
$ts,
$da
) ) {
# TS_ISO_8601_BASIC
} elseif ( preg_match(
'/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',
$ts,
$da
) ) {
# TS_POSTGRES
} elseif ( preg_match(
'/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',
$ts,
$da
) ) {
# TS_POSTGRES
} elseif ( preg_match(
# Day of week
'/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' .
# dd Mon yyyy
'\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' .
# hh:mm:ss
'[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S',
$ts
) ) {
# TS_RFC2822, accepting a trailing comment.
# See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
# The regex is a superset of rfc2822 for readability
$strtime = strtok( $ts, ';' );
} elseif ( preg_match( '/^[A-Z][a-z]{5,8}, \d\d-[A-Z][a-z]{2}-\d{2} \d\d:\d\d:\d\d/', $ts ) ) {
# TS_RFC850
$strtime = $ts;
} elseif ( preg_match( '/^[A-Z][a-z]{2} [A-Z][a-z]{2} +\d{1,2} \d\d:\d\d:\d\d \d{4}/', $ts ) ) {
# asctime
$strtime = $ts;
} else {
throw new TimestampException( __METHOD__ . ": Invalid timestamp - $ts" );
}
if ( !$strtime ) {
$da = array_map( 'intval', $da );
$da[0] = "%04d-%02d-%02dT%02d:%02d:%02d.00+00:00";
$strtime = call_user_func_array( "sprintf", $da );
}
try {
if ( $strtime === 'unixmicro' ) {
$final = DateTime::createFromFormat( 'U.u', $ts, new DateTimeZone( 'GMT' ) );
} else {
$final = new DateTime( $strtime, new DateTimeZone( 'GMT' ) );
}
} catch ( Exception $e ) {
throw new TimestampException( __METHOD__ . ': Invalid timestamp format.', $e->getCode(), $e );
}
if ( $final === false ) {
throw new TimestampException( __METHOD__ . ': Invalid timestamp format.' );
}
$this->timestamp = $final;
} | php | {
"resource": ""
} |
q247597 | ConvertibleTimestamp.convert | validation | public static function convert( $style = TS_UNIX, $ts ) {
try {
$ct = new static( $ts );
return $ct->getTimestamp( $style );
} catch ( TimestampException $e ) {
return false;
}
} | php | {
"resource": ""
} |
q247598 | ConvertibleTimestamp.getTimestamp | validation | public function getTimestamp( $style = TS_UNIX ) {
if ( !isset( self::$formats[$style] ) ) {
throw new TimestampException( __METHOD__ . ': Illegal timestamp output type.' );
}
$output = $this->timestamp->format( self::$formats[$style] );
if ( $style == TS_RFC2822 ) {
$output .= ' GMT';
}
if ( $style == TS_MW && strlen( $output ) !== 14 ) {
throw new TimestampException( __METHOD__ . ': The timestamp cannot be represented in ' .
'the specified format' );
}
return $output;
} | php | {
"resource": ""
} |
q247599 | ConvertibleTimestamp.setTimezone | validation | public function setTimezone( $timezone ) {
try {
$this->timestamp->setTimezone( new DateTimeZone( $timezone ) );
} catch ( Exception $e ) {
throw new TimestampException( __METHOD__ . ': Invalid timezone.', $e->getCode(), $e );
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.