Improve code suffering from PHP 5.3's lack of support for foo()[]
authorBartosz Dziewoński <matma.rex@gmail.com>
Wed, 17 Feb 2016 19:54:59 +0000 (20:54 +0100)
committerBartosz Dziewoński <matma.rex@gmail.com>
Sun, 28 Feb 2016 21:49:20 +0000 (22:49 +0100)
I searched for /\$(\S+) = (.+?\(.*?\);)\n.*?\$\1\[/, ignored
everything involving isset(), unset() or array assigments, then
skimmed through the remaining results and changed things where they
made sense. These changes were not automated, so please review them.

Change-Id: Ib37b4c66fc57648470f151ad412210b3629c2538

28 files changed:
includes/Block.php
includes/EditPage.php
includes/GlobalFunctions.php
includes/api/ApiBase.php
includes/api/ApiOpenSearch.php
includes/db/Database.php
includes/db/DatabaseMssql.php
includes/filebackend/FSFileBackend.php
includes/installer/Installer.php
includes/jobqueue/JobQueueFederated.php
includes/jobqueue/JobRunner.php
includes/libs/MultiHttpClient.php
includes/libs/RiffExtractor.php
includes/libs/objectcache/MemcachedClient.php
includes/libs/virtualrest/RestbaseVirtualRESTService.php
includes/libs/virtualrest/VirtualRESTServiceClient.php
includes/media/ExifBitmap.php
includes/media/GIFMetadataExtractor.php
includes/media/PNGMetadataExtractor.php
includes/page/Article.php
includes/parser/Parser.php
includes/search/SearchPostgres.php
includes/skins/SkinTemplate.php
languages/ConverterRule.php
languages/Language.php
languages/LanguageConverter.php
maintenance/tidyUpBug37714.php
tests/testHelpers.inc

index 696a520..764592d 100644 (file)
@@ -1307,8 +1307,7 @@ class Block {
                # but actually an old subpage (bug #29797)
                if ( strpos( $target, '/' ) !== false ) {
                        # An old subpage, drill down to the user behind it
-                       $parts = explode( '/', $target );
-                       $target = $parts[0];
+                       $target = explode( '/', $target )[0];
                }
 
                $userObj = User::newFromName( $target );
index b5d0a7b..3206486 100644 (file)
@@ -2320,8 +2320,7 @@ class EditPage {
                # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
                # Show log extract when the user is currently blocked
                if ( $namespace == NS_USER || $namespace == NS_USER_TALK ) {
-                       $parts = explode( '/', $this->mTitle->getText(), 2 );
-                       $username = $parts[0];
+                       $username = explode( '/', $this->mTitle->getText(), 2 )[0];
                        $user = User::newFromName( $username, false /* allow IP users*/ );
                        $ip = User::isIP( $username );
                        $block = Block::newFromTarget( $user, $user );
index eb174f2..7ed5fba 100644 (file)
@@ -1949,9 +1949,9 @@ function mimeTypeMatch( $type, $avail ) {
        if ( array_key_exists( $type, $avail ) ) {
                return $type;
        } else {
-               $parts = explode( '/', $type );
-               if ( array_key_exists( $parts[0] . '/*', $avail ) ) {
-                       return $parts[0] . '/*';
+               $mainType = explode( '/', $type )[0];
+               if ( array_key_exists( "$mainType/*", $avail ) ) {
+                       return "$mainType/*";
                } elseif ( array_key_exists( '*/*', $avail ) ) {
                        return '*/*';
                } else {
@@ -1977,8 +1977,8 @@ function wfNegotiateType( $cprefs, $sprefs ) {
        $combine = [];
 
        foreach ( array_keys( $sprefs ) as $type ) {
-               $parts = explode( '/', $type );
-               if ( $parts[1] != '*' ) {
+               $subType = explode( '/', $type )[1];
+               if ( $subType != '*' ) {
                        $ckey = mimeTypeMatch( $type, $cprefs );
                        if ( $ckey ) {
                                $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
@@ -1987,8 +1987,8 @@ function wfNegotiateType( $cprefs, $sprefs ) {
        }
 
        foreach ( array_keys( $cprefs ) as $type ) {
-               $parts = explode( '/', $type );
-               if ( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
+               $subType = explode( '/', $type )[1];
+               if ( $subType != '*' && !array_key_exists( $type, $sprefs ) ) {
                        $skey = mimeTypeMatch( $type, $sprefs );
                        if ( $skey ) {
                                $combine[$type] = $sprefs[$skey] * $cprefs[$type];
index e71cbae..f99be4f 100644 (file)
@@ -694,8 +694,7 @@ abstract class ApiBase extends ContextSource {
         * @return mixed Parameter value
         */
        protected function getParameter( $paramName, $parseLimit = true ) {
-               $params = $this->getFinalParams();
-               $paramSettings = $params[$paramName];
+               $paramSettings = $this->getFinalParams()[$paramName];
 
                return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
        }
index 7a7d8f5..304b2d6 100644 (file)
@@ -338,8 +338,7 @@ class ApiOpenSearch extends ApiBase {
                        return trim( $matches[1] );
                } else {
                        // Just return the first line
-                       $lines = explode( "\n", $text );
-                       return trim( $lines[0] );
+                       return trim( explode( "\n", $text )[0] );
                }
        }
 
index 02a6ec8..c065ee9 100644 (file)
@@ -1558,8 +1558,8 @@ abstract class DatabaseBase implements IDatabase {
                                                // Special-case single values, as IN isn't terribly efficient
                                                // Don't necessarily assume the single key is 0; we don't
                                                // enforce linear numeric ordering on other arrays here.
-                                               $value = array_values( $value );
-                                               $list .= $field . " = " . $this->addQuotes( $value[0] );
+                                               $value = array_values( $value )[0];
+                                               $list .= $field . " = " . $this->addQuotes( $value );
                                        } else {
                                                $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
                                        }
index a295b0b..ce34537 100644 (file)
@@ -301,8 +301,7 @@ class DatabaseMssql extends Database {
                        $res = $res->result;
                }
 
-               $metadata = sqlsrv_field_metadata( $res );
-               return $metadata[$n]['Name'];
+               return sqlsrv_field_metadata( $res )[$n]['Name'];
        }
 
        /**
index 86d146d..efe78ee 100644 (file)
@@ -86,8 +86,8 @@ class FSFileBackend extends FileBackendStore {
                $this->fileMode = isset( $config['fileMode'] ) ? $config['fileMode'] : 0644;
                if ( isset( $config['fileOwner'] ) && function_exists( 'posix_getuid' ) ) {
                        $this->fileOwner = $config['fileOwner'];
-                       $info = posix_getpwuid( posix_getuid() );
-                       $this->currentUser = $info['name']; // cache this, assuming it doesn't change
+                       // cache this, assuming it doesn't change
+                       $this->currentUser = posix_getpwuid( posix_getuid() )['name'];
                }
        }
 
index c076cba..442baf7 100644 (file)
@@ -609,8 +609,7 @@ abstract class Installer {
                # posix_getegid() *not* getmygid() because we want the group of the webserver,
                # not whoever owns the current script.
                $gid = posix_getegid();
-               $getpwuid = posix_getpwuid( $gid );
-               $group = $getpwuid['name'];
+               $group = posix_getpwuid( $gid )['name'];
 
                return $group;
        }
index ecf1a28..c127239 100644 (file)
@@ -315,14 +315,13 @@ class JobQueueFederated extends JobQueue {
        }
 
        protected function doIsRootJobOldDuplicate( Job $job ) {
-               $params = $job->getRootJobParams();
-               $sigature = $params['rootJobSignature'];
-               $partition = $this->partitionRing->getLiveLocation( $sigature );
+               $signature = $job->getRootJobParams()['rootJobSignature'];
+               $partition = $this->partitionRing->getLiveLocation( $signature );
                try {
                        return $this->partitionQueues[$partition]->doIsRootJobOldDuplicate( $job );
                } catch ( JobQueueError $e ) {
                        if ( $this->partitionRing->ejectFromLiveRing( $partition, 5 ) ) {
-                               $partition = $this->partitionRing->getLiveLocation( $sigature );
+                               $partition = $this->partitionRing->getLiveLocation( $signature );
                                return $this->partitionQueues[$partition]->doIsRootJobOldDuplicate( $job );
                        }
                }
@@ -331,14 +330,13 @@ class JobQueueFederated extends JobQueue {
        }
 
        protected function doDeduplicateRootJob( IJobSpecification $job ) {
-               $params = $job->getRootJobParams();
-               $sigature = $params['rootJobSignature'];
-               $partition = $this->partitionRing->getLiveLocation( $sigature );
+               $signature = $job->getRootJobParams()['rootJobSignature'];
+               $partition = $this->partitionRing->getLiveLocation( $signature );
                try {
                        return $this->partitionQueues[$partition]->doDeduplicateRootJob( $job );
                } catch ( JobQueueError $e ) {
                        if ( $this->partitionRing->ejectFromLiveRing( $partition, 5 ) ) {
-                               $partition = $this->partitionRing->getLiveLocation( $sigature );
+                               $partition = $this->partitionRing->getLiveLocation( $signature );
                                return $this->partitionQueues[$partition]->doDeduplicateRootJob( $job );
                        }
                }
index ed29e59..c542d97 100644 (file)
@@ -289,9 +289,9 @@ class JobRunner implements LoggerAwareInterface {
                        $stats->timing( "jobqueue.pickup_delay.$jType", 1000 * $pickupDelay );
                }
                // Record root job age for jobs being run
-               $root = $job->getRootJobParams();
-               if ( $root['rootJobTimestamp'] ) {
-                       $age = max( 0, $popTime - wfTimestamp( TS_UNIX, $root['rootJobTimestamp'] ) );
+               $rootTimestamp = $job->getRootJobParams()['rootJobTimestamp'];
+               if ( $rootTimestamp ) {
+                       $age = max( 0, $popTime - wfTimestamp( TS_UNIX, $rootTimestamp ) );
                        $stats->timing( "jobqueue.pickup_root_age.$jType", 1000 * $age );
                }
                // Track the execution time for jobs
index 4e19025..331f2d5 100644 (file)
@@ -105,8 +105,7 @@ class MultiHttpClient {
         * @return array Response array for request
         */
        final public function run( array $req, array $opts = [] ) {
-               $req = $this->runMulti( [ $req ], $opts );
-               return $req[0]['response'];
+               return $this->runMulti( [ $req ], $opts )[0]['response'];
        }
 
        /**
index 3a8b55e..304b99b 100644 (file)
@@ -94,7 +94,6 @@ class RiffExtractor {
         * @return int
         */
        public static function extractUInt32( $string ) {
-               $unpacked = unpack( 'V', $string );
-               return $unpacked[1];
+               return unpack( 'V', $string )[1];
        }
 };
index ae82ca1..59322b6 100644 (file)
@@ -791,8 +791,7 @@ class MemcachedClient {
         * @param string $host
         */
        function _dead_host( $host ) {
-               $parts = explode( ':', $host );
-               $ip = $parts[0];
+               $ip = explode( ':', $host )[0];
                $this->_host_dead[$ip] = time() + 30 + intval( rand( 0, 10 ) );
                $this->_host_dead[$host] = $this->_host_dead[$ip];
                unset( $this->_cache_sock[$host] );
index d2dd89f..16c9331 100644 (file)
@@ -109,10 +109,10 @@ class RestbaseVirtualRESTService extends VirtualRESTService {
 
                $result = [];
                foreach ( $reqs as $key => $req ) {
-                       $parts = explode( '/', $req['url'] );
-                       if ( $parts[1] === 'v3' ) {
+                       $version = explode( '/', $req['url'] )[1];
+                       if ( $version === 'v3' ) {
                                $result[$key] = $this->onParsoid3Request( $req, $idGeneratorFunc );
-                       } elseif ( $parts[1] === 'v1' ) {
+                       } elseif ( $version === 'v1' ) {
                                $result[$key] = $this->onParsoid1Request( $req, $idGeneratorFunc );
                        } else {
                                throw new Exception( "Only v1 and v3 are supported." );
index c64fe34..4b8ad5e 100644 (file)
@@ -134,8 +134,7 @@ class VirtualRESTServiceClient {
         * @return array Response array for request
         */
        public function run( array $req ) {
-               $responses = $this->runMulti( [ $req ] );
-               return $responses[0];
+               return $this->runMulti( [ $req ] )[0];
        }
 
        /**
index 6a3809b..732be3d 100644 (file)
@@ -34,8 +34,7 @@ class ExifBitmapHandler extends BitmapHandler {
 
        function convertMetadataVersion( $metadata, $version = 1 ) {
                // basically flattens arrays.
-               $version = explode( ';', $version, 2 );
-               $version = intval( $version[0] );
+               $version = intval( explode( ';', $version, 2 )[0] );
                if ( $version < 1 || $version >= 2 ) {
                        return $metadata;
                }
index 65a8fdc..de409e7 100644 (file)
@@ -118,8 +118,7 @@ class GIFMetadataExtractor {
                                if ( strlen( $buf ) < 1 ) {
                                        throw new Exception( "Ran out of input" );
                                }
-                               $extension_code = unpack( 'C', $buf );
-                               $extension_code = $extension_code[1];
+                               $extension_code = unpack( 'C', $buf )[1];
 
                                if ( $extension_code == 0xF9 ) {
                                        // Graphics Control Extension.
@@ -131,8 +130,7 @@ class GIFMetadataExtractor {
                                        if ( strlen( $buf ) < 2 ) {
                                                throw new Exception( "Ran out of input" );
                                        }
-                                       $delay = unpack( 'v', $buf );
-                                       $delay = $delay[1];
+                                       $delay = unpack( 'v', $buf )[1];
                                        $duration += $delay * 0.01;
 
                                        fread( $fh, 1 ); // Transparent colour index
@@ -141,8 +139,7 @@ class GIFMetadataExtractor {
                                        if ( strlen( $term ) < 1 ) {
                                                throw new Exception( "Ran out of input" );
                                        }
-                                       $term = unpack( 'C', $term );
-                                       $term = $term[1];
+                                       $term = unpack( 'C', $term )[1];
                                        if ( $term != 0 ) {
                                                throw new Exception( "Malformed Graphics Control Extension block" );
                                        }
@@ -182,8 +179,7 @@ class GIFMetadataExtractor {
                                        if ( strlen( $blockLength ) < 1 ) {
                                                throw new Exception( "Ran out of input" );
                                        }
-                                       $blockLength = unpack( 'C', $blockLength );
-                                       $blockLength = $blockLength[1];
+                                       $blockLength = unpack( 'C', $blockLength )[1];
                                        $data = fread( $fh, $blockLength );
 
                                        if ( $blockLength != 11 ) {
@@ -206,8 +202,7 @@ class GIFMetadataExtractor {
                                                if ( strlen( $loopData ) < 2 ) {
                                                        throw new Exception( "Ran out of input" );
                                                }
-                                               $loopData = unpack( 'v', $loopData );
-                                               $loopCount = $loopData[1];
+                                               $loopCount = unpack( 'v', $loopData )[1];
 
                                                if ( $loopCount != 1 ) {
                                                        $isLooped = true;
@@ -245,8 +240,7 @@ class GIFMetadataExtractor {
                                if ( strlen( $buf ) < 1 ) {
                                        throw new Exception( "Ran out of input" );
                                }
-                               $byte = unpack( 'C', $buf );
-                               $byte = $byte[1];
+                               $byte = unpack( 'C', $buf )[1];
                                throw new Exception( "At position: " . ftell( $fh ) . ", Unknown byte " . $byte );
                        }
                }
@@ -283,8 +277,7 @@ class GIFMetadataExtractor {
                if ( strlen( $data ) < 1 ) {
                        throw new Exception( "Ran out of input" );
                }
-               $buf = unpack( 'C', $data );
-               $buf = $buf[1];
+               $buf = unpack( 'C', $data )[1];
                $bpp = ( $buf & 7 ) + 1;
                $buf >>= 7;
 
@@ -303,8 +296,7 @@ class GIFMetadataExtractor {
                        if ( strlen( $buf ) < 1 ) {
                                throw new Exception( "Ran out of input" );
                        }
-                       $block_len = unpack( 'C', $buf );
-                       $block_len = $block_len[1];
+                       $block_len = unpack( 'C', $buf )[1];
                        if ( $block_len == 0 ) {
                                return;
                        }
index 7d59767..f4f29dd 100644 (file)
@@ -105,8 +105,7 @@ class PNGMetadataExtractor {
                        if ( !$buf || strlen( $buf ) < 4 ) {
                                throw new Exception( __METHOD__ . ": Read error" );
                        }
-                       $chunk_size = unpack( "N", $buf );
-                       $chunk_size = $chunk_size[1];
+                       $chunk_size = unpack( "N", $buf )[1];
 
                        if ( $chunk_size < 0 ) {
                                throw new Exception( __METHOD__ . ": Chunk size too big for unpack" );
index 4252f85..f6b490a 100644 (file)
@@ -1252,8 +1252,7 @@ class Article implements Page {
                if ( $title->getNamespace() == NS_USER
                        || $title->getNamespace() == NS_USER_TALK
                ) {
-                       $parts = explode( '/', $title->getText() );
-                       $rootPart = $parts[0];
+                       $rootPart = explode( '/', $title->getText() )[0];
                        $user = User::newFromName( $rootPart, false /* allow IP users*/ );
                        $ip = User::isIP( $rootPart );
                        $block = Block::newFromTarget( $user, $user );
index 477d1f7..d65e8be 100644 (file)
@@ -3948,8 +3948,7 @@ class Parser {
         * @return string|bool
         */
        public function fetchTemplate( $title ) {
-               $rv = $this->fetchTemplateAndTitle( $title );
-               return $rv[0];
+               return $this->fetchTemplateAndTitle( $title )[0];
        }
 
        /**
@@ -4052,8 +4051,7 @@ class Parser {
         * @return File|bool
         */
        public function fetchFile( $title, $options = [] ) {
-               $res = $this->fetchFileAndTitle( $title, $options );
-               return $res[0];
+               return $this->fetchFileAndTitle( $title, $options )[0];
        }
 
        /**
index 8da39db..8ba49b6 100644 (file)
@@ -136,8 +136,7 @@ class SearchPostgres extends SearchDatabase {
                        # # TODO: Better output (example to catch: one 'two)
                        die( "Sorry, that was not a valid search string. Please go back and try again" );
                }
-               $top = $res->fetchRow();
-               $top = $top[0];
+               $top = $res->fetchRow()[0];
 
                $this->searchTerms = [];
                if ( $top === "" ) { # # e.g. if only stopwords are used XXX return something better
index 1328870..134c096 100644 (file)
@@ -99,9 +99,7 @@ class SkinTemplate extends Skin {
                $languageLinks = array();
 
                foreach ( $this->getOutput()->getLanguageLinks() as $languageLinkText ) {
-                       $languageLinkParts = explode( ':', $languageLinkText, 2 );
-                       $class = 'interlanguage-link interwiki-' . $languageLinkParts[0];
-                       unset( $languageLinkParts );
+                       $class = 'interlanguage-link interwiki-' . explode( ':', $languageLinkText, 2 )[0];
 
                        $languageLinkTitle = Title::newFromText( $languageLinkText );
                        if ( $languageLinkTitle ) {
index d66a86a..0d0d90d 100644 (file)
@@ -228,18 +228,14 @@ class ConverterRule {
                        }
                        // or display current variant in unidirectional array
                        if ( $disp === false && array_key_exists( $variant, $unidtable ) ) {
-                               $disp = array_values( $unidtable[$variant] );
-                               $disp = $disp[0];
+                               $disp = array_values( $unidtable[$variant] )[0];
                        }
                        // or display frist text under disable manual convert
                        if ( $disp === false && $this->mConverter->mManualLevel[$variant] == 'disable' ) {
                                if ( count( $bidtable ) > 0 ) {
-                                       $disp = array_values( $bidtable );
-                                       $disp = $disp[0];
+                                       $disp = array_values( $bidtable )[0];
                                } else {
-                                       $disp = array_values( $unidtable );
-                                       $disp = array_values( $disp[0] );
-                                       $disp = $disp[0];
+                                       $disp = array_values( array_values( $unidtable )[0] )[0];
                                }
                        }
                        return $disp;
@@ -267,8 +263,7 @@ class ConverterRule {
                                return $disp;
                        }
                        if ( array_key_exists( $variant, $this->mUnidtable ) ) {
-                               $disp = array_values( $this->mUnidtable[$variant] );
-                               $disp = $disp[0];
+                               $disp = array_values( $this->mUnidtable[$variant] )[0];
                        }
                        // Assigned above or still false.
                        return $disp;
index 5068777..0bd2276 100644 (file)
@@ -4303,8 +4303,7 @@ class Language {
                        return $this->mParentLanguage;
                }
 
-               $pieces = explode( '-', $this->getCode() );
-               $code = $pieces[0];
+               $code = explode( '-', $this->getCode() )[0];
                if ( !in_array( $code, LanguageConverter::$languagesWithVariants ) ) {
                        $this->mParentLanguage = null;
                        return null;
index 0be3784..81e78b5 100644 (file)
@@ -992,8 +992,8 @@ class LanguageConverter {
                                $first = false;
                                continue;
                        }
-                       $mappings = explode( '}-', $block, 2 );
-                       $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings[0] );
+                       $mappings = explode( '}-', $block, 2 )[0];
+                       $stripped = str_replace( [ "'", '"', '*', '#' ], '', $mappings );
                        $table = StringUtils::explode( ';', $stripped );
                        foreach ( $table as $t ) {
                                $m = explode( '=>', $t, 3 );
index e9c006e..f47e13c 100644 (file)
@@ -20,8 +20,7 @@ class TidyUpBug37714 extends Maintenance {
                );
 
                foreach ( $result as $row ) {
-                       $paramLines = explode( "\n", $row->log_params );
-                       $ids = explode( ',', $paramLines[0] ); // Array dereferencing is PHP >= 5.4 :(
+                       $ids = explode( ',', explode( "\n", $row->log_params )[0] );
                        $result = $this->getDB( DB_SLAVE )->select( // Work out what log entries were changed here.
                                'logging',
                                'log_type',
index 0299c26..76544a5 100644 (file)
@@ -661,8 +661,7 @@ class TestFileIterator implements Iterator {
                        ) );
                }
 
-               $tokens = array_values( $tokens );
-               return $tokens[0];
+               return array_values( $tokens )[0];
        }
 }