idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
300
public function hasPermission ( $ permission ) { if ( $ this -> id == self :: ADMINISTRATOR_ID ) { return true ; } return $ this -> permissions -> contains ( 'permission' , $ permission ) ; }
Check whether the group has a certain permission .
301
public static function generate ( string $ provider , string $ identifier , array $ attributes , array $ payload ) { $ token = new static ; $ token -> token = str_random ( 40 ) ; $ token -> provider = $ provider ; $ token -> identifier = $ identifier ; $ token -> user_attributes = $ attributes ; $ token -> payload = $ payload ; $ token -> created_at = Carbon :: now ( ) ; return $ token ; }
Generate an auth token for the specified user .
302
public function process ( Request $ request , Handler $ handler ) : Response { $ method = $ request -> getMethod ( ) ; $ uri = $ request -> getUri ( ) -> getPath ( ) ? : '/' ; $ routeInfo = $ this -> getDispatcher ( ) -> dispatch ( $ method , $ uri ) ; switch ( $ routeInfo [ 0 ] ) { case Dispatcher :: NOT_FOUND : throw new RouteNotFoundException ( $ uri ) ; case Dispatcher :: METHOD_NOT_ALLOWED : throw new MethodNotAllowedException ( $ method ) ; case Dispatcher :: FOUND : $ handler = $ routeInfo [ 1 ] ; $ parameters = $ routeInfo [ 2 ] ; return $ handler ( $ request , $ parameters ) ; } }
Dispatch the given request to our route collection .
303
public function findOrFail ( $ id , User $ actor = null ) { return $ this -> queryVisibleTo ( $ actor ) -> findOrFail ( $ id ) ; }
Find a post by ID optionally making sure it is visible to a certain user or throw an exception .
304
public function findByIds ( array $ ids , User $ actor = null ) { $ posts = $ this -> queryIds ( $ ids , $ actor ) -> get ( ) ; $ posts = $ posts -> sort ( function ( $ a , $ b ) use ( $ ids ) { $ aPos = array_search ( $ a -> id , $ ids ) ; $ bPos = array_search ( $ b -> id , $ ids ) ; if ( $ aPos === $ bPos ) { return 0 ; } return $ aPos < $ bPos ? - 1 : 1 ; } ) ; return $ posts ; }
Find posts by their IDs optionally making sure they are visible to a certain user .
305
public function filterVisibleIds ( array $ ids , User $ actor ) { return $ this -> queryIds ( $ ids , $ actor ) -> pluck ( 'posts.id' ) -> all ( ) ; }
Filter a list of post IDs to only include posts that are visible to a certain user .
306
public function getIndexForNumber ( $ discussionId , $ number , User $ actor = null ) { $ query = Discussion :: find ( $ discussionId ) -> posts ( ) -> whereVisibleTo ( $ actor ) -> where ( 'created_at' , '<' , function ( $ query ) use ( $ discussionId , $ number ) { $ query -> select ( 'created_at' ) -> from ( 'posts' ) -> where ( 'discussion_id' , $ discussionId ) -> whereNotNull ( 'number' ) -> take ( 1 ) -> orderByRaw ( 'ABS(CAST(number AS SIGNED) - ' . ( int ) $ number . ')' ) ; } ) ; return $ query -> count ( ) ; }
Get the position within a discussion where a post with a certain number is . If the post with that number does not exist the index of the closest post to it will be returned .
307
public function handle ( Saving $ event ) { if ( ! $ event -> actor -> isAdmin ( ) ) { return ; } if ( $ event -> actor -> id !== $ event -> user -> id ) { return ; } $ groups = array_get ( $ event -> data , 'relationships.groups.data' ) ; if ( ! isset ( $ groups ) ) { return ; } $ adminGroups = array_filter ( $ groups , function ( $ group ) { return $ group [ 'id' ] == Group :: ADMINISTRATOR_ID ; } ) ; if ( $ adminGroups ) { return ; } throw new PermissionDeniedException ; }
Prevent an admin from removing their admin permission via the API .
308
public function apply ( AbstractSearch $ search , $ query ) { $ query = $ this -> applyGambits ( $ search , $ query ) ; if ( $ query ) { $ this -> applyFulltext ( $ search , $ query ) ; } }
Apply gambits to a search given a search query .
309
public function getGroupsAttribute ( ) { if ( ! isset ( $ this -> attributes [ 'groups' ] ) ) { $ this -> attributes [ 'groups' ] = $ this -> relations [ 'groups' ] = Group :: where ( 'id' , Group :: GUEST_ID ) -> get ( ) ; } return $ this -> attributes [ 'groups' ] ; }
Get the guest s group containing only the guests group model .
310
private function findPackageVersion ( $ path , $ fallback = null ) { if ( file_exists ( "$path/.git" ) ) { $ cwd = getcwd ( ) ; chdir ( $ path ) ; $ output = [ ] ; $ status = null ; exec ( 'git rev-parse HEAD 2>&1' , $ output , $ status ) ; chdir ( $ cwd ) ; if ( $ status == 0 ) { return isset ( $ fallback ) ? "$fallback ($output[0])" : $ output [ 0 ] ; } } return $ fallback ; }
Try to detect a package s exact version .
311
public function read ( $ number ) { if ( $ number > $ this -> last_read_post_number ) { $ this -> last_read_post_number = $ number ; $ this -> last_read_at = Carbon :: now ( ) ; $ this -> raise ( new UserRead ( $ this ) ) ; } return $ this ; }
Mark the discussion as being read up to a certain point . Raises the DiscussionWasRead event .
312
public function findOrFail ( $ id , User $ user = null ) { $ query = Discussion :: where ( 'id' , $ id ) ; return $ this -> scopeVisibleTo ( $ query , $ user ) -> firstOrFail ( ) ; }
Find a discussion by ID optionally making sure it is visible to a certain user or throw an exception .
313
public function getReadIds ( User $ user ) { return Discussion :: leftJoin ( 'discussion_user' , 'discussion_user.discussion_id' , '=' , 'discussions.id' ) -> where ( 'discussion_user.user_id' , $ user -> id ) -> whereColumn ( 'last_read_post_number' , '>=' , 'last_post_number' ) -> pluck ( 'id' ) -> all ( ) ; }
Get the IDs of discussions which a user has read completely .
314
public function addCollection ( $ key , RouteCollection $ routes , $ prefix = null ) { $ this -> routes [ $ key ] = new RouteCollectionUrlGenerator ( $ this -> app -> url ( $ prefix ) , $ routes ) ; return $ this ; }
Register a named route collection for URL generation .
315
public function dispatchEventsFor ( $ entity , User $ actor = null ) { foreach ( $ entity -> releaseEvents ( ) as $ event ) { $ event -> actor = $ actor ; $ this -> events -> dispatch ( $ event ) ; } }
Dispatch all events for an entity .
316
public function sync ( Blueprint \ BlueprintInterface $ blueprint , array $ users ) { $ attributes = $ this -> getAttributes ( $ blueprint ) ; $ toDelete = Notification :: where ( $ attributes ) -> get ( ) ; $ toUndelete = [ ] ; $ newRecipients = [ ] ; foreach ( $ users as $ user ) { if ( ! ( $ user instanceof User ) ) { continue ; } $ existing = $ toDelete -> first ( function ( $ notification , $ i ) use ( $ user ) { return $ notification -> user_id === $ user -> id ; } ) ; if ( $ existing ) { $ toUndelete [ ] = $ existing -> id ; $ toDelete -> forget ( $ toDelete -> search ( $ existing ) ) ; } elseif ( ! static :: $ onePerUser || ! in_array ( $ user -> id , static :: $ sentTo ) ) { $ newRecipients [ ] = $ user ; static :: $ sentTo [ ] = $ user -> id ; } } if ( count ( $ toDelete ) ) { $ this -> setDeleted ( $ toDelete -> pluck ( 'id' ) -> all ( ) , true ) ; } if ( count ( $ toUndelete ) ) { $ this -> setDeleted ( $ toUndelete , false ) ; } if ( count ( $ newRecipients ) ) { $ this -> sendNotifications ( $ blueprint , $ newRecipients ) ; } }
Sync a notification so that it is visible to the specified users and not visible to anyone else . If it is being made visible for the first time attempt to send the user an email .
317
public function delete ( BlueprintInterface $ blueprint ) { Notification :: where ( $ this -> getAttributes ( $ blueprint ) ) -> update ( [ 'is_deleted' => true ] ) ; }
Delete a notification for all users .
318
public function restore ( BlueprintInterface $ blueprint ) { Notification :: where ( $ this -> getAttributes ( $ blueprint ) ) -> update ( [ 'is_deleted' => false ] ) ; }
Restore a notification for all users .
319
protected function mailNotifications ( MailableInterface $ blueprint , array $ recipients ) { foreach ( $ recipients as $ user ) { if ( $ user -> shouldEmail ( $ blueprint :: getType ( ) ) ) { $ this -> mailer -> send ( $ blueprint , $ user ) ; } } }
Mail a notification to a list of users .
320
protected function getAttributes ( Blueprint \ BlueprintInterface $ blueprint ) { return [ 'type' => $ blueprint :: getType ( ) , 'from_user_id' => ( $ fromUser = $ blueprint -> getFromUser ( ) ) ? $ fromUser -> id : null , 'subject_id' => ( $ subject = $ blueprint -> getSubject ( ) ) ? $ subject -> id : null , 'data' => ( $ data = $ blueprint -> getData ( ) ) ? json_encode ( $ data ) : null ] ; }
Construct an array of attributes to be stored in a notification record in the database given a notification blueprint .
321
public function enable ( $ name ) { if ( $ this -> isEnabled ( $ name ) ) { return ; } $ extension = $ this -> getExtension ( $ name ) ; $ this -> dispatcher -> dispatch ( new Enabling ( $ extension ) ) ; $ enabled = $ this -> getEnabled ( ) ; $ enabled [ ] = $ name ; $ this -> migrate ( $ extension ) ; $ this -> publishAssets ( $ extension ) ; $ this -> setEnabled ( $ enabled ) ; $ extension -> enable ( $ this -> app ) ; $ this -> dispatcher -> dispatch ( new Enabled ( $ extension ) ) ; }
Enables the extension .
322
public function disable ( $ name ) { $ enabled = $ this -> getEnabled ( ) ; if ( ( $ k = array_search ( $ name , $ enabled ) ) === false ) { return ; } $ extension = $ this -> getExtension ( $ name ) ; $ this -> dispatcher -> dispatch ( new Disabling ( $ extension ) ) ; unset ( $ enabled [ $ k ] ) ; $ this -> setEnabled ( $ enabled ) ; $ extension -> disable ( $ this -> app ) ; $ this -> dispatcher -> dispatch ( new Disabled ( $ extension ) ) ; }
Disables an extension .
323
public function uninstall ( $ name ) { $ extension = $ this -> getExtension ( $ name ) ; $ this -> disable ( $ name ) ; $ this -> migrateDown ( $ extension ) ; $ this -> unpublishAssets ( $ extension ) ; $ extension -> setInstalled ( false ) ; $ this -> dispatcher -> dispatch ( new Uninstalled ( $ extension ) ) ; }
Uninstalls an extension .
324
protected function publishAssets ( Extension $ extension ) { if ( $ extension -> hasAssets ( ) ) { $ this -> filesystem -> copyDirectory ( $ extension -> getPath ( ) . '/assets' , $ this -> app -> publicPath ( ) . '/assets/extensions/' . $ extension -> getId ( ) ) ; } }
Copy the assets from an extension s assets directory into public view .
325
protected function unpublishAssets ( Extension $ extension ) { $ this -> filesystem -> deleteDirectory ( $ this -> app -> publicPath ( ) . '/assets/extensions/' . $ extension -> getId ( ) ) ; }
Delete an extension s assets from public view .
326
public function getAsset ( Extension $ extension , $ path ) { return $ this -> app -> publicPath ( ) . '/assets/extensions/' . $ extension -> getId ( ) . $ path ; }
Get the path to an extension s published asset .
327
public function migrate ( Extension $ extension , $ direction = 'up' ) { $ this -> app -> bind ( 'Illuminate\Database\Schema\Builder' , function ( $ container ) { return $ container -> make ( 'Illuminate\Database\ConnectionInterface' ) -> getSchemaBuilder ( ) ; } ) ; $ extension -> migrate ( $ this -> migrator , $ direction ) ; }
Runs the database migrations for the extension .
328
public function getEnabledExtensions ( ) { $ enabled = [ ] ; $ extensions = $ this -> getExtensions ( ) ; foreach ( $ this -> getEnabled ( ) as $ id ) { if ( isset ( $ extensions [ $ id ] ) ) { $ enabled [ $ id ] = $ extensions [ $ id ] ; } } return $ enabled ; }
Get only enabled extensions .
329
public function extend ( Container $ app ) { foreach ( $ this -> getEnabledExtensions ( ) as $ extension ) { $ extension -> extend ( $ app ) ; } }
Call on all enabled extensions to extend the Flarum application .
330
protected function setEnabled ( array $ enabled ) { $ enabled = array_values ( array_unique ( $ enabled ) ) ; $ this -> config -> set ( 'extensions_enabled' , json_encode ( $ enabled ) ) ; }
Persist the currently enabled extensions .
331
public function loadLanguagePackFrom ( $ directory ) { $ name = $ title = basename ( $ directory ) ; if ( file_exists ( $ manifest = $ directory . '/composer.json' ) ) { $ json = json_decode ( file_get_contents ( $ manifest ) , true ) ; if ( empty ( $ json ) ) { throw new RuntimeException ( "Error parsing composer.json in $name: " . json_last_error_msg ( ) ) ; } $ locale = array_get ( $ json , 'extra.flarum-locale.code' ) ; $ title = array_get ( $ json , 'extra.flarum-locale.title' , $ title ) ; } if ( ! isset ( $ locale ) ) { throw new RuntimeException ( "Language pack $name must define \"extra.flarum-locale.code\" in composer.json." ) ; } $ this -> locales -> addLocale ( $ locale , $ title ) ; if ( ! is_dir ( $ localeDir = $ directory . '/locale' ) ) { throw new RuntimeException ( "Language pack $name must have a \"locale\" subdirectory." ) ; } if ( file_exists ( $ file = $ localeDir . '/config.js' ) ) { $ this -> locales -> addJsFile ( $ locale , $ file ) ; } if ( file_exists ( $ file = $ localeDir . '/config.css' ) ) { $ this -> locales -> addCssFile ( $ locale , $ file ) ; } foreach ( new DirectoryIterator ( $ localeDir ) as $ file ) { if ( $ file -> isFile ( ) && in_array ( $ file -> getExtension ( ) , [ 'yml' , 'yaml' ] ) ) { $ this -> locales -> addTranslations ( $ locale , $ file -> getPathname ( ) ) ; } } }
Load language pack resources from the given directory .
332
public function addCommand ( $ command ) { if ( is_string ( $ command ) ) { $ command = $ this -> app -> make ( $ command ) ; } if ( $ command instanceof Command ) { $ command -> setLaravel ( $ this -> app ) ; } $ this -> console -> add ( $ command ) ; }
Add a console command to the flarum binary .
333
public static function start ( $ title , User $ user ) { $ discussion = new static ; $ discussion -> title = $ title ; $ discussion -> created_at = Carbon :: now ( ) ; $ discussion -> user_id = $ user -> id ; $ discussion -> setRelation ( 'user' , $ user ) ; $ discussion -> raise ( new Started ( $ discussion ) ) ; return $ discussion ; }
Start a new discussion . Raises the DiscussionWasStarted event .
334
public function rename ( $ title ) { if ( $ this -> title !== $ title ) { $ oldTitle = $ this -> title ; $ this -> title = $ title ; $ this -> raise ( new Renamed ( $ this , $ oldTitle ) ) ; } return $ this ; }
Rename the discussion . Raises the DiscussionWasRenamed event .
335
public function hide ( User $ actor = null ) { if ( ! $ this -> hidden_at ) { $ this -> hidden_at = Carbon :: now ( ) ; $ this -> hidden_user_id = $ actor ? $ actor -> id : null ; $ this -> raise ( new Hidden ( $ this ) ) ; } return $ this ; }
Hide the discussion .
336
public function restore ( ) { if ( $ this -> hidden_at !== null ) { $ this -> hidden_at = null ; $ this -> hidden_user_id = null ; $ this -> raise ( new Restored ( $ this ) ) ; } return $ this ; }
Restore the discussion .
337
public function setFirstPost ( Post $ post ) { $ this -> created_at = $ post -> created_at ; $ this -> user_id = $ post -> user_id ; $ this -> first_post_id = $ post -> id ; return $ this ; }
Set the discussion s first post details .
338
public function setLastPost ( Post $ post ) { $ this -> last_posted_at = $ post -> created_at ; $ this -> last_posted_user_id = $ post -> user_id ; $ this -> last_post_id = $ post -> id ; $ this -> last_post_number = $ post -> number ; return $ this ; }
Set the discussion s last post details .
339
public function refreshLastPost ( ) { if ( $ lastPost = $ this -> comments ( ) -> latest ( ) -> first ( ) ) { $ this -> setLastPost ( $ lastPost ) ; } return $ this ; }
Refresh a discussion s last post details .
340
public function mergePost ( MergeableInterface $ post ) { $ lastPost = $ this -> posts ( ) -> latest ( ) -> first ( ) ; $ post = $ post -> saveAfter ( $ lastPost ) ; return $ this -> modifiedPosts [ ] = $ post ; }
Save a post attempting to merge it with the discussion s last post .
341
public function state ( User $ user = null ) { $ user = $ user ? : static :: $ stateUser ; return $ this -> hasOne ( UserState :: class ) -> where ( 'user_id' , $ user ? $ user -> id : null ) ; }
Define the relationship with the discussion s state for a particular user .
342
protected function setTitleAttribute ( $ title ) { $ this -> attributes [ 'title' ] = $ title ; $ this -> slug = Str :: slug ( $ title ) ; }
Set the discussion title .
343
public function getAttribute ( $ key ) { if ( ! is_null ( $ value = parent :: getAttribute ( $ key ) ) ) { return $ value ; } if ( ! $ this -> relationLoaded ( $ key ) && ( $ relation = $ this -> getCustomRelation ( $ key ) ) ) { if ( ! $ relation instanceof Relation ) { throw new LogicException ( 'Relationship method must return an object of type ' . Relation :: class ) ; } return $ this -> relations [ $ key ] = $ relation -> getResults ( ) ; } }
Get an attribute from the model . If nothing is found attempt to load a custom relation method with this key .
344
public function create ( $ name , $ extension = null , $ table = null , $ create = false ) { $ migrationPath = $ this -> getMigrationPath ( $ extension ) ; $ path = $ this -> getPath ( $ name , $ migrationPath ) ; $ stub = $ this -> getStub ( $ table , $ create ) ; $ this -> files -> put ( $ path , $ this -> populateStub ( $ stub , $ table ) ) ; return $ path ; }
Create a new migration for the given extension .
345
protected function error ( $ message ) { if ( $ this -> output instanceof ConsoleOutputInterface ) { $ this -> output -> getErrorOutput ( ) -> writeln ( "<error>$message</error>" ) ; } else { $ this -> output -> writeln ( "<error>$message</error>" ) ; } }
Send an error or warning message to the user .
346
public function isVisibleTo ( User $ user ) { return ( bool ) $ this -> newQuery ( ) -> whereVisibleTo ( $ user ) -> find ( $ this -> id ) ; }
Determine whether or not this post is visible to the given user .
347
public function newFromBuilder ( $ attributes = [ ] , $ connection = null ) { $ attributes = ( array ) $ attributes ; if ( ! empty ( $ attributes [ 'type' ] ) && isset ( static :: $ models [ $ attributes [ 'type' ] ] ) && class_exists ( $ class = static :: $ models [ $ attributes [ 'type' ] ] ) ) { $ instance = new $ class ; $ instance -> exists = true ; $ instance -> setRawAttributes ( $ attributes , true ) ; $ instance -> setConnection ( $ connection ? : $ this -> connection ) ; return $ instance ; } return parent :: newFromBuilder ( $ attributes , $ connection ) ; }
Create a new model instance according to the post s type .
348
protected function assignId ( ) { list ( $ vendor , $ package ) = explode ( '/' , $ this -> name ) ; $ package = str_replace ( [ 'flarum-ext-' , 'flarum-' ] , '' , $ package ) ; $ this -> id = "$vendor-$package" ; }
Assigns the id for the extension used globally .
349
public function getIcon ( ) { $ icon = $ this -> composerJsonAttribute ( 'extra.flarum-extension.icon' ) ; $ file = Arr :: get ( $ icon , 'image' ) ; if ( is_null ( $ icon ) || is_null ( $ file ) ) { return $ icon ; } $ file = $ this -> path . '/' . $ file ; if ( file_exists ( $ file ) ) { $ extension = pathinfo ( $ file , PATHINFO_EXTENSION ) ; if ( ! array_key_exists ( $ extension , self :: LOGO_MIMETYPES ) ) { throw new \ RuntimeException ( 'Invalid image type' ) ; } $ mimetype = self :: LOGO_MIMETYPES [ $ extension ] ; $ data = base64_encode ( file_get_contents ( $ file ) ) ; $ icon [ 'backgroundImage' ] = "url('data:$mimetype;base64,$data')" ; } return $ icon ; }
Loads the icon information from the composer . json .
350
public function toArray ( ) { return ( array ) array_merge ( [ 'id' => $ this -> getId ( ) , 'version' => $ this -> getVersion ( ) , 'path' => $ this -> path , 'icon' => $ this -> getIcon ( ) , 'hasAssets' => $ this -> hasAssets ( ) , 'hasMigrations' => $ this -> hasMigrations ( ) , ] , $ this -> composerJson ) ; }
Generates an array result for the object .
351
protected function getEmailData ( User $ user , $ email ) { $ token = $ this -> generateToken ( $ user , $ email ) ; return [ '{username}' => $ user -> display_name , '{url}' => $ this -> url -> to ( 'forum' ) -> route ( 'confirmEmail' , [ 'token' => $ token -> token ] ) , '{forum}' => $ this -> settings -> get ( 'forum_title' ) ] ; }
Get the data that should be made available to email templates .
352
public static function map ( ) { $ permissions = [ ] ; foreach ( static :: get ( ) as $ permission ) { $ permissions [ $ permission -> permission ] [ ] = ( string ) $ permission -> group_id ; } return $ permissions ; }
Get a map of permissions to the group IDs that have them .
353
protected function populateRoutes ( RouteCollection $ routes ) { $ factory = $ this -> app -> make ( RouteHandlerFactory :: class ) ; $ callback = include __DIR__ . '/routes.php' ; $ callback ( $ routes , $ factory ) ; $ this -> app -> make ( 'events' ) -> fire ( new ConfigureForumRoutes ( $ routes , $ factory ) ) ; $ defaultRoute = $ this -> app -> make ( 'flarum.settings' ) -> get ( 'default_route' ) ; if ( isset ( $ routes -> getRouteData ( ) [ 0 ] [ 'GET' ] [ $ defaultRoute ] ) ) { $ toDefaultController = $ routes -> getRouteData ( ) [ 0 ] [ 'GET' ] [ $ defaultRoute ] ; } else { $ toDefaultController = $ factory -> toForum ( Content \ Index :: class ) ; } $ routes -> get ( '/' , 'default' , $ toDefaultController ) ; }
Populate the forum client routes .
354
public function scopeWhereSubjectVisibleTo ( Builder $ query , User $ actor ) { $ query -> where ( function ( $ query ) use ( $ actor ) { $ classes = [ ] ; foreach ( static :: $ subjectModels as $ type => $ class ) { $ classes [ $ class ] [ ] = $ type ; } foreach ( $ classes as $ class => $ types ) { $ query -> orWhere ( function ( $ query ) use ( $ types , $ class , $ actor ) { $ query -> whereIn ( 'type' , $ types ) -> whereExists ( function ( $ query ) use ( $ class , $ actor ) { $ query -> selectRaw ( 1 ) -> from ( ( new $ class ) -> getTable ( ) ) -> whereColumn ( 'id' , 'subject_id' ) ; static :: $ dispatcher -> dispatch ( new ScopeModelVisibility ( $ class :: query ( ) -> setQuery ( $ query ) , $ actor , 'view' ) ) ; } ) ; } ) ; } } ) ; }
Scope the query to include only notifications whose subjects are visible to the given user .
355
public function scopeWhereSubject ( Builder $ query , $ model ) { $ query -> whereSubjectModel ( get_class ( $ model ) ) -> where ( 'subject_id' , $ model -> id ) ; }
Scope the query to include only notifications that have the given subject .
356
public function scopeWhereSubjectModel ( Builder $ query , string $ class ) { $ notificationTypes = array_filter ( self :: getSubjectModels ( ) , function ( $ modelClass ) use ( $ class ) { return $ modelClass === $ class or is_subclass_of ( $ class , $ modelClass ) ; } ) ; $ query -> whereIn ( 'type' , array_keys ( $ notificationTypes ) ) ; }
Scope the query to include only notification types that use the given subject model .
357
public static function generate ( $ email , $ userId ) { $ token = new static ; $ token -> token = str_random ( 40 ) ; $ token -> user_id = $ userId ; $ token -> email = $ email ; $ token -> created_at = Carbon :: now ( ) ; return $ token ; }
Generate an email token for the specified user .
358
public static function addColumns ( $ tableName , array $ columnDefinitions ) { return [ 'up' => function ( Builder $ schema ) use ( $ tableName , $ columnDefinitions ) { $ schema -> table ( $ tableName , function ( Blueprint $ table ) use ( $ schema , $ columnDefinitions ) { foreach ( $ columnDefinitions as $ columnName => $ options ) { $ type = array_shift ( $ options ) ; $ table -> addColumn ( $ type , $ columnName , $ options ) ; } } ) ; } , 'down' => function ( Builder $ schema ) use ( $ tableName , $ columnDefinitions ) { $ schema -> table ( $ tableName , function ( Blueprint $ table ) use ( $ columnDefinitions ) { $ table -> dropColumn ( array_keys ( $ columnDefinitions ) ) ; } ) ; } ] ; }
Add columns to a table .
359
public static function renameColumns ( $ tableName , array $ columnNames ) { return [ 'up' => function ( Builder $ schema ) use ( $ tableName , $ columnNames ) { $ schema -> table ( $ tableName , function ( Blueprint $ table ) use ( $ columnNames ) { foreach ( $ columnNames as $ from => $ to ) { $ table -> renameColumn ( $ from , $ to ) ; } } ) ; } , 'down' => function ( Builder $ schema ) use ( $ tableName , $ columnNames ) { $ schema -> table ( $ tableName , function ( Blueprint $ table ) use ( $ columnNames ) { foreach ( $ columnNames as $ to => $ from ) { $ table -> renameColumn ( $ from , $ to ) ; } } ) ; } ] ; }
Rename multiple columns .
360
public static function addSettings ( array $ defaults ) { return [ 'up' => function ( Builder $ schema ) use ( $ defaults ) { $ settings = new DatabaseSettingsRepository ( $ schema -> getConnection ( ) ) ; foreach ( $ defaults as $ key => $ value ) { $ settings -> set ( $ key , $ value ) ; } } , 'down' => function ( Builder $ schema ) use ( $ defaults ) { $ settings = new DatabaseSettingsRepository ( $ schema -> getConnection ( ) ) ; foreach ( array_keys ( $ defaults ) as $ key ) { $ settings -> delete ( $ key ) ; } } ] ; }
Add default values for config values .
361
public static function addPermissions ( array $ permissions ) { $ rows = [ ] ; foreach ( $ permissions as $ permission => $ groups ) { foreach ( ( array ) $ groups as $ group ) { $ rows [ ] = [ 'group_id' => $ group , 'permission' => $ permission , ] ; } } return [ 'up' => function ( Builder $ schema ) use ( $ rows ) { $ db = $ schema -> getConnection ( ) ; foreach ( $ rows as $ row ) { if ( $ db -> table ( 'group_permission' ) -> where ( $ row ) -> exists ( ) ) { continue ; } if ( $ db -> table ( 'groups' ) -> where ( 'id' , $ row [ 'group_id' ] ) -> doesntExist ( ) ) { continue ; } $ db -> table ( 'group_permission' ) -> insert ( $ row ) ; } } , 'down' => function ( Builder $ schema ) use ( $ rows ) { $ db = $ schema -> getConnection ( ) ; foreach ( $ rows as $ row ) { $ db -> table ( 'group_permission' ) -> where ( $ row ) -> delete ( ) ; } } ] ; }
Add default permissions .
362
public function parse ( $ text , $ context = null ) { $ parser = $ this -> getParser ( $ context ) ; $ this -> events -> dispatch ( new Parsing ( $ parser , $ context , $ text ) ) ; return $ parser -> parse ( $ text ) ; }
Parse text .
363
public function render ( $ xml , $ context = null , ServerRequestInterface $ request = null ) { $ renderer = $ this -> getRenderer ( ) ; $ this -> events -> dispatch ( new Rendering ( $ renderer , $ context , $ xml , $ request ) ) ; return $ renderer -> render ( $ xml ) ; }
Render parsed XML .
364
protected function getComponent ( $ name ) { $ formatter = $ this -> cache -> rememberForever ( 'flarum.formatter' , function ( ) { return $ this -> getConfigurator ( ) -> finalize ( ) ; } ) ; return $ formatter [ $ name ] ; }
Get a TextFormatter component .
365
protected function getCustomRelationship ( $ model , $ name ) { $ relationship = static :: $ dispatcher -> until ( new GetApiRelationship ( $ this , $ name , $ model ) ) ; if ( $ relationship && ! ( $ relationship instanceof Relationship ) ) { throw new LogicException ( 'GetApiRelationship handler must return an instance of ' . Relationship :: class ) ; } return $ relationship ; }
Get a custom relationship .
366
public function hasOne ( $ model , $ serializer , $ relation = null ) { return $ this -> buildRelationship ( $ model , $ serializer , $ relation ) ; }
Get a relationship builder for a has - one relationship .
367
public function hasMany ( $ model , $ serializer , $ relation = null ) { return $ this -> buildRelationship ( $ model , $ serializer , $ relation , true ) ; }
Get a relationship builder for a has - many relationship .
368
protected function applySort ( AbstractSearch $ search , array $ sort = null ) { $ sort = $ sort ? : $ search -> getDefaultSort ( ) ; if ( is_callable ( $ sort ) ) { $ sort ( $ search -> getQuery ( ) ) ; } else { foreach ( $ sort as $ field => $ order ) { if ( is_array ( $ order ) ) { foreach ( $ order as $ value ) { $ search -> getQuery ( ) -> orderByRaw ( snake_case ( $ field ) . ' != ?' , [ $ value ] ) ; } } else { $ search -> getQuery ( ) -> orderBy ( snake_case ( $ field ) , $ order ) ; } } } }
Apply sort criteria to a discussion search .
369
public function revise ( $ content , User $ actor ) { if ( $ this -> content !== $ content ) { $ this -> content = $ content ; $ this -> edited_at = Carbon :: now ( ) ; $ this -> edited_user_id = $ actor -> id ; $ this -> raise ( new Revised ( $ this ) ) ; } return $ this ; }
Revise the post s content .
370
public function setContentAttribute ( $ value ) { $ this -> attributes [ 'content' ] = $ value ? static :: $ formatter -> parse ( $ value , $ this ) : null ; }
Parse the content before it is saved to the database .
371
protected function runClosureMigration ( $ migration , $ direction = 'up' ) { if ( is_array ( $ migration ) && array_key_exists ( $ direction , $ migration ) ) { call_user_func ( $ migration [ $ direction ] , $ this -> schemaBuilder ) ; } else { throw new Exception ( 'Migration file should contain an array with up/down.' ) ; } }
Runs a closure migration based on the migrate direction .
372
public static function logIn ( string $ provider , string $ identifier ) : ? User { if ( $ provider = static :: where ( compact ( 'provider' , 'identifier' ) ) -> first ( ) ) { $ provider -> touch ( ) ; return $ provider -> user ; } return null ; }
Get the user associated with the provider so that they can be logged in .
373
public function send ( $ controller , User $ actor = null , array $ queryParams = [ ] , array $ body = [ ] ) : ResponseInterface { $ request = ServerRequestFactory :: fromGlobals ( null , $ queryParams , $ body ) ; $ request = $ request -> withAttribute ( 'actor' , $ actor ) ; if ( is_string ( $ controller ) ) { $ controller = $ this -> container -> make ( $ controller ) ; } if ( ! ( $ controller instanceof RequestHandlerInterface ) ) { throw new InvalidArgumentException ( 'Endpoint must be an instance of ' . RequestHandlerInterface :: class ) ; } try { return $ controller -> handle ( $ request ) ; } catch ( Exception $ e ) { if ( ! $ this -> errorHandler ) { throw $ e ; } return $ this -> errorHandler -> handle ( $ e ) ; } }
Execute the given API action class pass the input and return its response .
374
public function findOrFail ( $ id , User $ actor = null ) { $ query = Group :: where ( 'id' , $ id ) ; return $ this -> scopeVisibleTo ( $ query , $ actor ) -> firstOrFail ( ) ; }
Find a user by ID optionally making sure it is visible to a certain user or throw an exception .
375
public function findByName ( $ name , User $ actor = null ) { $ query = Group :: where ( 'name_singular' , $ name ) -> orWhere ( 'name_plural' , $ name ) ; return $ this -> scopeVisibleTo ( $ query , $ actor ) -> first ( ) ; }
Find a group by name .
376
public static function slug ( $ str ) { $ str = strtolower ( $ str ) ; $ str = preg_replace ( '/[^a-z0-9]/i' , '-' , $ str ) ; $ str = preg_replace ( '/-+/' , '-' , $ str ) ; $ str = preg_replace ( '/-$|^-/' , '' , $ str ) ; return $ str ; }
Create a slug out of the given string .
377
protected function autoDetectTimeZone ( $ object , $ originalObject = null ) { $ timezone = CarbonTimeZone :: instance ( $ object ) ; if ( $ timezone && is_int ( $ originalObject ? : $ object ) ) { $ timezone = $ timezone -> toRegionTimeZone ( $ this ) ; } return $ timezone ; }
Creates a DateTimeZone from a string DateTimeZone or integer offset then convert it as region timezone if integer .
378
protected function resolveCarbon ( $ date = null ) { if ( ! $ date ) { return $ this -> nowWithSameTz ( ) ; } if ( is_string ( $ date ) ) { return static :: parse ( $ date , $ this -> getTimezone ( ) ) ; } static :: expectDateTime ( $ date , [ 'null' , 'string' ] ) ; return $ date instanceof self ? $ date : static :: instance ( $ date ) ; }
Return the Carbon instance passed through a now instance in the same timezone if null given or parse the input if string given .
379
public function addUnitNoOverflow ( $ valueUnit , $ value , $ overflowUnit ) { return $ this -> setUnitNoOverflow ( $ valueUnit , $ this -> $ valueUnit + $ value , $ overflowUnit ) ; }
Add any unit to a new value without overflowing current other unit given .
380
public function subUnitNoOverflow ( $ valueUnit , $ value , $ overflowUnit ) { return $ this -> setUnitNoOverflow ( $ valueUnit , $ this -> $ valueUnit - $ value , $ overflowUnit ) ; }
Subtract any unit to a new value without overflowing current other unit given .
381
public function utcOffset ( int $ offset = null ) { if ( func_num_args ( ) < 1 ) { return $ this -> offsetMinutes ; } return $ this -> setTimezone ( static :: safeCreateDateTimeZone ( $ offset / static :: MINUTES_PER_HOUR ) ) ; }
Returns the minutes offset to UTC if no arguments passed else set the timezone with given minutes shift passed .
382
public function setTimezone ( $ value ) { $ date = parent :: setTimezone ( static :: safeCreateDateTimeZone ( $ value ) ) ; $ date -> getTimestamp ( ) ; return $ date ; }
Set the instance s timezone from a string or object .
383
public function setTimeFrom ( $ date = null ) { $ date = $ this -> resolveCarbon ( $ date ) ; return $ this -> setTime ( $ date -> hour , $ date -> minute , $ date -> second , $ date -> microsecond ) ; }
Set the hour minute second and microseconds for this instance to that of the passed instance .
384
public function setDateTimeFrom ( $ date = null ) { $ date = $ this -> resolveCarbon ( $ date ) ; return $ this -> modify ( $ date -> rawFormat ( 'Y-m-d H:i:s.u' ) ) ; }
Set the date and time for this instance to that of the passed instance .
385
public static function hasRelativeKeywords ( $ time ) { if ( strtotime ( $ time ) === false ) { return false ; } $ date1 = new DateTime ( '2000-01-01T00:00:00Z' ) ; $ date1 -> modify ( $ time ) ; $ date2 = new DateTime ( '2001-12-25T00:00:00Z' ) ; $ date2 -> modify ( $ time ) ; return $ date1 != $ date2 ; }
Determine if a time string will produce a relative date .
386
public function getIsoFormats ( $ locale = null ) { return [ 'LT' => $ this -> getTranslationMessage ( 'formats.LT' , $ locale , 'h:mm A' ) , 'LTS' => $ this -> getTranslationMessage ( 'formats.LTS' , $ locale , 'h:mm:ss A' ) , 'L' => $ this -> getTranslationMessage ( 'formats.L' , $ locale , 'MM/DD/YYYY' ) , 'LL' => $ this -> getTranslationMessage ( 'formats.LL' , $ locale , 'MMMM D, YYYY' ) , 'LLL' => $ this -> getTranslationMessage ( 'formats.LLL' , $ locale , 'MMMM D, YYYY h:mm A' ) , 'LLLL' => $ this -> getTranslationMessage ( 'formats.LLLL' , $ locale , 'dddd, MMMM D, YYYY h:mm A' ) , ] ; }
Returns list of locale formats for ISO formatting .
387
public function getCalendarFormats ( $ locale = null ) { return [ 'sameDay' => $ this -> getTranslationMessage ( 'calendar.sameDay' , $ locale , '[Today at] LT' ) , 'nextDay' => $ this -> getTranslationMessage ( 'calendar.nextDay' , $ locale , '[Tomorrow at] LT' ) , 'nextWeek' => $ this -> getTranslationMessage ( 'calendar.nextWeek' , $ locale , 'dddd [at] LT' ) , 'lastDay' => $ this -> getTranslationMessage ( 'calendar.lastDay' , $ locale , '[Yesterday at] LT' ) , 'lastWeek' => $ this -> getTranslationMessage ( 'calendar.lastWeek' , $ locale , '[Last] dddd [at] LT' ) , 'sameElse' => $ this -> getTranslationMessage ( 'calendar.sameElse' , $ locale , 'L' ) , ] ; }
Returns list of calendar formats for ISO formatting .
388
public function getPaddedUnit ( $ unit , $ length = 2 , $ padString = '0' , $ padType = STR_PAD_LEFT ) { return ( $ this -> $ unit < 0 ? '-' : '' ) . str_pad ( abs ( $ this -> $ unit ) , $ length , $ padString , $ padType ) ; }
Returns a unit of the instance padded with 0 by default or any other string if specified .
389
public function ordinal ( string $ key , string $ period = null ) : string { $ number = $ this -> $ key ; $ result = $ this -> translate ( 'ordinal' , [ ':number' => $ number , ':period' => $ period , ] ) ; return strval ( $ result === 'ordinal' ? $ number : $ result ) ; }
Return a property with its ordinal .
390
public function meridiem ( bool $ isLower = false ) : string { $ hour = $ this -> hour ; $ index = $ hour < 12 ? 0 : 1 ; if ( $ isLower ) { $ key = 'meridiem.' . ( $ index + 2 ) ; $ result = $ this -> translate ( $ key ) ; if ( $ result !== $ key ) { return $ result ; } } $ key = "meridiem.$index" ; $ result = $ this -> translate ( $ key ) ; if ( $ result === $ key ) { $ result = $ this -> translate ( 'meridiem' , [ ':hour' => $ this -> hour , ':minute' => $ this -> minute , ':isLower' => $ isLower , ] ) ; if ( $ result === 'meridiem' ) { return $ isLower ? $ this -> latinMeridiem : $ this -> latinUpperMeridiem ; } } elseif ( $ isLower ) { $ result = mb_strtolower ( $ result ) ; } return $ result ; }
Return the meridiem of the current time in the current locale .
391
public function getAltNumber ( string $ key ) : string { $ number = strlen ( $ key ) > 1 ? $ this -> $ key : $ this -> rawFormat ( 'h' ) ; $ translateKey = "alt_numbers.$number" ; $ symbol = $ this -> translate ( $ translateKey ) ; if ( $ symbol !== $ translateKey ) { return $ symbol ; } if ( $ number > 99 && $ this -> translate ( 'alt_numbers.99' ) !== 'alt_numbers.99' ) { $ start = '' ; foreach ( [ 10000 , 1000 , 100 ] as $ exp ) { $ key = "alt_numbers_pow.$exp" ; if ( $ number >= $ exp && $ number < $ exp * 10 && ( $ pow = $ this -> translate ( $ key ) ) !== $ key ) { $ unit = floor ( $ number / $ exp ) ; $ number -= $ unit * $ exp ; $ start .= ( $ unit > 1 ? $ this -> translate ( "alt_numbers.$unit" ) : '' ) . $ pow ; } } $ result = '' ; while ( $ number ) { $ chunk = $ number % 100 ; $ result = $ this -> translate ( "alt_numbers.$chunk" ) . $ result ; $ number = floor ( $ number / 100 ) ; } return "$start$result" ; } if ( $ number > 9 && $ this -> translate ( 'alt_numbers.9' ) !== 'alt_numbers.9' ) { $ result = '' ; while ( $ number ) { $ chunk = $ number % 10 ; $ result = $ this -> translate ( "alt_numbers.$chunk" ) . $ result ; $ number = floor ( $ number / 10 ) ; } return $ result ; } return $ number ; }
Returns the alternative number if available in the current locale .
392
public function setUnit ( $ unit , $ value = null ) { $ unit = static :: singularUnit ( $ unit ) ; $ dateUnits = [ 'year' , 'month' , 'day' ] ; if ( in_array ( $ unit , $ dateUnits ) ) { return $ this -> setDate ( ... array_map ( function ( $ name ) use ( $ unit , $ value ) { return $ name === $ unit ? $ value : $ this -> $ name ; } , $ dateUnits ) ) ; } $ units = [ 'hour' , 'minute' , 'second' , 'micro' ] ; if ( $ unit === 'millisecond' || $ unit === 'milli' ) { $ value *= 1000 ; $ unit = 'micro' ; } elseif ( $ unit === 'microsecond' ) { $ unit = 'micro' ; } return $ this -> setTime ( ... array_map ( function ( $ name ) use ( $ unit , $ value ) { return $ name === $ unit ? $ value : $ this -> $ name ; } , $ units ) ) ; }
Set specified unit to new given value .
393
public static function setFallbackLocale ( $ locale ) { $ translator = static :: getTranslator ( ) ; if ( method_exists ( $ translator , 'setFallbackLocales' ) ) { $ translator -> setFallbackLocales ( [ $ locale ] ) ; if ( $ translator instanceof Translator ) { $ preferredLocale = $ translator -> getLocale ( ) ; $ translator -> setMessages ( $ preferredLocale , array_replace_recursive ( $ translator -> getMessages ( ) [ $ locale ] ?? [ ] , Translator :: get ( $ locale ) -> getMessages ( ) [ $ locale ] ?? [ ] , $ translator -> getMessages ( $ preferredLocale ) ) ) ; } } }
Set the fallback locale .
394
public static function localeHasShortUnits ( $ locale ) { return static :: executeWithLocale ( $ locale , function ( $ newLocale , TranslatorInterface $ translator ) { return $ newLocale && ( ( $ y = static :: translateWith ( $ translator , 'y' ) ) !== 'y' && $ y !== static :: translateWith ( $ translator , 'year' ) ) || ( ( $ y = static :: translateWith ( $ translator , 'd' ) ) !== 'd' && $ y !== static :: translateWith ( $ translator , 'day' ) ) || ( ( $ y = static :: translateWith ( $ translator , 'h' ) ) !== 'h' && $ y !== static :: translateWith ( $ translator , 'hour' ) ) ; } ) ; }
Returns true if the given locale is internally supported and has short - units support . Support is considered enabled if either year day or hour has a short variant translated .
395
public static function getAvailableLocalesInfo ( ) { $ languages = [ ] ; foreach ( static :: getAvailableLocales ( ) as $ id ) { $ languages [ $ id ] = new Language ( $ id ) ; } return $ languages ; }
Returns list of Language object for each available locale . This object allow you to get the ISO name native name region and variant of the locale .
396
public static function createFromDate ( $ year = null , $ month = null , $ day = null , $ tz = null ) { return static :: create ( $ year , $ month , $ day , null , null , null , $ tz ) ; }
Create a Carbon instance from just a date . The time portion is set to now .
397
public static function createMidnightDate ( $ year = null , $ month = null , $ day = null , $ tz = null ) { return static :: create ( $ year , $ month , $ day , 0 , 0 , 0 , $ tz ) ; }
Create a Carbon instance from just a date . The time portion is set to midnight .
398
public static function createFromLocaleFormat ( $ format , $ locale , $ time , $ tz = null ) { return static :: rawCreateFromFormat ( $ format , static :: translateTimeString ( $ time , $ locale , 'en' ) , $ tz ) ; }
Create a Carbon instance from a specific format and a string in a given language .
399
public static function createFromLocaleIsoFormat ( $ format , $ locale , $ time , $ tz = null ) { $ time = static :: translateTimeString ( $ time , $ locale , 'en' , CarbonInterface :: TRANSLATE_MONTHS | CarbonInterface :: TRANSLATE_DAYS | CarbonInterface :: TRANSLATE_MERIDIEM ) ; return static :: createFromIsoFormat ( $ format , $ time , $ tz , $ locale ) ; }
Create a Carbon instance from a specific ISO format and a string in a given language .