idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
1,500
public function setProperty ( $ name , $ value ) { if ( strstr ( $ name , '.' ) ) { $ this -> setPropertyByPath ( $ name , $ value ) ; return true ; } if ( $ this -> isArray ( ) ) { $ this -> object [ $ name ] = $ value ; } else { $ this -> object -> $ name = $ value ; } return true ; }
Set Property .
1,501
protected function setPropertyByPath ( $ path , $ value ) { $ path = explode ( '.' , $ path ) ; $ root = $ path [ 0 ] ; unset ( $ path [ 0 ] ) ; $ array = ( $ this -> hasProperty ( $ root ) ? $ this -> getProperty ( $ root ) : [ ] ) ; $ pointer = & $ array ; foreach ( $ path as $ part ) { if ( ! isset ( $ pointer [ $ part ] ) ) { $ pointer [ $ part ] = [ ] ; } if ( ! is_array ( $ pointer [ $ part ] ) ) { $ pointer [ $ part ] = [ ] ; } $ pointer = & $ pointer [ $ part ] ; } $ pointer = $ value ; unset ( $ pointer ) ; $ this -> setProperty ( $ root , $ array ) ; }
Set a property by looping through .
1,502
public function unsetProperty ( $ name ) { if ( ! $ this -> hasProperty ( $ name ) ) { return false ; } if ( strstr ( $ name , '.' ) ) { try { $ path = explode ( '.' , $ name ) ; $ root = $ path [ 0 ] ; unset ( $ path [ 0 ] ) ; $ array = ( $ this -> hasProperty ( $ root ) ? $ this -> getProperty ( $ root ) : [ ] ) ; $ arrayPath = '["' . implode ( '"]["' , $ path ) . '"]' ; eval ( 'unset($array' . $ arrayPath . ');' ) ; $ this -> setProperty ( $ root , $ array ) ; } catch ( Exception $ e ) { return false ; } return true ; } if ( $ this -> isArray ( ) ) { unset ( $ this -> object [ $ name ] ) ; } else { unset ( $ this -> object -> $ name ) ; } return true ; }
Unset Property .
1,503
public function resolveArrayPath ( $ path ) { $ path = explode ( '.' , $ this -> escape ( $ path ) ) ; $ root = $ path [ 0 ] ; unset ( $ path [ 0 ] ) ; $ arrayPath = '["' . implode ( '"]["' , $ path ) . '"]' ; $ arrayBracket = '->' ; $ arrayBracketEnd = '' ; if ( $ this -> isArray ( ) ) { $ arrayBracket = '["' ; $ arrayBracketEnd = '"]' ; } return '$this->object' . $ arrayBracket . $ root . $ arrayBracketEnd . $ arrayPath ; }
Resolve punctuation format and return path .
1,504
public function loopThrough ( Closure $ callable ) { $ reference = $ this -> getReference ( ) ; if ( is_null ( $ reference ) ) { $ reference = $ this -> object ; } $ this -> loop ( $ reference , $ callable ) ; }
Loop through the stored data .
1,505
protected function loop ( $ data , Closure $ callable ) { if ( ! is_array ( $ data ) && ! is_object ( $ data ) ) { return ; } foreach ( $ data as $ key => $ value ) { call_user_func_array ( $ callable , [ $ key , $ value ] ) ; } }
Loop through the given data and call the given function .
1,506
protected function unsetNullRecursively ( $ data , $ reference = null ) { if ( is_null ( $ reference ) ) { $ reference = $ data ; } $ this -> loop ( $ reference , function ( $ key , $ value ) use ( & $ data ) { if ( is_array ( $ data ) ) { if ( is_null ( $ value ) ) { unset ( $ data [ $ key ] ) ; } else { $ data [ $ key ] = $ this -> unsetNullRecursively ( $ value ) ; } } if ( is_object ( $ data ) ) { if ( is_null ( $ value ) ) { unset ( $ data -> $ key ) ; } else { $ data -> $ key = $ this -> unsetNullRecursively ( $ value ) ; } } } ) ; return $ data ; }
Unset null properties and keys of the given data .
1,507
public function prepareWizardData ( ) { $ cacheKey = 'property-wizard' . md5 ( implode ( ':' , $ this -> handlersList ) ) ; $ data = Yii :: $ app -> cache -> get ( $ cacheKey ) ; if ( false === $ data ) { $ query = ( new Query ( ) ) -> from ( PropertyHandlers :: tableName ( ) ) -> indexBy ( 'id' ) -> select ( 'class_name' ) ; if ( ( count ( $ this -> handlersList ) != 0 ) ) { $ query -> where ( [ 'class_name' => $ this -> handlersList ] ) ; } $ handlers = $ query -> column ( ) ; $ storageToId = ( new Query ( ) ) -> from ( PropertyStorage :: tableName ( ) ) -> indexBy ( 'id' ) -> select ( 'class_name' ) -> column ( ) ; foreach ( $ handlers as $ id => $ className ) { $ data [ $ id ] = [ 'id' => $ id , 'allowedTypes' => $ className :: $ allowedTypes , 'allowedStorage' => array_keys ( array_intersect ( $ storageToId , $ className :: $ allowedStorage ) ) , 'allowInSearch' => ( bool ) $ className :: $ allowInSearch , 'multipleMode' => $ className :: $ multipleMode ] ; } Yii :: $ app -> cache -> set ( $ cacheKey , $ data , 86400 , new TagDependency ( [ 'tags' => [ NamingHelper :: getCommonTag ( PropertyHandlers :: class ) , NamingHelper :: getCommonTag ( PropertyStorage :: class ) ] ] ) ) ; } return $ data ; }
Prepares json string to use in js property creation wizard
1,508
public function handle ( ) { if ( ! $ this -> confirm ( 'Set up DB creds now? [y|N]' ) ) { return ; } $ connected = false ; while ( ! $ connected ) { $ host = $ this -> askDatabaseHost ( ) ; $ name = $ this -> askDatabaseName ( ) ; $ user = $ this -> askDatabaseUsername ( ) ; $ password = $ this -> askDatabasePassword ( ) ; $ this -> setLaravelConfiguration ( $ name , $ user , $ password , $ host ) ; if ( $ this -> databaseConnectionIsValid ( ) ) { $ connected = true ; } else { $ this -> error ( "Please ensure your database credentials are valid." ) ; } } $ this -> env -> write ( $ name , $ user , $ password , $ host ) ; $ this -> info ( 'Database successfully configured' ) ; }
Handle the Command
1,509
public function stats ( ) { return new Query \ Stats ( $ this -> mongo , $ this -> entity , $ this -> ref , $ this -> dateRange ) ; }
Query daily or monthly statistics .
1,510
public function dimension ( $ name = null , $ value = null ) { $ query = new Query \ Dimensions ( $ this -> mongo , $ this -> entity , $ this -> ref , $ this -> dateRange ) ; if ( ! empty ( $ name ) ) { if ( ! empty ( $ value ) ) { $ query -> setDimension ( $ name , $ value ) ; } else { $ query -> setDimension ( $ name ) ; } } return $ query ; }
Query the dimensions .
1,511
public function discard ( $ discard = null ) { if ( func_num_args ( ) === 0 ) { return $ this -> _data [ 'discard' ] ; } return $ this -> _data [ 'discard' ] = ( boolean ) $ discard ; }
Set whether or not this is a session cookie .
1,512
public function matches ( $ url ) { $ infos = parse_url ( $ url ) ; if ( $ this -> expired ( ) ) { return false ; } if ( ! $ this -> matchesScheme ( $ infos [ 'scheme' ] ) ) { return false ; } if ( ! $ this -> matchesDomain ( $ infos [ 'host' ] ) ) { return false ; } return $ this -> matchesPath ( $ infos [ 'path' ] ) ; }
Checks if a scheme domain and path match the Cookie ones .
1,513
public function matchesPath ( $ path ) { if ( $ this -> _data [ 'path' ] === '/' || $ this -> _data [ 'path' ] === $ path ) { return true ; } if ( strpos ( $ path , $ this -> _data [ 'path' ] ) !== 0 ) { return false ; } if ( substr ( $ this -> _data [ 'path' ] , - 1 , 1 ) === '/' ) { return true ; } return substr ( $ path , strlen ( $ this -> _data [ 'path' ] ) , 1 ) === '/' ; }
Checks if a path match the Cookie path .
1,514
public function matchesScheme ( $ scheme ) { $ scheme = strtolower ( $ scheme ) ; $ secure = $ this -> _data [ 'secure' ] ; return ( $ secure && $ scheme === 'https' ) || ( ! $ secure && $ scheme === 'http' ) ; }
Checks if a domain match the Cookie scheme .
1,515
public function expired ( $ onSessionExpires = false ) { if ( ! $ this -> _data [ 'expires' ] && $ onSessionExpires ) { return true ; } return $ this -> _data [ 'expires' ] < time ( ) && $ this -> _data [ 'expires' ] ; }
Checks if the Cookie expired .
1,516
public function toString ( ) { $ parts = [ ] ; $ data = $ this -> data ( ) ; $ parts [ ] = $ data [ 'name' ] . '=' . rawurlencode ( $ data [ 'value' ] ) ; if ( $ data [ 'domain' ] ) { $ parts [ ] = 'Domain=' . $ data [ 'domain' ] ; } if ( $ data [ 'path' ] ) { $ parts [ ] = 'Path=' . $ data [ 'path' ] ; } if ( isset ( $ data [ 'max-age' ] ) ) { $ parts [ ] = 'Max-Age=' . ( string ) $ data [ 'max-age' ] ; } elseif ( isset ( $ data [ 'expires' ] ) ) { $ parts [ ] = 'Expires=' . gmdate ( 'D, d M Y H:i:s \G\M\T' , $ data [ 'expires' ] ) ; } if ( $ data [ 'secure' ] ) { $ parts [ ] = 'Secure' ; } if ( $ data [ 'httponly' ] ) { $ parts [ ] = 'HttpOnly' ; } return join ( '; ' , $ parts ) ; }
Return a Set - Cookie string representation of a Cookie .
1,517
public static function fromString ( $ value ) { $ parts = array_filter ( array_map ( 'trim' , explode ( ';' , $ value ) ) ) ; if ( empty ( $ parts ) || ! strpos ( $ parts [ 0 ] , '=' ) ) { return [ ] ; } $ config = [ ] ; $ pieces = explode ( '=' , array_shift ( $ parts ) , 2 ) ; if ( count ( $ pieces ) !== 2 ) { return [ ] ; } $ config [ 'name' ] = trim ( $ pieces [ 0 ] ) ; $ config [ 'value' ] = urldecode ( trim ( $ pieces [ 1 ] , " \n\r\t\0\x0B" ) ) ; foreach ( $ parts as $ item ) { $ pieces = explode ( '=' , trim ( $ item ) , 2 ) ; $ pieces [ 0 ] = strtolower ( $ pieces [ 0 ] ) ; if ( count ( $ pieces ) !== 2 ) { $ config [ $ pieces [ 0 ] ] = true ; } else { $ config [ $ pieces [ 0 ] ] = $ pieces [ 1 ] ; } } return new static ( $ config ) ; }
Create a new Cookie object from a Set - Cookie header value
1,518
public static function isValidTimeStamp ( $ timestamp ) { return ( ( string ) ( integer ) $ timestamp === ( string ) $ timestamp ) && $ timestamp <= PHP_INT_MAX && $ timestamp >= ~ PHP_INT_MAX ; }
Checks if a timestamp is valid .
1,519
public static function invalidValue ( $ type , $ value ) { if ( is_object ( $ value ) ) { $ value = get_class ( $ value ) ; } elseif ( is_bool ( $ value ) || is_null ( $ value ) ) { $ value = var_export ( $ value , true ) ; } return new self ( sprintf ( 'The type "%s" does not have a name for the value "%s".' , $ type , $ value ) ) ; }
Creates a new exception for a value that is not valid for a type
1,520
protected function showMessage ( $ message , $ in_mode = self :: ALL , $ params = NULL ) { if ( isset ( $ params ) && is_array ( $ params ) ) { $ color_codes = '' ; $ tabs = '' ; foreach ( $ params as $ key => $ value ) { switch ( $ key ) { case 'foreground' : { $ color_codes .= "\033[" . $ this -> _foreground_colors [ $ value ] . "m" ; } break ; case 'background' : { $ color_codes .= "\033[" . $ this -> _background_colors [ $ value ] . "m" ; } break ; case 'indent' : { for ( $ i = 0 ; $ i < $ value ; $ i ++ ) { $ tabs = "\t" . $ tabs ; } } break ; } } $ message = $ color_codes . "[" . $ in_mode . "] " . $ tabs . $ message . "\033[0m" ; } else { $ message = "[" . $ in_mode . "] " . $ message ; } switch ( $ in_mode ) { case self :: TEST : if ( $ this -> test ) { $ this -> addToOutput ( $ message ) ; echo $ message . PHP_EOL ; } break ; case self :: VERBOSE : $ this -> addToOutput ( $ message ) ; if ( $ this -> _verbose ) { echo $ message . PHP_EOL ; } break ; case self :: ALL : $ this -> addToOutput ( $ message ) ; echo $ message . PHP_EOL ; break ; default : throw new \ OutOfBoundsException ( 'Undefined in_mode selected.' ) ; } }
Print a message on the console .
1,521
protected function setNewParam ( $ short_param_name , $ long_param_name , $ help_string , $ need_second_param , $ is_required ) { foreach ( $ this -> _shell_common_params as $ param ) { if ( ( $ short_param_name == $ param [ 'short_param_name' ] ) || ( $ long_param_name == $ param [ 'long_param_name' ] ) ) { throw new \ RuntimeException ( 'You are trying to set a previously defined param.' ) ; } } $ this -> _shell_common_params [ ] = array ( 'short_param_name' => $ short_param_name , 'long_param_name' => $ long_param_name , 'help_string' => $ help_string , 'need_second_param' => $ need_second_param , 'is_required' => $ is_required , ) ; }
Set a new exec param .
1,522
protected function parseParams ( ) { $ this -> params [ 'parsed_params' ] = array ( ) ; foreach ( $ this -> _shell_common_params as $ common_param ) { $ value = false ; foreach ( $ this -> command_options as $ option ) { if ( $ option [ 0 ] === $ common_param [ 'short_param_name' ] || $ option [ 0 ] === $ common_param [ 'long_param_name' ] ) { if ( ! isset ( $ option [ 1 ] ) ) { $ value = true ; } else { $ value = $ option [ 1 ] ; } break ; } } $ this -> params [ 'parsed_params' ] [ $ common_param [ 'short_param_name' ] ] = $ value ; $ this -> params [ 'parsed_params' ] [ $ common_param [ 'long_param_name' ] ] = $ value ; } }
Parse the input arguments and store them in a class property for later usage .
1,523
public function _updateContentType ( ) { unset ( $ this -> _headers [ 'Content-Type' ] ) ; $ suffix = '' ; if ( $ this -> isMultipart ( ) ) { $ suffix = '; boundary=' . $ this -> boundary ( ) ; } elseif ( $ this -> _charset ) { $ suffix = '; charset=' . $ this -> _charset . $ suffix ; } if ( $ this -> _mime ) { $ this -> _headers [ 'Content-Type' ] = $ this -> _mime . $ suffix ; } }
Update Content - Type helper
1,524
public function syncContentType ( ) { $ stream = reset ( $ this -> _streams ) ; if ( ! $ this -> isMultipart ( ) && $ stream ) { unset ( $ this -> _headers [ 'Content-Type' ] ) ; $ this -> mime ( $ stream -> mime ( ) ) ; $ this -> charset ( $ stream -> charset ( ) ) ; unset ( $ this -> _headers [ 'Content-Transfer-Encoding' ] ) ; if ( $ encoding = $ stream -> encoding ( ) ) { $ this -> _headers [ 'Content-Transfer-Encoding' ] = $ encoding ; } } }
Sync Content - Type helper .
1,525
protected function _headers ( $ options , $ mime , $ charset , $ encoding , $ length ) { $ headers = ! empty ( $ options [ 'headers' ] ) ? $ options [ 'headers' ] : [ ] ; if ( ! empty ( $ options [ 'disposition' ] ) ) { $ parts = [ $ options [ 'disposition' ] ] ; foreach ( [ 'name' , 'filename' ] as $ name ) { if ( ! empty ( $ options [ $ name ] ) ) { $ value = htmlspecialchars_decode ( htmlspecialchars ( $ options [ $ name ] , ENT_NOQUOTES | ENT_IGNORE , 'UTF-8' ) , ENT_NOQUOTES ) ; $ value = preg_replace ( '~[\s/\\\]~' , '' , $ value ) ; $ value = addcslashes ( $ value , '"' ) ; $ parts [ ] = "{$name}=\"{$value}\"" ; } } $ headers [ ] = "Content-Disposition: " . join ( '; ' , $ parts ) ; } if ( ! empty ( $ options [ 'id' ] ) ) { $ headers [ ] = 'Content-ID: ' . $ options [ 'id' ] ; } if ( ! empty ( $ mime ) ) { $ charset = $ charset ? '; charset=' . $ charset : '' ; $ headers [ ] = 'Content-Type: ' . $ mime . $ charset ; } if ( ! empty ( $ encoding ) ) { $ headers [ ] = 'Content-Transfer-Encoding: ' . $ encoding ; } if ( ! empty ( $ options [ 'length' ] ) ) { $ headers [ ] = 'Content-Length: ' . $ length ; } if ( ! empty ( $ options [ 'description' ] ) ) { $ headers [ ] = 'Content-Description: ' . $ options [ 'description' ] ; } if ( ! empty ( $ options [ 'location' ] ) ) { $ headers [ ] = 'Content-Location: ' . $ options [ 'location' ] ; } if ( ! empty ( $ options [ 'language' ] ) ) { $ headers [ ] = 'Content-Language: ' . $ options [ 'language' ] ; } return $ headers ; }
Extract headers form streams options .
1,526
public function currentCallback ( CallbackIterator $ iterator ) { $ clientFilename = $ this -> fileNames [ $ iterator -> key ( ) ] ; $ filename = $ this -> directory . DIRECTORY_SEPARATOR . $ clientFilename ; $ fileObject = new ValueObject ( file_get_contents ( $ filename ) ) ; $ fileObject -> setProperty ( 'filename' , $ filename ) ; $ fileObject -> setProperty ( 'client_filename' , $ clientFilename ) ; return $ fileObject ; }
Returns a file object .
1,527
static function isValidMId ( $ vMId ) { $ bRet = false ; if ( is_array ( $ vMId ) && count ( $ vMId ) > 0 ) { $ bRet = true ; foreach ( $ vMId as $ vItem ) { if ( ! CDId :: getInstance ( ) -> isValidId ( $ vItem ) ) { $ bRet = false ; break ; } } } else { $ bRet = CDId :: getInstance ( ) -> isValidId ( intval ( $ vMId ) ) ; } return $ bRet ; }
check if a mid is valid
1,528
static function createMId ( $ nCenter = 0 , $ nNode = 0 , $ sSource = null , & $ arrData = null ) { return CDId :: getInstance ( ) -> createId ( $ nCenter , $ nNode , $ sSource , $ arrData ) ; }
create a new mid
1,529
public function createNewToken ( $ captcha = null , $ answer = null , $ expire = 300 ) { if ( ( null === $ captcha ) || ( null === $ answer ) ) { $ captcha = $ this -> generateEquation ( ) ; $ answer = $ this -> evaluateEquation ( $ captcha ) ; } $ this -> token = [ 'captcha' => $ captcha , 'answer' => $ answer , 'expire' => ( int ) $ expire , 'start' => time ( ) ] ; $ _SESSION [ 'pop_captcha' ] = serialize ( $ this -> token ) ; return $ this ; }
Set the token of the CAPTCHA form element
1,530
public function setLabel ( $ label ) { parent :: setLabel ( $ label ) ; if ( isset ( $ this -> token [ 'captcha' ] ) ) { if ( ( strpos ( $ this -> token [ 'captcha' ] , '<img' ) === false ) && ( ( strpos ( $ this -> token [ 'captcha' ] , ' + ' ) !== false ) || ( strpos ( $ this -> token [ 'captcha' ] , ' - ' ) !== false ) || ( strpos ( $ this -> token [ 'captcha' ] , ' * ' ) !== false ) || ( strpos ( $ this -> token [ 'captcha' ] , ' / ' ) !== false ) ) ) { $ this -> label = $ this -> label . '(' . str_replace ( [ ' * ' , ' / ' ] , [ ' &#215; ' , ' &#247; ' ] , $ this -> token [ 'captcha' ] . ')' ) ; } else { $ this -> label = $ this -> label . $ this -> token [ 'captcha' ] ; } } return $ this ; }
Set the label of the captcha form element
1,531
protected function generateEquation ( ) { $ ops = [ ' + ' , ' - ' , ' * ' , ' / ' ] ; $ equation = null ; $ rand1 = rand ( 1 , 10 ) ; $ rand2 = rand ( 1 , 10 ) ; $ op = $ ops [ rand ( 0 , 3 ) ] ; if ( $ op == ' / ' ) { $ mod = ( $ rand2 > $ rand1 ) ? $ rand2 % $ rand1 : $ rand1 % $ rand2 ; while ( $ mod != 0 ) { $ rand1 = rand ( 1 , 10 ) ; $ rand2 = rand ( 1 , 10 ) ; $ mod = ( $ rand2 > $ rand1 ) ? $ rand2 % $ rand1 : $ rand1 % $ rand2 ; } } $ equation = ( $ rand2 > $ rand1 ) ? $ rand2 . $ op . $ rand1 : $ rand1 . $ op . $ rand2 ; return $ equation ; }
Randomly generate a simple basic equation
1,532
protected function calculateFirstAndLastPage ( ) { $ delta = \ floor ( $ this -> maximumNumberOfLinks / 2 ) ; $ firstPage = $ this -> currentPage - $ delta ; $ lastPage = $ this -> currentPage + $ delta + ( $ this -> maximumNumberOfLinks % 2 === 0 ? 1 : 0 ) ; if ( $ firstPage < 1 ) { $ lastPage -= $ firstPage - 1 ; } if ( $ lastPage > $ this -> numberOfPages ) { $ firstPage -= ( $ lastPage - $ this -> numberOfPages ) ; } $ this -> firstPage = \ max ( $ firstPage , 1 ) ; $ this -> lastPage = \ min ( $ lastPage , $ this -> numberOfPages ) ; }
calculates the first and last page to show
1,533
protected function getNumberOfPages ( ) { $ numberOfPages = \ ceil ( $ this -> totalCount / $ this -> itemsPerPage ) ; if ( $ this -> maximumNumberOfLinks > $ numberOfPages ) { return $ numberOfPages ; } return $ numberOfPages ; }
calculates the number of pages
1,534
protected function getPageArray ( ) { $ range = \ range ( $ this -> firstPage , $ this -> lastPage ) ; $ pageArray = [ ] ; foreach ( $ range as $ page ) { $ pageArray [ ] = [ 'page' => $ page , 'label' => $ page , 'type' => 'page' ] ; } return $ pageArray ; }
get an array of pages to display
1,535
protected function addItemToTheStartOfPageArray ( $ pageArray , $ page , $ type ) { array_unshift ( $ pageArray , [ 'page' => $ page , 'label' => $ this -> paginationConfig [ 'labels' ] [ $ type ] , 'type' => $ type ] ) ; return $ pageArray ; }
add a item to the start of the page array
1,536
protected function addItemToTheEndOfPageArray ( $ pageArray , $ page , $ type ) { $ pageArray [ ] = [ 'page' => $ page , 'label' => $ this -> paginationConfig [ 'labels' ] [ $ type ] , 'type' => $ type ] ; return $ pageArray ; }
add a item to the end of the page array
1,537
public function getOptions ( ) { $ options = [ ] ; foreach ( $ this -> childNodes as $ child ) { if ( $ child instanceof Option ) { $ options [ ] = $ child ; } } return $ options ; }
Get option elements
1,538
public function get ( ) { if ( Cache :: has ( $ this -> getCacheKey ( ) ) ) return Cache :: get ( $ this -> getCacheKey ( ) ) ; return $ this -> create ( ) ; }
Get the Token
1,539
public function check ( $ token ) { if ( ! Cache :: has ( $ this -> getCacheKey ( ) ) ) return false ; return Cache :: get ( $ this -> getCacheKey ( ) ) === $ token ; }
Check the token
1,540
protected function getCacheKey ( ) { $ model = new \ ReflectionClass ( $ this -> model ) ; $ namespace = Str :: slug ( $ model -> getNamespaceName ( ) ) ; $ class = Str :: slug ( $ model -> getShortName ( ) ) ; $ type = Str :: slug ( $ this -> type ) ; $ key = $ this -> model -> getKey ( ) ; if ( empty ( $ key ) ) throw new Exception ( "[Token] Error: Empty value for " . $ model -> getShortName ( ) . "'s attribute '" . $ this -> model -> getKeyName ( ) . "'." , 1 ) ; return 'malahierba-token' . '---' . $ namespace . '---' . $ class . '---' . $ type . '---' . $ key ; }
Get the cache key for save the token
1,541
protected function create ( ) { $ token = $ this -> generateTokenString ( ) ; Cache :: put ( $ this -> getCacheKey ( ) , $ token , $ this -> expire_in ) ; return $ token ; }
Create a new token and save as cache var
1,542
public function query ( $ method , $ pattern , $ callback ) { $ route = new Route ( $ pattern , $ callback , $ method ) ; $ this [ 'router' ] -> addRoute ( $ route ) ; return $ route ; }
Creates a route for a request .
1,543
public function run ( ) { $ request = Request :: createFromGlobals ( ) ; $ response = $ this -> handle ( $ request ) ; $ response -> send ( ) ; $ this -> invokeFinish ( [ ] , [ $ this , $ request , $ response ] ) ; }
Creates the request from globals handles it and returns the response .
1,544
public function addScanner ( $ languageName , $ scanner , $ langDescription ) { $ dummy = $ scanner === null ; $ d = array ( ) ; $ insert = array ( 'scanner' => $ scanner , 'description' => $ langDescription ) ; if ( ! is_array ( $ languageName ) ) { $ languageName = array ( $ languageName ) ; } foreach ( $ languageName as $ l ) { $ this -> lookupTable [ $ l ] = $ insert ; if ( ! $ dummy ) { $ this -> addDescription ( $ langDescription , $ l ) ; } } }
Adds a scanner into the table or overwrites an existing scanner .
1,545
public function removeScanner ( $ languageName ) { if ( is_array ( $ languageName ) ) { foreach ( $ languageName as $ l ) { unset ( $ this -> lookupTable [ $ l ] ) ; $ this -> unsetDescription ( $ l ) ; } } else { $ this -> unsetDescription ( $ languageName ) ; unset ( $ this -> lookupTable [ $ languageName ] ) ; } }
Removes a scanner from the table
1,546
private function getScannerArray ( $ languageName , $ default = true ) { $ g = null ; if ( array_key_exists ( $ languageName , $ this -> lookupTable ) ) { $ g = $ this -> lookupTable [ $ languageName ] ; } elseif ( $ this -> defaultScanner !== null && $ default === true ) { $ g = $ this -> lookupTable [ $ this -> defaultScanner ] ; } if ( $ g === null ) { return false ; } return $ g ; }
Method which retrives the desired scanner array and recursively settles the include dependencies while doing so .
1,547
public function getScanner ( $ languageName , $ default = true , $ instance = true ) { $ g = $ this -> getScannerArray ( $ languageName , $ default ) ; if ( $ g !== false ) { return $ instance ? new $ g [ 'scanner' ] : $ g [ 'scanner' ] ; } return null ; }
Returns a scanner for a language
1,548
public function addAction ( ) { $ parent = $ this -> params ( ) -> fromRoute ( 'parent' ) ; if ( ! is_numeric ( $ parent ) ) { $ this -> flashMessenger ( ) -> addMessage ( $ this -> scTranslate ( 'The category location was not specified.' ) ) ; return $ this -> redirect ( ) -> toRoute ( 'sc-admin/content-manager' ) -> setStatusCode ( 303 ) ; } try { $ categoryId = $ this -> getCategoryService ( ) -> makeCategory ( $ parent ) ; } catch ( RuntimeException $ e ) { $ this -> flashMessenger ( ) -> addMessage ( $ e -> getMessage ( ) ) ; return $ this -> redirect ( ) -> toRoute ( 'sc-admin/content-manager' ) -> setStatusCode ( 303 ) ; } return $ this -> redirect ( ) -> toRoute ( 'sc-admin/category/edit' , [ 'id' => $ categoryId ] ) ; }
Add Category .
1,549
public function editAction ( ) { $ id = $ this -> params ( ) -> fromRoute ( 'id' ) ; if ( ! is_numeric ( $ id ) ) { $ this -> flashMessenger ( ) -> addMessage ( $ this -> scTranslate ( 'The category ID was not specified.' ) ) ; return $ this -> redirect ( ) -> toRoute ( 'sc-admin/content-manager' ) -> setStatusCode ( 303 ) ; } try { $ category = $ this -> getCategoryService ( ) -> getCategory ( $ id ) ; } catch ( RuntimeException $ e ) { $ this -> flashMessenger ( ) -> addMessage ( $ e -> getMessage ( ) ) ; return $ this -> redirect ( ) -> toRoute ( 'sc-admin/content-manager' ) -> setStatusCode ( 303 ) ; } $ form = $ this -> getCategoryForm ( ) ; $ form -> setAttribute ( 'action' , $ this -> url ( ) -> fromRoute ( 'sc-admin/category/edit' , [ 'id' => $ id ] ) ) ; $ form -> bind ( $ category ) ; if ( $ this -> getRequest ( ) -> isPost ( ) ) { $ form -> setData ( $ this -> getRequest ( ) -> getPost ( ) ) ; if ( $ form -> isValid ( ) ) { $ this -> getCategoryService ( ) -> saveContent ( $ form -> getData ( ) ) ; } } return new ViewModel ( [ 'content' => $ category , 'form' => $ form , ] ) ; }
Edit Category .
1,550
public function indexAction ( ) { $ visibilityService = $ this -> getVisibilityService ( ) ; $ options = $ visibilityService -> getOptions ( ) ; $ widgetId = $ options -> getWidgetId ( ) ; if ( ! $ widgetId ) { $ this -> flashMessenger ( ) -> addMessage ( $ this -> scTranslate ( 'The widget identifier was not specified.' ) ) ; return $ this -> redirect ( ) -> toRoute ( 'sc-admin/layout' ) -> setStatusCode ( 303 ) ; } $ widget = $ this -> deriveWidget ( $ widgetId ) ; if ( empty ( $ widget ) ) { return $ this -> getResponse ( ) ; } if ( $ this -> getRequest ( ) -> isPost ( ) ) { $ event = $ this -> request -> getPost ( 'suboperation' ) ; if ( ! empty ( $ event ) ) { $ events = $ this -> getEventManager ( ) ; $ params = $ this -> getRequest ( ) -> getPost ( ) ; $ params [ 'widget_id' ] = $ widget -> getId ( ) ; $ result = $ events -> trigger ( $ event , $ this , $ params ) ; if ( $ result -> last ( ) instanceof Response ) { return $ result -> last ( ) ; } } } $ view = new ViewModel ; $ view -> options = $ options ; $ view -> widget = $ widget ; $ moduleOptions = $ this -> getModuleOptions ( ) ; $ view -> config = $ moduleOptions -> getWidgetByName ( $ widget -> getName ( ) ) ; $ view -> list = $ visibilityService -> getContentList ( ) ; $ visibilityService -> saveOptions ( ) ; return $ view ; }
Show content list with widget visibility options .
1,551
public function getErrorMessages ( FormInterface $ form , bool $ useLabels = false , array $ errors = [ ] ) : array { if ( $ form -> count ( ) > 0 ) { foreach ( $ form -> all ( ) as $ child ) { if ( ! $ child -> isValid ( ) ) { $ errors = $ this -> getErrorMessages ( $ child , $ useLabels , $ errors ) ; } } } foreach ( $ form -> getErrors ( ) as $ error ) { if ( $ useLabels ) { $ fieldNameData = $ this -> getErrorFormLabel ( $ form ) ; } else { $ fieldNameData = $ this -> getErrorFormId ( $ form ) ; } $ fieldName = $ fieldNameData ; if ( $ useLabels ) { $ fieldName = $ this -> translator -> trans ( $ fieldNameData [ 'label' ] , array ( ) , $ fieldNameData [ 'domain' ] ) ; } $ errors [ $ fieldName ] = $ error -> getMessage ( ) ; } return $ errors ; }
Returns an array with form fields errors
1,552
protected function getErrorFormLabel ( FormInterface $ form ) : array { $ vars = $ form -> createView ( ) -> vars ; $ label = $ vars [ 'label' ] ; $ translationDomain = $ vars [ 'translation_domain' ] ; $ result = array ( 'label' => $ label , 'domain' => $ translationDomain , ) ; if ( empty ( $ label ) ) { if ( $ form -> getParent ( ) !== null ) { $ result = $ this -> getErrorFormLabel ( $ form -> getParent ( ) ) ; } } return $ result ; }
Returns first label for field with error
1,553
public static function applicablePropertyModelId ( $ class , $ forceRefresh = false ) { if ( true === method_exists ( $ class , 'getApplicableClass' ) ) { $ modelClass = call_user_func ( [ $ class , 'getApplicableClass' ] ) ; } else { $ modelClass = is_string ( $ class ) ? $ class : get_class ( $ class ) ; } self :: retrieveApplicablePropertyModels ( $ forceRefresh ) ; if ( isset ( self :: $ applicablePropertyModels [ $ modelClass ] ) ) { return self :: $ applicablePropertyModels [ $ modelClass ] ; } else { throw new Exception ( 'Property group model record not found for class: ' . $ modelClass ) ; } }
Returns id of property_group_models record for requested classname
1,554
public static function classNameForApplicablePropertyModelId ( $ id , $ forceRefresh = false ) { self :: retrieveApplicablePropertyModels ( $ forceRefresh ) ; return array_search ( $ id , self :: $ applicablePropertyModels , true ) ; }
Returns class name of Model for which property or property_group model record is associated
1,555
public static function generateCacheKey ( $ models , $ postfix = 'properties' ) { $ ids = ArrayHelper :: getColumn ( $ models , 'id' , false ) ; sort ( $ ids ) ; $ first = reset ( $ models ) ; return $ first :: tableName ( ) . ':' . implode ( ',' , $ ids ) . "-$postfix" ; }
Generates cache key based on models array model table name and postfix
1,556
public static function getAvailablePropertyGroupsList ( $ className ) { $ applicablePropertyModelId = PropertiesHelper :: applicablePropertyModelId ( $ className ) ; $ availableGroups = Yii :: $ app -> cache -> lazy ( function ( ) use ( $ applicablePropertyModelId ) { return ArrayHelper :: map ( PropertyGroup :: find ( ) -> where ( [ 'applicable_property_model_id' => $ applicablePropertyModelId ] ) -> orderBy ( 'sort_order ASC' ) -> all ( ) , 'id' , function ( $ model ) { return ! empty ( $ model -> name ) ? $ model -> name : $ model -> internal_name ; } ) ; } , 'AvailablePropertyGroupsList: ' . $ applicablePropertyModelId , 86400 , PropertyGroup :: commonTag ( ) ) ; return $ availableGroups ; }
Get available property groups by class name .
1,557
public function match ( GenericRequest $ request ) { Utils :: reset ( ) ; $ handlers = $ this -> getHandlers ( ) ; $ matchResult = WurflConstants :: NO_MATCH ; foreach ( $ handlers as $ handler ) { $ handler -> setLogger ( $ this -> logger ) ; if ( $ handler -> canHandle ( $ request -> getUserAgentNormalized ( ) ) ) { $ matchResult = $ handler -> applyMatch ( $ request ) ; break ; } } return $ matchResult ; }
Return the the device id for the request
1,558
public function persistData ( ) { $ handlers = $ this -> getHandlers ( ) ; foreach ( $ handlers as $ handler ) { $ handler -> setLogger ( $ this -> logger ) ; $ handler -> persistData ( ) ; } }
Save the data from each \ Wurfl \ Handlers \ AbstractHandler
1,559
public function create ( $ operation ) { if ( ! is_string ( $ operation ) ) { throw new \ LogicException ( "Provided manipulation name {$operation} is not a string!" ) ; } $ operation = str_replace ( '-' , ' ' , $ operation ) ; $ operation = strtolower ( $ operation ) ; $ operation = ucwords ( $ operation ) ; $ operation = str_replace ( ' ' , '' , $ operation ) ; $ className = "Todstoychev\\Icr\\Manipulator\\" . $ operation ; if ( ! class_exists ( $ className ) ) { throw new IcrRuntimeException ( "Operation {$operation} does not exists!" ) ; } return new $ className ( $ this -> box , $ this -> point ) ; }
Creates manipulation instance
1,560
public function scopeOfOwner ( Builder $ builder , Model $ owner ) : Builder { return $ builder -> where ( 'owner_type' , $ owner -> getMorphClass ( ) ) -> where ( 'owner_id' , $ owner -> getKey ( ) ) ; }
Get tenants of the given owner .
1,561
protected function getFilters ( $ path , AssetInterface $ asset ) { $ config = $ this -> getConfig ( ) ; if ( ! empty ( $ config [ $ path ] ) ) { return $ config [ $ path ] ; } if ( ! empty ( $ asset -> mimetype ) && ! empty ( $ config [ $ asset -> mimetype ] ) ) { return $ config [ $ asset -> mimetype ] ; } $ extension = strtolower ( pathinfo ( $ asset -> getSourcePath ( ) , PATHINFO_EXTENSION ) ) ; if ( ! empty ( $ config [ $ extension ] ) ) { return $ config [ $ extension ] ; } return [ ] ; }
Get the filters from config based on path mimetype or extension .
1,562
protected function setFilter ( $ filter , AssetInterface $ asset ) { if ( is_null ( $ filter ) ) { return ; } if ( ! empty ( $ filter [ 'filter' ] ) ) { $ this -> ensureByFilter ( $ asset , $ filter [ 'filter' ] ) ; return ; } if ( ! empty ( $ filter [ 'service' ] ) ) { $ this -> ensureByService ( $ asset , $ filter [ 'service' ] ) ; return ; } throw new Exception \ RuntimeException ( 'Invalid filter supplied. Expected Filter or Service.' ) ; }
Set the filter by filter or service
1,563
public function index ( Request $ request ) { $ referrerDomain = parse_url ( $ request -> server ( 'HTTP_REFERER' ) , PHP_URL_HOST ) ; if ( $ referrerDomain !== $ this -> config -> get ( 'vanilla-integration.forum_domain' ) ) { return app ( ) -> abort ( 404 ) ; } if ( class_exists ( 'Debugbar' ) ) { \ Debugbar :: disable ( ) ; } $ clientID = $ this -> config -> get ( 'vanilla-integration.client_id' ) ; $ secret = $ this -> config -> get ( 'vanilla-integration.secret' ) ; $ user = [ ] ; if ( $ this -> auth -> check ( ) ) { $ currentUser = $ this -> auth -> user ( ) ; $ user [ 'uniqueid' ] = $ currentUser -> id ; $ user [ 'name' ] = $ currentUser -> getPresenter ( ) -> displayName ( ) ; $ user [ 'email' ] = $ currentUser -> email ; } $ secure = true ; WriteJsConnect ( $ user , $ request -> only ( [ 'client_id' , 'signature' , 'callback' , 'timestamp' ] ) , $ clientID , $ secret , $ secure ) ; return response ( '' ) -> header ( 'Content-Type' , 'application/javascript' ) ; }
Connect method . It s returning JSONP response
1,564
public static function convertToUTF8 ( $ str , $ config , $ context ) { $ encoding = $ config -> get ( 'Core.Encoding' ) ; if ( $ encoding === 'utf-8' ) return $ str ; static $ iconv = null ; if ( $ iconv === null ) $ iconv = function_exists ( 'iconv' ) ; set_error_handler ( array ( 'HTMLPurifier_Encoder' , 'muteErrorHandler' ) ) ; if ( $ iconv && ! $ config -> get ( 'Test.ForceNoIconv' ) ) { $ str = iconv ( $ encoding , 'utf-8//IGNORE' , $ str ) ; if ( $ str === false ) { restore_error_handler ( ) ; trigger_error ( 'Invalid encoding ' . $ encoding , E_USER_ERROR ) ; return '' ; } $ str = strtr ( $ str , HTMLPurifier_Encoder :: testEncodingSupportsASCII ( $ encoding ) ) ; restore_error_handler ( ) ; return $ str ; } elseif ( $ encoding === 'iso-8859-1' ) { $ str = utf8_encode ( $ str ) ; restore_error_handler ( ) ; return $ str ; } trigger_error ( 'Encoding not supported, please install iconv' , E_USER_ERROR ) ; }
Converts a string to UTF - 8 based on configuration .
1,565
public function all ( $ locale = null ) { if ( ! $ locale ) { $ locale = $ this -> getLocale ( ) ; } $ this -> load ( $ locale ) ; $ translations = collect ( [ ] ) ; foreach ( $ this -> languages [ $ locale ] as $ key => $ arg ) { $ translations -> put ( $ key , $ arg [ 'value' ] ) ; } return $ translations ; }
Get all available translations
1,566
public function load ( $ locale ) { if ( $ this -> isLoaded ( $ locale ) ) { return ; } $ this -> languages [ $ locale ] = $ this -> handler -> load ( $ locale ) ; }
Load the specified language .
1,567
protected function finalRender ( $ debug_data ) { parent :: finalRender ( $ debug_data ) ; $ url = \ Sifo \ Urls :: getInstance ( ) -> getUrlConfig ( ) ; echo '[INFO] Script debug properly saved. You can check it out at: ' . $ url [ 'sifo_debug_analyzer' ] . '?execution_key=' . \ Sifo \ Debug :: getExecutionKey ( ) . PHP_EOL ; }
Override method in order to show a message with a link to the Sifo Debug Analyzer .
1,568
function publish ( $ id , $ previous ) { $ this -> requestDecorator -> setId ( $ id . '/published' ) ; $ this -> requestDecorator -> addHeader ( 'X-Contentful-Version' , $ previous [ 'sys' ] [ 'version' ] ) ; $ result = $ this -> client -> put ( $ this -> requestDecorator -> makeResource ( ) , $ this -> requestDecorator -> makePayload ( ) , $ this -> requestDecorator -> makeHeaders ( ) ) ; $ this -> refresh ( ) ; return $ result ; }
Publish a record .
1,569
function unpublish ( $ id , $ previous ) { $ this -> requestDecorator -> setId ( $ id . '/published' ) ; $ this -> requestDecorator -> addHeader ( 'X-Contentful-Version' , $ previous [ 'sys' ] [ 'version' ] ) ; $ result = $ this -> client -> delete ( $ this -> requestDecorator -> makeResource ( ) , $ this -> requestDecorator -> makeHeaders ( ) ) ; $ this -> refresh ( ) ; return $ result ; }
Unublish a record .
1,570
public function add ( $ policyName , \ Psecio \ PropAuth \ Policy $ policy ) { $ this -> policies [ $ policyName ] = $ policy ; return $ this ; }
Add a new policy to the current set with the given key name
1,571
public function nextIs ( $ tokenName , $ ignoreWhitespace = false ) { $ i = $ this -> index + 1 ; $ len = count ( $ this -> tokens ) ; while ( $ i < $ len ) { $ tok = $ this -> tokens [ $ i ] [ 0 ] ; if ( $ ignoreWhitespace && $ tok === 'WHITESPACE' ) { $ i ++ ; } else { return $ tok === $ tokenName ; } } return false ; }
Returns true if the next token is the given token name optionally skipping whitespace
1,572
public function nextSequence ( $ sequence , $ ignore = array ( ) ) { $ i = $ this -> index + 1 ; $ len = count ( $ this -> tokens ) ; $ seqLen = count ( $ sequence ) ; $ seq = 0 ; $ seqStart = 0 ; while ( $ i < $ len ) { $ tok = $ this -> tokens [ $ i ] [ 0 ] ; if ( $ tok === $ sequence [ $ seq ] ) { if ( $ seq === 0 ) { $ seqStart = $ i ; } $ seq ++ ; $ i ++ ; if ( $ seq === $ seqLen ) { return $ seqStart ; } } else { if ( in_array ( $ tok , $ ignore ) ) { } else { $ seq = 0 ; } $ i ++ ; } } return $ len ; }
Returns the index of the next match of the sequence of tokens given optionally ignoring ertain tokens
1,573
public function nextOf ( $ tokenNames ) { $ i = $ this -> index + 1 ; $ len = count ( $ this -> tokens ) ; while ( $ i < $ len ) { $ tok = $ this -> tokens [ $ i ] [ 0 ] ; if ( in_array ( $ tok , $ tokenNames ) ) { return $ tok ; } $ i ++ ; } return null ; }
Returns the first token which occurs out of the set of given tokens
1,574
public function nextOfType ( $ tokenName ) { $ i = $ this -> index + 1 ; $ len = count ( $ this -> tokens ) ; while ( $ i < $ len ) { $ tok = $ this -> tokens [ $ i ] [ 0 ] ; if ( $ tok === $ tokenName ) { return $ i ; } $ i ++ ; } return $ len ; }
Returns the index of the next token with the given token name
1,575
private function parseRule ( ) { $ newToken = $ this -> tokens [ $ this -> index ] ; $ set = false ; if ( $ this -> index > 0 ) { $ prevToken = & $ this -> tokens [ $ this -> index - 1 ] ; $ prevTokenType = & $ prevToken [ 0 ] ; $ prevTokenText = & $ prevToken [ 1 ] ; $ concat = false ; $ map = array ( 'DOT' => 'CLASS_SELECTOR' , 'HASH' => 'ID_SELECTOR' , 'COLON' => 'PSEUDO_SELECTOR' , 'DOUBLE_COLON' => 'PSEUDO_SELECTOR' ) ; if ( isset ( $ map [ $ prevTokenType ] ) ) { $ newToken [ 0 ] = $ map [ $ prevTokenType ] ; $ prevTokenType = self :: $ deleteToken ; $ newToken [ 1 ] = $ prevTokenText . $ newToken [ 1 ] ; $ set = true ; } } if ( ! $ set ) { $ newToken [ 0 ] = 'ELEMENT_SELECTOR' ; } $ this -> tokens [ $ this -> index ] = $ newToken ; }
Parses a selector rule
1,576
private function cleanup ( ) { foreach ( $ this -> tokens as $ i => $ t ) { if ( $ t [ 0 ] === self :: $ deleteToken ) { unset ( $ this -> tokens [ $ i ] ) ; } } $ this -> tokens = array_values ( $ this -> tokens ) ; }
Cleans up the token stream by deleting any tokens marked for deletion and makes sure the array is continuous afterwards .
1,577
public function interpString ( $ m ) { $ patterns = array ( 'interp' => '/(?<!\\$)\\$\\{/' ) ; $ start = $ this -> pos ( ) ; if ( preg_match ( '/^"""/' , $ m [ 0 ] ) ) { $ patterns [ 'term' ] = '/"""/' ; $ this -> posShift ( 3 ) ; } else { assert ( preg_match ( '/^"/' , $ m [ 0 ] ) ) ; $ patterns [ 'term' ] = '/"/' ; $ this -> posShift ( 1 ) ; } while ( 1 ) { $ p = $ this -> pos ( ) ; list ( $ name , $ index , $ matches ) = $ this -> getNextNamed ( $ patterns ) ; if ( $ name === null ) { $ this -> record ( substr ( $ this -> string ( ) , $ start ) , 'STRING' ) ; $ this -> terminate ( ) ; break ; } elseif ( $ name === 'term' ) { $ range = $ index + strlen ( $ matches [ 0 ] ) ; $ this -> record ( substr ( $ this -> string ( ) , $ start , $ range - $ start ) , 'STRING' ) ; $ this -> pos ( $ range ) ; break ; } else { $ this -> record ( substr ( $ this -> string ( ) , $ start , $ index - $ start ) , 'STRING' ) ; $ this -> record ( $ matches [ 0 ] , 'DELIMITER' ) ; $ subscanner = new GroovyScanner ( $ this -> string ( ) ) ; $ subscanner -> interpolation = true ; $ subscanner -> init ( ) ; $ subscanner -> pos ( $ index + strlen ( $ matches [ 0 ] ) ) ; $ subscanner -> main ( ) ; $ tagged = $ subscanner -> tagged ( ) ; $ this -> record ( $ tagged , 'INTERPOLATION' , true ) ; $ this -> pos ( $ subscanner -> pos ( ) ) ; if ( $ this -> scan ( '/\\}/' ) ) { $ this -> record ( $ this -> match ( ) , 'DELIMITER' ) ; } $ start = $ this -> pos ( ) ; } assert ( $ p < $ this -> pos ( ) ) ; } }
string interpolation is complex and it nests so we do that in here
1,578
public function brace ( $ m ) { if ( $ m [ 0 ] === '{' ) { $ this -> braceStack ++ ; } elseif ( $ m [ 0 ] === '}' ) { if ( $ this -> braceStack <= 0 ) { return true ; } $ this -> braceStack -- ; } else { assert ( 0 ) ; } $ this -> record ( $ m [ 0 ] , null ) ; $ this -> posShift ( strlen ( $ m [ 0 ] ) ) ; }
this is for interpolated code the top - level scanner doesn t bind to this
1,579
public function get ( $ name ) { if ( isset ( $ this -> fields [ $ name ] ) ) { return $ this -> fields [ $ name ] ; } throw new FieldException ( "Fielder doesn't have [$name] field registered." ) ; }
Get registered field .
1,580
public function make ( $ class , $ type , $ slug , $ arguments = [ ] ) { $ field = $ this -> container -> make ( $ class ) ; $ field -> setType ( $ type ) -> setSlug ( $ slug ) -> setArguments ( $ arguments ) -> boot ( ) ; return $ field ; }
Creates field instance .
1,581
public function output ( $ view , $ data = [ ] ) { $ path = $ this -> processOutput ( $ view , $ data ) ; $ content = file_get_contents ( $ path ) ; @ unlink ( $ path ) ; return $ content ; }
Get pdf output for the view .
1,582
protected function processOutput ( $ view , $ data = [ ] ) { $ name = $ this -> generateFileName ( ) ; $ path = __DIR__ . DIRECTORY_SEPARATOR . "{$name}" ; file_put_contents ( $ path , $ this -> generateView ( $ view , $ data ) ) ; $ this -> getPhantomProcess ( $ path ) -> setTimeout ( 0 ) -> mustRun ( ) ; return $ path ; }
Process pdf output for the view .
1,583
public function download ( $ view , $ data = [ ] , $ name = 'download' ) { $ path = $ this -> processOutput ( $ view , $ data ) ; return $ this -> responseDownload ( $ path , $ name ) ; }
Download generated pdf file .
1,584
protected function responseDownload ( $ path , $ name ) { $ response = new Response ( file_get_contents ( $ path ) , 200 , [ 'Content-Type' => 'application/pdf' , 'Content-Description' => 'File Transfer' , 'Content-Disposition' => 'attachment; filename="' . $ name . '.pdf"' , 'Content-Transfer-Encoding' => 'binary' ] ) ; @ unlink ( $ path ) ; return $ response -> send ( ) ; }
Http response to download the pdf .
1,585
public function stream ( $ view , $ data = [ ] ) { $ path = $ this -> processOutput ( $ view , $ data ) ; return $ this -> responseStream ( $ path ) ; }
View pdf in the browser .
1,586
protected function responseStream ( $ path ) { $ response = new Response ( file_get_contents ( $ path ) , 200 , [ 'Content-type' => 'application/pdf' , 'Content-Transfer-Encoding' => 'binary' ] ) ; @ unlink ( $ path ) ; return $ response -> send ( ) ; }
Http response to stream pdf in the browser .
1,587
protected function getSystem ( ) { $ osName = strtolower ( php_uname ( ) ) ; if ( $ this -> contains ( $ osName , 'darwin' ) ) { return 'macosx' ; } elseif ( $ this -> contains ( $ osName , 'win' ) ) { return 'windows' ; } elseif ( $ this -> contains ( $ osName , 'linux' ) ) { return PHP_INT_SIZE === 4 ? 'linux-i686' : 'linux-x86_64' ; } else { throw new RuntimeException ( 'Unknown operating system.' ) ; } }
Get the operating system name for the current platform .
1,588
protected function generateView ( $ view , $ data = [ ] ) { if ( is_null ( $ this -> viewPath ) ) { return $ view ; } $ twig = new Twig_Environment ( new Twig_Loader_Filesystem ( realpath ( $ this -> viewPath ) ) ) ; return $ twig -> render ( $ view , $ data ) ; }
Generate view for the pdf file .
1,589
protected function getConfigurationFile ( ) { if ( ! is_null ( $ this -> configPath ) ) { return realpath ( $ this -> configPath ) ; } elseif ( function_exists ( 'base_path' ) and file_exists ( $ phantomConfiguration = base_path ( ) . DIRECTORY_SEPARATOR . 'SunPdf.js' ) ) { return realpath ( $ phantomConfiguration ) ; } else { return realpath ( __DIR__ . '/../phantom.js' ) ; } }
Get PhantomJS configuration file .
1,590
public function isCorrectType ( $ type , $ path ) { if ( ! $ type ) { return true ; } if ( ! isset ( $ this -> typeCache [ $ path ] ) ) { $ this -> typeCache [ $ path ] = is_file ( $ path ) ? 'file' : 'dir' ; } return $ this -> typeCache [ $ path ] === $ type ; }
Checks wether an path is of the correct type dir or file
1,591
public function filter ( array $ contents ) { $ filtered = array ( ) ; $ this -> typeCache = array ( ) ; foreach ( $ contents as $ item ) { $ passed = true ; foreach ( $ this -> filters as $ filter ) { $ correctType = $ this -> isCorrectType ( $ filter [ 'type' ] , $ item ) ; if ( $ correctType and preg_match ( $ filter [ 'pattern' ] , $ item ) !== $ expected ) { $ passed = false ; } } if ( $ passed ) { $ filtered [ ] = $ item ; } } return $ contents ; }
Filters a batch of filesystem entries
1,592
public static function cleanThumbnail ( ) : array { $ result = [ ] ; $ files = Finder :: findFiles ( '*' ) -> in ( self :: $ parameters [ 'thumbPath' ] ) ; foreach ( $ files as $ file ) { if ( unlink ( $ file -> getPathname ( ) ) ) { $ result [ ] = $ file -> getPathname ( ) ; } } return $ result ; }
Clean thumbnail .
1,593
private static function getThumbFiles ( ) : array { $ result = [ ] ; $ thumbFinder = Finder :: findFiles ( '*' ) -> in ( self :: $ parameters [ 'thumbPath' ] ) ; foreach ( $ thumbFinder as $ file ) { $ basename = $ file -> getBaseName ( ) ; $ specialDelimiter = strrpos ( $ basename , '_' ) ; $ lastDot = strrpos ( $ basename , '.' ) ; $ result [ $ file -> getRealPath ( ) ] = substr ( $ basename , 0 , $ specialDelimiter ) . substr ( $ basename , $ lastDot ) ; } return $ result ; }
Get thumb files .
1,594
private static function getPathFiles ( array $ path ) : array { $ result = [ ] ; $ pathFinder = Finder :: findFiles ( '*' ) -> in ( $ path ) ; foreach ( $ pathFinder as $ file ) { $ result [ $ file -> getRealPath ( ) ] = $ file -> getBaseName ( ) ; } return $ result ; }
Get path files .
1,595
public static function synchronizeThumbnail ( array $ path ) : array { $ result = [ ] ; $ thumbFiles = self :: getThumbFiles ( ) ; $ pathFiles = self :: getPathFiles ( $ path ) ; $ diff = array_diff ( $ thumbFiles , $ pathFiles ) ; foreach ( $ diff as $ oldName => $ file ) { if ( unlink ( $ oldName ) ) { $ result [ ] = $ oldName ; } } return $ result ; }
Synchronize thumbnail .
1,596
public static function getUnusedFiles ( array $ path ) : array { $ thumbFiles = self :: getThumbFiles ( ) ; $ pathFiles = self :: getPathFiles ( $ path ) ; return $ diff = array_diff ( $ pathFiles , $ thumbFiles ) ; }
Get unused files .
1,597
public static function isSrcPathExists ( string $ path , string $ file = null ) : bool { $ src = self :: $ parameters [ 'dir' ] . $ path . $ file ; return file_exists ( $ src ) && is_file ( $ src ) ; }
Is src path exists .
1,598
public static function getSrcPath ( string $ path , string $ file = null , string $ width = null , string $ height = null , array $ flags = [ ] , int $ quality = null ) : string { $ cacheName = 'getSrcPath' . $ path . $ file . $ width . $ height . implode ( $ flags ) . $ quality ; $ destination = ( self :: $ parameters [ 'cache' ] ? self :: $ cache -> load ( $ cacheName ) : null ) ; if ( $ destination === null ) { if ( ! file_exists ( self :: $ parameters [ 'thumbPath' ] ) ) { throw new \ Exception ( 'Path: ' . self :: $ parameters [ 'thumbPath' ] . ' does not exist!' ) ; } $ template = self :: $ parameters [ 'template' ] ; if ( isset ( $ template [ $ path ] ) ) { $ conf = $ template [ $ path ] ; $ destination = self :: resizeImage ( $ conf [ 'path' ] , $ file , $ conf [ 'width' ] ?? null , $ conf [ 'height' ] ?? null , $ conf [ 'flags' ] ?? [ ] , $ conf [ 'quality' ] ?? null ) ; } else { $ destination = self :: resizeImage ( $ path , $ file , $ width , $ height , $ flags , $ quality ) ; } if ( self :: $ parameters [ 'cache' ] ) { try { self :: $ cache -> save ( $ cacheName , $ destination , [ Cache :: FILES => [ self :: $ parameters [ 'dir' ] . $ path . $ file ] ] ) ; } catch ( \ Throwable $ e ) { } } } return substr ( $ destination , strlen ( realpath ( self :: $ parameters [ 'dir' ] ) ) + 1 ) ; }
Get src path .
1,599
private static function getImageFlag ( array $ flags ) : int { $ res = 0 ; foreach ( $ flags as $ flag ) { $ res |= constant ( Image :: class . '::' . $ flag ) ; } return $ res ; }
Get image flag .