idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
51,200
public function getAvgExecutionTime ( ) : float { return $ this -> getTotalExecutionTime ( ) ? ( $ this -> getTotalExecutionTime ( ) / \ count ( $ this -> data [ 'commands' ] ) ) : ( float ) 0 ; }
Get average execution time .
51,201
protected function notifyEvent ( $ command , $ arguments , $ return , $ time = 0 ) { if ( $ this -> eventDispatcher ) { $ event = new $ this -> eventClass ( ) ; $ event -> setCommand ( $ command ) -> setArguments ( $ arguments ) -> setReturn ( $ return ) -> setExecutionTime ( $ time ) ; $ this -> eventDispatcher -> dispatch ( 'amqp.command' , $ event ) ; } }
Notify an event to the event dispatcher .
51,202
protected function call ( $ object , $ name , array $ arguments = [ ] ) { $ start = microtime ( true ) ; $ ret = call_user_func_array ( array ( $ object , $ name ) , $ arguments ) ; $ this -> notifyEvent ( $ name , $ arguments , $ ret , microtime ( true ) - $ start ) ; return $ ret ; }
Call a method and notify an event .
51,203
public function setEventDispatcher ( $ eventDispatcher , $ eventClass ) { if ( ! is_object ( $ eventDispatcher ) || ! method_exists ( $ eventDispatcher , 'dispatch' ) ) { throw new Exception ( 'The EventDispatcher must be an object and implement a dispatch method' ) ; } $ class = new \ ReflectionClass ( $ eventClass ) ; if ( ! $ class -> implementsInterface ( '\M6Web\Bundle\AmqpBundle\Event\DispatcherInterface' ) ) { throw new Exception ( 'The Event class : ' . $ eventClass . ' must implement DispatcherInterface' ) ; } $ this -> eventDispatcher = $ eventDispatcher ; $ this -> eventClass = $ eventClass ; }
Set an event dispatcher to notify amqp command .
51,204
public function get ( $ class , $ connexion , array $ exchangeOptions , array $ queueOptions , $ lazy = false ) { if ( ! class_exists ( $ class ) ) { throw new \ InvalidArgumentException ( sprintf ( "Producer class '%s' doesn't exist" , $ class ) ) ; } if ( $ lazy ) { if ( ! $ connexion -> isConnected ( ) ) { $ connexion -> connect ( ) ; } } $ channel = new $ this -> channelClass ( $ connexion ) ; $ exchange = $ this -> createExchange ( $ this -> exchangeClass , $ channel , $ exchangeOptions ) ; if ( isset ( $ queueOptions [ 'name' ] ) ) { $ queue = new $ this -> queueClass ( $ channel ) ; $ queue -> setName ( $ queueOptions [ 'name' ] ) ; $ queue -> setArguments ( $ queueOptions [ 'arguments' ] ) ; $ queue -> setFlags ( ( $ queueOptions [ 'passive' ] ? AMQP_PASSIVE : AMQP_NOPARAM ) | ( $ queueOptions [ 'durable' ] ? AMQP_DURABLE : AMQP_NOPARAM ) | ( $ queueOptions [ 'auto_delete' ] ? AMQP_AUTODELETE : AMQP_NOPARAM ) ) ; $ queue -> declareQueue ( ) ; $ queue -> bind ( $ exchangeOptions [ 'name' ] ) ; foreach ( $ queueOptions [ 'routing_keys' ] as $ routingKey ) { $ queue -> bind ( $ exchangeOptions [ 'name' ] , $ routingKey ) ; } } $ producer = new $ class ( $ exchange , $ exchangeOptions ) ; return $ producer ; }
build the producer class .
51,205
private function exchangeOptions ( ) { $ builder = new NodeBuilder ( ) ; return $ builder -> arrayNode ( 'exchange_options' ) -> children ( ) -> scalarNode ( 'name' ) -> isRequired ( ) -> end ( ) -> scalarNode ( 'type' ) -> info ( 'Set the type of the exchange. If exchange already exist - you can skip it. Otherwise behavior is unpredictable' ) -> end ( ) -> booleanNode ( 'passive' ) -> defaultFalse ( ) -> end ( ) -> booleanNode ( 'durable' ) -> defaultTrue ( ) -> end ( ) -> booleanNode ( 'auto_delete' ) -> defaultFalse ( ) -> end ( ) -> arrayNode ( 'arguments' ) -> prototype ( 'scalar' ) -> end ( ) -> defaultValue ( array ( ) ) -> normalizeKeys ( false ) -> end ( ) -> arrayNode ( 'routing_keys' ) -> prototype ( 'scalar' ) -> end ( ) -> defaultValue ( array ( ) ) -> end ( ) -> arrayNode ( 'publish_attributes' ) -> prototype ( 'scalar' ) -> end ( ) -> defaultValue ( array ( ) ) -> end ( ) -> end ( ) ; }
Exchange options for both consumer and producer .
51,206
protected function createExchange ( $ exchangeClass , $ channel , array $ exchangeOptions ) { $ exchange = new $ exchangeClass ( $ channel ) ; $ exchange -> setName ( $ exchangeOptions [ 'name' ] ) ; if ( isset ( $ exchangeOptions [ 'type' ] ) ) { $ exchange -> setType ( $ exchangeOptions [ 'type' ] ) ; $ exchange -> setArguments ( $ exchangeOptions [ 'arguments' ] ) ; $ exchange -> setFlags ( ( $ exchangeOptions [ 'passive' ] ? AMQP_PASSIVE : AMQP_NOPARAM ) | ( $ exchangeOptions [ 'durable' ] ? AMQP_DURABLE : AMQP_NOPARAM ) | ( $ exchangeOptions [ 'auto_delete' ] ? AMQP_AUTODELETE : AMQP_NOPARAM ) ) ; $ exchange -> declareExchange ( ) ; } return $ exchange ; }
Create and declare exchange .
51,207
public static function assertHasCss ( $ node , $ selector , array $ filters = [ ] , string $ message = '' ) { PHPUnitAssert :: assertThat ( $ node , new LocatorConstraint ( 'css' , $ selector , $ filters ) , $ message ) ; }
Assert that an html tag exists inside the current tag .
51,208
public static function assertHasNoCss ( $ node , $ selector , array $ filters = [ ] , string $ message = '' ) { PHPUnitAssert :: assertThat ( $ node , new NegativeLocatorConstraint ( 'css' , $ selector , $ filters ) , $ message ) ; }
Assert that an html tag does not exist inside the current tag .
51,209
public static function to_absolute_attribute ( $ attribute , $ content , $ base_url = null ) { return preg_replace ( '/(' . $ attribute . '=[\'"])\//' , '$1' . rtrim ( $ base_url , '/' ) . '/' , $ content ) ; }
Convert an attribute strigng from a relative to absolute by providing a base_url .
51,210
public static function autocreate_directory ( $ directory ) { if ( ! file_exists ( $ directory ) ) { mkdir ( $ directory , 0777 , true ) ; } if ( ! is_writable ( $ directory ) ) { throw new \ Exception ( "Directory \"{$directory}\" is not writable" ) ; } }
Check if a directory does not exist create it otherwise check if it is writable .
51,211
public static function clear_directory ( $ directory ) { foreach ( scandir ( $ directory ) as $ file ) { if ( $ file !== '.' and $ file !== '..' ) { unlink ( $ directory . $ file ) ; } } }
Delete all the files from a directory .
51,212
public function save_driver_content ( \ Openbuildings \ Spiderling \ Driver $ driver , $ filename , $ title ) { $ content = $ driver -> content ( ) ; foreach ( [ 'href' , 'action' , 'src' ] as $ attribute ) { $ content = self :: to_absolute_attribute ( $ attribute , $ content , $ this -> _base_url ) ; } $ testview = self :: render_file ( __DIR__ . '/../assets/error-page.php' , [ 'url' => $ driver -> current_url ( ) , 'title' => $ title , 'javascript_errors' => $ driver -> javascript_errors ( ) , 'javascript_messages' => $ driver -> javascript_messages ( ) , ] ) ; $ page_content = str_replace ( '</body>' , $ testview . '</body>' , $ content ) ; file_put_contents ( $ this -> _directory . "/$filename.html" , $ page_content ) ; try { $ driver -> screenshot ( $ this -> _directory . "/$filename.png" ) ; } catch ( \ Openbuildings \ Spiderling \ Exception_Notimplemented $ e ) { } }
Save the current content of the driver into an html file . Add javascript errors messages and a title to the html content .
51,213
public function init ( $ argument = false , $ multiple = false ) { if ( ! empty ( $ argument ) ) { return new ArgumentTypeAbstract ( ( $ multiple === true ) ? $ this -> makeMultiple ( $ this -> getArguments ( ) ) : $ this -> getArguments ( ) , $ this -> getName ( ) , $ this -> getDescription ( ) , $ multiple ) ; } return new FieldAbstract ( ( $ multiple === true ) ? new ListType ( $ this -> getFields ( ) ) : $ this -> getFields ( ) , $ this -> getName ( ) , $ this -> getDescription ( ) ) ; }
Create an object depends on is argument required
51,214
public function getArguments ( $ groupName = null , $ multiple = false ) { return $ this -> setRequired ( $ this -> updateRelations ( $ this -> builder -> getArguments ( ) , true , $ multiple ) , $ groupName ) ; }
Return array of arguments
51,215
private function setRequired ( array $ fields , string $ groupName = null ) : array { foreach ( $ fields as $ fieldName => $ field ) { if ( ! empty ( $ field [ 'required' ] ) ) { if ( isset ( $ field [ 'groups' ] ) && ! is_array ( $ field [ 'groups' ] ) ) { $ field [ 'groups' ] = [ $ field [ 'groups' ] ] ; } if ( empty ( $ field [ 'groups' ] ) || in_array ( $ groupName , $ field [ 'groups' ] ) ) { $ fields [ $ fieldName ] = $ this -> makeRequired ( $ fields [ $ fieldName ] ) ; } } } return $ fields ; }
Set required to attributes
51,216
protected function hydrate ( $ entity , array $ arguments ) { foreach ( $ arguments as $ argument => $ value ) { if ( is_array ( $ value ) ) { if ( isset ( $ this -> em -> getClassMetadata ( get_class ( $ entity ) ) -> associationMappings [ $ argument ] ) ) { $ value = $ this -> hydrateRelation ( $ entity , $ argument , $ value ) ; } } $ entity -> { "set" . Inflector :: camelize ( $ argument ) } ( $ value ) ; } return $ entity ; }
Hydrate array to entity object
51,217
private function hydrateRelation ( $ entity , $ name , $ value ) { $ relationClass = $ this -> em -> getClassMetadata ( get_class ( $ entity ) ) -> getAssociationMapping ( $ name ) [ "targetEntity" ] ; $ relation = $ entity -> { "get" . Inflector :: camelize ( $ name ) } ( ) ; if ( in_array ( 'id' , array_keys ( $ value ) ) ) { $ relation = $ this -> em -> getRepository ( $ relationClass ) -> find ( $ value [ 'id' ] ) ; unset ( $ value [ 'id' ] ) ; } elseif ( empty ( $ relation ) ) { $ relation = new $ relationClass ; } return $ this -> hydrate ( $ relation , $ value ) ; }
Map and hydrate relations
51,218
private function mapScalarFields ( array $ fullFields ) { $ fields = [ ] ; foreach ( $ fullFields as $ field ) { if ( ! empty ( $ field [ 'id' ] ) ) { $ type = 'IdType' ; } else { switch ( $ field [ 'type' ] ) { case "integer" : $ type = 'IntType' ; break ; case "datetime" : $ type = 'DateTimeType' ; break ; case "float" : $ type = 'FloatType' ; break ; case "boolean" : $ type = 'BooleanType' ; break ; case "date" : $ type = 'DateType' ; break ; case "timestamp" : $ type = 'TimestampType' ; break ; default : $ type = 'StringType' ; } } $ fields [ ] = [ 'fieldName' => $ field [ 'fieldName' ] , 'fieldType' => $ type , 'fieldRequired' => $ field [ 'nullable' ] ] ; } return $ fields ; }
Map fields type and required
51,219
private function createService ( $ boundObject , $ boundClassVars , InputInterface $ input , Generator $ generator ) { $ serviceClassNameDetails = $ generator -> createClassNameDetails ( $ input -> getArgument ( 'name' ) . 'Service' , 'Service\\GraphQL' ) ; $ generator -> generateClass ( $ serviceClassNameDetails -> getFullName ( ) , dirname ( dirname ( __FILE__ ) ) . '/Resources/skeleton/Service.tpl.php' , array_merge ( [ 'entityFullName' => $ boundObject [ 'bounded_full_class_name' ] , 'entityName' => $ boundObject [ 'bounded_class_name' ] , ] , $ boundClassVars ) ) ; $ generator -> writeChanges ( ) ; return $ serviceClassNameDetails ; }
Creates helper class
51,220
public function getClassesByPath ( $ path ) { $ allClasses = [ ] ; foreach ( $ this -> findAllClasses ( [ $ this -> rootPath . "/$path" ] , 'php' ) as $ class ) { $ allClasses [ ] = trim ( $ class , "0\\" ) ; } return $ allClasses ; }
Get classes by path
51,221
public function findAllClasses ( array $ dirs , string $ extension ) { $ classes = array ( ) ; foreach ( $ dirs as $ prefix => $ dir ) { $ iterator = new \ RecursiveIteratorIterator ( new \ RecursiveDirectoryIterator ( $ dir ) , \ RecursiveIteratorIterator :: LEAVES_ONLY ) ; $ nsPrefix = $ prefix !== '' ? $ prefix . '\\' : '' ; foreach ( $ iterator as $ file ) { if ( ( $ fileName = $ file -> getBasename ( '.' . $ extension ) ) == $ file -> getBasename ( ) ) { continue ; } $ classes [ ] = $ nsPrefix . str_replace ( '.' , '\\' , $ fileName ) ; } } return $ classes ; }
Find all classes by path and extension
51,222
protected function updateRelations ( array $ fields , $ argument = false ) { foreach ( $ fields as $ key => $ field ) { foreach ( $ field as $ name => $ value ) { if ( $ name == 'type' ) { if ( $ value instanceof ListType ) { if ( $ value -> getItemType ( ) instanceof TypeAbstract ) { $ fields [ $ key ] [ $ name ] = new ListType ( $ value -> getItemType ( ) -> init ( $ argument ) ) ; } } if ( $ value instanceof TypeAbstract ) { $ fields [ $ key ] [ $ name ] = $ value -> init ( $ argument ) ; } } } } return $ fields ; }
Update all relation fields to argument or field . Depends on type argument
51,223
protected function makeRequired ( $ argument ) { if ( $ argument instanceof TypeInterface ) { $ argument = new NonNullType ( $ argument ) ; } elseif ( is_array ( $ argument ) ) { $ argument [ 'type' ] = new NonNullType ( $ argument [ 'type' ] ) ; } return $ argument ; }
Make Argument required
51,224
protected function makeMultiple ( array $ arguments ) { $ result = [ ] ; foreach ( $ arguments as $ argumentName => $ argument ) { $ result [ $ argumentName ] = $ argument [ 'type' ] = new ListType ( $ argument [ 'type' ] ) ; } return $ result ; }
Make argument as list
51,225
private function register ( $ type , $ actions , Generator $ generator ) { $ classes = [ 'Query' => [ 'namespace' => 'GraphQL\\Query' , 'template' => 'Query.tpl.php' , ] , 'Mutation' => [ 'namespace' => 'GraphQL\\Mutation' , 'template' => 'Mutation.tpl.php' , ] , ] ; $ class = $ classes [ $ type ] ; $ classNameDetails = $ generator -> createClassNameDetails ( $ type . 'Type' , $ class [ 'namespace' ] ) ; $ classFields = [ ] ; $ fileName = $ this -> fileManager -> getRelativePathForFutureClass ( $ classNameDetails -> getFullName ( ) ) ; $ classObjectFullName = $ classNameDetails -> getFullName ( ) ; if ( is_file ( $ fileName ) ) { $ classObject = $ this -> { lcfirst ( $ type ) . 'Type' } ; foreach ( $ classObject -> getFields ( ) as $ classField ) { $ classFields [ ] = [ 'fullName' => get_class ( $ classField ) , 'shortName' => Str :: getShortClassName ( get_class ( $ classField ) ) ] ; } $ tmpFileName = $ fileName . '.bak' ; rename ( $ fileName , $ tmpFileName ) ; } $ generator -> generateClass ( $ classNameDetails -> getFullName ( ) , dirname ( dirname ( __FILE__ ) ) . '/Resources/skeleton/' . $ class [ 'template' ] , [ 'fields' => array_merge ( $ classFields , [ $ actions ] ) ] ) ; $ generator -> writeChanges ( ) ; if ( is_file ( $ fileName ) && isset ( $ tmpFileName ) ) { unlink ( $ tmpFileName ) ; } }
Register class in main query
51,226
protected function cutArgument ( $ name , & $ args ) { if ( isset ( $ args [ $ name ] ) ) { $ result = $ args [ $ name ] ; unset ( $ args [ $ name ] ) ; return $ result ; } return null ; }
Get argument and delete them from list of incoming arguments
51,227
public function addField ( string $ name , $ type , array $ options = [ ] ) { $ this -> fields [ $ name ] = array_merge ( $ options , [ 'type' => $ type ] ) ; if ( ! isset ( $ options [ 'argument' ] ) || $ options [ 'argument' ] !== false ) { $ this -> arguments [ $ name ] = array_merge ( $ options , [ 'type' => $ type ] ) ; } return $ this ; }
Add single fields with type and list of options
51,228
public function withResourceOwnerVersion ( $ resourceOwnerVersion ) { $ resourceOwnerVersion = ( int ) $ resourceOwnerVersion ; if ( in_array ( $ resourceOwnerVersion , [ 1 , 2 ] ) ) { $ this -> resourceOwnerVersion = $ resourceOwnerVersion ; } return $ this ; }
Updates the preferred resource owner version .
51,229
public function open ( $ pdfFile ) { $ this -> file = $ pdfFile ; $ this -> setOutputDirectory ( dirname ( $ pdfFile ) ) ; return $ this ; }
open pdf file that will be converted . make sure it is exists
51,230
public function generate ( ) { $ output = $ this -> outputDir . "/" . preg_replace ( "/\.pdf$/" , "" , basename ( $ this -> file ) ) . ".html" ; $ options = $ this -> generateOptions ( ) ; if ( PHP_OS === 'WINNT' ) { $ command = '"' . $ this -> bin ( ) . '" ' . $ options . ' "' . $ this -> file . '" "' . $ output . '"' ; } else { $ command = $ this -> bin ( ) . " " . $ options . " '" . $ this -> file . "' '" . $ output . "'" ; } exec ( $ command ) ; return $ this ; }
generating html files using pdftohtml software .
51,231
public function generateOptions ( ) { $ generated = [ ] ; array_walk ( $ this -> options , function ( $ value , $ key ) use ( & $ generated ) { $ result = "" ; switch ( $ key ) { case "singlePage" : $ result = $ value ? "-c" : "-s" ; break ; case "imageJpeg" : $ result = "-fmt " . ( $ value ? "jpg" : "png" ) ; break ; case "zoom" : $ result = "-zoom " . $ value ; break ; case "ignoreImages" : $ result = $ value ? "-i" : "" ; break ; case 'noFrames' : $ result = $ value ? '-noframes' : '' ; break ; } $ generated [ ] = $ result ; } ) ; return implode ( " " , $ generated ) ; }
generate options based on the preserved options
51,232
public function setOptions ( $ key , $ value ) { if ( isset ( $ this -> options [ $ key ] ) ) $ this -> options [ $ key ] = $ value ; return $ this ; }
change value of preserved configuration
51,233
public function clearOutputDirectory ( ) { $ files = new \ RecursiveIteratorIterator ( new \ RecursiveDirectoryIterator ( $ this -> outputDir , \ FilesystemIterator :: SKIP_DOTS ) ) ; foreach ( $ files as $ file ) { $ path = ( string ) $ file ; $ basename = basename ( $ path ) ; if ( $ basename != '..' && $ basename != ".gitignore" ) { if ( is_file ( $ path ) && file_exists ( $ path ) ) unlink ( $ path ) ; elseif ( is_dir ( $ path ) && file_exists ( $ path ) ) rmdir ( $ path ) ; } } return $ this ; }
clear the whole files that has been generated by pdftohtml . Make sure directory ONLY contain generated files from pdftohtml because it remove the whole contents under preserved output directory
51,234
public function getJs ( ) { $ bounds = $ this -> getBounds ( ) -> getJs ( ) ; $ options = $ this -> getEncodedOptions ( ) ; $ js = [ ] ; $ js [ ] = "var {$this->getName()} = new google.maps.GroundOverlay('{$this->url}',{$bounds}, {$options});" ; foreach ( $ this -> events as $ event ) { $ js [ ] = $ event -> getJs ( $ this -> getName ( ) ) ; } return implode ( "\n" , $ js ) ; }
Returns the js code to create a rectangle on a map
51,235
public function getName ( $ autoGenerate = true ) { if ( ! empty ( $ this -> _name ) ) { return $ this -> _name ; } if ( $ autoGenerate ) { $ reflection = new \ ReflectionClass ( $ this ) ; $ this -> _name = self :: $ autoNamePrefix . Inflector :: variablize ( $ reflection -> getShortName ( ) ) . self :: $ counter ++ ; } return $ this -> _name ; }
Returns the name of the object that is going to be used as a js variable of the renderer service .
51,236
public function setEvents ( $ events ) { $ events = ( array ) $ events ; foreach ( $ events as $ event ) { $ this -> addEvent ( $ event ) ; } }
Batch set events by an array of Event objects
51,237
public function getEncodedOptions ( ) { $ options = [ ] ; foreach ( $ this -> options as $ key => $ value ) { if ( $ value === null ) { continue ; } $ options [ $ key ] = $ this -> encode ( $ value ) ; } return Json :: encode ( $ options ) ; }
Returns json encoded options to configure js objects
51,238
protected function encode ( $ value ) { if ( is_object ( $ value ) && method_exists ( $ value , 'getJs' ) ) { return new JsExpression ( $ value -> getJs ( ) ) ; } elseif ( is_bool ( $ value ) ) { return new JsExpression ( ( $ value ? 'true' : 'false' ) ) ; } elseif ( is_array ( $ value ) ) { $ parsed = [ ] ; foreach ( $ value as $ child ) { $ parsed [ ] = $ this -> encode ( $ child ) ; } return $ parsed ; } try { return Json :: decode ( $ value ) ; } catch ( InvalidParamException $ e ) { } return $ value ; }
Makes sure a value is properly set to be JSON encoded
51,239
public function setMapTypeIds ( array $ types ) { $ parsed = [ ] ; foreach ( $ types as $ type ) { $ parsed [ ] = MapTypeId :: getIsValid ( $ type ) ? new JsExpression ( $ type ) : $ type ; } $ this -> options [ 'mapTypeIds' ] = $ parsed ; }
Sets the map type ids and makes sure to get the proper value on the array
51,240
public function setTravelMode ( $ value ) { if ( ! TravelMode :: getIsValid ( $ value ) ) { throw new InvalidConfigException ( 'Invalid "travelMode" value' ) ; } $ this -> options [ 'travelMode' ] = new JsExpression ( $ value ) ; }
Sets the travelMode
51,241
public function setPosition ( $ value ) { if ( ! ControlPosition :: getIsValid ( $ value ) ) { throw new InvalidConfigException ( 'Unknown "position" value' ) ; } $ this -> options [ 'position' ] = new JsExpression ( $ value ) ; }
Sets the position of the control .
51,242
public function setOptions ( InfoWindowOptions $ infoWindowOptions ) { $ options = array_filter ( $ infoWindowOptions -> options ) ; $ this -> options = ArrayHelper :: merge ( $ this -> options , $ options ) ; }
Sets the options based on a InfoWindowOptions object
51,243
public function setAnimation ( $ animation ) { if ( ! in_array ( $ animation , [ Animation :: BOUNCE , Animation :: DROP ] ) ) { throw new InvalidConfigException ( 'Unknown animation' ) ; } $ this -> options [ 'animation' ] = new JsExpression ( $ animation ) ; }
Sets the animation of the marker
51,244
public function setLabelColor ( $ value ) { if ( ! LabelColor :: getIsValid ( $ value ) ) { throw new InvalidConfigException ( 'Unknown "labelColor" value' ) ; } $ this -> options [ 'labelColor' ] = new JsExpression ( $ value ) ; }
Sets the labelColor making sure it is not going to be encoded as a js string .
51,245
public function setTemperatureUnits ( $ value ) { if ( ! TemperatureUnit :: getIsValid ( $ value ) ) { throw new InvalidConfigException ( 'Unknown "temperatureUnits" value' ) ; } $ this -> options [ 'temperatureUnits' ] = new JsExpression ( $ value ) ; }
Sets the temperatureUnits making sure it is not going to be encoded as a js string .
51,246
public function setWindSpeedUnits ( $ value ) { if ( ! WindSpeedUnits :: getIsValid ( $ value ) ) { throw new InvalidConfigException ( 'Unknown "windSpeedUnits" value' ) ; } $ this -> options [ 'windSpeedUnits' ] = new JsExpression ( $ value ) ; }
Sets the windSpeedUnits making sure it is not going to be encoded as a js string .
51,247
public function setStrokePosition ( $ value ) { if ( ! StrokePosition :: getIsValid ( $ value ) ) { throw new InvalidConfigException ( 'Unknown "StrokePosition" value' ) ; } $ this -> options [ 'strokePosition' ] = new JsExpression ( $ value ) ; }
Sets the stroke position
51,248
public function getJs ( ) { $ js = $ this -> getInfoWindowJs ( ) ; $ js [ ] = "var {$this->getName()} = new google.maps.Marker({$this->getEncodedOptions()});" ; foreach ( $ this -> events as $ event ) { $ js [ ] = $ event -> getJs ( $ this -> getName ( ) ) ; } return implode ( "\n" , $ js ) ; }
The constructor js code for the Marker object
51,249
public static function getCenterOfMarkers ( $ markers ) { $ coords = [ ] ; foreach ( $ markers as $ marker ) { if ( ! ( $ marker instanceof Marker ) ) { throw new InvalidParamException ( '$markers must be an array of "' . self :: className ( ) . '" objects' ) ; } $ coords [ ] = $ marker -> position ; } return LatLng :: getCenterOfCoordinates ( $ coords ) ; }
Returns the center coordinates of an array of Markers
51,250
public function getCenterLat ( ) { return ( is_null ( $ this -> getSouthWest ( ) ) || is_null ( $ this -> getNorthEast ( ) ) ) ? null : floatval ( ( $ this -> getSouthWest ( ) -> getLat ( ) + $ this -> getNorthEast ( ) -> getLat ( ) ) / 2 ) ; }
Get the latitude of the center of the zone
51,251
public function getCenterLng ( ) { return ( is_null ( $ this -> getSouthWest ( ) ) || is_null ( $ this -> getNorthEast ( ) ) ) ? null : floatval ( ( $ this -> getSouthWest ( ) -> getLng ( ) + $ this -> getNorthEast ( ) -> getLng ( ) ) / 2 ) ; }
Get the longitude of the center of the zone
51,252
public function getHomothety ( $ factor ) { $ bounds = new LatLngBounds ( ) ; $ lat = $ this -> getCenterLat ( ) ; $ lng = $ this -> getCenterLng ( ) ; $ bounds -> getNorthEast ( ) -> setLat ( $ factor * $ this -> getNorthEast ( ) -> getLat ( ) + $ lat * ( 1 - $ factor ) ) ; $ bounds -> getSouthWest ( ) -> setLat ( $ factor * $ this -> getSouthWest ( ) -> getLat ( ) + $ lat * ( 1 - $ factor ) ) ; $ bounds -> getNorthEast ( ) -> setLng ( $ factor * $ this -> getNorthEast ( ) -> getLng ( ) + $ lng * ( 1 - $ factor ) ) ; $ bounds -> getSouthWest ( ) -> setLng ( $ factor * $ this -> getSouthWest ( ) -> getLng ( ) + $ lng * ( 1 - $ factor ) ) ; return $ bounds ; }
Does a homothety transformation on the bounds centered on the center of the bounds
51,253
public function getZoomOut ( $ zoomCoeficient ) { if ( $ zoomCoeficient > 0 ) { $ bounds = $ this -> getHomothety ( pow ( 2 , $ zoomCoeficient ) ) ; return $ bounds ; } return $ this ; }
Returns zoomed out bounds
51,254
public static function getBoundsOfBounds ( $ boundaries , $ margin = 0.0 ) { $ minLat = 1000 ; $ maxLat = - 1000 ; $ minLng = 1000 ; $ maxLng = - 1000 ; foreach ( $ boundaries as $ bounds ) { if ( ! ( $ bounds instanceof LatLngBounds ) ) { throw new InvalidParamException ( '"$boundaries" must be an array of "' . self :: className ( ) . '" objects' ) ; } $ minLat = min ( $ minLat , $ bounds -> getSouthWest ( ) -> getLat ( ) ) ; $ minLng = min ( $ minLng , $ bounds -> getSouthWest ( ) -> getLng ( ) ) ; $ maxLat = max ( $ maxLat , $ bounds -> getNorthEast ( ) -> getLat ( ) ) ; $ maxLng = max ( $ maxLng , $ bounds -> getNorthEast ( ) -> getLng ( ) ) ; } if ( $ margin > 0 ) { $ minLat = $ minLat - $ margin * ( $ maxLat - $ minLat ) ; $ minLng = $ minLng - $ margin * ( $ maxLng - $ minLng ) ; $ maxLat = $ maxLat + $ margin * ( $ maxLat - $ minLat ) ; $ maxLng = $ maxLng + $ margin * ( $ maxLng - $ minLng ) ; } return new self ( [ 'southWest' => new LatLng ( [ 'lat' => $ minLat , 'lng' => $ minLng ] ) , 'northEast' => new LatLng ( [ 'lat' => $ maxLat , 'lng' => $ maxLng ] ) ] ) ; }
Returns the boundaries of an array of Bound objects
51,255
public static function getBoundsOfCoordinates ( $ coords , $ margin = 0.0 ) { $ minLat = 1000 ; $ maxLat = - 1000 ; $ minLng = 1000 ; $ maxLng = - 1000 ; foreach ( $ coords as $ coord ) { if ( ! ( $ coord instanceof LatLng ) ) { throw new InvalidParamException ( '$coords must be an array of "' . LatLng :: className ( ) . '" objects' ) ; } $ minLat = min ( $ minLat , $ coord -> getLat ( ) ) ; $ maxLat = max ( $ maxLat , $ coord -> getLat ( ) ) ; $ minLng = min ( $ minLng , $ coord -> getLng ( ) ) ; $ maxLng = max ( $ maxLng , $ coord -> getLng ( ) ) ; } if ( $ margin > 0 ) { $ minLat = $ minLat - $ margin * ( $ maxLat - $ minLat ) ; $ minLng = $ minLng - $ margin * ( $ maxLng - $ minLng ) ; $ maxLat = $ maxLat + $ margin * ( $ maxLat - $ minLat ) ; $ maxLng = $ maxLng + $ margin * ( $ maxLng - $ minLng ) ; } return new self ( [ 'southWest' => new LatLng ( [ 'lat' => $ minLat , 'lng' => $ minLng ] ) , 'northEast' => new LatLng ( [ 'lat' => $ maxLat , 'lng' => $ maxLng ] ) ] ) ; }
Returns the boundaries of an array of LatLng objects
51,256
public static function getBoundsOfMarkers ( $ markers , $ margin = 0.0 ) { $ coords = [ ] ; foreach ( $ markers as $ marker ) { if ( ! ( $ marker instanceof Marker ) ) { throw new InvalidParamException ( '"$markers" must be an array of "' . Marker :: className ( ) . '" objects' ) ; } $ coords [ ] = $ marker -> position ; } return LatLngBounds :: getBoundsOfCoordinates ( $ coords , $ margin ) ; }
Returns the boundaries of an array of Marker objects
51,257
public static function getBoundsOfPolygons ( $ polygons , $ margin = 0.0 ) { $ coords = [ ] ; foreach ( $ polygons as $ polygon ) { if ( ! ( $ polygon instanceof Polygon ) ) { throw new InvalidParamException ( '"$polygons" must be an array of "' . Polygon :: className ( ) . '" objects' ) ; } $ coords = ArrayHelper :: merge ( $ coords , $ polygon -> paths ) ; } return LatLngBounds :: getBoundsOfCoordinates ( $ coords , $ margin ) ; }
Returns the boundaries of an array of Polygon objects
51,258
public static function getBoundsFromCenterAndZoom ( LatLng $ center , $ zoom , $ width , $ height = null ) { if ( is_null ( $ height ) ) { $ height = $ width ; } $ centerLat = $ center -> getLat ( ) ; $ centerLng = $ center -> getLng ( ) ; $ pix = LatLng :: latToPixels ( $ centerLat , $ zoom ) ; $ neLat = LatLng :: pixelsToLat ( $ pix - round ( ( $ height - 1 ) / 2 ) , $ zoom ) ; $ swLat = LatLng :: pixelsToLat ( $ pix + round ( ( $ height - 1 ) / 2 ) , $ zoom ) ; $ pix = LatLng :: lngToPixels ( $ centerLng , $ zoom ) ; $ swLng = LatLng :: pixelsToLng ( $ pix - round ( ( $ width - 1 ) / 2 ) , $ zoom ) ; $ neLng = LatLng :: pixelsToLng ( $ pix + round ( ( $ width - 1 ) / 2 ) , $ zoom ) ; return new self ( [ 'southWest' => new LatLng ( [ 'lat' => $ swLat , 'lng' => $ swLng ] ) , 'northEast' => new LatLng ( [ 'lat' => $ neLat , 'lng' => $ neLng ] ) ] ) ; }
Calculate the bounds corresponding to a specific center and zoom level for a give map size in pixels
51,259
public function getJs ( $ name ) { switch ( $ this -> getType ( ) ) { case EventType :: DEFAULT_ONCE : return $ this -> getEventJs ( $ name , true ) ; case EventType :: DOM : return $ this -> getDomEventJs ( $ name ) ; case EventType :: DOM_ONCE : return $ this -> getDomEventJs ( $ name , true ) ; case EventType :: DEFAULT_EVENT : default : return $ this -> getEventJs ( $ name ) ; } }
Returns the js code to attach a Google event or a Dom event to a js object
51,260
public function reverse ( LatLng $ coord , $ params = [ ] ) { $ params [ 'latlng' ] = $ coord -> __toString ( ) ; $ this -> params = ArrayHelper :: merge ( $ this -> params , $ params ) ; return parent :: request ( ) ; }
Makes a reverse geocoding
51,261
public function getJs ( ) { $ name = $ this -> getName ( ) ; $ reflection = new \ ReflectionClass ( $ this ) ; $ object = $ reflection -> getShortName ( ) ; $ js [ ] = "var {$name} = new google.maps.{$object}();" ; $ js [ ] = "$name.setMap({$this->map});" ; return implode ( "\n" , $ js ) ; }
Returns the javascript code required to initialize the object
51,262
public function setContent ( $ value ) { if ( strpos ( strtolower ( $ value ) , 'getelementbyid' ) > 0 ) { $ this -> options [ 'content' ] = new JsExpression ( $ value ) ; } else { $ value = preg_replace ( '/\r\n|\n|\r/' , "\\n" , $ value ) ; $ value = preg_replace ( '/(["\'])/' , '\\\\\1' , $ value ) ; $ this -> options [ 'content' ] = $ value ; } }
Sets the content of the infoWindow object . It has support to get the content from a DOM node .
51,263
public function distanceFrom ( LatLng $ coord ) { $ latDist = abs ( $ this -> getLat ( ) - $ coord -> getLat ( ) ) ; $ lngDist = abs ( $ this -> getLng ( ) - $ coord -> getLng ( ) ) ; $ radDist = deg2rad ( sqrt ( pow ( $ latDist , 2 ) + pow ( $ lngDist , 2 ) ) ) ; return $ radDist * UnitsType :: EARTH_RADIUS ; }
Very approximate calculation of the distance in kilometers between two coordinates
51,264
public function exactDistanceSLCFrom ( LatLng $ coord , $ unit = UnitsType :: KILOMETERS ) { $ lat1 = $ this -> getLat ( ) ; $ lat2 = $ coord -> getLat ( ) ; $ lon1 = $ this -> getLng ( ) ; $ lon2 = $ coord -> getLng ( ) ; $ theta = $ lon1 - $ lon2 ; $ dist = sin ( deg2rad ( $ lat1 ) ) * sin ( deg2rad ( $ lat2 ) ) + cos ( deg2rad ( $ lat1 ) ) * cos ( deg2rad ( $ lat2 ) ) * cos ( deg2rad ( $ theta ) ) ; $ dist = acos ( $ dist ) ; $ dist = rad2deg ( $ dist ) ; $ miles = $ dist * 60 * 1.1515 ; switch ( $ unit ) { case UnitsType :: KILOMETERS : $ distance = $ miles * 1.609344 ; break ; case UnitsType :: NAUTIC_MILES : $ distance = $ miles * 0.8684 ; break ; case UnitsType :: MILES : default : $ distance = $ miles ; } return $ distance ; }
Exact distance with spherical law of cosines
51,265
public function exactDistanceFrom ( LatLng $ coord ) { $ lat1 = deg2rad ( $ this -> getLat ( ) ) ; $ lat2 = deg2rad ( $ coord -> getLat ( ) ) ; $ lon1 = deg2rad ( $ this -> getLng ( ) ) ; $ lon2 = deg2rad ( $ coord -> getLng ( ) ) ; $ dLatHalf = ( $ lat2 - $ lat1 ) / 2 ; $ dLonHalf = ( $ lon2 - $ lon1 ) / 2 ; $ a = pow ( sin ( $ dLatHalf ) , 2 ) + cos ( $ lat1 ) * cos ( $ lat2 ) * pow ( sin ( $ dLonHalf ) , 2 ) ; $ c = 2 * atan2 ( sqrt ( $ a ) , sqrt ( 1 - $ a ) ) ; return $ c * UnitsType :: EARTH_RADIUS ; }
Exact distance with Haversine formula
51,266
public static function getCenterOfCoordinates ( $ coords ) { $ cnt = count ( $ coords ) ; if ( $ cnt == 0 ) { return null ; } $ centerLat = $ centerLng = 0 ; foreach ( $ coords as $ coord ) { if ( ! ( $ coord instanceof LatLng ) ) { throw new InvalidParamException ( '$coord must be an array of "' . self :: className ( ) . '" objects' ) ; } $ centerLat += $ coord -> getLat ( ) ; $ centerLng += $ coord -> getLng ( ) ; } return new self ( [ 'lat' => ( $ centerLat / $ cnt ) , 'lng' => ( $ centerLng / $ cnt ) ] ) ; }
Calculates the center of an array of coordinates
51,267
public function setOptions ( PolylineOptions $ polylineOptions ) { $ options = array_filter ( $ polylineOptions -> options ) ; $ this -> options = ArrayHelper :: merge ( $ this -> options , $ options ) ; }
Sets the options based on a PolylineOptions object
51,268
public function getCenterOfBounds ( ) { $ path = ArrayHelper :: getValue ( $ this -> options , 'path' ) ; return is_array ( $ path ) && ! empty ( $ path ) ? LatLngBounds :: getBoundsOfCoordinates ( $ path ) -> getCenterCoordinates ( ) : null ; }
Returns the center of bounds of the
51,269
public function attachInfoWindow ( InfoWindow $ infoWindow , $ shared = true ) { $ this -> infoWindow = $ infoWindow ; $ this -> isInfoWindowShared = $ shared ; }
Attaches a info window to the object
51,270
public function addIcon ( IconSequence $ icon ) { $ copy = clone $ icon ; $ copy -> setName ( null ) ; $ this -> options [ 'icons' ] [ ] = new JsExpression ( $ copy -> getJs ( ) ) ; }
Adds an IconSequence
51,271
public function byLocations ( $ coords , $ encode = true ) { $ this -> params [ 'locations' ] = $ encode ? Encoder :: encodeCoordinates ( $ coords ) : implode ( '|' , $ coords ) ; return parent :: request ( ) ; }
Makes elevation request by locations
51,272
public function byPath ( $ coords , $ samples , $ encode = true ) { $ this -> params [ 'path' ] = $ encode ? Encoder :: encodeCoordinates ( $ coords ) : implode ( '|' , $ coords ) ; $ this -> params [ 'samples' ] = $ samples ; return parent :: request ( ) ; }
Makes elevation request by paths
51,273
public function setOptions ( RectangleOptions $ rectangleOptions ) { $ options = array_filter ( $ rectangleOptions -> options ) ; $ this -> options = ArrayHelper :: merge ( $ this -> options , $ options ) ; }
Sets the options based on a RectangleOptions object
51,274
public function getCenterOfBounds ( ) { return ( null !== $ this -> bounds && $ this -> bounds instanceof LatLngBounds ) ? $ this -> bounds -> getCenterCoordinates ( ) : null ; }
Returns center of bounds
51,275
public function getCenterOfPaths ( ) { $ paths = ArrayHelper :: getValue ( $ this -> options , 'paths' ) ; return is_array ( $ paths ) && ! empty ( $ paths ) ? LatLngBounds :: getBoundsOfCoordinates ( $ paths ) -> getCenterCoordinates ( ) : null ; }
Returns the center coordinates of paths
51,276
public function containsCoordinate ( LatLng $ coord , $ isCheckVertex = false ) { if ( $ isCheckVertex == true && $ this -> isOnVertexOfPolygon ( $ coord ) == true ) { return true ; } $ intersections = 0 ; $ paths = ArrayHelper :: getValue ( $ this -> options , 'paths' ) ; $ vertexCount = count ( $ paths ) ; for ( $ i = 1 ; $ i < $ vertexCount ; $ i ++ ) { $ vertex1 = $ paths [ $ i - 1 ] ; $ vertex2 = $ paths [ $ i ] ; if ( $ vertex1 -> lat == $ vertex2 -> lat && $ vertex1 -> lat == $ coord -> lat && $ coord -> lng > min ( $ vertex1 -> lng , $ vertex2 -> lng ) && $ coord -> lng < max ( $ vertex1 -> lng , $ vertex2 -> lng ) ) { return true ; } if ( $ coord -> lat > min ( $ vertex1 -> lat , $ vertex2 -> lat ) && $ coord -> lat <= max ( $ vertex1 -> lat , $ vertex2 -> lat ) && $ coord -> lng <= max ( $ vertex1 -> lng , $ vertex2 -> lng ) && $ vertex1 -> lat != $ vertex2 -> lat ) { $ xinters = $ coord -> lat - $ vertex1 -> lat ; $ xinters = $ xinters * ( $ vertex2 -> lng - $ vertex1 -> lng ) ; $ xinters = $ xinters / ( $ vertex2 -> lat - $ vertex1 -> lat ) ; $ xinters = $ xinters + $ vertex1 -> lng ; if ( $ xinters == $ coord -> lng ) { return true ; } if ( $ vertex1 -> lng == $ vertex2 -> lng || $ coord -> lng <= $ xinters ) { $ intersections ++ ; } } } if ( $ intersections % 2 != 0 ) { return true ; } return false ; }
Returns true if coordinate is within polygon
51,277
public function isCoordinateOnVertex ( LatLng $ coord ) { $ paths = ArrayHelper :: getValue ( $ this -> options , 'paths' ) ; foreach ( $ paths as $ vertex ) { if ( $ vertex -> lat == $ coord -> lat && $ vertex -> lng == $ coord -> lng ) { return true ; } } return false ; }
Returns true if coordinate is vertex of polygon .
51,278
protected function request ( $ options = [ ] ) { try { $ params = array_filter ( $ this -> params ) ; $ response = $ this -> getClient ( ) -> get ( $ this -> getUrl ( ) , [ 'query' => $ params ] , $ options ) ; return trim ( $ this -> format ) === 'json' ? json_decode ( $ response -> getBody ( ) , true ) : simplexml_load_string ( $ response -> getBody ( ) ) ; } catch ( RequestException $ e ) { return null ; } }
Makes the request to the Google API
51,279
public function getPlugin ( $ name ) { return isset ( $ this -> _plugins [ $ name ] ) ? $ this -> _plugins [ $ name ] : null ; }
Returns an installed plugin by name
51,280
public static function encodeCoordinates ( $ coords ) { static $ encoder ; if ( $ encoder == null ) { $ encoder = new self ( ) ; } $ points = [ ] ; foreach ( $ coords as $ coord ) { $ points [ ] = explode ( ',' , $ coord ) ; } return "enc:{$encoder->encode($points)}" ; }
Helper function to encode coordinates when there is no required to configure the encoder
51,281
private function encodeSignedNumber ( $ num ) { $ sgn_num = $ num << 1 ; if ( $ num < 0 ) { $ sgn_num = ~ ( $ sgn_num ) ; } return $ this -> encodeNumber ( $ sgn_num ) ; }
Encodes a signed number
51,282
private function encodeNumber ( $ num ) { $ encodeString = '' ; while ( $ num >= 0x20 ) { $ nextValue = ( 0x20 | ( $ num & 0x1f ) ) + 63 ; $ encodeString .= chr ( $ nextValue ) ; $ num >>= 5 ; } $ finalValue = $ num + 63 ; $ encodeString .= chr ( $ finalValue ) ; return $ encodeString ; }
Encondes a number
51,283
private function parseContextLinkHeaders ( array $ values , IRI $ baseIri ) { for ( $ i = 0 , $ total = count ( $ values ) ; $ i < $ total ; $ i ++ ) { if ( strpos ( $ values [ $ i ] , ',' ) !== false ) { foreach ( preg_split ( '/,(?=([^"]*"[^"]*")*[^"]*$)/' , $ values [ $ i ] ) as $ v ) { $ values [ ] = trim ( $ v ) ; } unset ( $ values [ $ i ] ) ; } } $ contexts = $ matches = array ( ) ; $ trimWhitespaceCallback = function ( $ str ) { return trim ( $ str , "\"' \n\t" ) ; } ; foreach ( $ values as $ val ) { $ part = array ( ) ; foreach ( preg_split ( '/;(?=([^"]*"[^"]*")*[^"]*$)/' , $ val ) as $ kvp ) { preg_match_all ( '/<[^>]+>|[^=]+/' , $ kvp , $ matches ) ; $ pieces = array_map ( $ trimWhitespaceCallback , $ matches [ 0 ] ) ; $ part [ $ pieces [ 0 ] ] = isset ( $ pieces [ 1 ] ) ? $ pieces [ 1 ] : '' ; } if ( in_array ( 'http://www.w3.org/ns/json-ld#context' , explode ( ' ' , $ part [ 'rel' ] ) ) ) { $ contexts [ ] = ( string ) $ baseIri -> resolve ( trim ( key ( $ part ) , '<> ' ) ) ; } } return array_values ( array_unique ( $ contexts ) ) ; }
Parse HTTP Link headers
51,284
public static function getDocument ( $ input , $ options = null ) { $ options = self :: mergeOptions ( $ options ) ; $ input = self :: expand ( $ input , $ options ) ; $ processor = new Processor ( $ options ) ; return $ processor -> getDocument ( $ input ) ; }
Load and parse a JSON - LD document
51,285
public static function expand ( $ input , $ options = null ) { $ options = self :: mergeOptions ( $ options ) ; $ processor = new Processor ( $ options ) ; $ activectx = array ( '@base' => null ) ; if ( is_string ( $ input ) ) { $ remoteDocument = $ options -> documentLoader -> loadDocument ( $ input ) ; $ input = $ remoteDocument -> document ; $ activectx [ '@base' ] = new IRI ( $ remoteDocument -> documentUrl ) ; if ( null !== $ remoteDocument -> contextUrl ) { $ processor -> processContext ( $ remoteDocument -> contextUrl , $ activectx ) ; } } if ( $ options -> base ) { $ activectx [ '@base' ] = $ options -> base ; } if ( null !== $ options -> expandContext ) { $ processor -> processContext ( $ options -> expandContext , $ activectx ) ; } $ processor -> expand ( $ input , $ activectx ) ; if ( is_object ( $ input ) && property_exists ( $ input , '@graph' ) && ( 1 === count ( get_object_vars ( $ input ) ) ) ) { $ input = $ input -> { '@graph' } ; } if ( false === is_array ( $ input ) ) { $ input = ( null === $ input ) ? array ( ) : array ( $ input ) ; } return $ input ; }
Expand a JSON - LD document
51,286
public static function flatten ( $ input , $ context = null , $ options = null ) { $ options = self :: mergeOptions ( $ options ) ; $ input = self :: expand ( $ input , $ options ) ; $ processor = new Processor ( $ options ) ; $ flattened = $ processor -> flatten ( $ input ) ; if ( null === $ context ) { return $ flattened ; } return self :: doCompact ( $ flattened , $ context , $ options , true ) ; }
Flatten a JSON - LD document
51,287
public static function toRdf ( $ input , $ options = null ) { $ options = self :: mergeOptions ( $ options ) ; $ expanded = self :: expand ( $ input , $ options ) ; $ processor = new Processor ( $ options ) ; return $ processor -> toRdf ( $ expanded ) ; }
Convert a JSON - LD document to RDF quads
51,288
public static function fromRdf ( array $ quads , $ options = null ) { $ options = self :: mergeOptions ( $ options ) ; $ processor = new Processor ( $ options ) ; return $ processor -> fromRdf ( $ quads ) ; }
Convert an array of RDF quads to a JSON - LD document
51,289
public static function frame ( $ input , $ frame , $ options = null ) { $ options = self :: mergeOptions ( $ options ) ; $ input = self :: expand ( $ input , $ options ) ; $ frame = ( is_string ( $ frame ) ) ? $ options -> documentLoader -> loadDocument ( $ frame ) -> document : $ frame ; if ( false === is_object ( $ frame ) ) { throw new JsonLdException ( JsonLdException :: UNSPECIFIED , 'Invalid frame detected. It must be an object.' , $ frame ) ; } $ processor = new Processor ( $ options ) ; $ frameContext = new JsonObject ( ) ; if ( property_exists ( $ frame , '@context' ) ) { $ frameContext -> { '@context' } = $ frame -> { '@context' } ; } $ processor -> expand ( $ frame , array ( ) , null , true ) ; if ( is_object ( $ frame ) && property_exists ( $ frame , '@graph' ) && ( 1 === count ( get_object_vars ( $ frame ) ) ) ) { $ frame = $ frame -> { '@graph' } ; } if ( false === is_array ( $ frame ) ) { $ frame = array ( $ frame ) ; } $ result = $ processor -> frame ( $ input , $ frame ) ; return self :: doCompact ( $ result , $ frameContext , $ options , true ) ; }
Frame a JSON - LD document according a supplied frame
51,290
public static function toString ( $ value , $ pretty = false ) { $ options = 0 ; if ( PHP_VERSION_ID >= 50400 ) { $ options |= JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ; if ( $ pretty ) { $ options |= JSON_PRETTY_PRINT ; } return json_encode ( $ value , $ options ) ; } else { $ result = json_encode ( $ value ) ; $ result = str_replace ( '\\/' , '/' , $ result ) ; return preg_replace_callback ( '/\\\\u([a-f0-9]{4})/' , function ( $ match ) { return iconv ( 'UCS-4LE' , 'UTF-8' , pack ( 'V' , hexdec ( $ match [ 1 ] ) ) ) ; } , $ result ) ; } }
Convert the PHP structure returned by the various processing methods to a string
51,291
private function updateMessage ( ) { $ this -> message = $ this -> rawMessage ; $ dot = false ; if ( '.' === substr ( $ this -> message , - 1 ) ) { $ this -> message = substr ( $ this -> message , 0 , - 1 ) ; $ dot = true ; } if ( null !== $ this -> document ) { $ this -> message .= sprintf ( ' in %s' , $ this -> document ) ; } if ( $ this -> snippet ) { $ this -> message .= sprintf ( ' (near %s)' , $ this -> snippet ) ; } if ( $ dot ) { $ this -> message .= '.' ; } }
Updates the exception message by including the file name if available .
51,292
public static function fromJsonLd ( JsonObject $ element ) { if ( false === property_exists ( $ element , '@value' ) ) { return false ; } $ value = $ element -> { '@value' } ; $ type = ( property_exists ( $ element , '@type' ) ) ? $ element -> { '@type' } : null ; $ language = ( property_exists ( $ element , '@language' ) ) ? $ element -> { '@language' } : null ; if ( is_int ( $ value ) || is_float ( $ value ) ) { if ( ( $ value != ( int ) $ value ) || ( RdfConstants :: XSD_DOUBLE === $ type ) ) { $ value = preg_replace ( '/(0{0,14})E(\+?)/' , 'E' , sprintf ( '%1.15E' , $ value ) ) ; if ( ( null === $ type ) && ( null === $ language ) ) { return new TypedValue ( $ value , RdfConstants :: XSD_DOUBLE ) ; } } else { $ value = sprintf ( '%d' , $ value ) ; if ( ( null === $ type ) && ( null === $ language ) ) { return new TypedValue ( $ value , RdfConstants :: XSD_INTEGER ) ; } } } elseif ( is_bool ( $ value ) ) { $ value = ( $ value ) ? 'true' : 'false' ; if ( ( null === $ type ) && ( null === $ language ) ) { return new TypedValue ( $ value , RdfConstants :: XSD_BOOLEAN ) ; } } elseif ( false === is_string ( $ value ) ) { return false ; } if ( ( null === $ type ) && ( null !== $ language ) ) { return new LanguageTaggedString ( $ value , $ language ) ; } return new TypedValue ( $ value , ( null === $ type ) ? RdfConstants :: XSD_STRING : $ type ) ; }
Create a LanguageTaggedString or TypedValue from a JSON - LD element
51,293
private function doMergeIntoProperty ( $ property , $ existingValues , $ value ) { if ( null === $ value ) { return ; } if ( ! $ this -> isValidPropertyValue ( $ value ) ) { throw new \ InvalidArgumentException ( 'value must be a scalar, a node, a language-tagged string, or a typed value' ) ; } $ normalizedValue = $ this -> normalizePropertyValue ( $ value ) ; foreach ( $ existingValues as $ existing ) { if ( $ this -> equalValues ( $ existing , $ normalizedValue ) ) { return ; } } $ existingValues [ ] = $ normalizedValue ; if ( 1 === count ( $ existingValues ) ) { $ existingValues = $ existingValues [ 0 ] ; } $ this -> properties [ $ property ] = $ existingValues ; if ( $ normalizedValue instanceof NodeInterface ) { $ value -> addReverseProperty ( $ property , $ this ) ; } }
Merge a value into a set of existing values .
51,294
protected function addReverseProperty ( $ property , NodeInterface $ node ) { $ this -> revProperties [ $ property ] [ $ node -> getId ( ) ] = $ node ; }
Add a reverse property .
51,295
protected function removeReverseProperty ( $ property , NodeInterface $ node ) { unset ( $ this -> revProperties [ $ property ] [ $ node -> getId ( ) ] ) ; if ( 0 === count ( $ this -> revProperties [ $ property ] ) ) { unset ( $ this -> revProperties [ $ property ] ) ; } }
Remove a reverse property .
51,296
protected function isValidPropertyValue ( $ value ) { return ( is_scalar ( $ value ) || ( is_object ( $ value ) && ( ( ( $ value instanceof NodeInterface ) && ( $ value -> getGraph ( ) === $ this -> graph ) ) || ( $ value instanceof Value ) ) ) ) ; }
Checks whether a value is a valid property value .
51,297
protected function normalizePropertyValue ( $ value ) { if ( false === is_scalar ( $ value ) ) { return $ value ; } return Value :: fromJsonLd ( ( object ) array ( '@value' => $ value ) ) ; }
Normalizes a property value by converting scalars to Value objects .
51,298
protected function equalValues ( $ value1 , $ value2 ) { if ( gettype ( $ value1 ) !== gettype ( $ value2 ) ) { return false ; } if ( is_object ( $ value1 ) && ( $ value1 instanceof Value ) ) { return $ value1 -> equals ( $ value2 ) ; } return ( $ value1 === $ value2 ) ; }
Checks whether the two specified values are the same .
51,299
public static function parse ( $ document ) { if ( function_exists ( 'mb_detect_encoding' ) && ( false === mb_detect_encoding ( $ document , 'UTF-8' , true ) ) ) { throw new JsonLdException ( JsonLdException :: LOADING_DOCUMENT_FAILED , 'The JSON-LD document does not appear to be valid UTF-8.' ) ; } $ data = json_decode ( $ document , false , 512 ) ; switch ( json_last_error ( ) ) { case JSON_ERROR_NONE : break ; case JSON_ERROR_DEPTH : throw new JsonLdException ( JsonLdException :: LOADING_DOCUMENT_FAILED , 'The maximum stack depth has been exceeded.' ) ; case JSON_ERROR_STATE_MISMATCH : throw new JsonLdException ( JsonLdException :: LOADING_DOCUMENT_FAILED , 'Invalid or malformed JSON.' ) ; case JSON_ERROR_CTRL_CHAR : throw new JsonLdException ( JsonLdException :: LOADING_DOCUMENT_FAILED , 'Control character error (possibly incorrectly encoded).' ) ; case JSON_ERROR_SYNTAX : throw new JsonLdException ( JsonLdException :: LOADING_DOCUMENT_FAILED , 'Syntax error, malformed JSON.' ) ; case JSON_ERROR_UTF8 : throw new JsonLdException ( JsonLdException :: LOADING_DOCUMENT_FAILED , 'Malformed UTF-8 characters (possibly incorrectly encoded).' ) ; default : throw new JsonLdException ( JsonLdException :: LOADING_DOCUMENT_FAILED , 'Unknown error while parsing JSON.' ) ; } return ( empty ( $ data ) ) ? null : $ data ; }
Parses a JSON - LD document to a PHP value