Bobby
Bobby

Reputation: 217

Mediawiki-PHP: Check if an article belongs to a category

I'm editing a Mediawiki extension (PageCreationNotif) to send mail when a page is added to a certain category. The extension original code is here: https://phabricator.wikimedia.org/diffusion/EPCN/browse/master/

The function I'm working on (onArticleInsertComplete in PageCreationNotif.hooks.php) takes a ( &$article ) as input parameter. I want to execute the function code only if $article belongs to "Project" category, already created.

Could you provide me the right code snippet to do this?

It would be like (pseudocode):

public static function onArticleInsertComplete(&$article){

    if( $article.belongsTo(Category.Project) ){
        //do stuff
    }
}

Thank you in advance.

Upvotes: 0

Views: 257

Answers (1)

Sam Wilson
Sam Wilson

Reputation: 4512

There isn't anything like a belongsTo() method in the WikiPage class, so you have to iterate over the categories yourself, checking for membership:

public function onArticleInsertComplete( WikiPage &$article ) {
    $inCat = false;
    foreach ( $article->getCategories() as $cat) {
        if ( $cat->getText() === "Project" ) {
            $inCat = true;
        }
    }
    if ( $inCat ) {
        // Send email etc.
    }
}

(Code is not tested.)

Update: Actually, re-reading your question, I think you're better off hooking in to CategoryAfterPageAdded:

Hooks::register( 'CategoryAfterPageAdded', function( Category $category, WikiPage $page ) {
    if ( $category->getTitle()->getBaseText() === 'Project' ) {
        // Send email.
    }
} );

Upvotes: 1

Related Questions