Completed
Push — master ( a9dd44...63d5c2 )
by Sébastien
05:04
created

JSONRenderer   B

Complexity

Total Complexity 41

Size/Duplication

Total Lines 244
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 69.85%

Importance

Changes 3
Bugs 1 Features 3
Metric Value
dl 0
loc 244
ccs 139
cts 199
cp 0.6985
rs 8.2769
c 3
b 1
f 3
wmc 41
lcom 1
cbo 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
B getBookContentArray() 0 52 6
C getFullBookContentArray() 0 34 8
A getContentArray() 0 8 2
A getContentArrayTypeahead() 0 15 4
B addCompleteArray() 0 46 4
F getJson() 0 73 17

How to fix   Complexity   

Complex Class

Complex classes like JSONRenderer often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use JSONRenderer, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * COPS (Calibre OPDS PHP Server) class file
4
 *
5
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6
 * @author     Sébastien Lucas <[email protected]>
7
 */
8
9
require_once ("base.php");
10
require_once ("book.php");
11
12
class JSONRenderer
13
{
14
    /**
15
     * @param Book $book
16
     * @return array
17
     */
18 4
    public static function getBookContentArray ($book) {
19 4
        global $config;
20 4
        $i = 0;
21 4
        $preferedData = array ();
22 4
        foreach ($config['cops_prefered_format'] as $format)
23
        {
24 4
            if ($i == 2) { break; }
25 4
            if ($data = $book->getDataFormat ($format)) {
26 4
                $i++;
27 4
                array_push ($preferedData, array ("url" => $data->getHtmlLink (), "name" => $format));
28 4
            }
29 4
        }
30
31 4
        $publisher = $book->getPublisher();
32 4
        if (is_null ($publisher)) {
33
            $pn = "";
34
            $pu = "";
35
        } else {
36 4
            $pn = $publisher->name;
37 4
            $link = new LinkNavigation ($publisher->getUri ());
38 4
            $pu = $link->hrefXhtml ();
39
        }
40
41 4
        $serie = $book->getSerie ();
42 4
        if (is_null ($serie)) {
43 2
            $sn = "";
44 2
            $scn = "";
45 2
            $su = "";
46 2
        } else {
47 2
            $sn = $serie->name;
48 2
            $scn = str_format (localize ("content.series.data"), $book->seriesIndex, $serie->name);
49 2
            $link = new LinkNavigation ($serie->getUri ());
50 2
            $su = $link->hrefXhtml ();
51
        }
52 4
        $cc = $book->getCustomColumnValues($config['cops_calibre_custom_column_list']);
53
54 4
        return array ("id" => $book->id,
55 4
                      "hasCover" => $book->hasCover,
56 4
                      "preferedData" => $preferedData,
57 4
                      "rating" => $book->getRating (),
58 4
                      "publisherName" => $pn,
59 4
                      "publisherurl" => $pu,
60 4
                      "pubDate" => $book->getPubDate (),
61 4
                      "languagesName" => $book->getLanguages (),
62 4
                      "authorsName" => $book->getAuthorsName (),
63 4
                      "tagsName" => $book->getTagsName (),
64 4
                      "seriesName" => $sn,
65 4
                      "seriesIndex" => $book->seriesIndex,
66 4
                      "seriesCompleteName" => $scn,
67 4
                      "seriesurl" => $su,
68 4
                      "customcolumns_list" => $cc);
69
    }
70
71
    /**
72
     * @param Book $book
73
     * @return array
74
     */
75 1
    public static function getFullBookContentArray ($book) {
76 1
        global $config;
77 1
        $out = self::getBookContentArray ($book);
78 1
        $database = GetUrlParam (DB);
79
80 1
        $out ["coverurl"] = Data::getLink ($book, "jpg", "image/jpeg", Link::OPDS_IMAGE_TYPE, "cover.jpg", NULL)->hrefXhtml ();
81 1
        $out ["thumbnailurl"] = Data::getLink ($book, "jpg", "image/jpeg", Link::OPDS_THUMBNAIL_TYPE, "cover.jpg", NULL, NULL, $config['cops_html_thumbnail_height'] * 2)->hrefXhtml ();
82 1
        $out ["content"] = $book->getComment (false);
83 1
        $out ["datas"] = array ();
84 1
        $dataKindle = $book->GetMostInterestingDataToSendToKindle ();
85 1
        foreach ($book->getDatas() as $data) {
86 1
            $tab = array ("id" => $data->id, "format" => $data->format, "url" => $data->getHtmlLink (), "mail" => 0, "readerUrl" => "");
87 1
            if (!empty ($config['cops_mail_configuration']) && !is_null ($dataKindle) && $data->id == $dataKindle->id) {
88 1
                $tab ["mail"] = 1;
89 1
            }
90 1
            if ($data->format == "EPUB") {
91 1
                $tab ["readerUrl"] = "epubreader.php?data={$data->id}&db={$database}";
92 1
            }
93 1
            array_push ($out ["datas"], $tab);
94 1
        }
95 1
        $out ["authors"] = array ();
96 1
        foreach ($book->getAuthors () as $author) {
97 1
            $link = new LinkNavigation ($author->getUri ());
98 1
            array_push ($out ["authors"], array ("name" => $author->name, "url" => $link->hrefXhtml ()));
99 1
        }
100 1
        $out ["tags"] = array ();
101 1
        foreach ($book->getTags () as $tag) {
102 1
            $link = new LinkNavigation ($tag->getUri ());
103 1
            array_push ($out ["tags"], array ("name" => $tag->name, "url" => $link->hrefXhtml ()));
104 1
        }
105 1
        $out ["customcolumns_preview"] = $book->getCustomColumnValues($config['cops_calibre_custom_column_preview']);
106
107 1
        return $out;
108
    }
109
110
    public static function getContentArray ($entry) {
111
        if ($entry instanceof EntryBook) {
112
            $out = array ( "title" => $entry->title);
113
            $out ["book"] = self::getBookContentArray ($entry->book);
114
            return $out;
115
        }
116
        return array ( "title" => $entry->title, "content" => $entry->content, "navlink" => $entry->getNavLink (), "number" => $entry->numberOfElement );
117
    }
118
119 7
    public static function getContentArrayTypeahead ($page) {
120 7
        $out = array ();
121 7
        foreach ($page->entryArray as $entry) {
122 7
            if ($entry instanceof EntryBook) {
123 2
                array_push ($out, array ("class" => $entry->className, "title" => $entry->title, "navlink" => $entry->book->getDetailUrl ()));
124 2
            } else {
125 7
                if (empty ($entry->className) xor Base::noDatabaseSelected ()) {
126 6
                    array_push ($out, array ("class" => $entry->className, "title" => $entry->title, "navlink" => $entry->getNavLink ()));
127 6
                } else {
128 7
                    array_push ($out, array ("class" => $entry->className, "title" => $entry->content, "navlink" => $entry->getNavLink ()));
129
                }
130
            }
131 7
        }
132 7
        return $out;
133
    }
134
135 1
    public static function addCompleteArray ($in) {
136 1
        global $config;
137 1
        $out = $in;
138
139 1
        $out ["c"] = array ("version" => VERSION, "i18n" => array (
140 1
                           "coverAlt" => localize("i18n.coversection"),
141 1
                           "authorsTitle" => localize("authors.title"),
142 1
                           "bookwordTitle" => localize("bookword.title"),
143 1
                           "tagsTitle" => localize("tags.title"),
144 1
                           "seriesTitle" => localize("series.title"),
145 1
                           "customizeTitle" => localize ("customize.title"),
146 1
                           "aboutTitle" => localize ("about.title"),
147 1
                           "previousAlt" => localize ("paging.previous.alternate"),
148 1
                           "nextAlt" => localize ("paging.next.alternate"),
149 1
                           "searchAlt" => localize ("search.alternate"),
150 1
                           "sortAlt" => localize ("sort.alternate"),
151 1
                           "homeAlt" => localize ("home.alternate"),
152 1
                           "cogAlt" => localize ("cog.alternate"),
153 1
                           "permalinkAlt" => localize ("permalink.alternate"),
154 1
                           "publisherName" => localize("publisher.name"),
155 1
                           "pubdateTitle" => localize("pubdate.title"),
156 1
                           "languagesTitle" => localize("language.title"),
157 1
                           "contentTitle" => localize("content.summary"),
158 1
                           "sortorderAsc" => localize("search.sortorder.asc"),
159 1
                           "sortorderDesc" => localize("search.sortorder.desc"),
160 1
                           "customizeEmail" => localize("customize.email")),
161
                       "url" => array (
162 1
                           "detailUrl" => "index.php?page=13&id={0}&db={1}",
163 1
                           "coverUrl" => "fetch.php?id={0}&db={1}",
164 1
                           "thumbnailUrl" => "fetch.php?height=" . $config['cops_html_thumbnail_height'] . "&id={0}&db={1}"),
165
                       "config" => array (
166 1
                           "use_fancyapps" => $config ["cops_use_fancyapps"],
167 1
                           "max_item_per_page" => $config['cops_max_item_per_page'],
168 1
                           "kindleHack"        => "",
169 1
                           "server_side_rendering" => useServerSideRendering (),
170 1
                           "html_tag_filter" => $config['cops_html_tag_filter']));
171 1
        if ($config['cops_thumbnail_handling'] == "1") {
172 1
            $out ["c"]["url"]["thumbnailUrl"] = $out ["c"]["url"]["coverUrl"];
173 1
        } else if (!empty ($config['cops_thumbnail_handling'])) {
174 1
            $out ["c"]["url"]["thumbnailUrl"] = $config['cops_thumbnail_handling'];
175 1
        }
176 1
        if (preg_match("/./", $_SERVER['HTTP_USER_AGENT'])) {
177 1
          $out ["c"]["config"]["kindleHack"] = 'style="text-decoration: none !important;"';
178 1
        }
179 1
        return $out;
180
    }
181
182 7
    public static function getJson ($complete = false) {
183 7
        global $config;
184 7
        $page = getURLParam ("page", Base::PAGE_INDEX);
185 7
        $query = getURLParam ("query");
186 7
        $search = getURLParam ("search");
187 7
        $qid = getURLParam ("id");
188 7
        $n = getURLParam ("n", "1");
189 7
        $database = GetUrlParam (DB);
190
191 7
        $currentPage = Page::getPage ($page, $qid, $query, $n);
192 7
        $currentPage->InitializeContent ();
193
194 7
        if ($search) {
195 7
            return self::getContentArrayTypeahead ($currentPage);
196
        }
197
198
        $out = array ( "title" => $currentPage->title);
199
        $entries = array ();
200
        foreach ($currentPage->entryArray as $entry) {
201
            array_push ($entries, self::getContentArray ($entry));
202
        }
203
        if (!is_null ($currentPage->book)) {
204
            $out ["book"] = self::getFullBookContentArray ($currentPage->book);
205
        }
206
        $out ["databaseId"] = GetUrlParam (DB, "");
207
        $out ["databaseName"] = Base::getDbName ();
208
        if ($out ["databaseId"] == "") {
209
            $out ["databaseName"] = "";
210
        }
211
        $out ["fullTitle"] = $out ["title"];
212
        if ($out ["databaseId"] != "" && $out ["databaseName"] != $out ["fullTitle"]) {
213
            $out ["fullTitle"] = $out ["databaseName"] . " > " . $out ["fullTitle"];
214
        }
215
        $out ["page"] = $page;
216
        $out ["multipleDatabase"] = Base::isMultipleDatabaseEnabled () ? 1 : 0;
217
        $out ["entries"] = $entries;
218
        $out ["isPaginated"] = 0;
219
        if ($currentPage->isPaginated ()) {
220
            $prevLink = $currentPage->getPrevLink ();
221
            $nextLink = $currentPage->getNextLink ();
222
            $out ["isPaginated"] = 1;
223
            $out ["prevLink"] = "";
224
            if (!is_null ($prevLink)) {
225
                $out ["prevLink"] = $prevLink->hrefXhtml ();
226
            }
227
            $out ["nextLink"] = "";
228
            if (!is_null ($nextLink)) {
229
                $out ["nextLink"] = $nextLink->hrefXhtml ();
230
            }
231
            $out ["maxPage"] = $currentPage->getMaxPage ();
232
            $out ["currentPage"] = $currentPage->n;
233
        }
234
        if (!is_null (getURLParam ("complete")) || $complete) {
235
            $out = self::addCompleteArray ($out);
236
       }
237
238
        $out ["containsBook"] = 0;
239
        if ($currentPage->containsBook ()) {
240
            $out ["containsBook"] = 1;
241
        }
242
243
        $out["abouturl"] = "index.php" . addURLParameter ("?page=" . Base::PAGE_ABOUT, DB, $database);
244
245
        if ($page == Base::PAGE_ABOUT) {
246
            $temp = preg_replace ("/\<h1\>About COPS\<\/h1\>/", "<h1>About COPS " . VERSION . "</h1>", file_get_contents('about.html'));
247
            $out ["fullhtml"] = $temp;
248
        }
249
250
        $out ["homeurl"] = "index.php";
251
        if ($page != Base::PAGE_INDEX && !is_null ($database)) $out ["homeurl"] = $out ["homeurl"] .  "?" . addURLParameter ("", DB, $database);
252
253
        return $out;
254
    }
255
}