Completed
Push — master ( 4a5166...6912d9 )
by Matthew
03:30 queued 13s
created

LabsHelper::allProjects()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 0
1
<?php
2
3
namespace AppBundle\Helper;
4
5
use Symfony\Component\Config\Definition\Exception\Exception;
6
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
7
use Symfony\Component\DependencyInjection\ContainerInterface;
8
use Symfony\Component\VarDumper\VarDumper;
9
10
class LabsHelper
11
{
12
    /** @var string */
13
    protected $dbName;
14
15
    /** @var \Doctrine\DBAL\Connection */
16
    protected $client;
17
18
    /** @var ContainerInterface */
19
    protected $container;
20
21
    /** @var string */
22
    protected $url;
23
24
    public function __construct(ContainerInterface $container)
25
    {
26
        $this->container = $container;
27
    }
28
29
    public function checkEnabled($tool)
30
    {
31
        if (!$this->container->getParameter("enable.$tool")) {
32
            throw new NotFoundHttpException('This tool is disabled');
33
        }
34
    }
35
36
    /**
37
     * Is xTools connecting to WMF Labs?
38
     *
39
     * @return boolean
40
     */
41
    public function isLabs()
42
    {
43
        return (bool)$this->container->getParameter('app.is_labs');
44
    }
45
46
    /**
47
     * Get the record for the given project in the meta.wiki table
48
     * @param  string $project Valid project in the formats:
49
     *                         https://en.wikipedia.org, en.wikipedia, enwiki
50
     * @return array|false     Database record or false if no record was found.
51
     *                         Relevant values returned include the 'dbname' (enwiki),
52
     *                         'lang', 'name' (Wikipedia) and 'url' (https://en.wikipeda.org)
53
     */
54
    private function getProjectMetadata($project)
55
    {
56
        // First, run through our project map.  This is expected to return back
57
        // to the project name if there is no defined mapping.
58
        if ($this->container->hasParameter("app.project.$project")) {
59
            $project = $this->container->getParameter("app.project.$project");
60
        }
61
62
        // If this is a single-project setup, manually construct the metadata.
63
        if ($this->container->getParameter("app.single_wiki")) {
64
            return [
65
                'dbname' => $this->container->getParameter('database_replica_name'),
66
                'url' => $this->container->getParameter('wiki_url'),
67
                'lang' => $this->container->getParameter('lang'),
68
                'name' => 'Xtools', // Not used?
69
            ];
70
        }
71
72
        // Grab the connection to the meta database
73
        $this->client = $this->container
74
            ->get('doctrine')
75
            ->getManager('meta')
76
            ->getConnection();
77
78
        // Create the query we're going to run against the meta database
79
        $wikiQuery = $this->client->createQueryBuilder();
80
        $wikiQuery
81
            ->select([ 'dbname', 'name', 'url', 'lang' ])
82
            ->from('wiki')
83
            ->where($wikiQuery->expr()->eq('dbname', ':project'))
84
            // The meta database will have the project's URL stored as https://en.wikipedia.org
85
            // so we need to query for it accordingly, trying different variations the user
86
            // might have inputted.
87
            ->orwhere($wikiQuery->expr()->like('url', ':projectUrl'))
88
            ->orwhere($wikiQuery->expr()->like('url', ':projectUrl2'))
89
            ->setParameter('project', $project)
90
            ->setParameter('projectUrl', "https://$project")
91
            ->setParameter('projectUrl2', "https://$project.org");
92
        $wikiStatement = $wikiQuery->execute();
93
94
        // Fetch the wiki data
95
        $wikis = $wikiStatement->fetchAll();
96
97
        // Return false if we can't find the wiki
98
        if (count($wikis) < 1) {
99
            return false;
100
        }
101
102
        // Otherwise, return the first result (in the rare event there are more than one).
103
        return $wikis[0];
104
    }
105
106
    /**
107
     * Returns a project's domain (en.wikipedia) given various formats
108
     * @param  string $project Valid project in the formats:
109
     *                         https://en.wikipedia.org, en.wikipedia, enwiki
110
     * @return string|false    lang.project.org ('url' value for that wiki)
111
     *                         or false if project was not found
112
     */
113
    public function normalizeProject($project)
114
    {
115
        $project = preg_replace("/^https?:\/\//", '', $project);
116
        $metaData = $this->getProjectMetadata($project);
117
118
        if ($metaData) {
119
            // Get domain from the first result (in the rare event there are more than one).
120
            return preg_replace("/^https?:\/\//", '', $metaData['url']);
121
        } else {
122
            return false;
123
        }
124
    }
125
126
    /**
127
     * Get a list of all projects.
128
     */
129
    public function allProjects()
130
    {
131
        $wikiQuery = $this->client->createQueryBuilder();
132
        $wikiQuery->select([ 'dbName', 'name', 'url' ])->from('wiki');
133
        $stmt = $wikiQuery->execute();
134
        $out = $stmt->fetchAll();
135
        return $out;
136
    }
137
138
    /**
139
     * All mapping tables to environment-specific names, as specified in config/table_map.yml
140
     * Used for example to convert revision -> revision_replica
141
     * https://wikitech.wikimedia.org/wiki/Help:Tool_Labs/Database#Tables_for_revision_or_logging_queries_involving_user_names_and_IDs
142
     *
143
     * @param string $table  Table name
144
     * @param string $dbName Database name
145
     * @param string|null $table_extension Optional table extension, which will only get used if we're on labs.
146
     *
147
     * @return string Converted table name
148
     */
149
    public function getTable($table, $dbName = null, $table_extension = null)
150
    {
151
        // This is a workaround for a one-to-many mapping
152
        // as required by Labs.  We combine $table with
153
        // $table_extension in order to generate the new table name
154
        if ($this->isLabs() && $table_extension !== null) {
155
            $table = $table . "_" . $table_extension;
156
        }
157
158
        // Use the table specified in the table mapping configuration, if present.
159
        $mapped = false;
0 ignored issues
show
Unused Code introduced by
$mapped is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
160 View Code Duplication
        if ($this->container->hasParameter("app.table.$table")) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
161
            $mapped = true;
0 ignored issues
show
Unused Code introduced by
$mapped is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
162
            $table = $this->container->getParameter("app.table.$table");
163
        }
164
165
        // Figure out database name.
166
        // Use class variable for the database name if not set via function parameter.
167
        $dbNameActual = $dbName ? $dbName : $this->dbName;
168
        if ($this->isLabs() && substr($dbNameActual, -2) != '_p') {
169
            // Append '_p' if this is labs.
170
            $dbNameActual .= '_p';
171
        }
172
173
        return $dbNameActual ? "$dbNameActual.$table" : $table;
174
    }
175
176
    // TODO: figure out how to use Doctrine to query host 'tools-db'
177
}
178