Completed
Push — master ( c2c212...38c104 )
by Sam
03:48
created

LabsHelper::checkEnabled()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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