_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q254000 | MediaLink.parse | validation | public static function parse(&$string) {
$media = array(
"objects" => array(), //All @mentions, you can mention anytype of object
"hashes" => array(), //You can use any kind of hashes
"links" => array(), //Will attempt to fetch link descriptions where possible
);
//Match mentions, urls, and hastags
preg_match_all('#@([\\d\\w]+)#', $string, $mentions);
preg_match_all('/#([\\d\\w]+)/', $string, $hashTags);
preg_match_all('/((http|https|ftp|ftps)\:\/\/)([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?([a-zA-Z0-9\-\.]+)\.([a-zA-Z]{2,3})(\:[0-9]{2,5})?(\/([a-z0-9+\$_-]\.?)+)*\/?/', $data, $openLinks);
//print_R($mentions);
//print_R($hashTags);
//print_R($openLinks);
//$string = "parsed";
return $media;
} | php | {
"resource": ""
} |
q254001 | Dispatcher.dispatch | validation | public static function dispatch($eventName, Event $event)
{
if (null === self::$dispatcher) {
return $event;
}
self::$dispatcher->dispatch($eventName, $event);
DataLogger::log(sprintf('The "%s" event was dispatched', $eventName));
if ($event->getAbort()) {
DataLogger::log(sprintf('The "%s" event was aborted', $eventName), DataLogger::ERROR);
throw new EventAbortedException($event->getAbortMessage());
}
return $event;
} | php | {
"resource": ""
} |
q254002 | Browser.checkBrowsers | validation | protected function checkBrowsers()
{
return (
// well-known, well-used
// Special Notes:
// (1) Opera must be checked before FireFox due to the odd
// user agents used in some older versions of Opera
// (2) WebTV is strapped onto Internet Explorer so we must
// check for WebTV before IE
// (3) (deprecated) Galeon is based on Firefox and needs to be
// tested before Firefox is tested
// (4) OmniWeb is based on Safari so OmniWeb check must occur
// before Safari
// (5) Netscape 9+ is based on Firefox so Netscape checks
// before FireFox are necessary
$this->checkBrowserWebTv() ||
$this->checkBrowserInternetExplorer() ||
$this->checkBrowserOpera() ||
$this->checkBrowserGaleon() ||
$this->checkBrowserNetscapeNavigator9Plus() ||
$this->checkBrowserFirefox() ||
$this->checkBrowserChrome() ||
$this->checkBrowserOmniWeb() ||
// common mobile
$this->checkBrowserAndroid() ||
$this->checkBrowseriPad() ||
$this->checkBrowseriPod() ||
$this->checkBrowseriPhone() ||
$this->checkBrowserBlackBerry() ||
$this->checkBrowserNokia() ||
// common bots
$this->checkBrowserGoogleBot() ||
$this->checkBrowserMSNBot() ||
$this->checkBrowserBingBot() ||
$this->checkBrowserSlurp() ||
// check for facebook external hit when loading URL
$this->checkFacebookExternalHit() ||
// WebKit base check (post mobile and others)
$this->checkBrowserSafari() ||
// everyone else
$this->checkBrowserNetPositive() ||
$this->checkBrowserFirebird() ||
$this->checkBrowserKonqueror() ||
$this->checkBrowserIcab() ||
$this->checkBrowserPhoenix() ||
$this->checkBrowserAmaya() ||
$this->checkBrowserLynx() ||
$this->checkBrowserShiretoko() ||
$this->checkBrowserIceCat() ||
$this->checkBrowserIceweasel() ||
$this->checkBrowserW3CValidator() ||
$this->checkBrowserMozilla() /* Mozilla is such an open standard that you must check it last */
);
} | php | {
"resource": ""
} |
q254003 | Cookie.set | validation | public function set($name, $value, $expire = 0, $path = null, $domain = null, $secure = false, $httpOnly = false) {
/*
* La cookie expira al cerrar el navegador por defecto, pero si
* en $expire se pasa un -1 la cookie tendra una duracion de 1 año.
*/
if ($expire === -1) {
$expire = time() + 3600 * 24 * 365;
} else {
$expire *= 60;
}
// Convierto el valor a base64
$value = base64_encode($value);
// Crea la cookie
if ($path != null) {
if ($domain != null) {
if ($secure) {
if ($httpOnly) {
setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly);
} else {
setcookie($name, $value, $expire, $path, $domain, $secure);
}
} else {
setcookie($name, $value, $expire, $path, $domain);
}
} else {
setcookie($name, $value, $expire, $path);
}
} else {
setcookie($name, $value, $expire);
}
} | php | {
"resource": ""
} |
q254004 | Cookie.remove | validation | public function remove($name, $path = null, $domain = null, $secure = false, $httpOnly = false) {
if ($this->exists($name)) {
$expire = time() - (3600 * 24 * 365);
$this->set($name, '', $expire, $path, $domain, $secure, $httpOnly);
}
} | php | {
"resource": ""
} |
q254005 | Headers.add | validation | public function add(string $header): self
{
foreach ($this->getAll() as $tmp) {
if ($tmp === $header) {
throw new Exception("The '{$header}' header has already been added.");
}
}
$this->headerList[] = $header;
return self::$instance;
} | php | {
"resource": ""
} |
q254006 | Headers.addByHttpCode | validation | public function addByHttpCode(int $code): self
{
$serverProtocol = filter_input(
\INPUT_SERVER,
'SERVER_PROTOCOL',
\FILTER_SANITIZE_STRING
);
$protocol = !empty($serverProtocol) ? $serverProtocol : 'HTTP/1.1';
$sHeader = "{$protocol} {$code} ".self::getHTTPExplanationByCode($code);
return $this->add($sHeader);
} | php | {
"resource": ""
} |
q254007 | Headers.run | validation | public function run(): void
{
$this->isRan = true;
foreach ($this->getAll() as $header) {
header($header);
}
} | php | {
"resource": ""
} |
q254008 | Registry.set | validation | public function set(string $key, $value): self
{
$this->store[$key] = $value;
return self::$instance;
} | php | {
"resource": ""
} |
q254009 | Registry.get | validation | public function get(string $key = '')
{
if (empty($key)) {
return $this->store;
} else {
return $this->store[$key] ?? null;
}
} | php | {
"resource": ""
} |
q254010 | Module.getDb | validation | public function getDb()
{
if (is_null($this->_db)) {
if (!isset($this->dbConfig['class'])) {
$this->dbConfig['class'] = 'cascade\components\dataInterface\connectors\db\Connection';
}
$this->_db = Yii::createObject($this->dbConfig);
$this->_db->open();
}
if (empty($this->_db) || !$this->_db->isActive) {
throw new Exception("Unable to connect to foreign database.");
}
return $this->_db;
} | php | {
"resource": ""
} |
q254011 | Email.authorize | validation | public function authorize(RecordInterface &$user, $remember = false)
{
// Call default authorize behaviour
if (parent::authorize($user, $remember)) {
// If remember flag is passed - save it
if ($remember) {
// Create token
$token = $user[$this->dbHashEmailField].(time()+($this->cookieTime)).$user[$this->dbHashPasswordField];
// Set db accessToken
$user[$this->dbAccessToken] = $token;
$user->save();
// Set cookies with token
$expiry = time()+($this->cookieTime);
$cookieData = array( "token" => $token, "expiry" => $expiry );
setcookie('_cookie_accessToken', serialize($cookieData), $expiry);
}
}
} | php | {
"resource": ""
} |
q254012 | Email.authorizeWithEmail | validation | public function authorizeWithEmail($hashedEmail, $hashedPassword, $remember = null, & $user = null)
{
// Status code
$result = new EmailStatus(0);
// Check if this email is registered
if (dbQuery($this->dbTable)->where($this->dbHashEmailField, $hashedEmail)->first($user)) {
$dbTable = $this->dbTable;
$hashPasswordField = $dbTable::$_attributes[$this->dbHashPasswordField];
// Check if passwords match
if ($user[$hashPasswordField] === $hashedPassword) {
$result = new EmailStatus(EmailStatus::SUCCESS_EMAIL_AUTHORIZE);
// Login with current user
$this->authorize($user, $remember);
} else { // Wrong password
$result = new EmailStatus(EmailStatus::ERROR_EMAIL_AUTHORIZE_WRONGPWD);
}
} else { // Email not found
$result = new EmailStatus(EmailStatus::ERROR_EMAIL_AUTHORIZE_NOTFOUND);
}
// Call external authorize handler if present
if (is_callable($this->authorizeHandler)) {
// Call external handler - if it fails - return false
if (!call_user_func_array($this->authorizeHandler, array(&$user, &$result))) {
$result = new EmailStatus(EmailStatus::ERROR_EMAIL_AUTHORIZE_HANDLER);
}
}
return $result;
} | php | {
"resource": ""
} |
q254013 | Email.register | validation | public function register($email, $hashedPassword = null, & $user = null, $valid = false)
{
// Status code
$result = new EmailStatus(0);
// Check if this email is not already registered
if (!dbQuery($this->dbTable)->cond($this->dbEmailField, $email)->first($user)) {
/**@var $user RecordInterface */
// If user object is NOT passed
if (!isset($user)) {
// Create empty db record instance
$user = new $this->dbTable(false);
}
$user[$this->dbEmailField] = $email;
$user[$this->dbHashEmailField] = $this->hash($email);
// If password is passed
if (isset($hashedPassword)) {
$user[$this->dbHashPasswordField] = $hashedPassword;
} else { // Generate random password
$user[$this->dbHashPasswordField] = $this->generatePassword();
}
// If this email is not valid or confirmed
if (!$valid) {
$user[$this->dbConfirmField] = $this->hash($email.time());
} else { // Email is already confirmed
$user[$this->dbConfirmField] = 1;
}
$activeField = $this->dbActiveField;
$createdField = $this->dbCreatedField;
$user->$activeField = 1;
$user->$createdField = date('Y-m-d H:i:s');
// Save object to database
$user->save();
// Class default authorization
$this->authorize($user);
// Everything is OK
$result = new EmailStatus(EmailStatus::SUCCESS_EMAIL_REGISTERED);
} else { // Email not found
$result = new EmailStatus(EmailStatus::ERROR_EMAIL_REGISTER_FOUND);
}
// Call external register handler if present
if (is_callable($this->registerHandler)) {
// Call external handler - if it fails - return false
if (!call_user_func_array($this->registerHandler, array(&$user, &$result))) {
$result = new EmailStatus(EmailStatus::ERROR_EMAIL_REGISTER_HANDLER);
}
}
return $result;
} | php | {
"resource": ""
} |
q254014 | Email.__async_authorize | validation | public function __async_authorize($hashEmail = null, $hashPassword = null)
{
$result = array('status' => '0');
// Get hashed email field by all possible methods
if (!isset($hashEmail)) {
if (isset($_POST) && isset($_POST[$this->dbHashEmailField])) {
$hashEmail = $_POST[$this->dbHashEmailField];
} elseif (isset($_GET) && isset($_GET[$this->dbHashEmailField])) {
$hashEmail = $_GET[$this->dbHashEmailField];
} else {
$result['email_error'] = "\n".'['.$this->dbHashEmailField.'] field is not passed';
}
}
// Get hashed password field by all possible methods
if (!isset($hashPassword)) {
if (isset($_POST) && isset($_POST[$this->dbHashPasswordField])) {
$hashPassword = $_POST[$this->dbHashPasswordField];
} elseif (isset($_GET) && isset($_GET[$this->dbHashPasswordField])) {
$hashPassword = $_GET[$this->dbHashPasswordField];
} else {
$result['email_error'] = "\n".'['.$this->dbHashPasswordField.'] field is not passed';
}
}
// If we have authorization data
if (isset($hashEmail) && isset($hashPassword)) {
$hashEmail = $this->hash($hashEmail);
$hashPassword = $this->hash($hashPassword);
/**@var EmailStatus $authorizeResult Perform generic registration*/
$authorizeResult = $this->authorizeWithEmail($hashEmail, $hashPassword);
// Check if it was successfull
if ($authorizeResult->code == EmailStatus::SUCCESS_EMAIL_AUTHORIZE) {
$result['status'] = '1';
}
// Save email register status
$result[self::RESPONSE_STATUS_TEXTFIELD] = $authorizeResult->text;
$result[self::RESPONSE_STATUS_FIELD] = $authorizeResult->code;
$result = array_merge($result, $authorizeResult->response);
}
return $result;
} | php | {
"resource": ""
} |
q254015 | Email.__authorize | validation | public function __authorize($hashEmail = null, $hashPassword = null)
{
// Perform asynchronous authorization
$asyncResult = $this->__async_authorize($hashEmail, $hashPassword);
if ($asyncResult) {
}
} | php | {
"resource": ""
} |
q254016 | FileSystemMapper.read | validation | protected function read($namespace)
{
$file = $this->adapter->getFileName($namespace);
if (!$this->fileSystem->has($file)) {
return [];
}
return $this->adapter->onRead($this->fileSystem->read($file));
} | php | {
"resource": ""
} |
q254017 | FileSystemMapper.write | validation | protected function write($namespace, array $data)
{
$file = $this->adapter->getFileName($namespace);
$contents = $this->adapter->prepareForWriting($data);
if (!$this->fileSystem->has($file)) {
$this->fileSystem->write($file, $contents);
}
$this->fileSystem->update($file, $contents);
} | php | {
"resource": ""
} |
q254018 | GridBuilder.render | validation | public function render(){
$sort=0;
$query=$this->request->getQuery();
if(isset($query['sort']) && isset($this->columns[$query['sort']])){
$sort=$query['sort'];
}
return $this->formatter->render($this->columns
,$this->getRecords()
,$this->dataManager->getTotalCount(),$this->limit,$this->page,$sort);
} | php | {
"resource": ""
} |
q254019 | Widget.getRefreshInstructions | validation | public function getRefreshInstructions()
{
$i = [];
$i['type'] = 'widget';
$i['systemId'] = $this->collectorItem->systemId;
$i['recreateParams'] = $this->recreateParams;
if ($this->section) {
$i['section'] = $this->section->systemId;
}
return $i;
} | php | {
"resource": ""
} |
q254020 | Widget.getState | validation | public function getState($key, $default = null)
{
return Yii::$app->webState->get($this->stateKeyName($key), $default);
} | php | {
"resource": ""
} |
q254021 | Widget.setState | validation | public function setState($key, $value)
{
return Yii::$app->webState->set($this->stateKeyName($key), $value);
} | php | {
"resource": ""
} |
q254022 | Encryptor.decrypt | validation | private function decrypt($encrypted, $appId)
{
try {
$key = $this->getAESKey();
$ciphertext = base64_decode($encrypted, true);
$iv = substr($key, 0, 16);
$decrypted = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);
} catch (BaseException $e) {
throw new EncryptionException($e->getMessage(), EncryptionException::ERROR_DECRYPT_AES);
}
try {
$result = $this->decode($decrypted);
if (strlen($result) < 16) {
return '';
}
$content = substr($result, 16, strlen($result));
$listLen = unpack('N', substr($content, 0, 4));
$xmlLen = $listLen[1];
$xml = substr($content, 4, $xmlLen);
$fromAppId = trim(substr($content, $xmlLen + 4));
} catch (BaseException $e) {
throw new EncryptionException($e->getMessage(), EncryptionException::ERROR_INVALID_XML);
}
if ($fromAppId !== $appId) {
throw new EncryptionException('Invalid appId.', EncryptionException::ERROR_INVALID_APPID);
}
$dataSet = json_decode($xml, true);
if ($dataSet && (JSON_ERROR_NONE === json_last_error())) {
// For mini-program JSON formats.
// Convert to XML if the given string can be decode into a data array.
$xml = XML::build($dataSet);
}
return $xml;
} | php | {
"resource": ""
} |
q254023 | ArrayIntersections.getAll | validation | public function getAll() {
if (is_null($this->intersections)) {
$this->intersections = [];
if ($this->arraysSize >= 2) {
$this->createIntersections();
}
}
return $this->intersections;
} | php | {
"resource": ""
} |
q254024 | ArrayIntersections.createIntersections | validation | protected function createIntersections() {
$totalNumberOfCombinations = min(pow(2, $this->arraysSize), $this->maxNumberOfCombinations);
$maskGenerator = new BitMaskGenerator($this->arraysSize, 2);
$i = 0;
$noresult = 0;
while ($i < $totalNumberOfCombinations && $noresult < $totalNumberOfCombinations && $mask = $maskGenerator->getNextMask()) {
if (!$this->isNoResultMask($mask)) {
$i++;
$this->generateIntersection($mask);
continue;
}
$noresult++;
}
if (!is_null($this->intersections)) {
uasort($this->intersections, function ($a, $b) {
return count($b) - count($a);
});
}
} | php | {
"resource": ""
} |
q254025 | ArrayIntersections.isNoResultMask | validation | protected function isNoResultMask($mask) {
foreach ($this->noResultMasks as $noresultMask) {
if ($mask === $noresultMask) {
return TRUE; // @codeCoverageIgnore
}
if (($mask & $noresultMask) === $noresultMask) {
$this->noResultMasks[] = $mask;
return TRUE;
}
}
return FALSE;
} | php | {
"resource": ""
} |
q254026 | ArrayIntersections.generateIntersection | validation | protected function generateIntersection($combinationMask) {
$combination = [];
foreach (str_split($combinationMask) as $key => $indicator) {
if ($indicator) {
$combination[] = $this->arrays[$this->arrayKeys[$key]];
}
}
$intersection = call_user_func_array('array_intersect_assoc', $combination);
if (count($intersection) >= $this->threshold) {
$this->intersections[] = $intersection;
return;
}
$this->noResultMasks[] = $combinationMask;
} | php | {
"resource": ""
} |
q254027 | Module.getConfig | validation | public function getConfig()
{
return [
'form_elements' => [
'aliases' => [
'checkbox' => Element\Checkbox::class,
'Checkbox' => Element\Checkbox::class,
'ckeditor' => Element\CkEditor::class,
'ckEditor' => Element\CkEditor::class,
'CkEditor' => Element\CkEditor::class,
'csrf' => Element\Csrf::class,
'Csrf' => Element\Csrf::class,
'date' => Element\Date::class,
'Date' => Element\Date::class,
'datetime' => Element\DateTime::class,
'dateTime' => Element\DateTime::class,
'DateTime' => Element\DateTime::class,
'email' => Element\Email::class,
'Email' => Element\Email::class,
'multipleinput' => Element\MultipleInput::class,
'multipleInput' => Element\MultipleInput::class,
'MultipleInput' => Element\MultipleInput::class,
'password' => Element\Password::class,
'Password' => Element\Password::class,
'rangefilter' => Element\RangeFilter::class,
'rangeFilter' => Element\RangeFilter::class,
'RangeFilter' => Element\RangeFilter::class,
'time' => Element\Time::class,
'Time' => Element\Time::class,
'timezoneselect' => Element\TimeZoneSelect::class,
'timezoneSelect' => Element\TimeZoneSelect::class,
'TimezoneSelect' => Element\TimeZoneSelect::class,
'username' => Element\Username::class,
'Username' => Element\Username::class,
'yesnoselect' => Element\YesNoSelect::class,
'yesNoSelect' => Element\YesNoSelect::class,
'YesNoSelect' => Element\YesNoSelect::class
],
'factories' => [
Element\Checkbox::class => ElementFactory::class,
Element\CkEditor::class => ElementFactory::class,
Element\Csrf::class => ElementFactory::class,
Element\Date::class => ElementFactory::class,
Element\DateTime::class => ElementFactory::class,
Element\Email::class => ElementFactory::class,
Element\MultipleInput::class => ElementFactory::class,
Element\Password::class => ElementFactory::class,
Element\RangeFilter::class => ElementFactory::class,
Element\Time::class => ElementFactory::class,
Element\TimeZoneSelect::class => ElementFactory::class,
Element\Username::class => ElementFactory::class,
Element\YesNoSelect::class => ElementFactory::class
]
]
];
} | php | {
"resource": ""
} |
q254028 | Request.getPut | validation | public static function getPut()
{
$aPut = array();
$rPutResource = fopen("php://input", "r");
while ($sData = fread($rPutResource, 1024)) {
$aSeparatePut = explode('&', $sData);
foreach($aSeparatePut as $sOne) {
$aOnePut = explode('=', $sOne);
$aPut[$aOnePut[0]] = $aOnePut[1];
}
}
return $aPut;
} | php | {
"resource": ""
} |
q254029 | Request.setStatus | validation | public static function setStatus($iCode)
{
if ($iCode === 200) { header('HTTP/1.1 200 Ok'); }
else if ($iCode === 201) { header('HTTP/1.1 201 Created'); }
else if ($iCode === 204) { header("HTTP/1.0 204 No Content"); }
else if ($iCode === 403) { header('HTTP/1.1 403 Forbidden'); }
else if ($iCode === 404) { header('HTTP/1.1 404 Not Found'); }
} | php | {
"resource": ""
} |
q254030 | DataItem.loadForeignObject | validation | protected function loadForeignObject()
{
if ($this->_isLoadingForeignObject) {
throw new RecursionException('Ran into recursion while loading foreign object');
}
$this->_isLoadingForeignObject = true;
if (isset($this->foreignPrimaryKey)) {
$foreignObject = $this->dataSource->getForeignDataModel($this->foreignPrimaryKey);
if ($foreignObject) {
$this->foreignObject = $foreignObject;
}
}
if (empty($this->_foreignObject)) {
\d($this->foreignPrimaryKey);
\d($this->dataSource->name);
throw new MissingItemException('Foreign item could not be found: ' . $this->foreignPrimaryKey);
}
$this->_isLoadingForeignObject = false;
} | php | {
"resource": ""
} |
q254031 | ViewFactory.createView | validation | public static function createView(
string $actionName,
?string $ctrlName = null
): ?View {
$viewsRoot = AppHelper::getInstance()->getComponentRoot('views');
$addPath = '';
if (!empty($ctrlName)) {
$addPath .= \DIRECTORY_SEPARATOR.strtolower($ctrlName);
}
$viewFile = $viewsRoot.$addPath.\DIRECTORY_SEPARATOR
.strtolower($actionName).'.php';
if (is_readable($viewFile)) {
return new View($viewFile);
}
return null;
} | php | {
"resource": ""
} |
q254032 | ViewFactory.createLayout | validation | public static function createLayout(string $layoutName, View $view): ?Layout
{
$layoutsRoot = AppHelper::getInstance()->getComponentRoot('layouts');
$layoutFile = $layoutsRoot.\DIRECTORY_SEPARATOR
.strtolower($layoutName).'.php';
if (is_readable($layoutFile)) {
return new Layout($layoutFile, $view);
}
return null;
} | php | {
"resource": ""
} |
q254033 | ViewFactory.createSnippet | validation | public static function createSnippet(string $snptName): ?Snippet
{
$snptRoot = AppHelper::getInstance()->getComponentRoot('snippets');
$snptFile = $snptRoot.\DIRECTORY_SEPARATOR
.strtolower($snptName).'.php';
if (is_readable($snptFile)) {
return new Snippet($snptFile);
}
return null;
} | php | {
"resource": ""
} |
q254034 | DigitalOcean.create | validation | public function create($params = array())
{
$serverConfig = array_merge($this->defaults, $params);
try {
$response = $this->client->request->post($this->apiEndpoint."/droplets", ['json' => $serverConfig]);
if (202 != $this->client->getStatus($response)) {
throw new Exception('Unable to create server.');
}
} catch (Exception $e) {
echo 'Unable to create server because '.$e->getMessage();
}
return $this->client->getBody($response);
} | php | {
"resource": ""
} |
q254035 | DigitalOcean.delete | validation | public function delete($id)
{
try {
$response = $this->client->request->delete($this->apiEndpoint."/droplets/$id");
$status = $this->client->getStatus($response);
if (204 != $status) {
throw new Exception('Digital Ocean responded that it could not delete it.');
}
return $status;
} catch (Exception $e) {
echo 'Unable to delete server because '.$e->getMessage();
}
} | php | {
"resource": ""
} |
q254036 | DigitalOcean.images | validation | public function images($params)
{
try {
$response = $this->client->request->get($this->apiEndpoint.'/images'.$this->paramsToString($params));
$status = $this->client->getStatus($response);
if (200 != $status) {
throw new Exception('Digital Ocean was not able to successfully provide a list of snapshots.');
}
return $this->client->getBody($response);
} catch (Exception $e) {
echo 'Unable to list snapshots because '.$e->getMessage();
}
} | php | {
"resource": ""
} |
q254037 | IronMQ.clear | validation | public function clear($queue)
{
$this->client->request->post(
$this->apiEndpoint.'/projects/'.$this->params['project'].'/queues/'.$queue.'/clear'
);
} | php | {
"resource": ""
} |
q254038 | Text.mb_str_pad | validation | public function mb_str_pad($input, $length, $string = ' ', $type = STR_PAD_LEFT)
{
return str_pad($input, $length + strlen($input) - mb_strlen($input), $string, $type );
} | php | {
"resource": ""
} |
q254039 | SourceFile.getLines | validation | public function getLines($lazy = true, $raw = false)
{
if (is_null($this->_lines)) {
$file = $this->filePointer;
if (!$file) {
return false;
}
rewind($file);
$this->_lines = [];
$currentLineNumber = 0;
while (($buffer = fgetcsv($this->filePointer, 0, $this->delimeter)) !== false) {
$currentLineNumber++;
if ($currentLineNumber <= $this->skipLines) {
continue;
}
$line = Yii::createObject(['class' => SourceFileLine::className(), 'sourceFile' => $this, 'lineNumber' => $currentLineNumber-1, 'content' => $buffer]);
if ($this->testIgnore($line)) {
continue;
}
$lineId = $line->id;
if (!isset($lineId)) {
continue;
}
$this->_lines[$lineId] = $line;
if ($lazy) {
$line->clean();
}
}
}
return $this->_lines;
} | php | {
"resource": ""
} |
q254040 | SourceFile.getFilePointer | validation | public function getFilePointer()
{
if (!isset($this->_filePointer)) {
ini_set('auto_detect_line_endings', true);
$this->_filePointer = false;
$file = null;
if (isset($this->local) && file_exists($this->local)) {
$file = $this->local;
$pathinfo = pathinfo($this->local);
} elseif (isset($this->url)) {
$fileCacheKey = md5(__CLASS__ . __FUNCTION__ . $this->url);
$fileContent = Yii::$app->fileCache->get($fileCacheKey);
$pathinfo = pathinfo($this->url);
$file = Yii::$app->fileStorage->getTempFile(false, $pathinfo['extension']);
if ($fileContent) {
file_put_contents($file, $fileContent);
} else {
if (!$this->downloadFile($this->url, $file)) {
$file = null;
} else {
Yii::$app->fileCache->set($fileCacheKey, file_get_contents($file), 86400);
}
}
}
if (isset($file)) {
$file = $this->normalizeFile($file);
}
if (file_exists($file)) {
$this->_filePointer = fopen($file, 'r');
}
}
return $this->_filePointer;
} | php | {
"resource": ""
} |
q254041 | SourceFile.getHeaders | validation | public function getHeaders()
{
if (!isset($this->_headers)) {
$this->_headers = $this->readLine(1);
if (!$this->_headers) {
$this->_headers = [];
}
}
return $this->_headers;
} | php | {
"resource": ""
} |
q254042 | MenuFactory.createItem | validation | public function createItem($name, array $options = array())
{
if (!empty($options['admin'])) {
$admin = $options['admin'];
if ( !$options['admin'] instanceof AdminInterface ) {
$admin = $this->container->get('sonata.admin.pool')->getAdminByAdminCode($admin);
}
$action = isset($options['admin_action']) ? $options['admin_action'] : 'list';
$options['uri'] = $admin->generateUrl($action);
$options['translationDomain'] = $admin->getTranslationDomain();
}
/**
* Knp\Menu\Silex\RouterAwareFactory
*/
if (!empty($options['route'])) {
$params = isset($options['routeParameters']) ? $options['routeParameters'] : array();
$absolute = isset($options['routeAbsolute']) ? $options['routeAbsolute'] : false;
$options['uri'] = $this->generator->generate($options['route'], $params, $absolute);
}
// use VinceT\AdminBundle\Menu\MenuItem
$item = new MenuItem($name, $this);
$options = array_merge(
array(
'uri' => null,
'label' => null,
'attributes' => array(),
'linkAttributes' => array(),
'childrenAttributes' => array(),
'labelAttributes' => array(),
'extras' => array(),
'display' => true,
'displayChildren' => true,
'translationDomain' => 'messages',
'displayLink' => true,
'displayLabel' => true,
),
$options
);
$item
->setUri($options['uri'])
->setLabel($options['label'])
->setAttributes($options['attributes'])
->setLinkAttributes($options['linkAttributes'])
->setChildrenAttributes($options['childrenAttributes'])
->setLabelAttributes($options['labelAttributes'])
->setExtras($options['extras'])
->setDisplay($options['display'])
->setDisplayChildren($options['displayChildren'])
->setTranslationDomain($options['translationDomain'])
->setDisplayLink($options['displayLink'])
->setDisplayLabel($options['displayLabel']);
return $item;
return parent::createItem($name, $options);
} | php | {
"resource": ""
} |
q254043 | Paginator.getPage | validation | public function getPage($page = null)
{
if (is_null($page)) {
$page = $this->page;
}
list($offset, $size) = $this->getLimts($page);
$this->manager->limit($offset, $size);
return $this->manager->values();
} | php | {
"resource": ""
} |
q254044 | Web2All_Table_Collection_SimpleDataProvider.getADORecordSet | validation | public function getADORecordSet()
{
if (!$this->sql) {
// no sql set
throw new Exception('Web2All_Table_Collection_SimpleDataProvider::getADORecordSet: no SQL query set');
}
return $this->db->SelectLimit($this->sql,$this->limit,$this->offset,$this->params);
} | php | {
"resource": ""
} |
q254045 | Model.buildColumnPropertiesCache | validation | private static function buildColumnPropertiesCache()
{
// Get the calling child class, ensuring that the Model class was not used!
$class = self::getStaticChildClass();
// Create an AnnotationReader and get all of the annotations on properties of this class.
$annotations = new AnnotationReader($class);
$properties = $annotations->getPropertyAnnotations();
// Initialize a collection of column => property names.
self::$columnPropertiesCache[$class] = [];
// Loop through each property annotation...
foreach($properties as $property)
{
// Skip non-annotated properties!
if($property === [])
continue;
// If the current property has a @ColumnNameAnnotation...
if(array_key_exists("ColumnName", $property))
// THEN add the column name and property name pairing to the collection!
self::$columnPropertiesCache[$class][$property["ColumnName"]][] = $property["var"]["name"];
else
// OTHERWISE add the property name to the collection, paired to itself!
self::$columnPropertiesCache[$class][$property["var"]["name"]][] = $property["var"]["name"];
}
} | php | {
"resource": ""
} |
q254046 | Model.getColumnName | validation | private static function getColumnName(string $name): ?string
{
// Get the calling child class, ensuring that the Model class was not used!
$class = self::getStaticChildClass();
// IF the column => property cache has not yet been built, or does not exist for this class...
if (self::$columnPropertiesCache === null || !array_key_exists($class, self::$columnPropertiesCache) ||
self::$columnPropertiesCache[$class] === null)
// THEN build it now!
self::buildColumnPropertiesCache();
// IF the name exists as a column => property cache key...
if(array_key_exists($name, self::$columnPropertiesCache[$class]))
// THEN return the column name as is!
return $name;
// OTHERWISE, we need to loop through all of the column => property pairings in the cache...
foreach(self::$columnPropertiesCache[$class] as $column => $properties)
{
// IF the current column name is associated with a property matching the name provided...
if(in_array($name, $properties))
// THEN return the current column name.
return $column;
}
// Nothing was matched, return NULL!
return null;
} | php | {
"resource": ""
} |
q254047 | Model.select | validation | public static function select(): Collection
{
// Ensure the database is connected!
$pdo = Database::connect();
// Get the calling child class, ensuring that the Model class was not used!
$class = self::getStaticChildClass();
// Get the table name from either a @TableNameAnnotation or an automated conversion from the class name...
$tableName = self::getTableName();
// Build the SQL statement.
$sql = "SELECT * FROM \"$tableName\"";
// Fetch the results from the database.
$results = $pdo->query($sql)->fetchAll();
// Create a new Collection to store the converted objects.
$collection = new Collection($class, []);
// Loop through each result...
foreach($results as $result)
{
// Create a new object and populate it's properties.
$object = new $class($result);
// Append the new object to the collection.
$collection->push($object);
}
// Finally, return the Collection!
return $collection;
} | php | {
"resource": ""
} |
q254048 | Model.where | validation | public static function where(string $column, string $operator, $value): Collection
{
// Ensure the database is connected!
$pdo = Database::connect();
// Get the calling child class, ensuring that the Model class was not used!
$class = self::getStaticChildClass();
// Get the table name from either a @TableNameAnnotation or an automated conversion from the class name...
$tableName = self::getTableName();
// Lookup the correct column name.
$column = self::getColumnName($column);
// IF no matching column name could be determined, THEN throw an Exception!
if($column === null)
throw new ModelMissingPropertyException("Could not find a property '$column' of class '$class'. ".
"Are you missing a '@ColumnNameAnnotation' on a property?");
// Build the SQL statement.
$sql = "SELECT * FROM \"$tableName\" WHERE \"$column\" $operator ".
(gettype($value) === "string" ? "'$value'" : "$value");
// Fetch the results from the database.
$results = $pdo->query($sql)->fetchAll();
// Create a new Collection to store the converted objects.
$collection = new Collection($class, []);
// Loop through each result...
foreach($results as $result)
{
// Create a new object and populate it's properties.
$object = new $class($result);
// Append the new object to the collection.
$collection->push($object);
}
// Finally, return the Collection!
return $collection;
} | php | {
"resource": ""
} |
q254049 | Model.getPrimaryKey | validation | private static function getPrimaryKey(string $table): array
{
if (self::$primaryKeyCache !== null && array_key_exists($table, self::$primaryKeyCache))
return self::$primaryKeyCache[$table];
// Ensure the database is connected!
$pdo = Database::connect();
/** @noinspection SqlResolve */
$query = "
SELECT
tc.constraint_name, tc.table_name, kcu.column_name,
ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column_name
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'PRIMARY KEY' AND tc.table_name = '$table'
";
$results = $pdo->query($query);
self::$primaryKeyCache[$table] = $results->fetch(); // ONLY ONE PRIMARY KEY!
return self::$primaryKeyCache[$table];
} | php | {
"resource": ""
} |
q254050 | Model.isPrimaryKey | validation | private static function isPrimaryKey(string $table, string $column): bool
{
return self::getPrimaryKey($table)["column_name"] === $column;
} | php | {
"resource": ""
} |
q254051 | Model.getForeignKeys | validation | private static function getForeignKeys(string $table): array
{
if (self::$foreignKeysCache !== null && array_key_exists($table, self::$foreignKeysCache))
return self::$foreignKeysCache[$table];
// Ensure the database is connected!
$pdo = Database::connect();
/** @noinspection SqlResolve */
$query = "
SELECT
tc.constraint_name, tc.table_name, kcu.column_name,
ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column_name
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name = '$table'
";
self::$foreignKeysCache[$table] = [];
$rows = $pdo->query($query);
while($row = $rows->fetch())
self::$foreignKeysCache[$table][$row["column_name"]] = $row;
return self::$foreignKeysCache[$table];
} | php | {
"resource": ""
} |
q254052 | Model.getForeignKeysNames | validation | private static function getForeignKeysNames(string $table): array
{
if (self::$foreignKeysCache === null || !array_key_exists($table, self::$foreignKeysCache))
self::getForeignKeys($table);
return array_keys(self::$foreignKeysCache[$table]);
} | php | {
"resource": ""
} |
q254053 | Model.isForeignKey | validation | private static function isForeignKey(string $table, string $column): bool
{
return array_key_exists($column, self::getForeignKeys($table));
} | php | {
"resource": ""
} |
q254054 | Model.getNullables | validation | private static function getNullables(string $table): array
{
if (self::$nullablesCache !== null && array_key_exists($table, self::$nullablesCache))
return self::$nullablesCache[$table];
// Ensure the database is connected!
$pdo = Database::connect();
/** @noinspection SqlResolve */
$query = "
SELECT
column_name, data_type, is_nullable, column_default
FROM
information_schema.columns
WHERE table_name = '$table' AND is_nullable = 'YES'
";
self::$nullablesCache[$table] = [];
$rows = $pdo->query($query);
while($row = $rows->fetch())
self::$nullablesCache[$table][$row["column_name"]] = $row;
return self::$nullablesCache[$table];
} | php | {
"resource": ""
} |
q254055 | Model.getNullableNames | validation | private static function getNullableNames(string $table): array
{
if (self::$nullablesCache === null || !array_key_exists($table, self::$nullablesCache))
self::getNullables($table);
return array_keys(self::$nullablesCache[$table]);
} | php | {
"resource": ""
} |
q254056 | Model.isNullable | validation | private static function isNullable(string $table, string $column): bool
{
// IF the nullables cache is not already built, THEN build it!
if (self::$nullablesCache === null || !array_key_exists($table, self::$nullablesCache))
self::getNullables($table);
// Return TRUE if the column is included in the nullables cache!
return array_key_exists($column, self::$nullablesCache[$table]);
} | php | {
"resource": ""
} |
q254057 | Model.getColumns | validation | private static function getColumns(string $table): array
{
if (self::$columnsCache !== null && array_key_exists($table, self::$columnsCache))
return self::$columnsCache[$table];
// Ensure the database is connected!
$pdo = Database::connect();
/** @noinspection SqlResolve */
$query = "
SELECT
*
FROM
information_schema.columns
WHERE table_name = '$table'
";
self::$columnsCache[$table] = [];
$rows = $pdo->query($query);
while($row = $rows->fetch())
self::$columnsCache[$table][$row["column_name"]] = $row;
return self::$columnsCache[$table];
} | php | {
"resource": ""
} |
q254058 | ValueCache.fetchAll | validation | public function fetchAll() {
$list = [];
foreach($this->cache as $domain => $values) {
foreach($values as $key => $value)
$list[ sprintf("%s.%s", $domain!='<NULL>' ? $domain : '', $key) ] = $value;
}
return $list;
} | php | {
"resource": ""
} |
q254059 | CommandTransformer.transformCommandToMessage | validation | public function transformCommandToMessage($command)
{
if (!is_object($command)) {
throw CommandTransformationException::expectedObject($command);
}
if (!isset($this->commands[get_class($command)])) {
throw CommandTransformationException::unknownCommand($command, array_keys($this->commands));
}
if ($this->serializer instanceof EncoderInterface && !$this->serializer->supportsEncoding($this->format)) {
throw CommandTransformationException::unsupportedFormat($command, $this->format);
}
$info = $this->commands[get_class($command)];
return new CommandMessage(
$info->getVhost(),
$info->getExchange(),
$this->serializer->serialize($command, $this->format),
$info->getRoutingKey(),
$info->getFlags(),
$this->resolveMessageAttributes($command, $info)
);
} | php | {
"resource": ""
} |
q254060 | Installer.setPermission | validation | public static function setPermission(array $paths)
{
foreach ($paths as $path => $permission) {
echo "chmod('$path', $permission)...";
if (is_dir($path) || is_file($path)) {
chmod($path, octdec($permission));
echo "done.\n";
} else {
echo "file not found.\n";
}
}
} | php | {
"resource": ""
} |
q254061 | Injector.execute | validation | public function execute(callable $callback, array $vars): Response
{
$arguments = $this->resolveDependencies($callback, $vars);
return call_user_func_array($callback, $arguments);
} | php | {
"resource": ""
} |
q254062 | Injector.resolveDependencies | validation | private function resolveDependencies(callable $callback, array $vars): array
{
$method = new \ReflectionMethod($callback[0], $callback[1]);
$dependencies = [];
foreach ($method->getParameters() as $parameter) {
if ($parameter->getClass() === null && !count($vars)) {
break;
}
if ($parameter->getClass() === null && count($vars)) {
$dependencies[] = array_shift($vars);
continue;
}
$dependencies[] = $this->injector->make($parameter->getClass()->name);
}
return $dependencies;
} | php | {
"resource": ""
} |
q254063 | BlockManager.resolveOptions | validation | protected function resolveOptions(array $options)
{
if ($this->optionsResolved) {
return;
}
$this->optionsResolver->clear();
$this->optionsResolver->setRequired(
array(
'blockname',
)
);
parent::resolveOptions($options);
$this->optionsResolved = true;
} | php | {
"resource": ""
} |
q254064 | BlockManager.createContributorDir | validation | protected function createContributorDir($sourceDir, array $options, $username)
{
if (null === $username) {
return;
}
$this->init($sourceDir, $options, $username);
if (is_dir($this->contributorDir)) {
return;
}
$this->filesystem->copy($this->productionDir . '/slot.json', $this->contributorDir . '/slot.json', true);
$this->filesystem->mirror($this->productionDir . '/blocks', $this->contributorDir . '/blocks');
} | php | {
"resource": ""
} |
q254065 | BlockManager.addBlockToSlot | validation | protected function addBlockToSlot($dir, array $options)
{
$slot = $this->getSlotDefinition($dir);
$blocks = $slot["blocks"];
$blockName = $options["blockname"];
$position = $options["position"];
array_splice($blocks, $position, 0, $blockName);
$slot["next"] = str_replace('block', '', $blockName) + 1;
$slot["blocks"] = $blocks;
$this->saveSlotDefinition($dir, $slot);
return $blockName;
} | php | {
"resource": ""
} |
q254066 | BlockManager.getSlotDefinition | validation | protected function getSlotDefinition($dir)
{
$slotsFilename = $this->getSlotDefinitionFile($dir);
return json_decode(FilesystemTools::readFile($slotsFilename), true);
} | php | {
"resource": ""
} |
q254067 | BlockManager.saveSlotDefinition | validation | protected function saveSlotDefinition($dir, array $slot)
{
$slotsFilename = $this->getSlotDefinitionFile($dir);
FilesystemTools::writeFile($slotsFilename, json_encode($slot), $this->filesystem);
} | php | {
"resource": ""
} |
q254068 | BlockManager.removeBlockFromSlotFile | validation | protected function removeBlockFromSlotFile(array $options, $targetDir = null)
{
$targetDir = $this->workDirectory($targetDir);
$slot = $this->getSlotDefinition($targetDir);
$blockName = $options["blockname"];
$tmp = array_flip($slot["blocks"]);
unset($tmp[$blockName]);
$slot["blocks"] = array_keys($tmp);
$this->saveSlotDefinition($targetDir, $slot);
return $blockName;
} | php | {
"resource": ""
} |
q254069 | TwigEngine.registerCustomFunctions | validation | protected function registerCustomFunctions()
{
$functionList = $this->functionGenerator->getFunctionList();
foreach ($functionList as $function) {
if (isset($function['name']) && isset($function['callable'])) {
$twigFunction = new Twig_SimpleFunction($function['name'], $function['callable']);
$this->engine->addFunction($twigFunction);
}
}
} | php | {
"resource": ""
} |
q254070 | Compiler.setConfig | validation | public function setConfig($name, $value) {
if (is_null($name)) {
$this->_config = new ArrayStorage($value);
} else {
$this->_config->setDeepValue($name, $value);
}
return $this;
} | php | {
"resource": ""
} |
q254071 | Compiler.compileSource | validation | public function compileSource($source) {
$source = $this->stripComments($source);
$source = $this->saveLiterals($source);
$result = preg_replace_callback('#' . $this->_config['tokenStart'] . '(.*)' . $this->_config['tokenEnd'] . '#smU', array($this, 'onTokenFound'), $source);
$result = $this->restoreLiterals($result);
return $result;
} | php | {
"resource": ""
} |
q254072 | Compiler.onTokenFound | validation | private function onTokenFound($token) {
if (is_array($token)) $token = array_pop($token);
$token = trim($token);
$tokenParts = explode(' ', $token);
$tag = array_shift($tokenParts);
$params = implode(' ', $tokenParts);
if ($this->_blocks->has($tag)) {
if ($this->_blocks->getDeepValue($tag . '/runtime')) {
$res = '<?php $this->_compiler->invokeBlock(\'' . $tag . '\', ' . $this->compileExpression($params) . '); ?>';
} else {
$res = $this->onBlockTagOpen($tag, $params);
}
} elseif (substr($tag, 0, strlen($this->_config['blockClose'])) == $this->_config['blockClose']) {
$tag = substr($tag, strlen($this->_config['blockClose']));
$res = $this->onBlockTagClose($tag, $params);
} else {
$res = $this->onVarEchoToken($token, $params);
}
return $res;
} | php | {
"resource": ""
} |
q254073 | Compiler._processModifiers | validation | private function _processModifiers($expression) {
$mStart = '';
$mEnd = '';
$rawEcho = false;
/** process modifiers */
if (strpos($expression, '|') !== false && strpos($expression, '||') === false) {
$modifiers = explode('|', $expression);
$expression = array_shift($modifiers);
foreach ($modifiers as $modifier) {
$params = array();
if (strpos($modifier, ':') !== false) {
$params = explode(':', $modifier);
$modifier = array_shift($params);
}
if ($modifier == 'raw') {
$rawEcho = true;
continue;
}
if ($this->isCallable($modifier)) {
$mStart = $modifier . '(' . $mStart;
if ($modifier !== 'raw') {
foreach ($params as $param) {
$mEnd .= ', ' . $this->compileExpression($param);
}
}
$mEnd .= ')';
} else {
throw new \Exception('SLOT compiler error: undefined modifier ' . $modifier);
}
}
}
return array(
$expression,
$mStart,
$mEnd,
$rawEcho
);
} | php | {
"resource": ""
} |
q254074 | ServiceContainerCodeGenerator.generateConfigCreatorMethod | validation | private function generateConfigCreatorMethod(ConfigService $config)
{
$configClass = Util::normalizeFqcn($config->getClass());
$configData = var_export($config->getData(), true);
return <<<PHP
public function getAppConfig() : {$configClass}
{
if (isset(\$this->singletons['{$config->getId()}}'])) {
return \$this->singletons['{$config->getId()}'];
}
\$data = {$configData};
return \$this->singletons['{$config->getId()}'] = new {$configClass}(\$data);
}
PHP;
} | php | {
"resource": ""
} |
q254075 | ServiceContainerCodeGenerator.generatePureCreatorMethod | validation | private function generatePureCreatorMethod(ServiceDefinition $service) : string
{
$taggedAs = implode(', ', $service->getTags());
$classNormalized = $this->normalizeFqcn($service->getClass());
//// SINGLETON ////////////////////////////////////////////////////////////////////////////////////////////
if ($service->isSingleton()) {
return <<<PHP
/**
* Get service {$service->getId()} (Singleton)
*
* It is tagged as: {$taggedAs}
*
* @return {$this->normalizeFqcn($service->getClass())}
*/
public function {$this->mapIdToServiceGetter($service->getId())} () : $classNormalized {
if (isset(\$this->singletons['{$service->getId()}'])) {
return \$this->singletons['{$service->getId()}'];
}
/** @noinspection OneTimeUseVariablesInspection */
\$service = \$this->singletons['{$service->getId()}'] = new $classNormalized(
{$this->buildInjectionParameters($this->container, $service->getInjection()->getCreatorInjection())}
);
{$this->generateSetterInjectionsCode($service)}
return \$service;
}
PHP;
}
//// PROTOTYPE ////////////////////////////////////////////////////////////////////////////////////////////
return <<<PHP
/**
* Get a fresh instance of service "{$service->getId()}" (Prototype)
*
* It is tagged as: {$taggedAs}
*
* @return {$this->normalizeFqcn($service->getClass())}
*/
public function {$this->mapIdToServiceGetter($service->getId())} () : $classNormalized {
\$this->prototypes['{$service->getId()}'] = (\$this->prototypes['{$service->getId()}'] ?? 0) + 1;
/** @noinspection OneTimeUseVariablesInspection */
\$service = new $classNormalized(
{$this->buildInjectionParameters($this->container, $service->getInjection()->getCreatorInjection())}
);
{$this->generateSetterInjectionsCode($service)}
return \$service;
}
PHP;
} | php | {
"resource": ""
} |
q254076 | ServiceContainerCodeGenerator.generateFactoryCreatorMethod | validation | private function generateFactoryCreatorMethod(FactoredService $service) : string
{
$factoryMethod = $service->getFactoryMethod();
$taggedAs = implode(', ', $service->getTags());
$classNormalized = $this->normalizeFqcn($service->getClass());
$optional = $service->getFactoryMethod()->isOptional() ? '?' : '';
//// SINGLETON ////////////////////////////////////////////////////////////////////////////////////////////
if ($service->isSingleton()) {
return <<<PHP
/**
* Get the factored service "{$service->getId()}" (Singleton)
*
* It is tagged as: {$taggedAs}
*
* @return {$this->normalizeFqcn($service->getClass())}
*/
public function {$this->mapIdToServiceGetter($service->getId())} () : {$optional}{$classNormalized}
{
if (isset(\$this->singletons['{$service->getId()}'])) {
return \$this->singletons['{$service->getId()}'];
}
/** @noinspection OneTimeUseVariablesInspection */
\$service = \$this->singletons['{$service->getId()}'] = {$this->generateCreatorByServiceId($factoryMethod->getFactoryId())}->{$factoryMethod->getMethodName()}(
{$this->buildInjectionParameters($this->container, $factoryMethod->getInjection())}
);
{$this->generateSetterInjectionsCode($service)}
return \$service;
}
PHP;
}
//// PROTOTYPE ////////////////////////////////////////////////////////////////////////////////////////////
return <<<PHP
/**
* Get a fresh instance of service "{$service->getId()}" (Prototype)
*
* It is tagged as: {$taggedAs}
*
* @return {$this->normalizeFqcn($service->getClass())}
*/
public function {$this->mapIdToServiceGetter($service->getId())} () : $classNormalized
{
\$this->prototypes['{$service->getId()}'] = (\$this->prototypes['{$service->getId()}'] ?? 0) + 1;
/** @noinspection OneTimeUseVariablesInspection */
\$service = {$this->generateCreatorByServiceId($factoryMethod->getFactoryId())}->{$factoryMethod->getMethodName()}(
{$this->buildInjectionParameters($this->container, $factoryMethod->getInjection())}
);
{$this->generateSetterInjectionsCode($service)}
return \$service;
}
PHP;
} | php | {
"resource": ""
} |
q254077 | Filesystem.makeDirectory | validation | public function makeDirectory($path, $mode = 0755, $recursive = false) {
if (!file_exists($path)) {
return mkdir($path, $mode, $recursive);
}
return true;
} | php | {
"resource": ""
} |
q254078 | SiteBuilder.build | validation | public function build()
{
$this->appDir = $this->rootDir . '/app';
$siteDir = $this->appDir . '/data/' . $this->siteName;
$siteConfigDir = $siteDir . '/config';
$pagesDir = $siteDir . '/pages/pages';
$rolesDir = $siteDir . '/roles';
$slotsDir = $siteDir . '/slots';
$usersDir = $siteDir . '/users';
$folders = array(
$siteConfigDir,
$pagesDir,
$rolesDir,
$slotsDir,
$usersDir,
);
$this->filesystem->mkdir($folders);
$this->createConfiguration($siteDir);
$this->createSite($siteDir);
$this->createRoles($rolesDir);
$this->createUsers($usersDir);
$this->filesystem->touch($siteDir . '/incomplete.json');
return $this;
} | php | {
"resource": ""
} |
q254079 | FileManager.dir | validation | static public function dir($directory, $date = false)
{
if ($date) {
$directory = rtrim($directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . self::getDateDirectory();
}
if (!is_dir($directory)) {
$umask = umask(0000);
if (@mkdir($directory, 0777, true) === false) {
throw new Exception(sprintf('Directory "%s" cannot be created.', $directory));
}
umask($umask);
}
return $directory;
} | php | {
"resource": ""
} |
q254080 | FileManager.generateFilename | validation | static public function generateFilename($directory, $extension, $length = 16)
{
do {
$name = \Extlib\Generator::generate($length);
$filepath = rtrim($directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . sprintf('%s.%s', $name, $extension);
} while (file_exists($filepath));
return $name;
} | php | {
"resource": ""
} |
q254081 | FileManager.getMimeType | validation | static public function getMimeType($filePath, $default = 'application/octet-stream')
{
$mimeType = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $filePath);
if ($mimeType === false) {
$mimeType = $default;
}
return $mimeType;
} | php | {
"resource": ""
} |
q254082 | FileManager.recursiveDelete | validation | static public function recursiveDelete($path)
{
if (is_file($path)) {
return unlink($path);
}
$scans = glob(rtrim($path, '/') . '/*');
foreach ($scans as $scan) {
self::recursiveDelete($scan);
}
return rmdir($path);
} | php | {
"resource": ""
} |
q254083 | FileManager.removeFiles | validation | static public function removeFiles($directory)
{
$scan = glob(rtrim($directory, '/') . '/*');
foreach ($scan as $file) {
if (is_file($file)) {
unlink($file);
}
}
return true;
} | php | {
"resource": ""
} |
q254084 | ImportPeopleFromCSVCommand.addOptionShortcut | validation | protected function addOptionShortcut($name, $description, $default)
{
$this->addOption($name, null, InputOption::VALUE_OPTIONAL, $description, $default);
return $this;
} | php | {
"resource": ""
} |
q254085 | ImportPeopleFromCSVCommand.loadAnswerMatching | validation | protected function loadAnswerMatching()
{
if ($this->input->hasOption('load-choice-matching')) {
$fs = new Filesystem();
$filename = $this->input->getOption('load-choice-matching');
if (!$fs->exists($filename)) {
$this->logger->warning("The file $filename is not found. Choice matching not loaded");
} else {
$this->logger->debug("Loading $filename as choice matching");
$this->cacheAnswersMapping = \json_decode(\file_get_contents($filename), true);
}
}
} | php | {
"resource": ""
} |
q254086 | ImportPeopleFromCSVCommand.processTextType | validation | protected function processTextType(
$value,
\Symfony\Component\Form\FormInterface $form,
\Chill\CustomFieldsBundle\Entity\CustomField $cf
)
{
$form->submit(array($cf->getSlug() => $value));
$value = $form->getData()[$cf->getSlug()];
$this->logger->debug(sprintf("Found value : %s for custom field with question "
. "'%s'", $value, $this->helper->localize($cf->getName())));
return $value;
} | php | {
"resource": ""
} |
q254087 | Router.runHttpErrorPage | validation | public function runHttpErrorPage(int $iError)
{
if (isset($_SERVER) && isset($_SERVER['HTTP_HOST'])) {
foreach (Config::get('route') as $sHost => $oHost) {
if ((!strstr($sHost, '/') && $sHost == $_SERVER['HTTP_HOST'])
|| (strstr($sHost, '/') && strstr($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], $sHost))) {
$this->_oRoutes = $oHost->routes;
if (strstr($sHost, '/') && strstr($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], $sHost)) {
$this->_sBaseUri = preg_replace('#^[^/]+#', '', $sHost);
}
$sHttpErrorPageName = '_getPage'.iError;
$this->$sHttpErrorPageName();
}
}
}
} | php | {
"resource": ""
} |
q254088 | Router._loadController | validation | private function _loadController($oControllerName, string $sActionName, array $aParams = array())
{
$aPhpDoc = PhpDoc::getPhpDocOfMethod($oControllerName, $sActionName);
if (isset($aPhpDoc['Cache'])) {
if (!isset($aPhpDoc['Cache']['maxage'])) { $aPhpDoc['Cache']['maxage'] = 0; }
$oMobileDetect = new \Mobile_Detect;
if ($oMobileDetect->isMobile()) { $sCacheExt = '.mobi'; }
else { $sCacheExt = ''; }
$mCacheReturn = Cache::get($sActionName.$sCacheExt, $aPhpDoc['Cache']['maxage']);
if ($mCacheReturn !== false) { return $mCacheReturn; }
}
if (isset($aPhpDoc['Secure'])) {
if (isset($aPhpDoc['Secure']['roles']) && $this->_oSecurity->getUserRole() != $aPhpDoc['Secure']['roles']) {
$this->_getPage403();
}
}
$oController = new $oControllerName;
ob_start();
if (!defined('PORTAL')) { define('PORTAL', 'Batch'); }
if (method_exists($oController, 'beforeExecuteRoute')) {
call_user_func_array(array($oController, 'beforeExecuteRoute'), array());
}
$mReturnController = call_user_func_array(array($oController, $sActionName), $aParams);
if (method_exists($oController, 'afterExecuteRoute')) {
call_user_func_array(array($oController, 'afterExecuteRoute'), array());
}
$mReturn = ob_get_clean();
if ($mReturn == '') { $mReturn = $mReturnController; }
if (isset($aPhpDoc['Cache'])) {
$oMobileDetect = new \Mobile_Detect;
if ($oMobileDetect->isMobile()) { $sCacheExt = '.mobi'; }
else { $sCacheExt = ''; }
if (defined('COMPRESS_HTML') && COMPRESS_HTML) {
$mReturn = str_replace(array("\t", "\r", " "), array("", "", "", " "), $mReturn);
}
Cache::set($sActionName.$sCacheExt, $mReturn, $aPhpDoc['Cache']['maxage']);
}
return $mReturn;
} | php | {
"resource": ""
} |
q254089 | Router._getPage403 | validation | private function _getPage403()
{
var_dump(debug_backtrace());
header("HTTP/1.0 403 Forbidden");
if (isset($this->_oRoutes->e403)) {
$this->_oRoutes->e403->route = '/';
$_SERVER['REQUEST_URI'] = '/';
$this->_route($this->_oRoutes->e403, $_SERVER['REQUEST_URI']);
}
exit;
} | php | {
"resource": ""
} |
q254090 | Router._getPage404 | validation | private function _getPage404()
{
header("HTTP/1.0 404 Not Found");
if (isset($this->_oRoutes->e404)) {
$this->_oRoutes->e404->route = '/';
$_SERVER['REQUEST_URI'] = '/';
$this->_route($this->_oRoutes->e404, $_SERVER['REQUEST_URI']);
}
exit;
} | php | {
"resource": ""
} |
q254091 | Router._checkCache | validation | private function _checkCache(\stdClass $oCache)
{
/**
* cache-control http
*/
$sHearderValidity = false;
$sHeader = "Cache-Control:";
if (isset($oCache->visibility) && ($oCache->visibility = 'public' || $oCache->visibility = 'private')) {
$sHearderValidity = true;
$sHeader .= " ".$oCache->visibility.",";
}
if (isset($oCache->max_age)) {
$sHearderValidity = true;
$sHeader .= " maxage=".$oCache->max_age.",";
}
if (isset($oCache->must_revalidate) && $oCache->must_revalidate === true) {
$sHearderValidity = true;
$sHeader .= " must-revalidate,";
}
if ($sHearderValidity === true) {
$sHeader = substr($sHeader, 0, -1);
if (!headers_sent()) { header($sHeader); }
}
/**
* ETag http
*/
if (isset($oCache->ETag)) { header("ETag: \"".$oCache->ETag."\""); }
/**
* expire
*/
if (isset($oCache->max_age)) { if (!headers_sent()) { header('Expires: '.gmdate('D, d M Y H:i:s', time() + $oCache->max_age).' GMT'); } }
/**
* Last-Modified http
*/
if (isset($oCache->last_modified)) { if (!headers_sent()) { header('Last-Modified: '.gmdate('D, d M Y H:i:s', time() + $oCache->last_modified).' GMT'); } }
/**
* vary http
*/
if (isset($oCache->vary)) { header('Vary: '.$oCache->vary); }
} | php | {
"resource": ""
} |
q254092 | CustomerRepository.beforeDeleteById | validation | public function beforeDeleteById(
\Magento\Customer\Api\CustomerRepositoryInterface $subject,
$customerId
) {
$this->deleteDwnl($customerId);
$result = [$customerId];
return $result;
} | php | {
"resource": ""
} |
q254093 | Environment.symbol | validation | protected static function symbol($symbol) {
if ($symbol instanceof Symbol)
return [$symbol->symbol, $symbol->package];
throw new \UnexpectedValueException(sprintf("Unexpected value of type '%s'.", is_object($symbol) ? get_class($symbol) : gettype($symbol)));
} | php | {
"resource": ""
} |
q254094 | Environment.import | validation | public function import(Package $package, $id = null) {
$id = is_null($id) ? $package->id : $id;
//load symbols
$this->symbols = array_merge($package->symbols, $this->symbols);
//load macros
$this->macros = array_merge($package->macros, $this->macros);
//store package
$this->packages[$id] = $package;
} | php | {
"resource": ""
} |
q254095 | Processor.process | validation | public function process(Pipeline\Pipeline $pipeline, $payload)
{
$runner = clone($this);
$runner->stages = $pipeline->getIterator();
return $runner->handle($payload);
} | php | {
"resource": ""
} |
q254096 | Worker.goWait | validation | function goWait($maxExecution = null)
{
# Go For Jobs
#
$jobExecution = 0; $sleep = 0;
while ( 1 )
{
if ( 0 == $executed = $this->goUntilEmpty() ) {
// List is Empty; Smart Sleep
$sleep += 100000;
usleep($sleep);
if ($sleep > 2 * 1000000)
// Sleep more than 2 second not allowed!!
$sleep = 100000;
continue;
}
$jobExecution += $executed;
if ($jobExecution >= $maxExecution)
// Maximum Execution Task Exceed!!
break;
if ( $sleep = $this->getSleep() )
// Take a breath between hooks
usleep($sleep);
$sleep = 0;
}
} | php | {
"resource": ""
} |
q254097 | Worker.performPayload | validation | function performPayload(iPayloadQueued $processPayload)
{
$triesCount = 0;
if ($processPayload instanceof FailedPayload) {
if ( $processPayload->getCountRetries() > $this->getMaxTries() )
throw new exPayloadMaxTriesExceed(
$processPayload
, sprintf('Max Tries Exceeds After %s Tries.', $processPayload->getCountRetries())
, null
);
}
$payLoadData = $processPayload->getData();
try {
if ( ob_get_level() )
## clean output buffer, display just error page
ob_end_clean();
ob_start();
$this->event()->trigger(
EventHeapOfWorker::EVENT_PAYLOAD_RECEIVED
, [ 'payload' => $processPayload, 'data' => $payLoadData, 'worker' => $this ]
);
ob_end_flush(); // Strange behaviour, will not work
flush(); // Unless both are called !
} catch (\LogicException $e) {
// Exception is logical and its ok to throw
throw $e;
} catch (\Exception $e) {
// Process Failed
// Notify Main Stream
if (! $processPayload instanceof FailedPayload)
$failedPayload = new FailedPayload($processPayload, $triesCount);
else
$failedPayload = $processPayload;
throw new exPayloadPerformFailed($failedPayload, $e);
}
} | php | {
"resource": ""
} |
q254098 | Worker.giveBuiltInQueue | validation | function giveBuiltInQueue(iQueueDriver $queueDriver)
{
if ($this->builtinQueue)
throw new exImmutable(sprintf(
'Built-in Queue (%s) is given.'
, \Poirot\Std\flatten($this->builtinQueue)
));
$this->builtinQueue = $queueDriver;
return $this;
} | php | {
"resource": ""
} |
q254099 | PageSavedListener.onPageSaved | validation | public function onPageSaved(PageSavedEvent $event)
{
$blocks = $event->getApprovedBlocks();
foreach ($blocks as $blockk) {
foreach ($blockk as $block) {
$this->pageProductionRenderer->renderBlock(json_encode($block));
}
}
$mediaFiles = array_unique($this->pageProductionRenderer->getMediaFiles());
$webDir = $this->configurationHandler->webDir();
$fs = new Filesystem();
foreach ($mediaFiles as $mediaFile) {
$targetMediaFile = str_replace('/backend/', '/production/', $mediaFile);
$fs->copy($webDir . $mediaFile, $webDir . $targetMediaFile);
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.