_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q247800 | Phone_number.get_number_type | validation | public function get_number_type($phone_number = '', $region = NULL)
{
$inputParams = array(
'phone_number' => $phone_number,
'region' => $region
);
$this->debug->info(__FUNCTION__, 'Input Params: ', $inputParams);
if (empty($phone_number)) {
$this->debug->warning(__FUNCTION__, 'Phone Number input is Empty!');
return NULL;
}
$phone_number = trim($phone_number);
try {
$phoneNumberUtil = PhoneNumberUtil::getInstance();
$use_region = NULL !== $region ? strtoupper($region) : self::DEFAULT_REGION;
$phoneNumberObject = $phoneNumberUtil->parse(trim($phone_number), $use_region);
$result = $phoneNumberUtil->getNumberType($phoneNumberObject);
$this->debug->debug(__FUNCTION__, 'Use REGION: ' . $use_region);
$this->debug->info(__FUNCTION__, 'Final Result: ' . $result);
return $result;
}
catch (\Exception $e) {
$message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();
$this->debug->error(__FUNCTION__, $message);
return NULL;
}
} | php | {
"resource": ""
} |
q247801 | RelPath.splitPath | validation | public static function splitPath( $path ) {
$fragments = [];
while ( true ) {
$cur = dirname( $path );
if ( $cur[0] === DIRECTORY_SEPARATOR ) {
// dirname() on Windows sometimes returns a leading backslash, but other
// times retains the leading forward slash. Slashes other than the leading one
// are returned as-is, and therefore do not need to be touched.
// Furthermore, don't break on *nix where \ is allowed in file/directory names.
$cur[0] = '/';
}
if ( $cur === $path || ( $cur === '.' && basename( $path ) === $path ) ) {
break;
}
$fragment = trim( substr( $path, strlen( $cur ) ), '/' );
if ( !$fragments ) {
$fragments[] = $fragment;
} elseif ( $fragment === '..' && basename( $cur ) !== '..' ) {
$cur = dirname( $cur );
} elseif ( $fragment !== '.' ) {
$fragments[] = $fragment;
}
$path = $cur;
}
if ( $path !== '' ) {
$fragments[] = trim( $path, '/' );
}
return array_reverse( $fragments );
} | php | {
"resource": ""
} |
q247802 | RelPath.getRelativePath | validation | public static function getRelativePath( $path, $start = null ) {
if ( $start === null ) {
// @codeCoverageIgnoreStart
$start = getcwd();
}
// @codeCoverageIgnoreEnd
if ( substr( $path, 0, 1 ) !== '/' || substr( $start, 0, 1 ) !== '/' ) {
return false;
}
$pathParts = self::splitPath( $path );
$countPathParts = count( $pathParts );
$startParts = self::splitPath( $start );
$countStartParts = count( $startParts );
$commonLength = min( $countPathParts, $countStartParts );
for ( $i = 0; $i < $commonLength; $i++ ) {
if ( $startParts[$i] !== $pathParts[$i] ) {
break;
}
}
$relList = ( $countStartParts > $i )
? array_fill( 0, $countStartParts - $i, '..' )
: [];
$relList = array_merge( $relList, array_slice( $pathParts, $i ) );
return implode( '/', $relList ) ?: '.';
} | php | {
"resource": ""
} |
q247803 | RelPath.joinPath | validation | public static function joinPath( $base, $path ) {
if ( substr( $path, 0, 1 ) === '/' ) {
// $path is absolute.
return $path;
}
if ( substr( $base, 0, 1 ) !== '/' ) {
// $base is relative.
return false;
}
$pathParts = self::splitPath( $path );
$resultParts = self::splitPath( $base );
while ( ( $part = array_shift( $pathParts ) ) !== null ) {
switch ( $part ) {
case '.':
break;
case '..':
if ( count( $resultParts ) > 1 ) {
array_pop( $resultParts );
}
break;
default:
$resultParts[] = $part;
break;
}
}
return implode( '/', $resultParts );
} | php | {
"resource": ""
} |
q247804 | Phone_telco.carrier_data | validation | public function carrier_data($carrier = '', $field_output = '')
{
$inputParams = array(
'carrier' => $carrier,
'field_output' => $field_output
);
$field_output = strtolower($field_output);
$this->debug->info(__FUNCTION__, 'Input Params: ', $inputParams);
try {
$vnCarrierData = DataRepository::getData('vn_carrier_data');
$this->debug->debug(__FUNCTION__, 'VN Carrier All Data: ', $vnCarrierData);
if (array_key_exists($carrier, $vnCarrierData)) {
$isCarrier = $vnCarrierData[$carrier];
$this->debug->debug(__FUNCTION__, 'Is Carrier Data: ', $isCarrier);
if (array_key_exists($field_output, $isCarrier)) {
$result = $isCarrier[$field_output];
$this->debug->info(__FUNCTION__, 'Final Result get Field : ' . $field_output, $result);
return $result;
}
if ($field_output = 'full') {
$this->debug->info(__FUNCTION__, 'Final Result get Field : ' . $field_output, $isCarrier);
return $isCarrier;
}
}
}
catch (\Exception $e) {
$message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();
$this->debug->error(__FUNCTION__, $message);
return NULL;
}
return NULL;
} | php | {
"resource": ""
} |
q247805 | ClassLoader.load | validation | public static function load($class)
{
$class = static::normalizeClass($class);
foreach (static::$directories as $directory) {
if (Sbp::fileExists($directory.DIRECTORY_SEPARATOR.$class, $path)) {
require_once $path;
return true;
}
}
} | php | {
"resource": ""
} |
q247806 | ClassLoader.register | validation | public static function register($prepend = true, $callback = null, $app = null)
{
if (!static::$registered) {
static::$registered = spl_autoload_register(array('\\Sbp\\Laravel\\ClassLoader', 'load'), true, $prepend);
if (is_null($app)) {
$app = __DIR__.'/../../../../../../app';
}
if (!file_exists($app.'/storage') || !is_writable($app.'/storage')) {
throw new SbpException("Laravel app and/or writable storage directory not found at $app, please specify the path with the following code:\nSbp\\Laravel\\ClassLoader::register(true, 'sha1', \$laravelAppPath)");
}
Sbp::writeIn(Sbp::SAME_DIR);
Sbp::fileExists($app.'/routes');
$storage = $app.'/storage/sbp';
if (!file_exists($storage)) {
if (mkdir($storage, 0777)) {
file_put_contents($storage.'/.gitignore', "*\n!.gitignore");
}
}
Sbp::writeIn($storage, $callback);
}
} | php | {
"resource": ""
} |
q247807 | Api.request | validation | public function request(array $data)
{
$data = array_replace($this->config, $data);
return $this->client->callRequest($data);
} | php | {
"resource": ""
} |
q247808 | SmsLink.getLink | validation | public function getLink($phone_number = '', $body = '')
{
if (!empty($body)) {
$body = "?body=" . $body;
}
$sms = 'sms:' . trim($phone_number . $body);
return $sms;
} | php | {
"resource": ""
} |
q247809 | MigrationCommand.createMigration | validation | protected function createMigration()
{
//Create the migration
$app = app();
$migrationFiles = array(
$this->laravel->path."/database/migrations/*_create_countries_table.php" => 'countries::generators.migration',
);
$seconds = 0;
foreach ($migrationFiles as $migrationFile => $outputFile) {
if (sizeof(glob($migrationFile)) == 0) {
$migrationFile = str_replace('*', date('Y_m_d_His', strtotime('+' . $seconds . ' seconds')), $migrationFile);
$fs = fopen($migrationFile, 'x');
if ($fs) {
$output = "<?php\n\n" .$app['view']->make($outputFile)->with('table', 'countries')->render();
fwrite($fs, $output);
fclose($fs);
} else {
return false;
}
$seconds++;
}
}
//Create the seeder
$seeder_file = $this->laravel->path."/database/seeds/CountriesSeeder.php";
$output = "<?php\n\n" .$app['view']->make('countries::generators.seeder')->render();
if (!file_exists( $seeder_file )) {
$fs = fopen($seeder_file, 'x');
if ($fs) {
fwrite($fs, $output);
fclose($fs);
} else {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q247810 | SessionDataHolder.unsetData | validation | public function unsetData():void
{
foreach (array_keys($this->data) as $var) {
if (!in_array($var, self::ALL_HEADERS)) {
unset($this->data[$var]);
}
}
} | php | {
"resource": ""
} |
q247811 | Log.getMessage | validation | public function getMessage()
{
return '['.$this->prefix.( $this->context === null ? '' : (' - '.get_class($this->context)) ).'] ' . $this->msg;
} | php | {
"resource": ""
} |
q247812 | FileHandler.getIdPath | validation | private function getIdPath(string $id):string
{
if (!preg_match("/^[a-z0-9]$/ui", $id)) {
throw new HandlerException(
sprintf("The session id %s is invalid", $id),
$this
);
}
return $this->savePath."/$id.session";
} | php | {
"resource": ""
} |
q247813 | CountriesServiceProvider.registerCommands | validation | protected function registerCommands()
{
$this->app['command.countries.migration'] = $this->app->share(function($app)
{
return new MigrationCommand($app);
});
$this->commands('command.countries.migration');
} | php | {
"resource": ""
} |
q247814 | Path.examine | validation | protected static function examine($part, array &$array, $path_relative, $allow_escape = false)
{
if($part === '.')
{
return;
}
if($part !== '..')
{
$array[] = $part;
return;
}
// $part == '..', handle escaping.
$last = end($array);
if($last === '..')
{ // Escaping is allowed and we're already on the run.
$array[] = $part;
return;
}
if($last !== false)
{ // $last element exists - move up the stack.
array_pop($array);
return;
}
if(!$path_relative)
{ // Path is not relative - skip updir.
return;
}
if(!$allow_escape)
throw new \UnexpectedValueException('Attempt to traverse outside the root directory.');
$array[] = $part;
} | php | {
"resource": ""
} |
q247815 | SessionManager.isSessionValid | validation | private function isSessionValid(SessionDataHolder $session, ServerRequestInterface $request):bool
{
// if the session is expired
if (($lastReq = $session->getLastRequestTime())
&& ($lastReq + $this->getExpire() * 60) < time())
{
return false;
}
// if the client IP changed
if ($this->getValidateClientIp()
&& ($clientIp = $session->getClientIp())
&& isset($request->getServerParams()['REMOTE_ADDR'])
&& $clientIp != $request->getServerParams()['REMOTE_ADDR'])
{
return false;
}
return true;
} | php | {
"resource": ""
} |
q247816 | SessionManager.getSessionCookie | validation | public function getSessionCookie():?SetCookie
{
try {
// envoie du cookie de session
if ($this->isStarted()) {
return new SetCookie(
$this->getName(),
$this->getDataHolder()->getId(),
(time() + $this->getExpire() * 60),
$this->getCookiePath() ?? '/',
$this->getCookieHost() ?? '',
$this->getCookieSecure(),
$this->isCookieHttpOnly()
);
}
// sinon destruction du cookie de session
else {
return SetCookie::thatDeletesCookie($this->getName());
}
}
catch (\Throwable $exception) {
throw new SessionManagerException(
"Error while preparing the session cookie",
$this, null, $exception
);
}
} | php | {
"resource": ""
} |
q247817 | SessionManager.stop | validation | public function stop():void
{
if ($this->isStarted()) {
$this->getHandler()->destroy($this->getDataHolder()->getId());
$this->dataHolder = null;
}
} | php | {
"resource": ""
} |
q247818 | Countries.getList | validation | public function getList($sort = null)
{
//Get the countries list
$countries = $this->getCountries();
//Sorting
$validSorts = array(
'name',
'fullname',
'iso_3166_2',
'iso_3166_3',
'capital',
'citizenship',
'currency',
'currency_code',
'calling_code'
);
if (!is_null($sort) && in_array($sort, $validSorts)){
uasort($countries, function($a, $b) use ($sort) {
if (!isset($a[$sort]) && !isset($b[$sort])){
return 0;
} elseif (!isset($a[$sort])){
return -1;
} elseif (!isset($b[$sort])){
return 1;
} else {
return strcasecmp($a[$sort], $b[$sort]);
}
});
}
//Return the countries
return $countries;
} | php | {
"resource": ""
} |
q247819 | Url.parse | validation | public function parse($url)
{
$parts = $this->_parse_url($url);
foreach(array('user', 'pass', 'fragment') as $part)
if(isset($parts[$part]))
$parts[$part] = urldecode($parts[$part]);
if(isset($parts['host']))
$parts['host'] = idn_to_utf8($parts['host']);
if(isset($parts['path']))
$parts['path'] = rawurldecode(str_ireplace('%2F', '%252F', $parts['path']));
return $this->setParts($parts);
} | php | {
"resource": ""
} |
q247820 | Url.setParts | validation | public function setParts(array $parts)
{
/** Filter input array */
$parts = array_intersect_key($parts, $this->params);
/** Force port to be numeric.
*
* If it would fail to convert (converts to zero), we will strip it.
*/
if(isset($parts['port']))
$parts['port'] = (int)$parts['port'];
/** Convert query string to ksort()'ed array */
if(isset($parts['query']))
{
$query = $this->_parse_str($parts['query']);
$this->_rksort($query);
$parts['query'] = $query;
}
/** Reset empty replacement parts to null
*
* This simplifies later checks for existence of URL parts.
*/
array_walk(
$parts,
function(&$part, $key)
{
if(is_string($part))
{ /** Use strlen() instead of empty() to account for possible "0" values
*
* Valid case for (f.e.) user/pass parts.
*/
$part = strlen($part) ? $part : null;
}
else
{
$part = $part ?: null;
}
}
);
$self = clone $this;
// Keep URL parts in the same order at all times.
$self->params = array_replace($this->params, $parts);
return $self;
} | php | {
"resource": ""
} |
q247821 | Coordinate3D.fromPolar | validation | public static function fromPolar($length, $ap, $av)
{
return new static($length * cos($ap) * cos($av), $length * sin($ap) * cos($av), $length * sin($av));
} | php | {
"resource": ""
} |
q247822 | Coordinate3D.translate | validation | public function translate($shift, $y = null, $z = null)
{
if($shift instanceof self)
return new static($this->gps['x'] + $shift->gps['x'], $this->gps['y'] + $shift->gps['y'], $this->gps['z'] + $shift->gps['z']);
else
return new static($this->gps['x'] + $shift, $this->gps['y'] + $y, $this->gps['z'] + $z);
} | php | {
"resource": ""
} |
q247823 | SessionMiddleware.getSession | validation | public static function getSession(ServerRequestInterface $request):SessionDataHolder
{
$session = $request->getAttribute(static::REQ_ATTR);
if (!$session instanceof SessionDataHolder) {
throw new SessionMiddlewareException(
"No session object is available in the request attributes"
);
}
return $session;
} | php | {
"resource": ""
} |
q247824 | GSeq.create | validation | public static function create($b, $q, $n = 1)
{
if($n == 1)
return new static($b, $q);
static::ensureValid($n, "Amount of elements must be an integer number bigger than zero.");
return new static($b * (1 - $q) / (1 - pow($q, $n)), $q);
} | php | {
"resource": ""
} |
q247825 | GSeq.sum | validation | public function sum($n, $m = 0)
{
if($m > 0)
return $this->sum($n+$m) - $this->sum($m);
static::ensureValid($n);
return $this->b * (1 - pow($this->q, $n)) / (1 - $this->q);
} | php | {
"resource": ""
} |
q247826 | Browser.perform | validation | protected function perform(callable $callback, ...$params)
{
$result = $callback($this->curl, ...$params);
if(curl_errno($this->curl) !== CURLE_OK)
throw new CurlException($this->curl);
if($result === false)
throw new CurlException("Unable to perform $callback - unknown error.");
return $result;
} | php | {
"resource": ""
} |
q247827 | Browser.request | validation | protected function request(array $options)
{
$this->info = null;
$this->setOpt($options);
$result = $this->perform('curl_exec');
$this->info = $this->perform('curl_getinfo');
return $result;
} | php | {
"resource": ""
} |
q247828 | Browser.setOpt | validation | public function setOpt($name, $value = null)
{
if(is_array($name))
{
try
{
$i = 0;
foreach($name as $opt => $value)
{
$this->setOpt($opt, $value);
++$i;
}
}
catch(CurlException $e)
{
throw $e->getCode() ? $e : new CurlException("Set failed at #$i: " . $e->getMessage());
}
}
else
{
try
{
set_error_handler(
function($s, $m, $f, $l, $c = null)
use($name)
{
throw new CurlException("$m (" . CurlOptions::name($name) . ").");
},
\E_WARNING
);
$this->perform('curl_setopt', $name, $value);
}
finally
{
restore_error_handler();
}
}
} | php | {
"resource": ""
} |
q247829 | Browser.get | validation | public function get($url, $method = "GET")
{
return $this->request([
CURLOPT_HTTPGET => true,
CURLOPT_CUSTOMREQUEST => $method ?: "GET",
CURLOPT_URL => "$url",
]);
} | php | {
"resource": ""
} |
q247830 | Browser.post | validation | public function post($url, $data = null, $method = "POST")
{
return $this->request([
CURLOPT_POST => true,
CURLOPT_CUSTOMREQUEST => $method ?: "POST",
CURLOPT_URL => "$url",
CURLOPT_POSTFIELDS => $data ?: '',
]);
} | php | {
"resource": ""
} |
q247831 | Browser.put | validation | public function put($url, $data = null, $len = null, $method = "PUT")
{
return $this->request([
CURLOPT_PUT => true,
CURLOPT_CUSTOMREQUEST => $method ?: "PUT",
CURLOPT_URL => "$url",
CURLOPT_INFILE => $data,
CURLOPT_INFILESIZE => $len,
]);
} | php | {
"resource": ""
} |
q247832 | BustersPhp.asset | validation | protected function asset($type)
{
$busters = $this->checkAndGetBusters();
// get busters.json hash for item of this type mapped down to this type
// only
$bustersOfThisType = array();
foreach ($busters as $key => $value) {
if (strpos($key, $type) !== false) {
$bustersOfThisType[$key] = $value;
}
}
$busterStrings = $this->parseTags($bustersOfThisType, $type);
return implode("\n", $busterStrings);
} | php | {
"resource": ""
} |
q247833 | BustersPhp.checkAndGetBusters | validation | protected function checkAndGetBusters()
{
// if no bustersJson, exception
if ($this->fileSystem->fileExists($this->config['bustersJsonPath']) === false) {
throw new LengthException('busters json not found.');
}
// get busters json and decode it
$bustersJson = $this->fileSystem->getFile($this->config['bustersJsonPath']);
if ($bustersJson == '') {
throw new UnderflowException('busters json is empty.');
}
$busters = json_decode($bustersJson);
// is it valid json?
if (json_last_error() !== JSON_ERROR_NONE) {
throw new UnexpectedValueException('bustersJson is invalid JSON.');
}
return $busters;
} | php | {
"resource": ""
} |
q247834 | BustersPhp.parseTags | validation | protected function parseTags(array $bustersOfThisType, $type)
{
// add to array and implode to string
$busterStrings = array();
foreach ($bustersOfThisType as $fileName => $hash) {
// get config
$template = $this->config[$type.'Template'];
$rootPath = $this->config['rootPath'];
$pathInfo = pathInfo($fileName);
$fileBasePath = $pathInfo['dirname'];
$fileBaseName = $pathInfo['filename'];
// replace stuff
$template = str_replace('{{ROOT_PATH}}', $rootPath, $template);
$template = str_replace('{{HASH}}', $hash, $template);
$template = str_replace('{{FILE_PATH}}', $fileBasePath, $template);
$template = str_replace('{{FILE_NAME}}', $fileBaseName, $template);
$busterStrings[] = $template;
}
return $busterStrings;
} | php | {
"resource": ""
} |
q247835 | Documentation.getMethodDocumentation | validation | public function getMethodDocumentation(\ReflectionMethod $method)
{
$comment = $this->getMethodComment($method);
$summary = $this->getSummary($comment);
$parameters = $this->getParameters($comment);
$returnType = $this->getReturnType($comment);
$documentation = [];
if ($summary) {
$documentation['summary'] = $summary;
// If there is no Summary, there CAN NOT be a Description
$description = $this->getDescription($comment);
if ($description) {
$documentation['description'] = $description;
}
}
// These should always show even if they're empty
$documentation['parameters'] = $parameters;
$documentation['returnType'] = $returnType;
return $documentation;
} | php | {
"resource": ""
} |
q247836 | Documentation.getMethodComment | validation | protected function getMethodComment(\ReflectionMethod $method)
{
$lines = preg_split("/((\r?\n)|(\r\n?))/", $method->getDocComment());
$count = count($lines);
foreach ($lines as $i => $line) {
$line = preg_replace('/^\s*(\/\*\*|\*\/?)\s*/', '', $line);
$line = trim($line);
$lines[$i] = $line;
if (!$line && ($i == 0 || $i == $count - 1)) { // If first or last lines are blank
unset($lines[$i]);
}
}
return array_values($lines);
} | php | {
"resource": ""
} |
q247837 | Documentation.getSummary | validation | protected function getSummary(array $lines)
{
$summary = '';
foreach ($lines as $line) {
// Check for blank line
if (!$line) {
// If summary exists break out
if ($summary) {
break;
}
continue;
}
// Check for tag
if ($line[0] == '@') {
break;
}
// Otherwise we're good for summary
$summary .= $line . "\n";
if (substr($line, -1) == '.') {
break;
}
}
return trim($summary);
} | php | {
"resource": ""
} |
q247838 | Documentation.getDescription | validation | protected function getDescription(array $lines)
{
$description = '';
$summaryFound = false;
$summaryPassed = false;
foreach ($lines as $line) {
if ($line && !$summaryPassed) {
$summaryFound = true;
if (substr(trim($line), -1) == '.') {
$summaryPassed = true;
}
continue;
}
if (!$line && $summaryFound && !$summaryPassed) {
$summaryPassed = true;
continue;
}
if ($line && $line[0] == '@') {
break;
}
if ($line && $summaryPassed) {
$description .= $line . "\n";
}
}
return trim($description);
} | php | {
"resource": ""
} |
q247839 | Documentation.getParameters | validation | protected function getParameters(array $lines)
{
$comment = implode("\n", $lines);
preg_match_all('/@param\s([\s\S]+?(?=@))/', $comment, $paramsDoc);
$params = [];
if (isset($paramsDoc[1])) {
foreach ($paramsDoc[1] as $paramDoc) {
// Break up the documentation into 3 parts:
// @param type $name description
// 1. The type
// 2. The name
// 3. The description
$documentation = [];
preg_match('/([^$]+)?\$(\w+)(.+)?/s', $paramDoc, $documentation);
list(/*ignore*/, $type, $name, $description) = $documentation;
// Clean up description
$lines = preg_split("/((\r?\n)|(\r\n?))/", $description);
foreach ($lines as $key => $value) {
$value = preg_replace('/\r/', '', $value);
$value = preg_replace('/^\s+\*/', '', $value);
$value = trim($value);
$lines[$key] = $value;
}
$description = implode("\n", $lines);
// Sort out the values
$params[$name] = [
'type' => trim($type),
'description' => trim($description),
];
}
}
return $params;
} | php | {
"resource": ""
} |
q247840 | Documentation.getReturnType | validation | protected function getReturnType(array $lines)
{
foreach ($lines as $line) {
if (strpos($line, '@return') === 0) {
$type = trim(str_replace('@return', '', $line));
$type = str_replace('$this', 'self', $type);
$type = explode('|', $type);
return $type;
}
}
return [];
} | php | {
"resource": ""
} |
q247841 | ImageBehavior.unlinkFiles | validation | public function unlinkFiles($fileName)
{
$folder = $this->getWebrootFolder();
if ($fileName) {
if (@file_exists($folder . '/' . $fileName)) {
unlink($folder . '/' . $fileName);
}
if (@file_exists($folder . '/' . $this->thumbFolder . '/' . $fileName)) {
unlink($folder . '/' . $this->thumbFolder . '/' . $fileName);
}
if (is_array($this->sizes)) {
$i = 0;
foreach ($this->sizes as $size) {
if (@file_exists($folder . '/' . $i . '/' . $fileName)) {
unlink($folder . '/' . $i . '/' . $fileName);
}
$i++;
}
}
}
} | php | {
"resource": ""
} |
q247842 | TerraHttpClient.buildUrl | validation | protected function buildUrl($url, $params = [])
{
if ($this->useOauth) {
$params['access_token'] = $this->getAccessToken();
}
$params = http_build_query($params);
return $this->baseUrl . $url . '?' . $params;
} | php | {
"resource": ""
} |
q247843 | OAuthToken.make | validation | public function make($key, $secret)
{
$this->credentials['key'] = $key;
$this->credentials['secret'] = $secret;
return $this;
} | php | {
"resource": ""
} |
q247844 | OAuthToken.makeRequestToken | validation | public function makeRequestToken(Response $response)
{
parse_str($response->content(), $params);
$this->validateRequestTokenResponse($params);
$this->credentials['key'] = $params['oauth_token'];
$this->credentials['secret'] = $params['oauth_token_secret'];
$this->credentials['callback_confirmed'] = (isset($params['oauth_callback_confirmed'])) ?
(boolean) $params['oauth_callback_confirmed'] : null;
return $this;
} | php | {
"resource": ""
} |
q247845 | OAuthToken.makeAccessToken | validation | public function makeAccessToken(Response $response)
{
parse_str($response->content(), $params);
$this->validateAccessTokenResponse($params);
$this->credentials['key'] = $params['oauth_token'];
$this->credentials['secret'] = $params['oauth_token_secret'];
$this->credentials['user_id'] = $params['user_id'];
$this->credentials['screen_name'] = $params['screen_name'];
return $this;
} | php | {
"resource": ""
} |
q247846 | OAuthToken.validateRequestTokenResponse | validation | public function validateRequestTokenResponse($params)
{
if (!isset($params['oauth_token']) ||
!isset($params['oauth_token_secret']) ||
empty($params['oauth_token']) ||
empty($params['oauth_token_secret'])) {
throw new InvalidOAuthTokenException('request token');
}
return true;
} | php | {
"resource": ""
} |
q247847 | OAuthToken.validateAccessTokenResponse | validation | public function validateAccessTokenResponse($params)
{
if (!isset($params['oauth_token']) ||
!isset($params['oauth_token_secret']) ||
empty($params['oauth_token']) ||
empty($params['oauth_token_secret'])) {
throw new InvalidOAuthTokenException('access token');
}
return true;
} | php | {
"resource": ""
} |
q247848 | BaseModel.getAll | validation | public static function getAll($offset = null, $limit = null)
{
$query = self::find();
self::addPaginationParameters($query, $offset, $limit);
return $query->all();
} | php | {
"resource": ""
} |
q247849 | BaseModel.getAllProvider | validation | public static function getAllProvider($relatedRecords = [], $sort = [], $limit = null)
{
$query = self::find()->with($relatedRecords)->orderBy($sort);
return self::convertToProvider($query, [], $limit);
} | php | {
"resource": ""
} |
q247850 | BaseModel.getIdByField | validation | public static function getIdByField($field, $value)
{
$result = self::find()->where([$field => $value])->limit(1)->one();
return ($result) ? $result->id : null;
} | php | {
"resource": ""
} |
q247851 | BaseModel.getByCreatedDateRange | validation | public static function getByCreatedDateRange(
$startDate,
$endDate,
$createdAtColumn = 'created_at'
) {
$model = get_called_class();
$model = new $model;
return self::find()
->andWhere(
$model::tableName() . '.' . $createdAtColumn . ' BETWEEN :start_date AND :end_date',
['start_date' => $startDate, 'end_date' => $endDate]
);
} | php | {
"resource": ""
} |
q247852 | BaseModel.getFirstError | validation | public function getFirstError($attribute = null)
{
if (!$this->errors) {
return null;
} elseif (is_null($attribute)) {
$errors = $this->getErrors();
reset($errors);
$firstError = current($errors);
$arrayKeys = array_keys($firstError);
$error = $firstError[$arrayKeys[0]];
return $error;
}
return parent::getFirstError($attribute);
} | php | {
"resource": ""
} |
q247853 | BaseModel.getDropdownMap | validation | public static function getDropdownMap($keyAttribute, $valueAttribute, array $default = [])
{
$map = ArrayHelper::map(self::getActive(), $keyAttribute, $valueAttribute);
if ($default) {
$map = array_merge($default, $map);
}
return $map;
} | php | {
"resource": ""
} |
q247854 | Provider.settings | validation | public function settings($setting = null)
{
if (!is_null($setting)) {
return isset($this->settings[$setting]) ? $this->settings[$setting] : null;
}
return $this->settings;
} | php | {
"resource": ""
} |
q247855 | Provider.validateSettings | validation | protected function validateSettings($settings)
{
if (!is_array($settings)) {
throw new InvalidProviderSettingsException();
}
$intersection = array_intersect(array_keys($settings), $this->mandatory);
return count($intersection) === count($this->mandatory);
} | php | {
"resource": ""
} |
q247856 | ReflectionController.hasEndpoint | validation | public function hasEndpoint($method, $endpointName)
{
$methodName = $this->parseEndpointName($method, $endpointName);
return $this->reflection->hasMethod($methodName);
} | php | {
"resource": ""
} |
q247857 | ReflectionController.getEndpointResult | validation | public function getEndpointResult($method, $endpointName, Request $request)
{
$methodName = $this->parseEndpointName($method, $endpointName);
if (!$this->reflection->hasMethod($methodName)) {
throw new \RuntimeException("{$this->reflection->getName()}::{$methodName} does not exist");
}
$reflectionMethod = $this->reflection->getMethod($methodName);
return $reflectionMethod->invokeArgs(
$this->controller,
$this->mapRequestToArguments($reflectionMethod, $request)
);
} | php | {
"resource": ""
} |
q247858 | ReflectionController.mapRequestToArguments | validation | protected function mapRequestToArguments(\ReflectionMethod $method, Request $request)
{
$map = [];
foreach ($method->getParameters() as $parameter) {
$value = $request->getParameter(
$parameter->getName(),
$parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null
);
if ($parameter->getClass() &&
$parameter->getClass()->implementsInterface(Deserializable::class)
) {
/** @var Deserializable $deserializable */
$value = $parameter->getClass()
->newInstanceWithoutConstructor()
->ayeAyeDeserialize($value);
$className = $parameter->getClass()->getName();
if (!is_object($value) || get_class($value) !== $className) {
throw new \RuntimeException("$className::ayeAyeDeserialize did not return an instance of itself");
}
}
$map[$parameter->getName()] = $value;
}
return $map;
} | php | {
"resource": ""
} |
q247859 | ReflectionController.parseEndpointName | validation | protected function parseEndpointName($method, $endpoint)
{
$endpoint = str_replace(' ', '', ucwords(str_replace(['-', '+', '%20'], ' ', $endpoint)));
$method = strtolower($method);
return $method . $endpoint . 'Endpoint';
} | php | {
"resource": ""
} |
q247860 | ReflectionController.hasChildController | validation | public function hasChildController($controllerName)
{
$methodName = $this->parseControllerName($controllerName);
return $this->reflection->hasMethod($methodName);
} | php | {
"resource": ""
} |
q247861 | ReflectionController.getChildController | validation | public function getChildController($controllerName)
{
$methodName = $this->parseControllerName($controllerName);
if (!$this->reflection->hasMethod($methodName)) {
throw new \RuntimeException("{$this->reflection->getName()}::{$methodName} does not exist");
}
$controller = $this->reflection->getMethod($methodName)->invokeArgs($this->controller, []);
if (!is_object($controller) || !$controller instanceof Controller) {
throw new \RuntimeException("{$this->reflection->getName()}::{$methodName} did not return a Controller");
}
return $controller;
} | php | {
"resource": ""
} |
q247862 | Custom_Rating.set_submenu | validation | public function set_submenu() {
$submenu = Module::CustomRatingGrifus()->getOption( 'submenu' );
WP_Menu::add(
'submenu',
$submenu['custom-rating-grifus'],
[ $this, 'render' ],
[ $this, 'add_scripts' ],
[ $this, 'add_styles' ]
);
} | php | {
"resource": ""
} |
q247863 | Custom_Rating.add_styles | validation | public function add_styles() {
$css = App::EFG()->getOption( 'assets', 'css' );
WP_Register::add(
'style',
$css['extensionsForGrifusAdmin']
);
WP_Register::add(
'style',
Module::CustomRatingGrifus()->getOption(
'assets', 'css', 'customRatingGrifusAdmin'
)
);
} | php | {
"resource": ""
} |
q247864 | AccessToken.parseResponse | validation | public function parseResponse(Response $response)
{
$json = $response->json();
/*
* The returned response must not be in JSON
* format, unless it is an error.
*/
if (!is_null($json)) {
if (isset($json->error)) {
$error = $json->error;
throw new AccessTokenException($error->type.': '.$error->message, $error->code);
}
}
$token = $response->content();
return $this->parseToken($token);
} | php | {
"resource": ""
} |
q247865 | HandlerContainer.process | validation | public function process(Request $request) : Response
{
$router = $request->attributes->get('router');
$next = next($this->middlewareStack);
if ($next instanceof Middleware) {
$router->log("Router: Calling Middleware: %s", get_class($next));
$response = $next->process($request, $this);
$router->log("Router: Leaving Middleware: %s", get_class($next));
return $response;
} elseif (is_string($next)) {
$router->log("Router: Calling Middleware: %s", $next);
$response = $router->getMiddleware($next)->process($request, $this);
$router->log("Router: Leaving Middleware: %s", $next);
return $response;
} else {
$params = $request->attributes->get('controller');
// Call controller with request and args
$router->log("Router: Calling Controller: %s@%s", $params->className, $params->method);
$return = (new $params->className($params->container))->{$params->method}($request, ...array_values($params->args));
$router->log("Router: Controller Left");
// Instantly return Response objects
if ($return instanceof Response) {
return $return;
}
// If not a string (or something easily castable to a string) assume Json -> JsonResponse
if (is_array($return) or is_object($return)) {
return new JsonResponse(
$return,
Response::HTTP_OK,
array('content-type' => 'application/json')
);
}
// Strings, and other primitives.
return new Response(
$return,
Response::HTTP_OK,
array('content-type' => 'text/html')
);
}
} | php | {
"resource": ""
} |
q247866 | Store.put | validation | public function put($key, $data, $duration = null)
{
return $this->cache->put(
$key,
$data,
($duration) ?: $this->duration
);
} | php | {
"resource": ""
} |
q247867 | Router.processRequest | validation | public function processRequest(Request $request, Controller $controller, array $requestChain = null)
{
$reflectionController = $this->getControllerReflector()->reflectController($controller);
// If the request chain is null as apposed to empty, we can get it from the request
if (is_null($requestChain)) {
$requestChain = $request->getRequestChain();
}
// Get the next element of the front of the chain
$nextLink = array_shift($requestChain);
if ($nextLink) {
// If the next element represents a controller, recurse with the new controller and remaining chain
if ($reflectionController->hasChildController($nextLink)) {
return $this->processRequest(
$request,
$reflectionController->getChildController($nextLink),
$requestChain
);
}
// If the next element represents an endpoint, call it, passing in the request data
if ($reflectionController->hasEndpoint($request->getMethod(), $nextLink)) {
$data = $reflectionController->getEndpointResult($request->getMethod(), $nextLink, $request);
$this->setStatus($reflectionController->getStatus());
return $data;
}
// If we had another element but it doesn't represent anything, throw an exception.
$message = "Could not find controller or endpoint matching '$nextLink'";
throw new Exception($message, 404);
}
// If there were no more links in the chain, call the index endpoint if there is one.
// Index endpoints will prevent automated automatic documentation, which may be undesirable. See below.
if ($reflectionController->hasEndpoint($request->getMethod(), 'index')) {
$data = $reflectionController->getEndpointResult($request->getMethod(), 'index', $request);
$this->setStatus($reflectionController->getStatus());
return $data;
}
// Generate documentation for the current controller and return it.
return $reflectionController->getDocumentation();
} | php | {
"resource": ""
} |
q247868 | JSendResponse.getData | validation | public function getData($defaultValue = null)
{
return ArrayHelper::getValue($this->parsedResponse, self::RESPONSE_DATA_PARAM, $defaultValue);
} | php | {
"resource": ""
} |
q247869 | JSendResponse.get | validation | public function get($key, $default = null)
{
return ArrayHelper::getValue(
$this->parsedResponse,
sprintf('%s.%s', self::RESPONSE_DATA_PARAM, $key),
$default
);
} | php | {
"resource": ""
} |
q247870 | Facebook.authenticate | validation | public function authenticate()
{
$state = $this->makeState();
$this->store->put($state, $this->settings);
return $this->redirect->to($this->authURL($state));
} | php | {
"resource": ""
} |
q247871 | Facebook.callback | validation | public function callback($input)
{
if (isset($input['error'])) {
throw new AuthenticationException($input['error'].':'.$input['error_description']);
}
if (!isset($input['code']) || empty($input['code'])) {
throw new AuthenticationException('invalid code');
}
if (!isset($input['state']) || empty($input['state'])) {
throw new AuthenticationException('invalid state');
}
if (!$this->store->has($input['state'])) {
throw new AuthenticationException('state expired');
}
$access_token = $this->requestAccessToken($input['code']);
return $this->requestProfile($access_token);
} | php | {
"resource": ""
} |
q247872 | Facebook.authURL | validation | public function authURL($state)
{
$url = $this->settings['authentication_url'];
$params = [
'client_id' => $this->settings('api_key'),
'redirect_uri' => $this->settings('redirect_uri'),
'scope' => $this->settings('permissions'),
'state' => $state,
];
return $url.'?'.http_build_query($params);
} | php | {
"resource": ""
} |
q247873 | Facebook.requestAccessToken | validation | public function requestAccessToken($code)
{
if (!$code || empty($code)) {
throw new InvalidFacebookCodeException();
}
$request = [
'url' => $this->settings['token_url'],
'params' => [
'client_id' => $this->settings['api_key'],
'redirect_uri' => $this->settings['redirect_uri'],
'client_secret' => $this->settings['secret'],
'code' => $code,
'format' => 'json',
],
];
return $this->access_token->make($this->http->get($request));
} | php | {
"resource": ""
} |
q247874 | Facebook.requestProfile | validation | public function requestProfile(AccessTokenInterface $access_token)
{
$request = [
'url' => $this->settings['api_url'].$this->settings['profile_uri'],
'params' => ['access_token' => $access_token->token()],
];
return $this->parseProfileResponse($this->http->get($request), $access_token);
} | php | {
"resource": ""
} |
q247875 | Facebook.parseProfileResponse | validation | public function parseProfileResponse(Response $response, AccessTokenInterface $access_token)
{
$profile = $response->json();
if (gettype($profile) !== 'object') {
throw new InvalidProfileException();
}
if (isset($profile->error)) {
$error = $profile->error;
throw new InvalidProfileException($error->type.': '.$error->message, $error->code);
}
$profile->access_token = $access_token->token();
return $this->profile->instantiate($profile, $this->name);
} | php | {
"resource": ""
} |
q247876 | Bootstrap.bootstrap | validation | public function bootstrap($app)
{
Yii::setAlias('@wavecms', '@vendor/mrstroz/yii2-wavecms');
if ($app->id === 'app-backend' || $app->id === 'app-frontend') {
/** Set extra aliases required in Wavecms with shared hostings*/
Yii::setAlias('@frontWeb',
str_replace('/admin', '', Yii::getAlias('@web'))
);
Yii::setAlias('@frontWebroot',
str_replace('/public/admin', '/public', Yii::getAlias('@webroot'))
);
}
/** Set backend language based on user lang (Must be done before define translations */
if ($app->id === 'app-backend') {
if (!Yii::$app->user->isGuest) {
Yii::$app->language = Yii::$app->user->identity->lang;
}
}
$this->initTranslations();
/** @var Module $module */
if ($app->hasModule('wavecms') && ($module = $app->getModule('wavecms')) instanceof Module) {
if ($app instanceof ConsoleApplication) {
$module->controllerNamespace = 'mrstroz\wavecms\commands';
} else {
$module->controllerNamespace = 'mrstroz\wavecms\controllers';
if ($app->id === 'app-backend') {
/** @var string errorAction Set error action */
Yii::$app->errorHandler->errorAction = $module->errorAction;
/** Set required components */
$app->set('wavecms', [
'class' => 'mrstroz\wavecms\WavecmsComponent',
'languages' => $module->languages
]);
$app->set('cacheFrontend', [
'class' => 'yii\caching\FileCache',
'cachePath' => Yii::getAlias('@frontend') . '/runtime/cache'
]);
$app->set('settings', [
'class' => 'yii2mod\settings\components\Settings',
]);
Yii::$app->assetManager->appendTimestamp = true;
Yii::$app->i18n->translations['yii2mod.settings'] = [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@yii2mod/settings/messages'
];
$this->initContainer($module);
$this->initLanguages();
$this->initParams();
$this->initRoutes($app, $module);
$this->initNavigation();
}
}
}
} | php | {
"resource": ""
} |
q247877 | Bootstrap.initLanguages | validation | protected function initLanguages()
{
if (!Yii::$app->user->isGuest) {
Yii::$app->language = Yii::$app->user->identity->lang;
}
if (!isset(Yii::$app->wavecms))
throw new InvalidConfigException(Yii::t('wavecms/main', 'Component "wavecms" not defined in config.php'));
if (!count(Yii::$app->wavecms->languages))
throw new InvalidConfigException(Yii::t('wavecms/main', 'Property "languages" is not defined in config file for component "wavecms"'));
if (!Yii::$app->session->get('editedLanguage')) {
Yii::$app->session->set('editedLanguage', Yii::$app->wavecms->languages[0]);
}
Yii::$app->wavecms->editedLanguage = Yii::$app->session->get('editedLanguage');
} | php | {
"resource": ""
} |
q247878 | Bootstrap.initParams | validation | protected function initParams()
{
Yii::$app->view->params['h1'] = Yii::t('wavecms/main', '<i>Not set</i>');
Yii::$app->view->params['buttons_top'] = [];
Yii::$app->view->params['buttons_btm'] = [];
Yii::$app->view->params['buttons_sublist'] = [];
} | php | {
"resource": ""
} |
q247879 | Bootstrap.initContainer | validation | protected function initContainer($module)
{
$map = [];
$defaultClassMap = [
/* FORMS */
'AddPermissionForm' => AddPermissionForm::class,
'AssignRoleForm' => AssignRoleForm::class,
'LoginForm' => LoginForm::class,
'RequestPasswordResetForm' => RequestPasswordResetForm::class,
'ResetPasswordForm' => ResetPasswordForm::class,
/* MODELS */
'AuthAssignment' => AuthAssignment::class,
'AuthItem' => AuthItem::class,
'AuthItemChild' => AuthItemChild::class,
'AuthRule' => AuthRule::class,
'Message' => Message::class,
'SourceMessage' => SourceMessage::class,
'User' => User::class,
/* QUERIES */
'MessageQuery' => MessageQuery::class,
'SourceMessageQuery' => SourceMessageQuery::class,
'UserQuery' => UserQuery::class,
/* SEARCH */
'SourceMessageSearch' => SourceMessageSearch::class,
'UserSearch' => UserSearch::class,
];
$routes = [
'mrstroz\\wavecms\\forms' => [
'AddPermissionForm',
'AssignRoleForm',
'LoginForm',
'RequestPasswordResetForm',
'ResetPasswordForm',
],
'mrstroz\\wavecms\\models' => [
'AuthAssignment',
'AuthItem',
'AuthItemChild',
'AuthRule',
'Message',
'SourceMessage',
'User',
],
'mrstroz\\wavecms\\models\\query' => [
'MessageQuery',
'SourceMessageQuery',
'UserQuery',
],
'mrstroz\\wavecms\\models\\search' => [
'SourceMessageSearch',
'UserSearch',
]
];
$mapping = array_merge($defaultClassMap, $module->classMap);
foreach ($mapping as $name => $definition) {
$map[$this->getContainerRoute($routes, $name) . "\\$name"] = $definition;
}
$di = Yii::$container;
foreach ($map as $class => $definition) {
/** Check if definition does not exist in container. */
if (!$di->has($class)) {
$di->set($class, $definition);
}
}
} | php | {
"resource": ""
} |
q247880 | Bootstrap.initNavigation | validation | protected function initNavigation()
{
Yii::$app->params['nav']['wavecms_dashboard'] = [
'label' => FontAwesome::icon('home') . Yii::t('wavecms/main', 'Dashboard'),
'url' => ['/'],
'position' => 500
];
Yii::$app->params['nav']['wavecms_user'] = [
'label' => FontAwesome::icon('users') . Yii::t('wavecms/user', 'Users'),
'url' => 'javascript: ;',
'options' => [
'class' => 'drop-down'
],
'permission' => 'wavecms-user',
'position' => 9000,
'items' => [
[
'label' => FontAwesome::icon('user') . Yii::t('wavecms/user', 'List of users'),
'url' => ['/wavecms/user/index']
],
[
'label' => FontAwesome::icon('key') . Yii::t('wavecms/user', 'Roles'),
'url' => ['/wavecms/role/index']
],
]
];
Yii::$app->params['nav']['wavecms_settings'] = [
'label' => FontAwesome::icon('cog') . Yii::t('wavecms/main', 'Settings'),
'url' => 'javascript: ;',
'options' => [
'class' => 'drop-down'
],
'permission' => 'wavecms-settings',
'position' => 10000,
'items' => [
[
'label' => FontAwesome::icon('flag') . Yii::t('wavecms/main', 'Translations'),
'url' => ['/wavecms/translation/index']
],
[
'label' => FontAwesome::icon('database') . Yii::t('wavecms/main', 'Cache'),
'url' => ['/wavecms/settings/cache']
]
]
];
} | php | {
"resource": ""
} |
q247881 | Bootstrap.getContainerRoute | validation | private function getContainerRoute(array $routes, $name)
{
foreach ($routes as $route => $names) {
if (in_array($name, $names, false)) {
return $route;
}
}
throw new Exception("Unknown configuration class name '{$name}'");
} | php | {
"resource": ""
} |
q247882 | Action.init | validation | public function init()
{
$this->query = $this->controller->query;
if ($this->query) {
$modelClass = Yii::createObject($this->query->modelClass);
$this->modelClass = $modelClass;
$this->tableName = $modelClass::tableName();
}
parent::init(); // TODO: Change the autogenerated stub
} | php | {
"resource": ""
} |
q247883 | Utils.encodeId | validation | public static function encodeId($id, $salt, $hashLength = self::MIN_HASH_LENGTH)
{
$hashIds = new Hashids($salt, $hashLength);
return $hashIds->encode($id);
} | php | {
"resource": ""
} |
q247884 | Utils.decodeId | validation | public static function decodeId($hash, $salt, $hashLength = self::MIN_HASH_LENGTH)
{
$hashIds = new Hashids($salt, $hashLength);
return ArrayHelper::getValue($hashIds->decode($hash), '0');
} | php | {
"resource": ""
} |
q247885 | Utils.getStatusHtml | validation | public static function getStatusHtml($status, $extraClasses = '', $baseClass = 'label', $tag = 'span')
{
$status = strtolower($status);
$statusHyphenated = implode('-', explode(' ', $status));
$class = trim("{$baseClass} {$baseClass}-$statusHyphenated $extraClasses");
return Html::tag($tag, $status, ['class' => $class]);
} | php | {
"resource": ""
} |
q247886 | Utils.formatPhoneNumberToInternationalFormat | validation | public static function formatPhoneNumberToInternationalFormat($countryCode, $number, $numberLength)
{
$actualNumber = substr($number, -($numberLength), $numberLength);
if (!$actualNumber) {
return $number;
}
return '+' . $countryCode . $actualNumber;
} | php | {
"resource": ""
} |
q247887 | Twitter.authenticate | validation | public function authenticate()
{
$request_token = $this->oauth->getRequestToken($this->settings, $this->consumer, $this->token);
$auth_url = $this->settings('auth_api_url').$this->settings('authentication_uri');
$auth_url .= '?'.http_build_query(['oauth_token' => $request_token->key]);
return $this->redirect->to($auth_url);
} | php | {
"resource": ""
} |
q247888 | Twitter.callback | validation | public function callback($input)
{
if (isset($input['denied'])) {
throw new AuthenticationCanceledException();
}
if (!isset($input['oauth_token']) || !isset($input['oauth_verifier'])) {
throw new InvalidOAuthTokenException('missing oauth_token or oauth_verifier');
}
$verifier_token = $this->token->verifier($input['oauth_token'], $input['oauth_verifier']);
$access_token = $this->oauth->getAccessToken($this->settings, $this->consumer, $verifier_token);
return $this->getProfile($access_token);
} | php | {
"resource": ""
} |
q247889 | Launcher.create_tables | validation | public function create_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'efg_custom_rating';
if ( $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" ) != $table_name ) {
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
post_id mediumint(9) NOT NULL,
ip varchar(45) NOT NULL,
vote int(2) NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
} | php | {
"resource": ""
} |
q247890 | FileBehavior.uploadFile | validation | public function uploadFile($event)
{
if (!array_key_exists($this->attribute, $event->sender->attributes)) {
throw new InvalidConfigException(Yii::t('wavecms/main', 'Attribute {attribute} not found in model {model}', ['attribute' => $this->attribute, 'model' => $event->sender->className()]));
}
$oldFile = false;
if (isset($event->sender->oldAttributes[$this->attribute])) {
$oldFile = $event->sender->oldAttributes[$this->attribute];
}
$uploadedFile = UploadedFile::getInstance($event->sender, $this->attribute);
if (null !== $uploadedFile && $uploadedFile->size !== 0) {
$folder = $this->getWebrootFolder();
if ($oldFile) {
$this->unlinkFiles($oldFile);
}
$baseName = $uploadedFile->baseName;
$fileName = $baseName . '.' . $uploadedFile->extension;
while (@file_exists($folder . '/' . $fileName)) {
$baseName .= '_';
$fileName = $baseName . '.' . $uploadedFile->extension;
}
FileHelper::createDirectory($folder, 0777);
$uploadedFile->saveAs($folder . '/' . $fileName);
$event->sender->{$this->attribute} = $fileName;
} else {
if (Yii::$app->request->post($this->attribute . '_file_delete')) {
$this->unlinkFiles($oldFile);
$event->sender->{$this->attribute} = null;
} else {
$event->sender->{$this->attribute} = $oldFile;
}
}
} | php | {
"resource": ""
} |
q247891 | FileBehavior.unlinkFiles | validation | public function unlinkFiles($fileName)
{
$folder = $this->getWebrootFolder();
if ($fileName) {
if (@file_exists($folder . '/' . $fileName)) {
unlink($folder . '/' . $fileName);
}
}
} | php | {
"resource": ""
} |
q247892 | ExtraDataProcessor.appendExtraFields | validation | private function appendExtraFields(array $extra)
{
foreach ($this->extraData as $key => $value) {
$extra[$key] = $value;
}
return $extra;
} | php | {
"resource": ""
} |
q247893 | ExtraDataProcessor.addExtraData | validation | public function addExtraData(array $extraData = [])
{
foreach ($extraData as $key => $data) {
$this->extraData[$key] = $data;
}
} | php | {
"resource": ""
} |
q247894 | ExtraDataProcessor.removeExtraData | validation | public function removeExtraData(array $extraDataKeys = [])
{
foreach ($extraDataKeys as $key) {
if (array_key_exists($key, $this->extraData)) {
unset($this->extraData[$key]);
}
}
} | php | {
"resource": ""
} |
q247895 | OAuth.getRequestToken | validation | public function getRequestToken($settings,
OAuthConsumerInterface $consumer,
OAuthTokenInterface $token)
{
$url = $settings['auth_api_url'].$settings['request_token_uri'];
$options = ['oauth_callback' => $settings['callback_url']];
$headers = $this->headers($settings, 'POST', $url, $consumer, $token, $options);
// build request
$request = ['url' => $url,'headers' => $headers];
return $this->token->makeRequestToken($this->http->post($request));
} | php | {
"resource": ""
} |
q247896 | OAuth.normalizeHeaders | validation | public function normalizeHeaders($params)
{
$out = '';
foreach ($params as $key => $param) {
$out .= $key.'="'.rawurlencode(trim($param)).'",';
}
return rtrim($out, ',');
} | php | {
"resource": ""
} |
q247897 | Api.go | validation | public function go()
{
$response = $this->getResponse();
try {
$request = $this->getRequest();
$response->setWriterFactory(
$this->getWriterFactory()
);
$response->setRequest(
$request
);
$response->setBodyData(
$this->getRouter()->processRequest(
$this->getRequest(),
$this->controller
)
);
$response->setStatus(
$this->controller->getStatus()
);
} catch (AyeAyeException $e) {
$this->log(LogLevel::INFO, $e->getPublicMessage());
$this->log(LogLevel::ERROR, $e->getMessage(), ['exception' => $e]);
$response->setBodyData($e->getPublicMessage());
$response->setStatus(new Status($e->getCode()));
} catch (\Exception $e) {
$status = new Status(500);
$this->log(LogLevel::CRITICAL, $e->getMessage(), ['exception' => $e]);
$response->setBodyData($status->getMessage());
$response->setStatus($status);
}
// Ultimate fail safe
try {
$response->prepareResponse();
} catch (\Exception $e) {
$this->log(LogLevel::CRITICAL, $e->getMessage(), ['exception' => $e]);
return $this->createFailSafeResponse();
}
return $response;
} | php | {
"resource": ""
} |
q247898 | Api.createFailSafeResponse | validation | protected function createFailSafeResponse()
{
$status = new Status(500);
$response = new Response();
$response->setRequest(new Request());
$response->setWriter(new Json());
$response->setStatus($status);
$response->setBodyData($status->getMessage());
return $response;
} | php | {
"resource": ""
} |
q247899 | Exception.jsonSerialize | validation | public function jsonSerialize()
{
$serialized = [
'message' => $this->getPublicMessage(),
'code' => $this->getCode(),
];
if ($this->getPrevious() instanceof $this) {
/** @var static $previous */
$previous = $this->getPrevious();
$serialized['previous'] = $previous->jsonSerialize();
}
return $serialized;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.