idx int64 0 60.3k | question stringlengths 99 4.85k | target stringlengths 5 718 |
|---|---|---|
900 | private function splitData ( string & $ str ) { if ( $ str === '' ) { return $ str ; } $ replace = function ( & $ string ) { if ( \ strpos ( $ string , $ this -> symbUnescapedRel ) !== false ) { $ string = \ preg_replace ( self :: $ DELIMITER . $ this -> symbRel . "(?=" . $ this -> symbRel . ")|" . $ this -> symbRel . "(?=" . $ this -> sepData . ")|" . $ this -> symbRel . "(?=" . $ this -> sepComp . ")|" . $ this -> symbRel . "(?=" . $ this -> symbEnd . ")" . self :: $ DELIMITER , '' , $ string ) ; } return \ str_replace ( $ this -> stringSafe , $ this -> symbUnescapedRel , $ string ) ; } ; if ( \ strpos ( $ str , $ this -> sepUnescapedComp ) === false ) { return $ replace ( $ str ) ; } $ array = \ preg_split ( self :: $ DELIMITER . "(?<!" . $ this -> symbRel . ")" . $ this -> sepComp . self :: $ DELIMITER , $ str ) ; if ( $ array === false ) { $ array = [ [ ] ] ; } if ( \ count ( $ array ) === 1 ) { return $ replace ( $ str ) ; } foreach ( $ array as & $ value ) { $ value = $ replace ( $ value ) ; } return $ array ; } | Composite data element |
901 | public function loadString ( & $ string ) : array { $ string = $ this -> unwrap ( $ string ) ; $ this -> rawSegments = $ string ; return $ this -> parse ( $ string ) ; } | Load the message from a string . |
902 | protected function readMessageDefaults ( \ SimpleXMLElement $ message ) : array { $ defaults = [ ] ; foreach ( $ message -> defaults [ 0 ] ?? [ ] as $ defaultValueNode ) { $ attributes = $ defaultValueNode -> attributes ( ) ; $ id = ( string ) $ attributes -> id ; $ defaults [ $ id ] = ( string ) $ attributes -> value ; } return $ defaults ; } | read default values in given message xml |
903 | protected function readXmlNodes ( \ SimpleXMLElement $ element ) : array { $ arrayElements = [ ] ; foreach ( $ element as $ name => $ node ) { if ( $ name == "defaults" ) { continue ; } $ arrayElement = [ ] ; $ arrayElement [ "type" ] = $ name ; $ arrayElement [ "attributes" ] = $ this -> readAttributesArray ( $ node ) ; $ details = $ this -> readXmlNodes ( $ node ) ; if ( ! empty ( $ details ) ) { $ arrayElement [ "details" ] = $ details ; } $ arrayElements [ ] = $ arrayElement ; } return $ arrayElements ; } | read message segments and groups |
904 | protected function readAttributesArray ( \ SimpleXMLElement $ element ) : array { $ attributes = [ ] ; foreach ( $ element -> attributes ( ) as $ attrName => $ attr ) { $ attributes [ ( string ) $ attrName ] = ( string ) $ attr ; } return $ attributes ; } | return an xml elements attributes in as array |
905 | public function loadCodesXml ( string $ codesXml ) : array { $ codesXmlString = \ file_get_contents ( $ codesXml ) ; $ codesXml = new \ SimpleXMLIterator ( $ codesXmlString ) ; unset ( $ codesXmlString ) ; $ codes = [ ] ; foreach ( $ codesXml as $ codeCollection ) { $ id = ( string ) $ codeCollection -> attributes ( ) -> id ; $ codes [ $ id ] = [ ] ; foreach ( $ codeCollection as $ codeNode ) { $ codeAttributes = $ codeNode -> attributes ( ) ; $ code = ( string ) $ codeAttributes -> id ; $ codes [ $ id ] [ $ code ] = ( string ) $ codeAttributes -> desc ; } } return $ codes ; } | get all data element codes |
906 | public function loadSegmentsXml ( string $ segment_xml_file ) : array { $ segments_xml = \ file_get_contents ( $ segment_xml_file ) ; $ xml = \ simplexml_load_string ( $ segments_xml ) ; unset ( $ segments_xml ) ; $ this -> segments = [ ] ; foreach ( $ xml as $ segmentNode ) { $ qualifier = ( string ) $ segmentNode -> attributes ( ) -> id ; $ segment = [ ] ; $ segment [ "attributes" ] = $ this -> readAttributesArray ( $ segmentNode ) ; $ details = $ this -> readXmlNodes ( $ segmentNode ) ; if ( ! empty ( $ details ) ) { $ segment [ "details" ] = $ details ; } $ this -> segments [ $ qualifier ] = $ segment ; } return $ this -> segments ; } | convert segment definition from XML to array . Sequence of data_elements and composite_data_element same as in XML |
907 | public function prepare ( array $ parsed ) : array { $ this -> msgs = $ this -> splitMessages ( $ parsed , $ this -> errors ) ; $ groups = [ ] ; $ service = $ this -> msgs [ 'service' ] ; $ this -> serviceSeg = $ this -> processService ( $ service ) ; foreach ( $ this -> msgs as $ k => $ msg ) { if ( $ k === 'service' ) { continue ; } $ grouped = $ this -> loopMessage ( $ msg , $ this -> xmlMsg , $ this -> errors ) ; $ groups [ ] = $ grouped [ 'message' ] ; } $ this -> ediGroups = $ groups ; return $ groups ; } | Split multiple messages and process |
908 | private function splitMessages ( & $ parsed , & $ errors ) : array { $ messages = [ ] ; $ tmpmsg = [ ] ; $ service = [ ] ; $ hasInterchangeDelimiters = 0 ; $ hasMessageDelimiters = 0 ; foreach ( $ parsed as $ c => $ segment ) { switch ( $ segment [ 0 ] ) { case 'UNB' : $ hasInterchangeDelimiters = 0 ; $ hasInterchangeDelimiters ++ ; $ service [ 'UNB' ] = $ segment ; break ; case 'UNZ' : $ hasInterchangeDelimiters -- ; if ( $ hasInterchangeDelimiters != 0 ) { $ sid = ( $ hasInterchangeDelimiters < 0 ) ? "UNB" : "UNZ" ; $ errors [ ] = [ "text" => $ this -> messageTextConf [ 'MISSINGINTERCHANGEDELIMITER' ] , "position" => $ c , "segmentId" => $ sid , ] ; } $ service [ 'UNZ' ] = $ segment ; break ; case 'UNH' : $ hasMessageDelimiters = 0 ; $ hasMessageDelimiters ++ ; $ tmpmsg = [ $ segment ] ; break ; case 'UNT' : $ hasMessageDelimiters -- ; $ tmpmsg [ ] = $ segment ; $ messages [ ] = $ tmpmsg ; if ( $ hasMessageDelimiters != 0 ) { $ sid = ( $ hasMessageDelimiters < 0 ) ? "UNH" : "UNT" ; $ errors [ ] = [ "text" => $ this -> messageTextConf [ 'MISSINGMESSAGEDELIMITER' ] , "position" => $ c , "segmentId" => $ sid , ] ; } break ; default : $ tmpmsg [ ] = $ segment ; break ; } } if ( $ hasInterchangeDelimiters != 0 ) { $ sid = ( $ hasInterchangeDelimiters < 0 ) ? "UNB" : "UNZ" ; $ errors [ ] = [ "text" => $ this -> messageTextConf [ 'MISSINGINTERCHANGEDELIMITER' ] , "position" => $ c ?? '' , "segmentId" => $ sid , ] ; } if ( $ hasMessageDelimiters != 0 ) { $ sid = ( $ hasMessageDelimiters < 0 ) ? "UNH" : "UNT" ; $ errors [ ] = [ "text" => $ this -> messageTextConf [ 'MISSINGMESSAGEDELIMITER' ] , "position" => $ c ?? '' , "segmentId" => $ sid , ] ; } $ messages [ 'service' ] = $ service ; return $ messages ; } | Split multiple messages |
909 | private function loopMessage ( array & $ message , \ SimpleXMLElement $ xml , array & $ errors ) : array { $ groupedEdi = [ ] ; $ segmentIdx = 0 ; foreach ( $ xml -> children ( ) as $ elm ) { if ( $ elm -> getName ( ) == "group" ) { $ this -> processXmlGroup ( $ elm , $ message , $ segmentIdx , $ groupedEdi , $ errors ) ; } elseif ( $ elm -> getName ( ) == "segment" ) { $ this -> processXmlSegment ( $ elm , $ message , $ segmentIdx , $ groupedEdi , $ errors ) ; } } if ( $ segmentIdx != \ count ( $ message ) ) { $ errors [ ] = [ "text" => $ this -> messageTextConf [ 'NOTCONFORMANT' ] , ] ; } return [ 'message' => $ groupedEdi , 'errors' => $ errors ] ; } | Transform a parsed edi in its groupings |
910 | private function processXmlGroup ( \ SimpleXMLElement $ elm , array & $ message , int & $ segmentIdx , array & $ array , array & $ errors ) { $ groupVisited = false ; $ newGroup = [ ] ; for ( $ g = 0 ; $ g < $ elm [ 'maxrepeat' ] ; $ g ++ ) { $ grouptemp = [ ] ; if ( $ message [ $ segmentIdx ] [ 0 ] != $ elm -> children ( ) [ 0 ] [ 'id' ] ) { if ( ! $ groupVisited && isset ( $ elm [ 'required' ] ) ) { $ elmType = $ elm [ 'id' ] -> __toString ( ) ; $ fixed = false ; if ( isset ( $ this -> groupTemplates [ $ elmType ] ) ) { \ array_splice ( $ message , $ segmentIdx , 0 , $ this -> groupTemplates [ $ elmType ] ) ; $ fixed = true ; } $ errors [ ] = [ "text" => $ this -> messageTextConf [ 'MISSINGREQUIREDGROUP' ] . " " . ( $ fixed ? '(patched)' : '' ) , "position" => $ segmentIdx , "segmentId" => $ elmType , ] ; } else { break ; } } foreach ( $ elm -> children ( ) as $ elm2 ) { if ( $ elm2 -> getName ( ) == "group" ) { $ this -> processXmlGroup ( $ elm2 , $ message , $ segmentIdx , $ grouptemp , $ errors ) ; } else { $ this -> processXmlSegment ( $ elm2 , $ message , $ segmentIdx , $ grouptemp , $ errors ) ; } $ groupVisited = true ; } $ newGroup [ ] = $ grouptemp ; } if ( \ count ( $ newGroup ) === 0 ) { return ; } $ array [ $ elm [ 'id' ] -> __toString ( ) ] = $ newGroup ; } | Process an XML Group |
911 | private function processXmlSegment ( \ SimpleXMLElement $ elm , array & $ message , int & $ segmentIdx , array & $ array , array & $ errors ) { $ segmentVisited = false ; for ( $ i = 0 ; $ i < $ elm [ 'maxrepeat' ] ; $ i ++ ) { if ( \ call_user_func ( $ this -> comparisonFunction , $ message [ $ segmentIdx ] , $ elm ) ) { $ jsonMessage = $ this -> processSegment ( $ message [ $ segmentIdx ] , $ this -> xmlSeg , $ segmentIdx , $ errors ) ; $ segmentVisited = true ; $ this -> doAddArray ( $ array , $ jsonMessage ) ; $ segmentIdx ++ ; } else { if ( ! $ segmentVisited && isset ( $ elm [ 'required' ] ) ) { $ fixed = false ; if ( $ elm [ 'replacewith' ] !== null ) { $ elmType = ( string ) $ elm [ 'replacewith' ] ; } else { $ elmType = ( string ) $ elm [ 'id' ] ; } if ( isset ( $ this -> segmentTemplates [ $ elmType ] ) ) { $ jsonMessage = $ this -> processSegment ( $ this -> segmentTemplates [ $ elmType ] , $ this -> xmlSeg , $ segmentIdx , $ errors ) ; $ fixed = true ; $ this -> doAddArray ( $ array , $ jsonMessage ) ; } $ errors [ ] = [ "text" => $ this -> messageTextConf [ 'MISSINGREQUIREDSEGMENT' ] . " " . ( $ fixed ? '(patched)' : '' ) , "position" => $ segmentIdx , "segmentId" => ( string ) $ elm [ 'id' ] , ] ; } return ; } } } | Process an XML Segment . |
912 | private function doAddArray ( array & $ array , array & $ jsonMessage ) { if ( isset ( $ array [ $ jsonMessage [ 'key' ] ] ) ) { if ( isset ( $ array [ $ jsonMessage [ 'key' ] ] [ 'segmentCode' ] ) || $ jsonMessage [ 'key' ] === 'UnrecognisedType' ) { $ temp = $ array [ $ jsonMessage [ 'key' ] ] ; $ array [ $ jsonMessage [ 'key' ] ] = [ ] ; $ array [ $ jsonMessage [ 'key' ] ] [ ] = $ temp ; } $ array [ $ jsonMessage [ 'key' ] ] [ ] = $ jsonMessage [ 'value' ] ; } else { $ array [ $ jsonMessage [ 'key' ] ] = $ jsonMessage [ 'value' ] ; } } | Adds a processed segment to the current group . |
913 | public function getJson ( bool $ pretty = false ) { if ( $ pretty ) { return \ json_encode ( $ this -> ediGroups , JSON_PRETTY_PRINT ) ; } return \ json_encode ( $ this -> ediGroups ) ; } | Get result as json . |
914 | public function getJsonServiceSegments ( bool $ pretty = false ) { if ( $ pretty ) { return \ json_encode ( $ this -> serviceSeg , JSON_PRETTY_PRINT ) ; } return \ json_encode ( $ this -> serviceSeg ) ; } | Get json service segments . |
915 | public function getMigrationSql ( $ version , $ increment ) { if ( intval ( $ version ) != $ version ) { throw new \ InvalidArgumentException ( "Version '$version' should be a integer number" ) ; } $ version = intval ( $ version ) ; $ filePattern = $ this -> folder . "/migrations" . "/" . ( $ increment < 0 ? "down" : "up" ) . "/*.sql" ; $ result = array_filter ( glob ( $ filePattern ) , function ( $ file ) use ( $ version ) { return preg_match ( "/^0*$version(-dev)?\.sql$/" , basename ( $ file ) ) ; } ) ; if ( count ( $ result ) > 1 ) { throw new InvalidMigrationFile ( "You have two files with the same version number '$version'" ) ; } foreach ( $ result as $ file ) { if ( intval ( basename ( $ file ) ) === $ version ) { return $ file ; } } return null ; } | Get the full path script based on the version |
916 | protected function migrate ( $ upVersion , $ increment , $ force ) { $ versionInfo = $ this -> getCurrentVersion ( ) ; $ currentVersion = intval ( $ versionInfo [ 'version' ] ) + $ increment ; if ( strpos ( $ versionInfo [ 'status' ] , Migration :: VERSION_STATUS_PARTIAL ) !== false && ! $ force ) { throw new DatabaseIsIncompleteException ( 'Database was not fully updated. Use --force for migrate.' ) ; } while ( $ this -> canContinue ( $ currentVersion , $ upVersion , $ increment ) && file_exists ( $ file = $ this -> getMigrationSql ( $ currentVersion , $ increment ) ) ) { if ( $ this -> callableProgress ) { call_user_func_array ( $ this -> callableProgress , [ 'migrate' , $ currentVersion ] ) ; } $ this -> getDbCommand ( ) -> setVersion ( $ currentVersion , Migration :: VERSION_STATUS_PARTIAL . ' ' . ( $ increment > 0 ? 'up' : 'down' ) ) ; $ this -> getDbCommand ( ) -> executeSql ( file_get_contents ( $ file ) ) ; $ this -> getDbCommand ( ) -> setVersion ( $ currentVersion , Migration :: VERSION_STATUS_COMPLETE ) ; $ currentVersion = $ currentVersion + $ increment ; } } | Method for execute the migration . |
917 | public function update ( $ upVersion = null , $ force = false ) { $ versionInfo = $ this -> getCurrentVersion ( ) ; $ version = intval ( $ versionInfo [ 'version' ] ) ; $ increment = 1 ; if ( $ upVersion !== null && $ upVersion < $ version ) { $ increment = - 1 ; } $ this -> migrate ( $ upVersion , $ increment , $ force ) ; } | Run all scripts to up or down the database version from current up to latest version or the specified version . |
918 | public function parseConfig ( array $ configs ) { foreach ( $ configs as & $ config ) { $ config [ 'states' ] = $ this -> parseStates ( $ config [ 'states' ] ) ; if ( isset ( $ config [ 'callbacks' ] ) ) { $ config [ 'callbacks' ] = $ this -> parseCallbacks ( $ config [ 'callbacks' ] ) ; } } return $ configs ; } | Does whatever is needed to transform the config in an acceptable argument for the factory |
919 | protected function parseStates ( array $ states ) { $ newStates = array ( ) ; foreach ( $ states as $ key => $ state ) { if ( null === $ state ) { $ newStates [ ] = $ key ; } elseif ( self :: CFG_STATE_DISABLE !== $ state ) { $ newStates [ ] = $ state ; } elseif ( null !== $ index = array_search ( $ key , $ newStates ) ) { unset ( $ newStates [ $ index ] ) ; } } return $ newStates ; } | Allows the disabling of states |
920 | protected function parseCallbacks ( array $ callbacks ) { foreach ( array ( 'before' , 'after' ) as $ position ) { foreach ( $ callbacks [ $ position ] as $ i => $ callback ) { if ( $ callback [ 'disabled' ] ) { unset ( $ callbacks [ $ position ] [ $ i ] ) ; } } uasort ( $ callbacks [ $ position ] , function ( $ a , $ b ) { if ( $ a [ 'priority' ] === $ b [ 'priority' ] ) { return 0 ; } return $ a [ 'priority' ] < $ b [ 'priority' ] ? - 1 : 1 ; } ) ; } return $ callbacks ; } | Allows the disabling of callbacks |
921 | protected function createChildInstance ( ) { $ instance = new static ( ... \ func_get_args ( ) ) ; if ( isset ( $ this -> document ) ) { $ instance -> setDomDocument ( $ this -> document ) ; } if ( isset ( $ this -> root_instance ) ) { $ instance -> root_instance = $ this -> root_instance ; } else { $ instance -> root_instance = $ this ; } if ( \ is_bool ( $ this -> xml_mode ) ) { $ instance -> xml_mode = $ this -> xml_mode ; } if ( isset ( $ this -> document ) && $ this -> dom_xpath instanceof \ DOMXPath ) { $ instance -> dom_xpath = $ this -> dom_xpath ; } return $ instance ; } | Create new instance of self with some properties of its parents |
922 | public function xpath ( string $ xpath_query ) { $ result = $ this -> createChildInstance ( ) ; if ( isset ( $ this -> document ) ) { $ result -> xpath_query = $ xpath_query ; if ( isset ( $ this -> root_instance ) || isset ( $ this -> xpath_query ) ) { foreach ( $ this -> nodes as $ node ) { if ( $ result_node_list = $ this -> xpathQuery ( '.' . $ xpath_query , $ node ) ) { $ result -> loadDomNodeList ( $ result_node_list ) ; } } } else { if ( $ result_node_list = $ this -> xpathQuery ( $ xpath_query ) ) { $ result -> loadDomNodeList ( $ result_node_list ) ; } } } return $ result ; } | Use xpath and return new DomQuery with resulting nodes |
923 | public function setDomDocument ( \ DOMDocument $ document ) { if ( isset ( $ this -> document ) && $ this -> document !== $ document ) { throw new \ Exception ( 'Other DOMDocument already set!' ) ; } $ this -> document = $ document ; } | Set dom document |
924 | public function loadDomNodeList ( \ DOMNodeList $ dom_node_list ) { if ( ! isset ( $ this -> document ) && $ dom_node_list -> length === 0 ) { throw new \ Exception ( 'DOMDocument is missing!' ) ; } if ( $ dom_node_list -> length > 0 ) { $ this -> setDomDocument ( $ dom_node_list -> item ( 0 ) -> ownerDocument ) ; } foreach ( $ dom_node_list as $ node ) { $ this -> addDomNode ( $ node ) ; } } | Add nodes from dom node list to result set |
925 | public function addDomNode ( \ DOMNode $ dom_node , $ prepend = false ) { if ( $ prepend ) { array_unshift ( $ this -> nodes , $ dom_node ) ; } else { $ this -> nodes [ ] = $ dom_node ; } $ this -> length = \ count ( $ this -> nodes ) ; $ this -> setDomDocument ( $ dom_node -> ownerDocument ) ; } | Add node to result set |
926 | public function loadContent ( string $ content , $ encoding = 'UTF-8' ) { $ this -> preserve_no_newlines = ( strpos ( $ content , '<' ) !== false && strpos ( $ content , "\n" ) === false ) ; if ( ! \ is_bool ( $ this -> xml_mode ) ) { $ this -> xml_mode = ( stripos ( $ content , '<?xml' ) === 0 ) ; } $ this -> xml_print_pi = ( stripos ( $ content , '<?xml' ) === 0 ) ; $ xml_pi_node_added = false ; if ( ! $ this -> xml_mode && $ encoding && stripos ( $ content , '<?xml' ) === false ) { $ content = '<?xml encoding="' . $ encoding . '">' . $ content ; $ xml_pi_node_added = true ; } libxml_disable_entity_loader ( true ) ; libxml_use_internal_errors ( true ) ; $ dom_document = new \ DOMDocument ( '1.0' , $ encoding ) ; $ dom_document -> strictErrorChecking = false ; $ dom_document -> validateOnParse = false ; $ dom_document -> recover = true ; if ( $ this -> xml_mode ) { $ dom_document -> loadXML ( $ content , $ this -> libxml_options ) ; } else { $ dom_document -> loadHTML ( $ content , $ this -> libxml_options ) ; } $ this -> setDomDocument ( $ dom_document ) ; if ( $ xml_pi_node_added ) { foreach ( $ dom_document -> childNodes as $ node ) { if ( $ node -> nodeType === XML_PI_NODE ) { $ dom_document -> removeChild ( $ node ) ; break ; } } } foreach ( $ dom_document -> childNodes as $ node ) { $ this -> nodes [ ] = $ node ; } $ this -> length = \ count ( $ this -> nodes ) ; } | Load html or xml content |
927 | public function get ( $ index ) { $ result = \ array_slice ( $ this -> nodes , $ index , 1 ) ; if ( \ count ( $ result ) > 0 ) { return $ result [ 0 ] ; } return null ; } | Grants access to the DOM nodes of this instance |
928 | public function find ( $ selector ) { if ( \ is_string ( $ selector ) ) { $ css_expression = $ selector ; } else { $ selector_tag_names = array ( ) ; $ selector_result = self :: create ( $ selector ) ; foreach ( $ selector_result as $ node ) { $ selector_tag_names [ ] = $ node -> tagName ; } $ css_expression = implode ( ',' , $ selector_tag_names ) ; } $ xpath_expression = CssToXpath :: transform ( $ css_expression ) ; $ result = $ this -> xpath ( $ xpath_expression ) ; if ( \ is_string ( $ selector ) ) { $ result -> css_query = $ css_expression ; $ result -> selector = $ css_expression ; } if ( isset ( $ selector_result ) ) { $ new_result_nodes = array ( ) ; foreach ( $ result -> nodes as $ result_node ) { foreach ( $ selector_result -> nodes as $ selector_result_node ) { if ( $ result_node -> isSameNode ( $ selector_result_node ) ) { $ new_result_nodes [ ] = $ result_node ; } } } $ result -> nodes = $ new_result_nodes ; } return $ result ; } | Get the descendants of each element in the current set of matched elements filtered by a selector |
929 | public function findOrFail ( $ selector ) { $ result = $ this -> find ( $ selector ) ; if ( $ result -> length === 0 ) { if ( \ is_string ( $ selector ) ) { throw new \ Exception ( 'Find with selector "' . $ selector . '" failed!' ) ; } throw new \ Exception ( 'Find with node (collection) as selector failed!' ) ; } return $ result ; } | Get the descendants of each element in the current set of matched elements filtered by a selector . If no results are found a exception is thrown . |
930 | public function each ( callable $ callback ) { foreach ( $ this -> nodes as $ index => $ node ) { $ return_value = \ call_user_func ( $ callback , $ node , $ index ) ; if ( $ return_value === false ) { break ; } } return $ this ; } | Iterate over result set and executing a callback for each node |
931 | public function map ( callable $ callback ) { $ result = array ( ) ; foreach ( $ this -> nodes as $ index => $ node ) { $ return_value = \ call_user_func ( $ callback , $ node , $ index ) ; if ( $ return_value === null ) { continue ; } elseif ( \ is_array ( $ return_value ) ) { $ result = \ array_merge ( $ result , $ return_value ) ; } else { $ result [ ] = $ return_value ; } } return $ result ; } | Pass each element in the current matched set through a function producing an array containing the return values |
932 | protected function getClonedNodes ( ) { $ cloned_nodes = array ( ) ; foreach ( $ this -> nodes as $ node ) { $ cloned_node = $ node -> cloneNode ( true ) ; if ( $ cloned_node instanceof \ DOMElement && $ cloned_node -> hasAttribute ( 'dqn_tmp_id' ) ) { $ cloned_node -> removeAttribute ( 'dqn_tmp_id' ) ; } $ cloned_nodes [ ] = $ cloned_node ; } return $ cloned_nodes ; } | Return array with cloned nodes |
933 | private function createDomXpath ( ) { $ xpath = new \ DOMXPath ( $ this -> document ) ; if ( $ this -> xml_mode ) { foreach ( $ xpath -> query ( 'namespace::*' ) as $ node ) { if ( $ node -> prefix !== 'xml' ) { $ xpath -> registerNamespace ( $ node -> prefix , $ node -> namespaceURI ) ; } } } return $ xpath ; } | Create dom xpath instance |
934 | public static function getElementId ( \ DOMElement $ node ) { if ( $ node -> hasAttribute ( 'dqn_tmp_id' ) ) { return $ node -> getAttribute ( 'dqn_tmp_id' ) ; } $ node_id = md5 ( mt_rand ( ) ) ; $ node -> setAttribute ( 'dqn_tmp_id' , $ node_id ) ; return $ node_id ; } | Get id for node |
935 | private function handleHtmlResult ( $ html ) { if ( $ this -> preserve_no_newlines ) { $ html = str_replace ( "\n" , '' , $ html ) ; } if ( stripos ( $ html , 'dqn_tmp_id=' ) !== false ) { $ html = preg_replace ( '/ dqn_tmp_id="([a-z0-9]+)"/' , '' , $ html ) ; } return $ html ; } | Handle html when resulting html is requested |
936 | public function getInnerHtml ( ) { $ html = '' ; if ( $ content_node = $ this -> getFirstElmNode ( ) ) { $ document = $ content_node -> ownerDocument ; foreach ( $ content_node -> childNodes as $ node ) { if ( $ this -> xml_mode ) { $ html .= $ document -> saveXML ( $ node ) ; } else { $ html .= $ document -> saveHTML ( $ node ) ; } } $ html = $ this -> handleHtmlResult ( $ html ) ; } return $ html ; } | Get the HTML contents of the first element in the set of matched elements . |
937 | public function text ( $ val = null ) { if ( $ val !== null ) { foreach ( $ this -> nodes as $ node ) { $ node -> nodeValue = $ val ; } return $ this ; } if ( $ node = $ this -> getFirstElmNode ( ) ) { return $ node -> nodeValue ; } } | Get the combined text contents of each element in the set of matched elements including their descendants or set the text contents of the matched elements . |
938 | public function html ( $ html_string = null ) { if ( $ html_string !== null ) { foreach ( $ this as $ node ) { $ node -> get ( 0 ) -> nodeValue = '' ; $ node -> append ( $ html_string ) ; } return $ this ; } return $ this -> getInnerHtml ( ) ; } | Get the HTML contents of the first element in the set of matched elements |
939 | public function attr ( string $ name , $ val = null ) { if ( $ val !== null ) { foreach ( $ this -> getElements ( ) as $ node ) { $ node -> setAttribute ( $ name , $ val ) ; } return $ this ; } if ( $ node = $ this -> getFirstElmNode ( ) ) { return $ node -> getAttribute ( $ name ) ; } } | Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element . |
940 | public function data ( string $ key = null , $ val = null ) { $ doc_hash = spl_object_hash ( $ this -> document ) ; if ( $ val !== null ) { if ( ! isset ( self :: $ node_data [ $ doc_hash ] ) ) { self :: $ node_data [ $ doc_hash ] = array ( ) ; } foreach ( $ this -> getElements ( ) as $ node ) { if ( ! isset ( self :: $ node_data [ $ doc_hash ] [ self :: getElementId ( $ node ) ] ) ) { self :: $ node_data [ $ doc_hash ] [ self :: getElementId ( $ node ) ] = ( object ) array ( ) ; } self :: $ node_data [ $ doc_hash ] [ self :: getElementId ( $ node ) ] -> $ key = $ val ; } return $ this ; } if ( $ node = $ this -> getFirstElmNode ( ) ) { if ( isset ( self :: $ node_data [ $ doc_hash ] ) && isset ( self :: $ node_data [ $ doc_hash ] [ self :: getElementId ( $ node ) ] ) ) { if ( $ key === null ) { return self :: $ node_data [ $ doc_hash ] [ self :: getElementId ( $ node ) ] ; } elseif ( isset ( self :: $ node_data [ $ doc_hash ] [ self :: getElementId ( $ node ) ] -> $ key ) ) { return self :: $ node_data [ $ doc_hash ] [ self :: getElementId ( $ node ) ] -> $ key ; } } if ( $ key === null ) { $ data = array ( ) ; foreach ( $ node -> attributes as $ attr ) { if ( strpos ( $ attr -> nodeName , 'data-' ) === 0 ) { $ val = $ attr -> nodeValue [ 0 ] === '{' ? json_decode ( $ attr -> nodeValue ) : $ attr -> nodeValue ; $ data [ substr ( $ attr -> nodeName , 5 ) ] = $ val ; } } return ( object ) $ data ; } if ( $ data = $ node -> getAttribute ( 'data-' . $ key ) ) { $ val = $ data [ 0 ] === '{' ? json_decode ( $ data ) : $ data ; return $ val ; } } } | Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements . |
941 | public function removeData ( $ name = null ) { $ remove_names = \ is_array ( $ name ) ? $ name : explode ( ' ' , $ name ) ; $ doc_hash = spl_object_hash ( $ this -> document ) ; if ( ! isset ( self :: $ node_data [ $ doc_hash ] ) ) { return ; } foreach ( $ this -> getElements ( ) as $ node ) { if ( ! $ node -> hasAttribute ( 'dqn_tmp_id' ) ) { continue ; } $ node_id = self :: getElementId ( $ node ) ; if ( isset ( self :: $ node_data [ $ doc_hash ] [ $ node_id ] ) ) { if ( $ name === null ) { self :: $ node_data [ $ doc_hash ] [ $ node_id ] = null ; } else { foreach ( $ remove_names as $ remove_name ) { if ( isset ( self :: $ node_data [ $ doc_hash ] [ $ node_id ] -> $ remove_name ) ) { self :: $ node_data [ $ doc_hash ] [ $ node_id ] -> $ remove_name = null ; } } } } } } | Remove a previously - stored piece of data . |
942 | public function css ( string $ name , $ val = null ) { if ( $ val !== null ) { foreach ( $ this -> getElements ( ) as $ node ) { $ style = self :: parseStyle ( $ node -> getAttribute ( 'style' ) ) ; $ style [ $ name ] = $ val ; $ node -> setAttribute ( 'style' , self :: getStyle ( $ style ) ) ; } return $ this ; } if ( $ node = $ this -> getFirstElmNode ( ) ) { $ style = self :: parseStyle ( $ node -> getAttribute ( 'style' ) ) ; if ( isset ( $ style [ $ name ] ) ) { return $ style [ $ name ] ; } } } | Get the value of a computed style property for the first element in the set of matched elements or set one or more CSS properties for every matched element . |
943 | public function removeAttr ( $ name ) { $ remove_names = \ is_array ( $ name ) ? $ name : explode ( ' ' , $ name ) ; foreach ( $ this -> getElements ( ) as $ node ) { foreach ( $ remove_names as $ remove_name ) { $ node -> removeAttribute ( $ remove_name ) ; } } return $ this ; } | Remove an attribute from each element in the set of matched elements . Name can be a space - separated list of attributes . |
944 | public function prop ( string $ name , $ val = null ) { if ( $ val !== null ) { foreach ( $ this -> nodes as $ node ) { $ node -> $ name = $ val ; } return $ this ; } if ( $ name === 'outerHTML' ) { return $ this -> getOuterHtml ( ) ; } if ( $ node = $ this -> getFirstElmNode ( ) ) { if ( isset ( $ node -> $ name ) ) { return $ node -> $ name ; } } } | Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element . |
945 | public function children ( $ selector = null ) { $ result = $ this -> createChildInstance ( ) ; if ( isset ( $ this -> document ) && $ this -> length > 0 ) { if ( isset ( $ this -> root_instance ) || $ this -> getXpathQuery ( ) ) { foreach ( $ this -> nodes as $ node ) { if ( $ node -> hasChildNodes ( ) ) { $ result -> loadDomNodeList ( $ node -> childNodes ) ; } } } else { $ result -> loadDomNodeList ( $ this -> document -> childNodes ) ; } if ( $ selector !== false ) { $ filtered_elements = array ( ) ; foreach ( $ result -> getElements ( ) as $ result_elm ) { $ filtered_elements [ ] = $ result_elm ; } $ result -> nodes = $ filtered_elements ; $ result -> length = \ count ( $ result -> nodes ) ; } if ( $ selector ) { $ result = $ result -> filter ( $ selector ) ; } } return $ result ; } | Get the children of each element in the set of matched elements optionally filtered by a selector . |
946 | public function siblings ( $ selector = null ) { $ result = $ this -> createChildInstance ( ) ; if ( isset ( $ this -> document ) && $ this -> length > 0 ) { foreach ( $ this -> nodes as $ node ) { if ( $ node -> parentNode ) { foreach ( $ node -> parentNode -> childNodes as $ sibling ) { if ( $ sibling instanceof \ DOMElement && ! $ sibling -> isSameNode ( $ node ) ) { $ result -> addDomNode ( $ sibling ) ; } } } } if ( $ selector ) { $ result = $ result -> filter ( $ selector ) ; } } return $ result ; } | Get the siblings of each element in the set of matched elements optionally filtered by a selector . |
947 | public function parent ( $ selector = null ) { $ result = $ this -> createChildInstance ( ) ; if ( isset ( $ this -> document ) && $ this -> length > 0 ) { foreach ( $ this -> nodes as $ node ) { if ( $ node -> parentNode ) { $ result -> addDomNode ( $ node -> parentNode ) ; } } if ( $ selector ) { $ result = $ result -> filter ( $ selector ) ; } } return $ result ; } | Get the parent of each element in the current set of matched elements optionally filtered by a selector |
948 | public function closest ( $ selector ) { $ result = $ this -> createChildInstance ( ) ; if ( isset ( $ this -> document ) && $ this -> length > 0 ) { foreach ( $ this -> nodes as $ node ) { $ current = $ node ; while ( $ current instanceof \ DOMElement ) { if ( self :: create ( $ current ) -> is ( $ selector ) ) { $ result -> addDomNode ( $ current ) ; break ; } $ current = $ current -> parentNode ; } } } return $ result ; } | For each element in the set get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree . |
949 | public function not ( $ selector ) { $ result = $ this -> createChildInstance ( ) ; if ( $ this -> length > 0 ) { if ( \ is_callable ( $ selector ) ) { foreach ( $ this -> nodes as $ index => $ node ) { if ( ! $ selector ( $ node , $ index ) ) { $ result -> addDomNode ( $ node ) ; } } } else { $ selection = self :: create ( $ this -> document ) -> find ( $ selector ) ; if ( $ selection -> length > 0 ) { foreach ( $ this -> nodes as $ node ) { $ matched = false ; foreach ( $ selection as $ result_node ) { if ( $ result_node -> isSameNode ( $ node ) ) { $ matched = true ; break 1 ; } } if ( ! $ matched ) { $ result -> addDomNode ( $ node ) ; } } } else { $ result -> addNodes ( $ this -> nodes ) ; } } } return $ result ; } | Remove elements from the set of matched elements . |
950 | public function index ( $ selector = null ) { if ( $ selector === null ) { if ( $ node = $ this -> getFirstElmNode ( ) ) { $ position = 0 ; while ( $ node && ( $ node = $ node -> previousSibling ) ) { if ( $ node instanceof \ DOMElement ) { $ position ++ ; } else { break ; } } return $ position ; } } else { foreach ( $ this as $ key => $ node ) { if ( $ node -> is ( $ selector ) ) { return $ key ; } } } return - 1 ; } | Get the position of the first element within the DOM relative to its sibling elements . Or get the position of the first node in the result that matches the selector . |
951 | public function is ( $ selector ) { if ( $ this -> length > 0 ) { if ( \ is_callable ( $ selector ) ) { foreach ( $ this -> nodes as $ index => $ node ) { if ( $ selector ( $ node , $ index ) ) { return true ; } } } else { $ selection = self :: create ( $ this -> document ) -> find ( $ selector ) ; foreach ( $ selection -> nodes as $ result_node ) { foreach ( $ this -> nodes as $ node ) { if ( $ result_node -> isSameNode ( $ node ) ) { return true ; } } } } } return false ; } | Check if any node matches the selector |
952 | public function has ( $ selector ) { $ result = $ this -> createChildInstance ( ) ; if ( $ this -> length > 0 ) { foreach ( $ this as $ node ) { if ( $ node -> find ( $ selector ) -> length > 0 ) { $ result -> addDomNode ( $ node -> get ( 0 ) ) ; } } } return $ result ; } | Reduce the set of matched elements to those that have a descendant that matches the selector |
953 | public function first ( $ selector = null ) { $ result = $ this [ 0 ] ; if ( $ selector ) { $ result = $ result -> filter ( $ selector ) ; } return $ result ; } | Returns DomQuery with first node |
954 | public function last ( $ selector = null ) { $ result = $ this [ $ this -> length - 1 ] ; if ( $ selector ) { $ result = $ result -> filter ( $ selector ) ; } return $ result ; } | Returns DomQuery with last node |
955 | public function next ( $ selector = null ) { $ result = $ this -> createChildInstance ( ) ; if ( isset ( $ this -> document ) && $ this -> length > 0 ) { foreach ( $ this -> nodes as $ node ) { if ( $ next = self :: getNextElement ( $ node ) ) { $ result -> addDomNode ( $ next ) ; } } if ( $ selector ) { $ result = $ result -> filter ( $ selector ) ; } } return $ result ; } | Returns DomQuery with immediately following sibling of all nodes |
956 | public function prev ( $ selector = null ) { $ result = $ this -> createChildInstance ( ) ; if ( isset ( $ this -> document ) && $ this -> length > 0 ) { foreach ( $ this -> nodes as $ node ) { if ( $ prev = self :: getPreviousElement ( $ node ) ) { $ result -> addDomNode ( $ prev ) ; } } if ( $ selector ) { $ result = $ result -> filter ( $ selector ) ; } } return $ result ; } | Returns DomQuery with immediately preceding sibling of all nodes |
957 | public function remove ( $ selector = null ) { $ result = $ this ; if ( $ selector ) { $ result = $ result -> filter ( $ selector ) ; } foreach ( $ result -> nodes as $ node ) { if ( $ node -> parentNode ) { $ node -> parentNode -> removeChild ( $ node ) ; } } $ result -> nodes = array ( ) ; $ result -> length = 0 ; return $ result ; } | Remove the set of matched elements |
958 | private function importNodes ( $ content , callable $ import_function ) { if ( \ is_array ( $ content ) ) { foreach ( $ content as $ item ) { $ this -> importNodes ( $ item , $ import_function ) ; } } else { if ( \ is_string ( $ content ) && strpos ( $ content , "\n" ) !== false ) { $ this -> preserve_no_newlines = false ; if ( isset ( $ this -> root_instance ) ) { $ this -> root_instance -> preserve_no_newlines = false ; } } if ( ! ( $ content instanceof self ) ) { $ content = new self ( $ content ) ; } foreach ( $ this -> nodes as $ node ) { foreach ( $ content -> getNodes ( ) as $ content_node ) { if ( $ content_node -> ownerDocument === $ node -> ownerDocument ) { $ imported_node = $ content_node -> cloneNode ( true ) ; } else { $ imported_node = $ this -> document -> importNode ( $ content_node , true ) ; } $ import_function ( $ node , $ imported_node ) ; } } } } | Import nodes and insert or append them via callback function |
959 | private function getTargetResult ( $ target , $ context = null ) { if ( $ context === null && \ is_string ( $ target ) && strpos ( $ target , '<' ) === false ) { $ context = $ this -> document ; } return $ context === null ? self :: create ( $ target ) : self :: create ( $ target , $ context ) ; } | Get target result using selector or instance of self |
960 | public function append ( ) { $ this -> importNodes ( \ func_get_args ( ) , function ( $ node , $ imported_node ) { $ node -> appendChild ( $ imported_node ) ; } ) ; return $ this ; } | Insert content to the end of each element in the set of matched elements . |
961 | public function prepend ( ) { $ this -> importNodes ( \ func_get_args ( ) , function ( $ node , $ imported_node ) { $ node -> insertBefore ( $ imported_node , $ node -> childNodes -> item ( 0 ) ) ; } ) ; return $ this ; } | Insert content to the beginning of each element in the set of matched elements |
962 | public function before ( ) { $ this -> importNodes ( \ func_get_args ( ) , function ( $ node , $ imported_node ) { if ( $ node -> parentNode instanceof \ DOMDocument ) { throw new \ Exception ( 'Can not set before root element ' . $ node -> tagName . ' of document' ) ; } $ node -> parentNode -> insertBefore ( $ imported_node , $ node ) ; } ) ; return $ this ; } | Insert content before each element in the set of matched elements . |
963 | public function after ( ) { $ this -> importNodes ( \ func_get_args ( ) , function ( $ node , $ imported_node ) { if ( $ node -> nextSibling ) { $ node -> parentNode -> insertBefore ( $ imported_node , $ node -> nextSibling ) ; } else { $ node -> parentNode -> appendChild ( $ imported_node ) ; } } ) ; return $ this ; } | Insert content after each element in the set of matched elements . |
964 | public function wrapAll ( ) { $ wrapper_node = null ; $ wrap_target_node = null ; $ this -> importNodes ( \ func_get_args ( ) , function ( $ node , $ imported_node ) use ( & $ wrapper_node , & $ wrap_target_node ) { if ( $ node -> parentNode instanceof \ DOMDocument ) { throw new \ Exception ( 'Can not wrap inside root element ' . $ node -> tagName . ' of document' ) ; } if ( $ wrapper_node && $ wrap_target_node ) { $ old = $ node -> parentNode -> removeChild ( $ node ) ; $ wrap_target_node -> appendChild ( $ old ) ; } else { $ wrapper_node = $ imported_node ; $ old = $ node -> parentNode -> replaceChild ( $ imported_node , $ node ) ; $ target = $ imported_node ; while ( $ target -> hasChildNodes ( ) ) { $ target = $ target -> childNodes [ 0 ] ; } $ target -> appendChild ( $ old ) ; $ wrap_target_node = $ target ; } } ) ; return $ this ; } | Wrap an HTML structure around all elements in the set of matched elements |
965 | public function wrapInner ( ) { foreach ( $ this -> nodes as $ node ) { self :: create ( $ node -> childNodes ) -> wrapAll ( \ func_get_args ( ) ) ; } return $ this ; } | Wrap an HTML structure around the content of each element in the set of matched elements |
966 | public static function transform ( string $ path ) { if ( isset ( self :: $ xpath_cache [ $ path ] ) ) { return self :: $ xpath_cache [ $ path ] ; } $ tmp_path = self :: replaceCharInsideEnclosure ( $ path , ',' ) ; if ( strpos ( $ tmp_path , ',' ) !== false ) { $ paths = explode ( ',' , $ tmp_path ) ; $ expressions = array ( ) ; foreach ( $ paths as $ single_path ) { $ single_path = str_replace ( "\0" , ',' , $ single_path ) ; $ xpath = self :: transform ( trim ( $ single_path ) ) ; $ expressions [ ] = $ xpath ; } return implode ( '|' , $ expressions ) ; } $ path_escaped = self :: replaceCharInsideEnclosure ( $ path , ' ' ) ; $ tokens = preg_split ( '/\s+/' , $ path_escaped ) ; $ segments = array ( ) ; foreach ( $ tokens as $ key => $ token ) { $ token = str_replace ( "\0" , ' ' , $ token ) ; if ( $ segment = self :: getSegmentFromToken ( $ token , $ key , $ tokens ) ) { $ segments [ ] = $ segment ; } } $ new_path_tokens = self :: transformCssSegments ( $ segments ) ; $ xpath_result = implode ( '' , $ new_path_tokens ) ; self :: $ xpath_cache [ $ path ] = $ xpath_result ; return $ xpath_result ; } | Transform CSS selector expression to XPath |
967 | private static function transformCssSegments ( array $ segments ) { $ new_path_tokens = array ( ) ; foreach ( $ segments as $ num => $ segment ) { if ( $ segment -> relation_token === '>' ) { $ new_path_tokens [ ] = '/' ; } elseif ( $ segment -> relation_token === '~' || $ segment -> relation_token === '+' ) { $ new_path_tokens [ ] = '/following-sibling::' ; } else { $ new_path_tokens [ ] = '//' ; } if ( $ segment -> selector !== '' ) { $ new_path_tokens [ ] = $ segment -> selector ; } else { $ new_path_tokens [ ] = '*' ; } if ( $ segment -> relation_token === '+' && isset ( $ segments [ $ num - 1 ] ) ) { $ prev_selector = implode ( '' , self :: transformCssSegments ( [ $ segments [ $ num - 1 ] ] ) ) ; $ new_path_tokens [ ] = '[preceding-sibling::*[1][self::' . ltrim ( $ prev_selector , '/' ) . ']]' ; } foreach ( array_reverse ( $ segment -> attribute_filters ) as $ attr ) { $ new_path_tokens [ ] = self :: transformAttrSelector ( $ attr ) ; } foreach ( array_reverse ( $ segment -> pseudo_filters ) as $ attr ) { $ new_path_tokens [ ] = self :: transformCssPseudoSelector ( $ attr , $ new_path_tokens ) ; } } return $ new_path_tokens ; } | Transform css segments to xpath |
968 | private static function transformCssPseudoSelector ( $ expression , array & $ new_path_tokens ) { if ( preg_match ( '|not\((.+)\)|i' , $ expression , $ matches ) ) { $ parts = explode ( ',' , $ matches [ 1 ] ) ; foreach ( $ parts as & $ part ) { $ part = trim ( $ part ) ; $ part = 'self::' . ltrim ( self :: transform ( $ part ) , '/' ) ; } $ not_selector = implode ( ' or ' , $ parts ) ; return '[not(' . $ not_selector . ')]' ; } elseif ( preg_match ( '|contains\((.+)\)|i' , $ expression , $ matches ) ) { return '[text()[contains(.,\'' . $ matches [ 1 ] . '\')]]' ; } elseif ( preg_match ( '|has\((.+)\)|i' , $ expression , $ matches ) ) { if ( strpos ( $ matches [ 1 ] , '> ' ) === 0 ) { return '[child::' . ltrim ( self :: transform ( $ matches [ 1 ] ) , '/' ) . ']' ; } else { return '[descendant::' . ltrim ( self :: transform ( $ matches [ 1 ] ) , '/' ) . ']' ; } } elseif ( $ expression === 'first' || $ expression === 'last' ) { array_unshift ( $ new_path_tokens , '(' ) ; $ new_path_tokens [ ] = ')' ; } $ pseudo_class_selectors = array ( 'disabled' => '[@disabled]' , 'first-child' => '[not(preceding-sibling::*)]' , 'last-child' => '[not(following-sibling::*)]' , 'only-child' => '[not(preceding-sibling::*) and not(following-sibling::*)]' , 'empty' => '[count(*) = 0 and string-length() = 0]' , 'not-empty' => '[count(*) > 0 or string-length() > 0]' , 'parent' => '[count(*) > 0]' , 'header' => '[self::h1 or self::h2 or self::h3 or self::h5 or self::h5 or self::h6]' , 'odd' => '[position() mod 2 = 0]' , 'even' => '[position() mod 2 = 1]' , 'first' => '[1]' , 'last' => '[last()]' , 'root' => '[not(parent::*)]' ) ; if ( ! isset ( $ pseudo_class_selectors [ $ expression ] ) ) { throw new \ Exception ( 'Pseudo class ' . $ expression . ' unknown' ) ; } return $ pseudo_class_selectors [ $ expression ] ; } | Transform css pseudo selector expression to xpath expression |
969 | private static function transformAttrSelector ( $ expression ) { if ( preg_match ( '|@?([a-z0-9_]+)(([\!\*\^\$\~\|]{0,1})=)[\'"]([^\'"]+)[\'"]|i' , $ expression , $ matches ) ) { if ( $ matches [ 3 ] === '' ) { return '[@' . strtolower ( $ matches [ 1 ] ) . "='" . $ matches [ 4 ] . "']" ; } elseif ( $ matches [ 3 ] === '!' ) { return '[@' . strtolower ( $ matches [ 1 ] ) . "!='" . $ matches [ 4 ] . "']" ; } elseif ( $ matches [ 3 ] === '~' ) { return "[contains(concat(' ', normalize-space(@" . strtolower ( $ matches [ 1 ] ) . "), ' '), ' " . $ matches [ 4 ] . " ')]" ; } elseif ( $ matches [ 3 ] === '*' ) { return "[contains(@" . strtolower ( $ matches [ 1 ] ) . ", '" . $ matches [ 4 ] . "')]" ; } elseif ( $ matches [ 3 ] === '^' ) { return "[starts-with(@" . strtolower ( $ matches [ 1 ] ) . ", '" . $ matches [ 4 ] . "')]" ; } elseif ( $ matches [ 3 ] === '$' ) { return "[@" . $ matches [ 1 ] . " and substring(@" . $ matches [ 1 ] . ", string-length(@" . $ matches [ 1 ] . ")-" . ( \ strlen ( $ matches [ 4 ] ) - 1 ) . ") = '" . $ matches [ 4 ] . "']" ; } elseif ( $ matches [ 3 ] === '|' ) { return '[@' . strtolower ( $ matches [ 1 ] ) . "='" . $ matches [ 4 ] . "' or starts-with(@" . strtolower ( $ matches [ 1 ] ) . ", '" . $ matches [ 4 ] . '-' . "')]" ; } } if ( preg_match ( '|([a-z0-9_]{1})([a-z0-9_-]*)|i' , $ expression , $ matches ) ) { return "[@" . $ matches [ 1 ] . $ matches [ 2 ] . "]" ; } throw new \ Exception ( 'Attribute selector is malformed or contains unsupported characters.' ) ; } | Transform css attribute selector expression to xpath expression |
970 | protected function command ( ) { $ command = 'php artisan spark:install --force' ; if ( $ this -> command -> input -> getOption ( 'braintree' ) ) { $ command .= ' --braintree' ; } if ( $ this -> command -> input -> getOption ( 'team-billing' ) ) { $ command .= ' --team-billing' ; } return $ command ; } | Get the proper Spark installation command . |
971 | protected function downloadZip ( ) { $ this -> command -> output -> writeln ( '<info>Downloading Spark...</info>' ) ; file_put_contents ( $ zipPath = $ this -> command -> path . '/spark-archive.zip' , $ this -> zipResponse ( ) ) ; return $ zipPath ; } | Download the latest Spark release . |
972 | protected function zipResponse ( ) { $ release = $ this -> latestSparkRelease ( ) ; try { return ( string ) ( new HttpClient ) -> get ( $ this -> sparkUrl . '/api/releases/' . $ release . '/download?api_token=' . $ this -> readToken ( ) , [ 'headers' => [ 'X-Requested-With' => 'XMLHttpRequest' , ] , 'verify' => __DIR__ . '/../cacert.pem' , ] ) -> getBody ( ) ; } catch ( ClientException $ e ) { if ( $ e -> getResponse ( ) -> getStatusCode ( ) === 401 ) { $ this -> invalidLicense ( $ release ) ; } throw $ e ; } } | Get the raw Zip response for a Spark download . |
973 | protected function extractZip ( $ zipPath ) { $ archive = new ZipArchive ; $ archive -> open ( $ zipPath ) ; $ archive -> extractTo ( $ this -> command -> path . '/spark-new' ) ; $ archive -> close ( ) ; @ unlink ( $ zipPath ) ; } | Extract the Spark Zip archive . |
974 | protected function sparkPath ( ) { return $ this -> command -> path . '/spark-new/' . basename ( ( new Filesystem ) -> directories ( $ this -> command -> path . '/spark-new' ) [ 0 ] ) ; } | Get the release directory . |
975 | protected function homePath ( ) { if ( ! empty ( $ _SERVER [ 'HOME' ] ) ) { return $ _SERVER [ 'HOME' ] ; } elseif ( ! empty ( $ _SERVER [ 'HOMEDRIVE' ] ) && ! empty ( $ _SERVER [ 'HOMEPATH' ] ) ) { return $ _SERVER [ 'HOMEDRIVE' ] . $ _SERVER [ 'HOMEPATH' ] ; } else { throw new Exception ( 'Cannot determine home directory.' ) ; } } | Get the User s home path . |
976 | protected function valid ( $ token ) { try { ( new HttpClient ) -> get ( $ this -> sparkUrl . '/api/token/' . $ token . '/validate' , [ 'verify' => __DIR__ . '/cacert.pem' ] ) ; return true ; } catch ( Exception $ e ) { var_dump ( $ e -> getMessage ( ) ) ; return false ; } } | Determine if the given token is valid . |
977 | protected function writeComposerFile ( $ composer ) { file_put_contents ( $ this -> command -> path . '/composer.json' , json_encode ( $ composer , JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) ) ; } | Write the given Composer configuration back to disk . |
978 | private function safe_decode ( $ data ) { if ( is_array ( $ data ) ) { return array_map ( array ( $ this , 'safe_decode' ) , $ data ) ; } else if ( is_scalar ( $ data ) ) { return rawurldecode ( $ data ) ; } else { return '' ; } } | Decodes the string or array from it s URL encoded form If an array is passed each array value will will be decoded . |
979 | private function prepare_oauth1_params ( ) { $ defaults = array ( 'oauth_nonce' => $ this -> nonce ( ) , 'oauth_timestamp' => $ this -> timestamp ( ) , 'oauth_version' => $ this -> config [ 'oauth_version' ] , 'oauth_consumer_key' => $ this -> config [ 'consumer_key' ] , 'oauth_signature_method' => $ this -> config [ 'oauth_signature_method' ] , ) ; if ( $ oauth_token = $ this -> token ( ) ) $ defaults [ 'oauth_token' ] = $ oauth_token ; $ this -> request_settings [ 'oauth1_params' ] = array ( ) ; foreach ( $ defaults as $ k => $ v ) { $ this -> request_settings [ 'oauth1_params' ] [ $ this -> safe_encode ( $ k ) ] = $ this -> safe_encode ( $ v ) ; } } | Prepares OAuth1 signing parameters . |
980 | private function prepare_url ( ) { $ parts = parse_url ( $ this -> request_settings [ 'url' ] ) ; $ port = isset ( $ parts [ 'port' ] ) ? $ parts [ 'port' ] : false ; $ scheme = $ parts [ 'scheme' ] ; $ host = $ parts [ 'host' ] ; $ path = isset ( $ parts [ 'path' ] ) ? $ parts [ 'path' ] : false ; $ port or $ port = ( $ scheme == 'https' ) ? '443' : '80' ; if ( ( $ scheme == 'https' && $ port != '443' ) || ( $ scheme == 'http' && $ port != '80' ) ) { $ host = "$host:$port" ; } $ this -> request_settings [ 'url' ] = strtolower ( "$scheme://$host" ) ; $ this -> request_settings [ 'url' ] .= $ path ; } | Prepares the URL for use in the base string by ripping it apart and reconstructing it . |
981 | private function multipart_escape ( $ value ) { if ( ! $ this -> request_settings [ 'multipart' ] || strpos ( $ value , '@' ) !== 0 ) return $ value ; list ( $ file ) = explode ( ';' , substr ( $ value , 1 ) , 2 ) ; if ( file_exists ( $ file ) ) return $ value ; return " $value" ; } | If the request uses multipart and the parameter isn t a file path prepend a space otherwise return the original value . we chose a space here as twitter whitespace trims from the beginning of the tweet . we don t use \ 0 here because it s the character for string termination . |
982 | private function prepare_oauth_signature ( ) { $ this -> request_settings [ 'oauth1_params' ] [ 'oauth_signature' ] = $ this -> safe_encode ( base64_encode ( hash_hmac ( 'sha1' , $ this -> request_settings [ 'basestring' ] , $ this -> request_settings [ 'signing_key' ] , true ) ) ) ; } | Signs the OAuth 1 request |
983 | public function bearer_token_credentials ( ) { $ credentials = implode ( ':' , array ( $ this -> safe_encode ( $ this -> config [ 'consumer_key' ] ) , $ this -> safe_encode ( $ this -> config [ 'consumer_secret' ] ) ) ) ; return base64_encode ( $ credentials ) ; } | Create the bearer token for OAuth2 requests from the consumer_key and consumer_secret . |
984 | public function streaming_request ( $ method , $ url , $ params = array ( ) , $ callback = '' ) { if ( ! empty ( $ callback ) ) { if ( ! is_callable ( $ callback ) ) { return false ; } $ this -> config [ 'streaming_callback' ] = $ callback ; } $ this -> metrics [ 'start' ] = time ( ) ; $ this -> metrics [ 'interval_start' ] = $ this -> metrics [ 'start' ] ; $ this -> metrics [ 'messages' ] = 0 ; $ this -> metrics [ 'last_messages' ] = 0 ; $ this -> metrics [ 'bytes' ] = 0 ; $ this -> metrics [ 'last_bytes' ] = 0 ; $ this -> config [ 'is_streaming' ] = true ; $ this -> request ( $ method , $ url , $ params ) ; } | Make a long poll HTTP request using this library . This method is different to the other request methods as it isn t supposed to disconnect |
985 | private function curlWrite ( $ ch , $ data ) { $ l = strlen ( $ data ) ; if ( strpos ( $ data , $ this -> config [ 'streaming_eol' ] ) === false ) { $ this -> buffer .= $ data ; return $ l ; } $ buffered = explode ( $ this -> config [ 'streaming_eol' ] , $ data ) ; $ content = $ this -> buffer . $ buffered [ 0 ] ; $ this -> metrics [ 'messages' ] ++ ; $ this -> metrics [ 'bytes' ] += strlen ( $ content ) ; if ( ! is_callable ( $ this -> config [ 'streaming_callback' ] ) ) return 0 ; $ metrics = $ this -> update_metrics ( ) ; $ stop = call_user_func ( $ this -> config [ 'streaming_callback' ] , $ content , strlen ( $ content ) , $ metrics ) ; $ this -> buffer = $ buffered [ 1 ] ; if ( $ stop ) return 0 ; return $ l ; } | Utility function to parse the returned curl buffer and store them until an EOL is found . The buffer for curl is an undefined size so we need to collect the content until an EOL is found . |
986 | public function keyResultsBy ( $ field ) { $ results = clone $ this -> results ; $ this -> results = new Collection ; foreach ( $ results as $ r ) { $ this -> addRecord ( $ r , $ field ) ; } } | Set which field s value will be used to key the records by |
987 | public function lists ( $ field ) { $ l = [ ] ; foreach ( $ this -> results as $ r ) { $ v = $ r -> get ( $ field ) ; if ( $ v and ! $ r -> isRestricted ( $ field ) ) { $ l [ ] = $ v ; } } return $ l ; } | Returns an array containing the values from the given field |
988 | public function toCSV ( ) { $ writer = Writer :: createFromFileObject ( new SplTempFileObject ) ; $ writer -> insertOne ( $ this -> getHeaders ( ) ) ; foreach ( $ this -> results as $ r ) { $ record = [ ] ; foreach ( $ this -> getHeaders ( ) as $ h ) { $ record [ ] = $ r -> get ( $ h ) ; } $ writer -> insertOne ( $ record ) ; } return ( string ) $ writer ; } | Return results as a large prepared CSV string |
989 | public function toArray ( ) { $ result = [ ] ; foreach ( $ this -> results as $ r ) { $ result [ ] = $ r -> toArray ( ) ; } return $ result ; } | Return results as a simple array |
990 | public function cleanConfig ( ) { foreach ( $ this -> config as $ name => $ key_value ) { foreach ( $ key_value as $ key => $ value ) { $ this -> getDriver ( ) -> configSet ( $ name , $ key , $ value ) ; } } $ this -> config = array ( ) ; } | Revert any changed config . |
991 | public function setComplexConfig ( $ name , $ key , TableNode $ config_table ) { $ value = array ( ) ; foreach ( $ config_table -> getHash ( ) as $ row ) { if ( json_decode ( $ row [ 'value' ] ) ) { $ row [ 'value' ] = json_decode ( $ row [ 'value' ] , true ) ; } $ value [ $ row [ 'key' ] ] = $ row [ 'value' ] ; } $ this -> setConfig ( $ name , $ key , $ value ) ; } | Sets complex configuration . |
992 | public function setConfig ( $ name , $ key , $ value ) { $ backup = $ this -> getDriver ( ) -> configGet ( $ name , $ key ) ; $ this -> getDriver ( ) -> configSet ( $ name , $ key , $ value ) ; if ( ! array_key_exists ( $ name , $ this -> config ) ) { $ this -> config [ $ name ] [ $ key ] = $ backup ; return ; } if ( ! array_key_exists ( $ key , $ this -> config [ $ name ] ) ) { $ this -> config [ $ name ] [ $ key ] = $ backup ; } } | Sets a value in a configuration object . |
993 | public function prepareDefaultDrupalDriver ( $ event ) { $ feature = $ event -> getFeature ( ) ; $ scenario = $ event instanceof ScenarioLikeTested ? $ event -> getScenario ( ) : $ event -> getOutline ( ) ; $ driver = $ this -> parameters [ 'default_driver' ] ; foreach ( array_merge ( $ feature -> getTags ( ) , $ scenario -> getTags ( ) ) as $ tag ) { if ( ! empty ( $ this -> parameters [ $ tag . '_driver' ] ) ) { $ driver = $ this -> parameters [ $ tag . '_driver' ] ; } } $ this -> drupal -> setDefaultDriverName ( $ driver ) ; $ environment = $ event -> getEnvironment ( ) ; $ this -> drupal -> setEnvironment ( $ environment ) ; } | Configures default Drupal driver to use before each scenario or outline . |
994 | public function getRegion ( $ region ) { $ session = $ this -> getSession ( ) ; $ regionObj = $ session -> getPage ( ) -> find ( 'region' , $ region ) ; if ( ! $ regionObj ) { throw new \ Exception ( sprintf ( 'No region "%s" found on the page %s.' , $ region , $ session -> getCurrentUrl ( ) ) ) ; } return $ regionObj ; } | Return a region from the current page . |
995 | public function assertAtPath ( $ path ) { $ this -> getSession ( ) -> visit ( $ this -> locatePath ( $ path ) ) ; try { $ this -> getSession ( ) -> getStatusCode ( ) ; $ this -> assertHttpResponse ( '200' ) ; } catch ( UnsupportedDriverActionException $ e ) { } } | Visit a given path and additionally check for HTTP response code 200 . |
996 | public function beforeJavascriptStep ( $ event ) { $ this -> registerFeature ( $ event ) ; if ( ! $ this -> hasTag ( 'javascript' ) ) { return ; } $ text = $ event -> getStep ( ) -> getText ( ) ; if ( preg_match ( '/(follow|press|click|submit)/i' , $ text ) ) { $ this -> iWaitForAjaxToFinish ( $ event ) ; } } | For javascript enabled scenarios always wait for AJAX before clicking . |
997 | public function afterJavascriptStep ( $ event ) { if ( ! $ this -> hasTag ( 'javascript' ) ) { return ; } $ text = $ event -> getStep ( ) -> getText ( ) ; if ( preg_match ( '/(follow|press|click|submit)/i' , $ text ) ) { $ this -> iWaitForAjaxToFinish ( $ event ) ; } } | For javascript enabled scenarios always wait for AJAX after clicking . |
998 | public function iWaitForAjaxToFinish ( $ event = null ) { $ condition = <<<JS (function() { function isAjaxing(instance) { return instance && instance.ajaxing === true; } var d7_not_ajaxing = true; if (typeof Drupal !== 'undefined' && typeof Drupal.ajax !== 'undefined' && typeof Drupal.ajax.instances === 'undefined') { for(var i in Drupal.ajax) { if (isAjaxing(Drupal.ajax[i])) { d7_not_ajaxing = false; } } } var d8_not_ajaxing = (typeof Drupal === 'undefined' || typeof Drupal.ajax === 'undefined' || typeof Drupal.ajax.instances === 'undefined' || !Drupal.ajax.instances.some(isAjaxing)) return ( // Assert no AJAX request is running (via jQuery or Drupal) and no // animation is running. (typeof jQuery === 'undefined' || (jQuery.active === 0 && jQuery(':animated').length === 0)) && d7_not_ajaxing && d8_not_ajaxing ); }());JS ; $ ajax_timeout = $ this -> getMinkParameter ( 'ajax_timeout' ) ; $ result = $ this -> getSession ( ) -> wait ( 1000 * $ ajax_timeout , $ condition ) ; if ( ! $ result ) { if ( $ ajax_timeout === null ) { throw new \ Exception ( 'No AJAX timeout has been defined. Please verify that "Drupal\MinkExtension" is configured in behat.yml (and not "Behat\MinkExtension").' ) ; } if ( $ event ) { $ event_data = ' ' . json_encode ( [ 'name' => $ event -> getName ( ) , 'feature' => $ event -> getFeature ( ) -> getTitle ( ) , 'step' => $ event -> getStep ( ) -> getText ( ) , 'suite' => $ event -> getSuite ( ) -> getName ( ) , ] ) ; } else { $ event_data = '' ; } throw new \ RuntimeException ( 'Unable to complete AJAX request.' . $ event_data ) ; } } | Wait for AJAX to finish . |
999 | public function pressButton ( $ button ) { try { $ this -> getSession ( ) -> wait ( 1000 , 'typeof(jQuery)=="undefined" || jQuery("#autocomplete").length === 0' ) ; } catch ( UnsupportedDriverActionException $ e ) { } return parent :: pressButton ( $ button ) ; } | Presses button with specified id|name|title|alt|value . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.