idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
46,000
public function dir_readdir ( ) { $ current = current ( $ this -> listing ) ; next ( $ this -> listing ) ; return $ current ? $ current [ 'path' ] : false ; }
Reads an entry from directory handle .
46,001
public function stream_stat ( ) { $ stat = $ this -> url_stat ( $ this -> uri , static :: STREAM_URL_IGNORE_SIZE | STREAM_URL_STAT_QUIET ) ? : [ ] ; if ( empty ( $ stat [ 'mode' ] ) ) { $ stat [ 'mode' ] = 0100000 + $ this -> getConfiguration ( 'permissions' ) [ 'file' ] [ 'public' ] ; $ stat [ 2 ] = $ stat [ 'mode' ] ; } $ stat [ 'size' ] = $ stat [ 7 ] = StreamUtil :: getSize ( $ this -> handle ) ; return $ stat ; }
Retrieves information about a file resource .
46,002
public function stream_truncate ( $ new_size ) { if ( $ this -> isReadOnly ) { return false ; } $ this -> needsFlush = true ; $ this -> ensureWritableHandle ( ) ; return ftruncate ( $ this -> handle , $ new_size ) ; }
Truncates the stream .
46,003
public function unlink ( $ uri ) { $ this -> uri = $ uri ; return $ this -> invoke ( $ this -> getFilesystem ( ) , 'delete' , [ $ this -> getTarget ( ) ] , 'unlink' ) ; }
Deletes a file .
46,004
public function url_stat ( $ uri , $ flags ) { $ this -> uri = $ uri ; try { return $ this -> getFilesystem ( ) -> stat ( $ this -> getTarget ( ) , $ flags ) ; } catch ( FileNotFoundException $ e ) { if ( ! ( $ flags & STREAM_URL_STAT_QUIET ) ) { $ this -> triggerError ( 'stat' , $ e ) ; } } catch ( \ Exception $ e ) { $ this -> triggerError ( 'stat' , $ e ) ; } return false ; }
Retrieves information about a file .
46,005
protected function getStream ( $ path , $ mode ) { switch ( $ mode [ 0 ] ) { case 'r' : $ this -> needsCowCheck = true ; return $ this -> getFilesystem ( ) -> readStream ( $ path ) ; case 'w' : $ this -> needsFlush = true ; return fopen ( 'php://temp' , 'w+b' ) ; case 'a' : return $ this -> getAppendStream ( $ path ) ; case 'x' : return $ this -> getXStream ( $ path ) ; case 'c' : return $ this -> getWritableStream ( $ path ) ; } return false ; }
Returns a stream for a given path and mode .
46,006
protected function getAppendStream ( $ path ) { if ( $ handle = $ this -> getWritableStream ( $ path ) ) { StreamUtil :: trySeek ( $ handle , 0 , SEEK_END ) ; } return $ handle ; }
Returns an appendable stream for a given path and mode .
46,007
protected function ensureWritableHandle ( ) { if ( ! $ this -> needsCowCheck ) { return ; } $ this -> needsCowCheck = false ; if ( StreamUtil :: isWritable ( $ this -> handle ) ) { return ; } $ this -> handle = StreamUtil :: copy ( $ this -> handle ) ; }
Guarantees that the handle is writable .
46,008
protected function getTarget ( $ uri = null ) { if ( ! isset ( $ uri ) ) { $ uri = $ this -> uri ; } $ target = substr ( $ uri , strpos ( $ uri , '://' ) + 3 ) ; return $ target === false ? '' : $ target ; }
Returns the local writable target of the resource within the stream .
46,009
protected function getConfiguration ( $ key = null ) { return $ key ? static :: $ config [ $ this -> getProtocol ( ) ] [ $ key ] : static :: $ config [ $ this -> getProtocol ( ) ] ; }
Returns the configuration .
46,010
protected function getFilesystem ( ) { if ( isset ( $ this -> filesystem ) ) { return $ this -> filesystem ; } $ this -> filesystem = static :: $ filesystems [ $ this -> getProtocol ( ) ] ; return $ this -> filesystem ; }
Returns the filesystem .
46,011
protected function invoke ( $ object , $ method , array $ args , $ errorname = null ) { try { return call_user_func_array ( [ $ object , $ method ] , $ args ) ; } catch ( \ Exception $ e ) { $ errorname = $ errorname ? : $ method ; $ this -> triggerError ( $ errorname , $ e ) ; } return false ; }
Calls a method on an object catching any exceptions .
46,012
protected function openLockHandle ( ) { $ sub_dir = bin2hex ( $ this -> getProtocol ( ) ) ; $ temp_dir = sys_get_temp_dir ( ) . '/flysystem-stream-wrapper/' . $ sub_dir ; ! is_dir ( $ temp_dir ) && @ mkdir ( $ temp_dir , 0777 , true ) ; $ lock_key = sha1 ( Util :: normalizePath ( $ this -> getTarget ( ) ) ) ; return fopen ( $ temp_dir . '/' . $ lock_key , 'c' ) ; }
Creates an advisory lock handle .
46,013
protected function releaseLock ( $ operation ) { $ exists = is_resource ( $ this -> lockHandle ) ; $ success = $ exists && flock ( $ this -> lockHandle , $ operation ) ; $ exists && fclose ( $ this -> lockHandle ) ; $ this -> lockHandle = null ; return $ success ; }
Releases the advisory lock .
46,014
protected function shouldMail ( Exception $ exception ) { if ( config ( 'laravelEmailExceptions.ErrorEmail.email' ) != true || ! config ( 'laravelEmailExceptions.ErrorEmail.toEmailAddress' ) || ! config ( 'laravelEmailExceptions.ErrorEmail.fromEmailAddress' ) || $ this -> shouldntReport ( $ exception ) || $ this -> isInDontEmailList ( $ exception ) || $ this -> appSpecificDontEmail ( $ exception ) || $ this -> throttle ( $ exception ) || $ this -> globalThrottle ( ) ) { return false ; } return true ; }
Determine if the exception should be mailed
46,015
protected function mailException ( Exception $ exception ) { $ data = [ 'exception' => $ exception , 'toEmail' => config ( 'laravelEmailExceptions.ErrorEmail.toEmailAddress' ) , 'fromEmail' => config ( 'laravelEmailExceptions.ErrorEmail.fromEmailAddress' ) , ] ; Mail :: send ( 'laravelEmailExceptions::emailException' , $ data , function ( $ message ) { $ default = 'An Exception has been thrown on ' . config ( 'app.name' , 'unknown' ) . ' (' . config ( 'app.env' , 'unknown' ) . ')' ; $ subject = config ( 'laravelEmailExceptions.ErrorEmail.emailSubject' ) ? : $ default ; $ message -> from ( config ( 'laravelEmailExceptions.ErrorEmail.fromEmailAddress' ) ) -> to ( config ( 'laravelEmailExceptions.ErrorEmail.toEmailAddress' ) ) -> subject ( $ subject ) ; } ) ; }
mail the exception
46,016
protected function globalThrottle ( ) { if ( config ( 'laravelEmailExceptions.ErrorEmail.globalThrottle' ) == false ) { return false ; } else { if ( Cache :: store ( config ( 'laravelEmailExceptions.ErrorEmail.throttleCacheDriver' ) ) -> has ( $ this -> globalThrottleCacheKey ) ) { if ( Cache :: store ( config ( 'laravelEmailExceptions.ErrorEmail.throttleCacheDriver' ) ) -> get ( $ this -> globalThrottleCacheKey , 0 ) >= config ( 'laravelEmailExceptions.ErrorEmail.globalThrottleLimit' ) ) { return true ; } else { Cache :: store ( config ( 'laravelEmailExceptions.ErrorEmail.throttleCacheDriver' ) ) -> increment ( $ this -> globalThrottleCacheKey ) ; return false ; } } else { Cache :: store ( config ( 'laravelEmailExceptions.ErrorEmail.throttleCacheDriver' ) ) -> put ( $ this -> globalThrottleCacheKey , 1 , $ this -> getDateTimeMinutesFromNow ( config ( 'laravelEmailExceptions.ErrorEmail.globalThrottleDurationMinutes' ) ) ) ; return false ; } } }
check if we need to globally throttle the exception
46,017
protected function throttle ( Exception $ exception ) { if ( config ( 'laravelEmailExceptions.ErrorEmail.throttle' ) == false || $ this -> isInDontThrottleList ( $ exception ) ) { return false ; } else { if ( Cache :: store ( config ( 'laravelEmailExceptions.ErrorEmail.throttleCacheDriver' ) ) -> has ( $ this -> getThrottleCacheKey ( $ exception ) ) ) { return true ; } else { Cache :: store ( config ( 'laravelEmailExceptions.ErrorEmail.throttleCacheDriver' ) ) -> put ( $ this -> getThrottleCacheKey ( $ exception ) , true , $ this -> getDateTimeMinutesFromNow ( config ( 'laravelEmailExceptions.ErrorEmail.throttleDurationMinutes' ) ) ) ; return false ; } } }
check if we need to throttle the exception and do the throttling if required
46,018
protected function getThrottleCacheKey ( Exception $ exception ) { if ( $ this -> throttleCacheKey == null ) { $ this -> throttleCacheKey = preg_replace ( "/[^A-Za-z0-9]/" , '' , 'laravelEmailException' . get_class ( $ exception ) . $ exception -> getMessage ( ) . $ exception -> getCode ( ) ) ; } return $ this -> throttleCacheKey ; }
get the throttle cache key
46,019
protected function isInList ( $ list , Exception $ exception ) { if ( $ list && is_array ( $ list ) ) { foreach ( $ list as $ type ) { if ( $ exception instanceof $ type ) { return true ; } } } return false ; }
check if a given exception matches the class of any in the list
46,020
public function instance ( ) { $ cache = new CacheItemPool ( ) ; $ cache -> changeConfig ( [ 'cacheDirectory' => $ this -> getCacheDirectory ( ) , ] ) ; return new PasswordExposedChecker ( null , $ cache ) ; }
Creates and returns an instance of PasswordExposedChecker .
46,021
protected function getParameters ( DOMElement $ embed ) { $ parameters = [ 'noLayout' => true , 'objectParameters' => [ ] , ] ; $ linkParameters = $ this -> getLinkParameters ( $ embed ) ; if ( $ linkParameters !== null ) { $ parameters [ 'linkParameters' ] = $ linkParameters ; } foreach ( $ embed -> attributes as $ attribute ) { if ( ! isset ( $ this -> excludedAttributes [ $ attribute -> localName ] ) && $ attribute -> localName !== 'url' && strpos ( $ attribute -> localName , EmbedLinking :: TEMP_PREFIX ) !== 0 ) { $ parameters [ 'objectParameters' ] [ $ attribute -> localName ] = $ attribute -> nodeValue ; } } return $ parameters ; }
Returns embed s parameters .
46,022
protected function getLinkParameters ( DOMElement $ embed ) { if ( ! $ embed -> hasAttribute ( 'url' ) ) { return null ; } $ target = $ embed -> getAttribute ( EmbedLinking :: TEMP_PREFIX . 'target' ) ; $ title = $ embed -> getAttribute ( EmbedLinking :: TEMP_PREFIX . 'title' ) ; $ id = $ embed -> getAttribute ( EmbedLinking :: TEMP_PREFIX . 'id' ) ; $ class = $ embed -> getAttribute ( EmbedLinking :: TEMP_PREFIX . 'class' ) ; $ resourceFragmentIdentifier = $ embed -> getAttribute ( EmbedLinking :: TEMP_PREFIX . 'anchor_name' ) ; $ resourceType = static :: LINK_RESOURCE_URL ; $ resourceId = null ; if ( $ embed -> hasAttribute ( EmbedLinking :: TEMP_PREFIX . 'object_id' ) ) { $ resourceType = static :: LINK_RESOURCE_CONTENT ; $ resourceId = $ embed -> getAttribute ( EmbedLinking :: TEMP_PREFIX . 'object_id' ) ; } elseif ( $ embed -> hasAttribute ( EmbedLinking :: TEMP_PREFIX . 'node_id' ) ) { $ resourceType = static :: LINK_RESOURCE_LOCATION ; $ resourceId = $ embed -> getAttribute ( EmbedLinking :: TEMP_PREFIX . 'node_id' ) ; } $ parameters = [ 'href' => $ embed -> getAttribute ( 'url' ) , 'resourceType' => $ resourceType , 'resourceId' => $ resourceId , 'wrapped' => $ this -> isLinkWrapped ( $ embed ) , ] ; if ( ! empty ( $ resourceFragmentIdentifier ) ) { $ parameters [ 'resourceFragmentIdentifier' ] = $ resourceFragmentIdentifier ; } if ( ! empty ( $ target ) ) { $ parameters [ 'target' ] = $ target ; } if ( ! empty ( $ title ) ) { $ parameters [ 'title' ] = $ title ; } if ( ! empty ( $ id ) ) { $ parameters [ 'id' ] = $ id ; } if ( ! empty ( $ class ) ) { $ parameters [ 'class' ] = $ class ; } return $ parameters ; }
Returns embed s link parameters or null if embed is not linked .
46,023
protected function flattenLinksInLinks ( DOMDocument $ document , $ contentFieldId ) { $ xpath = new DOMXPath ( $ document ) ; $ xpathExpression = '//link[parent::link]' ; $ links = $ xpath -> query ( $ xpathExpression ) ; foreach ( $ links as $ link ) { $ targetElement = $ link -> parentNode -> parentNode ; $ parentLink = $ link -> parentNode ; $ targetElement -> insertBefore ( $ link , $ parentLink ) ; $ targetElement -> insertBefore ( $ parentLink , $ link ) ; $ this -> log ( LogLevel :: NOTICE , "Found nested links. Flatten links where contentobject_attribute.id=$contentFieldId" ) ; } }
ezxmltext may contain link elements below another link element . This method flattens such structure .
46,024
private function markTemporaryParagraphs ( $ document ) { foreach ( $ document -> getElementsByTagName ( 'paragraph' ) as $ paragraph ) { if ( $ this -> isTemporary ( $ paragraph ) ) { $ paragraph -> setAttribute ( 'ez-temporary' , 1 ) ; } } }
Marks temporary paragraph with the ez - temporary attribute . Those paragraph are simply ignored when generating the HTML5 code of the field .
46,025
protected function containsBlock ( DOMElement $ paragraph ) { $ xpath = new DOMXPath ( $ paragraph -> ownerDocument ) ; $ containedExpression = $ this -> getContainmentMapXPathExpression ( false ) ; return $ xpath -> query ( $ containedExpression , $ paragraph ) -> length !== 0 || $ xpath -> query ( 'custom/paragraph' , $ paragraph ) -> length !== 0 || $ xpath -> query ( 'custom/section' , $ paragraph ) -> length !== 0 ; }
Check whether the paragraph contains a block element . The block elements are listed in the containment map . In addition the custom tags can also be a block element . This is detected by checking if the paragraph contains a custom element which also contains a paragraph .
46,026
public function setCustomStylesheets ( $ customStylesheets ) { $ this -> customStylesheets = [ ] ; if ( ! $ customStylesheets ) { return ; } foreach ( $ customStylesheets as $ stylesheet ) { if ( ! isset ( $ this -> customStylesheets [ $ stylesheet [ 'priority' ] ] ) ) { $ this -> customStylesheets [ $ stylesheet [ 'priority' ] ] = [ ] ; } $ this -> customStylesheets [ $ stylesheet [ 'priority' ] ] [ ] = $ stylesheet [ 'path' ] ; } }
Sets the custom stylesheets grouped by priority .
46,027
public function validate ( FieldDefinition $ fieldDefinition , SPIValue $ value ) { $ validationErrors = [ ] ; if ( $ this -> internalLinkValidator !== null ) { $ errors = $ this -> internalLinkValidator -> validate ( $ value -> xml ) ; foreach ( $ errors as $ error ) { $ validationErrors [ ] = new ValidationError ( $ error ) ; } } return $ validationErrors ; }
Validates a field .
46,028
protected function copyLinkAttributes ( DOMElement $ embed ) { $ link = $ embed -> parentNode ; if ( $ link -> hasAttribute ( 'object_id' ) ) { $ embed -> setAttribute ( static :: TEMP_PREFIX . 'object_id' , $ link -> getAttribute ( 'object_id' ) ) ; } if ( $ link -> hasAttribute ( 'node_id' ) ) { $ embed -> setAttribute ( static :: TEMP_PREFIX . 'node_id' , $ link -> getAttribute ( 'node_id' ) ) ; } if ( $ link -> hasAttribute ( 'anchor_name' ) ) { $ embed -> setAttribute ( static :: TEMP_PREFIX . 'anchor_name' , $ link -> getAttribute ( 'anchor_name' ) ) ; } if ( $ link -> hasAttribute ( 'target' ) ) { $ embed -> setAttribute ( static :: TEMP_PREFIX . 'target' , $ link -> getAttribute ( 'target' ) ) ; } if ( $ link -> hasAttribute ( 'xhtml:title' ) ) { $ embed -> setAttribute ( static :: TEMP_PREFIX . 'title' , $ link -> getAttribute ( 'xhtml:title' ) ) ; } if ( $ link -> hasAttribute ( 'xhtml:id' ) ) { $ embed -> setAttribute ( static :: TEMP_PREFIX . 'id' , $ link -> getAttribute ( 'xhtml:id' ) ) ; } if ( $ link -> hasAttribute ( 'class' ) ) { $ embed -> setAttribute ( static :: TEMP_PREFIX . 'class' , $ link -> getAttribute ( 'class' ) ) ; } if ( $ link -> hasAttribute ( 'url' ) ) { $ embed -> setAttribute ( static :: TEMP_PREFIX . 'url' , $ link -> getAttribute ( 'url' ) ) ; } if ( $ link -> hasAttribute ( 'url_id' ) ) { $ embed -> setAttribute ( static :: TEMP_PREFIX . 'url_id' , $ link -> getAttribute ( 'url_id' ) ) ; } }
Copies embed s link attributes to linked embed itself prefixed so they can be unambiguously recognized .
46,029
protected function unwrap ( DOMElement $ embed ) { $ link = $ embed -> parentNode ; $ childCount = 0 ; foreach ( $ link -> childNodes as $ node ) { if ( ! ( $ node -> nodeType === XML_TEXT_NODE && $ node -> isWhitespaceInElementContent ( ) ) ) { ++ $ childCount ; } } if ( $ childCount === 1 ) { $ link -> parentNode -> replaceChild ( $ embed , $ link ) ; } }
Unwraps embed element in the case when it is single content of its link .
46,030
public function clear ( ) { $ this -> allowed_file_extensions = null ; $ this -> error_messages = array ( ) ; $ this -> file_extensions_mime_types = null ; $ this -> files = array ( ) ; $ this -> input_file_name = null ; $ this -> max_file_size = null ; $ this -> max_image_dimensions = array ( ) ; $ this -> move_uploaded_queue = array ( ) ; $ this -> move_uploaded_to = '.' ; $ this -> new_file_name = null ; $ this -> overwrite = false ; $ this -> web_safe_file_name = true ; $ this -> security_scan = false ; $ this -> stop_on_failed_upload_multiple = true ; }
Clear all properties to its default values .
46,031
public function getUploadedData ( ) { if ( empty ( $ this -> move_uploaded_queue ) || ! is_array ( $ this -> move_uploaded_queue ) ) { return array ( ) ; } $ output = array ( ) ; foreach ( $ this -> move_uploaded_queue as $ key => $ queue_item ) { if ( is_array ( $ queue_item ) && array_key_exists ( 'name' , $ queue_item ) && array_key_exists ( 'tmp_name' , $ queue_item ) && array_key_exists ( 'new_name' , $ queue_item ) && array_key_exists ( 'move_uploaded_to' , $ queue_item ) && array_key_exists ( 'move_uploaded_status' , $ queue_item ) && $ queue_item [ 'move_uploaded_status' ] === 'success' ) { $ file_name_explode = explode ( '.' , $ queue_item [ 'name' ] ) ; $ file_extension = ( isset ( $ file_name_explode [ count ( $ file_name_explode ) - 1 ] ) ? $ file_name_explode [ count ( $ file_name_explode ) - 1 ] : null ) ; unset ( $ file_name_explode ) ; $ Finfo = new \ finfo ( ) ; $ mime = $ Finfo -> file ( $ queue_item [ 'move_uploaded_to' ] , FILEINFO_MIME_TYPE ) ; unset ( $ Finfo ) ; $ output [ $ key ] = array ( ) ; $ output [ $ key ] [ 'name' ] = $ queue_item [ 'name' ] ; $ output [ $ key ] [ 'extension' ] = $ file_extension ; $ output [ $ key ] [ 'size' ] = ( is_file ( $ queue_item [ 'move_uploaded_to' ] ) ? filesize ( $ queue_item [ 'move_uploaded_to' ] ) : 0 ) ; $ output [ $ key ] [ 'new_name' ] = $ queue_item [ 'new_name' ] ; $ output [ $ key ] [ 'full_path_new_name' ] = $ queue_item [ 'move_uploaded_to' ] ; $ output [ $ key ] [ 'mime' ] = $ mime ; $ output [ $ key ] [ 'md5_file' ] = ( is_file ( $ queue_item [ 'move_uploaded_to' ] ) ? md5_file ( $ queue_item [ 'move_uploaded_to' ] ) : null ) ; unset ( $ file_extension , $ mime ) ; } } return $ output ; }
Get the uploaded data .
46,032
protected function renameDuplicateFile ( $ file_name , $ loop_count = 1 ) { if ( ! file_exists ( $ this -> move_uploaded_to . DIRECTORY_SEPARATOR . $ file_name ) ) { return $ file_name ; } else { $ file_name_explode = explode ( '.' , $ file_name ) ; $ file_extension = ( isset ( $ file_name_explode [ count ( $ file_name_explode ) - 1 ] ) ? $ file_name_explode [ count ( $ file_name_explode ) - 1 ] : null ) ; unset ( $ file_name_explode [ count ( $ file_name_explode ) - 1 ] ) ; $ file_name_only = implode ( '.' , $ file_name_explode ) ; unset ( $ file_name_explode ) ; $ i = 1 ; $ found = true ; do { $ new_file_name = $ file_name_only . '_' . $ i . '.' . $ file_extension ; if ( file_exists ( $ this -> move_uploaded_to . DIRECTORY_SEPARATOR . $ new_file_name ) ) { $ found = true ; if ( $ i > 1000 ) { $ file_name = uniqid ( ) . '-' . str_replace ( '.' , '' , microtime ( true ) ) ; $ found = false ; } } else { $ file_name = $ new_file_name ; $ found = false ; } $ i ++ ; } while ( $ found === true ) ; unset ( $ file_extension , $ file_name_only , $ new_file_name ) ; return $ file_name ; } }
Rename the file where it is duplicate with existing file .
46,033
protected function setErrorMessage ( $ error_messages , $ code , $ errorAttributes = '' , $ errorFileName = '' , $ errorFileSize = '' , $ errorFileMime = '' ) { $ arg_list = func_get_args ( ) ; $ numargs = func_num_args ( ) ; for ( $ i = 0 ; $ i < $ numargs ; $ i ++ ) { if ( is_array ( $ arg_list ) && array_key_exists ( $ i , $ arg_list ) && ! is_scalar ( $ arg_list [ $ i ] ) ) { return false ; } elseif ( $ arg_list === false ) { return false ; } } unset ( $ arg_list , $ i , $ numargs ) ; $ this -> error_messages [ ] = $ error_messages ; $ this -> error_codes [ ] = array ( 'code' => $ code , 'errorAttributes' => $ errorAttributes , 'errorFileName' => $ errorFileName , 'errorFileSize' => $ errorFileSize , 'errorFileMime' => $ errorFileMime , ) ; }
Set the error message into error_messages and error_codes properties .
46,034
protected function setNewFileName ( ) { $ this -> new_file_name = trim ( $ this -> new_file_name ) ; if ( $ this -> new_file_name == null ) { if ( is_array ( $ this -> files [ $ this -> input_file_name ] ) && array_key_exists ( 'name' , $ this -> files [ $ this -> input_file_name ] ) ) { $ file_name_explode = explode ( '.' , $ this -> files [ $ this -> input_file_name ] [ 'name' ] ) ; unset ( $ file_name_explode [ count ( $ file_name_explode ) - 1 ] ) ; $ this -> new_file_name = implode ( '.' , $ file_name_explode ) ; unset ( $ file_name_explode ) ; } else { $ this -> setNewFileNameToRandom ( ) ; } } $ reserved_characters = array ( '\\' , '/' , '?' , '%' , '*' , ':' , '|' , '"' , '<' , '>' , '!' , '@' ) ; $ this -> new_file_name = str_replace ( $ reserved_characters , '' , $ this -> new_file_name ) ; unset ( $ reserved_characters ) ; if ( preg_match ( '#[^\.]+#iu' , $ this -> new_file_name ) == 0 ) { $ this -> setNewFileNameToRandom ( ) ; } $ reserved_words = array ( 'CON' , 'PRN' , 'AUX' , 'CLOCK$' , 'NUL' , 'COM1' , 'COM2' , 'COM3' , 'COM4' , 'COM5' , 'COM6' , 'COM7' , 'COM8' , 'COM9' , 'LPT1' , 'LPT2' , 'LPT3' , 'LPT4' , 'LPT5' , 'LPT6' , 'LPT7' , 'LPT8' , 'LPT9' , 'LST' , 'KEYBD$' , 'SCREEN$' , '$IDLE$' , 'CONFIG$' , '$Mft' , '$MftMirr' , '$LogFile' , '$Volume' , '$AttrDef' , '$Bitmap' , '$Boot' , '$BadClus' , '$Secure' , '$Upcase' , '$Extend' , '$Quota' , '$ObjId' , '$Reparse' , ) ; foreach ( $ reserved_words as $ reserved_word ) { if ( strtolower ( $ reserved_word ) == strtolower ( $ this -> new_file_name ) ) { $ this -> setNewFileNameToRandom ( ) ; } } unset ( $ reserved_word , $ reserved_words ) ; if ( $ this -> new_file_name == null ) { $ this -> setNewFileNameToRandom ( ) ; } }
Set the new file name if it was not set check for reserved file name and removed those characters .
46,035
protected function validateImageDimension ( ) { if ( empty ( $ this -> max_image_dimensions ) ) { return true ; } if ( is_array ( $ this -> files [ $ this -> input_file_name ] ) && array_key_exists ( 'tmp_name' , $ this -> files [ $ this -> input_file_name ] ) && is_file ( $ this -> files [ $ this -> input_file_name ] [ 'tmp_name' ] ) ) { $ image = getimagesize ( $ this -> files [ $ this -> input_file_name ] [ 'tmp_name' ] ) ; if ( $ image === false ) { return true ; } elseif ( is_array ( $ image ) && count ( $ image ) >= 2 ) { if ( $ image [ 0 ] <= $ this -> max_image_dimensions [ 0 ] && $ image [ 1 ] <= $ this -> max_image_dimensions [ 1 ] ) { return true ; } elseif ( $ image [ 0 ] <= 0 || $ image [ 1 ] <= 0 ) { $ this -> setErrorMessage ( sprintf ( static :: __ ( 'The uploaded image contain no image or multiple images. (%s).' ) , $ image [ 0 ] . 'x' . $ image [ 1 ] ) , 'RDU_IMG_NO_OR_MULTIPLE_IMAGES' , $ image [ 0 ] . 'x' . $ image [ 1 ] , $ this -> files [ $ this -> input_file_name ] [ 'name' ] , $ this -> files [ $ this -> input_file_name ] [ 'size' ] , $ this -> files [ $ this -> input_file_name ] [ 'type' ] ) ; return false ; } else { $ this -> setErrorMessage ( sprintf ( static :: __ ( 'The uploaded image dimensions are larger than allowed max dimensions. (%s &gt; %s).' ) , $ image [ 0 ] . 'x' . $ image [ 1 ] , $ this -> max_image_dimensions [ 0 ] . 'x' . $ this -> max_image_dimensions [ 1 ] ) , 'RDU_IMG_DIMENSION_OVER_MAX' , $ image [ 0 ] . 'x' . $ image [ 1 ] . ' &gt; ' . $ this -> max_image_dimensions [ 0 ] . 'x' . $ this -> max_image_dimensions [ 1 ] , $ this -> files [ $ this -> input_file_name ] [ 'name' ] , $ this -> files [ $ this -> input_file_name ] [ 'size' ] , $ this -> files [ $ this -> input_file_name ] [ 'type' ] ) ; return false ; } } else { return true ; } } return true ; }
Validate image dimension if uploaded file is image and size is smaller than specified max_image_dimensions .
46,036
protected function validateOptionsProperties ( ) { if ( ! is_array ( $ this -> allowed_file_extensions ) && $ this -> allowed_file_extensions != null ) { $ this -> allowed_file_extensions = array ( $ this -> allowed_file_extensions ) ; } if ( ! is_array ( $ this -> file_extensions_mime_types ) && $ this -> file_extensions_mime_types != null ) { $ this -> file_extensions_mime_types = null ; } if ( is_numeric ( $ this -> max_file_size ) && ! is_int ( $ this -> max_file_size ) ) { $ this -> max_file_size = intval ( $ this -> max_file_size ) ; } elseif ( ! is_int ( $ this -> max_file_size ) && $ this -> max_file_size != null ) { $ this -> max_file_size = null ; } if ( ! is_array ( $ this -> max_image_dimensions ) || ( is_array ( $ this -> max_image_dimensions ) && ( count ( $ this -> max_image_dimensions ) != 2 || ( count ( $ this -> max_image_dimensions ) == 2 && count ( $ this -> max_image_dimensions ) != count ( $ this -> max_image_dimensions , COUNT_RECURSIVE ) ) ) ) ) { $ this -> max_image_dimensions = array ( ) ; } else { if ( ! is_int ( $ this -> max_image_dimensions [ 0 ] ) || ! is_int ( $ this -> max_image_dimensions [ 1 ] ) ) { $ this -> max_image_dimensions = array ( ) ; } } if ( empty ( $ this -> move_uploaded_to ) ) { trigger_error ( static :: __ ( 'The move_uploaded_to property was not set' ) , E_USER_ERROR ) ; } if ( ! is_string ( $ this -> new_file_name ) && $ this -> new_file_name != null ) { $ this -> new_file_name = null ; } if ( ! is_bool ( $ this -> overwrite ) ) { $ this -> overwrite = false ; } if ( ! is_bool ( $ this -> web_safe_file_name ) ) { $ this -> web_safe_file_name = true ; } if ( ! is_bool ( $ this -> security_scan ) ) { $ this -> security_scan = false ; } if ( ! is_bool ( $ this -> stop_on_failed_upload_multiple ) ) { $ this -> stop_on_failed_upload_multiple = true ; } }
Validate that these options properties has properly set in the correct type .
46,037
public function countExecutions ( RequestBuilder $ requestBuilder ) { $ expectation = $ requestBuilder -> build ( ) ; $ expectation -> setResponse ( new Response ( ) ) ; $ uri = $ this -> createBaseUri ( ) -> withPath ( self :: API_EXECUTIONS_URL ) ; $ request = ( new PsrRequest ( ) ) -> withUri ( $ uri ) -> withMethod ( 'post' ) -> withHeader ( 'Content-Type' , 'application/json' ) -> withBody ( new StringStream ( json_encode ( $ expectation ) ) ) ; $ response = $ this -> connection -> send ( $ request ) ; if ( 200 === $ response -> getStatusCode ( ) ) { $ json = json_decode ( $ response -> getBody ( ) -> __toString ( ) ) ; return $ json -> count ; } $ this -> checkErrorResponse ( $ response ) ; }
Counts the amount of times a request was executed in phiremock .
46,038
public function setScenarioState ( ScenarioState $ scenarioState ) { $ uri = $ this -> createBaseUri ( ) -> withPath ( self :: API_SCENARIOS_URL ) ; $ request = ( new PsrRequest ( ) ) -> withUri ( $ uri ) -> withMethod ( 'put' ) -> withHeader ( 'Content-Type' , 'application/json' ) -> withBody ( new StringStream ( json_encode ( $ scenarioState ) ) ) ; $ response = $ this -> connection -> send ( $ request ) ; if ( 200 !== $ response -> getStatusCode ( ) ) { $ this -> checkErrorResponse ( $ response ) ; } }
Sets scenario state .
46,039
public function actions ( ) { return [ 'image-upload' => \ bizley \ contenttools \ actions \ UploadAction :: class , 'image-insert' => \ bizley \ contenttools \ actions \ InsertAction :: class , 'image-rotate' => \ bizley \ contenttools \ actions \ RotateAction :: class , ] ; }
Here is the setting for image handling ContentTools actions . Simple versions of these are provided by yii2 - content - tools so let s just use them . Remember to configure widget to know where to find them .
46,040
public function actionSave ( ) { if ( Yii :: $ app -> request -> isPost ) { $ page = Yii :: $ app -> request -> post ( 'page' ) ; $ model = Content :: findOne ( [ 'page' => $ page ] ) ; if ( $ model === null ) { $ model = new Content ( ) ; } $ model -> setAttributes ( [ 'data' => Yii :: $ app -> request -> post ( 'contentTools0' ) , 'page' => $ page , ] ) ; if ( ! $ model -> save ( ) ) { return $ this -> asJson ( [ 'errors' => $ model -> errors ] ) ; } return $ this -> asJson ( true ) ; } return $ this -> asJson ( [ 'errors' => [ 'No data sent in POST.' ] ] ) ; }
This action handles saving the content . Actual data is saved in database and represented by Content model .
46,041
public function upload ( ) { if ( ! $ this -> validate ( ) ) { return false ; } try { $ save_path = Yii :: getAlias ( $ this -> _uploadDir ) ; FileHelper :: createDirectory ( $ save_path ) ; $ image = $ this -> image -> baseName . '.' . $ this -> image -> extension ; if ( ! $ this -> image -> saveAs ( FileHelper :: normalizePath ( $ save_path . '/' . $ image ) ) ) { return false ; } $ this -> path = Yii :: getAlias ( $ save_path . '/' . $ image ) ; $ this -> url = Yii :: getAlias ( $ this -> _viewPath . '/' . $ image ) ; return true ; } catch ( Exception $ e ) { Yii :: error ( $ e -> getMessage ( ) ) ; } return false ; }
Validates and saves the image . Creates the folder to store images if necessary .
46,042
public function size ( string $ path ) : Promise { if ( ! @ \ file_exists ( $ path ) ) { return new Failure ( new FilesystemException ( "Path does not exist" ) ) ; } if ( ! @ \ is_file ( $ path ) ) { return new Failure ( new FilesystemException ( "Path is not a regular file" ) ) ; } if ( ( $ size = @ \ filesize ( $ path ) ) === false ) { return new Failure ( new FilesystemException ( \ error_get_last ( ) [ "message" ] ) ) ; } \ clearstatcache ( true , $ path ) ; return new Success ( $ size ) ; }
Retrieve the size in bytes of the file at the specified path .
46,043
public function isdir ( string $ path ) : Promise { if ( ! @ \ file_exists ( $ path ) ) { return new Success ( false ) ; } $ isDir = @ \ is_dir ( $ path ) ; \ clearstatcache ( true , $ path ) ; return new Success ( $ isDir ) ; }
Does the specified path exist and is it a directory?
46,044
public function isfile ( string $ path ) : Promise { if ( ! @ \ file_exists ( $ path ) ) { return new Success ( false ) ; } $ isFile = @ \ is_file ( $ path ) ; \ clearstatcache ( true , $ path ) ; return new Success ( $ isFile ) ; }
Does the specified path exist and is it a file?
46,045
public function mtime ( string $ path ) : Promise { if ( ! @ \ file_exists ( $ path ) ) { return new Failure ( new FilesystemException ( "Path does not exist" ) ) ; } $ mtime = @ \ filemtime ( $ path ) ; \ clearstatcache ( true , $ path ) ; return new Success ( $ mtime ) ; }
Retrieve the path s last modification time as a unix timestamp .
46,046
public function atime ( string $ path ) : Promise { if ( ! @ \ file_exists ( $ path ) ) { return new Failure ( new FilesystemException ( "Path does not exist" ) ) ; } $ atime = @ \ fileatime ( $ path ) ; \ clearstatcache ( true , $ path ) ; return new Success ( $ atime ) ; }
Retrieve the path s last access time as a unix timestamp .
46,047
public function ctime ( string $ path ) : Promise { if ( ! @ \ file_exists ( $ path ) ) { return new Failure ( new FilesystemException ( "Path does not exist" ) ) ; } $ ctime = @ \ filectime ( $ path ) ; \ clearstatcache ( true , $ path ) ; return new Success ( $ ctime ) ; }
Retrieve the path s creation time as a unix timestamp .
46,048
public static function fromString ( $ startTime , $ endTime ) { return new self ( Time :: fromString ( $ startTime ) , Time :: fromString ( $ endTime ) ) ; }
Creates a new interval from time strings .
46,049
protected function setDayOfWeek ( $ dayOfWeek ) { if ( ! in_array ( $ dayOfWeek , Days :: toArray ( ) ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Invalid day of week "%s".' , $ dayOfWeek ) ) ; } $ this -> dayOfWeek = $ dayOfWeek ; }
Sets the day of week .
46,050
protected function setOpeningIntervals ( array $ openingIntervals ) { if ( empty ( $ openingIntervals ) ) { throw new \ InvalidArgumentException ( 'The day must have at least one opening interval.' ) ; } $ this -> openingIntervals = [ ] ; foreach ( $ openingIntervals as $ openingInterval ) { if ( ! is_array ( $ openingInterval ) || ! isset ( $ openingInterval [ 0 ] ) || ! isset ( $ openingInterval [ 1 ] ) ) { throw new \ InvalidArgumentException ( 'Each interval must be an array containing opening and closing times.' ) ; } $ this -> openingIntervals [ ] = TimeInterval :: fromString ( $ openingInterval [ 0 ] , $ openingInterval [ 1 ] ) ; } usort ( $ this -> openingIntervals , function ( TimeInterval $ a , TimeInterval $ b ) { return ( $ a -> getStart ( ) > $ b -> getStart ( ) ) ? 1 : - 1 ; } ) ; }
Sets the opening intervals .
46,051
private function getClosestDateBefore ( \ DateTime $ date ) { $ tmpDate = clone $ date ; $ dayOfWeek = ( int ) $ tmpDate -> format ( 'N' ) ; $ time = Time :: fromDate ( $ tmpDate ) ; if ( ! $ this -> holidays -> isHoliday ( $ tmpDate ) && null !== $ day = $ this -> getDay ( $ dayOfWeek ) ) { if ( null !== $ closestTime = $ day -> getClosestOpeningTimeBefore ( $ time , $ tmpDate ) ) { $ tmpDate -> setTime ( $ closestTime -> getHours ( ) , $ closestTime -> getMinutes ( ) , $ closestTime -> getSeconds ( ) ) ; return $ tmpDate ; } } $ tmpDate = $ this -> getDateBefore ( $ tmpDate ) ; while ( $ this -> holidays -> isHoliday ( $ tmpDate ) ) { $ tmpDate = $ this -> getDateBefore ( $ tmpDate ) ; } $ closestDay = $ this -> getClosestDayBefore ( ( int ) $ tmpDate -> format ( 'N' ) ) ; $ closingTime = $ closestDay -> getClosingTime ( $ tmpDate ) ; $ tmpDate -> setTime ( $ closingTime -> getHours ( ) , $ closingTime -> getMinutes ( ) , $ closingTime -> getSeconds ( ) ) ; return $ tmpDate ; }
Gets the closest business date before the given date .
46,052
private function getClosestDateAfter ( \ DateTime $ date ) { $ tmpDate = clone $ date ; $ dayOfWeek = ( int ) $ tmpDate -> format ( 'N' ) ; $ time = Time :: fromDate ( $ tmpDate ) ; if ( ! $ this -> holidays -> isHoliday ( $ tmpDate ) && null !== $ day = $ this -> getDay ( $ dayOfWeek ) ) { if ( null !== $ closestTime = $ day -> getClosestOpeningTimeAfter ( $ time , $ tmpDate ) ) { $ tmpDate -> setTime ( $ closestTime -> getHours ( ) , $ closestTime -> getMinutes ( ) , $ closestTime -> getSeconds ( ) ) ; return $ tmpDate ; } } $ tmpDate = $ this -> getDateAfter ( $ tmpDate ) ; while ( $ this -> holidays -> isHoliday ( $ tmpDate ) ) { $ tmpDate = $ this -> getDateAfter ( $ tmpDate ) ; } $ closestDay = $ this -> getClosestDayBefore ( ( int ) $ tmpDate -> format ( 'N' ) ) ; $ closingTime = $ closestDay -> getOpeningTime ( $ tmpDate ) ; $ tmpDate -> setTime ( $ closingTime -> getHours ( ) , $ closingTime -> getMinutes ( ) , $ closingTime -> getSeconds ( ) ) ; return $ tmpDate ; }
Gets the closest business date after the given date .
46,053
private function getDayBefore ( $ dayNumber ) { $ tmpDayNumber = $ dayNumber ; for ( $ i = 0 ; $ i < 6 ; $ i ++ ) { $ tmpDayNumber = ( Days :: MONDAY === $ tmpDayNumber ) ? Days :: SUNDAY : -- $ tmpDayNumber ; if ( null !== $ day = $ this -> getDay ( $ tmpDayNumber ) ) { return $ day ; } } return $ this -> getDay ( $ dayNumber ) ; }
Gets the business day before the day number .
46,054
private function getDay ( $ dayNumber ) { return isset ( $ this -> days [ $ dayNumber ] ) ? $ this -> days [ $ dayNumber ] : null ; }
Gets the day corresponding to the day number .
46,055
public static function fromString ( $ time ) { try { $ date = new \ DateTime ( $ time ) ; } catch ( \ Exception $ e ) { throw new \ InvalidArgumentException ( sprintf ( 'Invalid time "%s".' , $ time ) ) ; } return self :: fromDate ( $ date ) ; }
Creates a new time from a string .
46,056
public static function fromDate ( \ DateTime $ date ) { return new self ( $ date -> format ( 'H' ) , $ date -> format ( 'i' ) , $ date -> format ( 's' ) ) ; }
Creates a new time from a date .
46,057
public static function toString ( $ dayOfWeek ) { return isset ( self :: $ strings [ $ dayOfWeek ] ) ? self :: $ strings [ $ dayOfWeek ] : null ; }
Returns a string representation of a day .
46,058
private function evaluateOpeningIntervals ( \ DateTime $ context ) { $ contextHash = $ context -> format ( \ DateTime :: ISO8601 ) ; if ( ! isset ( $ this -> openingIntervalsCache [ $ contextHash ] ) ) { $ intervals = call_user_func ( $ this -> openingIntervalsEvaluator , $ context ) ; if ( ! is_array ( $ intervals ) ) { throw new \ RuntimeException ( 'The special day evaluator must return an array of opening intervals.' ) ; } $ this -> openingIntervalsCache [ $ contextHash ] = $ intervals ; } $ this -> setOpeningIntervals ( $ this -> openingIntervalsCache [ $ contextHash ] ) ; }
Evaluates the opening intervals .
46,059
public function create ( FilesystemInterface $ cache , $ path ) { $ stream = $ cache -> readStream ( $ path ) ; $ response = new StreamedResponse ( ) ; $ response -> headers -> set ( 'Content-Type' , $ cache -> getMimetype ( $ path ) ) ; $ response -> headers -> set ( 'Content-Length' , $ cache -> getSize ( $ path ) ) ; $ response -> setPublic ( ) ; $ response -> setMaxAge ( 31536000 ) ; $ response -> setExpires ( date_create ( ) -> modify ( '+1 years' ) ) ; if ( $ this -> request ) { $ response -> setLastModified ( date_create ( ) -> setTimestamp ( $ cache -> getTimestamp ( $ path ) ) ) ; $ response -> isNotModified ( $ this -> request ) ; } $ response -> setCallback ( function ( ) use ( $ stream ) { if ( ftell ( $ stream ) !== 0 ) { rewind ( $ stream ) ; } fpassthru ( $ stream ) ; fclose ( $ stream ) ; } ) ; return $ response ; }
Create the response .
46,060
static function parse ( $ jobLine ) { $ parts = preg_split ( '@ @' , $ jobLine , NULL , PREG_SPLIT_NO_EMPTY ) ; if ( count ( $ parts ) < 5 ) { throw new \ InvalidArgumentException ( 'Wrong job number of arguments.' ) ; } $ command = implode ( ' ' , array_slice ( $ parts , 5 ) ) ; $ lastRunTime = $ logFile = $ logSize = $ errorFile = $ errorSize = $ comments = null ; if ( strpos ( $ command , '#' ) ) { list ( $ command , $ comment ) = explode ( '#' , $ command ) ; $ comments = trim ( $ comment ) ; } if ( strpos ( $ command , '2>>' ) ) { list ( $ command , $ errorFile ) = explode ( '2>>' , $ command ) ; $ errorFile = trim ( $ errorFile ) ; } if ( strpos ( $ command , '>>' ) ) { list ( $ command , $ logPart ) = explode ( '>>' , $ command ) ; $ logPart = explode ( ' ' , trim ( $ logPart ) ) ; $ logFile = trim ( $ logPart [ 0 ] ) ; } if ( isset ( $ logFile ) && file_exists ( $ logFile ) ) { $ lastRunTime = filemtime ( $ logFile ) ; $ logSize = filesize ( $ logFile ) ; } if ( isset ( $ errorFile ) && file_exists ( $ errorFile ) ) { $ lastRunTime = max ( $ lastRunTime ? : 0 , filemtime ( $ errorFile ) ) ; $ errorSize = filesize ( $ errorFile ) ; } $ command = trim ( $ command ) ; $ status = 'error' ; if ( $ logSize === null && $ errorSize === null ) { $ status = 'unknown' ; } else if ( $ errorSize === null || $ errorSize == 0 ) { $ status = 'success' ; } $ job = new Job ( ) ; $ job -> setMinute ( $ parts [ 0 ] ) -> setHour ( $ parts [ 1 ] ) -> setDayOfMonth ( $ parts [ 2 ] ) -> setMonth ( $ parts [ 3 ] ) -> setDayOfWeek ( $ parts [ 4 ] ) -> setCommand ( $ command ) -> setErrorFile ( $ errorFile ) -> setErrorSize ( $ errorSize ) -> setLogFile ( $ logFile ) -> setLogSize ( $ logSize ) -> setComments ( $ comments ) -> setLastRunTime ( $ lastRunTime ) -> setStatus ( $ status ) ; return $ job ; }
Parse crontab line into Job object
46,061
private function generateHash ( ) { $ this -> hash = hash ( 'md5' , serialize ( array ( strval ( $ this -> getMinute ( ) ) , strval ( $ this -> getHour ( ) ) , strval ( $ this -> getDayOfMonth ( ) ) , strval ( $ this -> getMonth ( ) ) , strval ( $ this -> getDayOfWeek ( ) ) , strval ( $ this -> getCommand ( ) ) , ) ) ) ; return $ this ; }
Generate a unique hash related to the job entries
46,062
public function getEntries ( ) { return array ( $ this -> getMinute ( ) , $ this -> getHour ( ) , $ this -> getDayOfMonth ( ) , $ this -> getMonth ( ) , $ this -> getDayOfWeek ( ) , $ this -> getCommand ( ) , $ this -> prepareLog ( ) , $ this -> prepareError ( ) , $ this -> prepareComments ( ) , ) ; }
Get an array of job entries
46,063
public function render ( ) { if ( null === $ this -> getCommand ( ) ) { throw new \ InvalidArgumentException ( 'You must specify a command to run.' ) ; } $ line = trim ( implode ( " " , $ this -> getEntries ( ) ) ) ; return $ line ; }
Render the job for crontab
46,064
public function getErrorContent ( ) { if ( $ this -> getErrorFile ( ) && file_exists ( $ this -> getErrorFile ( ) ) ) { return file_get_contents ( $ this -> getErrorFile ( ) ) ; } else { return null ; } }
Return the error file content
46,065
public function getLogContent ( ) { if ( $ this -> getLogFile ( ) && file_exists ( $ this -> getLogFile ( ) ) ) { return file_get_contents ( $ this -> getLogFile ( ) ) ; } else { return null ; } }
Return the log file content
46,066
public function setHour ( $ hour ) { if ( ! preg_match ( self :: $ _regex [ 'hour' ] , $ hour ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Hour "%s" is incorect' , $ hour ) ) ; } $ this -> hour = $ hour ; return $ this -> generateHash ( ) ; }
Set the hour
46,067
public function setDayOfMonth ( $ dayOfMonth ) { if ( ! preg_match ( self :: $ _regex [ 'dayOfMonth' ] , $ dayOfMonth ) ) { throw new \ InvalidArgumentException ( sprintf ( 'DayOfMonth "%s" is incorect' , $ dayOfMonth ) ) ; } $ this -> dayOfMonth = $ dayOfMonth ; return $ this -> generateHash ( ) ; }
Set the day of month
46,068
public function setMonth ( $ month ) { if ( ! preg_match ( self :: $ _regex [ 'month' ] , $ month ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Month "%s" is incorect' , $ month ) ) ; } $ this -> month = $ month ; return $ this -> generateHash ( ) ; }
Set the month
46,069
public function setDayOfWeek ( $ dayOfWeek ) { if ( ! preg_match ( self :: $ _regex [ 'dayOfWeek' ] , $ dayOfWeek ) ) { throw new \ InvalidArgumentException ( sprintf ( 'DayOfWeek "%s" is incorect' , $ dayOfWeek ) ) ; } $ this -> dayOfWeek = $ dayOfWeek ; return $ this -> generateHash ( ) ; }
Set the day of week
46,070
public function setCommand ( $ command ) { if ( ! preg_match ( self :: $ _regex [ 'command' ] , $ command ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Command "%s" is incorect' , $ command ) ) ; } $ this -> command = $ command ; return $ this -> generateHash ( ) ; }
Set the command
46,071
public static function parse ( $ varLine ) { $ parts = explode ( '=' , $ varLine , 2 ) ; if ( ! $ parts || count ( $ parts ) !== 2 ) { throw new \ InvalidArgumentException ( "Line does not appear to contain a variable" ) ; } $ variable = new Variable ( ) ; $ variable -> setName ( trim ( array_shift ( $ parts ) ) ) -> setValue ( trim ( array_shift ( $ parts ) ) ) ; return $ variable ; }
Parse a variable line
46,072
protected function crontabCommand ( Crontab $ crontab ) { $ cmd = $ this -> getCrontabExecutable ( ) ; if ( $ crontab -> getUser ( ) ) { $ cmd .= sprintf ( ' -u %s ' , $ crontab -> getUser ( ) ) ; } return $ cmd ; }
Calcuates crontab command
46,073
public function writeToFile ( Crontab $ crontab , $ filename ) { if ( ! is_writable ( $ filename ) ) { throw new \ InvalidArgumentException ( 'File ' . $ filename . ' is not writable.' ) ; } file_put_contents ( $ filename , $ crontab -> render ( ) . PHP_EOL ) ; return $ this ; }
Write the current crons to a file .
46,074
public function hasShared ( $ abstract , $ checkMode = null ) { $ exists = isset ( $ this -> _instances [ $ abstract ] ) ; return ! $ exists || $ checkMode === null ? $ exists : $ this -> _instances [ $ abstract ] [ 'mode' ] === $ checkMode ; }
Check to see if an abstract has a shared instance already bound
46,075
public function handle ( Context $ c ) : Response { $ this -> setContext ( $ c ) ; $ this -> _callStartTime = $ this -> _callStartTime ? : microtime ( true ) ; return parent :: handle ( $ c ) ; }
Standard route handler with call time set
46,076
protected function _getRouteMethods ( Request $ r , string $ method ) { $ method = ucfirst ( $ method ) ; if ( $ r -> isXmlHttpRequest ( ) ) { yield 'ajax' . $ method ; yield 'ajax' . ucfirst ( strtolower ( $ r -> getMethod ( ) ) ) . $ method ; } yield strtolower ( $ r -> getMethod ( ) ) . $ method ; yield 'process' . $ method ; return null ; }
Yield methods to attempt
46,077
protected function _prepareResponse ( Context $ c , $ result , $ buffer = null ) { if ( $ result instanceof ContextAware ) { $ result -> setContext ( $ c ) ; } if ( $ this -> _callStartTime && $ result instanceof CubexResponse ) { return $ result -> setCallStartTime ( $ this -> _callStartTime ) ; } if ( $ result instanceof Response ) { return $ result ; } if ( $ result instanceof Renderable ) { return $ this -> _makeCubexResponse ( $ result -> render ( ) ) ; } if ( $ result instanceof ISafeHtmlProducer ) { return $ this -> _makeCubexResponse ( $ result -> produceSafeHTML ( ) -> getContent ( ) ) ; } $ result = parent :: _prepareResponse ( $ c , $ result , $ buffer ) ; try { Strings :: stringable ( $ result ) ; return $ this -> _makeCubexResponse ( $ result ) ; } catch ( \ InvalidArgumentException $ e ) { } return $ result ; }
Convert a route response into a valid Response
46,078
protected function _processRoute ( Context $ c , $ handler , & $ response ) { if ( $ handler === null ) { throw new \ RuntimeException ( ConditionHandler :: ERROR_NO_HANDLER , 500 ) ; } throw new \ RuntimeException ( self :: ERROR_NO_ROUTE , 404 ) ; }
If all else fails push the route result through this method
46,079
public function handle ( Context $ c ) : Response { $ response = null ; $ this -> setContext ( $ c ) ; $ this -> _callStartTime = $ this -> _callStartTime ? : microtime ( true ) ; if ( $ this -> canProcess ( $ response ) !== true ) { if ( $ response instanceof Response ) { return $ this -> _prepareResponse ( $ c , $ response , null ) ; } throw new \ Exception ( self :: ERROR_ACCESS_DENIED , 403 ) ; } return parent :: handle ( $ c ) ; }
Standard route handler pre - authenticated
46,080
public function configure ( ConfigProviderInterface $ cfg ) { if ( $ this -> _configured ) { return $ this ; } try { $ config = $ cfg -> getSection ( 'console' ) ; $ commands = $ config -> getItem ( 'commands' , [ ] ) ; $ patterns = $ config -> getItem ( 'patterns' , [ ] ) ; } catch ( \ Throwable $ e ) { $ commands = $ patterns = [ ] ; } $ this -> _searchPatterns = array_merge ( $ this -> _searchPatterns , $ patterns ) ; foreach ( $ commands as $ name => $ class ) { $ command = $ this -> getCommandByString ( $ class ) ; if ( $ command !== null ) { if ( ! is_int ( $ name ) ) { $ command -> setName ( $ name ) ; } $ this -> add ( $ command ) ; } } $ this -> _configured = true ; return $ this ; }
Pull the configuration from cubex and setup resolving patterns and defined command lists
46,081
public function find ( $ name ) { try { return parent :: find ( $ name ) ; } catch ( \ Throwable $ e ) { $ command = $ this -> getCommandByString ( $ name , true ) ; if ( $ command !== null ) { $ this -> add ( $ command ) ; return $ this -> get ( $ name ) ; } throw $ e ; } }
Find a command and fail over to namespaced class split on .
46,082
protected function _createFromActionableMethod ( \ ReflectionClass $ class ) { if ( $ class -> hasMethod ( 'executeCommand' ) ) { $ methodName = 'executeCommand' ; } else if ( $ class -> hasMethod ( 'process' ) ) { $ methodName = 'process' ; } else { return null ; } $ method = $ class -> getMethod ( $ methodName ) ; $ addedArguments = false ; $ propBlock = new DocBlockParser ( $ method -> getDocComment ( ) ) ; $ descriptions = [ ] ; foreach ( $ propBlock -> getTags ( ) as $ name => $ description ) { $ tagName = $ name ; $ descriptions [ $ tagName ] = $ description ; } foreach ( $ method -> getParameters ( ) as $ paramNum => $ parameter ) { if ( $ paramNum < 2 && $ methodName == 'executeCommand' ) { continue ; } $ mode = InputArgument :: REQUIRED ; $ default = null ; if ( $ parameter -> isDefaultValueAvailable ( ) ) { $ mode = InputArgument :: OPTIONAL ; $ default = $ parameter -> getDefaultValue ( ) ; } $ this -> addArgument ( $ parameter -> name , $ parameter -> isArray ( ) ? $ mode | InputArgument :: IS_ARRAY : $ mode , isset ( $ descriptions [ $ parameter -> name ] ) ? $ descriptions [ $ parameter -> name ] : '' , $ default ) ; $ addedArguments = true ; } return $ addedArguments ; }
Create arguments from your executeCommand method parameters
46,083
protected function _createOptionsFromPublic ( \ ReflectionClass $ class ) { $ properties = $ class -> getProperties ( \ ReflectionProperty :: IS_PUBLIC ) ; if ( empty ( $ properties ) ) { return null ; } foreach ( $ properties as $ property ) { $ propBlock = new DocBlockParser ( $ property -> getDocComment ( ) ) ; $ short = null ; $ description = $ propBlock -> getSummary ( ) ; $ mode = InputOption :: VALUE_OPTIONAL ; if ( $ propBlock -> hasTag ( 'short' ) ) { $ short = $ propBlock -> getTag ( 'short' ) ; } if ( $ propBlock -> hasTag ( 'description' ) ) { $ description = $ propBlock -> getTag ( 'description' ) ; } if ( $ propBlock -> hasTag ( 'valuerequired' ) ) { $ mode = InputOption :: VALUE_REQUIRED ; } if ( $ propBlock -> hasTag ( 'flag' ) ) { $ mode = InputOption :: VALUE_NONE ; } $ this -> addOption ( $ property -> name , $ short , $ mode , $ description , $ property -> getValue ( $ this ) ) ; } return null ; }
Create options and arguments from the public properties on your command
46,084
public function getMethodName ( ) { if ( ! empty ( $ this -> methodRef ) ) { return substr ( $ this -> methodRef , strpos ( $ this -> methodRef , ':' ) + 1 ) ; } return null ; }
Gets the method name of API .
46,085
public function dump ( $ requestId , $ request , $ response ) { if ( empty ( $ requestId ) ) { throw new \ InvalidArgumentException ( 'The request ID cannot be empty.' ) ; } $ dir = $ this -> rootDir . '/' . substr ( $ requestId , 0 , 2 ) . '/' . substr ( $ requestId , 2 , 1 ) ; $ this -> ensureDirectoryExists ( $ dir ) ; $ this -> saveFile ( $ dir . '/' . $ requestId . '_req.data' , $ request ) ; $ this -> saveFile ( $ dir . '/' . $ requestId . '_resp.data' , $ response ) ; }
Dumps data of request and response to storage .
46,086
public function dumpLastRequest ( SoapClient $ client ) { $ requestId = $ client -> getRequestId ( ) ; if ( ! empty ( $ requestId ) ) { $ this -> dump ( $ requestId , $ client -> getLastRequest ( ) , $ client -> getLastResponse ( ) ) ; } }
Dumps data of the last request .
46,087
private function fixupRawTag ( $ rawValue ) { if ( 0 === strpos ( $ rawValue , 'v' ) ) { $ rawValue = substr ( $ rawValue , 1 ) ; } $ foundIt = strpos ( $ rawValue , '+' ) ; if ( false !== $ foundIt ) { $ rawValue = substr ( $ rawValue , 0 , $ foundIt ) ; } $ rawValue = strtr ( $ rawValue , [ '.alpha' => '-alpha' , '.beta' => '-beta' , '.dev' => '-dev' ] ) ; $ pieces = explode ( '.' , $ rawValue ) ; $ count = count ( $ pieces ) ; if ( 0 == $ count ) { $ pieces [ ] = '0' ; $ count = 1 ; } for ( $ add = $ count ; $ add < 3 ; ++ $ add ) { $ pieces [ ] = '0' ; } $ return = implode ( '.' , array_slice ( $ pieces , 0 , 3 ) ) ; return $ return ; }
Why do we have to do this? Your guess is as good as mine . The only flaw I ve seen in the semver lib we re using and the regex s in there are too complicated to mess with .
46,088
public function compile ( $ pharFile = 'bowerphp.phar' ) { if ( file_exists ( $ pharFile ) ) { unlink ( $ pharFile ) ; } $ phar = new \ Phar ( $ pharFile , 0 , 'bowerphp.phar' ) ; $ phar -> setSignatureAlgorithm ( \ Phar :: SHA1 ) ; $ phar -> startBuffering ( ) ; $ finder = new Finder ( ) ; $ finder -> files ( ) -> ignoreVCS ( true ) -> name ( '*.php' ) -> notName ( 'Compiler.php' ) -> notName ( 'ClassLoader.php' ) -> in ( __DIR__ . '/..' ) ; foreach ( $ finder as $ file ) { $ this -> addFile ( $ phar , $ file ) ; } $ finder = new Finder ( ) ; $ finder -> files ( ) -> ignoreVCS ( true ) -> name ( '*.php' ) -> name ( '*.pem' ) -> name ( '*.pem.md5' ) -> exclude ( 'Tests' ) -> in ( __DIR__ . '/../../vendor/symfony/' ) -> in ( __DIR__ . '/../../vendor/guzzle/guzzle/src/' ) -> in ( __DIR__ . '/../../vendor/ircmaxell/password-compat/lib/' ) -> in ( __DIR__ . '/../../vendor/paragonie/random_compat/lib/' ) -> in ( __DIR__ . '/../../vendor/knplabs/github-api/lib/' ) -> in ( __DIR__ . '/../../vendor/samsonasik/package-versions/src/PackageVersions/' ) -> in ( __DIR__ . '/../../vendor/vierbergenlars/php-semver/src/vierbergenlars/LibJs/' ) -> in ( __DIR__ . '/../../vendor/vierbergenlars/php-semver/src/vierbergenlars/SemVer/' ) -> in ( __DIR__ . '/../../vendor/hamcrest/hamcrest-php/hamcrest/' ) ; foreach ( $ finder as $ file ) { $ this -> addFile ( $ phar , $ file ) ; } $ this -> addFile ( $ phar , new \ SplFileInfo ( __DIR__ . '/../../vendor/autoload.php' ) ) ; $ this -> addFile ( $ phar , new \ SplFileInfo ( __DIR__ . '/../../vendor/composer/autoload_psr4.php' ) ) ; $ this -> addFile ( $ phar , new \ SplFileInfo ( __DIR__ . '/../../vendor/composer/autoload_files.php' ) ) ; $ this -> addFile ( $ phar , new \ SplFileInfo ( __DIR__ . '/../../vendor/composer/autoload_namespaces.php' ) ) ; $ this -> addFile ( $ phar , new \ SplFileInfo ( __DIR__ . '/../../vendor/composer/autoload_classmap.php' ) ) ; $ this -> addFile ( $ phar , new \ SplFileInfo ( __DIR__ . '/../../vendor/composer/autoload_real.php' ) ) ; $ this -> addFile ( $ phar , new \ SplFileInfo ( __DIR__ . '/../../vendor/composer/autoload_static.php' ) ) ; if ( file_exists ( __DIR__ . '/../../vendor/composer/include_paths.php' ) ) { $ this -> addFile ( $ phar , new \ SplFileInfo ( __DIR__ . '/../../vendor/composer/include_paths.php' ) ) ; } $ this -> addFile ( $ phar , new \ SplFileInfo ( __DIR__ . '/../../vendor/composer/ClassLoader.php' ) ) ; $ this -> addBin ( $ phar ) ; $ phar -> setStub ( $ this -> getStub ( ) ) ; $ phar -> stopBuffering ( ) ; if ( $ this -> gz ) { $ phar -> compressFiles ( \ Phar :: GZ ) ; } $ this -> addFile ( $ phar , new \ SplFileInfo ( __DIR__ . '/../../LICENSE' ) , false ) ; unset ( $ phar ) ; chmod ( 'bowerphp.phar' , 0700 ) ; }
Compiles bower into a single phar file
46,089
protected function logHttp ( Client $ client , OutputInterface $ output ) { $ guzzle = $ client -> getHttpClient ( ) ; if ( OutputInterface :: VERBOSITY_DEBUG <= $ output -> getVerbosity ( ) ) { $ logger = function ( $ message ) use ( $ output ) { $ finfo = new \ finfo ( FILEINFO_MIME ) ; $ msg = ( 'text' == substr ( $ finfo -> buffer ( $ message ) , 0 , 4 ) ) ? $ message : '(binary string)' ; $ output -> writeln ( '<info>Guzzle</info> ' . $ msg ) ; } ; $ logAdapter = new ClosureLogAdapter ( $ logger ) ; $ logPlugin = new LogPlugin ( $ logAdapter , MessageFormatter :: DEBUG_FORMAT ) ; $ guzzle -> addSubscriber ( $ logPlugin ) ; } }
Debug HTTP interactions
46,090
public function getUnits ( ) { $ headers = $ this -> __getLastResponseHeaders ( ) ; if ( ! empty ( $ headers ) && preg_match ( '@^Units: (\d+)/(\d+)/(\d+)@m' , $ headers , $ m ) ) { return new Units ( $ m [ 1 ] , $ m [ 2 ] , $ m [ 3 ] ) ; } return new Units ( - 1 , - 1 , - 1 ) ; }
Gets info about units for the last request .
46,091
public function onException ( FailCallEvent $ event ) { $ exception = $ event -> getException ( ) ; $ logLevel = $ this -> getLogLevel ( $ exception ) ; if ( $ exception instanceof NetworkException ) { $ this -> logger -> log ( $ logLevel , 'Call {method} completed with network error: {error}' , [ 'method' => $ event -> getMethodRef ( ) , 'login' => $ event -> getUser ( ) -> getLogin ( ) , 'request_id' => $ event -> getRequestId ( ) , 'error' => $ exception -> getMessage ( ) , ] ) ; } else { $ message = sprintf ( 'Call {method} completed with exception %s: %s' , get_class ( $ exception ) , $ exception -> getMessage ( ) ) ; $ this -> logger -> log ( $ logLevel , $ message , [ 'method' => $ event -> getMethodRef ( ) , 'request_id' => $ event -> getRequestId ( ) , 'login' => $ event -> getUser ( ) -> getLogin ( ) , 'code' => $ exception -> getCode ( ) , 'exception' => $ exception , ] ) ; } }
Logs the thrown exception .
46,092
public function setDefinition ( $ reportDefinition ) { if ( $ reportDefinition instanceof ReportDefinitionBuilder ) { $ reportDefinition = $ reportDefinition -> build ( ) ; } $ this -> definition = $ reportDefinition ; return $ this ; }
Sets the report definition .
46,093
public function createFinanceToken ( $ methodName , $ operationNum ) { if ( empty ( $ this -> options [ 'master_token' ] ) ) { throw new \ LogicException ( 'The finance token cannot be created when the master token is empty.' ) ; } if ( empty ( $ this -> options [ 'login' ] ) ) { throw new \ LogicException ( 'The finance token cannot be created when the login is empty.' ) ; } return hash ( 'sha256' , $ this -> options [ 'master_token' ] . $ operationNum . $ methodName . $ this -> options [ 'login' ] ) ; }
Creates the finance token .
46,094
protected function setDefaultOptions ( OptionsResolver $ resolver ) { $ loginNormalizer = function ( Options $ options , $ value ) { if ( is_string ( $ value ) ) { return strtolower ( str_replace ( '.' , '-' , $ value ) ) ; } return $ value ; } ; $ invokerNormalizer = function ( Options $ options , $ value ) { if ( null === $ value ) { return new Invoker ( $ options [ 'retry_max_attempts' ] , $ options [ 'retry_factor' ] , $ options [ 'retry_max_delay' ] ) ; } return $ value ; } ; $ resolver -> setRequired ( [ 'access_token' ] ) -> setDefaults ( [ 'locale' => self :: LOCALE_EN , 'master_token' => null , 'login' => null , 'sandbox' => false , 'use_operator_units' => false , 'soap_options' => [ ] , 'invoker' => null , 'retry_factor' => 1 , 'retry_max_attempts' => 3 , 'retry_max_delay' => 60 , ] ) -> setAllowedValues ( 'locale' , [ self :: LOCALE_EN , self :: LOCALE_RU , self :: LOCALE_UA ] ) -> setAllowedTypes ( 'master_token' , [ 'null' , 'string' ] ) -> setAllowedTypes ( 'login' , [ 'null' , 'string' ] ) -> setAllowedTypes ( 'access_token' , 'string' ) -> setAllowedTypes ( 'sandbox' , 'bool' ) -> setAllowedTypes ( 'use_operator_units' , 'bool' ) -> setAllowedTypes ( 'invoker' , [ 'null' , 'callable' ] ) -> setAllowedTypes ( 'retry_factor' , 'int' ) -> setAllowedTypes ( 'retry_max_attempts' , 'int' ) -> setAllowedTypes ( 'retry_max_delay' , [ 'int' , 'float' ] ) -> setNormalizer ( 'login' , $ loginNormalizer ) -> setNormalizer ( 'invoker' , $ invokerNormalizer ) ; }
Sets the default options .
46,095
public function download ( $ reportFile , ReportRequest $ reportRequest , $ retryInterval = null ) { try { $ this -> waitReady ( $ reportRequest , $ retryInterval ? : 0 , [ RequestOptions :: SINK => $ reportFile , ] ) ; } catch ( \ Exception $ ex ) { if ( is_file ( $ reportFile ) && is_writable ( $ reportFile ) ) { if ( false !== $ fh = fopen ( $ reportFile , 'w' ) ) { ftruncate ( $ fh , 0 ) ; fclose ( $ fh ) ; } } throw $ ex ; } }
Downloads and save report to the specified file .
46,096
public function save ( $ destination ) { if ( ! $ this -> isReady ( ) ) { throw new LogicException ( 'The report is not ready yet.' ) ; } if ( is_string ( $ destination ) ) { $ fh = fopen ( $ destination , 'w' ) ; if ( ! is_resource ( $ fh ) ) { throw new \ RuntimeException ( sprintf ( 'Could not open file "%s" for write.' , $ destination ) ) ; } $ destination = $ fh ; } elseif ( ! is_resource ( $ destination ) ) { throw new \ InvalidArgumentException ( 'The destination must be string with path to a file or a file descriptor, but given "%s".' , is_object ( $ destination ) ? get_class ( $ destination ) : gettype ( $ destination ) ) ; } $ destStream = GuzzleFunc \ stream_for ( $ destination ) ; GuzzleFunc \ copy_to_stream ( $ this -> response -> getBody ( ) , $ destStream ) ; }
Saves the report to the specified destination .
46,097
public static function qualifiedClassName ( $ className , $ namespace ) { if ( empty ( $ className ) ) { throw new \ InvalidArgumentException ( 'Class name cannot be empty.' ) ; } if ( empty ( $ namespace ) ) { throw new \ InvalidArgumentException ( 'Current namespace cannot be empty.' ) ; } $ className = trim ( $ className , '\\' ) ; $ len = strlen ( $ namespace ) ; if ( strlen ( $ className ) > $ len && ( $ namespace . '\\' ) === substr ( $ className , 0 , $ len + 1 ) ) { return substr ( $ className , $ len + 1 ) ; } return $ className ; }
Resolves Qualified Class Name for the current namespace .
46,098
public function build ( ) { $ prevState = libxml_use_internal_errors ( true ) ; try { $ doc = $ this -> buildDocument ( ) ; if ( ! empty ( $ this -> schema ) && ! $ doc -> schemaValidate ( $ this -> schema ) ) { throw ReportDefinitionException :: schemaValidation ( libxml_get_errors ( ) ) ; } if ( false === $ xml = $ doc -> saveXML ( ) ) { throw ReportDefinitionException :: compileError ( libxml_get_errors ( ) ) ; } return $ xml ; } finally { libxml_clear_errors ( ) ; libxml_use_internal_errors ( $ prevState ) ; } }
Builds the report definition in XML format .
46,099
public function init ( array $ params ) { if ( $ this -> config -> bowerFileExists ( ) ) { $ bowerJson = $ this -> config -> getBowerFileContent ( ) ; $ this -> config -> setSaveToBowerJsonFile ( ) ; $ this -> config -> updateBowerJsonFile2 ( $ bowerJson , $ params ) ; } else { $ this -> config -> initBowerJsonFile ( $ params ) ; } }
Init bower . json