idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
45,800
public function findManyByUuid ( $ uuids , $ columns = [ '*' ] ) { if ( empty ( $ uuids ) ) { return $ this -> model -> newCollection ( ) ; } return $ this -> whereUuidKey ( $ uuids ) -> get ( $ columns ) ; }
Find multiple models by their UUID keys .
45,801
public function whereUuidKey ( $ uuid ) { if ( is_array ( $ uuid ) || $ uuid instanceof Arrayable ) { $ this -> query -> whereIn ( $ this -> model -> getQualifiedUuidKeyName ( ) , $ uuid ) ; return $ this ; } return $ this -> where ( $ this -> model -> getQualifiedUuidKeyName ( ) , '=' , $ uuid ) ; }
Add a where clause on the UUID key to the query .
45,802
public static function getResponseCaseType ( ) { $ format = static :: $ requestedKeyCaseFormat ; if ( ! is_null ( $ format ) ) { return $ format ; } $ caseFormat = request ( ) -> header ( static :: CASE_TYPE_HEADER , null ) ; if ( ! is_null ( $ caseFormat ) ) { if ( $ caseFormat == static :: CAMEL_CASE ) { $ format = static :: CAMEL_CASE ; } elseif ( $ caseFormat == static :: SNAKE_CASE ) { $ format = static :: SNAKE_CASE ; } } if ( is_null ( $ format ) ) { $ caseFormat = Config ( static :: CASE_TYPE_CONFIG_PATH ) ; if ( $ caseFormat == static :: CAMEL_CASE || empty ( $ caseFormat ) ) { $ format = static :: CAMEL_CASE ; } elseif ( $ caseFormat == static :: SNAKE_CASE ) { $ format = static :: SNAKE_CASE ; } else { throw new BadRequestHttpException ( 'Invalid case type specified in API config.' ) ; } } static :: $ requestedKeyCaseFormat = $ format ; return $ format ; }
Get the required case type for transforming response data
45,803
public static function formatKeyCaseAccordingToReponseFormat ( $ key ) { $ format = static :: getResponseCaseType ( ) ; if ( $ format == static :: CAMEL_CASE ) { $ key = camel_case ( $ key ) ; } else { $ key = snake_case ( $ key ) ; } return $ key ; }
Format the provided key string into the required case response format
45,804
public static function destroy ( $ ids ) { if ( UuidValidator :: validate ( $ ids ) ) { return static :: destroyByUuid ( $ ids ) ; } else { return parent :: destroy ( $ ids ) ; } }
Wrapper to allow both IDs and UUIDs to be used
45,805
public static function destroyByUuid ( $ uuids ) { $ count = 0 ; $ ids = is_array ( $ uuids ) ? $ uuids : func_get_args ( ) ; $ key = ( $ instance = new static ) -> getUuidKeyName ( ) ; foreach ( $ instance -> whereIn ( $ key , $ ids ) -> get ( ) as $ model ) { if ( $ model -> delete ( ) ) { $ count ++ ; } } return $ count ; }
Destroy the models for the given UUIDs .
45,806
protected function setUuidKeysForSaveQuery ( Builder $ query ) { $ query -> where ( $ this -> getUuidKeyName ( ) , '=' , $ this -> getUuidKeyForSaveQuery ( ) ) ; return $ query ; }
Set the UUID keys for a save update query .
45,807
public function patch ( $ model , $ data ) { try { $ resource = $ model -> update ( $ data ) ; } catch ( \ Exception $ e ) { if ( $ e instanceof QueryException ) { if ( stristr ( $ e -> getMessage ( ) , 'duplicate' ) ) { throw new ConflictHttpException ( 'Duplicate entry for ' . $ this -> model ) ; } elseif ( Config :: get ( 'api.debug' ) === true ) { throw $ e ; } } $ errorMessage = 'Unexpected error trying to store this resource.' ; if ( Config :: get ( 'api.debug' ) === true ) { $ errorMessage .= ' ' . $ e -> getMessage ( ) ; } throw new UnprocessableEntityHttpException ( $ errorMessage ) ; } return $ resource ; }
Patch a resource of the given model with the given request
45,808
public function persistResource ( RestfulModel $ resource ) { try { $ resource -> save ( ) ; } catch ( \ Exception $ e ) { if ( $ e instanceof QueryException ) { if ( stristr ( $ e -> getMessage ( ) , 'duplicate' ) ) { throw new ConflictHttpException ( 'The resource already exists: ' . $ this -> model ) ; } elseif ( Config :: get ( 'api.debug' ) === true ) { throw $ e ; } } $ errorMessage = 'Unexpected error trying to store this resource.' ; if ( Config :: get ( 'api.debug' ) === true ) { $ errorMessage .= ' ' . $ e -> getMessage ( ) ; } throw new UnprocessableEntityHttpException ( $ errorMessage ) ; } return $ resource ; }
Create model in the database
45,809
public function authorizeUserAction ( $ ability , $ arguments = [ ] ) { if ( is_null ( $ ability ) ) { return true ; } if ( ! $ this -> userCan ( $ ability , $ arguments ) ) { throw new AccessDeniedHttpException ( 'Unauthorized action' ) ; } }
Shorthand function which checks the currently logged in user against an action for the controller s model and throws a 403 if unauthorized
45,810
public function qualifyCollectionQuery ( $ query ) { $ user = auth ( ) -> user ( ) ; $ modelPolicy = Gate :: getPolicyFor ( static :: $ model ) ; if ( is_null ( $ modelPolicy ) ) { return $ query ; } if ( method_exists ( $ modelPolicy , 'qualifyCollectionQueryWithUser' ) ) { $ query = $ modelPolicy -> qualifyCollectionQueryWithUser ( $ user , $ query ) ; } return $ query ; }
This function can be used to add conditions to the query builder which will specify the currently logged in user s ownership of the model
45,811
public function userCan ( $ ability , $ arguments = [ ] ) { $ user = auth ( ) -> user ( ) ; if ( empty ( $ arguments ) ) { $ arguments = static :: $ model ; } if ( is_array ( $ arguments ) ) { $ model = reset ( $ arguments ) ; } else { $ model = $ arguments ; } $ modelPolicy = Gate :: getPolicyFor ( $ model ) ; if ( is_null ( $ modelPolicy ) ) { return true ; } if ( $ user -> can ( $ ability , $ arguments ) ) { return true ; } return false ; }
Determine if the currently logged in user can perform the specified ability on the model of the controller When relevant a specific instance of a model is used - otherwise the model name .
45,812
public function getAll ( $ uuid , Request $ request ) { $ parentModel = static :: $ parentModel ; $ parentResource = $ parentModel :: findOrFail ( $ uuid ) ; $ this -> authorizeUserAction ( $ this -> parentAbilitiesRequired [ 'view' ] , $ parentResource ) ; $ model = static :: $ model ; $ resourceRelationName = model_relation_name ( $ model ) ; $ withArray = [ ] ; foreach ( $ model :: $ localWith as $ modelRelation ) { $ withArray [ ] = $ resourceRelationName . '.' . $ modelRelation ; } $ withArray = array_merge ( [ $ resourceRelationName ] , $ withArray ) ; $ parentResource = $ parentResource -> where ( $ parentResource -> getKeyName ( ) , '=' , $ parentResource -> getKey ( ) ) -> with ( $ withArray ) -> first ( ) ; $ collection = $ parentResource -> getRelationValue ( $ resourceRelationName ) ; if ( $ collection == null ) { $ collection = new Collection ( ) ; } return $ this -> response -> collection ( $ collection , $ this -> getTransformer ( ) ) ; }
Request to retrieve a collection of all items owned by the parent of this resource
45,813
public function post ( $ parentUuid , Request $ request ) { $ parentModel = static :: $ parentModel ; $ parentResource = $ parentModel :: findOrFail ( $ parentUuid ) ; $ this -> authorizeUserAction ( $ this -> parentAbilitiesRequired [ 'create' ] , $ parentResource ) ; $ this -> authorizeUserAction ( 'create' ) ; $ requestData = $ request -> input ( ) ; $ model = new static :: $ model ; $ this -> restfulService -> validateResource ( $ model , $ requestData ) ; $ resource = new $ model ( $ requestData ) ; $ parentRelation = $ parentResource -> { $ this -> getChildRelationNameForParent ( $ parentResource , static :: $ model ) } ( ) ; $ resource -> { $ parentRelation -> getForeignKeyName ( ) } = $ parentUuid ; $ resource = $ this -> restfulService -> persistResource ( $ resource ) ; $ resource = $ model :: with ( $ model :: $ localWith ) -> where ( $ model -> getKeyName ( ) , '=' , $ resource -> getKey ( ) ) -> first ( ) ; if ( $ this -> shouldTransform ( ) ) { $ response = $ this -> response -> item ( $ resource , $ this -> getTransformer ( ) ) -> setStatusCode ( 201 ) ; } else { $ response = $ resource ; } return $ response ; }
Request to create the child resource owned by the parent resource
45,814
public function patch ( $ parentUuid , $ uuid , Request $ request ) { $ parentModel = static :: $ parentModel ; $ parentResource = $ parentModel :: findOrFail ( $ parentUuid ) ; $ this -> authorizeUserAction ( $ this -> parentAbilitiesRequired [ 'update' ] , $ parentResource ) ; $ model = new static :: $ model ; $ resource = static :: $ model :: findOrFail ( $ uuid ) ; if ( $ resource -> getAttribute ( ( $ parentResource -> getKeyName ( ) ) ) != $ parentResource -> getKey ( ) ) { throw new AccessDeniedHttpException ( 'Resource \'' . class_basename ( static :: $ model ) . '\' with given UUID ' . $ uuid . ' does not belong to ' . 'resource \'' . class_basename ( static :: $ parentModel ) . '\' with given UUID ' . $ parentUuid . '; ' ) ; } $ this -> authorizeUserAction ( 'update' , $ resource ) ; $ this -> restfulService -> validateResourceUpdate ( $ resource , $ request -> input ( ) ) ; $ this -> restfulService -> patch ( $ resource , $ request -> input ( ) ) ; $ resource = $ model :: with ( $ model :: $ localWith ) -> where ( $ model -> getKeyName ( ) , '=' , $ uuid ) -> first ( ) ; if ( $ this -> shouldTransform ( ) ) { $ response = $ this -> response -> item ( $ resource , $ this -> getTransformer ( ) ) ; } else { $ response = $ resource ; } return $ response ; }
Request to update the specified child resource
45,815
public function delete ( $ parentUuid , $ uuid ) { $ parentModel = static :: $ parentModel ; $ parentResource = $ parentModel :: findOrFail ( $ parentUuid ) ; $ this -> authorizeUserAction ( $ this -> parentAbilitiesRequired [ 'delete' ] , $ parentResource ) ; $ resource = static :: $ model :: findOrFail ( $ uuid ) ; $ this -> authorizeUserAction ( 'delete' , $ resource ) ; if ( $ resource -> getAttribute ( ( $ parentResource -> getKeyName ( ) ) ) != $ parentResource -> getKey ( ) ) { throw new AccessDeniedHttpException ( 'Resource \'' . class_basename ( static :: $ model ) . '\' with given UUID ' . $ uuid . ' does not belong to ' . 'resource \'' . class_basename ( static :: $ parentModel ) . '\' with given UUID ' . $ parentUuid . '; ' ) ; } $ deletedCount = $ resource -> delete ( ) ; if ( $ deletedCount < 1 ) { throw new NotFoundHttpException ( 'Could not find a resource with that UUID to delete' ) ; } return $ this -> response -> noContent ( ) -> setStatusCode ( 204 ) ; }
Deletes a child resource by UUID
45,816
protected function getTransformer ( ) { $ transformer = null ; if ( ! is_null ( static :: $ transformer ) ) { $ transformer = static :: $ transformer ; } else { if ( ! is_null ( static :: $ model ) ) { if ( ! is_null ( ( static :: $ model ) :: $ transformer ) ) { $ transformer = ( static :: $ model ) :: $ transformer ; } } } if ( is_null ( $ transformer ) ) { $ transformer = BaseTransformer :: class ; } return new $ transformer ; }
Figure out which transformer to use
45,817
protected function isRequestBodyACollection ( Request $ request ) { $ input = $ request -> input ( ) ; if ( is_array ( $ input ) && count ( $ input ) > 0 ) { $ firstChild = array_shift ( $ input ) ; if ( is_array ( $ firstChild ) ) { return true ; } } return false ; }
Check if this request s body input is a collection of objects or not
45,818
protected function prependResponseMessage ( $ response , $ message ) { $ content = $ response -> getOriginalContent ( ) ; $ content [ 'message' ] = $ message . $ content [ 'message' ] ; $ response -> setContent ( $ content ) ; return $ response ; }
Prepend a Response message with a custom message Useful for adding error info to internal request responses before returning them
45,819
protected function getChildRelationNameForParent ( $ parent , $ child ) { $ manyName = model_relation_name ( $ child , 'many' ) ; if ( method_exists ( $ parent , $ manyName ) ) { return $ manyName ; } $ oneName = model_relation_name ( $ child , 'one' ) ; if ( method_exists ( $ parent , $ oneName ) ) { return $ oneName ; } }
Try to find the relation name of the child model in the parent model
45,820
protected function prepareReplacements ( Exception $ exception ) { $ replacements = parent :: prepareReplacements ( $ exception ) ; if ( $ exception instanceof \ Illuminate \ Validation \ ValidationException ) { $ replacements = $ this -> formatCaseOfValidationMessages ( $ replacements ) ; } $ updatedFormat = [ ] ; foreach ( $ this -> format as $ key => $ value ) { $ updatedFormat [ APIBoilerplate :: formatKeyCaseAccordingToReponseFormat ( $ key ) ] = $ value ; } $ this -> format = $ updatedFormat ; return $ replacements ; }
Override prepare replacements function to add extra functionality
45,821
protected function formatCaseOfValidationMessages ( $ replacements ) { $ errorKey = Config ( 'api.errorFormat.errors' ) ; if ( array_key_exists ( $ errorKey , $ replacements ) ) { $ errorMessages = $ replacements [ $ errorKey ] ; if ( Config ( APIBoilerplate :: CASE_TYPE_CONFIG_PATH ) == APIBoilerplate :: CAMEL_CASE ) { $ errorMessages = camel_case_array_keys ( $ errorMessages ) ; } else { $ errorMessages = snake_case_array_keys ( $ errorMessages ) ; } $ replacements [ $ errorKey ] = $ errorMessages ; } return $ replacements ; }
Formats the case of validation message keys if response case is not snake - case
45,822
public function findOrFail ( $ id , $ columns = [ '*' ] ) { try { $ resource = parent :: findOrFail ( $ id , $ columns ) ; } catch ( ModelNotFoundException $ e ) { throw new NotFoundHttpException ( 'Resource \'' . class_basename ( $ e -> getModel ( ) ) . '\' with given UUID ' . $ id . ' not found' ) ; } return $ resource ; }
Wrapper to throw a 404 instead of a 500 on model not found
45,823
public function token ( Request $ request ) { $ authHeader = $ request -> header ( 'Authorization' ) ; if ( strtolower ( substr ( $ authHeader , 0 , 5 ) ) !== 'basic' ) { throw new UnauthorizedHttpException ( 'Invalid authorization header, should be type basic' ) ; } $ credentials = base64_decode ( trim ( substr ( $ authHeader , 5 ) ) ) ; list ( $ login , $ password ) = explode ( ':' , $ credentials , 2 ) ; if ( ! $ token = auth ( ) -> attempt ( [ 'email' => $ login , 'password' => $ password ] ) ) { throw new UnauthorizedHttpException ( 'Unauthorized login' ) ; } return $ this -> respondWithToken ( $ token ) ; }
Get a JWT via given credentials .
45,824
protected function respondWithToken ( $ token ) { $ tokenReponse = new \ Stdclass ; $ tokenReponse -> jwt = $ token ; $ tokenReponse -> token_type = 'bearer' ; $ tokenReponse -> expires_in = auth ( ) -> factory ( ) -> getTTL ( ) ; return $ this -> response -> item ( $ tokenReponse , $ this -> getTransformer ( ) ) -> setStatusCode ( 200 ) ; }
Get the token array structure .
45,825
protected function processParamBag ( ParameterBag $ bag ) { $ parameters = $ bag -> all ( ) ; if ( ! empty ( $ parameters ) && count ( $ parameters ) > 0 ) { $ parameters = snake_case_array_keys ( $ parameters ) ; $ bag -> replace ( $ parameters ) ; } }
Process parameters within a ParameterBag to snake_case the keys
45,826
public function transform ( $ object ) { if ( is_object ( $ object ) && $ object instanceof RestfulModel ) { $ transformed = $ this -> transformRestfulModel ( $ object ) ; } elseif ( is_object ( $ object ) && $ object instanceof \ stdClass ) { $ transformed = $ this -> transformStdClass ( $ object ) ; } else { throw new \ Exception ( 'Unexpected object type encountered in transformer' ) ; } return $ transformed ; }
Transform an object into a jsonable array
45,827
public function transformRestfulModel ( RestfulModel $ model ) { $ this -> model = $ model ; $ transformed = $ model -> toArray ( ) ; $ filterOutAttributes = $ this -> getFilteredOutAttributes ( ) ; $ transformed = array_filter ( $ transformed , function ( $ key ) use ( $ filterOutAttributes ) { return ! in_array ( $ key , $ filterOutAttributes ) ; } , ARRAY_FILTER_USE_KEY ) ; foreach ( $ model -> getDates ( ) as $ dateColumn ) { if ( ! empty ( $ model -> $ dateColumn ) && ! in_array ( $ dateColumn , $ filterOutAttributes ) ) { $ transformed [ $ dateColumn ] = $ model -> $ dateColumn -> toIso8601String ( ) ; } } $ transformed = array_merge ( [ 'id' => $ model -> getKey ( ) ] , $ transformed ) ; unset ( $ transformed [ $ model -> getKeyName ( ) ] ) ; $ transformed = $ this -> transformKeysCase ( $ transformed ) ; $ transformed = $ this -> transformRelations ( $ transformed ) ; return $ transformed ; }
Transform an eloquent object into a jsonable array
45,828
protected function transformKeysCase ( array $ transformed ) { $ levels = config ( 'api.formatsOptions.transform_keys_levels' , null ) ; $ transformed = $ this -> formatKeyCase ( $ transformed , $ levels ) ; if ( $ levels == 1 && ! is_null ( $ this -> model ) ) { foreach ( $ this -> model -> getCasts ( ) as $ fieldName => $ castType ) { if ( $ castType == 'array' ) { $ fieldNameFormatted = $ this -> formatKeyCase ( $ fieldName ) ; if ( array_key_exists ( $ fieldNameFormatted , $ transformed ) ) { $ transformed [ $ fieldNameFormatted ] = $ this -> formatKeyCase ( $ transformed [ $ fieldNameFormatted ] ) ; } } } } return $ transformed ; }
Transform the keys of the object to the correct case as required
45,829
protected function formatKeyCase ( $ input , $ levels = null ) { $ caseFormat = APIBoilerplate :: getResponseCaseType ( ) ; if ( $ caseFormat == APIBoilerplate :: CAMEL_CASE ) { if ( is_array ( $ input ) ) { $ transformed = camel_case_array_keys ( $ input , $ levels ) ; } else { $ transformed = camel_case ( $ input ) ; } } elseif ( $ caseFormat == APIBoilerplate :: SNAKE_CASE ) { if ( is_array ( $ input ) ) { $ transformed = snake_case_array_keys ( $ input , $ levels ) ; } else { $ transformed = snake_case ( $ input ) ; } } return $ transformed ; }
Formats case of the input array or scalar to desired case
45,830
protected function getFilteredOutAttributes ( ) { $ filterOutAttributes = array_merge ( $ this -> model -> getHidden ( ) , [ $ this -> model -> getKeyName ( ) , 'deleted_at' , ] ) ; return array_unique ( $ filterOutAttributes ) ; }
Filter out some attributes immediately
45,831
protected function transformRelations ( array $ transformed ) { foreach ( $ this -> model -> getRelations ( ) as $ relationKey => $ relation ) { $ transformedRelationKey = $ this -> formatKeyCase ( $ relationKey ) ; if ( $ relation instanceof \ Illuminate \ Database \ Eloquent \ Relations \ Pivot ) { continue ; } elseif ( $ relation instanceof \ Illuminate \ Database \ Eloquent \ Collection ) { if ( count ( $ relation -> getIterator ( ) ) > 0 ) { $ relationModel = $ relation -> first ( ) ; $ relationTransformer = $ relationModel :: getTransformer ( ) ; if ( $ this -> model -> $ relationKey ) { $ transformed [ $ transformedRelationKey ] = [ ] ; foreach ( $ relation -> getIterator ( ) as $ key => $ relatedModel ) { $ transformedRelatedModel = $ relationTransformer -> transform ( $ relatedModel ) ; if ( isset ( $ transformedRelatedModel [ 'pivot' ] ) ) { unset ( $ transformedRelatedModel [ 'pivot' ] ) ; } $ transformed [ $ transformedRelationKey ] [ ] = $ transformedRelatedModel ; } } } } elseif ( $ relation instanceof RestfulModel ) { $ relationTransformer = $ relation :: getTransformer ( ) ; if ( $ this -> model -> $ relationKey ) { $ transformed [ $ transformedRelationKey ] = $ relationTransformer -> transform ( $ this -> model -> $ relationKey ) ; } } } return $ transformed ; }
Do relation transformations
45,832
public function getAll ( ) { $ model = new static :: $ model ; $ query = $ model :: with ( $ model :: $ localWith ) ; $ this -> qualifyCollectionQuery ( $ query ) ; $ perPage = $ model -> getPerPage ( ) ; if ( $ perPage ) { $ paginator = $ query -> paginate ( $ perPage ) ; return $ this -> response -> paginator ( $ paginator , $ this -> getTransformer ( ) ) ; } else { $ resources = $ query -> get ( ) ; return $ this -> response -> collection ( $ resources , $ this -> getTransformer ( ) ) ; } }
Request to retrieve a collection of all items of this resource
45,833
public function post ( Request $ request ) { $ this -> authorizeUserAction ( 'create' ) ; $ model = new static :: $ model ; $ this -> restfulService -> validateResource ( $ model , $ request -> input ( ) ) ; $ resource = $ this -> restfulService -> persistResource ( new $ model ( $ request -> input ( ) ) ) ; $ resource = $ model :: with ( $ model :: $ localWith ) -> where ( $ model -> getKeyName ( ) , '=' , $ resource -> getKey ( ) ) -> first ( ) ; if ( $ this -> shouldTransform ( ) ) { $ response = $ this -> response -> item ( $ resource , $ this -> getTransformer ( ) ) -> setStatusCode ( 201 ) ; } else { $ response = $ resource ; } return $ response ; }
Request to create a new resource
45,834
public function patch ( $ uuid , Request $ request ) { $ model = static :: $ model :: findOrFail ( $ uuid ) ; $ this -> authorizeUserAction ( 'update' , $ model ) ; $ this -> restfulService -> validateResourceUpdate ( $ model , $ request -> input ( ) ) ; $ this -> restfulService -> patch ( $ model , $ request -> input ( ) ) ; if ( $ this -> shouldTransform ( ) ) { $ response = $ this -> response -> item ( $ model , $ this -> getTransformer ( ) ) ; } else { $ response = $ model ; } return $ response ; }
Request to update the specified resource
45,835
public function delete ( $ uuid ) { $ model = static :: $ model :: findOrFail ( $ uuid ) ; $ this -> authorizeUserAction ( 'delete' , $ model ) ; $ deletedCount = $ model -> delete ( ) ; if ( $ deletedCount < 1 ) { throw new NotFoundHttpException ( 'Could not find a resource with that UUID to delete' ) ; } return $ this -> response -> noContent ( ) -> setStatusCode ( 204 ) ; }
Deletes a resource by UUID
45,836
public function getUri ( ) : string { $ tts = new TextToSpeechHandler ( $ this -> text , $ this -> provider ) ; $ filename = $ tts -> generateFilename ( ) ; if ( ! $ this -> directory -> has ( $ filename ) ) { $ data = $ tts -> getAudioData ( ) ; $ this -> directory -> write ( $ filename , $ data ) ; } return "x-file-cifs://" . $ this -> directory -> getSharePath ( ) . "/{$filename}" ; }
Get the URI for this message .
45,837
public function getName ( ) : string { if ( $ this -> name === null ) { $ data = $ this -> browse ( "Metadata" ) ; $ xml = new XmlParser ( $ data [ "Result" ] ) ; $ this -> name = $ xml -> getTag ( "title" ) -> nodeValue ; } return $ this -> name ; }
Get the name of the playlist .
45,838
protected function addUris ( array $ tracks , int $ position = null ) { if ( $ position === null ) { $ position = $ this -> getNextPosition ( ) ; } foreach ( $ tracks as $ track ) { $ data = $ this -> soap ( "AVTransport" , "AddURIToSavedQueue" , [ "UpdateID" => $ this -> updateId , "EnqueuedURI" => $ track -> getUri ( ) , "EnqueuedURIMetaData" => $ track -> getMetaData ( ) , "AddAtIndex" => $ position , ] ) ; $ this -> updateId = $ data [ "NewUpdateID" ] ; $ position ++ ; } }
Add tracks to the playlist .
45,839
public function removeTracks ( array $ positions ) : bool { $ data = $ this -> soap ( "AVTransport" , "ReorderTracksInSavedQueue" , [ "UpdateID" => $ this -> getUpdateID ( ) , "TrackList" => implode ( "," , $ positions ) , "NewPositionList" => "" , ] ) ; $ this -> updateId = $ data [ "NewUpdateID" ] ; return ( $ data [ "QueueLengthChange" ] == ( count ( $ positions ) * - 1 ) ) ; }
Remove tracks from the playlist .
45,840
public function moveTrack ( int $ from , int $ to ) : PlaylistInterface { $ data = $ this -> soap ( "AVTransport" , "ReorderTracksInSavedQueue" , [ "UpdateID" => $ this -> getUpdateID ( ) , "TrackList" => ( string ) $ from , "NewPositionList" => ( string ) $ to , ] ) ; $ this -> updateId = $ data [ "NewUpdateID" ] ; return $ this ; }
Move a track from one position in the playlist to another .
45,841
public function clear ( ) : QueueInterface { $ positions = [ ] ; $ max = $ this -> count ( ) ; for ( $ i = 0 ; $ i < $ max ; $ i ++ ) { $ positions [ ] = $ i ; } $ this -> removeTracks ( $ positions ) ; return $ this ; }
Remove all tracks from the queue .
45,842
private function lookupTopology ( ) : void { if ( $ this -> group !== null ) { return ; } $ attributes = $ this -> soap ( "ZoneGroupTopology" , "GetZoneGroupAttributes" ) ; $ this -> setGroup ( $ attributes [ "CurrentZoneGroupID" ] ) ; $ this -> coordinator = false ; if ( strpos ( $ attributes [ "CurrentZonePlayerUUIDsInGroup" ] , "," ) === false ) { $ this -> coordinator = true ; } else { list ( $ uuid ) = explode ( ":" , $ attributes [ "CurrentZoneGroupID" ] ) ; if ( $ uuid === $ this -> getUuid ( ) ) { $ this -> coordinator = true ; } } }
Ensure we ve determined this speaker s topology .
45,843
private function guessTrackClass ( string $ uri ) : string { $ classes = [ Spotify :: class , Google :: class , GoogleUnlimited :: class , Deezer :: class , Stream :: class , ] ; foreach ( $ classes as $ class ) { if ( substr ( $ uri , 0 , strlen ( $ class :: PREFIX ) ) === $ class :: PREFIX ) { return $ class ; } } return Track :: class ; }
Get the name of the Track class that represents a URI .
45,844
public function createFromXml ( XmlElement $ xml ) : TrackInterface { $ uri = ( string ) $ xml -> getTag ( "res" ) ; $ class = $ this -> guessTrackClass ( $ uri ) ; return $ class :: createFromXml ( $ xml , $ this -> controller ) ; }
Create a new Track instance from a URI .
45,845
public function write ( string $ file , string $ contents ) : DirectoryInterface { $ this -> filesystem -> write ( "{$this->directory}/{$file}" , $ contents ) ; return $ this ; }
Write data to a file .
45,846
public static function getMode ( string $ mode ) : array { $ options = [ "shuffle" => false , "repeat" => false , ] ; if ( in_array ( $ mode , [ "REPEAT_ALL" , "SHUFFLE" ] ) ) { $ options [ "repeat" ] = true ; } if ( in_array ( $ mode , [ "SHUFFLE_NOREPEAT" , "SHUFFLE" ] ) ) { $ options [ "shuffle" ] = true ; } return $ options ; }
Create a mode array from the mode text value .
45,847
public static function createMetaDataXml ( string $ id , string $ parent = "-1" , array $ extra = [ ] , string $ service = null ) : string { if ( $ service !== null ) { $ extra [ "desc" ] = [ "_attributes" => [ "id" => "cdudn" , "nameSpace" => "urn:schemas-rinconnetworks-com:metadata-1-0/" , ] , "_value" => "SA_RINCON{$service}_X_#Svc{$service}-0-Token" , ] ; } $ xml = XmlWriter :: createXml ( [ "DIDL-Lite" => [ "_attributes" => [ "xmlns:dc" => "http://purl.org/dc/elements/1.1/" , "xmlns:upnp" => "urn:schemas-upnp-org:metadata-1-0/upnp/" , "xmlns:r" => "urn:schemas-rinconnetworks-com:metadata-1-0/" , "xmlns" => "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" , ] , "item" => array_merge ( [ "_attributes" => [ "id" => $ id , "parentID" => $ parent , "restricted" => "true" , ] , ] , $ extra ) , ] , ] ) ; $ metadata = explode ( "\n" , $ xml ) [ 1 ] ; return $ metadata ; }
Create the xml metadata required by Sonos .
45,848
protected function soap ( string $ service , string $ action , array $ params = [ ] ) { $ params [ "ID" ] = $ this -> id ; return $ this -> getSpeaker ( ) -> soap ( $ service , $ action , $ params ) ; }
Send a soap request to the speaker for this alarm .
45,849
public function getSpeaker ( ) : SpeakerInterface { foreach ( $ this -> network -> getSpeakers ( ) as $ speaker ) { if ( $ speaker -> getUuid ( ) === $ this -> getRoom ( ) ) { return $ speaker ; } } throw new \ RuntimeException ( "Unable to find a speaker for this alarm" ) ; }
Get the speaker of the alarm .
45,850
public function setTime ( TimeInterface $ time ) : AlarmInterface { $ this -> attributes [ "StartTime" ] = $ time -> asString ( ) ; return $ this -> save ( ) ; }
Set the start time of the alarm .
45,851
public function setDuration ( TimeInterface $ duration ) : AlarmInterface { $ this -> attributes [ "Duration" ] = $ duration -> asString ( ) ; return $ this -> save ( ) ; }
Set the duration of the alarm .
45,852
public function getFrequency ( ) : int { $ data = $ this -> attributes [ "Recurrence" ] ; if ( $ data === "ONCE" ) { return AlarmInterface :: ONCE ; } if ( $ data === "DAILY" ) { $ data = "ON_0123456" ; } elseif ( $ data === "WEEKDAYS" ) { $ data = "ON_12345" ; } elseif ( $ data === "WEEKENDS" ) { $ data = "ON_06" ; } if ( ! preg_match ( "/^ON_([0-9]+)$/" , $ data , $ matches ) ) { $ error = "Unrecognised frequency for alarm ({$data}), please report this issue on github.com" ; throw new \ RuntimeException ( $ error ) ; } $ data = $ matches [ 1 ] ; $ days = 0 ; foreach ( $ this -> days as $ key => $ val ) { if ( strpos ( $ data , ( string ) $ key ) !== false ) { $ days = $ days | $ val ; } } return $ days ; }
Get the frequency of the alarm .
45,853
public function setFrequency ( int $ frequency ) : AlarmInterface { $ recurrence = "ON_" ; foreach ( $ this -> days as $ key => $ val ) { if ( $ frequency & $ val ) { $ recurrence .= $ key ; } } if ( $ recurrence === "ON_" ) { $ recurrence = "ONCE" ; } elseif ( $ recurrence === "ON_0123456" ) { $ recurrence = "DAILY" ; } elseif ( $ recurrence === "ON_01234" ) { $ recurrence = "WEEKDAYS" ; } elseif ( $ recurrence === "ON_56" ) { $ recurrence = "WEEKENDS" ; } $ this -> attributes [ "Recurrence" ] = $ recurrence ; return $ this -> save ( ) ; }
Set the frequency of the alarm .
45,854
protected function onHandler ( int $ day , bool $ set = null ) { $ frequency = $ this -> getFrequency ( ) ; if ( $ set === null ) { return ( bool ) ( $ frequency & $ day ) ; } if ( $ set && $ frequency ^ $ day ) { return $ this -> setFrequency ( $ frequency | $ day ) ; } if ( ! $ set && $ frequency & $ day ) { return $ this -> setFrequency ( $ frequency ^ $ day ) ; } return $ this ; }
Check or set whether this alarm is active on a particular day .
45,855
public function once ( bool $ set = null ) { if ( $ set ) { return $ this -> setFrequency ( AlarmInterface :: ONCE ) ; } return $ this -> getFrequency ( ) === AlarmInterface :: ONCE ; }
Check or set whether this alarm is a one time only alarm .
45,856
public function daily ( bool $ set = null ) { if ( $ set ) { return $ this -> setFrequency ( AlarmInterface :: DAILY ) ; } return $ this -> getFrequency ( ) === AlarmInterface :: DAILY ; }
Check or set whether this alarm runs every day or not .
45,857
public function getFrequencyDescription ( ) : string { $ data = $ this -> attributes [ "Recurrence" ] ; if ( $ data === "ONCE" ) { return "Once" ; } if ( $ data === "DAILY" ) { return "Daily" ; } if ( $ data === "WEEKDAYS" ) { return "Weekdays" ; } if ( $ data === "WEEKENDS" ) { return "Weekends" ; } $ data = $ this -> getFrequency ( ) ; $ days = [ AlarmInterface :: MONDAY => "Mon" , AlarmInterface :: TUESDAY => "Tues" , AlarmInterface :: WEDNESDAY => "Wed" , AlarmInterface :: THURSDAY => "Thurs" , AlarmInterface :: FRIDAY => "Fri" , AlarmInterface :: SATURDAY => "Sat" , AlarmInterface :: SUNDAY => "Sun" , ] ; $ description = "" ; foreach ( $ days as $ key => $ val ) { if ( $ data & $ key ) { if ( strlen ( $ description ) > 0 ) { $ description .= "," ; } $ description .= $ val ; } } return $ description ; }
Get the frequency of the alarm as a human readable description .
45,858
protected function getPlayMode ( string $ type ) : bool { $ mode = Helper :: getMode ( $ this -> attributes [ "PlayMode" ] ) ; return $ mode [ $ type ] ; }
Get a particular PlayMode .
45,859
protected function save ( ) : AlarmInterface { $ params = [ "StartLocalTime" => $ this -> attributes [ "StartTime" ] , "Duration" => $ this -> attributes [ "Duration" ] , "Recurrence" => $ this -> attributes [ "Recurrence" ] , "Enabled" => $ this -> attributes [ "Enabled" ] ? "1" : "0" , "RoomUUID" => $ this -> attributes [ "RoomUUID" ] , "ProgramURI" => $ this -> attributes [ "ProgramURI" ] , "ProgramMetaData" => $ this -> attributes [ "ProgramMetaData" ] , "PlayMode" => $ this -> attributes [ "PlayMode" ] , "Volume" => $ this -> attributes [ "Volume" ] , "IncludeLinkedZones" => $ this -> attributes [ "IncludeLinkedZones" ] , ] ; $ this -> soap ( "AlarmClock" , "UpdateAlarm" , $ params ) ; return $ this ; }
Update the alarm with the current instance settings .
45,860
public function setLogger ( LoggerInterface $ logger ) { $ this -> logger = $ logger ; $ this -> factory -> setLogger ( $ logger ) ; return $ this ; }
Set the logger object to use .
45,861
public function getLogger ( ) : LoggerInterface { if ( $ this -> logger === null ) { $ this -> setLogger ( new NullLogger ( ) ) ; } assert ( $ this -> logger instanceof LoggerInterface ) ; return $ this -> logger ; }
Get the logger object to use .
45,862
public function getFavouriteStation ( string $ name ) : Stream { $ roughMatch = false ; $ stations = $ this -> getFavouriteStations ( ) ; foreach ( $ stations as $ station ) { if ( $ station -> getTitle ( ) === $ name ) { return $ station ; } if ( strtolower ( $ station -> getTitle ( ) ) === strtolower ( $ name ) ) { $ roughMatch = $ station ; } } if ( $ roughMatch ) { return $ roughMatch ; } throw new NotFoundException ( "Unable to find a radio station by the name '{$name}'" ) ; }
Get the favourite radio station with the specified name .
45,863
public function getFavouriteShow ( string $ name ) : Stream { $ roughMatch = false ; $ shows = $ this -> getFavouriteShows ( ) ; foreach ( $ shows as $ show ) { if ( $ show -> getTitle ( ) === $ name ) { return $ show ; } if ( strtolower ( $ show -> getTitle ( ) ) === strtolower ( $ name ) ) { $ roughMatch = $ show ; } } if ( $ roughMatch ) { return $ roughMatch ; } throw new NotFoundException ( "Unable to find a radio show by the name '{$name}'" ) ; }
Get the favourite radio show with the specified name .
45,864
private function discoverDevices ( SocketInterface $ socket ) { $ this -> collection -> getLogger ( ) -> info ( "discovering devices..." ) ; $ response = $ socket -> request ( ) ; $ search = "urn:schemas-upnp-org:device:ZonePlayer:1" ; $ devices = [ ] ; foreach ( explode ( "\r\n\r\n" , $ response ) as $ reply ) { if ( ! $ reply ) { continue ; } if ( strpos ( $ reply , $ search ) === false ) { continue ; } $ data = [ ] ; foreach ( explode ( "\r\n" , $ reply ) as $ line ) { if ( ! $ pos = strpos ( $ line , ":" ) ) { continue ; } $ key = strtolower ( substr ( $ line , 0 , $ pos ) ) ; $ val = trim ( substr ( $ line , $ pos + 1 ) ) ; $ data [ $ key ] = $ val ; } $ devices [ ] = $ data ; } $ unique = [ ] ; foreach ( $ devices as $ device ) { if ( $ device [ "st" ] !== $ search ) { continue ; } if ( in_array ( $ device [ "usn" ] , $ unique ) ) { continue ; } $ this -> collection -> getLogger ( ) -> info ( "found device: {usn}" , $ device ) ; $ unique [ ] = $ device [ "usn" ] ; $ url = parse_url ( $ device [ "location" ] ) ; $ this -> collection -> addIp ( $ url [ "host" ] ) ; } }
Get all the devices on the current network .
45,865
protected function soap ( string $ service , string $ action , array $ params = [ ] ) { $ params [ "ObjectID" ] = $ this -> id ; if ( $ action === "Browse" ) { $ params [ "Filter" ] = "" ; $ params [ "SortCriteria" ] = "" ; } return $ this -> controller -> soap ( $ service , $ action , $ params ) ; }
Send a soap request to the controller for this queue .
45,866
protected function browse ( string $ type , int $ start = 0 , int $ limit = 1 ) { return $ this -> soap ( "ContentDirectory" , "Browse" , [ "BrowseFlag" => "Browse{$type}" , "StartingIndex" => $ start , "RequestedCount" => $ limit , "Filter" => "" , "SortCriteria" => "" , ] ) ; }
Send a browse request to the controller to get queue info .
45,867
protected function getUpdateId ( ) : int { if ( ! $ this -> updateId ) { $ data = $ this -> browse ( "DirectChildren" ) ; $ this -> updateId = $ data [ "UpdateID" ] ; } return $ this -> updateId ; }
Get the next update id or used the previously cached one .
45,868
public function getTracks ( int $ start = 0 , int $ total = 0 ) : array { $ tracks = [ ] ; if ( $ total > 0 && $ total < 100 ) { $ limit = $ total ; } else { $ limit = 100 ; } do { $ data = $ this -> browse ( "DirectChildren" , $ start , $ limit ) ; $ parser = new XmlParser ( $ data [ "Result" ] ) ; foreach ( $ parser -> getTags ( "item" ) as $ item ) { $ tracks [ ] = $ this -> trackFactory -> createFromXml ( $ item ) ; if ( $ total > 0 && count ( $ tracks ) >= $ total ) { return $ tracks ; } } $ start += $ limit ; } while ( $ data [ "NumberReturned" ] && $ data [ "TotalMatches" ] && count ( $ tracks ) < $ data [ "TotalMatches" ] ) ; return $ tracks ; }
Get tracks from the queue .
45,869
protected function addUris ( array $ tracks , int $ position = null ) { if ( $ position === null ) { $ position = $ this -> getNextPosition ( ) ; } $ chunks = array_chunk ( $ tracks , 16 ) ; foreach ( $ chunks as $ chunk ) { $ uris = "" ; $ metaData = "" ; $ first = true ; foreach ( $ chunk as $ track ) { if ( $ first ) { $ first = false ; } else { $ uris .= " " ; $ metaData .= " " ; } $ uris .= $ track -> getUri ( ) ; $ metaData .= $ track -> getMetaData ( ) ; } $ numberOfTracks = count ( $ chunk ) ; $ data = $ this -> soap ( "AVTransport" , "AddMultipleURIsToQueue" , [ "UpdateID" => 0 , "NumberOfURIs" => $ numberOfTracks , "EnqueuedURIs" => $ uris , "EnqueuedURIsMetaData" => $ metaData , "DesiredFirstTrackNumberEnqueued" => $ position , "EnqueueAsNext" => 0 , ] ) ; $ this -> updateId = $ data [ "NewUpdateID" ] ; $ position += $ numberOfTracks ; } }
Add multiple uris to the queue .
45,870
public function addTrack ( $ track , int $ position = null ) : QueueInterface { if ( is_string ( $ track ) ) { $ track = $ this -> trackFactory -> createFromUri ( $ track ) ; } if ( ! $ track instanceof UriInterface ) { $ error = "The first argument to addTrack() should be an object that implements " . UriInterface :: class ; throw new \ InvalidArgumentException ( $ error ) ; } if ( $ position === null ) { $ position = $ this -> getNextPosition ( ) ; } $ this -> soap ( "AVTransport" , "AddURIToQueue" , [ "UpdateID" => 0 , "EnqueuedURI" => $ track -> getUri ( ) , "EnqueuedURIMetaData" => $ track -> getMetaData ( ) , "DesiredFirstTrackNumberEnqueued" => $ position , "EnqueueAsNext" => 0 , ] ) ; return $ this ; }
Add a track to the queue .
45,871
public function addTracks ( array $ tracks , int $ position = null ) : QueueInterface { $ uris = [ ] ; foreach ( $ tracks as $ track ) { if ( is_string ( $ track ) ) { $ track = $ this -> trackFactory -> createFromUri ( $ track ) ; } if ( ! $ track instanceof UriInterface ) { $ error = "The tracks must contain either string URIs or objects that implement " . UriInterface :: class ; throw new \ InvalidArgumentException ( $ error ) ; } $ uris [ ] = $ track ; } $ this -> addUris ( $ uris , $ position ) ; return $ this ; }
Add tracks to the queue .
45,872
public function removeTracks ( array $ positions ) : bool { $ ranges = [ ] ; $ key = 0 ; $ last = - 1 ; sort ( $ positions ) ; foreach ( $ positions as $ position ) { $ position ++ ; if ( $ last > - 1 ) { if ( $ position === $ last + 1 ) { $ ranges [ $ key ] ++ ; $ last = $ position ; continue ; } } $ key = $ position ; $ ranges [ $ key ] = 1 ; $ last = $ position ; } $ offset = 0 ; foreach ( $ ranges as $ position => $ limit ) { $ position -= $ offset ; $ data = $ this -> soap ( "AVTransport" , "RemoveTrackRangeFromQueue" , [ "UpdateID" => $ this -> getUpdateID ( ) , "StartingIndex" => $ position , "NumberOfTracks" => $ limit , ] ) ; $ this -> updateId = $ data ; $ offset += $ limit ; } return true ; }
Remove tracks from the queue .
45,873
public static function createFromXml ( XmlElement $ xml , ControllerInterface $ controller ) : TrackInterface { return new static ( $ xml -> getTag ( "res" ) -> nodeValue , $ xml -> getTag ( "title" ) -> nodeValue ) ; }
Create a stream from an xml element .
45,874
public function request ( ) : string { $ sock = socket_create ( \ AF_INET , \ SOCK_DGRAM , \ SOL_UDP ) ; if ( $ sock === false ) { throw new NetworkException ( socket_strerror ( socket_last_error ( ) ) ) ; } $ level = ( int ) getprotobyname ( "ip" ) ; socket_set_option ( $ sock , $ level , \ IP_MULTICAST_TTL , 2 ) ; if ( $ this -> networkInterface !== null ) { socket_set_option ( $ sock , $ level , \ IP_MULTICAST_IF , $ this -> networkInterface ) ; } $ request = "M-SEARCH * HTTP/1.1\r\n" ; $ request .= "HOST: {$this->multicastAddress}:reservedSSDPport\r\n" ; $ request .= "MAN: ssdp:discover\r\n" ; $ request .= "MX: 1\r\n" ; $ request .= "ST: urn:schemas-upnp-org:device:ZonePlayer:1\r\n" ; $ this -> logger -> debug ( $ request ) ; socket_sendto ( $ sock , $ request , strlen ( $ request ) , 0 , $ this -> multicastAddress , 1900 ) ; $ read = [ $ sock ] ; $ write = [ ] ; $ except = [ ] ; $ name = null ; $ port = null ; $ tmp = "" ; $ response = "" ; while ( socket_select ( $ read , $ write , $ except , 1 ) ) { socket_recvfrom ( $ sock , $ tmp , 2048 , 0 , $ name , $ port ) ; $ response .= $ tmp ; } $ this -> logger -> debug ( $ response ) ; return $ response ; }
Send out the multicast discover request .
45,875
public function getState ( ) : int { $ name = $ this -> getStateName ( ) ; switch ( $ name ) { case "STOPPED" : return self :: STATE_STOPPED ; case "PLAYING" : return self :: STATE_PLAYING ; case "PAUSED_PLAYBACK" : return self :: STATE_PAUSED ; case "TRANSITIONING" : return self :: STATE_TRANSITIONING ; } return self :: STATE_UNKNOWN ; }
Get the current state of the group of speakers .
45,876
public function getStateDetails ( ) : StateInterface { $ data = $ this -> soap ( "AVTransport" , "GetPositionInfo" ) ; if ( $ data [ "TrackMetaData" ] === "NOT_IMPLEMENTED" ) { $ state = new State ( $ data [ "TrackURI" ] ) ; $ state -> setStream ( new Stream ( "x-rincon-stream:" . $ this -> getUuid ( ) , "Line-In" ) ) ; return $ state ; } if ( ! $ data [ "TrackMetaData" ] ) { return new State ( ) ; } $ parser = new XmlParser ( $ data [ "TrackMetaData" ] ) ; $ state = State :: createFromXml ( $ parser -> getTag ( "item" ) , $ this ) ; if ( ( string ) $ parser -> getTag ( "streamContent" ) ) { $ info = $ this -> getMediaInfo ( ) ; $ meta = new XmlParser ( $ info [ "CurrentURIMetaData" ] ) ; if ( $ title = ( string ) $ meta -> getTag ( "title" ) ) { $ state -> setStream ( new Stream ( "" , $ title ) ) ; } else { $ state -> setStream ( new Stream ( "" , $ parser -> getTag ( "title" ) ) ) ; } } $ state -> setNumber ( $ data [ "Track" ] ) ; $ state -> setDuration ( Time :: parse ( $ data [ "TrackDuration" ] ) ) ; $ state -> setPosition ( Time :: parse ( $ data [ "RelTime" ] ) ) ; if ( $ state -> getNumber ( ) > 0 ) { $ state -> setNumber ( $ state -> getNumber ( ) - 1 ) ; } return $ state ; }
Get attributes about the currently active track in the queue .
45,877
public function setState ( int $ state ) : ControllerInterface { switch ( $ state ) { case self :: STATE_PLAYING : return $ this -> play ( ) ; case self :: STATE_PAUSED : return $ this -> pause ( ) ; case self :: STATE_STOPPED : return $ this -> pause ( ) ; } throw new \ InvalidArgumentException ( "Unknown state: {$state})" ) ; }
Set the state of the group .
45,878
public function play ( ) : ControllerInterface { try { $ this -> soap ( "AVTransport" , "Play" , [ "Speed" => 1 , ] ) ; } catch ( SoapException $ e ) { if ( count ( $ this -> getQueue ( ) ) < 1 ) { $ e = new \ BadMethodCallException ( "Cannot play, the current queue is empty" ) ; } throw $ e ; } return $ this ; }
Start playing the active music for this group .
45,879
public function isStreaming ( ) : bool { $ prefixes = [ "x-sonosapi-stream:" , "x-sonosapi-radio:" , "x-rincon-stream:" , "x-sonos-htastream:" , ] ; $ media = $ this -> getMediaInfo ( ) ; foreach ( $ prefixes as $ prefix ) { if ( strpos ( $ media [ "CurrentURI" ] , $ prefix ) === 0 ) { return true ; } } return false ; }
Check if this controller is currently playing a stream .
45,880
public function useStream ( Stream $ stream ) : ControllerInterface { $ this -> soap ( "AVTransport" , "SetAVTransportURI" , [ "CurrentURI" => $ stream -> getUri ( ) , "CurrentURIMetaData" => $ stream -> getMetaData ( ) , ] ) ; return $ this ; }
Play a stream on this controller .
45,881
public function useLineIn ( SpeakerInterface $ speaker = null ) : ControllerInterface { if ( $ speaker === null ) { $ speaker = $ this ; } $ uri = "x-rincon-stream:" . $ speaker -> getUuid ( ) ; $ stream = new Stream ( $ uri , "Line-In" ) ; return $ this -> useStream ( $ stream ) ; }
Play a line - in from a speaker .
45,882
public function getSpeakers ( ) : array { $ group = [ ] ; $ speakers = $ this -> network -> getSpeakers ( ) ; foreach ( $ speakers as $ speaker ) { if ( $ speaker -> getGroup ( ) === $ this -> getGroup ( ) ) { $ group [ ] = $ speaker ; } } return $ group ; }
Get the speakers that are in the group of this controller .
45,883
public function addSpeaker ( SpeakerInterface $ speaker ) : ControllerInterface { if ( $ speaker -> getUuid ( ) === $ this -> getUuid ( ) ) { return $ this ; } $ speaker -> soap ( "AVTransport" , "SetAVTransportURI" , [ "CurrentURI" => "x-rincon:" . $ this -> getUuid ( ) , "CurrentURIMetaData" => "" , ] ) ; $ speaker -> setGroup ( $ speaker -> getGroup ( ) ) ; return $ this ; }
Adds the specified speaker to the group of this Controller .
45,884
public function restoreState ( ControllerStateInterface $ state ) : ControllerInterface { $ queue = $ this -> getQueue ( ) ; $ queue -> clear ( ) ; $ tracks = $ state -> getTracks ( ) ; if ( count ( $ tracks ) > 0 ) { $ queue -> addTracks ( $ tracks ) ; } if ( count ( $ tracks ) > 0 ) { $ this -> selectTrack ( $ state -> getTrack ( ) ) ; $ this -> seek ( $ state -> getPosition ( ) ) ; } $ this -> setShuffle ( $ state -> getShuffle ( ) ) ; $ this -> setRepeat ( $ state -> getRepeat ( ) ) ; $ this -> setCrossfade ( $ state -> getCrossfade ( ) ) ; if ( $ stream = $ state -> getStream ( ) ) { $ this -> useStream ( $ stream ) ; } $ speakers = [ ] ; foreach ( $ this -> getSpeakers ( ) as $ speaker ) { $ speakers [ $ speaker -> getUuid ( ) ] = $ speaker ; } foreach ( $ state -> getSpeakers ( ) as $ uuid => $ volume ) { if ( array_key_exists ( $ uuid , $ speakers ) ) { $ speakers [ $ uuid ] -> setVolume ( $ volume ) ; } } if ( $ state -> getState ( ) === self :: STATE_PLAYING ) { $ this -> play ( ) ; } elseif ( $ this -> getState ( ) === self :: STATE_PLAYING ) { $ this -> pause ( ) ; } return $ this ; }
Restore the Controller to a previously exported state .
45,885
public function interrupt ( UriInterface $ track , int $ volume = null ) : ControllerInterface { $ track -> getUri ( ) ; $ state = $ this -> exportState ( ) ; $ this -> useQueue ( ) -> getQueue ( ) -> clear ( ) -> addTrack ( $ track ) ; $ this -> setRepeat ( false ) ; if ( $ volume !== null ) { $ this -> setVolume ( $ volume ) ; } $ this -> play ( ) ; sleep ( 1 ) ; while ( $ this -> getState ( ) === self :: STATE_PLAYING ) { usleep ( 500000 ) ; } $ this -> restoreState ( $ state ) ; return $ this ; }
Interrupt the current audio with a track .
45,886
public function soap ( string $ service , string $ action , array $ params = [ ] ) { return $ this -> speaker -> soap ( $ service , $ action , $ params ) ; }
Send a soap request to the speaker .
45,887
public function setVolume ( int $ volume ) : SpeakerInterface { $ speakers = $ this -> getSpeakers ( ) ; foreach ( $ speakers as $ speaker ) { $ speaker -> setVolume ( $ volume ) ; } return $ this ; }
Set the volume of all the speakers this controller manages .
45,888
public function adjustVolume ( int $ adjust ) : SpeakerInterface { $ speakers = $ this -> getSpeakers ( ) ; foreach ( $ speakers as $ speaker ) { $ speaker -> adjustVolume ( $ adjust ) ; } return $ this ; }
Adjust the volume of all the speakers this controller manages .
45,889
public function mute ( bool $ mute = true ) : SpeakerInterface { $ this -> speaker -> mute ( $ mute ) ; return $ this ; }
Mute this speaker .
45,890
public static function fromFormat ( string $ format , string $ string ) : TimeInterface { $ time = CommonTime :: fromFormat ( $ format , $ string ) ; return new self ( $ time -> asInt ( ) ) ; }
Create a new instance from a time in a specified format .
45,891
public function getSpeakers ( ) : array { if ( is_array ( $ this -> speakers ) ) { return $ this -> speakers ; } $ devices = $ this -> collection -> getDevices ( ) ; if ( count ( $ devices ) < 1 ) { throw new \ RuntimeException ( "No devices in this collection" ) ; } $ this -> getLogger ( ) -> info ( "creating speaker instances" ) ; $ this -> speakers = [ ] ; foreach ( $ devices as $ device ) { if ( ! $ device -> isSpeaker ( ) ) { continue ; } $ speaker = new Speaker ( $ device ) ; try { $ speaker -> getGroup ( ) ; } catch ( UnknownGroupException $ e ) { continue ; } $ this -> speakers [ $ device -> getIp ( ) ] = $ speaker ; } return $ this -> speakers ; }
Get all the speakers on the network .
45,892
public function getController ( ) : ControllerInterface { $ controllers = $ this -> getControllers ( ) ; if ( $ controller = reset ( $ controllers ) ) { return $ controller ; } throw new NotFoundException ( "Unable to find any controllers on the current network" ) ; }
Get a Controller instance from the network .
45,893
public function getSpeakerByRoom ( string $ room ) : SpeakerInterface { $ speakers = $ this -> getSpeakers ( ) ; foreach ( $ speakers as $ speaker ) { if ( $ speaker -> getRoom ( ) === $ room ) { return $ speaker ; } } throw new NotFoundException ( "Unable to find a speaker for the room '{$room}'" ) ; }
Get a speaker with the specified room name .
45,894
public function getSpeakersByRoom ( string $ room ) : array { $ return = [ ] ; $ speakers = $ this -> getSpeakers ( ) ; foreach ( $ speakers as $ controller ) { if ( $ controller -> getRoom ( ) === $ room ) { $ return [ ] = $ controller ; } } return $ return ; }
Get all the speakers with the specified room name .
45,895
public function getControllers ( ) : array { $ controllers = [ ] ; $ speakers = $ this -> getSpeakers ( ) ; foreach ( $ speakers as $ speaker ) { if ( ! $ speaker -> isCoordinator ( ) ) { continue ; } $ ip = $ speaker -> getIp ( ) ; $ controllers [ $ ip ] = new Controller ( $ speaker , $ this ) ; } return $ controllers ; }
Get all the coordinators on the network .
45,896
public function getControllerByRoom ( string $ room ) : ControllerInterface { $ group = $ this -> getSpeakerByRoom ( $ room ) -> getGroup ( ) ; $ controllers = $ this -> getControllers ( ) ; foreach ( $ controllers as $ controller ) { if ( $ controller -> getGroup ( ) === $ group ) { return $ controller ; } } throw new NotFoundException ( "Unable to find the controller for the room '{$room}'" ) ; }
Get the coordinator for the specified room name .
45,897
public function getControllerByIp ( string $ ip ) : ControllerInterface { $ speakers = $ this -> getSpeakers ( ) ; if ( ! array_key_exists ( $ ip , $ speakers ) ) { throw new NotFoundException ( "Unable to find a speaker for the IP address '{$ip}'" ) ; } $ group = $ speakers [ $ ip ] -> getGroup ( ) ; foreach ( $ this -> getControllers ( ) as $ controller ) { if ( $ controller -> getGroup ( ) === $ group ) { return $ controller ; } } }
Get the coordinator for the specified ip address .
45,898
public function getPlaylists ( ) : array { if ( is_array ( $ this -> playlists ) ) { return $ this -> playlists ; } $ controller = $ this -> getController ( ) ; $ data = $ controller -> soap ( "ContentDirectory" , "Browse" , [ "ObjectID" => "SQ:" , "BrowseFlag" => "BrowseDirectChildren" , "Filter" => "" , "StartingIndex" => 0 , "RequestedCount" => 100 , "SortCriteria" => "" , ] ) ; $ parser = new XmlParser ( $ data [ "Result" ] ) ; $ playlists = [ ] ; foreach ( $ parser -> getTags ( "container" ) as $ container ) { $ playlists [ ] = new Playlist ( $ container , $ controller ) ; } return $ this -> playlists = $ playlists ; }
Get all the playlists available on the network .
45,899
public function hasPlaylist ( string $ name ) : bool { $ playlists = $ this -> getPlaylists ( ) ; foreach ( $ playlists as $ playlist ) { if ( $ playlist -> getName ( ) === $ name ) { return true ; } if ( strtolower ( $ playlist -> getName ( ) ) === strtolower ( $ name ) ) { return true ; } } return false ; }
Check if a playlist with the specified name exists on this network .