idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
51,000
public function setColumns ( $ label , $ control = NULL ) { if ( $ control === NULL ) { $ control = 12 - $ label ; } $ this -> labelColumns = $ label ; $ this -> controlColumns = $ control ; }
Set how many of Bootstrap rows shall the label and control occupy
51,001
protected function fetchConfig ( $ key ) { $ config = $ this -> config [ $ key ] ; if ( isset ( $ this -> configOverride [ $ this -> renderMode ] [ $ key ] ) ) { $ override = $ this -> configOverride [ $ this -> renderMode ] [ $ key ] ; $ config = array_merge ( $ config , $ override ) ; } return $ config ; }
Fetch config tailored for current render mode
51,002
protected function getElem ( $ key , ... $ additionalKeys ) { $ el = $ this -> configElem ( $ key , Html :: el ( ) ) ; foreach ( $ additionalKeys as $ additionalKey ) { $ config = $ this -> fetchConfig ( $ additionalKey ) ; $ el = $ this -> configElem ( $ config , $ el ) ; } return $ el ; }
Get element based on its first - level key
51,003
public function setPrompt ( $ prompt ) { if ( empty ( $ prompt ) ) { return $ this ; } if ( isset ( $ this -> items ) ) { if ( in_array ( NULL , array_keys ( $ this -> items ) ) ) { throw new InvalidArgumentException ( "There is an item whose value == null (non-strict comparison)." . "Setting prompt would interfere with this value." ) ; } } else { throw new NotSupportedException ( 'This must be a ChoiceControl' ) ; } $ this -> prompt = $ prompt ; return $ this ; }
Sets the first unselectable item on list . Its value is null .
51,004
public function addCell ( $ numOfColumns = BootstrapCell :: COLUMNS_NONE ) { if ( $ this -> columnsOccupied + $ numOfColumns > $ this -> numOfColumns ) { throw new InvalidArgumentException ( "the given number of columns with combination of already used" . " columns exceeds column limit ({$this->numOfColumns})" ) ; } $ cell = new BootstrapCell ( $ this , $ numOfColumns ) ; $ this -> cells [ ] = $ cell ; return $ cell ; }
Adds a new cell to which a control can be added .
51,005
public function addComponent ( IComponent $ component , $ name , $ insertBefore = NULL ) { $ this -> container -> addComponent ( $ component , $ name , $ insertBefore ) ; $ this -> ownedNames [ ] = $ name ; }
Delegate to underlying container and remember it .
51,006
public function getOption ( $ option , $ default = NULL ) { return isset ( $ this -> options [ $ option ] ) ? $ this -> options [ $ option ] : $ default ; }
Gets previously set option
51,007
public function render ( ) { $ renderer = $ this -> container -> form -> renderer ; $ element = $ renderer -> configElem ( RendererConfig :: gridRow , $ this -> elementPrototype ) ; foreach ( $ this -> cells as $ cell ) { $ cellHtml = $ cell -> render ( ) ; $ element -> addHtml ( $ cellHtml ) ; } return $ element ; }
Renders the row into a Html object
51,008
public function render ( ) { $ element = $ this -> elementPrototype ; $ renderer = $ this -> row -> getParent ( ) -> form -> renderer ; $ element = $ renderer -> configElem ( RendererConfig :: gridCell , $ element ) ; $ element -> class [ ] = $ this -> createClass ( ) ; if ( $ this -> childControl ) { $ pairHtml = $ renderer -> renderPair ( $ this -> childControl ) ; $ element -> addHtml ( $ pairHtml ) ; } return $ element ; }
Renders the cell into Html object
51,009
protected function addComponent ( IComponent $ component , $ name , $ insertBefore = NULL ) { if ( $ this -> childControl ) { throw new LogicException ( 'child control for this cell has already been set, you cannot add another one' ) ; } $ this -> row -> addComponent ( $ component , $ name , $ insertBefore ) ; $ this -> childControl = $ component ; }
Delegate to underlying component .
51,010
protected function createClass ( ) { $ cols = $ this -> numOfColumns ; if ( $ cols === self :: COLUMNS_NONE ) { return 'col' ; } elseif ( $ cols === self :: COLUMNS_AUTO ) { return 'col-auto' ; } else { if ( $ this -> row -> gridBreakPoint != NULL ) { return 'col-' . $ this -> row -> gridBreakPoint . '-' . $ this -> numOfColumns ; } else { return 'col-' . $ this -> numOfColumns ; } } }
Creates column class based on numOfColumns
51,011
public static function validate ( $ format , $ timeString ) { $ time = DateTime :: createFromFormat ( $ format , $ timeString ) ; return ( $ time !== FALSE ) && ( $ timeString === $ time -> format ( $ format ) ) ; }
Checks if give time string is indeed in the format specified . Some leading zeros check might be omitted .
51,012
public function addRow ( $ name = NULL ) { $ row = new BootstrapRow ( $ this , $ name ) ; $ this -> addComponent ( $ row , $ row -> name ) ; return $ row ; }
Adds a new Grid system row .
51,013
public function configureFromUserAgentString ( $ userAgentString , phpUserAgentStringParser $ userAgentStringParser = null ) { if ( null === $ userAgentStringParser ) { $ userAgentStringParser = new phpUserAgentStringParser ( ) ; } $ this -> setUserAgentString ( $ userAgentString ) ; $ this -> fromArray ( $ userAgentStringParser -> parse ( $ userAgentString ) ) ; }
Configure the user agent from a user agent string
51,014
public function fromArray ( array $ data ) { $ this -> setBrowserName ( $ data [ 'browser_name' ] ) ; $ this -> setBrowserVersion ( $ data [ 'browser_version' ] ) ; $ this -> setOperatingSystem ( $ data [ 'operating_system' ] ) ; $ this -> setEngine ( $ data [ 'engine' ] ) ; }
Configure the user agent from a data array
51,015
public function parse ( $ userAgentString = null ) { if ( ! $ userAgentString ) { $ userAgentString = isset ( $ _SERVER [ 'HTTP_USER_AGENT' ] ) ? $ _SERVER [ 'HTTP_USER_AGENT' ] : null ; } $ informations = $ this -> doParse ( $ userAgentString ) ; foreach ( $ this -> getFilters ( ) as $ filter ) { $ this -> $ filter ( $ informations ) ; } return $ informations ; }
Parse a user agent string .
51,016
protected function doParse ( $ userAgentString ) { $ userAgent = array ( 'string' => $ this -> cleanUserAgentString ( $ userAgentString ) , 'browser_name' => null , 'browser_version' => null , 'operating_system' => null , 'engine' => null ) ; if ( empty ( $ userAgent [ 'string' ] ) ) { return $ userAgent ; } $ pattern = '#(' . join ( '|' , $ this -> getKnownBrowsers ( ) ) . ')[/ ]+([0-9]+(?:\.[0-9]+)?)#' ; if ( preg_match_all ( $ pattern , $ userAgent [ 'string' ] , $ matches ) ) { $ i = count ( $ matches [ 1 ] ) - 1 ; if ( isset ( $ matches [ 1 ] [ $ i ] ) ) { $ userAgent [ 'browser_name' ] = $ matches [ 1 ] [ $ i ] ; } if ( isset ( $ matches [ 2 ] [ $ i ] ) ) { $ userAgent [ 'browser_version' ] = $ matches [ 2 ] [ $ i ] ; } } $ pattern = '#' . join ( '|' , $ this -> getKnownOperatingSystems ( ) ) . '#' ; if ( preg_match ( $ pattern , $ userAgent [ 'string' ] , $ match ) ) { if ( isset ( $ match [ 0 ] ) ) { $ userAgent [ 'operating_system' ] = $ match [ 0 ] ; } } $ pattern = '#' . join ( '|' , $ this -> getKnownEngines ( ) ) . '#' ; if ( preg_match ( $ pattern , $ userAgent [ 'string' ] , $ match ) ) { if ( isset ( $ match [ 0 ] ) ) { $ userAgent [ 'engine' ] = $ match [ 0 ] ; } } return $ userAgent ; }
Detect quickly informations from the user agent string
51,017
public function cleanUserAgentString ( $ userAgentString ) { $ userAgentString = trim ( strtolower ( $ userAgentString ) ) ; $ userAgentString = strtr ( $ userAgentString , $ this -> getKnownBrowserAliases ( ) ) ; $ userAgentString = strtr ( $ userAgentString , $ this -> getKnownOperatingSystemAliases ( ) ) ; $ userAgentString = strtr ( $ userAgentString , $ this -> getKnownEngineAliases ( ) ) ; return $ userAgentString ; }
Make user agent string lowercase and replace browser aliases
51,018
protected function filterAndroid ( array & $ userAgent ) { if ( 'safari' === $ userAgent [ 'browser_name' ] && strpos ( $ userAgent [ 'string' ] , 'android ' ) ) { $ userAgent [ 'browser_name' ] = 'android' ; $ userAgent [ 'operating_system' ] = 'android' ; $ userAgent [ 'browser_version' ] = preg_replace ( '|.+android ([0-9]+(?:\.[0-9]+)+).+|' , '$1' , $ userAgent [ 'string' ] ) ; } }
Android has a safari like signature
51,019
public function handle ( $ event ) { if ( config ( 'vanilo.cart.auto_assign_user' ) ) { if ( Cart :: getUser ( ) && Cart :: getUser ( ) -> id == $ event -> user -> id ) { return ; } Cart :: setUser ( $ event -> user ) ; } }
Assign a user to the cart
51,020
public function scopeOfCart ( $ query , $ cart ) { $ cartId = is_object ( $ cart ) ? $ cart -> id : $ cart ; return $ query -> where ( 'cart_id' , $ cartId ) ; }
Scope to query items of a cart
51,021
protected function createCart ( ) { if ( config ( 'vanilo.cart.auto_assign_user' ) && Auth :: check ( ) ) { $ attributes = [ 'user_id' => Auth :: user ( ) -> id ] ; } return $ this -> setCartModel ( CartProxy :: create ( $ attributes ?? [ ] ) ) ; }
Creates a new cart model and saves it s id in the session
51,022
private function getDefaultCartItemAttributes ( Buyable $ product , $ qty ) { return [ 'product_type' => $ product -> morphTypeName ( ) , 'product_id' => $ product -> getId ( ) , 'quantity' => $ qty , 'price' => $ product -> getPrice ( ) ] ; }
Returns the default attributes of a Buyable for a cart item
51,023
private function getExtraProductMergeAttributes ( Buyable $ product ) { $ result = [ ] ; $ cfg = config ( self :: EXTRA_PRODUCT_MERGE_ATTRIBUTES_CONFIG_KEY , [ ] ) ; if ( ! is_array ( $ cfg ) ) { throw new InvalidCartConfigurationException ( sprintf ( 'The value of `%s` configuration must be an array' , self :: EXTRA_PRODUCT_MERGE_ATTRIBUTES_CONFIG_KEY ) ) ; } foreach ( $ cfg as $ attribute ) { if ( ! is_string ( $ attribute ) ) { throw new InvalidCartConfigurationException ( sprintf ( 'The configuration `%s` can only contain an array of strings, `%s` given' , self :: EXTRA_PRODUCT_MERGE_ATTRIBUTES_CONFIG_KEY , gettype ( $ attribute ) ) ) ; } $ result [ $ attribute ] = $ product -> { $ attribute } ; } return $ result ; }
Returns the extra product merge attributes for cart_items based on the config
51,024
public function replaceClassName ( $ stub , $ tableName ) { return str_replace ( '{{class}}' , $ this -> options [ 'singular' ] ? str_singular ( studly_case ( $ tableName ) ) : studly_case ( $ tableName ) , $ stub ) ; }
replaces the class name in the stub .
51,025
public function replaceModuleInformation ( $ stub , $ modelInformation ) { $ stub = str_replace ( '{{table}}' , $ modelInformation [ 'table' ] , $ stub ) ; $ this -> fieldsHidden = '' ; $ this -> fieldsFillable = '' ; $ this -> fieldsCast = '' ; foreach ( $ modelInformation [ 'fillable' ] as $ field ) { if ( $ field != 'id' ) { $ this -> fieldsFillable .= ( strlen ( $ this -> fieldsFillable ) > 0 ? ', ' : '' ) . "'$field'" ; $ fieldsFiltered = $ this -> columns -> where ( 'field' , $ field ) ; if ( $ fieldsFiltered ) { switch ( strtolower ( $ fieldsFiltered -> first ( ) [ 'type' ] ) ) { case 'timestamp' : $ this -> fieldsDate .= ( strlen ( $ this -> fieldsDate ) > 0 ? ', ' : '' ) . "'$field'" ; break ; case 'datetime' : $ this -> fieldsDate .= ( strlen ( $ this -> fieldsDate ) > 0 ? ', ' : '' ) . "'$field'" ; break ; case 'date' : $ this -> fieldsDate .= ( strlen ( $ this -> fieldsDate ) > 0 ? ', ' : '' ) . "'$field'" ; break ; case 'tinyint(1)' : $ this -> fieldsCast .= ( strlen ( $ this -> fieldsCast ) > 0 ? ', ' : '' ) . "'$field' => 'boolean'" ; break ; } } } else { if ( $ field != 'id' && $ field != 'created_at' && $ field != 'updated_at' ) { $ this -> fieldsHidden .= ( strlen ( $ this -> fieldsHidden ) > 0 ? ', ' : '' ) . "'$field'" ; } } } $ stub = str_replace ( '{{fillable}}' , $ this -> fieldsFillable , $ stub ) ; $ stub = str_replace ( '{{hidden}}' , $ this -> fieldsHidden , $ stub ) ; $ stub = str_replace ( '{{casts}}' , $ this -> fieldsCast , $ stub ) ; $ stub = str_replace ( '{{dates}}' , $ this -> fieldsDate , $ stub ) ; $ stub = str_replace ( '{{modelnamespace}}' , $ this -> options [ 'namespace' ] , $ stub ) ; return $ stub ; }
replaces the module information .
51,026
public function getOptions ( ) { $ this -> options [ 'debug' ] = ( $ this -> option ( 'debug' ) ) ? true : false ; $ this -> options [ 'connection' ] = ( $ this -> option ( 'connection' ) ) ? $ this -> option ( 'connection' ) : '' ; $ this -> options [ 'folder' ] = ( $ this -> option ( 'folder' ) ) ? base_path ( $ this -> option ( 'folder' ) ) : app ( ) -> path ( ) ; $ this -> options [ 'folder' ] = rtrim ( $ this -> options [ 'folder' ] , '/' ) ; $ this -> options [ 'namespace' ] = ( $ this -> option ( 'namespace' ) ) ? str_replace ( 'app' , 'App' , $ this -> option ( 'namespace' ) ) : 'App' ; $ this -> options [ 'namespace' ] = rtrim ( $ this -> options [ 'namespace' ] , '/' ) ; $ this -> options [ 'namespace' ] = str_replace ( '/' , '\\' , $ this -> options [ 'namespace' ] ) ; $ this -> options [ 'all' ] = ( $ this -> option ( 'all' ) ) ? true : false ; $ this -> options [ 'table' ] = ( $ this -> option ( 'table' ) ) ? $ this -> option ( 'table' ) : '' ; $ this -> options [ 'singular' ] = ( $ this -> option ( 'singular' ) ) ? $ this -> option ( 'singular' ) : '' ; }
returns all the options that the user specified .
51,027
public function doComment ( $ text , $ overrideDebug = false ) { if ( $ this -> options [ 'debug' ] || $ overrideDebug ) { $ this -> comment ( $ text ) ; } }
will add a comment to the screen if debug is on or is over - ridden .
51,028
public function getAllTables ( ) { $ tables = [ ] ; if ( strlen ( $ this -> options [ 'connection' ] ) <= 0 ) { $ tables = collect ( DB :: select ( DB :: raw ( 'show tables' ) ) ) -> flatten ( ) ; } else { $ tables = collect ( DB :: connection ( $ this -> options [ 'connection' ] ) -> select ( DB :: raw ( 'show tables' ) ) ) -> flatten ( ) ; } $ tables = $ tables -> map ( function ( $ value , $ key ) { return collect ( $ value ) -> flatten ( ) [ 0 ] ; } ) -> reject ( function ( $ value , $ key ) { return $ value == 'migrations' ; } ) ; return $ tables ; }
will return an array of all table names .
51,029
protected function asDateTime ( $ value ) { if ( ! $ value instanceof Carbon ) { return Carbon :: instance ( $ value ) ; } return parent :: asDateTime ( $ value ) ; }
Ensure Timestamps are returned in DateTime .
51,030
public function from ( $ table ) { if ( $ table ) { $ this -> table = r \ table ( $ table ) ; $ this -> query -> table ( $ table ) ; } return parent :: from ( $ table ) ; }
Set the collection which the query is targeting .
51,031
public function compileOrders ( ) { if ( ! $ this -> orders ) { return ; } foreach ( $ this -> orders as $ order ) { $ column = $ order [ 'column' ] ; $ direction = $ order [ 'direction' ] ; $ compiled = strtolower ( $ direction ) == 'asc' ? r \ asc ( $ column ) : r \ desc ( $ column ) ; if ( $ order [ 'index' ] ) { $ compiled = [ 'index' => $ compiled ] ; } $ this -> query -> orderBy ( $ compiled ) ; } }
Compile orders into query .
51,032
protected function compileWheres ( ) { $ wheres = $ this -> wheres ; if ( ! $ wheres ) { return ; } $ this -> query -> filter ( function ( $ document ) use ( $ wheres ) { $ builder = new FilterBuilder ( $ document ) ; return $ builder -> compileWheres ( $ wheres ) ; } ) ; }
Compile the where array to filter chain .
51,033
public function push ( $ column , $ value = null , $ unique = false ) { $ operation = $ unique ? 'merge' : 'append' ; $ this -> compileWheres ( ) ; $ result = $ this -> query -> update ( [ $ column => r \ row ( $ column ) -> { $ operation } ( $ value ) , ] ) -> run ( ) ; return 0 == ( int ) $ result [ 'errors' ] ; }
Append one or more values to an array .
51,034
public function pull ( $ column , $ value = null ) { $ this -> compileWheres ( ) ; $ result = $ this -> query -> update ( [ $ column => r \ row ( $ column ) -> difference ( [ $ value ] ) , ] ) -> run ( ) ; return 0 == ( int ) $ result [ 'errors' ] ; }
Remove one or more values from an array .
51,035
public function drop ( $ columns ) { if ( ! is_array ( $ columns ) ) { $ columns = [ $ columns ] ; } $ this -> compileWheres ( ) ; $ result = $ this -> query -> replace ( function ( $ doc ) use ( $ columns ) { return $ doc -> without ( $ columns ) ; } ) -> run ( ) ; return 0 == ( int ) $ result [ 'errors' ] ; }
Remove one or more fields .
51,036
public function create ( ) { $ conn = $ this -> connection -> getConnection ( ) ; $ db = r \ db ( $ this -> connection -> getDatabaseName ( ) ) ; $ db -> tableCreate ( $ this -> table ) -> run ( $ conn ) ; }
Indicate that the table needs to be created .
51,037
public function drop ( ) { $ conn = $ this -> connection -> getConnection ( ) ; $ db = r \ db ( $ this -> connection -> getDatabaseName ( ) ) ; $ db -> tableDrop ( $ this -> table ) -> run ( $ conn ) ; }
Indicate that the collection should be dropped .
51,038
public function index ( $ columns , $ name = NULL , $ algorithm = NULL ) { $ conn = $ this -> connection -> getConnection ( ) ; $ db = r \ db ( $ this -> connection -> getDatabaseName ( ) ) ; $ db -> table ( $ this -> table ) -> indexCreate ( $ column ) -> run ( $ conn ) ; return $ this ; }
Specify an index for the collection .
51,039
public function reroute ( $ path ) { if ( strpos ( $ path , '://' ) === false ) { if ( substr ( $ path , 0 , 1 ) != '/' ) { $ path = '/' . $ path ; } $ path = $ this -> routeUrl ( $ path ) ; } header ( 'Location: ' . $ path ) ; $ this -> stop ( ) ; }
Redirect to path .
51,040
public function on ( $ event , $ callback , $ priority = 0 ) { if ( is_array ( $ event ) ) { foreach ( $ event as & $ evt ) { $ this -> on ( $ evt , $ callback , $ priority ) ; } return $ this ; } if ( ! isset ( $ this -> events [ $ event ] ) ) $ this -> events [ $ event ] = [ ] ; if ( is_object ( $ callback ) && $ callback instanceof \ Closure ) { $ callback = $ callback -> bindTo ( $ this , $ this ) ; } $ this -> events [ $ event ] [ ] = [ 'fn' => $ callback , 'prio' => $ priority ] ; return $ this ; }
Bind an event to closure
51,041
public function style ( $ href , $ version = false ) { $ list = [ ] ; foreach ( ( array ) $ href as $ style ) { $ type = 'text/css' ; $ rel = 'stylesheet' ; $ src = $ style ; if ( is_array ( $ style ) ) { extract ( $ style ) ; } $ ispath = strpos ( $ src , ':' ) !== false && ! preg_match ( '#^(|http\:|https\:)//#' , $ src ) ; $ list [ ] = '<link href="' . ( $ ispath ? $ this -> pathToUrl ( $ src ) : $ src ) . ( $ version ? "?ver={$version}" : "" ) . '" type="' . $ type . '" rel="' . $ rel . '">' ; } return implode ( "\n" , $ list ) ; }
Get style inc . markup
51,042
public function script ( $ src , $ version = false ) { $ list = [ ] ; foreach ( ( array ) $ src as $ script ) { $ type = 'text/javascript' ; $ src = $ script ; $ load = '' ; if ( is_array ( $ script ) ) { extract ( $ script ) ; } $ ispath = strpos ( $ src , ':' ) !== false && ! preg_match ( '#^(|http\:|https\:)//#' , $ src ) ; $ list [ ] = '<script src="' . ( $ ispath ? $ this -> pathToUrl ( $ src ) : $ src ) . ( $ version ? "?ver={$version}" : "" ) . '" type="' . $ type . '" ' . $ load . '></script>' ; } return implode ( "\n" , $ list ) ; }
Get script inc . markup
51,043
public function req_is ( $ type ) { switch ( strtolower ( $ type ) ) { case 'ajax' : return ( ( isset ( $ _SERVER [ 'HTTP_X_REQUESTED_WITH' ] ) && ( $ _SERVER [ 'HTTP_X_REQUESTED_WITH' ] == 'XMLHttpRequest' ) ) || ( isset ( $ _SERVER [ "CONTENT_TYPE" ] ) && stripos ( $ _SERVER [ "CONTENT_TYPE" ] , 'application/json' ) !== false ) || ( isset ( $ _SERVER [ "HTTP_CONTENT_TYPE" ] ) && stripos ( $ _SERVER [ "HTTP_CONTENT_TYPE" ] , 'application/json' ) !== false ) ) ; break ; case 'mobile' : $ mobileDevices = [ 'midp' , '240x320' , 'blackberry' , 'netfront' , 'nokia' , 'panasonic' , 'portalmmm' , 'sharp' , 'sie-' , 'sonyericsson' , 'symbian' , 'windows ce' , 'benq' , 'mda' , 'mot-' , 'opera mini' , 'philips' , 'pocket pc' , 'sagem' , 'samsung' , 'sda' , 'sgh-' , 'vodafone' , 'xda' , 'iphone' , 'ipod' , 'android' ] ; return preg_match ( '/(' . implode ( '|' , $ mobileDevices ) . ')/i' , strtolower ( $ _SERVER [ 'HTTP_USER_AGENT' ] ) ) ; break ; case 'post' : return ( strtolower ( $ _SERVER [ 'REQUEST_METHOD' ] ) == 'post' ) ; break ; case 'get' : return ( strtolower ( $ _SERVER [ 'REQUEST_METHOD' ] ) == 'get' ) ; break ; case 'put' : return ( strtolower ( $ _SERVER [ 'REQUEST_METHOD' ] ) == 'put' ) ; break ; case 'delete' : return ( strtolower ( $ _SERVER [ 'REQUEST_METHOD' ] ) == 'delete' ) ; break ; case 'ssl' : return ( ! empty ( $ _SERVER [ 'HTTPS' ] ) && $ _SERVER [ 'HTTPS' ] !== 'off' ) ; break ; } return false ; }
Request helper function
51,044
public function setGlobalFixedDelay ( $ delayMillis ) { $ url = $ this -> _makeUrl ( '__admin/settings' ) ; $ this -> _curl -> post ( $ url , array ( 'fixedDelay' => $ delayMillis ) ) ; }
Sets a delay on all stubbed responses
51,045
public function removeStub ( $ id ) { $ url = $ this -> _makeUrl ( '__admin/mappings/' . urlencode ( $ id ) ) ; $ this -> _curl -> delete ( $ url ) ; }
Deletes a particular stub identified by it s GUID from the server
51,046
public function generate ( ) { $ tex2png = $ this ; $ generate = function ( $ target ) use ( $ tex2png ) { $ tex2png -> actualFile = $ target ; try { $ tex2png -> createFile ( ) ; $ tex2png -> latexFile ( ) ; $ tex2png -> dvi2png ( ) ; } catch ( \ Exception $ e ) { $ tex2png -> error = $ e ; } $ tex2png -> clean ( ) ; } ; if ( $ this -> actualFile === null ) { $ target = $ this -> hash . '.png' ; $ this -> cache -> getOrCreate ( $ target , array ( ) , $ generate ) ; $ this -> file = $ this -> cache -> getCacheFile ( $ target ) ; $ this -> actualFile = $ this -> cache -> getCacheFile ( $ target , true ) ; } else { $ generate ( $ this -> actualFile ) ; } return $ this ; }
Generates the image
51,047
public function createFile ( ) { $ tmpfile = $ this -> tmpDir . '/' . $ this -> hash . '.tex' ; $ tex = '\documentclass[12pt]{article}' . "\n" ; $ tex .= '\usepackage[utf8]{inputenc}' . "\n" ; foreach ( $ this -> packages as $ package ) { $ tex .= '\usepackage{' . $ package . "}\n" ; } $ tex .= '\begin{document}' . "\n" ; $ tex .= '\pagestyle{empty}' . "\n" ; $ tex .= '\begin{displaymath}' . "\n" ; $ tex .= $ this -> formula . "\n" ; $ tex .= '\end{displaymath}' . "\n" ; $ tex .= '\end{document}' . "\n" ; if ( file_put_contents ( $ tmpfile , $ tex ) === false ) { throw new \ Exception ( 'Failed to open target file' ) ; } }
Create the LaTeX file
51,048
public function latexFile ( ) { $ command = 'cd ' . $ this -> tmpDir . '; ' . static :: LATEX . ' ' . $ this -> hash . '.tex < /dev/null |grep ^!|grep -v Emergency > ' . $ this -> tmpDir . '/' . $ this -> hash . '.err 2> /dev/null 2>&1' ; shell_exec ( $ command ) ; if ( ! file_exists ( $ this -> tmpDir . '/' . $ this -> hash . '.dvi' ) ) { throw new \ Exception ( 'Unable to compile LaTeX formula (is latex installed? check syntax)' ) ; } }
Compiles the LaTeX to DVI
51,049
public function dvi2png ( ) { $ command = static :: DVIPNG . ' -q -T tight -D ' . $ this -> density . ' -o ' . $ this -> actualFile . ' ' . $ this -> tmpDir . '/' . $ this -> hash . '.dvi 2>&1' ; if ( shell_exec ( $ command ) === null ) { throw new \ Exception ( 'Unable to convert the DVI file to PNG (is dvipng installed?)' ) ; } }
Converts the DVI file to PNG
51,050
public function types ( Request $ request , array $ types ) { foreach ( $ types as $ type ) { $ field = new $ type ( $ request ) ; $ this -> type ( $ field -> singularLabel ( ) , $ type :: $ model , $ field -> fields ( $ request ) ) ; } return $ this ; }
Register multiple fields for a Polymorphic relationship
51,051
public function resolveForDisplay ( $ model , $ attribute = null ) { try { parent :: resolveForDisplay ( $ model , $ this -> attribute . '_type' ) ; } catch ( \ Exception $ e ) { } foreach ( $ this -> meta [ 'types' ] as $ index => $ type ) { $ this -> meta [ 'types' ] [ $ index ] [ 'active' ] = $ this -> mapToKey ( $ type [ 'value' ] ) == $ model -> { $ this -> attribute . '_type' } ; foreach ( $ type [ 'fields' ] as $ field ) { try { $ field -> resolveForDisplay ( $ model -> { $ this -> attribute } ) ; } catch ( \ Exception $ e ) { } } } }
Extending the default method in order to add a try - catch statement . This has been PR d to the package but it has not yet been merged . Ideally we remove this overload when a fix has been implemented .
51,052
public function meta ( ) { return array_merge ( [ 'resourceName' => $ this -> resourceName , 'label' => forward_static_call ( [ $ this -> resourceClass , 'label' ] ) , 'singularLabel' => $ this -> singularLabel ?? $ this -> name ?? forward_static_call ( [ $ this -> resourceClass , 'singularLabel' ] ) , 'belongsToRelationship' => $ this -> belongsToRelationship , 'belongsToId' => $ this -> belongsToId , 'searchable' => $ this -> searchable , 'viewable' => $ this -> viewable , 'reverse' => false , ] , $ this -> meta ) ; }
A custom version of the standard response excluding the check for the reverse relationship as this is causing errors when including BelongsTo relationships in nested repeaters .
51,053
public function fields ( Request $ request ) { return array_merge ( [ Sortable :: make ( 'Sort' , 'id' ) , MorphTo :: make ( 'Repeatable' ) -> types ( array_wrap ( static :: getMorphToArray ( ) ) ) -> onlyOnDetail ( ) , Text :: make ( 'Name' ) , Polymorphic :: make ( 'Type' ) -> types ( $ request , $ this -> types ( $ request ) ) -> hideTypeWhenUpdating ( ) , $ this -> morphRepeaters ( $ request ) , ] , $ this -> extraInfo ( $ request ) ) ; }
Get the fields displayed by the resource .
51,054
public function types ( Request $ request ) { if ( ! $ resourceId = static :: getResourceId ( $ request ) ) { return [ ] ; } $ type = optional ( $ this -> model ( ) -> whereId ( $ resourceId ) -> first ( ) ) -> type ; if ( method_exists ( $ type , 'types' ) ) { return $ type :: types ( ) ; } ; if ( method_exists ( $ type , 'sourceTypes' ) ) { return $ type :: sourceTypes ( ) ; } ; return [ ] ; }
What type of repeater blocks should be made available to the resource .
51,055
public function morphRepeaters ( Request $ request ) { if ( ! $ this -> repeaterHasSubTypes ( $ request ) ) { return $ this -> merge ( [ ] ) ; } return $ this -> merge ( [ MorphMany :: make ( __ ( 'Repeaters' ) , 'repeaters' , Repeater :: class ) , ] ) ; }
Allow repeaters on this resource if available
51,056
protected function repeaterHasSubTypes ( Request $ request ) { if ( ! $ resourceId = $ this -> getResourceId ( $ request ) ) { return false ; } if ( ! $ model = $ this -> model ( ) -> whereId ( $ resourceId ) -> first ( ) ) { return false ; } return method_exists ( $ model -> type , 'types' ) ; }
Determine if the current repeater has sub - repeater types defined
51,057
protected function getResourceId ( Request $ request ) { if ( $ resourceId = $ request -> get ( 'viaResourceId' ) ) { return $ resourceId ; } ; parse_str ( parse_url ( $ request -> server -> get ( 'HTTP_REFERER' ) , PHP_URL_QUERY ) , $ params ) ; if ( $ resourceId = array_get ( $ params , 'viaResourceId' ) ) { return $ resourceId ; } ; if ( $ resourceId = $ request -> route ( 'resourceId' ) ) { return $ resourceId ; } ; return null ; }
Get the resource ID of the current repeater item
51,058
public static function containable ( ) { return collect ( config ( 'repeater-blocks.repeaters' ) ) -> filter ( function ( $ block ) { return in_array ( ResourceCanBeContainerised :: class , class_uses ( $ block ) ) ; } ) -> toArray ( ) ; }
Return the blocks which can be included in containers
51,059
public static function boot ( ) { parent :: boot ( ) ; static :: deleting ( function ( $ model ) { optional ( $ model -> type ) -> delete ( ) ; } ) ; static :: saved ( function ( $ model ) { optional ( $ model -> repeatable ) -> save ( ) ; } ) ; static :: deleted ( function ( $ model ) { optional ( $ model -> repeatable ) -> save ( ) ; } ) ; }
Hook into model boot events to ensure scout search indexes are updated
51,060
public function getLabelAttribute ( ) { if ( ! method_exists ( $ this -> type , 'resolveLabel' ) ) { return $ this -> title ; } return $ this -> type -> resolveLabel ( $ this ) ; }
Return the label to use when displaying this resource
51,061
public function setOptions ( $ options ) { if ( ! is_array ( $ options ) && ! $ options instanceof Traversable ) { throw new Exception \ InvalidArgumentException ( sprintf ( 'Parameter provided to %s must be an array or Traversable' , __METHOD__ ) ) ; } foreach ( $ options as $ key => $ value ) { $ setter = 'set' . str_replace ( ' ' , '' , ucwords ( str_replace ( '_' , ' ' , $ key ) ) ) ; if ( method_exists ( $ this , $ setter ) ) { $ this -> { $ setter } ( $ value ) ; } else { $ this -> setOption ( $ key , $ value ) ; } } return $ this ; }
Set many options at once
51,062
public function setOption ( $ option , $ value ) { $ option = strtolower ( $ option ) ; $ this -> options [ $ option ] = $ value ; return $ this ; }
Set an individual option
51,063
public function fromArray ( array $ params ) { foreach ( $ params as $ key => $ value ) { $ method = 'set' . ucfirst ( $ key ) ; if ( method_exists ( $ this , $ method ) ) { $ this -> $ method ( $ value ) ; } } $ this -> normalize ( ) ; return $ this ; }
Populate from native PHP array
51,064
public function fromString ( $ fileName ) { $ fileNameArray = $ fileName ? explode ( '.' , $ fileName ) : array ( ) ; if ( ! $ fileNameArray || count ( $ fileNameArray ) < 2 ) { throw new Exception \ InvalidArgumentException ( 'File name not correct' ) ; } $ fileExt = array_pop ( $ fileNameArray ) ; $ fileNameMain = implode ( '.' , $ fileNameArray ) ; $ fileNameArray = explode ( ',' , $ fileNameMain ) ; if ( ! $ fileExt || ! $ fileNameArray || ! $ fileNameArray [ 0 ] ) { throw new Exception \ InvalidArgumentException ( 'File name not correct' ) ; } $ fileNameArray = array_filter ( $ fileNameArray ) ; $ fileNameMain = array_shift ( $ fileNameArray ) ; $ this -> setExtension ( $ fileExt ) ; $ this -> setFilename ( $ fileNameMain ) ; $ args = $ fileNameArray ; $ argMapping = $ this -> argMapping ; $ params = array ( ) ; foreach ( $ args as $ arg ) { if ( ! $ arg ) { continue ; } if ( strlen ( $ arg ) < 3 || strpos ( $ arg , '_' ) !== 1 ) { continue ; } $ argKey = $ arg { 0 } ; if ( isset ( $ argMapping [ $ argKey ] ) ) { $ arg = substr ( $ arg , 2 ) ; if ( $ arg !== '' ) { $ params [ $ argMapping [ $ argKey ] ] = $ arg ; } } } $ this -> fromArray ( $ params ) ; return $ params ; }
Populate from filename string
51,065
public function toArray ( ) { return array ( 'filter' => $ this -> getFilter ( ) , 'width' => $ this -> getWidth ( ) , 'height' => $ this -> getHeight ( ) , 'percent' => $ this -> getPercent ( ) , 'dummy' => $ this -> getDummy ( ) , 'border' => $ this -> getBorder ( ) , 'layer' => $ this -> getLayer ( ) , 'quality' => $ this -> getQuality ( ) , 'crop' => $ this -> getCrop ( ) , 'x' => $ this -> getX ( ) , 'y' => $ this -> getY ( ) , 'rotate' => $ this -> getRotate ( ) , 'gravity' => $ this -> getGravity ( ) , 'extension' => $ this -> getExtension ( ) , 'filename' => $ this -> getFilename ( ) , ) ; }
Serialize to native PHP array
51,066
public function toString ( ) { $ params = $ this -> toArray ( ) ; $ filename = $ params [ 'filename' ] ; $ extension = $ params [ 'extension' ] ; unset ( $ params [ 'filename' ] , $ params [ 'extension' ] ) ; ksort ( $ params ) ; $ mapping = array_flip ( $ this -> argMapping ) ; $ defaults = $ this -> argDefaults ; $ nameArray = array ( ) ; foreach ( $ params as $ key => $ value ) { if ( $ value !== null && $ value !== $ defaults [ $ key ] ) { $ nameArray [ $ mapping [ $ key ] ] = $ mapping [ $ key ] . '_' . $ value ; } } $ nameArray = $ nameArray ? ',' . implode ( ',' , $ nameArray ) : '' ; return $ filename . $ nameArray . '.' . $ extension ; }
Serialize to query string
51,067
public function merge ( Config $ merge ) { foreach ( $ merge as $ key => $ value ) { if ( array_key_exists ( $ key , $ this -> data ) ) { if ( is_int ( $ key ) ) { $ this -> data [ ] = $ value ; } elseif ( $ value instanceof self && $ this -> data [ $ key ] instanceof self ) { $ this -> data [ $ key ] -> merge ( $ value ) ; } else { if ( $ value instanceof self ) { $ this -> data [ $ key ] = new static ( $ value -> toArray ( ) , $ this -> allowModifications ) ; } else { $ this -> data [ $ key ] = $ value ; } } } else { if ( $ value instanceof self ) { $ this -> data [ $ key ] = new static ( $ value -> toArray ( ) , $ this -> allowModifications ) ; } else { $ this -> data [ $ key ] = $ value ; } $ this -> count ++ ; } } return $ this ; }
Merge another Config with this one .
51,068
public function setReadOnly ( ) { $ this -> allowModifications = false ; foreach ( $ this -> data as $ value ) { if ( $ value instanceof self ) { $ value -> setReadOnly ( ) ; } } }
Prevent any more modifications being made to this instance .
51,069
protected function massAssign ( $ data = [ ] ) { if ( is_array ( $ data ) ) { if ( array_key_exists ( 'customer' , $ data ) ) { $ this -> setCustomer ( $ data [ 'customer' ] ) ; } if ( array_key_exists ( 'amount' , $ data ) ) { $ this -> setAmount ( $ data [ 'amount' ] ) ; } if ( array_key_exists ( 'description' , $ data ) ) { $ this -> setDescription ( $ data [ 'description' ] ) ; } if ( array_key_exists ( 'clientReference' , $ data ) ) { $ this -> setClientReference ( $ data [ 'clientReference' ] ) ; } if ( array_key_exists ( 'channel' , $ data ) ) { $ this -> setChannel ( $ data [ 'channel' ] ) ; } if ( preg_grep ( '/^callback/i' , array_keys ( $ data ) ) ) { $ this -> setCallback ( $ data ) ; } $ this -> assignOnReceiveMoneyInstance ( $ data ) ; $ this -> assignOnSendMoneyInstance ( $ data ) ; } return $ this ; }
This method is used to mass assign the properties required by the Hubtel ReceiveMoney and SendMoney Api
51,070
public static function make ( $ account = null , $ clientId = null , $ clientSecret = null ) { return new static ( $ account , $ clientId , $ clientSecret ) ; }
Create a new OVAC \ HubtelPayment instance .
51,071
protected function propertiesPassRequired ( ) { $ keys = array ( ) ; foreach ( $ this -> parametersRequired as $ key ) { if ( $ this -> accessPropertyByKey ( $ key ) ) { return true ; } $ keys [ 'currentKey' ] = $ key ; } throw new MissingParameterException ( 'The ' . $ keys [ 'currentKey' ] . ' parameter is required' ) ; }
This method checks that all properties marked as required have been assigned a value .
51,072
protected function accessPropertyByKey ( $ key ) { try { return $ this -> { 'get' . ucwords ( $ key ) } ( ) ; } catch ( BadMethodCallException $ e ) { throw new \ RuntimeException ( 'The ' . $ key . ' parameter must have a defined get' . ucwords ( $ key ) . ' method.' ) ; } }
This method calls the accessors for keys passed in and returns back the value it receives from the class instance
51,073
protected function pushHeaderMiddleware ( callable $ header ) { $ this -> stack -> push ( Middleware :: mapRequest ( $ header ) , 'hubtel-header-userAgent' ) ; return $ this -> stack ; }
Push the Header Middleware to the Handler Stack
51,074
protected function pushBasicAuthMiddleware ( callable $ header ) { $ this -> stack -> push ( Middleware :: mapRequest ( $ header ) , 'hubtel-header-basicAuth' ) ; return $ this -> stack ; }
Push the Header Middleware to the Handler Stack containing the bacic authentication in base64
51,075
protected function pushRetryMiddleware ( callable $ decider , callable $ delay = null ) { $ this -> stack -> push ( Middleware :: retry ( $ decider , $ delay ) , 'hubtel-retry-request' ) ; return $ this -> stack ; }
Pushes a Retry Middleware to the Guzzle Client Handler Stack .
51,076
public function callback ( $ primaryCallbackURL ) { if ( is_string ( $ primaryCallbackURL ) ) { $ this -> setPrimaryCallbackURL ( $ primaryCallbackURL ) -> setSecondaryCallbackURL ( $ primaryCallbackURL ) ; } return $ this ; }
This method sests a single callback for both the success and Error
51,077
public function setCallback ( $ data = [ ] ) { if ( is_array ( $ data ) ) { if ( array_key_exists ( 'callbackOnFail' , $ data ) ) { $ this -> setSecondaryCallbackURL ( $ data [ 'callbackOnFail' ] ) ; } if ( array_key_exists ( 'callbackOnSuccess' , $ data ) ) { $ this -> setPrimaryCallbackURL ( $ data [ 'callbackOnSuccess' ] ) ; } if ( array_key_exists ( 'error' , $ data ) ) { $ this -> setSecondaryCallbackURL ( $ data [ 'error' ] ) ; } if ( array_key_exists ( 'success' , $ data ) ) { $ this -> setPrimaryCallbackURL ( $ data [ 'success' ] ) ; } if ( array_key_exists ( 'callback' , $ data ) ) { $ this -> setCallback ( $ data [ 'callback' ] ) ; } } return $ this -> callback ( $ data ) ; }
This method sets the callbacks for the Hubtel Payments
51,078
public function execute ( $ query , $ rawData = false ) { if ( strlen ( $ query ) > self :: MAX_GET_SIZE ) { $ this -> method = 'POST' ; } $ client = new Client ( ) ; $ response = $ client -> request ( $ this -> method , self :: SPARQL_ENDPOINT , [ 'query' => [ "query" => $ query , "format" => "json" , "maxQueryTimeMillis" => $ this -> timeout * 1000 ] ] ) ; $ status = $ response -> getStatusCode ( ) ; if ( $ status != '200' ) { throw new Exception ( 'HTTP Error' ) ; } $ result = $ response -> getBody ( ) ; $ data = json_decode ( $ result , true ) ; if ( $ data === null || $ data === false ) { throw new Exception ( "HTTP request failed, response:\n" . substr ( $ result , 1024 ) ) ; } return $ this -> extractData ( $ data , $ rawData ) ; }
Query SPARQL endpoint
51,079
public function search ( $ query , $ lang = 'en' , $ limit = 10 ) { $ client = new Client ( ) ; $ response = $ client -> get ( self :: API_ENDPOINT , [ 'query' => [ 'action' => 'wbsearchentities' , 'format' => 'json' , 'strictlanguage' => true , 'language' => $ lang , 'uselang' => $ lang , 'search' => $ query , 'limit' => $ limit , 'props' => '' ] ] ) ; $ results = json_decode ( $ response -> getBody ( ) , true ) ; $ data = isset ( $ results [ 'search' ] ) ? $ results [ 'search' ] : [ ] ; $ collection = collect ( $ data ) ; $ output = $ collection -> map ( function ( $ item ) use ( $ lang ) { return new SearchResult ( $ item , $ lang , 'api' ) ; } ) ; return $ output ; }
Search entities by term
51,080
public function searchBy ( $ property , $ value = null , $ lang = 'en' , $ limit = 10 ) { if ( ! is_pid ( $ property ) ) { throw new Exception ( "First argument in searchBy() must be a valid Wikidata property ID (e.g.: P646)." , 1 ) ; } if ( ! $ value ) { throw new Exception ( "Second argument in searchBy() must be a string or a valid Wikidata entity ID (e.g.: Q646)." , 1 ) ; } $ subject = is_qid ( $ value ) ? 'wd:' . $ value : '"' . $ value . '"' ; $ query = ' SELECT ?item ?itemLabel ?itemAltLabel ?itemDescription WHERE { ?item wdt:' . $ property . ' ' . $ subject . '. SERVICE wikibase:label { bd:serviceParam wikibase:language "' . $ lang . '". } } LIMIT ' . $ limit . ' ' ; $ client = new SparqlClient ( ) ; $ data = $ client -> execute ( $ query ) ; $ collection = collect ( $ data ) ; $ output = $ collection -> map ( function ( $ item ) use ( $ lang ) { return new SearchResult ( $ item , $ lang , 'sparql' ) ; } ) ; return $ output ; }
Search entities by property ID and it value
51,081
public function get ( $ entityId , $ lang = 'en' ) { if ( ! is_qid ( $ entityId ) ) { throw new Exception ( "First argument in get() must by a valid Wikidata entity ID (e.g.: Q646)." , 1 ) ; } $ query = ' SELECT ?item ?itemLabel ?itemDescription ?itemAltLabel ?prop ?propLabel (GROUP_CONCAT(DISTINCT ?valueLabel;separator=", ") AS ?propValue) WHERE { BIND(wd:' . $ entityId . ' AS ?item). ?prop wikibase:directClaim ?p . ?item ?p ?value . SERVICE wikibase:label { bd:serviceParam wikibase:language "' . $ lang . '". ?value rdfs:label ?valueLabel . ?prop rdfs:label ?propLabel . ?item rdfs:label ?itemLabel . ?item skos:altLabel ?itemAltLabel . ?item schema:description ?itemDescription . } } group by ?item ?itemLabel ?itemDescription ?itemAltLabel ?prop ?propLabel ' ; $ client = new SparqlClient ( ) ; $ data = $ client -> execute ( $ query ) ; if ( ! $ data ) { return null ; } $ entity = new Entity ( $ data , $ lang ) ; return $ entity ; }
Get entity by ID
51,082
protected function prepareData ( RequestInterface $ request , User $ user ) { $ userId = $ user -> getIdentifier ( ) ; if ( $ userId === null ) { $ userId = get_class ( $ user ) ; } return [ RequestLogService :: USER_ID => $ userId , RequestLogService :: USER_ROLES => ',' . implode ( ',' , $ user -> getRoles ( ) ) . ',' , RequestLogService :: ACTION => $ request -> getUri ( ) -> getPath ( ) , RequestLogService :: EVENT_TIME => microtime ( true ) , RequestLogService :: DETAILS => json_encode ( [ 'method' => $ request -> getMethod ( ) , 'query' => $ request -> getUri ( ) -> getQuery ( ) , ] ) , ] ; }
Prepare data to log
51,083
public static function install ( $ persistence ) { $ schemaManager = $ persistence -> getDriver ( ) -> getSchemaManager ( ) ; $ schema = $ schemaManager -> createSchema ( ) ; $ fromSchema = clone $ schema ; try { $ table = $ schema -> createTable ( self :: TABLE_NAME ) ; $ table -> addOption ( 'engine' , 'InnoDB' ) ; $ table -> addColumn ( static :: COLUMN_USER_ID , "string" , [ "length" => 255 ] ) ; $ table -> addColumn ( static :: COLUMN_USER_ROLES , "string" , [ "notnull" => true , "length" => 4096 ] ) ; $ table -> addColumn ( static :: COLUMN_ACTION , "string" , [ "notnull" => false , "length" => 4096 ] ) ; $ table -> addColumn ( static :: COLUMN_EVENT_TIME , 'decimal' , [ 'precision' => 14 , 'scale' => 4 , "notnull" => true ] ) ; $ table -> addColumn ( static :: COLUMN_DETAILS , "text" , [ "notnull" => false ] ) ; $ table -> addIndex ( [ static :: COLUMN_USER_ID ] , 'IDX_' . static :: TABLE_NAME . '_' . static :: COLUMN_USER_ID ) ; $ table -> addIndex ( [ static :: COLUMN_EVENT_TIME ] , 'IDX_' . static :: TABLE_NAME . '_' . static :: COLUMN_EVENT_TIME ) ; } catch ( SchemaException $ e ) { \ common_Logger :: i ( 'Database Schema already up to date.' ) ; } $ queries = $ persistence -> getPlatform ( ) -> getMigrateSchemaSql ( $ fromSchema , $ schema ) ; foreach ( $ queries as $ query ) { $ persistence -> exec ( $ query ) ; } return new \ common_report_Report ( \ common_report_Report :: TYPE_SUCCESS , __ ( 'User activity log successfully registered.' ) ) ; }
Initialize log storage
51,084
public function export ( ) { $ delimiter = $ this -> getParameter ( 'field_delimiter' , ',' ) ; $ enclosure = $ this -> getParameter ( 'field_encloser' , '"' ) ; $ sortBy = $ this -> getParameter ( 'sortby' , '' ) ; $ sortOrder = $ this -> getParameter ( 'sortorder' , '' ) ; $ exportParameters = [ ] ; if ( $ this -> hasRequestParameter ( 'filtercolumns' ) ) { $ parameters = $ this -> getRequestParameter ( 'filtercolumns' ) ; if ( is_array ( $ parameters ) ) { $ exportParameters = $ parameters ; } } $ csvExporter = new LogEntryCsvStdOutExporter ( new LogEntryRepository ( $ exportParameters , $ sortBy , $ sortOrder ) , $ delimiter , $ enclosure ) ; setcookie ( 'fileDownload' , 'true' , 0 , '/' ) ; $ csvExporter -> export ( ) ; }
Export log entries from database to csv file dates should be in UTC
51,085
public function getSocket ( ) { if ( is_null ( $ this -> resource ) ) { $ socket = socket_create ( AF_INET , SOCK_STREAM , SOL_TCP ) ; if ( $ socket === false ) { throw new RequestLogException ( 'Unable to open TCP socket: ' . socket_strerror ( socket_last_error ( ) ) ) ; } $ success = socket_connect ( $ socket , $ this -> getOption ( self :: OPTION_HOST ) , $ this -> getOption ( self :: OPTION_PORT ) ) ; if ( $ success === false ) { throw new RequestLogException ( 'Unable to connect to host: ' . socket_strerror ( socket_last_error ( ) ) ) ; } $ this -> resource = $ socket ; } return $ this -> resource ; }
Connect to the server and return the open socket
51,086
public function table ( $ name , callable $ callback ) { $ blueprint = new Blueprint ( $ name , $ callback ) ; $ this -> blueprints [ $ name ] = $ blueprint -> build ( ) ; }
Describe a table with a given callback .
51,087
protected function applyBlueprint ( Blueprint $ blueprint ) { foreach ( $ blueprint -> columns as $ column ) { $ this -> updateColumn ( $ blueprint -> table , $ blueprint -> primary , $ column ) ; } }
Apply blueprint to the database .
51,088
protected function updateColumn ( $ table , $ primary , $ column ) { $ columns = $ this -> mergeColumns ( $ primary , $ column [ 'name' ] ) ; $ where = $ column [ 'where' ] ; foreach ( $ this -> database -> getRows ( $ table , $ columns , $ where ) as $ rowNum => $ row ) { $ this -> database -> updateByPrimary ( $ table , Helpers :: arrayOnly ( $ row , $ primary ) , $ column [ 'name' ] , $ this -> calculateNewValue ( $ column [ 'replace' ] , $ rowNum ) ) ; } }
Update all needed values of a give column .
51,089
protected function calculateNewValue ( $ replace , $ rowNum ) { $ value = $ this -> handlePossibleClosure ( $ replace ) ; return $ this -> replacePlaceholders ( $ value , $ rowNum ) ; }
Calculate new value for each row .
51,090
protected function buildWhereForArray ( $ primaryKeyValue ) { $ where = [ ] ; foreach ( $ primaryKeyValue as $ key => $ value ) { $ where [ ] = "{$key}='{$value}'" ; } return implode ( ' AND ' , $ where ) ; }
Build SQL where for key - value array .
51,091
public function build ( ) { $ callback = $ this -> callback ; $ callback ( $ this ) ; if ( is_null ( $ this -> primary ) ) { $ this -> primary = self :: $ defaultPrimary ; } return $ this ; }
Build the current blueprint .
51,092
public function getBlogPostImageSrc ( $ blogPost , $ size ) { $ thumbsPath = $ this -> getBlogPostThumbsPath ( ) ; $ urlPrefix = Configure :: read ( 'app.uploadedImagesDir' ) . DS . 'blog_posts' . DS ; $ imageFilename = $ blogPost -> id_blog_post . '-' . $ size . '-default.jpg' ; if ( ! file_exists ( $ thumbsPath . DS . $ imageFilename ) ) { $ manufacturerSize = "medium" ; if ( $ size == "single" ) { $ manufacturerSize = "large" ; } $ imageFilenameAndPath = $ urlPrefix . 'no-' . $ size . '-default.jpg' ; if ( $ blogPost -> id_manufacturer != 0 ) { $ imageFilenameAndPath = $ this -> getManufacturerImageSrc ( $ blogPost -> id_manufacturer , $ manufacturerSize ) ; } } else { $ imageFilenameAndPath = $ urlPrefix . $ imageFilename ; } return $ this -> prepareAsUrl ( $ imageFilenameAndPath ) ; }
Returns a blogpost s image with desired size If the blogpost has no image but a manufacturer was specified the manufacturer s image will be returned
51,093
private function generateTermsOfUsePdf ( $ customer ) { $ this -> set ( 'customer' , $ customer ) ; $ this -> set ( 'saveParam' , 'I' ) ; $ this -> RequestHandler -> renderAs ( $ this , 'pdf' ) ; return $ this -> render ( 'generateTermsOfUsePdf' ) ; }
generates pdf on - the - fly
51,094
public function initialize ( array $ config ) { $ this -> setTable ( $ this -> tablePrefix . $ this -> getTable ( ) ) ; if ( isset ( $ _SERVER [ 'HTTP_X_UNIT_TEST_MODE' ] ) || ( php_sapi_name ( ) == 'cli' && $ _SERVER [ 'argv' ] [ 0 ] && preg_match ( '/phpunit/' , $ _SERVER [ 'argv' ] [ 0 ] ) ) ) { $ this -> setConnection ( ConnectionManager :: get ( 'test' ) ) ; } parent :: initialize ( $ config ) ; }
legacy from CakePHP2
51,095
public function legacyUpdateOrderStateToNewBilledState ( $ dateFrom , $ statusOld , $ statusNew ) { $ conditions = [ 'order_state' => $ statusOld ] ; if ( ! is_null ( $ dateFrom ) ) { $ conditions [ ] = 'DATE_FORMAT(created, \'%Y-%m-%d\') < \'' . Configure :: read ( 'app.timeHelper' ) -> formatToDbFormatDate ( $ dateFrom ) . '\'' ; } $ rows = $ this -> updateAll ( [ 'order_state' => $ statusNew ] , $ conditions ) ; return $ rows ; }
can be removed safely in FCS v3 . 0
51,096
public function beforeRender ( Event $ event ) { parent :: beforeRender ( $ event ) ; if ( $ this -> getResponse ( ) -> getType ( ) != 'text/html' ) { return ; } $ this -> resetOriginalLoggedCustomer ( ) ; $ categoriesForMenu = [ ] ; if ( Configure :: read ( 'appDb.FCS_SHOW_PRODUCTS_FOR_GUESTS' ) || $ this -> AppAuth -> user ( ) ) { $ this -> Category = TableRegistry :: getTableLocator ( ) -> get ( 'Categories' ) ; $ allProductsCount = $ this -> Category -> getProductsByCategoryId ( Configure :: read ( 'app.categoryAllProducts' ) , false , '' , 0 , true ) ; $ newProductsCount = $ this -> Category -> getProductsByCategoryId ( Configure :: read ( 'app.categoryAllProducts' ) , true , '' , 0 , true ) ; $ categoriesForMenu = $ this -> Category -> getForMenu ( ) ; array_unshift ( $ categoriesForMenu , [ 'slug' => Configure :: read ( 'app.slugHelper' ) -> getNewProducts ( ) , 'name' => __ ( 'New_products' ) . ' <span class="additional-info"> (' . $ newProductsCount . ')</span>' , 'options' => [ 'fa-icon' => 'fa-star' . ( $ newProductsCount > 0 ? ' gold' : '' ) ] ] ) ; array_unshift ( $ categoriesForMenu , [ 'slug' => Configure :: read ( 'app.slugHelper' ) -> getAllProducts ( ) , 'name' => __ ( 'All_products' ) . ' <span class="additional-info"> (' . $ allProductsCount . ')</span>' , 'options' => [ 'fa-icon' => 'fa-tags' ] ] ) ; } $ this -> set ( 'categoriesForMenu' , $ categoriesForMenu ) ; $ this -> Manufacturer = TableRegistry :: getTableLocator ( ) -> get ( 'Manufacturers' ) ; $ manufacturersForMenu = $ this -> Manufacturer -> getForMenu ( $ this -> AppAuth ) ; $ this -> set ( 'manufacturersForMenu' , $ manufacturersForMenu ) ; $ this -> Page = TableRegistry :: getTableLocator ( ) -> get ( 'Pages' ) ; $ conditions = [ ] ; $ conditions [ 'Pages.active' ] = APP_ON ; $ conditions [ ] = 'Pages.position > 0' ; if ( ! $ this -> AppAuth -> user ( ) ) { $ conditions [ 'Pages.is_private' ] = APP_OFF ; } $ pages = $ this -> Page -> getThreaded ( $ conditions ) ; $ pagesForHeader = [ ] ; $ pagesForFooter = [ ] ; foreach ( $ pages as $ page ) { if ( $ page -> menu_type == 'header' ) { $ pagesForHeader [ ] = $ page ; } if ( $ page -> menu_type == 'footer' ) { $ pagesForFooter [ ] = $ page ; } } $ this -> set ( 'pagesForHeader' , $ pagesForHeader ) ; $ this -> set ( 'pagesForFooter' , $ pagesForFooter ) ; }
is not called on ajax actions!
51,097
public function getProductsByCategoryId ( $ categoryId , $ filterByNewProducts = false , $ keyword = '' , $ productId = 0 , $ countMode = false ) { $ params = [ 'active' => APP_ON ] ; if ( ! $ this -> getLoggedUser ( ) ) { $ params [ 'isPrivate' ] = APP_OFF ; } $ sql = 'SELECT ' ; $ sql .= $ this -> getFieldsForProductListQuery ( ) ; $ sql .= "FROM " . $ this -> tablePrefix . "product Products " ; if ( ! $ filterByNewProducts ) { $ sql .= "LEFT JOIN " . $ this -> tablePrefix . "category_product CategoryProducts ON CategoryProducts.id_product = Products.id_product LEFT JOIN " . $ this -> tablePrefix . "category Categories ON CategoryProducts.id_category = Categories.id_category " ; } $ sql .= $ this -> getJoinsForProductListQuery ( ) ; $ sql .= $ this -> getConditionsForProductListQuery ( ) ; if ( ! $ filterByNewProducts ) { $ params [ 'categoryId' ] = $ categoryId ; $ sql .= " AND CategoryProducts.id_category = :categoryId " ; $ sql .= " AND Categories.active = :active" ; } if ( $ filterByNewProducts ) { $ params [ 'dateAdd' ] = date ( 'Y-m-d' , strtotime ( '-' . Configure :: read ( 'appDb.FCS_DAYS_SHOW_PRODUCT_AS_NEW' ) . ' DAYS' ) ) ; $ sql .= " AND DATE_FORMAT(Products.created, '%Y-%m-%d') > :dateAdd" ; } if ( $ keyword != '' ) { $ params [ 'keyword' ] = '%' . $ keyword . '%' ; $ sql .= " AND (Products.name LIKE :keyword OR Products.description_short LIKE :keyword) " ; } if ( $ productId > 0 ) { $ params [ 'productId' ] = $ productId ; $ sql .= " AND Products.id_product = :productId " ; } $ sql .= $ this -> getOrdersForProductListQuery ( ) ; $ statement = $ this -> getConnection ( ) -> prepare ( $ sql ) ; $ statement -> execute ( $ params ) ; $ products = $ statement -> fetchAll ( 'assoc' ) ; $ products = $ this -> hideProductsWithActivatedDeliveryRhythmOrDeliveryBreak ( $ products ) ; if ( ! $ countMode ) { return $ products ; } else { return count ( $ products ) ; } return $ products ; }
custom sql for best performance product attributes ARE NOT fetched in this query!
51,098
public function getOrderPeriodFirstDay ( $ day ) { $ currentWeekday = $ this -> formatAsWeekday ( $ day ) ; $ dateDiff = 7 - $ this -> getSendOrderListsWeekday ( ) + $ currentWeekday ; $ date = strtotime ( '-' . $ dateDiff . ' day ' , $ day ) ; if ( $ currentWeekday > $ this -> getDeliveryWeekday ( ) ) { $ date = strtotime ( '+7 day' , $ date ) ; } $ date = date ( $ this -> getI18Format ( 'DateShortAlt' ) , $ date ) ; return $ date ; }
see tests for implementations
51,099
public function formatToDateShort ( $ dbString ) { $ timestamp = strtotime ( $ dbString ) ; if ( $ dbString == '' ) { return '' ; } return date ( $ this -> getI18Format ( 'DateShortAlt' ) , $ timestamp ) ; }
formats a timestamp to a short date