idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
15,600
protected function mapResponse ( $ success , array $ response ) { return ( new Response ( ) ) -> setRaw ( $ response ) -> map ( [ 'success' => $ success , 'message' => $ success ? 'Message sent' : $ response [ 'message' ] , ] ) ; }
Map the raw response to our response object .
15,601
public function setConfig ( array $ config ) { try { $ this -> config = $ this -> getConfigResolver ( ) -> resolve ( $ config ) ; } catch ( ExceptionInterface $ e ) { throw new InvalidArgumentException ( $ e -> getMessage ( ) , $ e -> getCode ( ) , $ e ) ; } }
Configures the api .
15,602
public function createPaymentForm ( array $ data ) { $ this -> ensureApiIsConfigured ( ) ; try { $ data = $ this -> getRequestOptionsResolver ( ) -> resolve ( $ data ) ; } catch ( ExceptionInterface $ e ) { throw new InvalidArgumentException ( $ e -> getMessage ( ) , $ e -> getCode ( ) , $ e ) ; } $ fields = [ 'TPE' => $ this -> config [ 'tpe' ] , 'date' => $ data [ 'date' ] , 'montant' => $ data [ 'amount' ] . $ data [ 'currency' ] , 'reference' => $ data [ 'reference' ] , 'texte-libre' => $ data [ 'comment' ] , 'version' => static :: VERSION , 'lgue' => $ data [ 'locale' ] , 'societe' => $ this -> config [ 'company' ] , 'mail' => $ data [ 'email' ] , ] ; $ macData = array_values ( $ fields ) ; $ fields [ 'texte-libre' ] = $ this -> htmlEncode ( $ data [ 'comment' ] ) ; if ( ! empty ( $ data [ 'schedule' ] ) ) { $ macData [ ] = $ fields [ 'nbrech' ] = count ( $ data [ 'schedule' ] ) ; $ count = 0 ; foreach ( $ data [ 'schedule' ] as $ datum ) { $ count ++ ; $ macData [ ] = $ fields [ 'dateech' . $ count ] = $ datum [ 'date' ] ; $ macData [ ] = $ fields [ 'montantech' . $ count ] = $ datum [ 'amount' ] . $ data [ 'currency' ] ; } for ( $ i = 2 * $ count + 10 ; $ i < 18 ; $ i ++ ) { $ macData [ ] = null ; } $ options = [ ] ; foreach ( $ data [ 'options' ] as $ key => $ value ) { $ options = "$key=$value" ; } $ macData [ ] = $ fields [ 'options' ] = implode ( '&' , $ options ) ; } $ fields [ 'MAC' ] = $ this -> computeMac ( $ macData ) ; $ fields [ 'url_retour' ] = $ data [ 'return_url' ] ; $ fields [ 'url_retour_ok' ] = $ data [ 'success_url' ] ; $ fields [ 'url_retour_err' ] = $ data [ 'failure_url' ] ; return [ 'action' => $ this -> getEndpointUrl ( static :: TYPE_PAYMENT ) , 'method' => 'POST' , 'fields' => $ fields , ] ; }
Creates the request form .
15,603
public function checkPaymentResponse ( array $ data ) { if ( ! isset ( $ data [ 'MAC' ] ) ) { return false ; } $ data = array_replace ( [ 'date' => null , 'montant' => null , 'reference' => null , 'texte-libre' => null , 'code-retour' => null , 'cvx' => null , 'vld' => null , 'brand' => null , 'status3ds' => null , 'numauto' => null , 'motifrefus' => null , 'originecb' => null , 'bincb' => null , 'hpancb' => null , 'ipclient' => null , 'originetr' => null , 'veres' => null , 'pares' => null , ] , $ data ) ; $ macData = [ $ this -> config [ 'tpe' ] , $ data [ "date" ] , $ data [ 'montant' ] , $ data [ 'reference' ] , $ data [ 'texte-libre' ] , static :: VERSION , $ data [ 'code-retour' ] , $ data [ 'cvx' ] , $ data [ 'vld' ] , $ data [ 'brand' ] , $ data [ 'status3ds' ] , $ data [ 'numauto' ] , $ data [ 'motifrefus' ] , $ data [ 'originecb' ] , $ data [ 'bincb' ] , $ data [ 'hpancb' ] , $ data [ 'ipclient' ] , $ data [ 'originetr' ] , $ data [ 'veres' ] , $ data [ 'pares' ] , null , ] ; return strtolower ( $ data [ 'MAC' ] ) === $ this -> computeMac ( $ macData ) ; }
Checks the payment response integrity .
15,604
public function getMacKey ( ) { $ key = $ this -> config [ 'key' ] ; $ hexStrKey = substr ( $ key , 0 , 38 ) ; $ hexFinal = "" . substr ( $ key , 38 , 2 ) . "00" ; $ cca0 = ord ( $ hexFinal ) ; if ( $ cca0 > 70 && $ cca0 < 97 ) { $ hexStrKey .= chr ( $ cca0 - 23 ) . substr ( $ hexFinal , 1 , 1 ) ; } else { if ( substr ( $ hexFinal , 1 , 1 ) == "M" ) { $ hexStrKey .= substr ( $ hexFinal , 0 , 1 ) . "0" ; } else { $ hexStrKey .= substr ( $ hexFinal , 0 , 2 ) ; } } return pack ( "H*" , $ hexStrKey ) ; }
Returns the key formatted for mac generation .
15,605
private function htmlEncode ( $ data ) { if ( empty ( $ data ) ) { return null ; } $ safeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890._-" ; $ result = "" ; for ( $ i = 0 ; $ i < strlen ( $ data ) ; $ i ++ ) { if ( strstr ( $ safeChars , $ data [ $ i ] ) ) { $ result .= $ data [ $ i ] ; } else if ( "7F" >= $ var = bin2hex ( substr ( $ data , $ i , 1 ) ) ) { $ result .= "&#x" . $ var . ";" ; } else { $ result .= $ data [ $ i ] ; } } return $ result ; }
Encode html string .
15,606
public static function create ( ExpressionNode $ array , ExpressionNode $ key ) { $ node = new static ( ) ; $ node -> addChild ( $ array , 'array' ) ; $ node -> addChild ( Token :: openBracket ( ) ) ; $ node -> addChild ( $ key , 'key' ) ; $ node -> addChild ( Token :: closeBracket ( ) ) ; return $ node ; }
Creates a new array lookup .
15,607
public function getKey ( $ index = 0 ) { $ keys = $ this -> getKeys ( ) ; if ( ! is_integer ( $ index ) ) { throw new \ InvalidArgumentException ( ) ; } if ( $ index < 0 || $ index >= count ( $ keys ) ) { throw new \ OutOfBoundsException ( ) ; } return $ keys [ $ index ] ; }
Returns a specific key in the lookup .
15,608
public function addLocales ( ConfigureLocales $ event ) { foreach ( new DirectoryIterator ( __DIR__ . '/../../locale' ) as $ file ) { if ( $ file -> isFile ( ) && in_array ( $ file -> getExtension ( ) , [ 'yml' , 'yaml' ] ) ) { $ event -> locales -> addTranslations ( $ file -> getBasename ( '.' . $ file -> getExtension ( ) ) , $ file -> getPathname ( ) ) ; } } }
Provides i18n files .
15,609
public function checkModuleValidity ( UploadedFile $ file , ExecutionContextInterface $ context ) { $ modulePath = $ this -> unzipModule ( $ file ) ; if ( $ modulePath !== false ) { try { $ moduleFiles = $ this -> getDirContents ( $ modulePath ) ; if ( \ count ( $ moduleFiles [ 'directories' ] ) !== 1 ) { throw new Exception ( Translator :: getInstance ( ) -> trans ( "Your zip must contain 1 root directory which is the root folder directory of your module" ) ) ; } $ moduleDirectory = $ moduleFiles [ 'directories' ] [ 0 ] ; $ this -> modulePath = sprintf ( '%s/%s' , $ modulePath , $ moduleDirectory ) ; $ moduleValidator = new ModuleValidator ( $ this -> modulePath ) ; $ moduleValidator -> validate ( ) ; $ this -> moduleDefinition = $ moduleValidator -> getModuleDefinition ( ) ; } catch ( Exception $ ex ) { $ context -> addViolation ( Translator :: getInstance ( ) -> trans ( "The module is not valid : %message" , [ '%message' => $ ex -> getMessage ( ) ] ) ) ; } } }
Check module validity
15,610
protected function unzipModule ( UploadedFile $ file ) { $ extractPath = false ; $ zip = new ZipArchiver ( true ) ; if ( ! $ zip -> open ( $ file -> getRealPath ( ) ) ) { throw new \ Exception ( "unable to open zipfile" ) ; } $ extractPath = $ this -> tempdir ( ) ; if ( $ extractPath !== false ) { if ( $ zip -> extract ( $ extractPath ) === false ) { $ extractPath = false ; } } $ zip -> close ( ) ; return $ extractPath ; }
Unzip a module file .
15,611
protected function tempdir ( ) { $ tempfile = tempnam ( sys_get_temp_dir ( ) , '' ) ; if ( file_exists ( $ tempfile ) ) { unlink ( $ tempfile ) ; } mkdir ( $ tempfile ) ; if ( is_dir ( $ tempfile ) ) { return $ tempfile ; } return false ; }
create a unique directory .
15,612
public static function create ( $ boolean = FALSE ) { $ is_upper = FormatterFactory :: getDefaultFormatter ( ) -> getConfig ( 'boolean_null_upper' ) ; $ node = new FalseNode ( ) ; $ node -> addChild ( NameNode :: create ( $ is_upper ? 'FALSE' : 'false' ) , 'constantName' ) ; return $ node ; }
Creates a new FalseNode .
15,613
public function appendMethodCall ( $ method_name ) { $ method_call = ObjectMethodCallNode :: create ( clone $ this , $ method_name ) ; $ this -> replaceWith ( $ method_call ) ; return $ method_call ; }
Allows you to append a method call to this one building a chain of method calls .
15,614
public function countAllContents ( $ contentVisibility = true ) { $ children = FolderQuery :: findAllChild ( $ this -> getId ( ) ) ; array_push ( $ children , $ this ) ; $ query = ContentQuery :: create ( ) -> filterByFolder ( new ObjectCollection ( $ children ) , Criteria :: IN ) ; if ( $ contentVisibility !== '*' ) { $ query -> filterByVisible ( $ contentVisibility ) ; } return $ query -> count ( ) ; }
count all products for current category and sub categories
15,615
public function getRoot ( $ folderId ) { $ folder = FolderQuery :: create ( ) -> findPk ( $ folderId ) ; if ( 0 !== $ folder -> getParent ( ) ) { $ parentFolder = FolderQuery :: create ( ) -> findPk ( $ folder -> getParent ( ) ) ; if ( null !== $ parentFolder ) { $ folderId = $ this -> getRoot ( $ parentFolder -> getId ( ) ) ; } } return $ folderId ; }
Get the root folder
15,616
public function runCommand ( Command $ command , array $ parameters = [ ] , OutputInterface $ output = null ) { $ parameters [ 'command' ] = $ command -> getName ( ) ; $ input = new ArrayInput ( $ parameters ) ; if ( $ output === null ) { $ output = new NullOutput ( ) ; } $ command -> setApplication ( new SymfonyConsoleApplication ( ) ) ; return $ command -> run ( $ input , $ output ) ; }
Run a Propel command .
15,617
public function buildPropelConfig ( ) { $ propelConfigCache = new ConfigCache ( $ this -> getPropelConfigFile ( ) , $ this -> debug ) ; if ( $ propelConfigCache -> isFresh ( ) ) { return ; } $ configService = new DatabaseConfigurationSource ( Yaml :: parse ( file_get_contents ( $ this -> getTheliaDatabaseConfigFile ( ) ) ) , $ this -> envParameters ) ; $ propelConfig = $ configService -> getPropelConnectionsConfiguration ( ) ; $ propelConfig [ 'propel' ] [ 'paths' ] [ 'phpDir' ] = THELIA_ROOT ; $ propelConfig [ 'propel' ] [ 'generator' ] [ 'objectModel' ] [ 'builders' ] = [ 'object' => '\Thelia\Core\Propel\Generator\Builder\Om\ObjectBuilder' , 'objectstub' => '\Thelia\Core\Propel\Generator\Builder\Om\ExtensionObjectBuilder' , 'objectmultiextend' => '\Thelia\Core\Propel\Generator\Builder\Om\MultiExtendObjectBuilder' , 'query' => '\Thelia\Core\Propel\Generator\Builder\Om\QueryBuilder' , 'querystub' => '\Thelia\Core\Propel\Generator\Builder\Om\ExtensionQueryBuilder' , 'queryinheritance' => '\Thelia\Core\Propel\Generator\Builder\Om\QueryInheritanceBuilder' , 'queryinheritancestub' => '\Thelia\Core\Propel\Generator\Builder\Om\ExtensionQueryInheritanceBuilder' , 'tablemap' => '\Thelia\Core\Propel\Generator\Builder\Om\TableMapBuilder' , 'event' => '\Thelia\Core\Propel\Generator\Builder\Om\EventBuilder' , ] ; $ propelConfigCache -> write ( Yaml :: dump ( $ propelConfig ) , [ new FileResource ( $ this -> getTheliaDatabaseConfigFile ( ) ) ] ) ; }
Generate the Propel configuration file .
15,618
public function buildPropelInitFile ( ) { $ propelInitCache = new ConfigCache ( $ this -> getPropelInitFile ( ) , $ this -> debug ) ; if ( $ propelInitCache -> isFresh ( ) ) { return ; } $ this -> runCommand ( new ConfigConvertCommand ( ) , [ '--config-dir' => $ this -> getPropelConfigDir ( ) , '--output-dir' => $ this -> getPropelConfigDir ( ) , '--output-file' => static :: $ PROPEL_CONFIG_CACHE_FILENAME , ] ) ; $ propelInitContent = file_get_contents ( $ this -> getPropelInitFile ( ) ) ; $ propelInitCache -> write ( $ propelInitContent , [ new FileResource ( $ this -> getPropelConfigFile ( ) ) ] ) ; }
Generate the Propel initialization file .
15,619
public function buildPropelModels ( ) { $ fs = new Filesystem ( ) ; if ( $ fs -> exists ( $ this -> getPropelModelDir ( ) . 'hash' ) && file_get_contents ( $ this -> getPropelCacheDir ( ) . 'hash' ) === file_get_contents ( $ this -> getPropelModelDir ( ) . 'hash' ) ) { return ; } $ fs -> remove ( $ this -> getPropelModelDir ( ) ) ; $ this -> runCommand ( new ModelBuildCommand ( ) , [ '--config-dir' => $ this -> getPropelConfigDir ( ) , '--schema-dir' => $ this -> getPropelSchemaDir ( ) , ] ) ; $ fs -> copy ( $ this -> getPropelCacheDir ( ) . 'hash' , $ this -> getPropelModelDir ( ) . 'hash' ) ; }
Generate the base Propel models .
15,620
public function registerPropelModelLoader ( ) { $ loader = new ClassLoader ( ) ; $ loader -> addPrefix ( '' , $ this -> getPropelModelDir ( ) ) ; $ loader -> register ( true ) ; }
Register a class loader to load the generated Propel models .
15,621
public function init ( $ force = false ) { $ flockFactory = new Factory ( new FlockStore ( ) ) ; $ lock = $ flockFactory -> createLock ( 'propel-cache-generation' ) ; $ lock -> acquire ( true ) ; try { if ( $ force ) { ( new Filesystem ( ) ) -> remove ( $ this -> getPropelCacheDir ( ) ) ; } if ( ! file_exists ( $ this -> getTheliaDatabaseConfigFile ( ) ) ) { return false ; } $ this -> buildPropelConfig ( ) ; $ this -> buildPropelInitFile ( ) ; require $ this -> getPropelInitFile ( ) ; $ theliaDatabaseConnection = Propel :: getConnection ( 'thelia' ) ; $ this -> schemaLocator -> setTheliaDatabaseConnection ( $ theliaDatabaseConnection ) ; $ this -> buildPropelGlobalSchema ( ) ; $ this -> buildPropelModels ( ) ; $ this -> registerPropelModelLoader ( ) ; $ theliaDatabaseConnection -> setAttribute ( ConnectionWrapper :: PROPEL_ATTR_CACHE_PREPARES , true ) ; if ( $ this -> debug ) { Tlog :: getInstance ( ) -> setLevel ( Tlog :: DEBUG ) ; Propel :: getServiceContainer ( ) -> setLogger ( 'defaultLogger' , Tlog :: getInstance ( ) ) ; $ theliaDatabaseConnection -> useDebug ( true ) ; } } catch ( \ Throwable $ th ) { $ fs = new Filesystem ( ) ; $ fs -> remove ( THELIA_CACHE_DIR . $ this -> environment ) ; $ fs -> remove ( $ this -> getPropelModelDir ( ) ) ; throw $ th ; } finally { $ lock -> release ( ) ; } return true ; }
Initialize the Propel environment and connection .
15,622
protected function addLoaderFile ( string $ file , string $ locale = null ) : void { if ( $ this -> loader === null ) { $ builder = $ this -> getContainerBuilder ( ) ; $ loader = $ builder -> getByType ( LoaderFactory :: class ) ; $ this -> loader = $ builder -> getDefinition ( $ loader ) ; } $ this -> loader -> addSetup ( 'addFile' , [ $ file , $ locale ] ) ; }
Prida soubor do loaderu
15,623
public function setLoad ( $ libraries ) { $ load = false ; $ product = false ; foreach ( $ libraries as $ name => $ version ) { if ( strpos ( $ version , 'dev' ) !== false ) { $ load = $ version ; $ product = $ name ; break ; } if ( version_compare ( $ load , $ version ) === - 1 ) { $ load = $ version ; $ product = $ name ; } } return $ this -> load = ( object ) array ( 'product' => $ product , 'version' => $ load ) ; }
Sets the product and version of library to load .
15,624
public function setPath ( ) { $ found = $ this -> getLoad ( ) ; $ path = false ; if ( ! empty ( $ found -> product ) ) { if ( ! is_file ( $ path = trailingslashit ( WPMU_PLUGIN_DIR ) . $ found -> product ) ) { if ( ! is_file ( $ path = trailingslashit ( WP_PLUGIN_DIR ) . $ found -> product ) ) { $ path = get_template_directory ( ) . '/inc/boldgrid-theme-framework/includes/theme' ; } } if ( defined ( 'BGTFW_PATH' ) ) { $ dir = ABSPATH . trim ( BGTFW_PATH , '/' ) . '/includes' ; if ( is_dir ( $ dir . '/vendor/boldgrid/library' ) ) { $ path = $ dir . '/theme' ; } } $ path = dirname ( $ path ) ; } return $ this -> path = $ path ; }
Sets the path class property .
15,625
public function load ( $ loader ) { if ( ! empty ( $ this -> configs [ 'libraryDir' ] ) ) { $ library = $ this -> configs [ 'libraryDir' ] . 'src/Library' ; if ( did_action ( 'Boldgrid\Library\Library\Start' ) === 0 ) { do_action ( 'Boldgrid\Library\Library\Start' , $ library ) ; if ( is_dir ( $ library ) ) { $ loader -> addPsr4 ( 'Boldgrid\\Library\\Library\\' , $ library ) ; $ load = new \ Boldgrid \ Library \ Library \ Start ( $ this -> configs ) ; $ load -> init ( ) ; } } } }
Adds the Library paths to the autoloader .
15,626
public function setDefault ( ) : void { $ repo = $ this -> getRepository ( ) ; $ locales = $ repo -> findAll ( ) ; foreach ( $ locales as $ locale ) { $ locale -> default = false ; $ repo -> persist ( $ locale ) ; } $ this -> default = true ; $ repo -> persist ( $ this ) ; $ repo -> flush ( ) ; }
Nastavi na vychozi
15,627
public function getOriginOfPageByPageIdAction ( ) { $ data = array ( ) ; $ tool = $ this -> getServiceLocator ( ) -> get ( 'MelisCmsPage' ) ; $ data = $ tool -> getOriginOfPage ( ) -> toArray ( ) ; return $ data ; }
Return the origin of the page by id
15,628
public function process ( \ Symfony \ Component \ DependencyInjection \ ContainerBuilder $ container ) { if ( ! $ container -> hasDefinition ( "thelia.admin.resources" ) ) { return ; } $ adminResources = $ container -> getDefinition ( "thelia.admin.resources" ) ; $ adminResources -> addMethodCall ( "addModuleResources" , [ $ this -> getResources ( ) , $ this -> getModuleCode ( ) ] ) ; }
Allow module to add resources in AdminResources Service
15,629
public function checkMandatoryColumns ( array $ data ) { $ diff = array_diff ( $ this -> mandatoryColumns , array_keys ( $ data ) ) ; if ( \ count ( $ diff ) > 0 ) { throw new \ UnexpectedValueException ( Translator :: getInstance ( ) -> trans ( 'The following columns are missing: %columns' , [ '%columns' => implode ( ', ' , $ diff ) ] ) ) ; } }
Check mandatory columns
15,630
public function applyOrderAndAliases ( array $ data ) { if ( $ this -> orderAndAliases === null ) { return $ data ; } $ processedData = [ ] ; foreach ( $ this -> orderAndAliases as $ key => $ value ) { if ( \ is_integer ( $ key ) ) { $ fieldName = $ value ; $ fieldAlias = $ value ; } else { $ fieldName = $ key ; $ fieldAlias = $ value ; } $ processedData [ $ fieldAlias ] = null ; if ( array_key_exists ( $ fieldName , $ data ) ) { $ processedData [ $ fieldAlias ] = $ data [ $ fieldName ] ; } } return $ processedData ; }
Apply order and aliases on data
15,631
public function beforeSerialize ( array $ data ) { foreach ( $ data as $ idx => & $ value ) { if ( $ value instanceof \ DateTime ) { $ value = $ value -> format ( 'Y-m-d H:i:s' ) ; } } return $ data ; }
Process data before serialization
15,632
private static function doFilter ( $ action , $ class ) { $ reflection = new \ ReflectionClass ( $ class ) ; foreach ( $ reflection -> getMethods ( ) as $ method ) { if ( $ method -> isPublic ( ) && ! $ method -> isConstructor ( ) ) { $ comment = $ method -> getDocComment ( ) ; if ( preg_match ( '/@nohook[ \t\*\n]+/' , $ comment ) ) { continue ; } preg_match_all ( '/@hook:?\s+([^\s]+)/' , $ comment , $ matches ) ? $ matches [ 1 ] : $ method -> name ; if ( empty ( $ matches [ 1 ] ) ) { $ hooks = array ( $ method -> name ) ; } else { $ hooks = $ matches [ 1 ] ; } $ priority = preg_match ( '/@priority:?\s+(\d+)/' , $ comment , $ matches ) ? $ matches [ 1 ] : 10 ; foreach ( $ hooks as $ hook ) { call_user_func ( $ action , $ hook , array ( $ class , $ method -> name ) , $ priority , $ method -> getNumberOfParameters ( ) ) ; } } } }
Process hooks .
15,633
public static function removeHook ( $ tag , $ class , $ name , $ priority = 10 ) { global $ wp_filter ; if ( isset ( $ wp_filter [ $ tag ] ) ) { if ( is_object ( $ wp_filter [ $ tag ] ) && isset ( $ wp_filter [ $ tag ] -> callbacks ) ) { $ fob = $ wp_filter [ $ tag ] ; $ callbacks = & $ wp_filter [ $ tag ] -> callbacks ; } else { $ callbacks = & $ wp_filter [ $ tag ] ; } if ( ! isset ( $ callbacks [ $ priority ] ) || empty ( $ callbacks [ $ priority ] ) ) { return false ; } foreach ( ( array ) $ callbacks [ $ priority ] as $ filter_id => $ filter ) { if ( ! isset ( $ filter [ 'function' ] ) || ! is_array ( $ filter [ 'function' ] ) ) { continue ; } if ( ! is_object ( $ filter [ 'function' ] [ 0 ] ) ) { continue ; } if ( $ filter [ 'function' ] [ 1 ] !== $ name ) { continue ; } if ( get_class ( $ filter [ 'function' ] [ 0 ] ) === $ class ) { if ( isset ( $ fob ) ) { $ fob -> remove_filter ( $ tag , $ filter [ 'function' ] , $ priority ) ; } else { unset ( $ callbacks [ $ priority ] [ $ filter_id ] ) ; if ( empty ( $ callbacks [ $ priority ] ) ) { unset ( $ callbacks [ $ priority ] ) ; } if ( empty ( $ callbacks ) ) { $ callbacks = array ( ) ; } unset ( $ GLOBALS [ 'merged_filters' ] [ $ tag ] ) ; } return true ; } } } return false ; }
Removes an anonymous object filter .
15,634
public function checkDate ( $ value , ExecutionContextInterface $ context ) { $ format = self :: PHP_DATE_FORMAT ; if ( ! empty ( $ value ) && false === \ DateTime :: createFromFormat ( $ format , $ value ) ) { $ context -> addViolation ( Translator :: getInstance ( ) -> trans ( "Date '%date' is invalid, please enter a valid date using %fmt format" , [ '%fmt' => self :: MOMENT_JS_DATE_FORMAT , '%date' => $ value ] ) ) ; } }
Validate a date entered with the current edition Language date format .
15,635
protected function initRequest ( Lang $ lang = null ) { $ container = $ this -> getContainer ( ) ; $ request = Request :: create ( $ this -> getBaseUrl ( $ lang ) ) ; $ request -> setSession ( new Session ( new MockArraySessionStorage ( ) ) ) ; $ container -> set ( "request_stack" , new RequestStack ( ) ) ; $ container -> get ( 'request_stack' ) -> push ( $ request ) ; $ requestContext = new RequestContext ( ) ; $ requestContext -> fromRequest ( $ request ) ; $ url = $ container -> get ( 'thelia.url.manager' ) ; $ url -> setRequestContext ( $ requestContext ) ; $ this -> getContainer ( ) -> get ( 'router.admin' ) -> setContext ( $ requestContext ) ; }
For init an Request if your command has need an Request
15,636
public function duplicate ( $ token , Customer $ customer = null , Currency $ currency = null , EventDispatcherInterface $ dispatcher = null ) { if ( ! $ dispatcher ) { return false ; } $ cartItems = $ this -> getCartItems ( ) ; $ cart = new Cart ( ) ; $ cart -> setAddressDeliveryId ( $ this -> getAddressDeliveryId ( ) ) ; $ cart -> setAddressInvoiceId ( $ this -> getAddressInvoiceId ( ) ) ; $ cart -> setToken ( $ token ) ; $ discount = 0 ; if ( null === $ currency ) { $ currencyQuery = CurrencyQuery :: create ( ) ; $ currency = $ currencyQuery -> findPk ( $ this -> getCurrencyId ( ) ) ? : $ currencyQuery -> findOneByByDefault ( 1 ) ; } $ cart -> setCurrency ( $ currency ) ; if ( $ customer ) { $ cart -> setCustomer ( $ customer ) ; if ( $ customer -> getDiscount ( ) > 0 ) { $ discount = $ customer -> getDiscount ( ) ; } } $ cart -> save ( ) ; foreach ( $ cartItems as $ cartItem ) { $ product = $ cartItem -> getProduct ( ) ; $ productSaleElements = $ cartItem -> getProductSaleElements ( ) ; if ( $ product && $ productSaleElements && $ product -> getVisible ( ) == 1 && ( $ productSaleElements -> getQuantity ( ) >= $ cartItem -> getQuantity ( ) || $ product -> getVirtual ( ) === 1 || ! ConfigQuery :: checkAvailableStock ( ) ) ) { $ item = new CartItem ( ) ; $ item -> setCart ( $ cart ) ; $ item -> setProductId ( $ cartItem -> getProductId ( ) ) ; $ item -> setQuantity ( $ cartItem -> getQuantity ( ) ) ; $ item -> setProductSaleElements ( $ productSaleElements ) ; $ prices = $ productSaleElements -> getPricesByCurrency ( $ currency , $ discount ) ; $ item -> setPrice ( $ prices -> getPrice ( ) ) -> setPromoPrice ( $ prices -> getPromoPrice ( ) ) -> setPromo ( $ productSaleElements -> getPromo ( ) ) ; $ item -> save ( ) ; $ dispatcher -> dispatch ( TheliaEvents :: CART_ITEM_DUPLICATE , new CartItemDuplicationItem ( $ item , $ cartItem ) ) ; } } $ dispatcher -> dispatch ( TheliaEvents :: CART_DUPLICATED , new CartDuplicationEvent ( $ cart , $ this ) ) ; try { $ this -> delete ( ) ; } catch ( \ Exception $ e ) { } return $ cart ; }
Duplicate the current existing cart . Only the token is changed
15,637
public function getLastCartItemAdded ( ) { return CartItemQuery :: create ( ) -> filterByCartId ( $ this -> getId ( ) ) -> orderByCreatedAt ( Criteria :: DESC ) -> findOne ( ) ; }
Retrieve the last item added in the cart
15,638
public function getTotalVAT ( $ taxCountry , $ taxState = null ) { return ( $ this -> getTaxedAmount ( $ taxCountry , true , $ taxState ) - $ this -> getTotalAmount ( true ) ) ; }
Return the VAT of all items
15,639
public function getWeight ( ) { $ weight = 0 ; foreach ( $ this -> getCartItems ( ) as $ cartItem ) { $ itemWeight = $ cartItem -> getProductSaleElements ( ) -> getWeight ( ) ; $ itemWeight *= $ cartItem -> getQuantity ( ) ; $ weight += $ itemWeight ; } return $ weight ; }
Retrieve the total weight for all products in cart
15,640
public function isVirtual ( ) { foreach ( $ this -> getCartItems ( ) as $ cartItem ) { if ( 0 < $ cartItem -> getProductSaleElements ( ) -> getWeight ( ) ) { return false ; } $ product = $ cartItem -> getProductSaleElements ( ) -> getProduct ( ) ; if ( ! $ product -> getVirtual ( ) ) { return false ; } } return true ; }
Tell if the cart contains only virtual products
15,641
protected function createComponentConfigurationForm ( ) : Form { $ form = $ this -> formFactory -> create ( ) ; $ form -> setAjaxRequest ( ) ; $ form -> addGroup ( 'cms.settings.basic' ) ; $ form -> addImageUpload ( 'cmsLogo' , 'cms.settings.logo' , 'cms.settings.deleteLogo' ) -> setNamespace ( 'cms' ) -> setPreview ( '300x100' ) ; $ form -> addCheckbox ( 'sendNewUserPassword' , 'cms.settings.sendNewUserPassword' ) ; $ form -> addCheckbox ( 'sendChangePassword' , 'cms.settings.sendChangePassword' ) ; $ form -> addCheckbox ( 'dockbarAdvanced' , 'cms.settings.dockbarAdvanced' ) ; $ form -> addSelectUntranslated ( 'defaultLocale' , 'cms.settings.defaultLocale' , $ this -> localeService -> fetch ( ) ) -> setDefaultValue ( $ this -> localeService -> defaultLocaleId ) ; $ form -> addMultiSelectUntranslated ( 'allowedLocales' , 'cms.settings.allowedLocales' , $ this -> localeService -> fetch ( ) ) -> setDefaultValue ( $ this -> localeService -> allowedLocaleIds ) -> setRequired ( ) ; $ form -> addGroup ( 'cms.settings.development' ) ; if ( ! $ this -> tracy -> isEnabled ( ) ) { $ form -> addLink ( 'debugOn' , 'cms.settings.debugOn' ) -> link ( $ this -> link ( 'debug!' , true ) ) -> setAjaxRequest ( ) -> addClass ( 'btn-success' ) -> setAttribute ( 'data-ajax-off' , 'history' ) ; } else { $ form -> addLink ( 'debugOff' , 'cms.settings.debugOff' ) -> link ( $ this -> link ( 'debug!' , false ) ) -> setAjaxRequest ( ) -> addClass ( 'btn-danger' ) -> setAttribute ( 'data-ajax-off' , 'history' ) ; } $ form -> addCheckbox ( 'mailPanel' , 'cms.settings.mailPanel' ) -> setDefaultValue ( $ this -> configurator -> mailPanel ) ; $ form -> getRenderer ( ) -> primaryButton = $ form -> addSubmit ( 'save' , 'form.save' ) ; $ form -> onSuccess [ ] = [ $ this , 'configurationFormSucseeded' ] ; return $ form ; }
Komponenta formulare nastaveni
15,642
public static function init ( $ name = 'boldgrid_settings' , $ key = 'library' ) { self :: $ name = $ name ; self :: $ key = $ key ; self :: $ option = self :: getOption ( ) ; }
Initialize the option utility .
15,643
public static function set ( $ key , $ value ) { self :: $ option [ self :: $ key ] [ $ key ] = $ value ; return update_option ( self :: $ name , self :: $ option ) ; }
Set option key value .
15,644
public static function delete ( $ key ) { unset ( self :: $ option [ self :: $ key ] [ $ key ] ) ; return update_option ( self :: $ name , self :: $ option ) ; }
Deletes by key in stored option .
15,645
public static function get ( $ key = null , $ default = array ( ) ) { return $ key && ! empty ( self :: $ option [ $ key ] ) ? self :: $ option [ $ key ] : $ default ; }
Retrieves an option key from the array .
15,646
final public function hasRequiredRole ( UserInterface $ user = null , array $ roles = [ ] ) { if ( $ user != null ) { $ userRoles = $ user -> getRoles ( ) ; foreach ( $ userRoles as $ role ) { if ( \ in_array ( $ role , $ roles ) ) { return true ; } } } return false ; }
Check if a user has at least one of the required roles
15,647
final public function isGranted ( array $ roles , array $ resources , array $ modules , array $ accesses ) { $ user = $ this -> checkRole ( $ roles ) ; if ( null === $ user ) { return false ; } else { return $ this -> isUserGranted ( $ roles , $ resources , $ modules , $ accesses , $ user ) ; } }
Checks if the current user is allowed
15,648
public function checkRole ( array $ roles ) { $ user = $ this -> getCustomerUser ( ) ; if ( ! $ this -> hasRequiredRole ( $ user , $ roles ) ) { $ user = $ this -> getAdminUser ( ) ; if ( ! $ this -> hasRequiredRole ( $ user , $ roles ) ) { $ user = null ; } } return $ user ; }
look if a user has the required role .
15,649
private function insertOrReplaceTag ( $ content , $ search , $ replace ) { $ newContent = null ; $ regexSearch = "/(\<$search\>\<\!\[CDATA\[([0-9.])+\]\]\>\<\/$search\>)/" ; if ( preg_match ( $ regexSearch , $ content ) ) { $ newContent = preg_replace ( $ regexSearch , $ replace , $ content ) ; } else { $ newContent = $ content . $ replace ; } return $ newContent ; }
This method modifies the XML plugin data and looks for width tags and replaces the value
15,650
private function updateMelisPlugin ( $ pageId , $ plugin , $ pluginId , $ content , $ updateSettings = false ) { $ pluginContent = $ content ; $ pluginSessionSettings = isset ( $ _SESSION [ 'meliscms' ] [ 'content-pages' ] [ $ pageId ] [ 'private:melisPluginSettings' ] [ $ pluginId ] ) ? $ _SESSION [ 'meliscms' ] [ 'content-pages' ] [ $ pageId ] [ 'private:melisPluginSettings' ] [ $ pluginId ] : '' ; $ pluginSettings = ( array ) json_decode ( $ pluginSessionSettings ) ; if ( $ plugin == 'melisTag' ) { $ pattern = '/type\=\"([html|media|textarea]*\")/' ; if ( preg_match ( $ pattern , $ pluginContent , $ matches ) ) { $ type = isset ( $ matches [ 0 ] ) ? $ matches [ 0 ] : null ; if ( $ type ) { if ( $ pluginSettings ) { $ pluginContent = $ this -> setPluginWidthXmlAttribute ( $ pluginContent , $ pluginSettings ) ; } } } } else { $ pattern = '\<' . $ plugin . '\sid\=\"(.*?)*\"' ; if ( preg_match ( '/' . $ pattern . '/' , $ pluginContent , $ matches ) ) { $ id = isset ( $ matches [ 0 ] ) ? $ matches [ 0 ] : null ; if ( $ id ) { if ( $ pluginSettings ) { $ pluginContent = $ this -> setPluginWidthXmlAttribute ( $ pluginContent , $ pluginSettings ) ; } } } } if ( isset ( $ _SESSION [ 'meliscms' ] [ 'content-pages' ] [ $ pageId ] [ $ plugin ] [ $ pluginId ] ) ) { $ _SESSION [ 'meliscms' ] [ 'content-pages' ] [ $ pageId ] [ $ plugin ] [ $ pluginId ] = $ this -> getPluginContentWithInsertedContainerId ( $ pageId , $ plugin , $ pluginId , $ pluginContent ) ; $ pluginContent = $ _SESSION [ 'meliscms' ] [ 'content-pages' ] [ $ pageId ] [ $ plugin ] [ $ pluginId ] ; if ( $ updateSettings ) { $ _SESSION [ 'meliscms' ] [ 'content-pages' ] [ $ pageId ] [ $ plugin ] [ $ pluginId ] = $ this -> reapplySettings ( $ pageId , $ plugin , $ pluginId , $ pluginContent ) ; } if ( $ plugin == 'melisTag' ) { $ content = $ this -> updateContent ( $ pageId , $ plugin , $ pluginId , $ pluginContent ) ; $ _SESSION [ 'meliscms' ] [ 'content-pages' ] [ $ pageId ] [ $ plugin ] [ $ pluginId ] = $ content ; } } }
This method modifies the tag plugin xml attribute applying the changes of the width
15,651
private function setPluginWidthXmlAttribute ( $ pluginXml , $ pluginSettings ) { try { $ pluginDesktop = isset ( $ pluginSettings [ 'width_desktop' ] ) ? $ pluginSettings [ 'width_desktop' ] : 100 ; $ pluginTablet = isset ( $ pluginSettings [ 'width_tablet' ] ) ? $ pluginSettings [ 'width_tablet' ] : 100 ; $ pluginMobile = isset ( $ pluginSettings [ 'width_mobile' ] ) ? $ pluginSettings [ 'width_mobile' ] : 100 ; $ xml = simplexml_load_string ( $ pluginXml ) ; if ( isset ( $ xml -> attributes ( ) -> width_desktop ) ) $ xml -> attributes ( ) -> width_desktop = $ pluginDesktop ; else $ xml -> addAttribute ( 'width_desktop' , $ pluginDesktop ) ; if ( isset ( $ xml -> attributes ( ) -> width_tablet ) ) $ xml -> attributes ( ) -> width_tablet = $ pluginTablet ; else $ xml -> addAttribute ( 'width_tablet' , $ pluginTablet ) ; if ( isset ( $ xml -> attributes ( ) -> width_mobile ) ) $ xml -> attributes ( ) -> width_mobile = $ pluginMobile ; else $ xml -> addAttribute ( 'width_mobile' , $ pluginMobile ) ; $ customXML = new \ SimpleXMLElement ( $ xml -> asXML ( ) ) ; $ dom = dom_import_simplexml ( $ customXML ) ; $ pluginXml = $ dom -> ownerDocument -> saveXML ( $ dom -> ownerDocument -> documentElement ) ; } catch ( \ Exception $ e ) { } return $ pluginXml ; }
This method will setup the width of the plugin xml config
15,652
public function getWeight ( ) { $ weight = 0 ; foreach ( $ this -> getOrderProducts ( ) as $ orderProduct ) { $ weight += $ orderProduct -> getQuantity ( ) * ( double ) $ orderProduct -> getWeight ( ) ; } return $ weight ; }
Compute this order weight .
15,653
public function getUntaxedPostage ( ) { if ( 0 < $ this -> getPostageTax ( ) ) { $ untaxedPostage = $ this -> getPostage ( ) - $ this -> getPostageTax ( ) ; } else { $ untaxedPostage = $ this -> getPostage ( ) ; } return $ untaxedPostage ; }
Return the postage without tax
15,654
public function hasVirtualProduct ( ) { $ virtualProductCount = OrderProductQuery :: create ( ) -> filterByOrderId ( $ this -> getId ( ) ) -> filterByVirtual ( 1 , Criteria :: EQUAL ) -> count ( ) ; return ( $ virtualProductCount !== 0 ) ; }
Check if the current order contains at less 1 virtual product with a file to download
15,655
public function setStatusHelper ( $ statusCode ) { if ( null !== $ ordeStatus = OrderStatusQuery :: create ( ) -> findOneByCode ( $ statusCode ) ) { $ this -> setOrderStatus ( $ ordeStatus ) -> save ( ) ; } }
Set the status of the current order to the provided status
15,656
public function getPaymentModuleInstance ( ) { if ( null === $ paymentModule = ModuleQuery :: create ( ) -> findPk ( $ this -> getPaymentModuleId ( ) ) ) { throw new TheliaProcessException ( "Payment module ID=" . $ this -> getPaymentModuleId ( ) . " was not found." ) ; } return $ paymentModule -> createInstance ( ) ; }
Get an instance of the payment module
15,657
public function getDeliveryModuleInstance ( ) { if ( null === $ deliveryModule = ModuleQuery :: create ( ) -> findPk ( $ this -> getDeliveryModuleId ( ) ) ) { throw new TheliaProcessException ( "Delivery module ID=" . $ this -> getDeliveryModuleId ( ) . " was not found." ) ; } return $ deliveryModule -> createInstance ( ) ; }
Get an instance of the delivery module
15,658
public static function getFromName ( $ messageName ) { if ( false === $ message = MessageQuery :: create ( ) -> filterByName ( $ messageName ) -> findOne ( ) ) { throw new \ Exception ( "Failed to load message $messageName." ) ; } return $ message ; }
Load a message from its name throwing an excemtoipn is none is found .
15,659
protected function init ( $ product , $ dependency = 'boldgrid/library' ) { $ this -> product = $ product ; $ this -> dependency = $ dependency ; Option :: init ( ) ; $ this -> libraries = Option :: get ( 'library' ) ; $ this -> verify ( ) ; }
Initialize class and set class properties .
15,660
public function register ( ) { $ version = new Version ( $ this -> getDependency ( ) ) ; Option :: set ( $ this -> getProduct ( ) , $ version -> getVersion ( ) ) ; }
Register the product in WordPress options .
15,661
public function isValid ( IsValidPaymentEvent $ event , $ eventName , EventDispatcherInterface $ dispatcher ) { $ module = $ event -> getModule ( ) ; $ dispatcher -> dispatch ( TheliaEvents :: getModuleEvent ( TheliaEvents :: MODULE_PAYMENT_IS_VALID , $ module -> getCode ( ) ) , $ event ) ; if ( $ event -> isPropagationStopped ( ) ) { return ; } $ event -> setValidModule ( $ module -> isValidPayment ( ) ) ; }
Check if a module is valid
15,662
protected function getRememberMeKeyFromCookie ( Request $ request , $ cookieName ) { $ ctp = new CookieTokenProvider ( ) ; return $ ctp -> getKeyFromCookie ( $ request , $ cookieName ) ; }
Get the remember me key from the cookie .
15,663
protected function createRememberMeCookie ( UserInterface $ user , $ cookieName , $ cookieExpiration ) { $ ctp = new CookieTokenProvider ( ) ; $ ctp -> createCookie ( $ user , $ cookieName , $ cookieExpiration ) ; }
Create the remember me cookie for the given user .
15,664
public function toUpperCase ( ) { $ token = $ this -> getConstantName ( ) -> lastToken ( ) ; $ token -> setText ( strtoupper ( $ token -> getText ( ) ) ) ; return $ this ; }
Convert the constant into uppercase .
15,665
public function toLowerCase ( ) { $ token = $ this -> getConstantName ( ) -> lastToken ( ) ; $ token -> setText ( strtolower ( $ token -> getText ( ) ) ) ; return $ this ; }
Convert the constant into lowercase .
15,666
public function listen ( $ channel , $ expr , callable $ handler ) { $ this -> adapter -> subscribe ( $ channel , function ( $ message ) use ( $ expr , $ handler ) { $ this -> handleSubscribeCallback ( $ message , $ expr , $ handler ) ; } ) ; }
Listen for an event .
15,667
public function dispatchBatch ( $ channel , array $ events ) { $ messages = [ ] ; $ validates = true ; foreach ( $ events as $ event ) { $ event = $ this -> prepEventForDispatch ( $ event ) ; if ( $ this -> validator ) { $ result = $ this -> validator -> validate ( $ event ) ; if ( $ result -> fails ( ) ) { $ validates = false ; 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 ) ; } }
Dispatch multiple events .
15,668
public function make ( array $ config ) { Arr :: requires ( $ config , [ 'from' , 'token' ] ) ; $ client = new Client ( ) ; return new CampfireGateway ( $ client , $ config ) ; }
Create a new campfire gateway instance .
15,669
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 ) ; }
Retrieve all database table names and store them into the event .
15,670
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 ) ; } }
Retrieve all column names for the current selected table .
15,671
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 ( ) ) ) ; } } }
Check if the select_where value is valid by firing a test query .
15,672
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 ) ; }
Retrieve all column names for the given table .
15,673
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 ) ; } }
Add a condition to a property .
15,674
private function isBackendOptionRequestFor ( $ event , $ fields ) { if ( ! $ this -> scopeMatcher -> currentScopeIsBackend ( ) ) { return false ; } return ( 'tl_metamodel_attribute' === $ event -> getEnvironment ( ) -> getDataDefinition ( ) -> getName ( ) ) && \ in_array ( $ event -> getPropertyName ( ) , $ fields ) ; }
Test if the event is an option request for any of the passed fields .
15,675
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 ; }
Get closest accepted cash amount .
15,676
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" ; }
Gets the uri to access the site .
15,677
public static function create ( $ class_name , $ method_name ) { if ( is_string ( $ class_name ) ) { $ class_name = NameNode :: create ( $ class_name ) ; } $ 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 ; }
Creates a method call on a class with an empty argument list .
15,678
public function clearCache ( CachedFileEvent $ event ) { $ path = $ this -> getCachePath ( $ event -> getCacheSubdirectory ( ) , false ) ; $ this -> clearDirectory ( $ path ) ; }
Clear the file cache . Is a subdirectory is specified only this directory is cleared . If no directory is specified the whole cache is cleared . Only files are deleted directories will remain .
15,679
protected function clearDirectory ( $ path ) { $ iterator = new \ DirectoryIterator ( $ path ) ; foreach ( $ iterator as $ fileinfo ) { if ( $ fileinfo -> isDot ( ) ) { continue ; } if ( $ fileinfo -> isFile ( ) || $ fileinfo -> isLink ( ) ) { @ unlink ( $ fileinfo -> getPathname ( ) ) ; } elseif ( $ fileinfo -> isDir ( ) ) { $ this -> clearDirectory ( $ fileinfo -> getPathname ( ) ) ; } } }
Recursively clears the specified directory .
15,680
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 ) ; }
Return the absolute URL to the cached file
15,681
protected function getCacheFilePath ( $ subdir , $ filename , $ forceOriginalFile = false , $ hashed_options = null ) { $ path = $ this -> getCachePath ( $ subdir ) ; $ safe_filename = preg_replace ( "[^:alnum:\-\._]" , "-" , strtolower ( basename ( $ filename ) ) ) ; if ( $ forceOriginalFile || $ hashed_options == null ) { return sprintf ( "%s/%s" , $ path , $ safe_filename ) ; } else { return sprintf ( "%s/%s-%s" , $ path , $ hashed_options , $ safe_filename ) ; } }
Return the full path of the cached file
15,682
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 ; } return $ path ; }
Return the cache directory path relative to Web Root
15,683
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 ) ; 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 ) ) ; } } $ 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 ; }
Return the absolute cache directory path
15,684
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 ; } }
Take care of saving a file in the database and file storage
15,685
public function updateFile ( FileCreateOrUpdateEvent $ event ) { if ( $ event -> getUploadedFile ( ) ) { $ url = $ event -> getModel ( ) -> getUploadDir ( ) . '/' . $ event -> getOldModel ( ) -> getFile ( ) ; unlink ( str_replace ( '..' , '' , $ url ) ) ; $ newUploadedFile = $ this -> fileManager -> copyUploadedFile ( $ event -> getModel ( ) , $ event -> getUploadedFile ( ) ) ; $ event -> setUploadedFile ( $ newUploadedFile ) ; } $ event -> getModel ( ) -> save ( ) ; $ event -> setModel ( $ event -> getModel ( ) ) ; }
Take care of updating file in the database and file storage
15,686
public function addFragment ( Fragment $ fragment ) { if ( ! empty ( $ this -> fields ) ) { $ fragment -> filter ( $ this -> fields ) ; } $ this -> fragmentBag -> addFragment ( $ fragment ) ; return $ this ; }
Add a new fragment
15,687
private function setMessages ( ) { $ allowed_html = array ( 'a' => array ( 'href' => array ( ) , ) , 'strong' => array ( ) , ) ; $ msg = new \ stdClass ( ) ; $ msg -> success = sprintf ( wp_kses ( __ ( '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 ( 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 ; }
Sets the messages returned by key prompt .
15,688
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 ; }
Get the current state of the BoldGrid Connect Key .
15,689
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' ; $ enableClaimMessage = apply_filters ( 'Boldgrid\Library\Library\Notice\ClaimPremiumKey_enable' , false ) ; include dirname ( __DIR__ ) . '/Views/KeyPrompt.php' ; self :: $ isDisplayed = true ; } }
Displays the notice .
15,690
public function addKey ( ) { 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 ) ) ; } }
Key input handling .
15,691
protected function validate ( ) { $ msg = $ this -> getMessages ( ) ; if ( ! isset ( $ _POST [ 'set_key_auth' ] ) || ! check_ajax_referer ( 'boldgrid_set_key' , 'set_key_auth' , false ) ) { wp_send_json_error ( array ( 'message' => $ msg -> nonce ) ) ; } if ( empty ( $ _POST [ 'api_key' ] ) ) { wp_send_json_error ( array ( 'message' => $ msg -> error ) ) ; } $ 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 ( ) ; }
Handles validation of user input on API key entry form .
15,692
public function getIsDismissed ( ) { if ( is_null ( self :: $ isDismissed ) ) { self :: $ isDismissed = Library \ Notice :: isDismissed ( $ this -> userNoticeKey ) ; } return self :: $ isDismissed ; }
Get static class property isDismissed .
15,693
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' ) ; }
Check if a template definition is the current active template
15,694
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 { $ di = new \ DirectoryIterator ( $ baseDir ) ; foreach ( $ di as $ file ) { if ( $ file -> isDot ( ) || ! $ file -> isDir ( ) ) { continue ; } if ( \ in_array ( $ file -> getFilename ( ) , $ exclude ) ) { continue ; } $ list [ ] = new TemplateDefinition ( $ file -> getFilename ( ) , $ templateType ) ; } } catch ( \ UnexpectedValueException $ ex ) { } } } return $ list ; }
Return a list of existing templates for a given template type
15,695
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' ) ] ) ; }
Manage Coupons list display
15,696
public function createAction ( ) { if ( null !== $ response = $ this -> checkAuth ( AdminResources :: COUPON , [ ] , AccessManager :: CREATE ) ) { return $ response ; } $ args = [ ] ; $ eventToDispatch = TheliaEvents :: COUPON_CREATE ; if ( $ this -> getRequest ( ) -> isMethod ( 'POST' ) ) { if ( null !== $ response = $ this -> validateCreateOrUpdateForm ( $ eventToDispatch , 'created' , 'creation' ) ) { return $ response ; } } else { $ 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' ; $ this -> getParserContext ( ) -> addForm ( $ this -> createForm ( AdminForm :: COUPON_CREATION ) ) ; return $ this -> render ( 'coupon-create' , $ args ) ; }
Manage Coupons creation display
15,697
protected function logError ( $ action , $ message , $ e ) { Tlog :: getInstance ( ) -> error ( sprintf ( 'Error during Coupon ' . $ action . ' process : %s. Exception was %s' , $ message , $ e -> getMessage ( ) ) ) ; return $ this ; }
Log error message
15,698
protected function validateCreateOrUpdateForm ( $ eventToDispatch , $ log , $ action , Coupon $ model = null ) { $ couponForm = $ this -> getForm ( $ action , $ model ) ; $ response = null ; $ message = false ; try { $ form = $ this -> validateForm ( $ couponForm , 'POST' ) ; $ couponEvent = $ this -> feedCouponCreateOrUpdateEvent ( $ form , $ model ) ; $ 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 { $ response = RedirectResponse :: create ( URL :: getInstance ( ) -> absoluteUrl ( $ this -> getRoute ( 'admin.coupon.list' ) ) ) ; } } catch ( FormValidationException $ ex ) { $ message = $ this -> createStandardFormValidationErrorMessage ( $ ex ) ; } catch ( \ Exception $ ex ) { $ message = $ this -> getTranslator ( ) -> trans ( 'Sorry, an error occurred: %err' , [ '%err' => $ ex -> getMessage ( ) ] ) ; $ this -> logError ( $ action , $ message , $ ex ) ; } if ( $ message !== false ) { $ couponForm -> setErrorMessage ( $ message ) ; $ this -> getParserContext ( ) -> addForm ( $ couponForm ) -> setGeneralError ( $ message ) ; } return $ response ; }
Validate the CreateOrUpdate form
15,699
protected function getAvailableConditions ( ) { $ couponManager = $ this -> container -> get ( 'thelia.coupon.manager' ) ; $ availableConditions = $ couponManager -> getAvailableConditions ( ) ; $ cleanedConditions = [ ] ; foreach ( $ availableConditions as $ availableCondition ) { $ condition = [ ] ; $ condition [ 'serviceId' ] = $ availableCondition -> getServiceId ( ) ; $ condition [ 'name' ] = $ availableCondition -> getName ( ) ; $ condition [ 'toolTip' ] = $ availableCondition -> getToolTip ( ) ; $ cleanedConditions [ ] = $ condition ; } return $ cleanedConditions ; }
Get all available conditions