_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q1800
MessageQuery.getFromName
train
public static function getFromName($messageName) { if (false === $message = MessageQuery::create()->filterByName($messageName)->findOne()) { throw new \Exception("Failed to load message $messageName."); } return $message; }
php
{ "resource": "" }
q1801
Registration.init
train
protected function init( $product, $dependency = 'boldgrid/library' ) { $this->product = $product; $this->dependency = $dependency; Option::init(); $this->libraries = Option::get( 'library' ); $this->verify(); }
php
{ "resource": "" }
q1802
Registration.register
train
public function register() { // Check the dependency version. $version = new Version( $this->getDependency() ); Option::set( $this->getProduct(), $version->getVersion() ); }
php
{ "resource": "" }
q1803
Payment.isValid
train
public function isValid(IsValidPaymentEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $module = $event->getModule(); // dispatch event to target specific module $dispatcher->dispatch( TheliaEvents::getModuleEvent( TheliaEvents::MODULE_PAYMENT_IS_VALID, $module->getCode() ), $event ); if ($event->isPropagationStopped()) { return; } // call legacy module method $event->setValidModule($module->isValidPayment()); }
php
{ "resource": "" }
q1804
RememberMeTrait.getRememberMeKeyFromCookie
train
protected function getRememberMeKeyFromCookie(Request $request, $cookieName) { $ctp = new CookieTokenProvider(); return $ctp->getKeyFromCookie($request, $cookieName); }
php
{ "resource": "" }
q1805
RememberMeTrait.createRememberMeCookie
train
protected function createRememberMeCookie(UserInterface $user, $cookieName, $cookieExpiration) { $ctp = new CookieTokenProvider(); $ctp->createCookie( $user, $cookieName, $cookieExpiration ); }
php
{ "resource": "" }
q1806
ConstantNode.toUpperCase
train
public function toUpperCase() { $token = $this->getConstantName()->lastToken(); $token->setText(strtoupper($token->getText())); return $this; }
php
{ "resource": "" }
q1807
ConstantNode.toLowerCase
train
public function toLowerCase() { $token = $this->getConstantName()->lastToken(); $token->setText(strtolower($token->getText())); return $this; }
php
{ "resource": "" }
q1808
EventManager.listen
train
public function listen($channel, $expr, callable $handler) { $this->adapter->subscribe($channel, function ($message) use ($expr, $handler) { $this->handleSubscribeCallback($message, $expr, $handler); }); }
php
{ "resource": "" }
q1809
EventManager.dispatchBatch
train
public function dispatchBatch($channel, array $events) { $messages = []; $validates = true; foreach ($events as $event) { /** @var EventInterface $event */ $event = $this->prepEventForDispatch($event); if ($this->validator) { $result = $this->validator->validate($event); if ($result->fails()) { $validates = false; // pass to validation fail handler? if ($this->validationFailHandler) { call_user_func($this->validationFailHandler, $result); } if ($this->throwValidationExceptionsOnDispatch) { throw new ValidationException($result); } } } $messages[] = $event->toMessage(); } if ($validates) { $this->adapter->publishBatch($channel, $messages); } }
php
{ "resource": "" }
q1810
CampfireFactory.make
train
public function make(array $config) { Arr::requires($config, ['from', 'token']); $client = new Client(); return new CampfireGateway($client, $config); }
php
{ "resource": "" }
q1811
BackendListener.getTableNames
train
public function getTableNames(GetPropertyOptionsEvent $event) { if (!$this->isBackendOptionRequestFor($event, ['tag_table'])) { return; } $sqlTable = $this->translator->trans( 'tl_metamodel_attribute.tag_table_type.sql-table', [], 'contao_tl_metamodel_attribute' ); $translated = $this->translator->trans( 'tl_metamodel_attribute.tag_table_type.translated', [], 'contao_tl_metamodel_attribute' ); $untranslated = $this->translator->trans( 'tl_metamodel_attribute.tag_table_type.untranslated', [], 'contao_tl_metamodel_attribute' ); $result = $this->getMetaModelTableNames($translated, $untranslated); foreach ($this->connection->getSchemaManager()->listTableNames() as $table) { if (0 !== \strpos($table, 'mm_')) { $result[$sqlTable][$table] = $table; } } if (\is_array($result[$translated])) { \asort($result[$translated]); } if (\is_array($result[$untranslated])) { \asort($result[$untranslated]); } if (\is_array($result[$sqlTable])) { \asort($result[$sqlTable]); } $event->setOptions($result); }
php
{ "resource": "" }
q1812
BackendListener.getColumnNames
train
public function getColumnNames(GetPropertyOptionsEvent $event) { if (!$this->isBackendOptionRequestFor($event, ['tag_column', 'tag_alias', 'tag_sorting'])) { return; } $result = $this->getColumnNamesFrom($event->getModel()->getProperty('tag_table')); if (!empty($result)) { \asort($result); $event->setOptions($result); } }
php
{ "resource": "" }
q1813
BackendListener.checkQuery
train
public function checkQuery(EncodePropertyValueFromWidgetEvent $event) { if (!$this->scopeMatcher->currentScopeIsBackend()) { return; } if (('tl_metamodel_attribute' !== $event->getEnvironment()->getDataDefinition()->getName()) || ('tag_where' !== $event->getProperty()) ) { return; } $where = $event->getValue(); $values = $event->getPropertyValueBag(); if ($where) { $query = $this->connection->createQueryBuilder() ->select($values->getPropertyValue('tag_table') . '.*') ->from($values->getPropertyValue('tag_table')) ->where($where) ->orderBy($values->getPropertyValue('tag_sorting') ?: $values->getPropertyValue('tag_id')); try { $query->execute(); } catch (\Exception $e) { throw new \RuntimeException( \sprintf( '%s %s', $this->translator->trans('sql_error', [], 'contao_tl_metamodel_attribute'), $e->getMessage() ) ); } } }
php
{ "resource": "" }
q1814
BackendListener.getColumnNamesFrom
train
private function getColumnNamesFrom($table) { if (0 === \strpos($table, 'mm_')) { $attributes = $this->getAttributeNamesFrom($table); \asort($attributes); $sql = $this->translator->trans( 'tl_metamodel_attribute.tag_column_type.sql', [], 'contao_tl_metamodel_attribute' ); $attribute = $this->translator->trans( 'tl_metamodel_attribute.tag_column_type.attribute', [], 'contao_tl_metamodel_attribute' ); return [ $sql => \array_diff_key( $this->getColumnNamesFromTable($table), \array_flip(\array_keys($attributes)) ), $attribute => $attributes, ]; } return $this->getColumnNamesFromTable($table); }
php
{ "resource": "" }
q1815
BackendListener.addCondition
train
private function addCondition($property, $condition) { $currentCondition = $property->getVisibleCondition(); if ((!($currentCondition instanceof ConditionChainInterface)) || ($currentCondition->getConjunction() != ConditionChainInterface::OR_CONJUNCTION) ) { if ($currentCondition === null) { $currentCondition = new PropertyConditionChain([$condition]); } else { $currentCondition = new PropertyConditionChain([$currentCondition, $condition]); } $currentCondition->setConjunction(ConditionChainInterface::OR_CONJUNCTION); $property->setVisibleCondition($currentCondition); } else { $currentCondition->addCondition($condition); } }
php
{ "resource": "" }
q1816
BackendListener.isBackendOptionRequestFor
train
private function isBackendOptionRequestFor($event, $fields) { if (!$this->scopeMatcher->currentScopeIsBackend()) { return false; } return ('tl_metamodel_attribute' === $event->getEnvironment()->getDataDefinition()->getName()) && \in_array($event->getPropertyName(), $fields); }
php
{ "resource": "" }
q1817
Cash.getClosestAcceptedCashAmount
train
protected function getClosestAcceptedCashAmount($amount): int { $value = Number::fromString($amount)->getIntegerPart(); $cent = $amount % 5; if ($cent <= 2) { $value = $value - $cent; } else { $value = $value + (5 - $cent); } return $value; }
php
{ "resource": "" }
q1818
Platform.getUri
train
public static function getUri() { $nginx_port = Docker::getContainerPort(Compose::getContainerName(self::projectName(), 'nginx'), 80); if (!$nginx_port) { throw new \RuntimeException("nginx container is not running"); } return "http://localhost:$nginx_port"; }
php
{ "resource": "" }
q1819
ClassMethodCallNode.create
train
public static function create($class_name, $method_name) { if (is_string($class_name)) { $class_name = NameNode::create($class_name); } /** @var ClassMethodCallNode $node */ $node = new static(); $node->addChild($class_name, 'className'); $node->addChild(Token::doubleColon()); $node->addChild(Token::identifier($method_name), 'methodName'); $node->addChild(Token::openParen(), 'openParen'); $node->addChild(new CommaListNode(), 'arguments'); $node->addChild(Token::closeParen(), 'closeParen'); return $node; }
php
{ "resource": "" }
q1820
BaseCachedFile.clearCache
train
public function clearCache(CachedFileEvent $event) { $path = $this->getCachePath($event->getCacheSubdirectory(), false); $this->clearDirectory($path); }
php
{ "resource": "" }
q1821
BaseCachedFile.clearDirectory
train
protected function clearDirectory($path) { $iterator = new \DirectoryIterator($path); /** @var \DirectoryIterator $fileinfo */ foreach ($iterator as $fileinfo) { if ($fileinfo->isDot()) { continue; } if ($fileinfo->isFile() || $fileinfo->isLink()) { @unlink($fileinfo->getPathname()); } elseif ($fileinfo->isDir()) { $this->clearDirectory($fileinfo->getPathname()); } } }
php
{ "resource": "" }
q1822
BaseCachedFile.getCacheFileURL
train
protected function getCacheFileURL($subdir, $safe_filename) { $path = $this->getCachePathFromWebRoot($subdir); return URL::getInstance()->absoluteUrl(sprintf("%s/%s", $path, $safe_filename), null, URL::PATH_TO_FILE, $this->cdnBaseUrl); }
php
{ "resource": "" }
q1823
BaseCachedFile.getCacheFilePath
train
protected function getCacheFilePath($subdir, $filename, $forceOriginalFile = false, $hashed_options = null) { $path = $this->getCachePath($subdir); $safe_filename = preg_replace("[^:alnum:\-\._]", "-", strtolower(basename($filename))); // Keep original safe name if no tranformations are applied if ($forceOriginalFile || $hashed_options == null) { return sprintf("%s/%s", $path, $safe_filename); } else { return sprintf("%s/%s-%s", $path, $hashed_options, $safe_filename); } }
php
{ "resource": "" }
q1824
BaseCachedFile.getCachePathFromWebRoot
train
protected function getCachePathFromWebRoot($subdir = null) { $cache_dir_from_web_root = $this->getCacheDirFromWebRoot(); if ($subdir != null) { $safe_subdir = basename($subdir); $path = sprintf("%s/%s", $cache_dir_from_web_root, $safe_subdir); } else { $path = $cache_dir_from_web_root; } // Check if path is valid, e.g. in the cache dir return $path; }
php
{ "resource": "" }
q1825
BaseCachedFile.getCachePath
train
protected function getCachePath($subdir = null, $create_if_not_exists = true) { $cache_base = $this->getCachePathFromWebRoot($subdir); $web_root = rtrim(THELIA_WEB_DIR, '/'); $path = sprintf("%s/%s", $web_root, $cache_base); // Create directory (recursively) if it does not exists. if ($create_if_not_exists && !is_dir($path)) { if (!@mkdir($path, 0777, true)) { throw new \RuntimeException(sprintf("Failed to create %s file in cache directory", $path)); } } // Check if path is valid, e.g. in the cache dir $cache_base = realpath(sprintf("%s/%s", $web_root, $this->getCachePathFromWebRoot())); if (strpos(realpath($path), $cache_base) !== 0) { throw new \InvalidArgumentException(sprintf("Invalid cache path %s, with subdirectory %s", $path, $subdir)); } return $path; }
php
{ "resource": "" }
q1826
BaseCachedFile.saveFile
train
public function saveFile(FileCreateOrUpdateEvent $event) { $model = $event->getModel(); $model->setFile(sprintf("tmp/%s", $event->getUploadedFile()->getFilename())); $con = Propel::getWriteConnection(ProductImageTableMap::DATABASE_NAME); $con->beginTransaction(); try { $nbModifiedLines = $model->save($con); $event->setModel($model); if (!$nbModifiedLines) { throw new FileException( sprintf( 'File "%s" (type %s) with parent id %s failed to be saved', $event->getParentName(), \get_class($model), $event->getParentId() ) ); } $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModel(), $event->getUploadedFile()); $event->setUploadedFile($newUploadedFile); $con->commit(); } catch (\Exception $e) { $con->rollBack(); throw $e; } }
php
{ "resource": "" }
q1827
BaseCachedFile.updateFile
train
public function updateFile(FileCreateOrUpdateEvent $event) { // Copy and save file if ($event->getUploadedFile()) { // Remove old picture file from file storage $url = $event->getModel()->getUploadDir() . '/' . $event->getOldModel()->getFile(); unlink(str_replace('..', '', $url)); $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModel(), $event->getUploadedFile()); $event->setUploadedFile($newUploadedFile); } // Update image modifications $event->getModel()->save(); $event->setModel($event->getModel()); }
php
{ "resource": "" }
q1828
HookRenderBlockEvent.addFragment
train
public function addFragment(Fragment $fragment) { if (!empty($this->fields)) { $fragment->filter($this->fields); } $this->fragmentBag->addFragment($fragment); return $this; }
php
{ "resource": "" }
q1829
KeyPrompt.setMessages
train
private function setMessages() { // Allowed html for wp_kses. $allowed_html = array( 'a' => array( 'href' => array(), ), 'strong' => array(), ); $msg = new \stdClass(); $msg->success = sprintf( wp_kses( /* translators: The Url to the BoldGrid Connect settings page. */ __( 'Your api key has been saved. To change, see <strong>Settings &#187; <a href="%1$s">BoldGrid Connect</a></strong>.', 'boldgrid-library' ), $allowed_html ), admin_url( 'options-general.php?page=boldgrid-connect.php' ) ); $msg->error = sprintf( // translators: 1 A br / break tag. esc_html__( 'Your API key appears to be invalid!%sPlease try to enter your BoldGrid Connect Key again.', 'boldgrid-library' ), '<br />' ); $msg->nonce = esc_html__( 'Security violation! An invalid nonce was detected.', 'boldgrid-library' ); $msg->timeout = esc_html__( 'Connection timed out. Please try again.', 'boldgrid-library' ); return $this->messages = $msg; }
php
{ "resource": "" }
q1830
KeyPrompt.getState
train
public static function getState() { $state = 'no-key-added'; $license = Configs::get( 'start' )->getKey()->getLicense(); if ( $license ) { $isPremium = $license->isPremium( 'boldgrid-inspirations' ); $license = $isPremium ? 'premium' : 'basic'; $state = $license . '-key-active'; } return $state; }
php
{ "resource": "" }
q1831
KeyPrompt.keyNotice
train
public function keyNotice() { $display_notice = apply_filters( 'Boldgrid\Library\Library\Notice\KeyPrompt_display', ( ! Library\Notice::isDismissed( $this->userNoticeKey ) ) ); if ( $display_notice ) { $current_user = wp_get_current_user(); $email = $current_user->user_email; $first_name = empty( $current_user->user_firstname ) ? '' : $current_user->user_firstname; $last_name = empty( $current_user->user_lastname ) ? '' : $current_user->user_lastname; $api = Library\Configs::get( 'api' ) . '/api/open/generateKey'; /** * Check if the Envato notice to claim a Premium Connect Key should be enabled. * * A theme can add this filter and return true, which will enable this notice. * * @since 2.1.0 */ $enableClaimMessage = apply_filters( 'Boldgrid\Library\Library\Notice\ClaimPremiumKey_enable', false ); include dirname( __DIR__ ) . '/Views/KeyPrompt.php'; self::$isDisplayed = true; } }
php
{ "resource": "" }
q1832
KeyPrompt.addKey
train
public function addKey() { /* * @todo A section of this code has been duplicated in Boldgrid\Library\Library\Key\addKey() * because the code for saving a key should be in the Key class and not the KeyPrompt class. * This method needs to be refactored using that addKey method. */ // When adding Keys, delete the transient to make sure we get new license info. delete_site_transient( 'bg_license_data' ); delete_site_transient( 'boldgrid_api_data' ); $key = $this->validate(); $data = $this->key->callCheckVersion( array( 'key' => $key ) ); $msg = $this->getMessages(); if ( is_object( $data ) ) { $this->key->save( $data, $key ); wp_send_json_success( array( 'message' => $msg->success, 'site_hash' => $data->result->data->site_hash, 'api_key' => apply_filters( 'Boldgrid\Library\License\getApiKey', false ), ) ); } else { $is_timeout = false !== strpos( $data, 'cURL error 28:' ); wp_send_json_error( array( 'message' => $is_timeout ? $msg->timeout : $msg->error ) ); } }
php
{ "resource": "" }
q1833
KeyPrompt.validate
train
protected function validate() { $msg = $this->getMessages(); // Validate nonce. if ( ! isset( $_POST['set_key_auth'] ) || ! check_ajax_referer( 'boldgrid_set_key', 'set_key_auth', false ) ) { wp_send_json_error( array( 'message' => $msg->nonce ) ); } // Validate user input. if ( empty( $_POST['api_key'] ) ) { wp_send_json_error( array( 'message' => $msg->error ) ); } // Validate key. $valid = new Library\Key\Validate( sanitize_text_field( $_POST['api_key'] ) ); if ( ! $valid->getValid() ) { wp_send_json_error( array( 'message' => $msg->error ) ); } return $valid->getHash(); }
php
{ "resource": "" }
q1834
KeyPrompt.getIsDismissed
train
public function getIsDismissed() { if( is_null( self::$isDismissed ) ) { self::$isDismissed = Library\Notice::isDismissed( $this->userNoticeKey ); } return self::$isDismissed; }
php
{ "resource": "" }
q1835
TheliaTemplateHelper.isActive
train
public function isActive(TemplateDefinition $tplDefinition) { $tplVar = ''; switch ($tplDefinition->getType()) { case TemplateDefinition::FRONT_OFFICE: $tplVar = 'active-front-template'; break; case TemplateDefinition::BACK_OFFICE: $tplVar = 'active-admin-template'; break; case TemplateDefinition::PDF: $tplVar = 'active-pdf-template'; break; case TemplateDefinition::EMAIL: $tplVar = 'active-mail-template'; break; } return $tplDefinition->getName() == ConfigQuery::read($tplVar, 'default'); }
php
{ "resource": "" }
q1836
TheliaTemplateHelper.getList
train
public function getList($templateType, $base = THELIA_TEMPLATE_DIR) { $list = $exclude = array(); $tplIterator = TemplateDefinition::getStandardTemplatesSubdirsIterator(); foreach ($tplIterator as $type => $subdir) { if ($templateType == $type) { $baseDir = rtrim($base, DS).DS.$subdir; try { // Every subdir of the basedir is supposed to be a template. $di = new \DirectoryIterator($baseDir); /** @var \DirectoryIterator $file */ foreach ($di as $file) { // Ignore 'dot' elements if ($file->isDot() || ! $file->isDir()) { continue; } // Ignore reserved directory names if (\in_array($file->getFilename(), $exclude)) { continue; } $list[] = new TemplateDefinition($file->getFilename(), $templateType); } } catch (\UnexpectedValueException $ex) { // Ignore the exception and continue } } } return $list; }
php
{ "resource": "" }
q1837
CouponController.browseAction
train
public function browseAction() { if (null !== $response = $this->checkAuth(AdminResources::COUPON, [], AccessManager::VIEW)) { return $response; } return $this->render('coupon-list', [ 'coupon_order' => $this->getListOrderFromSession('coupon', 'coupon_order', 'code') ]); }
php
{ "resource": "" }
q1838
CouponController.createAction
train
public function createAction() { if (null !== $response = $this->checkAuth(AdminResources::COUPON, [], AccessManager::CREATE)) { return $response; } // Parameters given to the template $args = []; $eventToDispatch = TheliaEvents::COUPON_CREATE; if ($this->getRequest()->isMethod('POST')) { if (null !== $response = $this->validateCreateOrUpdateForm( $eventToDispatch, 'created', 'creation' )) { return $response; } } else { // If no input for expirationDate, now + 2 months $defaultDate = new \DateTime(); $args['nowDate'] = $defaultDate->format($this->getDefaultDateFormat()); $args['defaultDate'] = $defaultDate->modify('+2 month')->format($this->getDefaultDateFormat()); } $args['dateFormat'] = $this->getDefaultDateFormat(); $args['availableCoupons'] = $this->getAvailableCoupons(); $args['urlAjaxAdminCouponDrawInputs'] = $this->getRoute( 'admin.coupon.draw.inputs.ajax', ['couponServiceId' => 'couponServiceId'], Router::ABSOLUTE_URL ); $args['formAction'] = 'admin/coupon/create'; // Setup empty data if form is already in parser context $this->getParserContext()->addForm($this->createForm(AdminForm::COUPON_CREATION)); return $this->render( 'coupon-create', $args ); }
php
{ "resource": "" }
q1839
CouponController.logError
train
protected function logError($action, $message, $e) { Tlog::getInstance()->error( sprintf( 'Error during Coupon ' . $action . ' process : %s. Exception was %s', $message, $e->getMessage() ) ); return $this; }
php
{ "resource": "" }
q1840
CouponController.validateCreateOrUpdateForm
train
protected function validateCreateOrUpdateForm($eventToDispatch, $log, $action, Coupon $model = null) { // Create the form from the request $couponForm = $this->getForm($action, $model); $response = null; $message = false; try { // Check the form against conditions violations $form = $this->validateForm($couponForm, 'POST'); $couponEvent = $this->feedCouponCreateOrUpdateEvent($form, $model); // Dispatch Event to the Action $this->dispatch( $eventToDispatch, $couponEvent ); $this->adminLogAppend( AdminResources::COUPON, AccessManager::UPDATE, sprintf( 'Coupon %s (ID ) ' . $log, $couponEvent->getTitle(), $couponEvent->getCouponModel()->getId() ), $couponEvent->getCouponModel()->getId() ); if ($this->getRequest()->get('save_mode') == 'stay') { $response = RedirectResponse::create(str_replace( '{id}', $couponEvent->getCouponModel()->getId(), $couponForm->getSuccessUrl() )); } else { // Redirect to the success URL $response = RedirectResponse::create( URL::getInstance()->absoluteUrl($this->getRoute('admin.coupon.list')) ); } } catch (FormValidationException $ex) { // Invalid data entered $message = $this->createStandardFormValidationErrorMessage($ex); } catch (\Exception $ex) { // Any other error $message = $this->getTranslator()->trans('Sorry, an error occurred: %err', ['%err' => $ex->getMessage()]); $this->logError($action, $message, $ex); } if ($message !== false) { // Mark the form as with error $couponForm->setErrorMessage($message); // Send the form and the error to the parser $this->getParserContext() ->addForm($couponForm) ->setGeneralError($message); } return $response; }
php
{ "resource": "" }
q1841
CouponController.getAvailableConditions
train
protected function getAvailableConditions() { /** @var CouponManager $couponManager */ $couponManager = $this->container->get('thelia.coupon.manager'); $availableConditions = $couponManager->getAvailableConditions(); $cleanedConditions = []; /** @var ConditionInterface $availableCondition */ foreach ($availableConditions as $availableCondition) { $condition = []; $condition['serviceId'] = $availableCondition->getServiceId(); $condition['name'] = $availableCondition->getName(); $condition['toolTip'] = $availableCondition->getToolTip(); $cleanedConditions[] = $condition; } return $cleanedConditions; }
php
{ "resource": "" }
q1842
CouponController.getAvailableCoupons
train
protected function getAvailableCoupons() { /** @var CouponManager $couponManager */ $couponManager = $this->container->get('thelia.coupon.manager'); $availableCoupons = $couponManager->getAvailableCoupons(); $cleanedCoupons = []; /** @var CouponInterface $availableCoupon */ foreach ($availableCoupons as $availableCoupon) { $condition = []; $condition['serviceId'] = $availableCoupon->getServiceId(); $condition['name'] = $availableCoupon->getName(); $condition['toolTip'] = $availableCoupon->getToolTip(); $cleanedCoupons[] = $condition; } return $cleanedCoupons; }
php
{ "resource": "" }
q1843
CouponController.cleanConditionForTemplate
train
protected function cleanConditionForTemplate(ConditionCollection $conditions) { $cleanedConditions = []; /** @var $condition ConditionInterface */ foreach ($conditions as $index => $condition) { $temp = [ 'serviceId' => $condition->getServiceId(), 'index' => $index, 'name' => $condition->getName(), 'toolTip' => $condition->getToolTip(), 'summary' => $condition->getSummary(), 'validators' => $condition->getValidators() ]; $cleanedConditions[] = $temp; } return $cleanedConditions; }
php
{ "resource": "" }
q1844
CouponController.feedCouponCreateOrUpdateEvent
train
protected function feedCouponCreateOrUpdateEvent(Form $form, Coupon $model = null) { // Get the form field values $data = $form->getData(); $serviceId = $data['type']; /** @var CouponInterface $coupon */ $coupon = $this->container->get($serviceId); $couponEvent = new CouponCreateOrUpdateEvent( $data['code'], $serviceId, $data['title'], $coupon->getEffects($data), $data['shortDescription'], $data['description'], $data['isEnabled'], \DateTime::createFromFormat($this->getDefaultDateFormat(), $data['expirationDate']), $data['isAvailableOnSpecialOffers'], $data['isCumulative'], $data['isRemovingPostage'], $data['maxUsage'], $data['locale'], $data['freeShippingForCountries'], $data['freeShippingForModules'], $data['perCustomerUsageCount'], empty($data['startDate']) ? null : \DateTime::createFromFormat($this->getDefaultDateFormat(), $data['startDate']) ); // If Update mode if (isset($model)) { $couponEvent->setCouponModel($model); } return $couponEvent; }
php
{ "resource": "" }
q1845
CouponController.buildConditionFromRequest
train
protected function buildConditionFromRequest() { $request = $this->getRequest(); $post = $request->request->getIterator(); $serviceId = $request->request->get('categoryCondition'); $operators = []; $values = []; foreach ($post as $key => $input) { if (isset($input['operator']) && isset($input['value'])) { $operators[$key] = $input['operator']; $values[$key] = $input['value']; } } /** @var ConditionFactory $conditionFactory */ $conditionFactory = $this->container->get('thelia.condition.factory'); $conditionToSave = $conditionFactory->build($serviceId, $operators, $values); return $conditionToSave; }
php
{ "resource": "" }
q1846
CouponController.manageConditionUpdate
train
protected function manageConditionUpdate(Coupon $coupon, ConditionCollection $conditions) { $couponEvent = new CouponCreateOrUpdateEvent( $coupon->getCode(), $coupon->getType(), $coupon->getTitle(), $coupon->getEffects(), $coupon->getShortDescription(), $coupon->getDescription(), $coupon->getIsEnabled(), $coupon->getExpirationDate(), $coupon->getIsAvailableOnSpecialOffers(), $coupon->getIsCumulative(), $coupon->getIsRemovingPostage(), $coupon->getMaxUsage(), $coupon->getLocale(), $coupon->getFreeShippingForCountries(), $coupon->getFreeShippingForModules(), $coupon->getPerCustomerUsageCount(), $coupon->getStartDate() ); $couponEvent->setCouponModel($coupon); $couponEvent->setConditions($conditions); $eventToDispatch = TheliaEvents::COUPON_CONDITION_UPDATE; // Dispatch Event to the Action $this->dispatch( $eventToDispatch, $couponEvent ); $this->adminLogAppend( AdminResources::COUPON, AccessManager::UPDATE, sprintf( 'Coupon %s (ID %s) conditions updated', $couponEvent->getCouponModel()->getTitle(), $couponEvent->getCouponModel()->getType() ), $couponEvent->getCouponModel()->getId() ); }
php
{ "resource": "" }
q1847
FileManager.getModelInstance
train
public function getModelInstance($fileType, $parentType) { if (! isset($this->supportedFileModels[$this->getFileTypeIdentifier($fileType, $parentType)])) { throw new FileException( sprintf("Unsupported file type '%s' for parent type '%s'", $fileType, $parentType) ); } $className = $this->supportedFileModels[$this->getFileTypeIdentifier($fileType, $parentType)]; $instance = new $className; if (! $instance instanceof FileModelInterface) { throw new FileException( sprintf( "Wrong class type for file type '%s', parent type '%s'. Class '%s' should implements FileModelInterface", $fileType, $parentType, $className ) ); } return $instance; }
php
{ "resource": "" }
q1848
FileManager.addFileModel
train
public function addFileModel($fileType, $parentType, $fullyQualifiedClassName) { $this->supportedFileModels[$this->getFileTypeIdentifier($fileType, $parentType)] = $fullyQualifiedClassName; }
php
{ "resource": "" }
q1849
FileManager.copyUploadedFile
train
public function copyUploadedFile(FileModelInterface $model, UploadedFile $uploadedFile, ConnectionInterface $con = null) { $newUploadedFile = null; if ($uploadedFile !== null) { $directory = $model->getUploadDir(); $fileName = $this->renameFile($model->getId(), $uploadedFile); $newUploadedFile = $uploadedFile->move($directory, $fileName); $model->setFile($fileName); if (!$model->save($con)) { throw new ImageException( sprintf( 'Failed to update model after copy of uploaded file %s to %s', $uploadedFile, $model->getFile() ) ); } } return $newUploadedFile; }
php
{ "resource": "" }
q1850
FileManager.deleteFile
train
public function deleteFile(FileModelInterface $model) { $url = $model->getUploadDir() . DS . $model->getFile(); @unlink(str_replace('..', '', $url)); $model->delete(); }
php
{ "resource": "" }
q1851
FileManager.renameFile
train
public function renameFile($modelId, UploadedFile $uploadedFile) { $extension = $uploadedFile->getClientOriginalExtension(); if (!empty($extension)) { $extension = '.' . strtolower($extension); } $fileName = $this->sanitizeFileName( str_replace( $extension, '', $uploadedFile->getClientOriginalName() ) . '-' . $modelId . $extension ); return $fileName; }
php
{ "resource": "" }
q1852
FileManager.isImage
train
public function isImage($mimeType) { $isValid = false; $allowedType = array('image/jpeg' , 'image/png' ,'image/gif'); if (\in_array($mimeType, $allowedType)) { $isValid = true; } return $isValid; }
php
{ "resource": "" }
q1853
Drupal.ensureSettings
train
protected function ensureSettings() { if (!$this->fs->exists(Platform::webDir() . '/sites/default')) { $this->fs->mkdir(Platform::webDir() . '/sites/default', 0775); } else { // If building from an existing project, Drupal may have fiddled with // the permissions preventing us from writing. $this->fs->chmod(Platform::webDir() . '/sites/default', 0775); } $has_settings = $this->fs->exists(Platform::webDir() . '/sites/default/settings.php'); if ($has_settings) { $this->fs->chmod(Platform::webDir() . '/sites/default/settings.php', 0664); } switch ($this->version) { case DrupalStackHelper::DRUPAL7: if (!$has_settings) { $this->fs->copy(CLI_ROOT . '/resources/stacks/drupal7/settings.php', Platform::webDir() . '/sites/default/settings.php', true); } break; case DrupalStackHelper::DRUPAL8: if (!$has_settings) { $this->fs->copy(CLI_ROOT . '/resources/stacks/drupal8/settings.php', Platform::webDir() . '/sites/default/settings.php', true); } $this->fs->mkdir([ Platform::sharedDir() . '/config', Platform::sharedDir() . '/config/active', Platform::sharedDir() . '/config/staging', ]); break; default: throw new \Exception('Unsupported version of Drupal. Write a pull reuqest!'); } }
php
{ "resource": "" }
q1854
Drupal.drushrc
train
public function drushrc() { // @todo: Check if drushrc.php exists, load in any $conf changes. switch ($this->version) { case DrupalStackHelper::DRUPAL7: $this->fs->copy(CLI_ROOT . '/resources/stacks/drupal7/drushrc.php', Platform::sharedDir() . '/drushrc.php', true); break; case DrupalStackHelper::DRUPAL8: $this->fs->copy(CLI_ROOT . '/resources/stacks/drupal8/drushrc.php', Platform::sharedDir() . '/drushrc.php', true); break; default: throw new \Exception('Unsupported version of Drupal. Write a pull reuqest!'); } // Replace template variables. $localSettings = file_get_contents(Platform::sharedDir() . '/drushrc.php'); // @todo this expects proxy to be running. $localSettings = str_replace('{{ project_domain }}', $this->projectName . '.' . $this->projectTld, $localSettings); file_put_contents(Platform::sharedDir() . '/drushrc.php', $localSettings); if (!file_exists(Platform::webDir() . '/sites/default/drushrc.php')) { $this->fs->symlink($this->getRelativeLinkToShared() . 'drushrc.php', Platform::webDir() . '/sites/default/drushrc.php'); } }
php
{ "resource": "" }
q1855
RatingPrompt.addPrompt
train
public function addPrompt( $prompt ) { $added = false; /* * Determine whether to add the new prompt or not. * * If we've already a prompt for user_did_this_x_times, don't add another prompt for the * same thing. * * If a plugin has already been dismissed, no need to add any additional rating prompts, * they will never be showing. */ if ( ! $this->isPrompt( $prompt['name'] ) && ! $this->isPluginDismissed( $prompt['plugin'] ) ) { $prompt['time_added'] = time(); $prompts = $this->getPrompts(); $prompts[] = $prompt; $added = $this->savePrompts( $prompts ); } return $added; }
php
{ "resource": "" }
q1856
RatingPrompt.admin_notices
train
public function admin_notices() { if ( ! current_user_can( $this->userRole ) ) { return; } $prompt = $this->getNext(); if ( empty( $prompt ) ) { return; } $slides = $this->getPromptSlides( $prompt ); if ( ! empty( $slides ) ) { echo '<div class="notice notice-success bglib-rating-prompt is-dismissible" data-slide-name="' . esc_attr( $prompt['name'] ) . '">'; foreach ( $slides as $slide ) { echo $slide; } wp_nonce_field( 'bglib-rating-prompt' ); echo '</div>'; } }
php
{ "resource": "" }
q1857
RatingPrompt.ajaxDismiss
train
public function ajaxDismiss() { if ( ! current_user_can( $this->userRole ) ) { wp_send_json_error( __( 'Permission denied.', 'boldgrid-library' ) ); } if( ! check_ajax_referer( 'bglib-rating-prompt', 'security', false ) ) { wp_send_json_error( __( 'Invalid nonce.', 'boldgrid-library' ) ); } $name = sanitize_text_field( $_POST['name'] ); $type = sanitize_text_field( $_POST['type'] ); $snooze_length = (int) $_POST['length']; switch( $type ) { case 'dismiss': $dismissed = $this->updatePromptKey( $name, 'time_dismissed', time() ); $dismissed ? wp_send_json_success() : wp_send_json_error( __( 'Error dismissing prompt', 'boldgrid-library' ) ); break; case 'snooze': $time_snoozed_set = $this->updatePromptKey( $name, 'time_snoozed', time() ); $snoozed = $this->updatePromptKey( $name, 'time_snoozed_until', time() + $snooze_length ); $time_snoozed_set && $snoozed ? wp_send_json_success() : wp_send_json_error( __( 'Error snoozing prompt', 'boldgrid-library' ) ); break; default: wp_send_json_error( __( 'Unknown action.', 'boldgrid-library' ) ); } }
php
{ "resource": "" }
q1858
RatingPrompt.getLastDismissal
train
public function getLastDismissal() { $lastDismissal = 0; $prompts = $this->getPrompts(); foreach ( $prompts as $prompt ) { $promptDismissal = 0; if ( ! empty( $prompt['time_dismissed'] ) ) { $promptDismissal = $prompt['time_dismissed']; } elseif ( ! empty( $prompt['time_snoozed'] ) ) { $promptDismissal = $prompt['time_snoozed']; } $lastDismissal = $promptDismissal > $lastDismissal ? $promptDismissal : $lastDismissal; } return $lastDismissal; }
php
{ "resource": "" }
q1859
RatingPrompt.admin_enqueue_scripts
train
public function admin_enqueue_scripts() { if ( ! current_user_can( $this->userRole ) ) { return; } $prompt = $this->getNext(); if ( ! empty( $prompt ) ) { wp_enqueue_script( 'bglib-rating-prompt-js', Library\Configs::get( 'libraryUrl' ) . 'src/assets/js/rating-prompt.js', 'jquery', date( 'Ymd' ) ); wp_enqueue_style( 'bglib-rating-prompt-css', Library\Configs::get( 'libraryUrl' ) . 'src/assets/css/rating-prompt.css', array(), date( 'Ymd' ) ); } }
php
{ "resource": "" }
q1860
RatingPrompt.getPromptSlides
train
public function getPromptSlides( $prompt ) { $slides = array(); if ( ! empty( $prompt['slides'] ) ) { foreach ( $prompt['slides'] as $slide_id => $slide ) { $slideMarkup = $this->getSlideMarkup( $slide_id, $slide ); $slides[$slide_id] = $slideMarkup; } } return $slides; }
php
{ "resource": "" }
q1861
RatingPrompt.getSlideMarkup
train
public function getSlideMarkup( $slide_id, $slide ) { $slideMarkup = '<div data-slide-id="' . esc_attr( $slide_id ) . '">'; $slideMarkup .= '<p>' . $slide['text'] . '</p>'; if ( ! empty( $slide['decisions'] ) ) { $slide_decisions = array(); foreach( $slide['decisions'] as $decision ) { $attributes = $this->getDecisionAttributes( $decision ); $markup = '<a '; foreach ( $attributes as $key => $value ) { $markup .= $key . '="' . $value . '" '; } $markup .= '>' . esc_html( $decision['text'] ) . '</a>'; $slide_decisions[] = $markup; } $slideMarkup .= '<ul><li>' . implode( '</li><li>', $slide_decisions ) . '</li></ul>'; } $slideMarkup .= '</div>'; return $slideMarkup; }
php
{ "resource": "" }
q1862
RatingPrompt.getPrompt
train
public function getPrompt( $name ) { $prompt_found = array(); $prompts = $this->getPrompts(); foreach( $prompts as $prompt ) { if ( $name === $prompt['name'] ) { $prompt_found = $prompt; break; } } return $prompt_found; }
php
{ "resource": "" }
q1863
RatingPrompt.isPluginDismissed
train
public function isPluginDismissed( $plugin ) { $dismissed = false; $plugin_prompts = $this->getPluginPrompts( $plugin ); foreach ( $plugin_prompts as $prompt ) { if ( ! empty( $prompt['time_dismissed'] ) ) { $dismissed = true; } } return $dismissed; }
php
{ "resource": "" }
q1864
RatingPrompt.getPluginPrompts
train
public function getPluginPrompts( $plugin ) { $pluginPrompts = array(); $prompts = $this->getPrompts(); foreach ( $prompts as $prompt ) { if ( $prompt['plugin'] === $plugin ) { $pluginPrompts[] = $prompt; } } return $pluginPrompts; }
php
{ "resource": "" }
q1865
RatingPrompt.getNext
train
public function getNext() { $nextPrompt = array(); $prompts = $this->getPrompts(); foreach ( $prompts as $prompt ) { $isDismissed = isset( $prompt['time_dismissed'] ); $isOlder = empty( $nextPrompt ) || ( ! $isDismissed && $prompt['time_added'] < $nextPrompt['time_added'] ); $isStillSnoozing = ! empty( $prompt['time_snoozed_until'] ) && $prompt['time_snoozed_until'] > time(); if ( ! $isDismissed && $isOlder && ! $isStillSnoozing ) { $nextPrompt = $prompt; } } if ( ! $this->isMinInterval() ) { $nextPrompt = array(); } return $nextPrompt; }
php
{ "resource": "" }
q1866
RatingPrompt.updatePrompt
train
public function updatePrompt( $prompt_to_save ) { $found = false; $prompts = $this->getPrompts(); foreach ( $prompts as $key => $prompt ) { if ( $prompt_to_save['name'] === $prompt['name'] ) { $found = true; $prompts[$key] = $prompt_to_save; break; } } return $found ? $this->savePrompts( $prompts ) : false; }
php
{ "resource": "" }
q1867
RatingPrompt.updatePromptKey
train
public function updatePromptKey( $name, $key, $value ) { $prompt = $this->getPrompt( $name ); $prompt[$key] = $value; return $this->updatePrompt( $prompt ); }
php
{ "resource": "" }
q1868
NamespaceNode.create
train
public static function create($name) { $name = (string) $name; $name = ltrim($name, '\\'); $namespace_node = Parser::parseSnippet("namespace $name;"); return $namespace_node; }
php
{ "resource": "" }
q1869
BaseModule.isPaymentModuleFor
train
public function isPaymentModuleFor(Order $order) { $model = $this->getModuleModel(); return $order->getPaymentModuleId() == $model->getId(); }
php
{ "resource": "" }
q1870
BaseModule.isDeliveryModuleFor
train
public function isDeliveryModuleFor(Order $order) { $model = $this->getModuleModel(); return $order->getDeliveryModuleId() == $model->getId(); }
php
{ "resource": "" }
q1871
BaseModule.initializeCoreI18n
train
private function initializeCoreI18n() { if ($this->hasContainer()) { /** @var Translator $translator */ $translator = $this->container->get('thelia.translator'); if (null !== $translator) { $i18nPath = sprintf('%s%s/I18n/', THELIA_MODULE_DIR, $this->getCode()); $languages = LangQuery::create()->find(); foreach ($languages as $language) { $locale = $language->getLocale(); $i18nFile = sprintf('%s%s.php', $i18nPath, $locale); if (is_file($i18nFile) && is_readable($i18nFile)) { $translator->addResource('php', $i18nFile, $locale, strtolower(self::getModuleCode())); } } } } }
php
{ "resource": "" }
q1872
Call.setArgs
train
protected function setArgs( $args ) { // Check for an API key being stored. if ( $this->getKey() ) { $args = wp_parse_args( $args, array( 'key' => $this->getKey() ) ); } // Check for a site hash being stored. if ( $this->getSiteHash() ) { $args = wp_parse_args( $args, array( 'site_hash' => $this->getSiteHash() ) ); } return $this->args = array( 'timeout' => 15, // Default timeout is 5 seconds, change to 15. 'body' => $args ); }
php
{ "resource": "" }
q1873
Call.call
train
private function call() { // Make the request. if ( 'get' === $this->method ) { $response = wp_remote_get( $this->url, $this->args ); } else { $response = wp_remote_post( $this->url, $this->args ); } // Decode the response and set class property. $this->response = json_decode( wp_remote_retrieve_body( $response ) ); // Validate the raw response. if ( $this->validateResponse( $response ) === false ) { return false; } // Response should be an object. if ( ! is_object( $this->response ) ) { $this->error = __( 'An invalid response was returned.', 'boldgrid-library' ); return false; } return true; }
php
{ "resource": "" }
q1874
Call.validateResponse
train
private function validateResponse( $response ) { // Make sure WordPress errors are handled. if ( is_wp_error( $response ) ) { $this->error = $response->get_error_message(); return false; } // Check for 200 response code from server. $responseCode = wp_remote_retrieve_response_code( $response ); if ( false === strstr( $responseCode, '200' ) ) { $responseMessage = wp_remote_retrieve_response_message( $response ); $this->error = "{$responseCode} {$responseMessage}"; return false; } // Check for nested status code not being successful. if ( isset( $this->response->status ) && 200 !== $this->response->status ) { $this->error = $this->response->result->data; return false; } return true; }
php
{ "resource": "" }
q1875
Parser.buildTree
train
public function buildTree(TokenIterator $iterator) { $this->skipped = []; $this->skipParent = NULL; $this->docComment = NULL; $this->skippedDocComment = []; $this->iterator = $iterator; $this->current = $this->iterator->current(); $this->currentType = $this->current ? $this->current->getType() : NULL; $top = new RootNode(); $this->top = $top; if ($this->currentType && $this->currentType !== T_OPEN_TAG) { $node = new TemplateNode(); // Parse any template statements that proceed the opening PHP tag. $this->templateStatementList($node); $top->addChild($node); } if ($this->tryMatch(T_OPEN_TAG, $top, NULL, TRUE, TRUE)) { $this->topStatementList($top); } return $top; }
php
{ "resource": "" }
q1876
Parser.parseFile
train
public static function parseFile($filename) { $source = @file_get_contents($filename); if ($source === FALSE) { return FALSE; } return self::parseSource($source, $filename); }
php
{ "resource": "" }
q1877
Parser.parseSource
train
public static function parseSource($source, $filename = NULL) { static $tokenizer, $parser = NULL; if (!isset($parser)) { $tokenizer = new Tokenizer(); $parser = new self(); } $tokens = $tokenizer->getAll($source, $filename); $parser->filename = $filename; return $parser->buildTree(new TokenIterator($tokens)); }
php
{ "resource": "" }
q1878
Parser.parseExpression
train
public static function parseExpression($expression) { $tree = self::parseSource('<?php ' . $expression . ';'); /** @var ExpressionStatementNode $statement_node */ $statement_node = $tree->firstChild()->next(); return $statement_node->getExpression()->remove(); }
php
{ "resource": "" }
q1879
Parser.templateStatementList
train
private function templateStatementList(ParentNode $node) { while ($this->current) { if ($this->currentType === T_OPEN_TAG) { return; } elseif ($this->currentType === T_INLINE_HTML) { $node->addChild($this->mustMatchToken(T_INLINE_HTML)); } elseif ($this->currentType === T_OPEN_TAG_WITH_ECHO) { $node->addChild($this->echoTagStatement()); } else { throw new ParserException( $this->filename, $this->iterator->getLineNumber(), $this->iterator->getColumnNumber(), 'expected PHP opening tag, but got ' . $this->iterator->current()->getText()); } } }
php
{ "resource": "" }
q1880
Parser.topStatementList
train
private function topStatementList(StatementBlockNode $node, $terminator = '') { $this->matchHidden($node); while ($this->currentType !== NULL && $this->currentType !== $terminator) { $node->addChild($this->topStatement()); $this->matchHidden($node); } $this->matchHidden($node); $this->matchDocComment($node, NULL); }
php
{ "resource": "" }
q1881
Parser.topStatement
train
private function topStatement() { switch ($this->currentType) { case T_USE: return $this->useBlock(); case T_CONST: return $this->_const(); case T_ABSTRACT: case T_FINAL: case T_CLASS: return $this->classDeclaration(); case T_INTERFACE: return $this->interfaceDeclaration(); case T_TRAIT: return $this->traitDeclaration(); case T_HALT_COMPILER: $node = new HaltCompilerNode(); $this->mustMatch(T_HALT_COMPILER, $node, 'name'); $this->mustMatch('(', $node, 'openParen'); $this->mustMatch(')', $node, 'closeParen'); $this->endStatement($node); $this->tryMatch(T_INLINE_HTML, $node); return $node; default: if ($this->currentType === T_FUNCTION && $this->isLookAhead(T_STRING, '&')) { return $this->functionDeclaration(); } elseif ($this->currentType === T_NAMESPACE && !$this->isLookAhead(T_NS_SEPARATOR)) { return $this->_namespace(); } return $this->statement(); } }
php
{ "resource": "" }
q1882
Parser._const
train
private function _const() { $node = new ConstantDeclarationStatementNode(); $this->matchDocComment($node); $this->mustMatch(T_CONST, $node); $declarations = new CommaListNode(); do { $declarations->addChild($this->constDeclaration()); } while ($this->tryMatch(',', $declarations)); $node->addChild($declarations, 'declarations'); $this->endStatement($node); return $node; }
php
{ "resource": "" }
q1883
Parser.constDeclaration
train
private function constDeclaration() { $node = new ConstantDeclarationNode(); $name_node = new NameNode(); $this->mustMatch(T_STRING, $name_node, NULL, TRUE); $node->addChild($name_node, 'name'); if ($this->mustMatch('=', $node)) { $node->addChild($this->staticScalar(), 'value'); } return $node; }
php
{ "resource": "" }
q1884
Parser.statement
train
private function statement() { switch ($this->currentType) { case T_CLOSE_TAG: // A close tag escapes into template mode. $node = new TemplateNode(); $this->mustMatch(T_CLOSE_TAG, $node); $this->templateStatementList($node); if ($this->iterator->hasNext()) { $this->mustMatch(T_OPEN_TAG, $node, NULL, TRUE, TRUE); } return $node; case T_IF: return $this->_if(); case T_WHILE: return $this->_while(); case T_DO: return $this->doWhile(); case T_FOR: return $this->_for(); case T_SWITCH: return $this->_switch(); case T_BREAK: return $this->_break(); case T_CONTINUE: return $this->_continue(); case T_RETURN: return $this->_return(); case T_YIELD: $node = new YieldStatementNode(); $node->addChild($this->_yield()); $this->endStatement($node); return $node; case T_GLOBAL: return $this->_global(); case T_ECHO: return $this->_echo(); case T_UNSET: return $this->_unset(); case T_FOREACH: return $this->_foreach(); case T_DECLARE: return $this->_declare(); case T_TRY: return $this->_try(); case T_THROW: return $this->_throw(); case T_GOTO: return $this->_goto(); case '{': return $this->innerStatementBlock(); case ';': $node = new BlankStatementNode(); $this->endStatement($node); return $node; case T_STATIC: if ($this->isLookAhead(T_VARIABLE)) { return $this->staticVariableList(); } else { return $this->exprStatement(); } case T_STRING: if ($this->isLookAhead(':')) { $node = new GotoLabelNode(); $this->mustMatch(T_STRING, $node, 'label'); $this->mustMatch(':', $node, NULL, TRUE, TRUE); return $node; } else { return $this->exprStatement(); } default: return $this->exprStatement(); } }
php
{ "resource": "" }
q1885
Parser.staticVariableList
train
private function staticVariableList() { $node = new StaticVariableStatementNode(); $this->matchDocComment($node); $this->mustMatch(T_STATIC, $node); $variables = new CommaListNode(); do { $variables->addChild($this->staticVariable()); } while ($this->tryMatch(',', $variables)); $node->addChild($variables, 'variables'); $this->endStatement($node); return $node; }
php
{ "resource": "" }
q1886
Parser.staticVariable
train
private function staticVariable() { $node = new StaticVariableNode(); $this->mustMatch(T_VARIABLE, $node, 'name', TRUE); if ($this->tryMatch('=', $node)) { $node->addChild($this->staticScalar(), 'initialValue'); } return $node; }
php
{ "resource": "" }
q1887
Parser.exprStatement
train
private function exprStatement() { $node = new ExpressionStatementNode(); $this->matchDocComment($node); $node->addChild($this->expr(), 'expression'); $this->endStatement($node); return $node; }
php
{ "resource": "" }
q1888
Parser.condition
train
private function condition(ParentNode $node, $property_name) { $this->mustMatch('(', $node, 'openParen'); if ($this->currentType === T_YIELD) { $node->addChild($this->_yield(), $property_name); } else { $node->addChild($this->expr(), $property_name); } $this->mustMatch(')', $node, 'closeParen'); }
php
{ "resource": "" }
q1889
Parser._if
train
private function _if() { $node = new IfNode(); $this->mustMatch(T_IF, $node); $this->condition($node, 'condition'); if ($this->tryMatch(':', $node, 'openColon', FALSE, TRUE)) { $node->addChild($this->innerIfInnerStatementList(), 'then'); while ($this->currentType === T_ELSEIF) { $this->matchHidden($node); $elseIf = new ElseIfNode(); $this->mustMatch(T_ELSEIF, $elseIf); $this->condition($elseIf, 'condition'); $this->mustMatch(':', $elseIf, 'openColon', FALSE, TRUE); $elseIf->addChild($this->innerIfInnerStatementList(), 'then'); $node->addChild($elseIf); } if ($this->tryMatch(T_ELSE, $node, 'elseKeyword')) { $this->mustMatch(':', $node, 'elseColon', FALSE, TRUE); $node->addChild($this->innerStatementListNode(T_ENDIF), 'else'); } $this->mustMatch(T_ENDIF, $node, 'endKeyword'); $this->endStatement($node); return $node; } else { $this->matchHidden($node); $node->addChild($this->statement(), 'then'); while ($this->currentType === T_ELSEIF) { $this->matchHidden($node); $elseIf = new ElseIfNode(); $this->mustMatch(T_ELSEIF, $elseIf); $this->condition($elseIf, 'condition'); $this->matchHidden($elseIf); $elseIf->addChild($this->statement(), 'then'); $node->addChild($elseIf); } if ($this->tryMatch(T_ELSE, $node, 'elseKeyword', FALSE, TRUE)) { $node->addChild($this->statement(), 'else'); } return $node; } }
php
{ "resource": "" }
q1890
Parser.innerIfInnerStatementList
train
private function innerIfInnerStatementList() { static $terminators = [T_ELSEIF, T_ELSE, T_ENDIF]; $node = new StatementBlockNode(); while ($this->currentType !== NULL && !in_array($this->currentType, $terminators)) { $this->matchHidden($node); $node->addChild($this->innerStatement()); } return $node; }
php
{ "resource": "" }
q1891
Parser._while
train
private function _while() { $node = new WhileNode(); $this->mustMatch(T_WHILE, $node); $this->condition($node, 'condition'); if ($this->tryMatch(':', $node, 'openColon', FALSE, TRUE)) { $node->addChild($this->innerStatementListNode(T_ENDWHILE), 'body'); $this->mustMatch(T_ENDWHILE, $node, 'endKeyword'); $this->endStatement($node); return $node; } else { $this->matchHidden($node); $node->addChild($this->statement(), 'body'); return $node; } }
php
{ "resource": "" }
q1892
Parser.doWhile
train
private function doWhile() { $node = new DoWhileNode(); $this->mustMatch(T_DO, $node, NULL, FALSE, TRUE); $node->addChild($this->statement(), 'body'); $this->mustMatch(T_WHILE, $node, 'whileKeyword'); $this->condition($node, 'condition'); $this->endStatement($node); return $node; }
php
{ "resource": "" }
q1893
Parser._for
train
private function _for() { $node = new ForNode(); $this->mustMatch(T_FOR, $node); $this->mustMatch('(', $node, 'openParen'); $this->forExpr($node, ';', 'initial'); $this->forExpr($node, ';', 'condition'); $this->forExpr($node, ')', 'step', TRUE, 'closeParen'); if ($this->tryMatch(':', $node, 'openColon', FALSE, TRUE)) { $node->addChild($this->innerStatementListNode(T_ENDFOR), 'body'); $this->mustMatch(T_ENDFOR, $node, 'endKeyword'); $this->endStatement($node); return $node; } else { $this->matchHidden($node); $node->addChild($this->statement(), 'body'); return $node; } }
php
{ "resource": "" }
q1894
Parser.forExpr
train
private function forExpr(ForNode $parent, $terminator, $property_name, $is_last = FALSE, $terminator_name = NULL) { if ($this->tryMatch($terminator, $parent)) { $parent->addChild(new CommaListNode(), $property_name); return; } $parent->addChild($this->exprList(), $property_name); $this->mustMatch($terminator, $parent, $terminator_name, $is_last, FALSE); }
php
{ "resource": "" }
q1895
Parser._switch
train
private function _switch() { $node = new SwitchNode(); $this->mustMatch(T_SWITCH, $node); $this->condition($node, 'switchOn'); if ($this->tryMatch(':', $node, 'openColon')) { $this->tryMatch(';', $node); while ($this->currentType !== NULL && $this->currentType !== T_ENDSWITCH) { $node->addChild($this->caseStatement(T_ENDSWITCH)); $this->matchHidden($node); } $this->mustMatch(T_ENDSWITCH, $node, 'endKeyword'); $this->endStatement($node); return $node; } else { $this->mustMatch('{', $node); $this->tryMatch(';', $node); while ($this->currentType !== NULL && $this->currentType !== '}') { $node->addChild($this->caseStatement('}')); $this->matchHidden($node); } $this->mustMatch('}', $node, NULL, TRUE); return $node; } }
php
{ "resource": "" }
q1896
Parser.caseStatement
train
private function caseStatement($terminator) { static $terminators = [T_CASE, T_DEFAULT]; if ($this->currentType === T_CASE) { $node = new CaseNode(); $this->mustMatch(T_CASE, $node); $node->addChild($this->expr(), 'matchOn'); if (!$this->tryMatch(':', $node, NULL, TRUE, TRUE) && !$this->tryMatch(';', $node, NULL, TRUE, TRUE)) { throw new ParserException( $this->filename, $this->iterator->getLineNumber(), $this->iterator->getColumnNumber(), 'expected :'); } if ($this->currentType !== $terminator && !in_array($this->currentType, $terminators)) { $this->matchHidden($node); $node->addChild($this->innerCaseStatementList($terminator), 'body'); } return $node; } elseif ($this->currentType === T_DEFAULT) { $node = new DefaultNode(); $this->mustMatch(T_DEFAULT, $node); if (!$this->tryMatch(':', $node, NULL, TRUE, TRUE) && !$this->tryMatch(';', $node, NULL, TRUE, TRUE)) { throw new ParserException( $this->filename, $this->iterator->getLineNumber(), $this->iterator->getColumnNumber(), 'expected :'); } if ($this->currentType !== $terminator && !in_array($this->currentType, $terminators)) { $this->matchHidden($node); $node->addChild($this->innerCaseStatementList($terminator), 'body'); } return $node; } throw new ParserException( $this->filename, $this->iterator->getLineNumber(), $this->iterator->getColumnNumber(), "expected case or default"); }
php
{ "resource": "" }
q1897
Parser.innerCaseStatementList
train
private function innerCaseStatementList($terminator) { static $terminators = [T_CASE, T_DEFAULT]; $node = new StatementBlockNode(); while ($this->currentType !== NULL && $this->currentType !== $terminator && !in_array($this->currentType, $terminators)) { $this->matchHidden($node); $node->addChild($this->innerStatement()); } return $node; }
php
{ "resource": "" }
q1898
Parser._break
train
private function _break() { $node = new BreakStatementNode(); $this->mustMatch(T_BREAK, $node); if ($this->tryMatch(';', $node, NULL, TRUE, TRUE) || $this->currentType === T_CLOSE_TAG) { return $node; } $this->parseLevel($node); $this->endStatement($node); return $node; }
php
{ "resource": "" }
q1899
Parser._continue
train
private function _continue() { $node = new ContinueStatementNode(); $this->mustMatch(T_CONTINUE, $node); if ($this->tryMatch(';', $node, NULL, TRUE, TRUE) || $this->currentType === T_CLOSE_TAG) { return $node; } $this->parseLevel($node); $this->endStatement($node); return $node; }
php
{ "resource": "" }