_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q7500 | IniParser.castItemValueToProperType | train | public function castItemValueToProperType($value)
{
$normalized = $value;
if (in_array($value, ['true', 'on', 'yes']))
{
$normalized = true;
}
elseif (in_array($value, ['false', 'off', 'no', 'none']))
{
$normalized = false;
}
elseif ('null' == $value)
{
$normalized = null;
}
elseif (is_numeric($value))
{
$number = $value + 0;
if (intval($number) == $number)
{
$normalized = (int)$number;
}
elseif (floatval($number) == $number)
{
$normalized = (float)$number;
}
}
elseif (is_array($value))
{
foreach ($value as $itemKey => $itemValue)
{
$normalized[$itemKey] = $this->castItemValueToProperType($itemValue);
}
}
return $normalized;
} | php | {
"resource": ""
} |
q7501 | Route.createFromReflection | train | public static function createFromReflection(\ReflectionMethod $reflectionMethod, string $basePath = '')
{
$routes = [];
if (is_a($reflectionMethod->class, '\Berlioz\Core\Controller\Controller', true)) {
try {
if ($reflectionMethod->isPublic()) {
if ($methodDoc = $reflectionMethod->getDocComment()) {
$docBlock = Router::getDocBlockFactory()->create($methodDoc);
if ($docBlock->hasTag('route')) {
/** @var \phpDocumentor\Reflection\DocBlock\Tags\Generic $tag */
foreach ($docBlock->getTagsByName('route') as $tag) {
$route = new Route;
$route->setRouteDeclaration($tag->getDescription()->render(), $basePath);
$route->setSummary($docBlock->getSummary());
$route->setDescription($docBlock->getDescription()->render());
$route->setInvoke($reflectionMethod->class, $reflectionMethod->getName());
$route->getRouteRegex();
$routes[] = $route;
}
}
}
} else {
/** @var \ReflectionMethod $reflectionMethod */
throw new BerliozException('Must be public');
}
} catch (BerliozException $e) {
/** @var \ReflectionMethod $reflectionMethod */
throw new BerliozException(sprintf('Method "%s::%s" route error: %s', $reflectionMethod->class, $reflectionMethod->getName(), $e->getMessage()));
}
} else {
throw new BerliozException(sprintf('Class "%s" must be a sub class of "\Berlioz\Core\Controller\Controller"', $reflectionMethod->class));
}
return $routes;
} | php | {
"resource": ""
} |
q7502 | Route.filterParameters | train | private function filterParameters(array $params): array
{
return
array_filter(
$params,
function (&$value) {
if (is_array($value)) {
$value = $this->filterParameters($value);
return count($value) > 0;
} else {
return !is_null($value);
}
}
);
} | php | {
"resource": ""
} |
q7503 | ErrorLogger.as_string | train | private function as_string( $value ) {
if ( is_object( $value ) && method_exists( $value, '__toString' ) ) {
$value = (string) $value;
}
if ( is_string( $value ) ) {
return $value;
} elseif ( is_null( $value ) ) {
return 'NULL';
} elseif ( is_bool( $value ) ) {
return $value ? '(boolean) TRUE' : '(boolean) FALSE';
}
if ( is_object( $value ) ) {
$value = get_class( $value );
$type = '(object) ';
} elseif ( is_array( $value ) ) {
$type = '';
$value = var_export( $value, TRUE );
}
isset( $type ) or $type = '(' . gettype( $value ) . ') ';
return $type . (string) $value;
} | php | {
"resource": ""
} |
q7504 | NodeFactoryImpl.createNodeInstanceFromNodeParameter | train | public function createNodeInstanceFromNodeParameter($value, $type, $datatype = null, $language = null)
{
switch ($type) {
case 'uri':
return $this->createNamedNode($value);
case 'bnode':
return $this->createBlankNode($value);
case 'literal':
return $this->createLiteral($value, $datatype, $language);
case 'typed-literal':
return $this->createLiteral($value, $datatype, $language);
case 'var':
return $this->createAnyPattern();
default:
throw new \Exception('Unknown $type given: '.$type);
}
} | php | {
"resource": ""
} |
q7505 | Retriever.methodLoader | train | private function methodLoader($methods)
{
foreach ($methods as $key => $param) {
if (is_array($param)) {
$methods[$key] = $this->methodLoader($this->getExportParams($key));
continue;
}
$method = 'get' . SimpleDataObjectConverter::snakeCaseToUpperCamelCase($param);
if (method_exists($this, $method)) {
$methods[$param] = $this->{$method}();
unset($methods[$key]);
}
}
return $methods;
} | php | {
"resource": ""
} |
q7506 | Retriever.getExportParams | train | private function getExportParams($key = null)
{
if ($key && isset($this->exportParams[$key])) {
return $this->exportParams[$key];
}
return $this->exportParams;
} | php | {
"resource": ""
} |
q7507 | SimpleDoctrineMappingLocator.setPaths | train | public function setPaths($paths)
{
$this->paths = $paths;
self::$pathsMap[$this->namespace] = $this->paths;
} | php | {
"resource": ""
} |
q7508 | CmsMap._toHtml | train | protected function _toHtml()
{
if (!$this->getOptions()) {
$cmsPages = $this->cmsPageCollection->addStoreFilter($this->getStoreFromContext());
foreach ($cmsPages as $cmsPage) {
/** @var \Magento\Cms\Model\Page $cmsPage */
$this->addOption($cmsPage->getId(), $cmsPage->getTitle());
}
}
return parent::_toHtml();
} | php | {
"resource": ""
} |
q7509 | CmsMap.getStoreFromContext | train | public function getStoreFromContext()
{
$params = $this->getRequest()->getParams();
if (isset($params['store'])) {
return [$params['store']];
} elseif (isset($params['website'])) {
/** @var Website $website */
$website = $this->storeManager->getWebsite($params['website']);
return $website->getStoreIds();
}
return array_keys($this->storeManager->getStores());
} | php | {
"resource": ""
} |
q7510 | UserCredentialAbstract._initializeProfile | train | private function _initializeProfile($userProfile) {
die(print_r($userProfile));
//validate that user profile has the correct information for password validation
if (!is_array($userProfile)
|| !isset($userProfile['username'])
|| !isset($userProfile['password'])
|| !isset($userProfile['fullname'])
|| !isset($userProfile['passhash'])
|| !is_string($userProfile['passhash'])
|| !isset($userProfile['passhist'])
|| !is_array($userProfile['passhist'])
|| !isset($userProfile['account_state'])
|| !isset($userProfile['policyinfo'])
|| !is_array($userProfile['policyinfo'])
|| !is_array($userProfile['platforminfo'])
) {
throw new UserCredentialException('The user profile is not properly initialized', 1000);
}
//validate tenancy is a datetime
if (array_key_exists('tenancy_expiry', $userProfile['policyinfo'])) {
$tenancyExpiry = $userProfile['policyinfo']['tenancy_expiry'];
if (($tenancyExpiry instanceof \DateTime) === false) {
throw new UserCredentialException('The user profile is not properly initialized', 1000);
}
}
//set a blank TOTP profile if not set
if (!isset($userProfile['totpinfo'])) {
$userProfile['totpinfo'] = array();
}
$this->_userProfile = $userProfile;
} | php | {
"resource": ""
} |
q7511 | UserCredentialAbstract._validateConsecutiveCharacterRepeat | train | final protected function _validateConsecutiveCharacterRepeat() {
//validate that required indices exist
if (!isset($this->_userProfile['username'])
|| !isset($this->_userProfile['password'])
|| !isset($this->_userProfile['fullname'])
|| !isset($this->_userProfile['passhist'])
) {
throw new UserCredentialException('The username and password are not set', 1016);
}
//FOR CHARACTER REPETITION
//determine which entropy to use (base or udf)
$entropyObj = $this->_udfEntropySetting;
$maxConsecutiveChars = (int) ($entropyObj['max_consecutive_chars']);
//because we offset by -2 when doing regex, if the limit is not greater or equal to 2, default to 2
if (!($maxConsecutiveChars >= 2)) {
$maxConsecutiveChars = 2;
}
//offset for purposes of matching (TODO: fix?)
$maxConsecutiveCharsRegexOffset = ++$maxConsecutiveChars - 2;
//build regex
$maxConsecutiveCharsRegex = '/' . $this->_regexBuildPattern(5, $maxConsecutiveCharsRegexOffset) . '/';
$testVal = preg_match($maxConsecutiveCharsRegex,$this->_userProfile['password']);
if ($testVal === false) {
throw new UserCredentialException('A fatal error occured in the password validation', 1018);
} elseif ($testVal == true) {
throw new UserCredentialException('The password violates policy about consecutive character repetitions. '. $this->_getPasswordCharacterRepeatDescription(), \USERCREDENTIAL_ACCOUNTPOLICY_WEAKPASSWD);
} else {/*Do nothing*/}
//FOR CHARACTER CLASS REPETITION
//determine which entropy to use (base or udf)
$maxConsecutiveCharsSameClass = (int) ($entropyObj['max_consecutive_chars_of_same_class']);
//because we offset by -2 when doing regex, if the limit is not greater or equal to 2, default to 2
if (!($maxConsecutiveCharsSameClass >= 2)) {
$maxConsecutiveCharsSameClass = 2;
}
//offset for purposes of matching (TODO: fix?)
$maxConsecutiveCharsSameClassRegexOffset = ++$maxConsecutiveCharsSameClass;
//build regex
$maxConsecutiveCharsSameClassRegex = '/' . $this->_regexBuildPattern(6, $maxConsecutiveCharsSameClassRegexOffset) . '/';
$testValSameClass = preg_match($maxConsecutiveCharsSameClassRegex,$this->_userProfile['password']);
if ($testValSameClass === false) {
throw new UserCredentialException('A fatal error occured in the password validation', 1018);
} elseif ($testValSameClass == true) {
throw new UserCredentialException('The password violates policy about consecutive repetition of characters of the same class. '. $this->_getPasswordCharacterClassRepeatDescription(), \USERCREDENTIAL_ACCOUNTPOLICY_WEAKPASSWD);
} else {
return true;
}
return true;
} | php | {
"resource": ""
} |
q7512 | UserCredentialAbstract._validatePolicy | train | final protected function _validatePolicy() {
//validate that required indices exist
if (!isset($this->_userProfile['username'])
|| !isset($this->_userProfile['password'])
|| !isset($this->_userProfile['fullname'])
|| !isset($this->_userProfile['passhist'])
) {
throw new UserCredentialException('The username and password are not set', 1016);
}
//determine which entropy to use (base or udf)
$policyObj = $this->_udfPasswordPolicy;
//check attempt limits
if ($this->_userProfile['account_state'] == \USERCREDENTIAL_ACCOUNTSTATE_AUTHFAILED) {
if ($this->_userProfile['policyinfo']['failed_attempt_count'] > $policyObj['illegal_attempts_limit']) {
throw new UserCredentialException('The account has exceeded login attempts and is locked. Contact admin', \USERCREDENTIAL_ACCOUNTPOLICY_ATTEMPTLIMIT2);
} elseif ($this->_userProfile['policyinfo']['failed_attempt_count'] == $policyObj['illegal_attempts_limit']) {
throw new UserCredentialException('The account has failed login '.(++$policyObj['illegal_attempts_limit']).' times in a row and is temporarily locked. Any further wrong passwords will lead to your account being locked fully. You will be automatically unlocked in '.(($policyObj['illegal_attempts_penalty_seconds']) / 60).' minutes or contact admin to unlock immediately', \USERCREDENTIAL_ACCOUNTPOLICY_ATTEMPTLIMIT1);
} else {
throw new UserCredentialException('Login failed. Wrong username or password', \USERCREDENTIAL_ACCOUNTPOLICY_VALID);
}
}
//check needs reset
$currDateTimeObj = new \DateTime();
$passChangeDaysElapsedObj = $currDateTimeObj->diff($this->_userProfile['policyinfo']['password_last_changed_datetime']);
$passChangeDaysElapsed = $passChangeDaysElapsedObj->format('%a');
if ($passChangeDaysElapsed > $policyObj['password_reset_frequency']) {
throw new UserCredentialException('The password has expired and must be changed', \USERCREDENTIAL_ACCOUNTPOLICY_EXPIRED);
}
return true;
} | php | {
"resource": ""
} |
q7513 | UserCredentialAbstract._validatePolicyAtChange | train | final protected function _validatePolicyAtChange() {
//validate that required indices exist
if (!isset($this->_userProfile['username'])
|| !isset($this->_userProfile['password'])
|| !isset($this->_userProfile['fullname'])
|| !isset($this->_userProfile['passhist'])
) {
throw new UserCredentialException('The username and password are not set', 1016);
}
//determine which entropy to use (base or udf)
$policyObj = $this->_udfPasswordPolicy;
//check password repeat
$passHistory = $this->_userProfile['passhist'];
$passHistoryRequired = array_slice($passHistory, 0, ((int) $policyObj['password_repeat_minimum']));
//iterate and verify
foreach ($passHistoryRequired as $passHistoryItem) {
if (password_verify($this->_userProfile['password'], $passHistoryItem)) {
throw new UserCredentialException('User cannot repeat any of their ' . $policyObj['password_repeat_minimum'] . ' last passwords', \USERCREDENTIAL_ACCOUNTPOLICY_REPEATERROR);
}
}
return true;
} | php | {
"resource": ""
} |
q7514 | UserCredentialAbstract._canChangePassword | train | final protected function _canChangePassword() {
//validate that required indices exist
if (!isset($this->_userProfile['username'])
|| !isset($this->_userProfile['password'])
|| !isset($this->_userProfile['fullname'])
|| !isset($this->_userProfile['passhist'])
) {
throw new UserCredentialException('The username and password are not set', 1016);
}
//Verify if the password was changed today or server has been futuredated
$currDateTimeObj = new \DateTime();
//Password was changed today or in the future
if ($currDateTimeObj <= $this->_userProfile['policyinfo']['password_last_changed_datetime']) {
return false;
} else {
return true;
}
} | php | {
"resource": ""
} |
q7515 | UserCredentialAbstract._validateTenancy | train | final protected function _validateTenancy() {
$userProfile = $this->_userProfile;
//Verify if the password was changed today or server has been futuredated
$currDateTimeObj = new \DateTime();
//if account has tenancy expiry, deny login if user account tenancy is past
if (array_key_exists('tenancy_expiry', $userProfile['policyinfo'])) {
$tenancyExpiry = $userProfile['policyinfo']['tenancy_expiry'];
if ($currDateTimeObj > $tenancyExpiry) {
throw new UserCredentialException('Tenancy problem with your account. Please contact your Administrator');
}
}
return true;
} | php | {
"resource": ""
} |
q7516 | AbstractAclManager.doLoadAcl | train | protected function doLoadAcl(ObjectIdentityInterface $objectIdentity)
{
$acl = null;
try {
$acl = $this->getAclProvider()->createAcl($objectIdentity);
} catch (AclAlreadyExistsException $ex) {
$acl = $this->getAclProvider()->findAcl($objectIdentity);
}
return $acl;
} | php | {
"resource": ""
} |
q7517 | FTPClient.connect | train | public function connect($timeout = 90) {
$host = $this->getAuthenticator()->getHost();
$port = $this->getAuthenticator()->getPort();
$this->setConnection(@ftp_connect($host, $port, $timeout));
if (false === $this->getConnection()) {
throw $this->newFTPException("connection failed");
}
return $this;
} | php | {
"resource": ""
} |
q7518 | FTPClient.delete | train | public function delete($path) {
if (false === @ftp_delete($this->getConnection(), $path)) {
throw $this->newFTPException(sprintf("delete %s failed", $path));
}
return $this;
} | php | {
"resource": ""
} |
q7519 | FTPClient.pasv | train | public function pasv($pasv) {
if (false === @ftp_pasv($this->getConnection(), $pasv)) {
throw $this->newFTPException(sprintf("pasv from %d to %d failed", !$pasv, $pasv));
}
return $this;
} | php | {
"resource": ""
} |
q7520 | FTPClient.put | train | public function put($localFile, $remoteFile, $mode = FTP_IMAGE, $startPos = 0) {
if (false === @ftp_put($this->getConnection(), $remoteFile, $localFile, $mode, $startPos)) {
throw $this->newFTPException(sprintf("put %s into %s failed", $localFile, $remoteFile));
}
return $this;
} | php | {
"resource": ""
} |
q7521 | Illuminate.alwaysFrom | train | public function alwaysFrom(string $address, ?string $name = null): void
{
$this->getMailer()->alwaysFrom($address, $name);
} | php | {
"resource": ""
} |
q7522 | Illuminate.alwaysTo | train | public function alwaysTo(string $address, ?string $name = null): void
{
$this->getMailer()->alwaysTo($address, $name);
} | php | {
"resource": ""
} |
q7523 | Illuminate.plain | train | public function plain(string $view, array $data, $callback): Receipt
{
return $this->send(['text' => $view], $data, $callback);
} | php | {
"resource": ""
} |
q7524 | Illuminate.setQueue | train | public function setQueue(QueueContract $queue)
{
if ($this->mailer instanceof MailerContract) {
$this->mailer->setQueue($queue);
}
$this->queue = $queue;
return $this;
} | php | {
"resource": ""
} |
q7525 | Illuminate.handleQueuedMessage | train | public function handleQueuedMessage(Job $job, $data)
{
$this->send($data['view'], $data['data'], $this->getQueuedCallable($data));
$job->delete();
} | php | {
"resource": ""
} |
q7526 | Config.loadUndefinedConfigPaths | train | public function loadUndefinedConfigPaths()
{
$list = [];
$collection = $this->coreConfig->getCollectionByPath(SgCoreInterface::PATH_UNDEFINED . '%');
/** @var \Magento\Framework\App\Config\Value $item */
foreach ($collection as $item) {
$path = explode('/', $item->getPath());
$key = array_pop($path);
$list[$key] = $item->getPath();
}
return $list;
} | php | {
"resource": ""
} |
q7527 | Config.getShopNumber | train | public function getShopNumber()
{
$shopNumber = $this->request->getParam('shop_number');
$item = $this->sgCoreConfig->getShopNumberCollection($shopNumber)->getFirstItem();
return $item->getData('value') ? $shopNumber : '';
} | php | {
"resource": ""
} |
q7528 | NotifierServiceProvider.registerMailer | train | protected function registerMailer(): void
{
$this->app->singleton('orchestra.mail', function ($app) {
$mailer = new Mailer($app, $transport = new TransportManager($app));
if ($app->bound('orchestra.platform.memory')) {
$mailer->attach($memory = $app->make('orchestra.platform.memory'));
$transport->setMemoryProvider($memory);
}
if ($app->bound('queue')) {
$mailer->setQueue($app->make('queue'));
}
return $mailer;
});
} | php | {
"resource": ""
} |
q7529 | NotifierServiceProvider.registerIlluminateMailerResolver | train | protected function registerIlluminateMailerResolver(): void
{
$this->app->afterResolving('mailer', function ($service) {
$this->app->make('orchestra.mail')->configureIlluminateMailer($service);
});
} | php | {
"resource": ""
} |
q7530 | S3Transporter.delete | train | public function delete($id) {
$params = $this->parseUrl($id);
try {
$this->getClient()->deleteObject(array(
'Bucket' => $params['bucket'],
'Key' => $params['key']
));
} catch (S3Exception $e) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q7531 | S3Transporter.parseUrl | train | public function parseUrl($url) {
$region = $this->getConfig('region');
$bucket = $this->getConfig('bucket');
$key = $url;
if (strpos($url, 'amazonaws.com') !== false) {
// s3<region>.amazonaws.com/<bucket>
if (preg_match('/^https?:\/\/s3(.+?)?\.amazonaws\.com\/(.+?)\/(.+?)$/i', $url, $matches)) {
$region = $matches[1] ?: $region;
$bucket = $matches[2];
$key = $matches[3];
// <bucket>.s3<region>.amazonaws.com
} else if (preg_match('/^https?:\/\/(.+?)\.s3(.+?)?\.amazonaws\.com\/(.+?)$/i', $url, $matches)) {
$bucket = $matches[1];
$region = $matches[2] ?: $region;
$key = $matches[3];
}
}
return array(
'bucket' => $bucket,
'key' => trim($key, '/'),
'region' => trim($region, '-')
);
} | php | {
"resource": ""
} |
q7532 | Net_SFTP_Stream.register | train | static function register($protocol = 'sftp')
{
if (in_array($protocol, stream_get_wrappers(), true)) {
return false;
}
$class = function_exists('get_called_class') ? get_called_class() : __CLASS__;
return stream_wrapper_register($protocol, $class);
} | php | {
"resource": ""
} |
q7533 | UserCredentialGoogleAuthLoginService.checkToken | train | protected function checkToken() {
//instantiate MultiOtp Wrapper
$multiOtpWrapper = new MultiotpWrapper();
//get the username
$currentUserName = $this->getCurrentUsername();
//assert that username is set
if (!(\strlen((string) $currentUserName))) {
throw new UserCredentialException('Cannot validate a TOTP token when username is not set!', 2106);
}
//assert that the token exists
$tokenExists = $multiOtpWrapper->CheckTokenExists($currentUserName);
if (!($tokenExists)) {
throw new UserCredentialException('The TOTP token for the current user does not exist', 2107);
}
//username mapped to their token name
$multiOtpWrapper->setToken($currentUserName);
//validate the Token
$oneTimeToken = $this->getOneTimeToken();
$tokenCheckResult = $multiOtpWrapper->CheckToken($oneTimeToken);
//The results are reversed
//TODO: Add intepretation of MultiOtp return results here to enable exception handling
if ($tokenCheckResult == 0) {
return true;
} else {
return false;
}
} | php | {
"resource": ""
} |
q7534 | Regions.getIsoStateByMagentoRegion | train | public function getIsoStateByMagentoRegion(DataObject $address)
{
$map = $this->getIsoToMagentoMapping();
$sIsoCode = null;
if ($address->getData('country_id') && $address->getData('region_code')) {
$sIsoCode = $address->getData('country_id') . "-" . $address->getData('region_code');
}
if (isset($map[$address->getData('country_id')])) {
foreach ($map[$address->getData('country_id')] as $isoCode => $mageCode) {
if ($mageCode === $address->getData('region_code')) {
$sIsoCode = $address->getData('country_id') . "-" . $isoCode;
break;
}
}
}
return $sIsoCode;
} | php | {
"resource": ""
} |
q7535 | SerializerEasyRdf.serializeIteratorToStream | train | public function serializeIteratorToStream(StatementIterator $statements, $outputStream)
{
/*
* check parameter $outputStream
*/
if (is_resource($outputStream)) {
// use it as it is
} elseif (is_string($outputStream)) {
$outputStream = fopen($outputStream, 'w');
} else {
throw new \Exception('Parameter $outputStream is neither a string nor resource.');
}
$graph = new \EasyRdf_Graph();
// go through all statements
foreach ($statements as $statement) {
/*
* Handle subject
*/
$stmtSubject = $statement->getSubject();
if ($stmtSubject->isNamed()) {
$s = $stmtSubject->getUri();
} elseif ($stmtSubject->isBlank()) {
$s = '_:'.$stmtSubject->getBlankId();
} else {
throw new \Exception('Subject can either be a blank node or an URI.');
}
/*
* Handle predicate
*/
$stmtPredicate = $statement->getPredicate();
if ($stmtPredicate->isNamed()) {
$p = $stmtPredicate->getUri();
} else {
throw new \Exception('Predicate can only be an URI.');
}
/*
* Handle object
*/
$stmtObject = $statement->getObject();
if ($stmtObject->isNamed()) {
$o = ['type' => 'uri', 'value' => $stmtObject->getUri()];
} elseif ($stmtObject->isBlank()) {
$o = ['type' => 'bnode', 'value' => '_:'.$stmtObject->getBlankId()];
} elseif ($stmtObject->isLiteral()) {
$o = [
'type' => 'literal',
'value' => $stmtObject->getValue(),
'datatype' => $stmtObject->getDataType()->getUri(),
];
} else {
throw new \Exception('Object can either be a blank node, an URI or literal.');
}
$graph->add($s, $p, $o);
}
fwrite($outputStream, $graph->serialise($this->serialization).PHP_EOL);
} | php | {
"resource": ""
} |
q7536 | OptionList.set | train | public function set(string $name, $value, int $type = self::TYPE_LOCAL): OptionList
{
if ($type == self::TYPE_GLOBAL) {
self::$globalOptions[$name] = $value;
} else {
$this->options[$name] = $value;
}
return $this;
} | php | {
"resource": ""
} |
q7537 | OptionList.isset | train | public function isset(string $name, int $type = null): bool
{
if (is_null($type)) {
return array_key_exists($name, $this->options) || array_key_exists($name, self::$globalOptions);
} else {
if ($type == self::TYPE_GLOBAL) {
return array_key_exists($name, self::$globalOptions);
} else {
return array_key_exists($name, $this->options);
}
}
} | php | {
"resource": ""
} |
q7538 | OptionList.getGlobal | train | public static function getGlobal(string $name)
{
if (isset(self::$globalOptions[$name])) {
return self::$globalOptions[$name];
} else {
return null;
}
} | php | {
"resource": ""
} |
q7539 | OptionList.is_null | train | public function is_null(string $name, int $type = null): bool
{
if (isset(self::$globalOptions[$name]) && (is_null($type) || $type == self::TYPE_GLOBAL)) {
return is_null(self::$globalOptions[$name]);
} else {
if (isset($this->options[$name]) && (is_null($type) || $type == self::TYPE_LOCAL)) {
return is_null($this->options[$name]);
} else {
return true;
}
}
} | php | {
"resource": ""
} |
q7540 | LocalFile.getByIdentifier | train | public static function getByIdentifier($id)
{
$file = config('filer.hash_routes') ? static::whereHash($id)->first() : static::find($id);
if (!$file) {
throw (new ModelNotFoundException)->setModel(static::class);
}
return $file;
} | php | {
"resource": ""
} |
q7541 | FileHelper.appendTo | train | public static function appendTo($src, $dest, $newline = false) {
// Open the destination.
$reader = @fopen($src, "r");
if (false === $reader) {
throw new FileNotFoundException($src);
}
// Open the destination.
$writer = @fopen($dest, "a");
if (false === $writer) {
throw new IOException(sprintf("Failed to open \"%s\"", $dest));
}
// Append the source into destination.
if (false === @file_put_contents($dest, $reader, FILE_APPEND)) {
throw new IOException(sprintf("Failed to append \"%s\" into \"%s\"", $src, $dest));
}
// Append a new line.
if (true === $newline && false === @file_put_contents($dest, "\n", FILE_APPEND)) {
throw new IOException(sprintf("Failed to append \"%s\" into \"%s\"", $src, $dest));
}
// Close the files.
if (false === @fclose($reader)) {
throw new IOException(sprintf("Failed to close \"%s\"", $src));
}
if (false === @fclose($writer)) {
throw new IOException(sprintf("Failed to close \"%s\"", $dest));
}
} | php | {
"resource": ""
} |
q7542 | FileHelper.formatSize | train | public static function formatSize($size, $unit = null, $decimals = 2) {
// Initialize the units.
$units = static::getUnits();
// Find the unit.
$index = array_search($unit, $units);
if (null !== $unit && false === $index) {
throw new IllegalArgumentException("The unit \"" . $unit . "\" does not exists");
}
// Initialize the output.
$output = $size;
$iteration = 0;
while (self::FILE_SIZE_DIVIDER <= $output || $iteration < $index) {
$output /= self::FILE_SIZE_DIVIDER;
++$iteration;
}
// Return the output.
return implode(" ", [sprintf("%." . $decimals . "f", $output), $units[$iteration]]);
} | php | {
"resource": ""
} |
q7543 | FileHelper.getFilenames | train | public static function getFilenames($pathname, $extension = null) {
// Check if the directory exists.
if (false === file_exists($pathname)) {
throw new FileNotFoundException($pathname);
}
// Initialize the filenames.
$filenames = [];
// Open the directory.
if (false !== ($directory = opendir($pathname))) {
// Initialize the offset.
$offset = strlen($extension);
// Read the directory.
while (($file = readdir($directory)) !== false) {
// Determines if the file should be added.
if (false === in_array($file, [".", ".."]) && ((null === $extension) || 0 === substr_compare($file, $extension, -$offset))) {
$filenames[] = $file;
}
}
// Close the directory.
closedir($directory);
}
// Return the filenames.
return $filenames;
} | php | {
"resource": ""
} |
q7544 | FileHelper.getSize | train | public static function getSize($filename) {
if (false === file_exists($filename)) {
throw new FileNotFoundException($filename);
}
clearstatcache();
return filesize($filename);
} | php | {
"resource": ""
} |
q7545 | FileHelper.getUnits | train | public static function getUnits() {
return [
self::FILE_SIZE_UNIT_B,
self::FILE_SIZE_UNIT_KB,
self::FILE_SIZE_UNIT_MB,
self::FILE_SIZE_UNIT_GB,
self::FILE_SIZE_UNIT_TB,
self::FILE_SIZE_UNIT_PB,
self::FILE_SIZE_UNIT_EB,
self::FILE_SIZE_UNIT_ZB,
self::FILE_SIZE_UNIT_YB,
];
} | php | {
"resource": ""
} |
q7546 | FileHelper.zip | train | public static function zip($source, $destination) {
// Check if the filename exists.
if (false === file_exists($source)) {
throw new FileNotFoundException($source);
}
// Initialize the ZIP archive.
$zip = new ZipArchive();
$zip->open($destination, ZipArchive::CREATE);
// Clean up.
$src = str_replace("\\\\", "/", realpath($source));
// Is file ? => Add it and return.
if (true === is_file($src)) {
$zip->addFromString(basename($src), static::getContents($src));
return $zip->close();
}
// Handle the files list.
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($src), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $current) {
// Clean up.
$cur = str_replace("\\\\", "/", realpath($current));
// Initialize the ZIP path.
$zipPath = preg_replace("/^" . str_replace("/", "\/", $src . "/") . "/", "", $cur);
// Check the file type.
if (true === is_file($cur)) {
$zip->addFromString($zipPath, static::getContents($cur));
}
if (true === is_dir($cur)) {
$zip->addEmptyDir($zipPath);
}
}
} | php | {
"resource": ""
} |
q7547 | Address.exists | train | public function exists($customerId, array $addressToCheck)
{
unset($addressToCheck['email']);
if (empty($addressToCheck['company'])) {
// company would be cast to an empty string, which does not match NULL in the database
unset($addressToCheck['company']);
}
$addressCollection = $this->addressFactory->create()
->getCollection()
->addFieldToFilter('parent_id', $customerId);
foreach ($addressToCheck as $addressField => $fieldValue) {
$addressCollection->addFieldToFilter(
$addressField,
$fieldValue
);
}
return $addressCollection->count() > 0;
} | php | {
"resource": ""
} |
q7548 | QuickSort.quickSort | train | private function quickSort($min, $max) {
$i = $min;
$j = $max;
$pivot = $this->values[$min + ($max - $min) / 2];
while ($i <= $j) {
while (true === $this->functor->compare($this->values[$i], $pivot)) {
++$i;
}
while (true === $this->functor->compare($pivot, $this->values[$j])) {
--$j;
}
if ($i <= $j) {
$this->swap($i, $j);
++$i;
--$j;
}
}
if ($min < $j) {
$this->quickSort($min, $j);
}
if ($i < $max) {
$this->quickSort($i, $max);
}
} | php | {
"resource": ""
} |
q7549 | QuickSort.swap | train | private function swap($a, $b) {
$value = $this->values[$a];
$this->values[$a] = $this->values[$b];
$this->values[$b] = $value;
} | php | {
"resource": ""
} |
q7550 | Crypt_RSA._decodeLength | train | function _decodeLength(&$string)
{
$length = ord($this->_string_shift($string));
if ($length & 0x80) { // definite length, long form
$length&= 0x7F;
$temp = $this->_string_shift($string, $length);
list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
}
return $length;
} | php | {
"resource": ""
} |
q7551 | Crypt_RSA._rsaes_pkcs1_v1_5_encrypt | train | function _rsaes_pkcs1_v1_5_encrypt($m)
{
$mLen = strlen($m);
// Length checking
if ($mLen > $this->k - 11) {
user_error('Message too long');
return false;
}
// EME-PKCS1-v1_5 encoding
$psLen = $this->k - $mLen - 3;
$ps = '';
while (strlen($ps) != $psLen) {
$temp = crypt_random_string($psLen - strlen($ps));
$temp = str_replace("\x00", '', $temp);
$ps.= $temp;
}
$type = 2;
// see the comments of _rsaes_pkcs1_v1_5_decrypt() to understand why this is being done
if (defined('CRYPT_RSA_PKCS15_COMPAT') && (!isset($this->publicExponent) || $this->exponent !== $this->publicExponent)) {
$type = 1;
// "The padding string PS shall consist of k-3-||D|| octets. ... for block type 01, they shall have value FF"
$ps = str_repeat("\xFF", $psLen);
}
$em = chr(0) . chr($type) . $ps . chr(0) . $m;
// RSA encryption
$m = $this->_os2ip($em);
$c = $this->_rsaep($m);
$c = $this->_i2osp($c, $this->k);
// Output the ciphertext C
return $c;
} | php | {
"resource": ""
} |
q7552 | Crypt_RSA._rsassa_pkcs1_v1_5_verify | train | function _rsassa_pkcs1_v1_5_verify($m, $s)
{
// Length checking
if (strlen($s) != $this->k) {
user_error('Invalid signature');
return false;
}
// RSA verification
$s = $this->_os2ip($s);
$m2 = $this->_rsavp1($s);
if ($m2 === false) {
user_error('Invalid signature');
return false;
}
$em = $this->_i2osp($m2, $this->k);
if ($em === false) {
user_error('Invalid signature');
return false;
}
// EMSA-PKCS1-v1_5 encoding
$em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
if ($em2 === false) {
user_error('RSA modulus too short');
return false;
}
// Compare
return $this->_equals($em, $em2);
} | php | {
"resource": ""
} |
q7553 | CallableReflection.getReflector | train | public function getReflector()
{
if ($this->isFunction() || $this->isClosure()) {
return new \ReflectionFunction($this->getCallable());
}
if ($this->isMethod()) {
return new \ReflectionMethod($this->getClassName(), $this->getMethodName());
}
if ($this->isInvokedObject()) {
return new \ReflectionMethod($this->getClassName(), '__invoke');
}
throw new \LogicException('Unknown callable reflection');
} | php | {
"resource": ""
} |
q7554 | AbstractApi.getCloudInstance | train | public static function getCloudInstance($accessKey, $secretKey, $apiHost, $cloudId)
{
$config = array(
'accounts' => array(
'default' => array(
'access_key' => $accessKey,
'secret_key' => $secretKey,
'api_host' => $apiHost,
),
),
'clouds' => array(
'default' => array(
'id' => $cloudId,
'account' => 'default',
)
),
);
/** @var \Xabbuh\PandaClient\AbstractApi $api */
$api = new static($config);
return $api->getCloud('default');
} | php | {
"resource": ""
} |
q7555 | File_X509._mapInAttributes | train | function _mapInAttributes(&$root, $path, $asn1)
{
$attributes = &$this->_subArray($root, $path);
if (is_array($attributes)) {
for ($i = 0; $i < count($attributes); $i++) {
$id = $attributes[$i]['type'];
/* $value contains the DER encoding of an ASN.1 value
corresponding to the attribute type identified by type */
$map = $this->_getMapping($id);
if (is_array($attributes[$i]['value'])) {
$values = &$attributes[$i]['value'];
for ($j = 0; $j < count($values); $j++) {
$value = $asn1->encodeDER($values[$j], $this->AttributeValue);
$decoded = $asn1->decodeBER($value);
if (!is_bool($map)) {
$mapped = $asn1->asn1map($decoded[0], $map);
if ($mapped !== false) {
$values[$j] = $mapped;
}
if ($id == 'pkcs-9-at-extensionRequest' && $this->_isSubArrayValid($values, $j)) {
$this->_mapInExtensions($values, $j, $asn1);
}
} elseif ($map) {
$values[$j] = base64_encode($value);
}
}
}
}
}
} | php | {
"resource": ""
} |
q7556 | File_X509._mapOutAttributes | train | function _mapOutAttributes(&$root, $path, $asn1)
{
$attributes = &$this->_subArray($root, $path);
if (is_array($attributes)) {
$size = count($attributes);
for ($i = 0; $i < $size; $i++) {
/* [value] contains the DER encoding of an ASN.1 value
corresponding to the attribute type identified by type */
$id = $attributes[$i]['type'];
$map = $this->_getMapping($id);
if ($map === false) {
user_error($id . ' is not a currently supported attribute', E_USER_NOTICE);
unset($attributes[$i]);
} elseif (is_array($attributes[$i]['value'])) {
$values = &$attributes[$i]['value'];
for ($j = 0; $j < count($values); $j++) {
switch ($id) {
case 'pkcs-9-at-extensionRequest':
$this->_mapOutExtensions($values, $j, $asn1);
break;
}
if (!is_bool($map)) {
$temp = $asn1->encodeDER($values[$j], $map);
$decoded = $asn1->decodeBER($temp);
$values[$j] = $asn1->asn1map($decoded[0], $this->AttributeValue);
}
}
}
}
}
} | php | {
"resource": ""
} |
q7557 | File_X509._mapOutDNs | train | function _mapOutDNs(&$root, $path, $asn1)
{
$dns = &$this->_subArray($root, $path);
if (is_array($dns)) {
$size = count($dns);
for ($i = 0; $i < $size; $i++) {
for ($j = 0; $j < count($dns[$i]); $j++) {
$type = $dns[$i][$j]['type'];
$value = &$dns[$i][$j]['value'];
if (is_object($value) && strtolower(get_class($value)) == 'file_asn1_element') {
continue;
}
$map = $this->_getMapping($type);
if (!is_bool($map)) {
$value = new File_ASN1_Element($asn1->encodeDER($value, $map));
}
}
}
}
} | php | {
"resource": ""
} |
q7558 | File_X509._decodeIP | train | function _decodeIP($ip)
{
$ip = base64_decode($ip);
list(, $ip) = unpack('N', $ip);
return long2ip($ip);
} | php | {
"resource": ""
} |
q7559 | File_X509.removeDNProp | train | function removeDNProp($propName)
{
if (empty($this->dn)) {
return;
}
if (($propName = $this->_translateDNProp($propName)) === false) {
return;
}
$dn = &$this->dn['rdnSequence'];
$size = count($dn);
for ($i = 0; $i < $size; $i++) {
if ($dn[$i][0]['type'] == $propName) {
unset($dn[$i]);
}
}
$dn = array_values($dn);
} | php | {
"resource": ""
} |
q7560 | File_X509.getChain | train | function getChain()
{
$chain = array($this->currentCert);
if (!is_array($this->currentCert) || !isset($this->currentCert['tbsCertificate'])) {
return false;
}
if (empty($this->CAs)) {
return $chain;
}
while (true) {
$currentCert = $chain[count($chain) - 1];
for ($i = 0; $i < count($this->CAs); $i++) {
$ca = $this->CAs[$i];
if ($currentCert['tbsCertificate']['issuer'] === $ca['tbsCertificate']['subject']) {
$authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier', $currentCert);
$subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca);
switch (true) {
case !is_array($authorityKey):
case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID:
if ($currentCert === $ca) {
break 3;
}
$chain[] = $ca;
break 2;
}
}
}
if ($i == count($this->CAs)) {
break;
}
}
foreach ($chain as $key => $value) {
$chain[$key] = new File_X509();
$chain[$key]->loadX509($value);
}
return $chain;
} | php | {
"resource": ""
} |
q7561 | File_X509._removeExtension | train | function _removeExtension($id, $path = null)
{
$extensions = &$this->_extensions($this->currentCert, $path);
if (!is_array($extensions)) {
return false;
}
$result = false;
foreach ($extensions as $key => $value) {
if ($value['extnId'] == $id) {
unset($extensions[$key]);
$result = true;
}
}
$extensions = array_values($extensions);
return $result;
} | php | {
"resource": ""
} |
q7562 | CustomerParser.parseEntity | train | public function parseEntity(Customer $entity) {
$output = [
$this->encodeInteger($entity->getCustomerNumber(), 9),
$this->encodeString($entity->getTitle(), 10),
$this->encodeString($entity->getSurname(), 25),
$this->encodeString($entity->getFirstname(), 25),
$this->encodeString($entity->getStreet(), 25),
$this->encodeString($entity->getPCode(), 10),
$this->encodeString($entity->getCity(), 25),
$this->encodeString($entity->getCountry(), 3),
$this->encodeString($entity->getTaxCode(), 16),
$this->encodeString($entity->getIdDocumentNo(), 15),
$this->encodeString($entity->getTelephone(), 20),
$this->encodeString($entity->getRentalAgreementNo(), 20),
$this->encodeDate($entity->getBeginDate()),
$this->encodeDate($entity->getTerminationDate()),
$this->encodeInteger($entity->getDeposit(), 12),
$this->encodeInteger($entity->getMaximumLevel(), 4),
$this->encodeString($entity->getRemarks(), 50),
$this->encodeDateTime($entity->getDatetimeLastModification()),
$this->encodeBoolean($entity->getBlocked()),
$this->encodeDate($entity->getBlockedDate()),
$this->encodeBoolean($entity->getDeletedRecord()),
$this->encodeBoolean($entity->getTicketReturnAllowed()),
$this->encodeBoolean($entity->getGroupCounting()),
$this->encodeBoolean($entity->getEntryMaxLevelAllowed()),
$this->encodeBoolean($entity->getMaxLevelCarPark()),
$this->encodeString($entity->getRemarks2(), 50),
$this->encodeString($entity->getRemarks3(), 50),
$this->encodeString($entity->getDivision(), 25),
$this->encodeString($entity->getEmail(), 120),
$this->encodeBoolean($entity->getCountingNeutralCards()),
$this->encodeString($entity->getNationality(), 3),
$this->encodeString($entity->getAccountingNumber(), 20),
];
return implode(";", $output);
} | php | {
"resource": ""
} |
q7563 | LiteralPatternImpl.matches | train | public function matches(Node $toMatch)
{
if ($toMatch->isConcrete()) {
if ($toMatch instanceof Literal) {
return $this->getValue() === $toMatch->getValue()
&& $this->getDatatype() === $toMatch->getDatatype()
&& $this->getLanguage() === $toMatch->getLanguage();
}
return false;
} else {
throw new \Exception('The node to match has to be a concrete node');
}
} | php | {
"resource": ""
} |
q7564 | NotifierManager.createOrchestraDriver | train | protected function createOrchestraDriver(): Notification
{
$mailer = $this->app->make('orchestra.mail');
$notifier = new Handlers\Orchestra($mailer);
if ($mailer->attached()) {
$notifier->attach($mailer->getMemoryProvider());
} else {
$notifier->attach($this->app->make('orchestra.memory')->makeOrFallback());
}
return $notifier;
} | php | {
"resource": ""
} |
q7565 | Customer.getCustomFields | train | public function getCustomFields($object)
{
$customFields = [];
foreach ($object->getCustomFields() as $field) {
$customFields[$field->getInternalFieldName()] = $field->getValue();
}
return $customFields;
} | php | {
"resource": ""
} |
q7566 | Forwarder.startup | train | public function startup()
{
/** @var \Shopgate\Base\Helper\Initializer\Forwarder $forwarderInitializer */
$manager = ObjectManager::getInstance();
$forwarderInitializer = $manager->get('Shopgate\Base\Helper\Initializer\Forwarder');
$this->config = $forwarderInitializer->getMainConfig();
$this->settingsApi = $forwarderInitializer->getSettingsInterface();
$this->exportApi = $forwarderInitializer->getExportInterface();
$this->importApi = $forwarderInitializer->getImportInterface();
$this->cronApi = $forwarderInitializer->getCronInterface();
$configInitializer = $forwarderInitializer->getConfigInitializer();
$this->storeManager = $configInitializer->getStoreManager();
$this->config->loadConfig();
} | php | {
"resource": ""
} |
q7567 | AbstractMappingCompilerPass.addEntityMapping | train | protected function addEntityMapping(
ContainerBuilder $container,
$entityManagerName,
$entityNamespace,
$entityMappingFilePath,
$enable = true
) : self {
$entityMapping = $this->resolveEntityMapping(
$container,
$entityManagerName,
$entityNamespace,
$entityMappingFilePath,
$enable
);
if ($entityMapping instanceof EntityMapping) {
$this->registerLocatorConfigurator($container);
$this->registerLocator($container, $entityMapping);
$this->registerDriver($container, $entityMapping);
$this->addDriverInDriverChain($container, $entityMapping);
$this->addAliases($container, $entityMapping);
}
return $this;
} | php | {
"resource": ""
} |
q7568 | AbstractMappingCompilerPass.resolveEntityMapping | train | private function resolveEntityMapping(
ContainerBuilder $container,
string $entityManagerName,
string $entityNamespace,
string $entityMappingFilePath,
$enable = true
) : ? EntityMapping {
$enableEntityMapping = $this->resolveParameterName(
$container,
$enable
);
if (false === $enableEntityMapping) {
return null;
}
$entityNamespace = $this->resolveParameterName($container, $entityNamespace);
if (!class_exists($entityNamespace)) {
throw new ConfigurationInvalidException('Entity ' . $entityNamespace . ' not found');
}
$entityMappingFilePath = $this->resolveParameterName($container, $entityMappingFilePath);
$entityManagerName = $this->resolveParameterName($container, $entityManagerName);
$this->resolveEntityManagerName($container, $entityManagerName);
return new EntityMapping(
$entityNamespace,
$entityMappingFilePath,
$entityManagerName
);
} | php | {
"resource": ""
} |
q7569 | AbstractMappingCompilerPass.registerLocatorConfigurator | train | private function registerLocatorConfigurator(ContainerBuilder $container)
{
$locatorConfiguratorId = 'simple_doctrine_mapping.locator_configurator';
if ($container->hasDefinition($locatorConfiguratorId)) {
return;
}
$locatorConfigurator = new Definition('Mmoreram\SimpleDoctrineMapping\Configurator\LocatorConfigurator');
$locatorConfigurator->setPublic(true);
$locatorConfigurator->setArguments([
new Reference('kernel'),
]);
$container->setDefinition($locatorConfiguratorId, $locatorConfigurator);
} | php | {
"resource": ""
} |
q7570 | AbstractMappingCompilerPass.registerLocator | train | private function registerLocator(
ContainerBuilder $container,
EntityMapping $entityMapping
) {
/**
* Locator.
*/
$locatorId = 'simple_doctrine_mapping.locator.' . $entityMapping->getUniqueIdentifier();
$locator = new Definition('Mmoreram\SimpleDoctrineMapping\Locator\SimpleDoctrineMappingLocator');
$locator->setPublic(false);
$locator->setArguments([
$entityMapping->getEntityNamespace(),
[$entityMapping->getEntityMappingFilePath()],
]);
$locator->setConfigurator([
new Reference('simple_doctrine_mapping.locator_configurator'),
'configure',
]);
$container->setDefinition($locatorId, $locator);
} | php | {
"resource": ""
} |
q7571 | AbstractMappingCompilerPass.addDriverInDriverChain | train | private function addDriverInDriverChain(
ContainerBuilder $container,
EntityMapping $entityMapping
) {
$chainDriverDefinition = $container
->getDefinition(
'doctrine.orm.' . $entityMapping->getEntityManagerName() . '_metadata_driver'
);
$container->setParameter(
'doctrine.orm.metadata.driver_chain.class',
'Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain'
);
$chainDriverDefinition->addMethodCall('addDriver', [
new Reference(
'doctrine.orm.' . $entityMapping->getUniqueIdentifier() . '_metadata_driver'
),
$entityMapping->getEntityNamespace(),
]);
} | php | {
"resource": ""
} |
q7572 | AbstractMappingCompilerPass.addAliases | train | private function addAliases(
ContainerBuilder $container,
EntityMapping $entityMapping
) {
$entityMappingFilePath = $entityMapping->getEntityMappingFilePath();
if (strpos($entityMappingFilePath, '@') === 0) {
$bundleName = trim(explode('/', $entityMappingFilePath, 2)[0]);
$className = explode('\\', $entityMapping->getEntityNamespace());
unset($className[count($className) - 1]);
$configurationServiceDefinition = $container
->getDefinition(
'doctrine.orm.' . $entityMapping->getEntityManagerName() . '_configuration'
);
$configurationServiceDefinition->addMethodCall('addEntityNamespace', [
$bundleName,
implode('\\', $className),
]);
}
} | php | {
"resource": ""
} |
q7573 | AbstractMappingCompilerPass.resolveEntityManagerName | train | private function resolveEntityManagerName(
ContainerBuilder $container,
string $entityManagerName
) {
if (!$container->has('doctrine.orm.' . $entityManagerName . '_metadata_driver')) {
throw new EntityManagerNotFoundException($entityManagerName);
}
} | php | {
"resource": ""
} |
q7574 | CURLConfiguration.removeHeader | train | public function removeHeader($name) {
if (true === array_key_exists($name, $this->headers)) {
unset($this->headers[$name]);
}
} | php | {
"resource": ""
} |
q7575 | File.dimensions | train | public function dimensions() {
return $this->_cache(__FUNCTION__, function($file) {
/** @type \Transit\File $file */
$dims = null;
if (!$file->isImage()) {
return $dims;
}
$data = @getimagesize($file->path());
if ($data && is_array($data)) {
$dims = array(
'width' => $data[0],
'height' => $data[1]
);
}
if (!$data) {
$image = @imagecreatefromstring(file_get_contents($file->path()));
$dims = array(
'width' => @imagesx($image),
'height' => @imagesy($image)
);
}
return $dims;
});
} | php | {
"resource": ""
} |
q7576 | File.exif | train | public function exif(array $fields = array()) {
if (!function_exists('exif_read_data')) {
return array();
}
return $this->_cache(__FUNCTION__, function($file) use ($fields) {
/** @type \Transit\File $file */
$exif = array();
$fields = $fields + array(
'make' => 'Make',
'model' => 'Model',
'exposure' => 'ExposureTime',
'orientation' => 'Orientation',
'fnumber' => 'FNumber',
'date' => 'DateTime',
'iso' => 'ISOSpeedRatings',
'focal' => 'FocalLength',
'latitude' => 'GPSLatitude',
'longitude' => 'GPSLongitude'
);
if ($file->supportsExif()) {
if ($data = @exif_read_data($file->path())) {
foreach ($fields as $key => $find) {
$value = '';
if (!empty($data[$find])) {
// Convert DMS (degrees, minutes, seconds) to decimals
if ($key === 'latitude' || $key === 'longitude'){
$deg = $data[$find][0];
$min = $data[$find][1];
$sec = $data[$find][2];
$value = $deg + ((($min * 60) + $sec) / 3600);
} else {
$value = $data[$find];
}
}
$exif[$key] = $value;
}
}
}
// Return empty values for files that don't support exif
if (!$exif) {
$exif = array_map(function() {
return '';
}, $fields);
}
return $exif;
});
} | php | {
"resource": ""
} |
q7577 | File.ext | train | public function ext() {
return $this->_cache(__FUNCTION__, function($file) {
/** @type \Transit\File $file */
// @version 1.1.1 Removed because of fileinfo bug
// return MimeType::getExtFromType($file->type(), true);
// @version 1.2.0 Allow support for $_FILES array
$path = $file->data('name') ?: $file->path();
return mb_strtolower(pathinfo($path, PATHINFO_EXTENSION));
});
} | php | {
"resource": ""
} |
q7578 | File.height | train | public function height() {
return $this->_cache(__FUNCTION__, function($file) {
/** @type \Transit\File $file */
if (!$file->isImage()) {
return null;
}
$height = 0;
if ($dims = $file->dimensions()) {
$height = $dims['height'];
}
return $height;
});
} | php | {
"resource": ""
} |
q7579 | File.move | train | public function move($path, $overwrite = false) {
$path = str_replace('\\', '/', $path);
if (substr($path, -1) !== '/') {
$path .= '/';
}
// Don't move to the same folder
if (realpath($path) === realpath($this->dir())) {
return true;
}
if (!file_exists($path)) {
mkdir($path, 0777, true);
} else if (!is_writable($path)) {
chmod($path, 0777);
}
// Determine name and overwrite
$name = $this->name();
$ext = $this->ext();
if (!$overwrite) {
$no = 1;
while (file_exists($path . $name . '.' . $ext)) {
$name = $this->name() . '-' . $no;
$no++;
}
}
// Move the file
$targetPath = $path . $name . '.' . $ext;
if (rename($this->path(), $targetPath)) {
$this->reset($targetPath);
return true;
}
return false;
} | php | {
"resource": ""
} |
q7580 | File.rename | train | public function rename($name = '', $append = '', $prepend = '', $overwrite = false) {
if (is_callable($name)) {
$name = call_user_func_array($name, array($this->name(), $this));
} else {
$name = $name ?: $this->name();
}
// Add boundaries
$name = (string) $prepend . $name . (string) $append;
// Remove unwanted characters
$name = preg_replace('/[^_\-\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/imu', '-', $name);
// Rename file
$ext = $this->ext() ?: MimeType::getExtFromType($this->type(), true);
$newName = $name;
// Don't overwrite
if (!$overwrite) {
$no = 1;
while (file_exists($this->dir() . $newName . '.' . $ext)) {
$newName = $name . '-' . $no;
$no++;
}
}
$targetPath = $this->dir() . $newName . '.' . $ext;
if (rename($this->path(), $targetPath)) {
$this->reset($targetPath);
return true;
}
return false;
} | php | {
"resource": ""
} |
q7581 | File.reset | train | public function reset($path = '') {
clearstatcache();
$this->_cache = array();
if ($path) {
$this->_data['name'] = basename($path);
$this->_path = $path;
}
return $this;
} | php | {
"resource": ""
} |
q7582 | File.supportsExif | train | public function supportsExif() {
return $this->_cache(__FUNCTION__, function($file) {
/** @type \Transit\File $file */
if (!$file->isImage()) {
return false;
}
return in_array($file->type(), array('image/jpeg', 'image/tiff'));
});
} | php | {
"resource": ""
} |
q7583 | File.width | train | public function width() {
return $this->_cache(__FUNCTION__, function($file) {
/** @type \Transit\File $file */
if (!$file->isImage()) {
return null;
}
$width = 0;
if ($dims = $file->dimensions()) {
$width = $dims['width'];
}
return $width;
});
} | php | {
"resource": ""
} |
q7584 | File.toArray | train | public function toArray() {
$data = array(
'basename' => $this->basename(),
'dir' => $this->dir(),
'ext' => $this->ext(),
'name' => $this->name(),
'path' => $this->path(),
'size' => $this->size(),
'type' => $this->type(),
'height' => $this->height(),
'width' => $this->width()
);
// Include exif data
foreach ($this->exif() as $key => $value) {
$data['exif.' . $key] = $value;
}
return $data;
} | php | {
"resource": ""
} |
q7585 | File._cache | train | protected function _cache($key, Closure $callback) {
if (isset($this->_cache[$key])) {
return $this->_cache[$key];
}
// Requires 5.4
// Closure::bind($callback, $this, __CLASS__);
$this->_cache[$key] = $callback($this);
return $this->_cache[$key];
} | php | {
"resource": ""
} |
q7586 | MimeType.getExtFromType | train | public static function getExtFromType($type, $primary = false) {
$exts = array();
foreach (self::$_types as $ext => $mimeType) {
$isPrimary = false;
if (is_array($mimeType)) {
$mimeType = $mimeType[0];
$isPrimary = $mimeType[1];
}
if ($mimeType == $type) {
if ($primary && $isPrimary) {
return $ext;
}
$exts[] = $ext;
}
}
if ($primary && isset($exts[0])) {
return $exts[0];
}
return $exts;
} | php | {
"resource": ""
} |
q7587 | MimeType.getTypeFromExt | train | public static function getTypeFromExt($ext) {
if (isset(self::$_types[$ext])) {
$mime = self::$_types[$ext];
if (is_array($mime)) {
$mime = $mime[0];
}
return $mime;
}
throw new InvalidArgumentException(sprintf('Invalid extension %s', $ext));
} | php | {
"resource": ""
} |
q7588 | MimeType.getApplicationList | train | public static function getApplicationList() {
if (self::$_application) {
return self::$_application;
}
self::$_application = self::_getList('application');
return self::$_application;
} | php | {
"resource": ""
} |
q7589 | MimeType.getAudioList | train | public static function getAudioList() {
if (self::$_audio) {
return self::$_audio;
}
self::$_audio = self::_getList('audio');
return self::$_audio;
} | php | {
"resource": ""
} |
q7590 | MimeType.getImageList | train | public static function getImageList() {
if (self::$_image) {
return self::$_image;
}
self::$_image = self::_getList('image');
return self::$_image;
} | php | {
"resource": ""
} |
q7591 | MimeType.getTextList | train | public static function getTextList() {
if (self::$_text) {
return self::$_text;
}
self::$_text = self::_getList('text');
return self::$_text;
} | php | {
"resource": ""
} |
q7592 | MimeType.getVideoList | train | public static function getVideoList() {
if (self::$_video) {
return self::$_video;
}
self::$_video = self::_getList('video');
return self::$_video;
} | php | {
"resource": ""
} |
q7593 | MimeType.getSubTypeList | train | public static function getSubTypeList($type) {
if (empty(self::$_subTypes[$type])) {
throw new InvalidArgumentException(sprintf('Sub-type %s does not exist', $type));
}
$types = array();
foreach (self::$_subTypes[$type] as $ext) {
$types[$ext] = self::getTypeFromExt($ext);
}
return $types;
} | php | {
"resource": ""
} |
q7594 | MimeType.isSubType | train | public static function isSubType($subType, $mimeType) {
return in_array(self::_findMimeType($mimeType), self::getSubTypeList($subType));
} | php | {
"resource": ""
} |
q7595 | MimeType._getList | train | protected static function _getList($type) {
$types = array();
foreach (self::$_types as $ext => $mimeType) {
if (is_array($mimeType)) {
$mimeType = $mimeType[0];
}
if (strpos($mimeType, $type) === 0) {
$types[$ext] = $mimeType;
}
}
return $types;
} | php | {
"resource": ""
} |
q7596 | MimeType._findMimeType | train | protected static function _findMimeType($mimeType) {
if ($mimeType instanceof File) {
$mimeType = $mimeType->type();
} else if (strpos($mimeType, '/') === false) {
$mimeType = self::getTypeFromExt($mimeType);
}
return $mimeType;
} | php | {
"resource": ""
} |
q7597 | Quote.setExternalCoupons | train | protected function setExternalCoupons()
{
$quote = $this->quoteCouponHelper->setCoupon();
$this->quote->loadActive($quote->getEntityId());
} | php | {
"resource": ""
} |
q7598 | Quote.setItems | train | protected function setItems()
{
foreach ($this->sgBase->getItems() as $item) {
if ($item->isSgCoupon()) {
continue;
}
$info = $item->getInternalOrderInfo();
$amountNet = $item->getUnitAmount();
$amountGross = $item->getUnitAmountWithTax();
try {
$product = $this->productHelper->loadById($info->getProductId());
} catch (\Exception $e) {
$product = null;
}
if (!is_object($product) || !$product->getId() || $product->getStatus() != MageStatus::STATUS_ENABLED) {
$this->log->error('Product with ID ' . $info->getProductId() . ' could not be loaded.');
$this->log->error('SG item number: ' . $item->getItemNumber());
$item->setUnhandledError(\ShopgateLibraryException::CART_ITEM_PRODUCT_NOT_FOUND, 'product not found');
continue;
}
try {
$quoteItem = $this->getQuoteItem($item, $product);
if ($this->useShopgatePrices()) {
if ($this->taxData->priceIncludesTax($this->storeManager->getStore())) {
$quoteItem->setCustomPrice($amountGross);
$quoteItem->setOriginalCustomPrice($amountGross);
} else {
$quoteItem->setCustomPrice($amountNet);
$quoteItem->setOriginalCustomPrice($amountNet);
}
}
$quoteItem->setTaxPercent($item->getTaxPercent());
if (!$item->isSimple()) {
$productWeight = $product->getTypeInstance()->getWeight($product);
$quoteItem->setWeight($productWeight);
}
$quoteItem->setRowWeight($quoteItem->getWeight() * $quoteItem->getQty());
$this->quote->setItemsCount($this->quote->getItemsCount() + 1);
} catch (\Exception $e) {
$this->log->error(
"Error importing product to quote by id: {$product->getId()}, error: {$e->getMessage()}"
);
$this->log->error('SG item number: ' . $item->getItemNumber());
$item->setMagentoError($e->getMessage());
}
}
/**
* Magento's flow is to save Quote on addItem, then on saveOrder load quote again. We mimic this here.
*/
$this->quoteRepository->save($this->quote);
$this->quote = $this->quoteRepository->get($this->quote->getId());
} | php | {
"resource": ""
} |
q7599 | Quote.setCustomer | train | protected function setCustomer()
{
$this->quoteCustomer->setEntity($this->quote);
$this->quoteCustomer->setAddress($this->quote);
$this->quoteCustomer->resetGuest($this->quote);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.