Test Setup Failed
Push — master ( 73b0fc...7f61e4 )
by Sugeng
02:53
created

PdfJs::getPdfJsModule()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 11
rs 10
cc 4
nc 5
nop 0
1
<?php
2
3
namespace diecoding\pdfjs;
4
5
use Yii;
6
use yii\base\InvalidConfigException;
7
use yii\base\Widget;
8
use yii\helpers\ArrayHelper;
9
use yii\helpers\Html;
10
11
/**
12
 * PdfJs is the class for widgets.
13
 * 
14
 * @link [sugeng-sulistiyawan.github.io](sugeng-sulistiyawan.github.io)
15
 * @author Sugeng Sulistiyawan <[email protected]>
16
 * @copyright Copyright (c) 2023
17
 */
18
class PdfJs extends Widget
19
{
20
	/**
21
	 * @var string
22
	 */
23
	public $url;
24
25
	/**
26
	 * @var string
27
	 */
28
	public $title;
29
30
	/**
31
	 * @var array
32
	 */
33
	public $options = [];
34
35
	/**
36
	 * Show or hide section container
37
	 * Example:
38
	 * 
39
	 * ```php
40
	 * 'sections' => [
41
	 * 	 'presentationMode' => true,
42
	 * 	 'print' => true,
43
	 * 	 'download' => true,
44
	 * 	 'secondaryToolbarToggle' => true,
45
	 * ],
46
	 * ```
47
	 * 
48
	 * This equivalent to:
49
	 * ```$('#{$sectionId}').remove();```;
50
	 * 
51
	 * @var array
52
	 */
53
	public $sections = [];
54
55
	/**
56
	 * @return Module
57
	 * @throws InvalidConfigException
58
	 */
59
	protected function getPdfJsModule()
60
	{
61
		$moduleClass = Module::class;
62
		foreach (Yii::$app->getModules(false) as $id => $module) {
63
			$class = is_array($module) ? $module['class'] : $module::class;
64
			if ($class === $moduleClass) {
65
				return Yii::$app->getModule($id);
66
			}
67
		}
68
69
		throw new InvalidConfigException('PDFJs module must be an application module.');
70
	}
71
72
	/**
73
	 * @inheritdoc
74
	 */
75
	public function run()
76
	{
77
		$module = $this->getPdfJsModule();
78
		$defaultOptions = $module->defaultOptions;
79
		$defaultSections = $module->defaultSections;
80
81
		$defaultOptions = ArrayHelper::merge($defaultOptions, [
82
			'style' => [
83
				'width' => '100%',
84
				'height' => '480px',
85
				'background-color' => 'rgba(212, 212, 215, 1)',
86
				'border' => 'none',
87
			],
88
		]);
89
90
		if (isset($this->options['style'])) {
91
			$style = $this->options['style'];
92
			unset($this->options['style']);
93
94
			Html::addCssStyle($defaultOptions, $style);
95
		}
96
		$this->options = ArrayHelper::merge($defaultOptions, $this->options);
97
		$this->sections = ArrayHelper::merge($defaultSections, $this->sections);
98
99
		return $this->render('viewer', [
100
			'url' => $this->url,
101
			'title' => $this->title,
102
			'widgetId' => $this->getId(),
103
			'module' => $this->getPdfJsModule(),
104
			'options' => $this->options,
105
			'sections' => $this->sections,
106
		]);
107
	}
108
}
109