diff --git a/src/Cli/CommandRegistry.php b/src/Cli/CommandRegistry.php index 9a200c89..b9c57101 100644 --- a/src/Cli/CommandRegistry.php +++ b/src/Cli/CommandRegistry.php @@ -39,7 +39,7 @@ class CommandRegistry { public function dispatch(array $rArgv): int { $rCommandName = $rArgv[1] ?? null; - if ($rCommandName === null || $rCommandName === '--help' || $rCommandName === '-h') { + if (in_array($rCommandName, [null, '--help', '-h'], true)) { $this->printHelp(); return 0; } diff --git a/src/Cli/Commands/CreatedCommand.php b/src/Cli/Commands/CreatedCommand.php index 71d0387b..3b01874d 100644 --- a/src/Cli/Commands/CreatedCommand.php +++ b/src/Cli/Commands/CreatedCommand.php @@ -75,7 +75,7 @@ class CreatedCommand implements CommandInterface { $rSourcesLeft = array_diff($rStreamInfo['stream_source'], $rServerInfo['cchannel_rsources']); - if (empty($rSourcesLeft) && $rStreamInfo['stream_source'] === $rServerInfo['cchannel_rsources']) { + if ($rSourcesLeft === [] && $rStreamInfo['stream_source'] === $rServerInfo['cchannel_rsources']) { echo 'Nothing to build - all sources are already encoded.' . "\n"; @unlink(CREATED_PATH . $rStreamID . '_.create'); return 0; diff --git a/src/Cli/Commands/DelayCommand.php b/src/Cli/Commands/DelayCommand.php index 56ae8b08..c1b2ce4a 100644 --- a/src/Cli/Commands/DelayCommand.php +++ b/src/Cli/Commands/DelayCommand.php @@ -148,7 +148,6 @@ class DelayCommand implements CommandInterface { * @param array $rSegments Published segments, oldest first ({seconds, file}). * @param int|null $rFedSegment Highest segment number queued so far. * @param array $rQueue Pending {data, dur, burst} entries. - * @return void */ private function queueForDaemon(array $rSegments, ?int &$rFedSegment, array &$rQueue): void { $rNew = []; @@ -189,7 +188,6 @@ class DelayCommand implements CommandInterface { * @param IngestFeeder $rFeeder The daemon feed. * @param array $rQueue Pending {data, dur, burst} entries. * @param array|null $rCurrent The segment being paced ({data, sent, start, dur, burst}). - * @return void */ private function pumpDaemon(IngestFeeder $rFeeder, array &$rQueue, ?array &$rCurrent): void { $rNow = microtime(true); @@ -249,7 +247,7 @@ class DelayCommand implements CommandInterface { $this->updateOldPlaylist($rOldSegments, $rPlaylistOld); } if (file_exists($rPlaylistDelay)) { - $rSegments = array_merge($rSegments, $this->getSegments($rPlaylistDelay, $rTotalSegments - count($rSegments))); + return array_merge($rSegments, $this->getSegments($rPlaylistDelay, $rTotalSegments - count($rSegments))); } return $rSegments; } diff --git a/src/Cli/Commands/LlodCommand.php b/src/Cli/Commands/LlodCommand.php index 5d6bd689..90c4096c 100644 --- a/src/Cli/Commands/LlodCommand.php +++ b/src/Cli/Commands/LlodCommand.php @@ -475,7 +475,7 @@ class LlodCommand implements CommandInterface { // (after trimming) falls back to the argument's default. $rValue = trim((string) ($rStreamArguments[$rKey]['value'] ?? '')); if ($rValue === '') { - $rValue = trim((string) ($rStreamArguments[$rKey]['argument_default_value'] ?? '')); + return trim((string) ($rStreamArguments[$rKey]['argument_default_value'] ?? '')); } return $rValue; }; @@ -518,7 +518,6 @@ class LlodCommand implements CommandInterface { * * @param resource $rFP Source stream. * @param string $rSniffed Receives the bytes read (they are part of the stream). - * @return bool */ private function looksLikeMpegTs($rFP, string &$rSniffed): bool { $rSniffed = ''; @@ -606,11 +605,9 @@ class LlodCommand implements CommandInterface { } else { $rError = null; - if (!empty($http_response_header)) { - foreach ($http_response_header as $rKey => $rHeader) { - if (preg_match('#HTTP/[0-9\\.]+\\s+([0-9]+)#', $rHeader, $rOutput)) { - $rError = $rHeader; - } + foreach ($http_response_header as $rHeader) { + if (preg_match('#HTTP/[0-9\\.]+\\s+([0-9]+)#', $rHeader, $rOutput)) { + $rError = $rHeader; } } diff --git a/src/Cli/Commands/LoopbackCommand.php b/src/Cli/Commands/LoopbackCommand.php index 893e3474..d167a4e4 100644 --- a/src/Cli/Commands/LoopbackCommand.php +++ b/src/Cli/Commands/LoopbackCommand.php @@ -381,7 +381,7 @@ class LoopbackCommand implements CommandInterface { } } if ($rKeep < count($rReturn)) { - $rReturn = array_slice($rReturn, count($rReturn) - $rKeep, $rKeep); + return array_slice($rReturn, count($rReturn) - $rKeep, $rKeep); } return $rReturn; } diff --git a/src/Cli/Commands/MonitorCommand.php b/src/Cli/Commands/MonitorCommand.php index 2413420a..367d2b4b 100644 --- a/src/Cli/Commands/MonitorCommand.php +++ b/src/Cli/Commands/MonitorCommand.php @@ -117,7 +117,7 @@ class MonitorCommand implements CommandInterface { $db->query('SELECT t1.*, t2.* FROM `streams_options` t1, `streams_arguments` t2 WHERE t1.stream_id = ? AND t1.argument_id = t2.id', $rStreamID); $rStreamArguments = $db->get_rows(); - if (!(0 < $rStreamInfo['delay_minutes']) && ($rStreamInfo['parent_id'] == 0)) { + if (0 >= $rStreamInfo['delay_minutes'] && ($rStreamInfo['parent_id'] == 0)) { $rDelay = false; $rFolder = STREAMS_PATH; } else { @@ -167,7 +167,7 @@ class MonitorCommand implements CommandInterface { $rStreamFailed = ProcessManager::isStreamRunning($rPID, $rStreamID) && file_exists($rPlaylist); $rBaselineFps = null; while (ProcessManager::isStreamRunning($rPID, $rStreamID) && file_exists($rPlaylist)) { - if (self::isAutoRestartDue($rAutoRestart)) { + if ($this->isAutoRestartDue($rAutoRestart)) { echo "Auto-restart\n"; StreamProcess::streamLog($rStreamID, SERVER_ID, 'AUTO_RESTART', $rCurrentSource); $rStreamFailed = false; @@ -183,7 +183,7 @@ class MonitorCommand implements CommandInterface { } $rLastSegment = $rSegment; $rProbe = FFprobeRunner::probeStream($rFolder . $rSegment); - list($rProbe, $rSegmentTime) = self::persistSegmentDuration($rProbe, $rStreamID, $rSegmentTime); + list($rProbe, $rSegmentTime) = $this->persistSegmentDuration($rProbe, $rStreamID, $rSegmentTime); file_put_contents(STREAMS_PATH . $rStreamID . '_.stream_info', json_encode($rProbe, JSON_UNESCAPED_UNICODE)); $rStreamInfo['stream_info'] = json_encode($rProbe, JSON_UNESCAPED_UNICODE); } @@ -207,7 +207,7 @@ class MonitorCommand implements CommandInterface { $rProbe = FFprobeRunner::probeStream($rFolder . $rSegment); if (isset($rProbe['codecs']['video']['avg_frame_rate']) || isset($rProbe['codecs']['video']['r_frame_rate'])) { $rFps = $rProbe['codecs']['video']['avg_frame_rate'] ?: $rProbe['codecs']['video']['r_frame_rate']; - $rFps = self::parseFrameRate($rFps); + $rFps = $this->parseFrameRate($rFps); if (0 < $rFps) { $rBaselineFps = $rFps; } @@ -452,7 +452,7 @@ class MonitorCommand implements CommandInterface { $rBitrate = 0; if (file_exists($rSegment)) { $rProbe = FFprobeRunner::probeStream($rSegment); - list($rProbe, $rSegmentTime) = self::persistSegmentDuration($rProbe, $rStreamID, $rSegmentTime); + list($rProbe, $rSegmentTime) = $this->persistSegmentDuration($rProbe, $rStreamID, $rSegmentTime); if ($rProbe) { $rStreamInfo['stream_info'] = json_encode($rProbe, JSON_UNESCAPED_UNICODE); $rBitrate = StreamUtils::getStreamBitrate('live', STREAMS_PATH . $rStreamID . '_.m3u8'); @@ -462,7 +462,7 @@ class MonitorCommand implements CommandInterface { } // Defining video/Audio parameters - list($rCompatible, $rAudioCodec, $rVideoCodec, $rResolution) = self::resolveStreamCodecMeta($rStreamInfo['stream_info'], SettingsManager::get('player_allow_hevc')); + list($rCompatible, $rAudioCodec, $rVideoCodec, $rResolution) = $this->resolveStreamCodecMeta($rStreamInfo['stream_info'], SettingsManager::get('player_allow_hevc')); if (!$rSegmentSeen && $rStreamInfo['stream_info'] && $rStreamInfo['on_demand']) { $db->query('UPDATE `streams_servers` SET `stream_info` = ?, `compatible` = ?, `audio_codec` = ?, `video_codec` = ?, `resolution` = ?, `bitrate` = ?, `stream_status` = 0, `stream_started` = ? WHERE `server_stream_id` = ?', $rStreamInfo['stream_info'], $rCompatible, $rAudioCodec, $rVideoCodec, $rResolution, intval($rBitrate), time() - $rOffset, $rStreamInfo['server_stream_id']); @@ -509,7 +509,6 @@ class MonitorCommand implements CommandInterface { * @param float $rFps Current frames per second. * @param float $rBaseline Baseline frames per second. * @param mixed $rThreshold fps_threshold percentage (1..100), or empty. - * @return bool */ public static function isFpsBelowThreshold(float $rFps, float $rBaseline, mixed $rThreshold): bool { $rPercent = min(100, max(1, intval($rThreshold) ?: 90)); @@ -523,7 +522,6 @@ class MonitorCommand implements CommandInterface { * * @param array $rSources Ordered source list (primary first). * @param mixed $rCurrentSource The source in use. - * @return array */ public static function higherPrioritySources(array $rSources, mixed $rCurrentSource): array { $rKey = array_search($rCurrentSource, $rSources); @@ -540,11 +538,11 @@ class MonitorCommand implements CommandInterface { * @param mixed $rRate Raw avg_frame_rate / r_frame_rate value. * @return float Frames per second; 0.0 for empty/zero/malformed input. */ - private static function parseFrameRate(mixed $rRate): float { + private function parseFrameRate(mixed $rRate): float { $rRate = (string) $rRate; if (strpos($rRate, '/') !== false) { list($rNum, $rDen) = array_map('floatval', explode('/', $rRate)); - return $rDen != 0.0 ? (float) ($rNum / $rDen) : 0.0; + return $rDen != 0.0 ? $rNum / $rDen : 0.0; } return (float) $rRate; } @@ -555,9 +553,8 @@ class MonitorCommand implements CommandInterface { * * @param mixed $rAutoRestart Decoded auto_restart config (['days'=>[...],'at'=>'HH:MM']). * @param int|null $rNow Timestamp to test against (defaults to now). - * @return bool */ - private static function isAutoRestartDue(mixed $rAutoRestart, ?int $rNow = null): bool { + private function isAutoRestartDue(mixed $rAutoRestart, ?int $rNow = null): bool { if (empty($rAutoRestart['days']) || empty($rAutoRestart['at'])) { return false; } @@ -577,7 +574,7 @@ class MonitorCommand implements CommandInterface { * @param mixed $rAllowHevc player_allow_hevc setting. * @return array{0:int,1:?string,2:?string,3:mixed} [compatible, audio, video, resolution] */ - private static function resolveStreamCodecMeta(mixed $rStreamInfoJson, mixed $rAllowHevc): array { + private function resolveStreamCodecMeta(mixed $rStreamInfoJson, mixed $rAllowHevc): array { $rCompatible = 0; $rAudioCodec = $rVideoCodec = $rResolution = null; if ($rStreamInfoJson) { @@ -605,7 +602,7 @@ class MonitorCommand implements CommandInterface { * @param mixed $rSegmentTime Current segment time. * @return array{0:mixed,1:mixed} [clamped probe, updated segment time] */ - private static function persistSegmentDuration(mixed $rProbe, mixed $rStreamID, mixed $rSegmentTime): array { + private function persistSegmentDuration(mixed $rProbe, mixed $rStreamID, mixed $rSegmentTime): array { if (10 < intval($rProbe['of_duration'])) { $rProbe['of_duration'] = 10; } diff --git a/src/Cli/Commands/OndemandCommand.php b/src/Cli/Commands/OndemandCommand.php index 715d3033..ff74b53a 100644 --- a/src/Cli/Commands/OndemandCommand.php +++ b/src/Cli/Commands/OndemandCommand.php @@ -81,7 +81,7 @@ class OndemandCommand implements CommandInterface { } $rStreamIDs = ConnectionTracker::activeOnDemandStreamIDs(SERVER_ID); - if (empty($rStreamIDs)) { + if ($rStreamIDs === []) { usleep(800000); continue; } diff --git a/src/Cli/CronJobs/CacheEngineCronJob.php b/src/Cli/CronJobs/CacheEngineCronJob.php index fde4f2ba..afb2addd 100644 --- a/src/Cli/CronJobs/CacheEngineCronJob.php +++ b/src/Cli/CronJobs/CacheEngineCronJob.php @@ -220,7 +220,7 @@ class CacheEngineCronJob implements CommandInterface { $cacheValidityCheck[] = $rStart; } } - if (!$cacheValidityCheck) { + if ($cacheValidityCheck === []) { $cacheValidityCheck = [0]; } foreach ($cacheValidityCheck as $rStart) { @@ -260,7 +260,7 @@ class CacheEngineCronJob implements CommandInterface { $cacheCleanupTrigger[] = $rStart; } } - if (!$cacheCleanupTrigger) { + if ($cacheCleanupTrigger === []) { $cacheCleanupTrigger = [0]; } foreach ($cacheCleanupTrigger as $rStart) { diff --git a/src/Cli/CronJobs/CleanupCronJob.php b/src/Cli/CronJobs/CleanupCronJob.php index 121d2802..40a2b551 100644 --- a/src/Cli/CronJobs/CleanupCronJob.php +++ b/src/Cli/CronJobs/CleanupCronJob.php @@ -128,22 +128,22 @@ class CleanupCronJob implements CommandInterface { if (!is_array($rMovieProperties)) { $rMovieProperties = []; } - if (!(isset($rMovieProperties['duration_secs']) && $rSeconds == $rMovieProperties['duration_secs'])) { + if (!isset($rMovieProperties['duration_secs']) || $rSeconds != $rMovieProperties['duration_secs']) { $rMovieProperties['duration_secs'] = $rSeconds; $rMovieProperties['duration'] = $rDuration; } - if (!(isset($rMovieProperties['video']) && $rFFProbee['codecs']['video']['codec_name'] == $rMovieProperties['video'])) { + if (!isset($rMovieProperties['video']) || $rFFProbee['codecs']['video']['codec_name'] != $rMovieProperties['video']) { $rMovieProperties['video'] = $rFFProbee['codecs']['video']; } - if (!(isset($rMovieProperties['audio']) && $rFFProbee['codecs']['audio']['codec_name'] == $rMovieProperties['audio'])) { + if (!isset($rMovieProperties['audio']) || $rFFProbee['codecs']['audio']['codec_name'] != $rMovieProperties['audio']) { $rMovieProperties['audio'] = $rFFProbee['codecs']['audio']; } if (SettingsManager::get('extract_subtitles')) { - if (!(isset($rMovieProperties['subtitle']) && $rFFProbee['codecs']['subtitle']['codec_name'] == $rMovieProperties['subtitle'])) { + if (!isset($rMovieProperties['subtitle']) || $rFFProbee['codecs']['subtitle']['codec_name'] != $rMovieProperties['subtitle']) { $rMovieProperties['subtitle'] = $rFFProbee['codecs']['subtitle']; } } - if (!(isset($rMovieProperties['bitrate']) && $rBitrate == $rMovieProperties['bitrate'])) { + if (!isset($rMovieProperties['bitrate']) || $rBitrate != $rMovieProperties['bitrate']) { if (0 < $rBitrate) { $rMovieProperties['bitrate'] = $rBitrate; } else { @@ -184,7 +184,7 @@ class CleanupCronJob implements CommandInterface { $rActualFiles = []; foreach ($rList as $rItem) { $rFilename = trim(explode("'", explode("'", $rItem)[1])[0]); - if (0 < strlen($rFilename)) { + if ($rFilename !== '') { if (in_array($rFilename, $rExisting)) { $rActualFiles[] = $rFilename; } else { diff --git a/src/Cli/CronJobs/EpgCronJob.php b/src/Cli/CronJobs/EpgCronJob.php index d1262a80..9bde18d8 100644 --- a/src/Cli/CronJobs/EpgCronJob.php +++ b/src/Cli/CronJobs/EpgCronJob.php @@ -113,7 +113,7 @@ class EpgCronJob implements CommandInterface { WHERE `epg_id` = ?;', $rData['epg_id'], $rData['epg_id']); $channelMap = $db->get_rows(true, 'channel_id'); - $batches = $rEPG->parseEPG($rData['epg_id'], $channelMap, intval($rData['offset']) ?: 0); + $batches = $rEPG->parseEPG($rData['epg_id'], $channelMap, intval($rData['offset'])); $this->reconnectDb(); @@ -166,7 +166,7 @@ class EpgCronJob implements CommandInterface { $this->printLog("[XMLTV] Generating XMLTV for $totalBouquets bouquet(s)"); foreach ($ApiDependencyIdentifier as $rBouquet => $BatchProcessId) { - if (!(strlen($rBouquet) > 0 && (count($BatchProcessId['streams']) > 0 || $rBouquet == 'all'))) { + if (strlen($rBouquet) <= 0 || count($BatchProcessId['streams']) <= 0 && $rBouquet != 'all') { continue; } @@ -336,7 +336,7 @@ class EpgCronJob implements CommandInterface { foreach ($db->get_rows() as $rRow) { $rBouquets = json_decode($rRow['bouquet'] ?? null, true); - if (!is_array($rBouquets) || empty($rBouquets)) { + if (!is_array($rBouquets) || $rBouquets === []) { $this->printLog("[XMLTV] Skipping invalid/empty bouquet value: " . var_export($rBouquets, true)); continue; } diff --git a/src/Cli/CronJobs/ErrorsCronJob.php b/src/Cli/CronJobs/ErrorsCronJob.php index 5d142864..bb1202bb 100644 --- a/src/Cli/CronJobs/ErrorsCronJob.php +++ b/src/Cli/CronJobs/ErrorsCronJob.php @@ -170,7 +170,7 @@ class ErrorsCronJob implements CommandInterface { $rErrors = preg_split('/\r\n|\r|\n/', (string) file_get_contents($rFile)); foreach ($rErrors as $rError) { $rError = trim((string) $rError); - if (!(empty($rError) || $this->inArray($rIgnoreErrors, $rError))) { + if (!empty($rError) && !$this->inArray($rIgnoreErrors, $rError)) { if (SettingsManager::get('stream_logs_save')) { $rQuery .= '(' . $rStreamID . ',' . SERVER_ID . ',' . time() . ',' . $db->escape($rError) . '),'; } diff --git a/src/Cli/CronJobs/MaxMindCronJob.php b/src/Cli/CronJobs/MaxMindCronJob.php index 72c2d9f5..869f3c9e 100644 --- a/src/Cli/CronJobs/MaxMindCronJob.php +++ b/src/Cli/CronJobs/MaxMindCronJob.php @@ -66,7 +66,7 @@ class MaxMindCronJob implements CommandInterface { $updater = MaxMindUpdater::fromSettings($rSettings); $rReleaseUpdater = new GeoLiteReleaseUpdater(); - if ($updater !== null) { + if ($updater instanceof \XcVm\Core\GeoIP\MaxMindUpdater) { echo 'Updating MaxMind databases...' . "\n"; $results = $updater->update($force); @@ -92,7 +92,7 @@ class MaxMindCronJob implements CommandInterface { // ASN lookups work without a licence. Runs on every node (each needs the mmdb // locally); records geoisp_version in version.json. $rEditions = json_decode((string) ($rSettings['maxmind_editions'] ?? '[]'), true) ?: []; - if (!($updater !== null && in_array('GeoIP2-ISP', $rEditions, true))) { + if (!$updater instanceof \XcVm\Core\GeoIP\MaxMindUpdater || !in_array('GeoIP2-ISP', $rEditions, true)) { $rReleaseUpdater->updateIsp($force); } diff --git a/src/Cli/CronJobs/ModuleLicensesCronJob.php b/src/Cli/CronJobs/ModuleLicensesCronJob.php index 47a7f197..70eaf5b9 100644 --- a/src/Cli/CronJobs/ModuleLicensesCronJob.php +++ b/src/Cli/CronJobs/ModuleLicensesCronJob.php @@ -56,7 +56,7 @@ class ModuleLicensesCronJob implements CommandInterface { $manager->listModules(), static fn ($m) => ($m['source'] ?? '') === 'platform' ); - if (empty($platform)) { + if ($platform === []) { echo "No platform modules installed.\n"; return 0; } diff --git a/src/Cli/CronJobs/RootMysqlCronJob.php b/src/Cli/CronJobs/RootMysqlCronJob.php index 069eefcf..c8be6022 100644 --- a/src/Cli/CronJobs/RootMysqlCronJob.php +++ b/src/Cli/CronJobs/RootMysqlCronJob.php @@ -168,10 +168,9 @@ class RootMysqlCronJob implements CommandInterface { if (isset($checkOut[0]) && trim($checkOut[0]) === 'active') { echo "[MYSQL] MariaDB successfully restarted\n"; return true; - } else { - echo "[MYSQL] FAILED to restart MariaDB\n"; - return false; } + echo "[MYSQL] FAILED to restart MariaDB\n"; + return false; } return true; diff --git a/src/Cli/CronJobs/RootSignalsCronJob.php b/src/Cli/CronJobs/RootSignalsCronJob.php index 60a6185b..826c691e 100644 --- a/src/Cli/CronJobs/RootSignalsCronJob.php +++ b/src/Cli/CronJobs/RootSignalsCronJob.php @@ -82,11 +82,12 @@ class RootSignalsCronJob implements CommandInterface { exec('sudo ip6tables -I INPUT -s ' . escapeshellcmd($rIP) . ' -j DROP'); } } - if (!$isPrivate && $rIP) { touch(FLOOD_TMP_PATH . 'block_' . $rIP); return true; - } elseif ($isPrivate) { + } + + if ($isPrivate) { error_log("Block attempt denied for private IP: " . $rIP); return false; } diff --git a/src/Cli/CronJobs/ServersCronJob.php b/src/Cli/CronJobs/ServersCronJob.php index 74d11796..31811706 100644 --- a/src/Cli/CronJobs/ServersCronJob.php +++ b/src/Cli/CronJobs/ServersCronJob.php @@ -47,12 +47,10 @@ class ServersCronJob implements CommandInterface { $rSocket = @fsockopen($rIP, $rPort, $rErrNo, $rErrStr, 3); $rStopTime = microtime(true); if (!$rSocket) { - $rStatus = -1; - } else { - fclose($rSocket); - $rStatus = floor(($rStopTime - $rStartTime) * 1000); + return -1; } - return $rStatus; + fclose($rSocket); + return (int) floor(($rStopTime - $rStartTime) * 1000); } private function loadCron(): void { diff --git a/src/Cli/CronJobs/StreamsCronJob.php b/src/Cli/CronJobs/StreamsCronJob.php index 3f2d0265..42b244a0 100644 --- a/src/Cli/CronJobs/StreamsCronJob.php +++ b/src/Cli/CronJobs/StreamsCronJob.php @@ -57,7 +57,7 @@ class StreamsCronJob implements CommandInterface { * native remuxer redials the ingest socket by itself, so it is adopted and * the channel does not blink. */ - private static function handOverNeedsRestart(array $rStream): int { + private function handOverNeedsRestart(array $rStream): int { $rPID = file_exists(STREAMS_PATH . $rStream['stream_id'] . '_.pid') ? intval(@file_get_contents(STREAMS_PATH . $rStream['stream_id'] . '_.pid')) : intval($rStream['pid']); if (!ProcessManager::isStreamRunning($rPID, $rStream['stream_id'])) { return 0; // nothing running: a plain start @@ -89,7 +89,7 @@ class StreamsCronJob implements CommandInterface { * @param int $rPID The producer's pid. * @return string The JSON to store. */ - private static function withResourceUsage(string $rProgressJson, int $rStreamID, int $rPID): string { + private function withResourceUsage(string $rProgressJson, int $rStreamID, int $rPID): string { $rProgress = json_decode($rProgressJson, true); if (!is_array($rProgress)) { $rProgress = []; @@ -175,7 +175,7 @@ class StreamsCronJob implements CommandInterface { if ($rRedis) { $rCount = 0; $rRedis = RedisManager::instance(); - if ($rRedis) { + if ($rRedis instanceof \Redis) { $rKeys = $rRedis->zRangeByScore('STREAM#' . $rStream['stream_id'], '-inf', '+inf'); if (count($rKeys) > 0) { $rConnections = array_map('igbinary_unserialize', $rRedis->mGet($rKeys)); @@ -310,7 +310,7 @@ class StreamsCronJob implements CommandInterface { $rCurrentReport = []; } } - $rProgress = $rReport ? json_encode($rReport) : ($rStream['progress_info'] ?: json_encode([])); + $rProgress = $rReport !== [] ? json_encode($rReport) : ($rStream['progress_info'] ?: json_encode([])); file_put_contents($rProgressPath, ''); if ($rStream['fps_restart']) { file_put_contents(STREAMS_PATH . $rStream['stream_id'] . '_.progress_check', $rProgress); @@ -318,7 +318,7 @@ class StreamsCronJob implements CommandInterface { } else { $rProgress = $rStream['progress_info']; } - $rProgress = self::withResourceUsage((string) $rProgress, intval($rStream['stream_id']), $rPID); + $rProgress = $this->withResourceUsage((string) $rProgress, intval($rStream['stream_id']), $rPID); // A supervised stream's codecs, resolution and bitrate come // from the daemon, measured off the bytes (reconcileSupervised // wrote them above); recomputing them here from a stream_info @@ -360,7 +360,7 @@ class StreamsCronJob implements CommandInterface { echo "\n"; } else { echo 'Start monitor...' . "\n\n"; - if (StreamProcess::startMonitor($rStream['stream_id'], self::handOverNeedsRestart($rStream)) === StreamProcess::MONITOR_PHP) { + if (StreamProcess::startMonitor($rStream['stream_id'], $this->handOverNeedsRestart($rStream)) === StreamProcess::MONITOR_PHP) { usleep(50000); // stagger PHP monitor spawns } } diff --git a/src/Cli/CronJobs/UpdateCronJob.php b/src/Cli/CronJobs/UpdateCronJob.php index 8e843bdc..a15d4b26 100644 --- a/src/Cli/CronJobs/UpdateCronJob.php +++ b/src/Cli/CronJobs/UpdateCronJob.php @@ -57,7 +57,7 @@ class UpdateCronJob implements CommandInterface { echo 'Update is available!' . "\n"; $updatedChanges = []; foreach (array_reverse($rUpdate['changelog']) as $rItem) { - if (!($rItem['version'] == XC_VM_VERSION)) { + if ($rItem['version'] != XC_VM_VERSION) { $updatedChanges[] = $rItem; } else { break; diff --git a/src/Core/Auth/AuthService.php b/src/Core/Auth/AuthService.php index 10884254..a0dfc577 100644 --- a/src/Core/Auth/AuthService.php +++ b/src/Core/Auth/AuthService.php @@ -182,7 +182,6 @@ class AuthService { * @param mixed $rKnown The configured secret. * @param mixed $rGiven What the request carried (a string, or anything a * query string can make: null, an array). - * @return bool */ public static function secretMatches(mixed $rKnown, mixed $rGiven): bool { if (!is_scalar($rKnown) || !is_string($rGiven)) { @@ -215,7 +214,7 @@ class AuthService { public static function validateHMAC(string $rHMAC, int|string $rExpiry, int|string $rStreamID, string $rExtension, string $rIP = '', string $rMACIP = '', string $rIdentifier = '', int $rMaxConnections = 0) { global $db, $rSettings; $rCached = $rSettings['enable_cache']; - if (0 < strlen($rIP) && 0 < strlen($rMACIP) && $rIP != $rMACIP) { + if ($rIP !== '' && $rMACIP !== '' && $rIP != $rMACIP) { return null; } @@ -232,12 +231,12 @@ class AuthService { foreach ($rKeys as $rKey) { $rSecret = Encryption::decrypt($rKey['key'], $rSettings['live_streaming_pass'], OPENSSL_EXTRA); - $rResult = hash_hmac('sha256', (string) $rStreamID . '##' . $rExtension . '##' . $rExpiry . '##' . $rMACIP . '##' . $rIdentifier . '##' . $rMaxConnections, $rSecret); + $rResult = hash_hmac('sha256', $rStreamID . '##' . $rExtension . '##' . $rExpiry . '##' . $rMACIP . '##' . $rIdentifier . '##' . $rMaxConnections, $rSecret); // Constant-time and strict. The old md5($rResult) == md5($rHMAC) used // loose ==, which reads two digests of the form 0e as the // number 0 and so as equal: an hmac like 240610708 passed as the key. - if (hash_equals($rResult, (string) $rHMAC)) { + if (hash_equals($rResult, $rHMAC)) { $rKeyID = $rKey['id']; break; } diff --git a/src/Core/Auth/Authenticator.php b/src/Core/Auth/Authenticator.php index a966fa3a..db4ee4a9 100644 --- a/src/Core/Auth/Authenticator.php +++ b/src/Core/Auth/Authenticator.php @@ -113,7 +113,7 @@ class Authenticator { ? json_decode($rAccessCode['groups'], true) : null; - if (!($rCodeCount == 0 || (is_array($rCodeGroups) && in_array($rUserInfo['member_group_id'], $rCodeGroups)))) { + if ($rCodeCount != 0 && (!is_array($rCodeGroups) || !in_array($rUserInfo['member_group_id'], $rCodeGroups))) { if (!empty($rSettings['save_login_logs'])) { $db->query("INSERT INTO `login_logs`(`type`, `access_code`, `user_id`, `status`, `login_ip`, `date`) VALUES('ADMIN', ?, ?, ?, ?, ?);", $rAccessCode['id'], $rUserInfo['id'], 'INVALID_CODE', $rIP, time()); } @@ -178,7 +178,7 @@ class Authenticator { return ['status' => STATUS_FAILURE]; } - if (!(in_array($rUserInfo['member_group_id'], ($rAccessCode && isset($rAccessCode['groups'])) ? (json_decode($rAccessCode['groups'], true) ?: []) : []) || count(AuthRepository::getActiveCodes(MAIN_HOME)) == 0)) { + if (!in_array($rUserInfo['member_group_id'], ($rAccessCode && isset($rAccessCode['groups'])) ? (json_decode($rAccessCode['groups'], true) ?: []) : []) && count(AuthRepository::getActiveCodes(MAIN_HOME)) != 0) { if (!empty($rSettings['save_login_logs'])) { $db->query("INSERT INTO `login_logs`(`type`, `access_code`, `user_id`, `status`, `login_ip`, `date`) VALUES('RESELLER', ?, ?, ?, ?, ?);", $rAccessCode['id'], $rUserInfo['id'], 'INVALID_CODE', $rIP, time()); } @@ -229,7 +229,6 @@ class Authenticator { * * @param string $rIP The address trying to sign in. * @param int $rLimit login_flood; 0 or less turns the limit off. - * @return bool */ public static function loginFloodExceeded(string $rIP, int $rLimit): bool { global $db; @@ -245,8 +244,6 @@ class Authenticator { * one. The id the visitor arrived with is one someone else may know — a cookie * planted from a sibling subdomain, a shared machine — and keeping it would * sign them in too (session fixation). - * - * @return void */ private static function renewSessionId(): void { if (session_status() === PHP_SESSION_ACTIVE) { diff --git a/src/Core/Auth/Authorization.php b/src/Core/Auth/Authorization.php index 8bf687e0..b1eec1f6 100644 --- a/src/Core/Auth/Authorization.php +++ b/src/Core/Auth/Authorization.php @@ -65,7 +65,7 @@ class Authorization { return false; } - if (!($rType == 'adv' && $rPermissions['is_admin'])) { + if ($rType != 'adv' || !$rPermissions['is_admin']) { return false; } diff --git a/src/Core/Auth/BruteforceGuard.php b/src/Core/Auth/BruteforceGuard.php index ac37e963..7180928a 100644 --- a/src/Core/Auth/BruteforceGuard.php +++ b/src/Core/Auth/BruteforceGuard.php @@ -40,8 +40,6 @@ class BruteforceGuard { /** * Resolve the user's IP address. - * - * @return string */ private static function getUserIP(): string { if (class_exists(NetworkUtils::class, false)) { @@ -52,8 +50,6 @@ class BruteforceGuard { /** * Get the allowed IPs list. - * - * @return array */ private static function getAllowedIPs(): array { if (class_exists(ServerRepository::class, false)) { @@ -67,8 +63,6 @@ class BruteforceGuard { /** * Get the blocked IPs list. - * - * @return array */ private static function getBlockedIPs(): array { if (class_exists(BlocklistService::class, false)) { @@ -82,11 +76,9 @@ class BruteforceGuard { /** * Get database instance. - * - * @return object|null */ private static function getDB(): ?object { - if (class_exists(DatabaseFactory::class, false) && DatabaseFactory::get() !== null) { + if (class_exists(DatabaseFactory::class, false) && DatabaseFactory::get() instanceof \XcVm\Core\Database\DatabaseHandler) { return DatabaseFactory::get(); } global $db; @@ -284,7 +276,7 @@ class BruteforceGuard { $floodLimit = intval($settings['auth_flood_limit']); $floodRow['attempts'] = self::truncateAttempts($floodRow['attempts'], $floodSeconds, true); - if (!($floodLimit > count($floodRow['attempts']))) { + if ($floodLimit <= count($floodRow['attempts'])) { $floodRow['block_until'] = time() + intval($settings['auth_flood_seconds']); } diff --git a/src/Core/Auth/PageAuthorization.php b/src/Core/Auth/PageAuthorization.php index fc78ac63..bd1664a0 100644 --- a/src/Core/Auth/PageAuthorization.php +++ b/src/Core/Auth/PageAuthorization.php @@ -27,8 +27,7 @@ class PageAuthorization { public static function checkResellerPermissions(?string $rPage = null): bool { global $rPermissions; - if ($rPage) { - } else { + if (!$rPage) { $rPage = strtolower(basename($_SERVER['SCRIPT_FILENAME'], '.php')); } @@ -75,8 +74,7 @@ class PageAuthorization { * @return bool True if the current user may access the page. */ public static function checkPermissions(?string $rPage = null): bool { - if ($rPage) { - } else { + if (!$rPage) { $rPage = strtolower(basename($_SERVER['SCRIPT_FILENAME'], '.php')); } @@ -91,8 +89,7 @@ class PageAuthorization { return true; } - if (RequestManager::has('id') || !Authorization::check('adv', 'add_bouquet')) { - } else { + if (!(RequestManager::has('id') || !Authorization::check('adv', 'add_bouquet'))) { return true; } @@ -115,8 +112,7 @@ class PageAuthorization { return true; } - if (RequestManager::has('id') || !Authorization::check('adv', 'create_channel')) { - } else { + if (!(RequestManager::has('id') || !Authorization::check('adv', 'create_channel'))) { return true; } @@ -140,8 +136,7 @@ class PageAuthorization { return true; } - if (RequestManager::has('id') || !Authorization::check('adv', 'add_epg')) { - } else { + if (!(RequestManager::has('id') || !Authorization::check('adv', 'add_epg'))) { return true; } @@ -154,8 +149,7 @@ class PageAuthorization { return true; } - if (RequestManager::has('id') || !Authorization::check('adv', 'add_episode')) { - } else { + if (!(RequestManager::has('id') || !Authorization::check('adv', 'add_episode'))) { return true; } @@ -175,8 +169,7 @@ class PageAuthorization { return true; } - if (RequestManager::has('id') || !Authorization::check('adv', 'add_group')) { - } else { + if (!(RequestManager::has('id') || !Authorization::check('adv', 'add_group'))) { return true; } @@ -210,6 +203,7 @@ class PageAuthorization { case 'record': return Authorization::check('adv', 'add_movie'); case 'recordings': + case 'movies': return Authorization::check('adv', 'movies'); case 'queue': return Authorization::check('adv', 'streams') || Authorization::check('adv', 'episodes') || Authorization::check('adv', 'series'); @@ -217,18 +211,14 @@ class PageAuthorization { if (RequestManager::has('id') && Authorization::check('adv', 'edit_movie')) { return true; } - if (RequestManager::has('id') || !Authorization::check('adv', 'add_movie')) { - } else { - if (RequestManager::has('import') && !Authorization::check('adv', 'import_movies')) { - } else { + if (!RequestManager::has('id') && Authorization::check('adv', 'add_movie')) { + if (!RequestManager::has('import') || Authorization::check('adv', 'import_movies')) { return true; } } break; case 'movie_mass': return Authorization::check('adv', 'mass_sedits_vod'); - case 'movies': - return Authorization::check('adv', 'movies'); case 'package': if (RequestManager::has('id') && Authorization::check('adv', 'edit_package')) { return true; @@ -327,10 +317,8 @@ class PageAuthorization { return true; } - if (RequestManager::has('id') || !Authorization::check('adv', 'add_stream')) { - } else { - if (RequestManager::has('import') && !Authorization::check('adv', 'import_streams')) { - } else { + if (!RequestManager::has('id') && Authorization::check('adv', 'add_stream')) { + if (!RequestManager::has('import') || Authorization::check('adv', 'import_streams')) { return true; } } diff --git a/src/Core/Auth/SessionManager.php b/src/Core/Auth/SessionManager.php index f80a2f70..f0d9fe73 100644 --- a/src/Core/Auth/SessionManager.php +++ b/src/Core/Auth/SessionManager.php @@ -130,8 +130,6 @@ class SessionManager { /** * Check if user is authenticated (non-blocking, no redirect) - * - * @return bool */ public static function isAuthenticated(): bool { if (!self::$started) { @@ -144,8 +142,6 @@ class SessionManager { /** * Get the auth token/hash for current session - * - * @return mixed */ public static function getUser(): mixed { $authKey = self::getKey('auth'); @@ -156,7 +152,6 @@ class SessionManager { * Get a session value by logical name * * @param string $name Logical name: 'auth', 'activity', 'ip', 'code', 'verify' - * @return mixed */ public static function getValue(string $name): mixed { $key = self::getKey($name); @@ -245,8 +240,6 @@ class SessionManager { /** * Get current context - * - * @return string|null */ public static function getContext(): ?string { return self::$context; @@ -286,7 +279,6 @@ class SessionManager { * Get the actual $_SESSION key for a logical name in current context * * @param string $name Logical name: 'auth', 'activity', 'ip', 'code', 'verify' - * @return string */ protected static function getKey(string $name): string { if (self::$context === null) { diff --git a/src/Core/Backup/BackupService.php b/src/Core/Backup/BackupService.php index c4a58227..30577aa3 100644 --- a/src/Core/Backup/BackupService.php +++ b/src/Core/Backup/BackupService.php @@ -96,8 +96,7 @@ class BackupService { foreach (scandir(MAIN_HOME . 'backups/') as $rBackup) { $rInfo = pathinfo(MAIN_HOME . 'backups/' . $rBackup); - if ($rInfo['extension'] != 'sql') { - } else { + if ($rInfo['extension'] == 'sql') { $rBackups[] = ['filename' => $rBackup, 'timestamp' => filemtime(MAIN_HOME . 'backups/' . $rBackup), 'date' => date('Y-m-d H:i:s', filemtime(MAIN_HOME . 'backups/' . $rBackup)), 'filesize' => filesize(MAIN_HOME . 'backups/' . $rBackup)]; } } @@ -147,8 +146,7 @@ class BackupService { foreach ($rFiles as $rFile) { try { - if (!(!$rFile->isDir && strtolower(pathinfo($rFile->name)['extension']) == 'sql' && 0 < $rFile->size)) { - } else { + if (!$rFile->isDir && strtolower(pathinfo($rFile->name)['extension']) == 'sql' && 0 < $rFile->size) { $rJSON = json_decode(json_encode($rFile, JSON_UNESCAPED_UNICODE), true); $rJSON['time'] = strtotime($rFile->server_modified); $rBackups[] = $rJSON; diff --git a/src/Core/Cache/RedisCache.php b/src/Core/Cache/RedisCache.php index dd384304..2484a6c0 100644 --- a/src/Core/Cache/RedisCache.php +++ b/src/Core/Cache/RedisCache.php @@ -42,7 +42,7 @@ use XcVm\Infrastructure\Redis\RedisManager; class RedisCache implements CacheInterface { /** @var \Redis|null phpredis connection */ - protected $redis = null; + protected $redis; /** @var string \Redis host */ protected $host; @@ -113,17 +113,12 @@ class RedisCache implements CacheInterface { } $prefixedKey = $this->prefix . $key; - $data = $this->redis->get($prefixedKey); - - if ($data === false) { - return false; - } // maxAge is handled by \Redis TTL, not by us // But if caller wants to check age, we can't — \Redis doesn't store creation time // For file-based TTL compat, we ignore maxAge here (\Redis uses its own TTL) - return $data; + return $this->redis->get($prefixedKey); } /** diff --git a/src/Core/Config/DomainResolver.php b/src/Core/Config/DomainResolver.php index e549b948..a192c054 100644 --- a/src/Core/Config/DomainResolver.php +++ b/src/Core/Config/DomainResolver.php @@ -63,7 +63,7 @@ class DomainResolver { if ($rProxied || $rSettings['use_mdomain_in_lists'] == 1) { $rResellerDomains = CacheReader::get('reseller_domains') ?: []; - if (!(strlen($rDomain) > 0 && in_array(strtolower($rDomain), $rResellerDomains))) { + if (strlen($rDomain) <= 0 || !in_array(strtolower($rDomain), $rResellerDomains)) { if (empty($rServers[$rServerID]['domain_name'])) { $rDomain = escapeshellcmd($rServers[$rServerID]['server_ip']); } elseif (filter_var($rDomain, FILTER_VALIDATE_IP)) { diff --git a/src/Core/Config/SettingsManager.php b/src/Core/Config/SettingsManager.php index 00a06994..69d89926 100644 --- a/src/Core/Config/SettingsManager.php +++ b/src/Core/Config/SettingsManager.php @@ -50,8 +50,6 @@ class SettingsManager { /** * Проверяет наличие ключа в настройках. - * - * @return bool */ public static function has(string $key): bool { return array_key_exists($key, self::$settings); @@ -64,7 +62,6 @@ class SettingsManager { * '0' и '' → false, '1' и любое непустое значение → true. * * @param bool $default Значение, если ключ отсутствует. - * @return bool */ public static function getBool(string $key, bool $default = false): bool { return array_key_exists($key, self::$settings) ? (bool) self::$settings[$key] : $default; @@ -72,8 +69,6 @@ class SettingsManager { /** * Возвращает значение как int. - * - * @return int */ public static function getInt(string $key, int $default = 0): int { return array_key_exists($key, self::$settings) ? (int) self::$settings[$key] : $default; @@ -81,8 +76,6 @@ class SettingsManager { /** * Возвращает значение как строку. - * - * @return string */ public static function getString(string $key, string $default = ''): string { return array_key_exists($key, self::$settings) ? (string) self::$settings[$key] : $default; @@ -93,8 +86,6 @@ class SettingsManager { * * JSON-поля декодируются в массивы ещё в SettingsRepository, поэтому здесь * достаточно проверить тип; для скаляров/null возвращается $default. - * - * @return array */ public static function getArray(string $key, array $default = []): array { $rValue = self::$settings[$key] ?? null; diff --git a/src/Core/Container/ServiceContainer.php b/src/Core/Container/ServiceContainer.php index f92714e1..5087c5d5 100644 --- a/src/Core/Container/ServiceContainer.php +++ b/src/Core/Container/ServiceContainer.php @@ -125,7 +125,7 @@ class ServiceContainer implements ContainerInterface { * @internal Bootstrap only. Modules receive ServiceContainer via boot(ServiceContainer $c). */ public static function getInstance(): self { - if (self::$instance === null) { + if (!self::$instance instanceof \XcVm\Core\Container\ServiceContainer) { self::$instance = new self(); } return self::$instance; @@ -135,7 +135,7 @@ class ServiceContainer implements ContainerInterface { * Сбросить контейнер (для тестов). */ public static function resetInstance(): void { - if (self::$instance !== null) { + if (self::$instance instanceof \XcVm\Core\Container\ServiceContainer) { self::$instance->factories = []; self::$instance->resolved = []; self::$instance->isFactory = []; @@ -158,14 +158,13 @@ class ServiceContainer implements ContainerInterface { /** * Зарегистрировать сервис. * - * Если $value — callable (замыкание или [class, method]), + * Если $value — callable(замыкание или [class, method]), * он будет вызван ОДИН раз при первом get(). Результат кэшируется. * * Если $value — не callable, сохраняется как готовое значение. * * @param string $id Уникальный идентификатор (например, 'db', 'settings') * @param mixed $value Фабрика (callable) или готовое значение - * @return $this */ public function set(string $id, mixed $value): static { // Удаляем ранее разрешённый сервис при перерегистрации @@ -188,7 +187,6 @@ class ServiceContainer implements ContainerInterface { * * @param string $id Идентификатор * @param callable $factory Фабрика: function(ServiceContainer $c): mixed - * @return $this */ public function factory(string $id, callable $factory): static { unset($this->resolved[$id]); @@ -207,7 +205,6 @@ class ServiceContainer implements ContainerInterface { * * @param string $id Идентификатор сервиса * @param string $tag Имя тега (например, 'event.subscriber', 'cron') - * @return $this */ public function tag(string $id, string $tag): static { if (!isset($this->tags[$tag])) { @@ -275,7 +272,6 @@ class ServiceContainer implements ContainerInterface { * Получить сервис по идентификатору. * * @param string $id Идентификатор - * @return mixed * @throws NotFoundException Если сервис не зарегистрирован * @throws \RuntimeException Если обнаружена циклическая зависимость или фабрика бросила исключение */ @@ -330,7 +326,6 @@ class ServiceContainer implements ContainerInterface { * * @param string $id Идентификатор * @param mixed $default Значение по умолчанию (если сервис не найден) - * @return mixed */ public function getOrDefault(string $id, mixed $default = null): mixed { if ($this->has($id)) { @@ -361,7 +356,6 @@ class ServiceContainer implements ContainerInterface { * Проверить, зарегистрирован ли сервис. * * @param string $id Идентификатор - * @return bool */ public function has(string $id): bool { return array_key_exists($id, $this->resolved) || isset($this->factories[$id]); @@ -385,7 +379,6 @@ class ServiceContainer implements ContainerInterface { * Удалить сервис из контейнера. * * @param string $id Идентификатор - * @return $this */ public function remove(string $id): static { unset( @@ -412,7 +405,6 @@ class ServiceContainer implements ContainerInterface { * Зарегистрировать несколько сервисов из массива. * * @param array $services Массив [id => value/callable, ...] - * @return $this */ public function register(array $services): static { foreach ($services as $id => $value) { @@ -427,8 +419,6 @@ class ServiceContainer implements ContainerInterface { /** * Магический доступ: $container->db вместо $container->get('db') - * - * @return mixed */ public function __get(string $id): mixed { return $this->get($id); @@ -436,8 +426,6 @@ class ServiceContainer implements ContainerInterface { /** * Магическая проверка: isset($container->db) - * - * @return bool */ public function __isset(string $id): bool { return $this->has($id); @@ -488,7 +476,6 @@ class ServiceContainer implements ContainerInterface { * Throw a CircularDependencyException describing the resolution chain. * * @param string $id Service id whose creation closed the cycle. - * @return never * @throws CircularDependencyException Always. */ private function throwCircularDependency(string $id): never { @@ -504,8 +491,6 @@ class ServiceContainer implements ContainerInterface { /** * Дамп содержимого контейнера (для отладки). - * - * @return array */ public function dump(): array { $result = []; diff --git a/src/Core/Database/Database.php b/src/Core/Database/Database.php index 6abf68b4..7f792dff 100644 --- a/src/Core/Database/Database.php +++ b/src/Core/Database/Database.php @@ -15,26 +15,26 @@ use XcVm\Core\Logging\FileLogger; */ class Database { - public $result = null; + public $result; - public $last_query = null; + public $last_query; - public $dbh = null; + public $dbh; public $connected = false; /** Last PDO error message (empty when the last query succeeded). */ protected $lastError = ''; - protected $dbuser = null; + protected $dbuser; - protected $dbpassword = null; + protected $dbpassword; - protected $dbname = null; + protected $dbname; - protected $dbhost = null; + protected $dbhost; - protected $dbport = null; + protected $dbport; /** * Constructor - Initializes database connection @@ -279,7 +279,7 @@ class Database { // noise filter drops the 'pdo' entry (duplicate entry / timeouts). $this->lastError = $e->getMessage(); - FileLogger::log('pdo', $e->getMessage(), $actual_query, (int) $e->getLine()); + FileLogger::log('pdo', $e->getMessage(), $actual_query, $e->getLine()); return false; } finally { @@ -313,7 +313,7 @@ class Database { try { $this->result = $this->dbh->query($query); } catch (\Exception $e) { - FileLogger::log('pdo', $e->getMessage(), $query, (int) $e->getLine()); + FileLogger::log('pdo', $e->getMessage(), $query, $e->getLine()); return false; } @@ -330,14 +330,13 @@ class Database { * @return array|false Rows (cleaned), or false if no active result. */ public function get_rows(bool $use_id = false, string $column_as_id = '', bool $unique_row = true, string $sub_row_id = '') { - if (!($this->dbh && $this->result)) { + if (!$this->dbh || !$this->result) { return false; } $rows = []; - if (0 >= $this->result->rowCount()) { - } else { + if (0 < $this->result->rowCount()) { foreach ($this->result->fetchAll(\PDO::FETCH_ASSOC) as $row) { if ($use_id && array_key_exists($column_as_id, $row)) { if (!isset($rows[$row[$column_as_id]])) { @@ -370,14 +369,13 @@ class Database { * @return array|false The row, or false if no active result. */ public function get_row() { - if (!($this->dbh && $this->result)) { + if (!$this->dbh || !$this->result) { return false; } $row = []; - if (0 >= $this->result->rowCount()) { - } else { + if (0 < $this->result->rowCount()) { $row = $this->result->fetch(\PDO::FETCH_ASSOC); } @@ -392,14 +390,13 @@ class Database { * @return mixed The scalar value, or false if no active result/row. */ public function get_col() { - if (!($this->dbh && $this->result)) { + if (!$this->dbh || !$this->result) { return false; } $row = false; - if (0 >= $this->result->rowCount()) { - } else { + if (0 < $this->result->rowCount()) { $row = $this->result->fetch(); $row = $row[0]; } @@ -447,7 +444,7 @@ class Database { * @return int Column count (0 if none). */ public function num_fields() { - if (!($this->dbh && $this->result)) { + if (!$this->dbh || !$this->result) { return 0; } @@ -476,7 +473,7 @@ class Database { * @phpstan-impure Return value reflects the current result set and changes as queries run. */ public function num_rows() { - if (!($this->dbh && $this->result)) { + if (!$this->dbh || !$this->result) { return 0; } diff --git a/src/Core/Database/DatabaseHandler.php b/src/Core/Database/DatabaseHandler.php index 0e74c65c..e9bf651a 100644 --- a/src/Core/Database/DatabaseHandler.php +++ b/src/Core/Database/DatabaseHandler.php @@ -80,7 +80,7 @@ class DatabaseHandler extends Database { protected $inTransaction = false; /** @var callable|null Optional logger callback: function(string $level, string $message, array $context) */ - protected $logger = null; + protected $logger; /** @var int Maximum reconnection attempts */ protected $maxReconnectAttempts = 3; @@ -431,7 +431,7 @@ class DatabaseHandler extends Database { * @return int|false Last insert ID on success, false on failure */ public function insert(string $table, array $data) { - if (empty($data)) { + if ($data === []) { return false; } @@ -464,7 +464,7 @@ class DatabaseHandler extends Database { * @return bool */ public function update(string $table, array $data, string $where, mixed ...$whereParams) { - if (empty($data)) { + if ($data === []) { return false; } diff --git a/src/Core/Database/MigrationRunner.php b/src/Core/Database/MigrationRunner.php index c612dac9..d797957d 100644 --- a/src/Core/Database/MigrationRunner.php +++ b/src/Core/Database/MigrationRunner.php @@ -20,7 +20,6 @@ class MigrationRunner { * `*.sql` file (statement by statement) and records successful ones. * * @param Database $db Database handle. - * @return void */ public static function run(Database $db): void { echo "Migrations\n------------------------------\n"; @@ -98,8 +97,6 @@ class MigrationRunner { /** * Delete files listed in migrations/deleted_files.txt during an update. - * - * @return void */ public static function runFileCleanup(): void { echo "File Cleanup\n------------------------------\n"; diff --git a/src/Core/Database/QueryHelper.php b/src/Core/Database/QueryHelper.php index 2f959452..d0a7b6e9 100644 --- a/src/Core/Database/QueryHelper.php +++ b/src/Core/Database/QueryHelper.php @@ -79,14 +79,12 @@ class QueryHelper { $rForceDefault = false; - if ($rRow['is_nullable'] != 'NO' || $rRow['column_default']) { - } else { + if ($rRow['is_nullable'] == 'NO' && !$rRow['column_default']) { if (in_array($rRow['data_type'], ['int', 'float', 'tinyint', 'double', 'decimal', 'smallint', 'mediumint', 'bigint', 'bit'])) { $rRow['column_default'] = 0; } else { $rRow['column_default'] = ''; } - $rForceDefault = true; } @@ -102,8 +100,7 @@ class QueryHelper { $rReturn[$rRow['column_name']] = $rValue; } } else { - if ($rOnlyExisting) { - } else { + if (!$rOnlyExisting) { $rReturn[$rRow['column_name']] = $rRow['column_default']; } } diff --git a/src/Core/Diagnostics/DiagnosticsService.php b/src/Core/Diagnostics/DiagnosticsService.php index a29d348f..4f89c4c4 100644 --- a/src/Core/Diagnostics/DiagnosticsService.php +++ b/src/Core/Diagnostics/DiagnosticsService.php @@ -101,12 +101,7 @@ class DiagnosticsService { if (!in_array(strtolower($videoCodec), $videoCodecs, true)) { return false; } - - if ($audioCodec && !in_array(strtolower($audioCodec), $audioCodecs, true)) { - return false; - } - - return true; + return !$audioCodec || in_array(strtolower($audioCodec), $audioCodecs, true); } /** @@ -159,14 +154,14 @@ class DiagnosticsService { $errors[] = $errorData; } - if (!empty($errors)) { + if ($errors !== []) { $truncateResult = $db->query('TRUNCATE `panel_logs`;'); if (!$truncateResult) { throw new \Exception('Failed to truncate panel logs table'); } } } catch (\Exception $e) { - throw new \Exception('Failed to process panel logs'); + throw new \Exception('Failed to process panel logs', $e->getCode(), $e); } return [ @@ -240,7 +235,7 @@ class DiagnosticsService { if ($response !== false) { $responseData = json_decode($response, true); - if (isset($responseData['status']) && $responseData['status'] === 'success' && !empty($ids)) { + if (isset($responseData['status']) && $responseData['status'] === 'success' && $ids !== []) { // mark sent logs instead of truncating the whole table $idList = implode(',', array_map('intval', $ids)); $db->query("UPDATE `panel_logs` SET `sent` = 1 WHERE `id` IN ($idList);"); @@ -340,15 +335,13 @@ class DiagnosticsService { $rServer = ServerRepository::getById($rServerID); $rGPUInfo = json_decode($rServer['gpu_info'], true); - if (!is_array($rGPUInfo)) { - } else { + if (is_array($rGPUInfo)) { foreach ($rGPUInfo['gpus'] as $rGPU) { foreach ($rGPU['processes'] as $rProcess) { $rArray = ['pid' => $rProcess['pid'], 'memory' => $rProcess['memory'], 'stream_id' => null]; $db->query('SELECT `stream_id` FROM `streams_servers` WHERE `pid` = ? AND `server_id` = ?;', $rProcess['pid'], $rServerID); - if (0 >= $db->num_rows()) { - } else { + if (0 < $db->num_rows()) { $rArray['stream_id'] = $db->get_row()['stream_id']; } diff --git a/src/Core/Events/AbstractEvent.php b/src/Core/Events/AbstractEvent.php index 2b804dc6..bf95f13c 100644 --- a/src/Core/Events/AbstractEvent.php +++ b/src/Core/Events/AbstractEvent.php @@ -29,8 +29,6 @@ abstract class AbstractEvent implements StoppableEventInterface { /** * Stop propagation so no further listeners receive this event. - * - * @return void */ public function stopPropagation(): void { $this->propagationStopped = true; diff --git a/src/Core/Events/EventDispatcher.php b/src/Core/Events/EventDispatcher.php index 7b4486a7..7bcc23f4 100644 --- a/src/Core/Events/EventDispatcher.php +++ b/src/Core/Events/EventDispatcher.php @@ -70,7 +70,7 @@ class EventDispatcher { * In tests: call setInstance() with a fresh instance per-test. */ public static function getInstance(): self { - if (self::$instance === null) { + if (!self::$instance instanceof \XcVm\Core\Events\EventDispatcher) { self::$instance = new self(); } return self::$instance; diff --git a/src/Core/Events/ListenerProvider.php b/src/Core/Events/ListenerProvider.php index 51c151b3..25711850 100644 --- a/src/Core/Events/ListenerProvider.php +++ b/src/Core/Events/ListenerProvider.php @@ -44,7 +44,7 @@ class ListenerProvider { foreach ($this->listeners[$eventClass] as $priority => $group) { $filtered = array_filter($group, fn($l) => $l !== $listener); - if (empty($filtered)) { + if ($filtered === []) { unset($this->listeners[$eventClass][$priority]); } else { $this->listeners[$eventClass][$priority] = array_values($filtered); diff --git a/src/Core/Events/Stream/StreamStartingEvent.php b/src/Core/Events/Stream/StreamStartingEvent.php index c7f44fd0..452f40d7 100644 --- a/src/Core/Events/Stream/StreamStartingEvent.php +++ b/src/Core/Events/Stream/StreamStartingEvent.php @@ -36,7 +36,6 @@ final class StreamStartingEvent extends AbstractEvent { * Abort the stream start and stop event propagation. * * @param string $reason Human-readable abort reason. - * @return void */ public function abort(string $reason): void { $this->abortReason = $reason; @@ -45,8 +44,6 @@ final class StreamStartingEvent extends AbstractEvent { /** * Reason supplied to abort(), or '' if not aborted. - * - * @return string */ public function getAbortReason(): string { return $this->abortReason; diff --git a/src/Core/GeoIP/MaxMindUpdater.php b/src/Core/GeoIP/MaxMindUpdater.php index 367f1227..63316069 100644 --- a/src/Core/GeoIP/MaxMindUpdater.php +++ b/src/Core/GeoIP/MaxMindUpdater.php @@ -210,7 +210,6 @@ class MaxMindUpdater { * Record today's date as the version for an edition in version.json. * * @param string $edition Edition id that was updated. - * @return void */ private function updateVersionFile(string $edition): void { $data = json_decode(@file_get_contents(self::VERSION_FILE), true) ?: []; diff --git a/src/Core/Http/ApiClient.php b/src/Core/Http/ApiClient.php index f47bdaf2..48f5ec17 100644 --- a/src/Core/Http/ApiClient.php +++ b/src/Core/Http/ApiClient.php @@ -69,9 +69,7 @@ class ApiClient { curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $rTimeout); curl_setopt($ch, CURLOPT_TIMEOUT, $rTimeout); - $rResult = curl_exec($ch); - - return $rResult; + return curl_exec($ch); } return null; } @@ -88,8 +86,7 @@ class ApiClient { global $rServers; foreach ($rServerIDs as $rServerID) { - if (!$rServers[$rServerID]['server_online']) { - } else { + if ($rServers[$rServerID]['server_online']) { $rURLs[$rServerID] = ['url' => $rServers[$rServerID]['api_url'], 'postdata' => $rData]; } } diff --git a/src/Core/Http/CurlClient.php b/src/Core/Http/CurlClient.php index b42f22d6..9addadb2 100644 --- a/src/Core/Http/CurlClient.php +++ b/src/Core/Http/CurlClient.php @@ -23,7 +23,7 @@ class CurlClient { */ public static function getMultiCURL(array $rURLs, ?callable $callback = null, int $rTimeout = 5) { global $rServers; - if (empty($rURLs)) { + if ($rURLs === []) { return []; } @@ -47,8 +47,7 @@ class CurlClient { curl_setopt($rCurl[$rKey], CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($rCurl[$rKey], CURLOPT_SSL_VERIFYPEER, false); - if ($rValue['postdata'] == null) { - } else { + if ($rValue['postdata'] != null) { curl_setopt($rCurl[$rKey], CURLOPT_POST, true); curl_setopt($rCurl[$rKey], CURLOPT_POSTFIELDS, http_build_query($rValue['postdata'])); } @@ -62,8 +61,7 @@ class CurlClient { } while ($rMultiExec == CURLM_CALL_MULTI_PERFORM); while ($rActive && $rMultiExec == CURLM_OK) { - if (curl_multi_select($rMulti) != -1) { - } else { + if (curl_multi_select($rMulti) == -1) { usleep(50000); } do { @@ -73,8 +71,7 @@ class CurlClient { foreach ($rCurl as $rKey => $rValue) { $rResults[$rKey] = curl_multi_getcontent($rValue); - if ($callback == null) { - } else { + if ($callback != null) { $rResults[$rKey] = call_user_func($callback, $rResults[$rKey], true); } curl_multi_remove_handle($rMulti, $rValue); @@ -136,8 +133,7 @@ class CurlClient { curl_setopt($rCurl, CURLOPT_FORBID_REUSE, true); curl_setopt($rCurl, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($rCurl, CURLOPT_SSL_VERIFYPEER, false); - if (empty($rPostData)) { - } else { + if ($rPostData !== []) { curl_setopt($rCurl, CURLOPT_POST, true); curl_setopt($rCurl, CURLOPT_POSTFIELDS, http_build_query($rPostData)); } @@ -163,7 +159,6 @@ class CurlClient { * * @param string $rURL Source URL (must be https://). * @param string $rDest Destination path (opened for writing). - * @return void * @throws \RuntimeException On a non-https URL, an unwritable target, or an HTTP error. */ public static function downloadToFile(string $rURL, string $rDest): void { @@ -185,7 +180,7 @@ class CurlClient { ]); $rOk = curl_exec($ch); $rErr = curl_error($ch); - $rCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); + $rCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); fclose($rHandle); diff --git a/src/Core/Http/Pipeline/StreamContext.php b/src/Core/Http/Pipeline/StreamContext.php index 1630573e..fa9eac00 100644 --- a/src/Core/Http/Pipeline/StreamContext.php +++ b/src/Core/Http/Pipeline/StreamContext.php @@ -58,8 +58,6 @@ final class StreamContext { /** * Whether the pipeline has been aborted. - * - * @return bool */ public function isAborted(): bool { return $this->aborted; @@ -67,8 +65,6 @@ final class StreamContext { /** * Reason passed to abort(), or '' if not aborted. - * - * @return string */ public function getAbortReason(): string { return $this->abortReason; @@ -76,8 +72,6 @@ final class StreamContext { /** * Application-level abort code (0 = unspecified). - * - * @return int */ public function getAbortCode(): int { return $this->abortCode; @@ -109,7 +103,6 @@ final class StreamContext { * Whether an attribute exists in the bag. * * @param string $key Attribute key. - * @return bool */ public function has(string $key): bool { return array_key_exists($key, $this->attributes); diff --git a/src/Core/Http/Request.php b/src/Core/Http/Request.php index 6d33ee8d..ffdc0482 100644 --- a/src/Core/Http/Request.php +++ b/src/Core/Http/Request.php @@ -42,13 +42,13 @@ class Request { protected $input = []; /** @var string Raw POST body */ - protected $rawBody = null; + protected $rawBody; /** @var string Client IP address */ - protected $clientIp = null; + protected $clientIp; /** @var Request|null Captured singleton for static access */ - protected static $captured = null; + protected static $captured; /** * Create from raw superglobals @@ -351,6 +351,7 @@ class Request { } else { return null; } + return null; } /** diff --git a/src/Core/Http/RequestGuard.php b/src/Core/Http/RequestGuard.php index 93ae3f33..37cb7d8c 100644 --- a/src/Core/Http/RequestGuard.php +++ b/src/Core/Http/RequestGuard.php @@ -43,8 +43,7 @@ if (!isset($_SERVER['argc'])) { $rData = file_get_contents(CACHE_TMP_PATH . 'allowed_domains'); $rAllowedDomains = igbinary_unserialize($rData); - if (!(is_array($rAllowedDomains) && !in_array(HOST, $rAllowedDomains) && HOST != 'xc_vm') || filter_var(HOST, FILTER_VALIDATE_IP)) { - } else { + if (is_array($rAllowedDomains) && !in_array(HOST, $rAllowedDomains) && HOST != 'xc_vm' && !filter_var(HOST, FILTER_VALIDATE_IP)) { generateError('INVALID_HOST'); } } diff --git a/src/Core/Http/RequestManager.php b/src/Core/Http/RequestManager.php index a6bc7125..b2d3c76e 100644 --- a/src/Core/Http/RequestManager.php +++ b/src/Core/Http/RequestManager.php @@ -54,8 +54,6 @@ class RequestManager { * * Прямая замена `isset(getAll()['key'])` — `isset()` нельзя применять к * результату get(), поэтому для проверок существования нужен этот метод. - * - * @return bool */ public static function has(string $key): bool { return isset(self::$request[$key]); diff --git a/src/Core/Http/Router.php b/src/Core/Http/Router.php index 3cb55f11..650179ed 100644 --- a/src/Core/Http/Router.php +++ b/src/Core/Http/Router.php @@ -115,7 +115,6 @@ class Router { /** * Current permission spec for the active group. - * @var array */ protected array $groupPermission = []; @@ -126,7 +125,7 @@ class Router { * Get the singleton instance. */ public static function getInstance(): self { - if (self::$instance === null) { + if (!self::$instance instanceof \XcVm\Core\Http\Router) { self::$instance = new self(); } return self::$instance; diff --git a/src/Core/Init/LegacyInitializer.php b/src/Core/Init/LegacyInitializer.php index 6b79162f..d83a9541 100644 --- a/src/Core/Init/LegacyInitializer.php +++ b/src/Core/Init/LegacyInitializer.php @@ -194,8 +194,6 @@ class LegacyInitializer { /** * Export the singleton managers to legacy superglobals. - * - * @return void */ public static function exportGlobals(): void { $GLOBALS["rSettings"] = SettingsManager::getAll(); diff --git a/src/Core/Localization/Translator.php b/src/Core/Localization/Translator.php index 258596cc..7b014964 100644 --- a/src/Core/Localization/Translator.php +++ b/src/Core/Localization/Translator.php @@ -17,10 +17,8 @@ class Translator { /** @var array */ private static array $translations = []; - /** @var string */ private static string $currentLang = 'en'; - /** @var string */ private static string $langsDir = __DIR__ . '/lang/'; /** @var string[] */ @@ -86,7 +84,7 @@ class Translator { self::$translations[$key] = $text; } - return !empty($replace) ? strtr($text, $replace) : $text; + return $replace !== [] ? strtr($text, $replace) : $text; } /** @@ -119,8 +117,8 @@ class Translator { } $languages = array_unique($languages); - if (empty($languages)) { - $languages = ['en']; + if ($languages === []) { + return ['en']; } return $languages; diff --git a/src/Core/Logging/DatabaseLogger.php b/src/Core/Logging/DatabaseLogger.php index df89d956..bbba676c 100644 --- a/src/Core/Logging/DatabaseLogger.php +++ b/src/Core/Logging/DatabaseLogger.php @@ -28,8 +28,6 @@ require_once __DIR__ . '/LoggerInterface.php'; class DatabaseLogger implements LoggerInterface { /** * Путь к файлу лога клиентских запросов. - * - * @var string|null */ private static ?string $logFile = null; @@ -61,8 +59,6 @@ class DatabaseLogger implements LoggerInterface { /** * Получить текущий путь к файлу лога. - * - * @return string */ public static function getLogFile(): string { if (self::$logFile !== null) { diff --git a/src/Core/Logging/FileLogger.php b/src/Core/Logging/FileLogger.php index b9698bc4..f7fe7209 100644 --- a/src/Core/Logging/FileLogger.php +++ b/src/Core/Logging/FileLogger.php @@ -30,8 +30,6 @@ class FileLogger implements LoggerInterface { /** * Путь к файлу лога. * По умолчанию используется LOGS_TMP_PATH . 'error_log.log' - * - * @var string|null */ private static ?string $logFile = null; @@ -47,8 +45,6 @@ class FileLogger implements LoggerInterface { /** * Получить текущий путь к файлу лога. * Если не установлен явно, используется LOGS_TMP_PATH . 'error_log.log' - * - * @return string */ public static function getLogFile(): string { if (self::$logFile !== null) { @@ -78,7 +74,7 @@ class FileLogger implements LoggerInterface { $rTrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); $rCaller = $rTrace[1] ?? []; - $rFile = (string) ($rCaller['file'] ?? ''); + $rFile = $rCaller['file'] ?? ''; if ($line <= 0 && isset($rCaller['line'])) { $line = (int) $rCaller['line']; } diff --git a/src/Core/Logging/Logger.php b/src/Core/Logging/Logger.php index 18fd3458..6d1a72c2 100644 --- a/src/Core/Logging/Logger.php +++ b/src/Core/Logging/Logger.php @@ -213,7 +213,7 @@ final class Logger { } $e = $e->getPrevious(); - if ($e) { + if ($e instanceof \Throwable) { $out[] = "---- CAUSED BY ----"; } } while ($e); diff --git a/src/Core/Logging/LoggerInterface.php b/src/Core/Logging/LoggerInterface.php index f826387c..84cabefc 100644 --- a/src/Core/Logging/LoggerInterface.php +++ b/src/Core/Logging/LoggerInterface.php @@ -26,8 +26,6 @@ interface LoggerInterface { * @param string $message Текст сообщения * @param string|int $extra Дополнительные данные (trace, query, и т.д.) * @param int $line Номер строки (опционально) - * - * @return void */ public static function log(string $type, string $message, string|int $extra = '', int $line = 0): void; } diff --git a/src/Core/Logging/UpdateLogger.php b/src/Core/Logging/UpdateLogger.php index 998d1163..b150dc7a 100644 --- a/src/Core/Logging/UpdateLogger.php +++ b/src/Core/Logging/UpdateLogger.php @@ -35,7 +35,6 @@ class UpdateLogger { * * @param string $level Severity label (e.g. INFO, ERROR). * @param string $message Message text. - * @return void */ public static function log(string $level, string $message): void { $rLine = sprintf("[%s] [%s] %s\n", date('Y-m-d H:i:s'), strtoupper($level), $message); @@ -46,7 +45,6 @@ class UpdateLogger { * Log an INFO-level message. * * @param string $message Message text. - * @return void */ public static function info(string $message): void { self::log('INFO', $message); @@ -56,7 +54,6 @@ class UpdateLogger { * Log an ERROR-level message. * * @param string $message Message text. - * @return void */ public static function error(string $message): void { self::log('ERROR', $message); @@ -64,8 +61,6 @@ class UpdateLogger { /** * Truncate the update log (start a fresh update run). - * - * @return void */ public static function reset(): void { file_put_contents(self::getLogFile(), '', LOCK_EX); diff --git a/src/Core/Module/BaseModule.php b/src/Core/Module/BaseModule.php index aa5e28f5..f0ab93a4 100644 --- a/src/Core/Module/BaseModule.php +++ b/src/Core/Module/BaseModule.php @@ -29,15 +29,11 @@ use XcVm\Core\Module\Contract\TopbarProviderInterface; abstract class BaseModule implements ModuleInterface, MigratableInterface, CronProviderInterface, TopbarProviderInterface, TableProviderInterface, PermissionProviderInterface, QuickToolsProviderInterface { /** * Unique module identifier. - * - * @return string */ abstract public function getName(): string; /** * Module version string. - * - * @return string */ abstract public function getVersion(): string; @@ -45,7 +41,6 @@ abstract class BaseModule implements ModuleInterface, MigratableInterface, CronP * Boot hook: register services/bindings into the container. No-op by default. * * @param ServiceContainer $container The DI container. - * @return void */ public function boot(ServiceContainer $container): void { } @@ -63,7 +58,6 @@ abstract class BaseModule implements ModuleInterface, MigratableInterface, CronP * Register the module's HTTP routes. No-op by default. * * @param Router $router The application router. - * @return void */ public function registerRoutes(Router $router): void { } @@ -72,7 +66,6 @@ abstract class BaseModule implements ModuleInterface, MigratableInterface, CronP * Register the module's CLI commands. No-op by default. * * @param CommandRegistry $registry The CLI command registry. - * @return void */ public function registerCommands(CommandRegistry $registry): void { } @@ -81,55 +74,42 @@ abstract class BaseModule implements ModuleInterface, MigratableInterface, CronP * Register the module's navbar entries. No-op by default. * * @param NavbarRegistry $registry The navbar registry. - * @return void */ public function registerNavbar(NavbarRegistry $registry): void { } /** * No-op default — override to contribute per-page topbar buttons. - * - * @return void */ public function registerTopbar(TopbarRegistry $registry): void { } /** * No-op default — override to register serverSide DataTable handlers. - * - * @return void */ public function registerTables(TableRegistry $registry): void { } /** * No-op default — override to register reseller sub-permission keys. - * - * @return void */ public function registerPermissions(PermissionRegistry $registry): void { } /** * No-op default — override to register one-shot Quick Tools actions. - * - * @return void */ public function registerQuickTools(QuickToolsRegistry $registry): void { } /** * Installation hook, run when the module is installed. No-op by default. - * - * @return void */ public function install(): void { } /** * Uninstallation hook, run when the module is removed. No-op by default. - * - * @return void */ public function uninstall(): void { } diff --git a/src/Core/Module/CoreNavbarProvider.php b/src/Core/Module/CoreNavbarProvider.php index 98874517..c85de4da 100644 --- a/src/Core/Module/CoreNavbarProvider.php +++ b/src/Core/Module/CoreNavbarProvider.php @@ -29,8 +29,6 @@ class CoreNavbarProvider implements NavbarProviderInterface { /** * Register all core navigation items with the NavbarRegistry. - * - * @return void */ public static function register(): void { self::_dashboard(); @@ -50,8 +48,6 @@ class CoreNavbarProvider implements NavbarProviderInterface { * Register Dashboard navigation items. * * Adds the main dashboard menu item and its live connections sub-item. - * - * @return void */ private static function _dashboard(): void { NavbarRegistry::add((new NavbarItem('dashboard')) @@ -70,8 +66,6 @@ class CoreNavbarProvider implements NavbarProviderInterface { * * Adds server management items including load balancer installation, * server/proxy management, ordering, and process monitoring. - * - * @return void */ private static function _servers(): void { NavbarRegistry::add((new NavbarItem('servers')) @@ -107,8 +101,6 @@ class CoreNavbarProvider implements NavbarProviderInterface { * Adds complete user management structure including Lines, MAG devices, * Enigma2 devices, and Reseller management with their respective * add/manage/mass-edit operations. - * - * @return void */ private static function _users(): void { NavbarRegistry::add((new NavbarItem('users')) @@ -197,8 +189,6 @@ class CoreNavbarProvider implements NavbarProviderInterface { * Live-streaming content: Streams, Created Channels and Radio Stations. * VOD (Movies/Series) moved to _vod(); Bouquets/Suppliers/Recordings/TV Guide * moved to _distribution(). Labelled "Streaming"; the key stays 'content'. - * - * @return void */ private static function _content(): void { NavbarRegistry::add((new NavbarItem('content')) @@ -262,8 +252,6 @@ class CoreNavbarProvider implements NavbarProviderInterface { * On-demand catalogue split out of Content: Movies and Series with their * add/import/manage/mass operations. Each leaf keeps its original * url/permissions/label; only the parent key changed (content.* → vod.*). - * - * @return void */ private static function _vod(): void { NavbarRegistry::add((new NavbarItem('vod')) @@ -319,8 +307,6 @@ class CoreNavbarProvider implements NavbarProviderInterface { * Content organisation & delivery split out of Content: Bouquets, Suppliers, * Recordings and TV Guide. Each leaf keeps its original url/permissions/label; * only the parent key changed (content.* → distribution.*). - * - * @return void */ private static function _distribution(): void { NavbarRegistry::add((new NavbarItem('distribution')) @@ -377,8 +363,6 @@ class CoreNavbarProvider implements NavbarProviderInterface { * * Modules inject extra log screens under 'logs' (or one of its subgroups) * at order 500+. - * - * @return void */ private static function _logs(): void { NavbarRegistry::add((new NavbarItem('logs')) @@ -464,8 +448,6 @@ class CoreNavbarProvider implements NavbarProviderInterface { * Adds system management structure including Service Setup, Access Codes, * Security, Tools, and Tickets. Logs live in their own top-level tab now * (see _logs()). - * - * @return void */ private static function _management(): void { // The former "System" group is flattened: its sections (Service Setup, @@ -577,8 +559,6 @@ class CoreNavbarProvider implements NavbarProviderInterface { * NavbarRegistry::add((new NavbarItem('profile.watch_settings')) * ->parent('profile')->url('settings_watch') * ->label('watch_settings')->permissions(['folder_watch_settings'])->order(110)); - * - * @return void */ private static function _profile(): void { NavbarRegistry::add((new NavbarItem('profile.edit')) diff --git a/src/Core/Module/ModuleLoader.php b/src/Core/Module/ModuleLoader.php index c26d978e..e49fcfc6 100644 --- a/src/Core/Module/ModuleLoader.php +++ b/src/Core/Module/ModuleLoader.php @@ -108,7 +108,7 @@ class ModuleLoader { } } - if (empty($jsonFiles)) { + if ($jsonFiles === []) { return $this; } @@ -226,7 +226,6 @@ class ModuleLoader { * @param ServiceContainer $container Service container for dependency injection. * @param Router|null $router Optional router for module route registration. * @param StreamPipeline|null $pipeline Optional stream pipeline for middleware registration. - * @return void */ public function bootAll(ServiceContainer $container, ?Router $router = null, ?StreamPipeline $pipeline = null): void { $navbarRegistry = new NavbarRegistry(); @@ -257,11 +256,11 @@ class ModuleLoader { $this->registerEventSubscribers($module, $container); } - if ($pipeline !== null) { + if ($pipeline instanceof \XcVm\Core\Http\Pipeline\StreamPipeline) { $this->registerStreamMiddleware($module, $pipeline); } - if ($module instanceof RouteProviderInterface && $router !== null) { + if ($router instanceof \XcVm\Core\Http\Router) { $module->registerRoutes($router); } @@ -294,7 +293,6 @@ class ModuleLoader { * Used in CLI context (console.php). * * @param CommandRegistry $registry Command registry for registering module commands. - * @return void */ public function registerAllCommands(CommandRegistry $registry): void { foreach ($this->modules as $name => $module) { @@ -400,8 +398,6 @@ class ModuleLoader { * Loads module override configuration from config/modules.php. * * Overrides can disable modules, override class names, or provide other module-specific settings. - * - * @return void */ protected function loadOverrides(): void { $overridesPath = defined('CONFIG_PATH') @@ -732,7 +728,6 @@ class ModuleLoader { * @param array &$state Visit state for each module (1=visiting, 2=visited). * @param array &$order Load order being built (appends module names). * @param array $stack Call stack trace (used for cycle error message). - * @return void * @throws \RuntimeException If cyclic dependency detected or dependency not found in discovered modules. */ protected function visitDependencyNode( @@ -799,8 +794,6 @@ class ModuleLoader { * * If the event class named in a #[ListensTo] attribute does not exist at * registration time the listener is silently skipped (graceful degradation). - * - * @return void */ private function registerEventSubscribers(ServiceProviderInterface $module, ServiceContainer $container): void { // Verify the container holds an actual EventDispatcher instance (not just the class name). @@ -850,8 +843,6 @@ class ModuleLoader { * Registers stream middleware declared by a module into the pipeline. * * Only called for modules implementing StreamMiddlewareProviderInterface. - * - * @return void */ private function registerStreamMiddleware(ModuleInterface $module, StreamPipeline $pipeline): void { if (!$module instanceof StreamMiddlewareProviderInterface) { @@ -912,7 +903,6 @@ class ModuleLoader { * existing config/modules.php files continue to work without migration. * * @param string $name Module name or directory name. - * @return ModuleState */ private function resolveState(string $name): ModuleState { $entry = $this->overrides[$name] ?? null; diff --git a/src/Core/Module/ModuleManager.php b/src/Core/Module/ModuleManager.php index e8f2caa6..ca18656a 100644 --- a/src/Core/Module/ModuleManager.php +++ b/src/Core/Module/ModuleManager.php @@ -68,13 +68,13 @@ class ModuleManager { */ public function archivePathFor(string $name, string $version): string { $name = $this->sanitizeModuleName($name); - $version = preg_replace('/[^0-9A-Za-z._\-]/', '', (string) $version); + $version = preg_replace('/[^0-9A-Za-z._\-]/', '', $version); return $this->archivesPath . '/' . $name . '_' . $version . '.zip'; } /** @return object|null Database instance from the container, or null if unavailable. */ private function getDb(): ?object { - if ($this->container !== null && $this->container->has('db')) { + if ($this->container instanceof \XcVm\Core\Container\ServiceContainer && $this->container->has('db')) { return $this->container->get('db'); } return null; @@ -168,7 +168,7 @@ class ModuleManager { } } if (!isset($out['hash_id'])) { - $out = ['hash_id' => $hash] + $out; + return ['hash_id' => $hash] + $out; } return $out; } @@ -386,7 +386,7 @@ class ModuleManager { // dependencies are themselves installed. $done = []; $guard = 0; - while (!empty($pending) && $guard++ < 1000) { + while ($pending !== [] && $guard++ < 1000) { $progressed = false; foreach (array_keys($pending) as $name) { $ready = true; @@ -533,7 +533,6 @@ class ModuleManager { * `hash_id` against the entry so a repo/URL cannot supply a different module. * * @param array $entry A getStandardSet() entry (source/repository/…, hash_id). - * @return void * @throws \RuntimeException on download/verify/install failure. */ private function installModuleFromSource(array $entry): void { @@ -693,7 +692,6 @@ class ModuleManager { * Loads the module instance, runs install(), and enables it. * * @param string $name Module name (lowercase, alphanumeric + hyphens). - * @return void * @throws \RuntimeException If the module cannot be loaded. */ public function installModule(string $name, ?string $version = null): void { @@ -736,7 +734,6 @@ class ModuleManager { * Runs uninstall() and disables the module. * * @param string $name Module name. - * @return void * @throws \RuntimeException If the module cannot be loaded. */ public function uninstallModule(string $name): void { @@ -745,7 +742,7 @@ class ModuleManager { // Refuse to remove a module that still-installed dependents rely on // (e.g. plex depends on watch — watch cannot be removed under it). $dependents = $this->installedDependentsOf($name); - if (!empty($dependents)) { + if ($dependents !== []) { throw new \RuntimeException( "Cannot uninstall '{$name}': still required by " . implode(', ', $dependents) . '. Uninstall ' . (count($dependents) === 1 ? 'it' : 'them') . ' first.' @@ -783,7 +780,6 @@ class ModuleManager { * enforced up front. * * @param string $name Module name. - * @return void * @throws \RuntimeException If an installed dependent still requires the module. */ public function deleteModule(string $name): void { @@ -791,7 +787,7 @@ class ModuleManager { // Same guard as uninstall: refuse while an installed dependent needs it. $dependents = $this->installedDependentsOf($name); - if (!empty($dependents)) { + if ($dependents !== []) { throw new \RuntimeException( "Cannot delete '{$name}': still required by " . implode(', ', $dependents) . '. Delete ' . (count($dependents) === 1 ? 'it' : 'them') . ' first.' @@ -827,7 +823,6 @@ class ModuleManager { * the module directory, its stored archives, and its config/modules.php entry. * * @param string $name Module name. - * @return void */ public function deleteModuleFilesOnly(string $name): void { $name = $this->sanitizeModuleName($name); @@ -860,7 +855,6 @@ class ModuleManager { * * @param string $name Module name. * @param array $manifest The module's manifest (read before deletion). - * @return void */ private function distributeDeletionToLoadBalancers(string $name, array $manifest): void { // Cheap manifest check first — a MAIN-only module was never on any LB, so @@ -904,7 +898,6 @@ class ModuleManager { * and version <= module->getVersion(), in ascending semver order. * * @param string $name Module name. - * @return void */ public function updateModule(string $name): void { $name = $this->sanitizeModuleName($name); @@ -1076,7 +1069,7 @@ class ModuleManager { $md5 = ''; try { $channel = in_array((string) ($update['channel'] ?? 'stable'), ['beta', 'unstable'], true) ? 'beta' : 'stable'; - $md5 = (string) ((new GitHubReleases($m[1], $m[2], $channel))->getAssetHash($version, $asset) ?? ''); + $md5 = (new GitHubReleases($m[1], $m[2], $channel))->getAssetHash($version, $asset) ?? ''; } catch (\Throwable $e) { // no hash available → download proceeds unverified } @@ -1129,7 +1122,6 @@ class ModuleManager { * * @param string $name Module name. * @param ModuleState $state Target lifecycle state. - * @return void */ public function setState(string $name, ModuleState $state): void { $name = $this->sanitizeModuleName($name); @@ -1142,7 +1134,7 @@ class ModuleManager { // but are set by installModule() itself and must never be blocked. if ($state === ModuleState::Disabled) { $dependents = $this->enabledDependentsOf($name); - if (!empty($dependents)) { + if ($dependents !== []) { throw new \RuntimeException( "Cannot disable '{$name}': still required by " . implode(', ', $dependents) . '. Disable ' . (count($dependents) === 1 ? 'it' : 'them') . ' first.' @@ -1179,7 +1171,6 @@ class ModuleManager { * * @param string $name Module name. * @param bool $enabled True to enable, false to disable. - * @return void */ public function setEnabled(string $name, bool $enabled): void { $this->setState($name, $enabled ? ModuleState::Enabled : ModuleState::Disabled); @@ -1311,7 +1302,6 @@ class ModuleManager { * is hardcoded and may drift from the shipped manifest). * * @param string $name Module name / directory. - * @return string|null */ private function manifestVersion(string $name): ?string { $v = $this->readModuleManifest($name)['version'] ?? null; @@ -1400,7 +1390,6 @@ class ModuleManager { * @param string $slug Module slug as listed on the platform. * @param string $version Exact version string (e.g. "1.2.0"), or '' for the latest. * @param string|null $apiKey API key for the SaaS platform. - * @return void * @throws \RuntimeException If the C extension is missing, download fails, or install fails. */ public function downloadFromPlatform(string $slug, string $version = '', ?string $apiKey = null): void { @@ -1669,7 +1658,6 @@ class ModuleManager { * @param string $slug Module slug on the platform. * @param string $version Exact version string. * @param string|null $apiKey Shared platform API key (from settings). - * @return void */ public function deployFromPlatformFilesOnly(string $slug, string $version, ?string $apiKey = null): void { $result = $this->pullFilesFromPlatform($slug, $version, $apiKey); @@ -1766,7 +1754,6 @@ class ModuleManager { * * @param string $slug Module slug. * @param string $modulePath Filesystem path to the module. - * @return void */ private function hotReload(string $slug, string $modulePath): void { $container = ServiceContainer::getInstance(); @@ -1852,7 +1839,6 @@ class ModuleManager { * * @param string $name Module name. * @param string|null $version Latest available version, or null to clear. - * @return void */ public function recordAvailableVersion(string $name, ?string $version): void { $name = $this->sanitizeModuleName($name); @@ -1894,7 +1880,7 @@ class ModuleManager { } $module = $loader->getModule($name); - if (!$module) { + if (!$module instanceof \XcVm\Core\Module\ModuleInterface) { throw new ModuleNotFoundException('Module instance is not available: ' . $name); } @@ -1909,7 +1895,7 @@ class ModuleManager { * @throws \InvalidArgumentException If the name is invalid. */ private function sanitizeModuleName(string $name): string { - $name = trim((string) $name); + $name = trim($name); if (!preg_match('/^[a-z0-9][a-z0-9\-]*$/', $name)) { throw new ModuleException('Invalid module name.'); } @@ -1937,7 +1923,6 @@ class ModuleManager { * requests can never read a partially-written file. * * @param array $overrides Module overrides to persist. - * @return void * @throws \RuntimeException If the file cannot be written or renamed. */ private function writeOverrides(array $overrides): void { @@ -2075,7 +2060,6 @@ class ModuleManager { * * @param string $zipFilePath Path to the zip file. * @param string $destination Extraction target directory. - * @return void * @throws \RuntimeException If extraction fails or unsafe entries are detected. */ private function extractZipViaZipArchive(string $zipFilePath, string $destination): void { @@ -2177,7 +2161,6 @@ class ModuleManager { * Recursively delete a directory and its contents. * * @param string $path Path to delete. - * @return void */ private function deleteDirectory(string $path): void { if (!file_exists($path)) { @@ -2210,7 +2193,6 @@ class ModuleManager { * * @param string $source Source directory path. * @param string $destination Destination directory path. - * @return void * @throws \RuntimeException If copying fails. */ private function copyDirectory(string $source, string $destination): void { diff --git a/src/Core/Module/NavbarItem.php b/src/Core/Module/NavbarItem.php index 8553e157..b689282d 100644 --- a/src/Core/Module/NavbarItem.php +++ b/src/Core/Module/NavbarItem.php @@ -28,7 +28,7 @@ class NavbarItem { public $key; /** @var string|null Parent key, null for top-level items */ - public $parent = null; + public $parent; /** @var string Target URL or '#' for group headers */ public $url = '#'; @@ -76,7 +76,6 @@ class NavbarItem { * Set the parent item key for hierarchical navigation. * * @param string $parentKey Dot-separated key of the parent item - * @return self */ public function parent(string $parentKey): self { $this->parent = $parentKey; @@ -89,7 +88,6 @@ class NavbarItem { * Use '#' for group headers that expand to show child items. * * @param string $url Target URL or '#' - * @return self */ public function url(string $url): self { $this->url = $url; @@ -104,7 +102,6 @@ class NavbarItem { * * @param string $translationKey Translation key for $language::get() * @param string $fallback Literal fallback text when translationKey is empty - * @return self */ public function label(string $translationKey, string $fallback = ''): self { $this->translationKey = $translationKey; @@ -119,7 +116,6 @@ class NavbarItem { * Empty array means no permission check. * * @param string[] $permissions List of permission names - * @return self */ public function permissions(array $permissions): self { $this->permissions = $permissions; @@ -132,7 +128,6 @@ class NavbarItem { * Lower values appear first. Default is 100. * * @param int $order Sort order - * @return self */ public function order(int $order): self { $this->order = $order; @@ -143,7 +138,6 @@ class NavbarItem { * Set the CSS icon class(es) for this navigation item. * * @param string $icon CSS classes, e.g. 'fas fa-server' or 'fe-activity' - * @return self */ public function icon(string $icon): self { $this->icon = $icon; @@ -154,8 +148,6 @@ class NavbarItem { * Mark this item as desktop-only. * * When true, the item is hidden on mobile devices. - * - * @return self */ public function desktopOnly(): self { $this->desktopOnly = true; @@ -166,8 +158,6 @@ class NavbarItem { * Hide the submenu on mobile devices. * * When true, child items are not rendered in mobile view. - * - * @return self */ public function noMobileSubmenu(): self { $this->noMobileSubmenu = true; @@ -180,7 +170,6 @@ class NavbarItem { * Useful for mega menu layouts or custom styling. * * @param string $cls CSS class name, e.g. 'megamenu' - * @return self */ public function submenuClass(string $cls): self { $this->submenuClass = $cls; @@ -194,7 +183,6 @@ class NavbarItem { * this navigation item will not be displayed. * * @param string $key Setting key name - * @return self */ public function settingDisabled(string $key): self { $this->settingDisabled = $key; @@ -205,8 +193,6 @@ class NavbarItem { * Render this item as a visual divider. * * Dividers are non-clickable elements that separate groups of items. - * - * @return self */ public function makeDivider(): self { $this->divider = true; diff --git a/src/Core/Module/NavbarRegistry.php b/src/Core/Module/NavbarRegistry.php index 4d89099c..2d32bac7 100644 --- a/src/Core/Module/NavbarRegistry.php +++ b/src/Core/Module/NavbarRegistry.php @@ -27,7 +27,6 @@ class NavbarRegistry { * Duplicate keys will overwrite previously registered items. * * @param NavbarItem $item The navigation item to register - * @return void */ public static function add(NavbarItem $item): void { self::$items[$item->key] = $item; @@ -98,7 +97,7 @@ class NavbarRegistry { } $result[] = $item; } - while (!empty($result) && end($result)->divider) { + while ($result !== [] && end($result)->divider) { array_pop($result); } return $result; @@ -109,8 +108,6 @@ class NavbarRegistry { * * Primarily useful for unit testing to ensure a clean state * between test cases. - * - * @return void */ public static function reset(): void { self::$items = []; diff --git a/src/Core/Parsing/StringWalker.php b/src/Core/Parsing/StringWalker.php index b4151512..30665a56 100644 --- a/src/Core/Parsing/StringWalker.php +++ b/src/Core/Parsing/StringWalker.php @@ -140,21 +140,20 @@ class StringWalker implements ParserInterface { protected function prepareChunk(StreamInterface $stream) { if (!$this->firstRun && is_null($this->shaved)) { $this->shaved = ''; - return true; - } elseif (is_null($this->shaved)) { + } + if (is_null($this->shaved)) { $this->shaved = ''; } $newChunk = $stream->getChunk(); - if ($newChunk !== false) { $this->chunk .= $newChunk; - return true; - } elseif ((trim($this->chunk) !== '') && ($this->chunk !== $this->lastChunk)) { - $this->lastChunk = $this->chunk; + } + if ((trim($this->chunk) !== '') && ($this->chunk !== $this->lastChunk)) { + $this->lastChunk = $this->chunk; return true; } diff --git a/src/Core/Parsing/UniqueNode.php b/src/Core/Parsing/UniqueNode.php index b027f868..883c9305 100644 --- a/src/Core/Parsing/UniqueNode.php +++ b/src/Core/Parsing/UniqueNode.php @@ -180,20 +180,14 @@ class UniqueNode implements ParserInterface { $chunk = $stream->getChunk(); if ($chunk === false) { - if (($this->hasSearchedUntilPos === -1) && (0 < strlen($this->workingBlob))) { - return true; - } - - return false; - } else { - if (($this->nextAction === 0) && !$this->options['extractContainer']) { - $this->workingBlob = substr($this->workingBlob, -1 * strlen('<' . $this->options['uniqueNode'] . '>')) . $chunk; - } else { - $this->workingBlob .= $chunk; - } - - return true; + return ($this->hasSearchedUntilPos === -1) && ((string) $this->workingBlob !== ''); } + if (($this->nextAction === 0) && !$this->options['extractContainer']) { + $this->workingBlob = substr($this->workingBlob, -1 * strlen('<' . $this->options['uniqueNode'] . '>')) . $chunk; + } else { + $this->workingBlob .= $chunk; + } + return true; } /** diff --git a/src/Core/Process/Multithread.php b/src/Core/Process/Multithread.php index 21c3e317..055f52e1 100644 --- a/src/Core/Process/Multithread.php +++ b/src/Core/Process/Multithread.php @@ -29,7 +29,7 @@ class Multithread { public $error = []; /** @var Thread[]|null Активные потоки */ - public $thread = null; + public $thread; /** @var array Команды в работе */ public $commands = []; @@ -46,8 +46,7 @@ class Multithread { */ public function __construct(array $commands, int $sizePool = 0) { $this->hasPool = 0 < $sizePool; - if (!$this->hasPool) { - } else { + if ($this->hasPool) { $this->toExecuted = array_splice($commands, $sizePool); } $this->commands = $commands; @@ -79,8 +78,7 @@ class Multithread { $this->error[$key] .= @$this->thread[$key]->getError(); if ($this->thread[$key]->isActive()) { $this->output[$key] .= $this->thread[$key]->listen(); - if (!$this->thread[$key]->isBusy()) { - } else { + if ($this->thread[$key]->isBusy()) { $this->thread[$key]->close(); unset($this->commands[$key]); $this->launchNextInQueue(); @@ -98,7 +96,7 @@ class Multithread { /** * Запустить следующую команду из очереди * - * @return bool|void + * @return bool|null */ public function launchNextInQueue() { if (count($this->toExecuted) != 0) { @@ -110,5 +108,6 @@ class Multithread { } else { return true; } + return null; } } diff --git a/src/Core/Process/ProcessManager.php b/src/Core/Process/ProcessManager.php index 31440cb3..f838ad59 100644 --- a/src/Core/Process/ProcessManager.php +++ b/src/Core/Process/ProcessManager.php @@ -55,8 +55,6 @@ class ProcessManager { * @return bool */ public static function isRunning(int $pid, ?string $exe = null) { - $pid = (int) $pid; - if ($pid <= 0) { return false; } @@ -92,8 +90,6 @@ class ProcessManager { * @return bool */ public static function isNamedProcessRunning(int $pid, string $processName, int|string $identifier, string $exe = null) { - $pid = (int) $pid; - if ($pid <= 0) { return false; } @@ -136,8 +132,6 @@ class ProcessManager { * @return bool */ public static function isStreamRunning(int $pid, int $streamId) { - $pid = (int) $pid; - if ($pid <= 0) { return false; } @@ -162,12 +156,7 @@ class ProcessManager { $cmdline = (string) @file_get_contents('/proc/' . $pid . '/cmdline'); return strpos($cmdline, "\0remux\0") !== false && strpos($cmdline, '/' . $streamId . '_.m3u8') !== false; } - - if (strpos($exe, 'php') === 0) { - return true; - } - - return false; + return strpos($exe, 'php') === 0; } /** @@ -178,8 +167,6 @@ class ProcessManager { * segmenter / loopback relay), or null when it cannot be read. */ public static function producerKind(int $pid) { - $pid = (int) $pid; - if ($pid <= 0 || !self::procExists($pid) || !is_readable('/proc/' . $pid . '/exe')) { return null; } @@ -212,8 +199,6 @@ class ProcessManager { * @return array{ticks:int,rss:int,at:float,start:int}|null Null when the process is gone. */ public static function resourceSample(int $pid) { - $pid = (int) $pid; - if ($pid <= 1) { return null; } @@ -344,8 +329,6 @@ class ProcessManager { * @return bool */ public static function kill(int $pid, int $signal = 9) { - $pid = (int) $pid; - if ($pid <= 0) { return false; } @@ -373,8 +356,6 @@ class ProcessManager { * @return int Age in seconds, or -1 if it cannot be determined */ public static function getProcessAge(int $pid) { - $pid = (int) $pid; - if ($pid <= 0 || !self::procExists($pid)) { return -1; } @@ -388,7 +369,7 @@ class ProcessManager { $rAge = time() - $rStart; - return $rAge > 0 ? $rAge : 0; + return max($rAge, 0); } // ─────────────────────────────────────────────────────────── @@ -474,7 +455,7 @@ class ProcessManager { */ protected static function procExists(int $pid) { $now = microtime(true); - $key = (int) $pid; + $key = $pid; if (isset(self::$procCache[$key]) && ($now - self::$procCache[$key]['time']) < self::$cacheTtl) { return self::$procCache[$key]['exists']; @@ -511,7 +492,6 @@ class ProcessManager { * @return bool */ public static function isStreamAlive(int $pid, int|string $streamID) { - $pid = (int) $pid; if ($pid <= 1) { return false; } @@ -554,7 +534,6 @@ class ProcessManager { * @return bool */ public static function isMonitorAlive(int $pid, int|string $streamID, ?string $exe = null) { - $pid = (int) $pid; if ($pid <= 0) { return false; } diff --git a/src/Core/Process/Thread.php b/src/Core/Process/Thread.php index 032830e4..e03ecf2f 100644 --- a/src/Core/Process/Thread.php +++ b/src/Core/Process/Thread.php @@ -19,25 +19,25 @@ namespace XcVm\Core\Process; class Thread { /** @var resource|null proc_open handle */ - public $process = null; + public $process; /** @var array Pipes (stdin, stdout, stderr) */ - public $pipes = null; + public $pipes; /** @var string Внутренний буфер */ - public $buffer = null; + public $buffer; /** @var string Накопленный stdout */ - public $output = null; + public $output; /** @var string Накопленный stderr */ - public $error = null; + public $error; /** @var int Таймаут в секундах (0 = без ограничений) */ - public $timeout = null; + public $timeout; /** @var int Время запуска процесса */ - public $start_time = null; + public $start_time; /** * Initialize an empty process-thread state. diff --git a/src/Core/Proxy/ProxyArchiveUpdater.php b/src/Core/Proxy/ProxyArchiveUpdater.php index f69918cc..769d3afe 100644 --- a/src/Core/Proxy/ProxyArchiveUpdater.php +++ b/src/Core/Proxy/ProxyArchiveUpdater.php @@ -84,7 +84,7 @@ class ProxyArchiveUpdater { $rReachable = true; try { $rReleases = $this->repo->getReleases(); - if (!empty($rReleases) && GitHubReleases::isValidVersion((string) $rReleases[0])) { + if ($rReleases !== [] && GitHubReleases::isValidVersion((string) $rReleases[0])) { $rVersion = (string) $rReleases[0]; } } catch (\Throwable $e) { diff --git a/src/Core/Storage/DropboxClient.php b/src/Core/Storage/DropboxClient.php index ef046ea6..a4967c67 100644 --- a/src/Core/Storage/DropboxClient.php +++ b/src/Core/Storage/DropboxClient.php @@ -76,7 +76,7 @@ class DropboxClient { * @throws DropboxException */ public function SetUseCUrl(bool $use_it, array $curlOptions = []) { - if (!$use_it && !empty($curlOptions)) { + if (!$use_it && $curlOptions !== []) { throw new DropboxException('not using cURL but specified cURL options'); } @@ -193,7 +193,7 @@ class DropboxClient { $path = ''; } - $res = $this->apiCall('2/files/list_folder', compact('path', 'recursive', 'include_deleted')); + $res = $this->apiCall('2/files/list_folder', ['path' => $path, 'recursive' => $recursive, 'include_deleted' => $include_deleted]); $entries = $res->entries; while ($res->has_more) { @@ -227,7 +227,7 @@ class DropboxClient { $path = 'rev:' . $rev; } - return self::compatMeta($this->apiCall('2/files/get_metadata', compact('path', 'include_deleted'))); + return self::compatMeta($this->apiCall('2/files/get_metadata', ['path' => $path, 'include_deleted' => $include_deleted])); } /** @@ -256,7 +256,7 @@ class DropboxClient { $path = 'rev:' . $rev; } - $context = $this->createRequestContext($url, compact('path')); + $context = $this->createRequestContext($url, ['path' => $path]); $fh = @fopen($dest_path, 'wb'); if ($fh === false) { @@ -370,7 +370,7 @@ class DropboxClient { while (!feof($fh)) { $content = fread($fh, 2097152); - $this->apiCall('2/files/upload_session/append_v2', ['cursor' => compact('session_id', 'offset')], true, $content); + $this->apiCall('2/files/upload_session/append_v2', ['cursor' => ['session_id' => $session_id, 'offset' => $offset]], true, $content); $offset += strlen($content); unset($content); @@ -381,12 +381,10 @@ class DropboxClient { @fclose($fh); - return $this->apiCall('2/files/upload_session/finish', ['cursor' => compact('session_id', 'offset'), 'commit' => $commit_params], true); - } else { - $content = file_get_contents($src_file); - - return $this->apiCall('2/files/upload', $commit_params, true, $content); + return $this->apiCall('2/files/upload_session/finish', ['cursor' => ['session_id' => $session_id, 'offset' => $offset], 'commit' => $commit_params], true); } + $content = file_get_contents($src_file); + return $this->apiCall('2/files/upload', $commit_params, true, $content); } /** @@ -409,7 +407,7 @@ class DropboxClient { } $url = 'https://content.dropboxapi.com/2/files/get_thumbnail'; - $context = $this->createRequestContext($url, compact('path', 'size', 'format')); + $context = $this->createRequestContext($url, ['path' => $path, 'size' => $size, 'format' => $format]); $thumb = ($this->useCurl ? self::execCurlAndClose($context) : file_get_contents($url, false, $context)); if ($echo) { @@ -440,25 +438,23 @@ class DropboxClient { $expires = (time() + 14400) - 60; return $data->link; - } else { - try { + } + try { $url = $this->apiCall('2/sharing/create_shared_link_with_settings', [ 'path' => $path, 'settings' => ['requested_visibility' => 'public'] ]); - } catch (DropboxException $ex) { - if ($ex->getTag() == 'shared_link_already_exists') { - $publicLinks = array_filter($this->apiCall('2/sharing/list_shared_links', ['path' => $path])->links, function ($link) { - return ($link->{'.tag'} == 'file') && ($link->link_permissions->resolved_visibility->{'.tag'} == 'public'); - }); - $url = reset($publicLinks); - } else { - throw $ex; - } + } catch (DropboxException $ex) { + if ($ex->getTag() == 'shared_link_already_exists') { + $publicLinks = array_filter($this->apiCall('2/sharing/list_shared_links', ['path' => $path])->links, function ($link) { + return ($link->{'.tag'} == 'file') && ($link->link_permissions->resolved_visibility->{'.tag'} == 'public'); + }); + $url = reset($publicLinks); + } else { + throw $ex; } - - return $url->url; } + return $url->url; } /** @@ -468,7 +464,7 @@ class DropboxClient { * @return object Delta response (entries + new cursor). */ public function Delta(string $cursor) { - return $this->apiCall('2/files/list_folder/continue', array_merge(compact('cursor'), [])); + return $this->apiCall('2/files/list_folder/continue', ['cursor' => $cursor]); } /** @@ -479,7 +475,7 @@ class DropboxClient { * @return object Response containing the cursor. */ public function LatestCursor(string $path = '', bool $include_media_info = false) { - $res = $this->apiCall('2/files/list_folder/get_latest_cursor', compact('path', 'include_media_info')); + $res = $this->apiCall('2/files/list_folder/get_latest_cursor', ['path' => $path, 'include_media_info' => $include_media_info]); return $res->cursor; } @@ -494,7 +490,7 @@ class DropboxClient { public function GetRevisions(string $path, int $limit = 10) { $path = self::toPath($path); - return $this->apiCall('2/files/list_revisions', compact('path', 'limit'))->entries; + return $this->apiCall('2/files/list_revisions', ['path' => $path, 'limit' => $limit])->entries; } /** @@ -509,7 +505,7 @@ class DropboxClient { $dropbox_file = $dropbox_file->path; } - return $this->apiCall('restore/' . $this->rootPath . '/' . $dropbox_file, compact('rev')); + return $this->apiCall('restore/' . $this->rootPath . '/' . $dropbox_file, ['rev' => $rev]); } /** @@ -526,7 +522,7 @@ class DropboxClient { $mode = ($include_deleted ? 'deleted_filename' : 'filename'); $meta = []; - foreach ($this->apiCall('2/files/search', compact('path', 'query', 'max_results', 'mode'))->matches as $match) { + foreach ($this->apiCall('2/files/search', ['path' => $path, 'query' => $query, 'max_results' => $max_results, 'mode' => $mode])->matches as $match) { $meta[] = self::compatMeta($match->metadata); } @@ -653,11 +649,10 @@ class DropboxClient { /** * cURL header callback that collects response headers. * - * @param \CurlHandle|resource $ch cURL handle. * @param string $header A single response header line. * @return int Number of bytes processed (required by cURL). */ - private static function _curlHeaderCallback($ch, string $header) { + private static function _curlHeaderCallback(string $header) { self::$_curlHeadersRef[] = trim($header); return strlen($header); @@ -855,7 +850,7 @@ class DropboxClient { $file_or_path = '/' . trim($file_or_path, '/'); if ($file_or_path == '/') { - $file_or_path = ''; + return ''; } return $file_or_path; diff --git a/src/Core/Updates/GitHubReleases.php b/src/Core/Updates/GitHubReleases.php index 0a02da01..de45b676 100644 --- a/src/Core/Updates/GitHubReleases.php +++ b/src/Core/Updates/GitHubReleases.php @@ -32,7 +32,7 @@ class GitHubReleases { private $cache_file = '/home/xc_vm/tmp/gitapi'; // Cache file path - private string $channel = 'stable'; // 'stable' or 'beta' ('unstable' accepted as a legacy alias) + private string $channel; // 'stable' or 'beta' ('unstable' accepted as a legacy alias) private $hash_file = 'hashes.md5'; @@ -49,7 +49,7 @@ class GitHubReleases { public function __construct(string $owner, string $repo, ?string $channel = 'stable', ?string $token = null) { $this->owner = $owner; $this->repo = $repo; - $this->channel = self::normalizeChannel($channel); + $this->channel = $this->normalizeChannel($channel); $this->cache_file = "{$this->cache_file}_{$repo}_{$this->channel}"; // Уникальный кэш для канала $this->api_url = "https://api.github.com/repos/{$owner}/{$repo}/releases"; $this->headers = $token ? [ @@ -66,7 +66,7 @@ class GitHubReleases { * @param string|null $channel Raw channel value (e.g. from settings) * @return string 'stable' or 'beta' */ - private static function normalizeChannel(?string $channel): string { + private function normalizeChannel(?string $channel): string { $channel = ($channel === 'unstable') ? 'beta' : (string) $channel; return in_array($channel, ['stable', 'beta'], true) ? $channel : 'stable'; } @@ -143,11 +143,10 @@ class GitHubReleases { fclose($file); error_log("Cache saved to {$this->cache_file}"); return true; - } else { - error_log("Failed to acquire lock on cache file {$this->cache_file}"); - fclose($file); - return false; } + error_log("Failed to acquire lock on cache file {$this->cache_file}"); + fclose($file); + return false; } /** @@ -208,7 +207,7 @@ class GitHubReleases { public function getLatestVersion(string $current_version): ?string { $releases = $this->getReleases(); - if (empty($releases)) { + if ($releases === []) { return null; } @@ -380,8 +379,6 @@ class GitHubReleases { $update_file = "xc_vm.tar.gz"; break; case "lb": - $update_file = "loadbalancer.tar.gz"; - break; case "lb_update": $update_file = "loadbalancer.tar.gz"; break; @@ -394,9 +391,7 @@ class GitHubReleases { } $upd_archive_url = "https://github.com/{$this->owner}/{$this->repo}/releases/download/{$target_version}/{$update_file}"; $hash_md5 = $this->getAssetHash($target_version, $update_file); - - $data = ["url" => $upd_archive_url, "md5" => $hash_md5]; - return $data; + return ["url" => $upd_archive_url, "md5" => $hash_md5]; } /** @@ -485,7 +480,6 @@ class GitHubReleases { * * @param string $version Release tag. * @param string $asset Asset filename. - * @return string */ public function assetUrl(string $version, string $asset): string { return "https://github.com/{$this->owner}/{$this->repo}/releases/download/{$version}/{$asset}"; diff --git a/src/Core/Util/AdminHelpers.php b/src/Core/Util/AdminHelpers.php index 5d05e172..85cb27c7 100644 --- a/src/Core/Util/AdminHelpers.php +++ b/src/Core/Util/AdminHelpers.php @@ -57,7 +57,7 @@ class AdminHelpers { public static function overwriteData(array $rData, array $rOverwrite, array $rSkip = []) { foreach ($rOverwrite as $rKey => $rValue) { if (array_key_exists($rKey, $rData) && !in_array($rKey, $rSkip)) { - if (!(empty($rValue) && is_null($rData[$rKey]))) { + if (!empty($rValue) || !is_null($rData[$rKey])) { $rData[$rKey] = $rValue; } } @@ -154,7 +154,7 @@ class AdminHelpers { * @return array Reordered array. */ public static function sortArrayByArray(array $rArray, array $rSort) { - if (empty($rArray) || empty($rSort)) { + if ($rArray === [] || $rSort === []) { return []; } @@ -195,14 +195,11 @@ class AdminHelpers { * @return string e.g. "02d 03h 04m" or "03h 04m 05s". */ public static function formatUptime(int $rUptime) { - $rUptime = (int) $rUptime; if (86400 <= $rUptime) { - $rUptime = sprintf('%02dd %02dh %02dm', intdiv($rUptime, 86400), intdiv($rUptime, 3600) % 24, intdiv($rUptime, 60) % 60); - } else { - $rUptime = sprintf('%02dh %02dm %02ds', intdiv($rUptime, 3600), intdiv($rUptime, 60) % 60, $rUptime % 60); + return sprintf('%02dd %02dh %02dm', intdiv($rUptime, 86400), intdiv($rUptime, 3600) % 24, intdiv($rUptime, 60) % 60); } - return $rUptime; + return sprintf('%02dh %02dm %02ds', intdiv($rUptime, 3600), intdiv($rUptime, 60) % 60, $rUptime % 60); } /** @@ -253,7 +250,7 @@ class AdminHelpers { } } catch (\Exception $e) { date_default_timezone_set($original_timezone); - throw new \RuntimeException('Error processing timezone list: ' . $e->getMessage()); + throw new \RuntimeException('Error processing timezone list: ' . $e->getMessage(), $e->getCode(), $e); } date_default_timezone_set($original_timezone); diff --git a/src/Core/Util/Encryption.php b/src/Core/Util/Encryption.php index 7347b987..6918dc77 100644 --- a/src/Core/Util/Encryption.php +++ b/src/Core/Util/Encryption.php @@ -83,7 +83,7 @@ class Encryption { public static function seal(string $data, string $key, string $deviceId) { $rNonce = random_bytes(self::SEAL_NONCE); $rTag = ''; - $rCipher = openssl_encrypt((string) $data, 'aes-256-gcm', self::sealKey($key, $deviceId), OPENSSL_RAW_DATA, $rNonce, $rTag, '', self::SEAL_TAG); + $rCipher = openssl_encrypt($data, 'aes-256-gcm', self::sealKey($key, $deviceId), OPENSSL_RAW_DATA, $rNonce, $rTag, '', self::SEAL_TAG); return self::base64urlEncode($rNonce . $rCipher . $rTag); } diff --git a/src/Core/Util/GeoIP.php b/src/Core/Util/GeoIP.php index 44b7558f..bff14c00 100644 --- a/src/Core/Util/GeoIP.php +++ b/src/Core/Util/GeoIP.php @@ -24,7 +24,7 @@ namespace XcVm\Core\Util; class GeoIP { /** @var string Cache directory for GeoIP lookups */ - protected static $cachePath = null; + protected static $cachePath; /** * Get ISP information for an IP address diff --git a/src/Core/Util/ImageUtils.php b/src/Core/Util/ImageUtils.php index ec6817c2..a4dad8e0 100644 --- a/src/Core/Util/ImageUtils.php +++ b/src/Core/Util/ImageUtils.php @@ -127,7 +127,7 @@ class ImageUtils { * @return string Internal `s:` reference, or the original URL. */ public static function downloadImage(string $rImage, ?int $rType = null) { - if (0 < strlen($rImage) && substr(strtolower($rImage), 0, 4) == 'http') { + if ($rImage !== '' && substr(strtolower($rImage), 0, 4) == 'http') { $rPathInfo = pathinfo(parse_url($rImage, PHP_URL_PATH) ?: $rImage); $rExt = strtolower($rPathInfo['extension'] ?? ''); if (!$rExt) { @@ -158,7 +158,7 @@ class ImageUtils { curl_setopt($rCurl, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($rCurl, CURLOPT_TIMEOUT, 5); $rData = curl_exec($rCurl); - if (strlen($rData) > 0) { + if ((string) $rData !== '') { $rPath = IMAGES_PATH . $rFilename . '.' . $rExt; // The images cache dir may not exist yet on a given node (e.g. an // LB running the watch import), so file_put_contents would fail @@ -196,8 +196,8 @@ class ImageUtils { $heightRatio = $maxHeight / (($origHeight ?: 1)); $ratio = min($widthRatio, $heightRatio); if ($ratio < 1) { - $newWidth = (int) $origWidth * $ratio; - $newHeight = (int) $origHeight * $ratio; + $newWidth = $origWidth * $ratio; + $newHeight = $origHeight * $ratio; } else { $newHeight = $origHeight; $newWidth = $origWidth; diff --git a/src/Core/Util/NetworkUtils.php b/src/Core/Util/NetworkUtils.php index c539a636..3edb2002 100644 --- a/src/Core/Util/NetworkUtils.php +++ b/src/Core/Util/NetworkUtils.php @@ -47,7 +47,6 @@ class NetworkUtils { * @param bool $rSubnetMatch Compare only the leading three octets. * @param string|null $rTargetIP Stored / other IP. * @param string|null $rClientIP Current client IP. - * @return bool */ public static function ipMatches(bool $rSubnetMatch, ?string $rTargetIP, ?string $rClientIP): bool { if ($rSubnetMatch) { @@ -181,19 +180,16 @@ class NetworkUtils { $rFloodRow[$rType] = $rActive; } $rAllow = false; - if (count($rFloodRow[$rType]) >= $rFloodLimit) { - } else { + if (count($rFloodRow[$rType]) < $rFloodLimit) { $rFloodRow[$rType][] = $rDownloadPID; $rAllow = true; } file_put_contents($rFile, json_encode($rFloodRow), LOCK_EX); return $rAllow; - } else { - return true; } - } else { return true; } + return true; } /** @@ -212,8 +208,7 @@ class NetworkUtils { if (file_exists($rFile)) { $rFloodRow[$rType] = []; foreach (json_decode(file_get_contents($rFile), true)[$rType] as $rPID) { - if (!(ProcessManager::isRunning($rPID, 'php-fpm') && $rPID != $rDownloadPID)) { - } else { + if (ProcessManager::isRunning($rPID, 'php-fpm') && $rPID != $rDownloadPID) { $rFloodRow[$rType][] = $rPID; } } diff --git a/src/Core/Util/StreamUtils.php b/src/Core/Util/StreamUtils.php index 96a40d56..cc3e05c3 100644 --- a/src/Core/Util/StreamUtils.php +++ b/src/Core/Util/StreamUtils.php @@ -30,22 +30,18 @@ class StreamUtils { if (strtolower($rKey) == 'path') { $rPath = true; } else { - if (strtolower($rKey) != 'domain') { - } else { + if (strtolower($rKey) == 'domain') { $rDomain = true; } } } - if (!substr($rCookie, -1) != ';') { - } else { + if (!substr($rCookie, -1) == ';') { $rCookie .= ';'; } - if ($rPath) { - } else { + if (!$rPath) { $rCookie .= 'path=/;'; } - if ($rDomain) { - } else { + if (!$rDomain) { $rCookie .= 'domain=;'; } return $rCookie; @@ -61,17 +57,15 @@ class StreamUtils { */ public static function getArguments(array $rArguments, ?string $rProtocol, mixed $rType) { $rReturn = []; - if (!empty($rArguments)) { - foreach ($rArguments as $rArgument_id => $rArgument) { - if ($rArgument['argument_cat'] == $rType && (is_null($rArgument['argument_wprotocol']) || stristr($rProtocol, $rArgument['argument_wprotocol']) || is_null($rProtocol))) { - if ($rArgument['argument_key'] == 'cookie') { - $rArgument['value'] = self::fixCookie($rArgument['value']); - } - if ($rArgument['argument_type'] == 'text') { - $rReturn[] = sprintf($rArgument['argument_cmd'], $rArgument['value']); - } else { - $rReturn[] = $rArgument['argument_cmd']; - } + foreach ($rArguments as $rArgument) { + if ($rArgument['argument_cat'] == $rType && (is_null($rArgument['argument_wprotocol']) || stristr($rProtocol, $rArgument['argument_wprotocol']) || is_null($rProtocol))) { + if ($rArgument['argument_key'] == 'cookie') { + $rArgument['value'] = self::fixCookie($rArgument['value']); + } + if ($rArgument['argument_type'] == 'text') { + $rReturn[] = sprintf($rArgument['argument_cmd'], $rArgument['value']); + } else { + $rReturn[] = $rArgument['argument_cmd']; } } } @@ -90,7 +84,7 @@ class StreamUtils { public static function parseTranscode(array $rArgs) { $rFitlerComplex = []; foreach ($rArgs as $rKey => $rArgument) { - if (!($rKey == 'gpu' || $rKey == 'software_decoding' || $rKey == '16')) { + if (!(in_array($rKey, ['gpu', 'software_decoding', '16']))) { if (isset($rArgument['cmd'])) { $rArgs[$rKey] = $rArgument = $rArgument['cmd']; } @@ -100,7 +94,7 @@ class StreamUtils { } } } - if (!empty($rFitlerComplex)) { + if ($rFitlerComplex !== []) { $rArgs[] = '-filter_complex "' . implode(',', $rFitlerComplex) . '"'; } $rNewArgs = []; @@ -169,7 +163,7 @@ class StreamUtils { * @return bool */ public static function needsResolver(string $rURL) { - if (strtolower(substr((string) $rURL, 0, 4)) !== 'http') { + if (strtolower(substr($rURL, 0, 4)) !== 'http') { return false; } $rHost = str_ireplace('www.', '', (string) parse_url($rURL, PHP_URL_HOST)); @@ -187,11 +181,9 @@ class StreamUtils { $rPathSize = count(explode('/', $rPath)); $rRegex = ['/\\/auth\\/(.*)$/m' => 3, '/\\/play\\/(.*)$/m' => 3, '/\\/play\\/(.*)\\/(.*)$/m' => 4, '/\\/live\\/(.*)\\/(\\d+)$/m' => 4, '/\\/live\\/(.*)\\/(\\d+)\\.(.*)$/m' => 4, '/\\/(.*)\\/(.*)\\/(\\d+)\\.(.*)$/m' => 4, '/\\/(.*)\\/(.*)\\/(\\d+)$/m' => 4, '/\\/live\\/(.*)\\/(.*)\\/(\\d+)\\.(.*)$/m' => 5, '/\\/live\\/(.*)\\/(.*)\\/(\\d+)$/m' => 5]; foreach ($rRegex as $rQuery => $rCount) { - if ($rPathSize != $rCount) { - } else { + if ($rPathSize == $rCount) { preg_match($rQuery, $rPath, $rMatches); - if (0 >= count($rMatches)) { - } else { + if (0 < count($rMatches)) { return true; } } @@ -208,11 +200,9 @@ class StreamUtils { * @return array|string|null Segment list, current segment id, or null if missing. */ public static function getPlaylistSegments(string $rPlaylist, int $rPrebuffer = 0, int $rSegmentDuration = 10) { - if (!file_exists($rPlaylist)) { - } else { + if (file_exists($rPlaylist)) { $rSource = file_get_contents($rPlaylist); - if (!preg_match_all('/(.*?).ts/', $rSource, $rMatches)) { - } else { + if (preg_match_all('/(.*?).ts/', $rSource, $rMatches)) { if (0 < $rPrebuffer) { $rTotalSegments = intval($rPrebuffer / (($rSegmentDuration ?: 1))); return array_slice($rMatches[0], -1 * $rTotalSegments); @@ -237,11 +227,9 @@ class StreamUtils { * @return string|false Rewritten playlist text, or false if unavailable. */ public static function generateAdminHLS(string $rM3U8, string $rPassword, int $rStreamID, string $rUIToken) { - if (!file_exists($rM3U8)) { - } else { + if (file_exists($rM3U8)) { $rSource = file_get_contents($rM3U8); - if (!preg_match_all('/(.*?)\\.ts/', $rSource, $rMatches)) { - } else { + if (preg_match_all('/(.*?)\\.ts/', $rSource, $rMatches)) { foreach ($rMatches[0] as $rMatch) { if ($rUIToken) { $rSource = str_replace($rMatch, '/admin/live?extension=m3u8&segment=' . $rMatch . '&uitoken=' . $rUIToken, $rSource); @@ -385,7 +373,7 @@ class StreamUtils { * @return string */ public static function sanitizeSegmentName(string $rRawSegment) { - return str_replace(['\\', '/'], '', urldecode((string) $rRawSegment)); + return str_replace(['\\', '/'], '', urldecode($rRawSegment)); } /** @@ -407,7 +395,7 @@ class StreamUtils { 'ts' => 'video/mp2t', ]; - return $rMap[(string) $rContainer] ?? 'application/octet-stream'; + return $rMap[$rContainer] ?? 'application/octet-stream'; } /** @@ -421,13 +409,13 @@ class StreamUtils { return (int) $rStartDate; } - if (substr_count((string) $rStartDate, '-') == 1) { - list($rDate, $rHour) = explode('-', (string) $rStartDate); + if (substr_count($rStartDate, '-') == 1) { + list($rDate, $rHour) = explode('-', $rStartDate); return (int) mktime((int) $rHour, 0, 0, (int) substr($rDate, 4, 2), (int) substr($rDate, 6, 2), (int) substr($rDate, 0, 4)); } - list($rDate, $rTime) = explode(':', (string) $rStartDate); + list($rDate, $rTime) = explode(':', $rStartDate); list($rYear, $rMonth, $rDay) = explode('-', $rDate); list($rHour, $rMinutes) = explode('-', $rTime); @@ -443,6 +431,6 @@ class StreamUtils { * @return int */ public static function segmentRetryBudget(int $rSegTimeSeconds, int $rConfiguredWaitSeconds) { - return max((int) $rSegTimeSeconds * 2, (int) $rConfiguredWaitSeconds ?: 20); + return max($rSegTimeSeconds * 2, $rConfiguredWaitSeconds ?: 20); } } diff --git a/src/Core/Util/SystemInfo.php b/src/Core/Util/SystemInfo.php index e2241d74..4f876510 100644 --- a/src/Core/Util/SystemInfo.php +++ b/src/Core/Util/SystemInfo.php @@ -78,8 +78,8 @@ class SystemInfo { $rJSON['network_speed'] = $NetSpeed; } } - $rJSON['bytes_sent_total'] = (intval(trim(file_get_contents('/sys/class/net/' . $rInterface . '/statistics/tx_bytes'))) ?: 0); - $rJSON['bytes_received_total'] = (intval(trim(file_get_contents('/sys/class/net/' . $rInterface . '/statistics/tx_bytes'))) ?: 0); + $rJSON['bytes_sent_total'] = (intval(trim(file_get_contents('/sys/class/net/' . $rInterface . '/statistics/tx_bytes')))); + $rJSON['bytes_received_total'] = (intval(trim(file_get_contents('/sys/class/net/' . $rInterface . '/statistics/tx_bytes')))); $rJSON['bytes_sent'] += $rData['out_bytes']; $rJSON['bytes_received'] += $rData['in_bytes']; } @@ -171,7 +171,7 @@ class SystemInfo { * @return string e.g., "5d 3h 12m 4s" */ public static function getUptime() { - if (!(file_exists('/proc/uptime') && is_readable('/proc/uptime'))) { + if (!file_exists('/proc/uptime') || !is_readable('/proc/uptime')) { return ''; } $tmp = explode(' ', file_get_contents('/proc/uptime')); @@ -189,8 +189,7 @@ class SystemInfo { @exec('ls /sys/class/net/', $rOutput, $rReturnVar); foreach ($rOutput as $rInterface) { $rInterface = trim(rtrim($rInterface, ':')); - if (!($rInterface != 'lo' && substr($rInterface, 0, 4) != 'bond')) { - } else { + if ($rInterface != 'lo' && substr($rInterface, 0, 4) != 'bond') { $rReturn[] = $rInterface; } } @@ -208,7 +207,7 @@ class SystemInfo { if (file_exists(LOGS_TMP_PATH . 'network')) { $rNetwork = json_decode(file_get_contents(LOGS_TMP_PATH . 'network'), true); foreach ((is_array($rNetwork) ? $rNetwork : []) as $rLine) { - if (!($rInterface && $rLine[0] != $rInterface) && !($rLine[0] == 'lo' || !$rInterface && substr($rLine[0], 0, 4) == 'bond')) { + if ((!$rInterface || $rLine[0] == $rInterface) && ($rLine[0] != 'lo' && ($rInterface || substr($rLine[0], 0, 4) != 'bond'))) { $rReturn[$rLine[0]] = ['in_bytes' => intval($rLine[1] / 2), 'in_packets' => $rLine[2], 'in_errors' => $rLine[3], 'out_bytes' => intval($rLine[4] / 2), 'out_packets' => $rLine[5], 'out_errors' => $rLine[6]]; } } @@ -279,14 +278,11 @@ class SystemInfo { $rOutput = []; @exec('nvidia-smi -x -q', $rOutput, $rReturnVar); $rOutput = implode('', $rOutput); - if (stripos($rOutput, ' $rJSON['attached_gpus'], 'driver_version' => $rJSON['driver_version'], 'cuda_version' => $rJSON['cuda_version'], 'gpus' => []]; - if (!isset($rJSON['gpu']['board_id'])) { - } else { + if (isset($rJSON['gpu']['board_id'])) { $rJSON['gpu'] = [$rJSON['gpu']]; } foreach ($rJSON['gpu'] as $rInstance) { diff --git a/src/Domain/Bouquet/BouquetService.php b/src/Domain/Bouquet/BouquetService.php index 8b09f678..1e939287 100644 --- a/src/Domain/Bouquet/BouquetService.php +++ b/src/Domain/Bouquet/BouquetService.php @@ -369,8 +369,7 @@ class BouquetService { foreach ($db->get_rows() as $rRow) { $rRow['bouquet'] = json_decode($rRow['bouquet'], true); - if (($rKey = array_search($rID, $rRow['bouquet'])) === false) { - } else { + if (($rKey = array_search($rID, $rRow['bouquet'])) !== false) { unset($rRow['bouquet'][$rKey]); } @@ -382,8 +381,7 @@ class BouquetService { foreach ($db->get_rows() as $rRow) { $rRow['bouquets'] = json_decode($rRow['bouquets'], true); - if (($rKey = array_search($rID, $rRow['bouquets'])) === false) { - } else { + if (($rKey = array_search($rID, $rRow['bouquets'])) !== false) { unset($rRow['bouquets'][$rKey]); } @@ -393,7 +391,7 @@ class BouquetService { // Notify modules (e.g. watch) so they drop the bouquet from their own // data — keeps core bouquet deletion free of module-owned tables. - EventDispatcher::dispatch(new BouquetDeletedEvent((int) $rID)); + EventDispatcher::dispatch(new BouquetDeletedEvent($rID)); self::scan(); return true; @@ -434,8 +432,7 @@ class BouquetService { $rChannels = AdminHelpers::confirmIDs(json_decode($rBouquet[$rColumn], true)); foreach ($rIDs as $rID) { - if (0 >= intval($rID) || in_array($rID, $rChannels)) { - } else { + if (0 < intval($rID) && !in_array($rID, $rChannels)) { $rChannels[] = $rID; $rChanged = true; } @@ -481,8 +478,7 @@ class BouquetService { $rChannels = AdminHelpers::confirmIDs(json_decode($rBouquet[$rColumn], true)); foreach ($rIDs as $rID) { - if (($rKey = array_search($rID, $rChannels)) === false) { - } else { + if (($rKey = array_search($rID, $rChannels)) !== false) { unset($rChannels[$rKey]); $rChanged = true; } diff --git a/src/Domain/Device/EnigmaService.php b/src/Domain/Device/EnigmaService.php index c0c3faba..aa5dd180 100644 --- a/src/Domain/Device/EnigmaService.php +++ b/src/Domain/Device/EnigmaService.php @@ -56,8 +56,7 @@ class EnigmaService { $rUserArray = []; foreach (['is_isplock', 'is_trial'] as $rItem) { - if (!isset($rData['c_' . $rItem])) { - } else { + if (isset($rData['c_' . $rItem])) { if (isset($rData[$rItem])) { $rUserArray[$rItem] = 1; } else { @@ -66,33 +65,27 @@ class EnigmaService { } } - if (!isset($rData['c_admin_notes'])) { - } else { + if (isset($rData['c_admin_notes'])) { $rUserArray['admin_notes'] = $rData['admin_notes']; } - if (!isset($rData['c_reseller_notes'])) { - } else { + if (isset($rData['c_reseller_notes'])) { $rUserArray['reseller_notes'] = $rData['reseller_notes']; } - if (!isset($rData['c_forced_country'])) { - } else { + if (isset($rData['c_forced_country'])) { $rUserArray['forced_country'] = $rData['forced_country']; } - if (!isset($rData['c_member_id'])) { - } else { + if (isset($rData['c_member_id'])) { $rUserArray['member_id'] = intval($rData['member_id']); } - if (!isset($rData['c_force_server_id'])) { - } else { + if (isset($rData['c_force_server_id'])) { $rUserArray['force_server_id'] = intval($rData['force_server_id']); } - if (!isset($rData['c_exp_date'])) { - } else { + if (isset($rData['c_exp_date'])) { if (isset($rData['no_expire'])) { $rUserArray['exp_date'] = null; } else { @@ -104,13 +97,10 @@ class EnigmaService { } } - if (!isset($rData['c_bouquets'])) { - } else { + if (isset($rData['c_bouquets'])) { $rUserArray['bouquet'] = []; - foreach (json_decode($rData['bouquets_selected'], true) as $rBouquet) { - if (!is_numeric($rBouquet)) { - } else { + if (is_numeric($rBouquet)) { $rUserArray['bouquet'][] = $rBouquet; } } @@ -118,14 +108,12 @@ class EnigmaService { $rUserArray['bouquet'] = '[' . implode(',', array_map('intval', $rUserArray['bouquet'])) . ']'; } - if (!isset($rData['reset_isp_lock'])) { - } else { + if (isset($rData['reset_isp_lock'])) { $rUserArray['isp_desc'] = ''; $rUserArray['as_number'] = $rUserArray['isp_desc']; } - if (!isset($rData['reset_device_lock'])) { - } else { + if (isset($rData['reset_device_lock'])) { $rArray['token'] = ''; $rArray['lversion'] = $rArray['token']; $rArray['cpu'] = $rArray['lversion']; @@ -139,43 +127,31 @@ class EnigmaService { foreach ($rDevices as $rDevice) { $rDeviceInfo = self::getById($rDevice); - if (!$rDeviceInfo) { - } else { - if (0 >= count($rArray)) { - } else { + if ($rDeviceInfo) { + if (0 < count($rArray)) { $rPrepare = QueryHelper::prepareArray($rArray); - - if (0 >= count($rPrepare['data'])) { - } else { + if (0 < count($rPrepare['data'])) { $rPrepare['data'][] = $rDevice; $rQuery = 'UPDATE `enigma2_devices` SET ' . $rPrepare['update'] . ' WHERE `device_id` = ?;'; $db->query($rQuery, ...$rPrepare['data']); } } - - if (0 >= count($rUserArray)) { - } else { + if (0 < count($rUserArray)) { $rUserIDs = []; - - if (!isset($rDeviceInfo['user']['id'])) { - } else { + if (isset($rDeviceInfo['user']['id'])) { $rUserIDs[] = $rDeviceInfo['user']['id']; } - - if (!isset($rDeviceInfo['user']['paired'])) { - } else { + if (isset($rDeviceInfo['user']['paired'])) { $rUserIDs[] = $rDeviceInfo['paired']['id']; } - foreach ($rUserIDs as $rUserID) { $rPrepare = QueryHelper::prepareArray($rUserArray); - if (0 >= count($rPrepare['data'])) { - } else { + if (0 < count($rPrepare['data'])) { $rPrepare['data'][] = $rUserID; $rQuery = 'UPDATE `lines` SET ' . $rPrepare['update'] . ' WHERE `id` = ?;'; $db->query($rQuery, ...$rPrepare['data']); - LineService::updateLineSignal($rUserID); + LineService::updateLineSignal($rUserID); } } } @@ -183,9 +159,8 @@ class EnigmaService { } return ['status' => STATUS_SUCCESS]; - } else { - return ['status' => STATUS_INVALID_INPUT, 'data' => $rData]; } + return ['status' => STATUS_INVALID_INPUT, 'data' => $rData]; } /** @@ -223,18 +198,15 @@ class EnigmaService { } } - if (strlen($rUserArray['username']) != 0) { - } else { + if (strlen($rUserArray['username']) == 0) { $rUserArray['username'] = AdminHelpers::generateString(32); } - if (strlen($rUserArray['password']) != 0) { - } else { + if (strlen($rUserArray['password']) == 0) { $rUserArray['password'] = AdminHelpers::generateString(32); } - if (strlen($rData['isp_clear']) != 0) { - } else { + if (strlen($rData['isp_clear']) == 0) { $rUserArray['isp_desc'] = ''; $rUserArray['as_number'] = null; } @@ -266,8 +238,7 @@ class EnigmaService { $rUserArray['bouquet'] = '[' . implode(',', array_map('intval', $rUserArray['bouquet'])) . ']'; if (isset($rData['exp_date']) && !isset($rData['no_expire'])) { - if (!(0 < strlen($rData['exp_date']) && $rData['exp_date'] != '1970-01-01')) { - } else { + if ((string) $rData['exp_date'] !== '' && $rData['exp_date'] != '1970-01-01') { try { $rDate = new \DateTime($rData['exp_date']); $rUserArray['exp_date'] = $rDate->format('U'); @@ -279,14 +250,12 @@ class EnigmaService { $rUserArray['exp_date'] = null; } - if ($rUserArray['member_id']) { - } else { + if (!$rUserArray['member_id']) { $rUserArray['member_id'] = $GLOBALS['rAdminUserInfo']['id']; } if (isset($rData['allowed_ips'])) { - if (is_array($rData['allowed_ips'])) { - } else { + if (!is_array($rData['allowed_ips'])) { $rData['allowed_ips'] = [$rData['allowed_ips']]; } @@ -305,12 +274,9 @@ class EnigmaService { $rDevice = $rArray; $rDevice['user'] = $rUserArray; - if (0 >= $rDevice['user']['pair_id']) { - } else { + if (0 < $rDevice['user']['pair_id']) { $rUserCheck = UserRepository::getLineById($rDevice['user']['pair_id']); - - if ($rUserCheck) { - } else { + if (!$rUserCheck) { return ['status' => STATUS_INVALID_USER, 'data' => $rData]; } } @@ -327,13 +293,11 @@ class EnigmaService { $rQuery = 'REPLACE INTO `lines`(' . $rPrepare['columns'] . ') VALUES(' . $rPrepare['placeholder'] . ');'; - if (!$db->query($rQuery, ...$rPrepare['data'])) { - } else { + if ($db->query($rQuery, ...$rPrepare['data'])) { $rInsertID = $db->last_insert_id(); $rArray['user_id'] = $rInsertID; LineService::updateLineSignal($rArray['user_id']); - if (isset($rData['edit'])) { - } else { + if (!isset($rData['edit'])) { $rArray['token'] = ''; $rArray['lversion'] = $rArray['token']; $rArray['cpu'] = $rArray['lversion']; @@ -341,24 +305,19 @@ class EnigmaService { $rArray['local_ip'] = $rArray['enigma_version']; $rArray['modem_mac'] = $rArray['local_ip']; } - $rPrepare = QueryHelper::prepareArray($rArray); $rQuery = 'REPLACE INTO `enigma2_devices`(' . $rPrepare['columns'] . ') VALUES(' . $rPrepare['placeholder'] . ');'; - if ($db->query($rQuery, ...$rPrepare['data'])) { $rInsertID = $db->last_insert_id(); - if (0 >= $rDevice['user']['pair_id']) { - } else { + if (0 < $rDevice['user']['pair_id']) { MagService::syncLineDevices($rDevice['user']['pair_id'], $rInsertID); - LineService::updateLineSignal($rDevice['user']['pair_id']); + LineService::updateLineSignal($rDevice['user']['pair_id']); } return ['status' => STATUS_SUCCESS, 'data' => ['insert_id' => $rInsertID]]; } - - if (isset($rData['edit'])) { - } else { + if (!isset($rData['edit'])) { $db->query('DELETE FROM `lines` WHERE `id` = ?;', $rInsertID); } } @@ -394,8 +353,7 @@ class EnigmaService { $db->query('SELECT `pair_id` FROM `lines` WHERE `id` = ?;', $rRow['user_id']); - if ($db->num_rows() != 1) { - } else { + if ($db->num_rows() == 1) { $rRow['paired'] = UserRepository::getLineById($rRow['user']['pair_id']); } @@ -439,8 +397,7 @@ class EnigmaService { $db->query('DELETE FROM `enigma2_devices` WHERE `device_id` = ?;', $rID); $db->query('DELETE FROM `enigma2_actions` WHERE `device_id` = ?;', $rID); - if (!$rEnigma['user']) { - } else { + if ($rEnigma['user']) { if ($rConvert) { $db->query('UPDATE `lines` SET `is_e2` = 0 WHERE `id` = ?;', $rEnigma['user']['id']); LineService::updateLineSignal($rEnigma['user']['id']); @@ -451,8 +408,7 @@ class EnigmaService { $db->query('SELECT `device_id` FROM `enigma2_devices` WHERE `user_id` = ?;', $rEnigma['user']['id']); $rCount += $db->num_rows(); - if ($rCount != 0) { - } else { + if ($rCount == 0) { LineService::deleteLineById($rEnigma['user']['id'], $rDeletePaired, $rCloseCons); } } @@ -484,8 +440,7 @@ class EnigmaService { $db->query('DELETE FROM `enigma2_devices` WHERE `device_id` IN (' . implode(',', $rIDs) . ');'); $db->query('DELETE FROM `enigma2_actions` WHERE `device_id` IN (' . implode(',', $rIDs) . ');'); - if (0 >= count($rUserIDs)) { - } else { + if (0 < count($rUserIDs)) { LineRepository::deleteMany($rUserIDs); } diff --git a/src/Domain/Device/MagService.php b/src/Domain/Device/MagService.php index 9caa218f..f2102e36 100644 --- a/src/Domain/Device/MagService.php +++ b/src/Domain/Device/MagService.php @@ -211,9 +211,8 @@ class MagService { } return ['status' => STATUS_SUCCESS]; - } else { - return ['status' => STATUS_INVALID_INPUT, 'data' => $rData]; } + return ['status' => STATUS_INVALID_INPUT, 'data' => $rData]; } /** @@ -292,7 +291,7 @@ class MagService { $rUserArray['bouquet'] = '[' . implode(',', array_map('intval', $rUserArray['bouquet'])) . ']'; if (isset($rData['exp_date']) && !isset($rData['no_expire'])) { - if (0 < strlen($rData['exp_date']) && $rData['exp_date'] != '1970-01-01') { + if ((string) $rData['exp_date'] !== '' && $rData['exp_date'] != '1970-01-01') { try { $rDate = new \DateTime($rData['exp_date']); $rUserArray['exp_date'] = $rDate->format('U'); @@ -451,8 +450,7 @@ class MagService { $rRow['user'] = UserRepository::getLineById($rRow['user_id']); $db->query('SELECT `pair_id` FROM `lines` WHERE `id` = ?;', $rRow['user_id']); - if ($db->num_rows() != 1) { - } else { + if ($db->num_rows() == 1) { $rRow['paired'] = UserRepository::getLineById($rRow['user']['pair_id']); } @@ -481,8 +479,7 @@ class MagService { $db->query('DELETE FROM `mag_events` WHERE `mag_device_id` = ?;', $rID); $db->query('DELETE FROM `mag_logs` WHERE `mag_id` = ?;', $rID); - if (!$rMag['user']) { - } else { + if ($rMag['user']) { if ($rConvert) { $db->query('UPDATE `lines` SET `is_mag` = 0 WHERE `id` = ?;', $rMag['user']['id']); LineService::updateLineSignal($rMag['user']['id']); @@ -493,8 +490,7 @@ class MagService { $db->query('SELECT `device_id` FROM `enigma2_devices` WHERE `user_id` = ?;', $rMag['user']['id']); $rCount += $db->num_rows(); - if ($rCount != 0) { - } else { + if ($rCount == 0) { LineService::deleteLineById($rMag['user']['id'], $rDeletePaired, $rCloseCons); } } @@ -528,8 +524,7 @@ class MagService { $db->query('DELETE FROM `mag_events` WHERE `mag_device_id` IN (' . implode(',', $rIDs) . ');'); $db->query('DELETE FROM `mag_logs` WHERE `mag_id` IN (' . implode(',', $rIDs) . ');'); - if (0 >= count($rUserIDs)) { - } else { + if (0 < count($rUserIDs)) { LineRepository::deleteMany($rUserIDs); } diff --git a/src/Domain/Epg/EPG.php b/src/Domain/Epg/EPG.php index a4c4f032..8c9f2414 100644 --- a/src/Domain/Epg/EPG.php +++ b/src/Domain/Epg/EPG.php @@ -210,7 +210,7 @@ class EPG { } $this->log("[EPG] Finished parseEPG() - collected $programCount programmes"); - return !empty($rInsertQuery) ? $rInsertQuery : false; + return $rInsertQuery !== [] ? $rInsertQuery : false; } /** @@ -238,10 +238,9 @@ class EPG { if (file_exists($rFilename) && filesize($rFilename) > 0) { $this->log("[EPG] Download successful: " . filesize($rFilename) . " bytes"); return true; - } else { - $this->log("[EPG] Download failed or file is empty: $rSource"); - return false; } + $this->log("[EPG] Download failed or file is empty: $rSource"); + return false; } /** diff --git a/src/Domain/Epg/EpgService.php b/src/Domain/Epg/EpgService.php index 3b9c2294..40d233e3 100644 --- a/src/Domain/Epg/EpgService.php +++ b/src/Domain/Epg/EpgService.php @@ -98,6 +98,7 @@ class EpgService { } } } + return null; } /** diff --git a/src/Domain/Line/ActiveCodeService.php b/src/Domain/Line/ActiveCodeService.php index 24161d5d..504f7bf8 100644 --- a/src/Domain/Line/ActiveCodeService.php +++ b/src/Domain/Line/ActiveCodeService.php @@ -76,7 +76,7 @@ class ActiveCodeService { } else { // Check for reseller custom package override $override = json_decode($user['override_packages'] ?? '', true) ?: []; - if (isset($override[$packageId]['official_credits']) && strlen((string) $override[$packageId]['official_credits']) > 0) { + if (isset($override[$packageId]['official_credits']) && (string) $override[$packageId]['official_credits'] !== '') { $costPerCode = floatval($override[$packageId]['official_credits']); } else { $costPerCode = floatval($package['official_credits'] ?? 0); @@ -434,13 +434,13 @@ class ActiveCodeService { public static function getRecentBatchNames(array $createdBy = [], int $limit = 100): array { $db = self::db(); $where = '`batch_name` IS NOT NULL'; - if (!empty($createdBy)) { + if ($createdBy !== []) { $where = '`created_by` IN (' . implode(',', array_map('intval', $createdBy)) . ') AND ' . $where; } return $db->fetchAll( 'SELECT DISTINCT `batch_name` FROM `activation_codes` WHERE ' . $where . ' - ORDER BY `created_at` DESC LIMIT ' . (int) $limit . ';' + ORDER BY `created_at` DESC LIMIT ' . $limit . ';' ); } @@ -458,7 +458,7 @@ class ActiveCodeService { */ public static function massAction(string $action, array $codeIds, array $user, bool $isAdmin, array $extra = []): array { $db = self::db(); - if (empty($codeIds)) { + if ($codeIds === []) { return ['status' => 'ERROR', 'message' => 'No codes selected.']; } @@ -482,7 +482,7 @@ class ActiveCodeService { $targetIds = array_column($codes, 'id'); $targetIdList = implode(',', $targetIds); $subscriberIds = array_filter(array_column($codes, 'subscriber_id')); - $subIdList = !empty($subscriberIds) ? implode(',', $subscriberIds) : '0'; + $subIdList = $subscriberIds !== [] ? implode(',', $subscriberIds) : '0'; switch ($action) { case 'mass_enable': @@ -585,7 +585,7 @@ class ActiveCodeService { $params[] = $batchName; } - $whereClause = !empty($where) ? ('WHERE ' . implode(' AND ', $where)) : ''; + $whereClause = $where !== [] ? ('WHERE ' . implode(' AND ', $where)) : ''; $sql = "SELECT `batch_name`, diff --git a/src/Domain/Security/BlocklistService.php b/src/Domain/Security/BlocklistService.php index e8f43636..cc6101ca 100644 --- a/src/Domain/Security/BlocklistService.php +++ b/src/Domain/Security/BlocklistService.php @@ -466,8 +466,7 @@ class BlocklistService { $rRow = $db->get_row(); $db->query('DELETE FROM `blocked_ips` WHERE `id` = ?;', $rID); - if (!file_exists(FLOOD_TMP_PATH . 'block_' . $rRow['ip'])) { - } else { + if (file_exists(FLOOD_TMP_PATH . 'block_' . $rRow['ip'])) { unlink(FLOOD_TMP_PATH . 'block_' . $rRow['ip']); } @@ -545,8 +544,7 @@ class BlocklistService { $rReturn = []; $db->query('SELECT * FROM `blocked_uas` ORDER BY `id` ASC;'); - if (0 >= $db->num_rows()) { - } else { + if (0 < $db->num_rows()) { foreach ($db->get_rows() ?: [] as $rRow) { $rReturn[] = $rRow; } @@ -565,8 +563,7 @@ class BlocklistService { $rReturn = []; $db->query('SELECT * FROM `blocked_isps` ORDER BY `id` ASC;'); - if (0 >= $db->num_rows()) { - } else { + if (0 < $db->num_rows()) { foreach ($db->get_rows() ?: [] as $rRow) { $rReturn[] = $rRow; } @@ -585,8 +582,7 @@ class BlocklistService { $db = self::db(); $db->query('SELECT * FROM `blocked_uas` WHERE `id` = ?;', $rID); - if ($db->num_rows() != 1) { - } else { + if ($db->num_rows() == 1) { return $db->get_row(); } return null; @@ -602,8 +598,7 @@ class BlocklistService { $db = self::db(); $db->query('SELECT * FROM `blocked_isps` WHERE `id` = ?;', $rID); - if ($db->num_rows() != 1) { - } else { + if ($db->num_rows() == 1) { return $db->get_row(); } return null; @@ -638,8 +633,7 @@ class BlocklistService { $db = self::db(); $db->query('SELECT * FROM `rtmp_ips` WHERE `id` = ?;', $rID); - if ($db->num_rows() != 1) { - } else { + if ($db->num_rows() == 1) { return $db->get_row(); } return null; diff --git a/src/Domain/Server/ServerRepository.php b/src/Domain/Server/ServerRepository.php index 4040366c..064d1db0 100644 --- a/src/Domain/Server/ServerRepository.php +++ b/src/Domain/Server/ServerRepository.php @@ -174,15 +174,14 @@ class ServerRepository { $rReturn = []; $db->query('SELECT * FROM `servers` WHERE `server_type` = 1 ORDER BY `id` ASC;'); - if (0 >= $db->num_rows()) { - } else { + if (0 < $db->num_rows()) { foreach ($db->get_rows() as $rRow) { if (isset($rPermissions['is_reseller']) && $rPermissions['is_reseller']) { $rRow['server_name'] = 'Proxy #' . $rRow['id']; } $rRow['server_online'] = in_array($rRow['status'], [1, 3]) && time() - $rRow['last_check_ago'] <= 90 || $rRow['is_main']; - if (!($rRow['server_online'] == 0 && $rOnline)) { + if ($rRow['server_online'] != 0 || !$rOnline) { $rReturn[$rRow['id']] = $rRow; } } @@ -205,13 +204,13 @@ class ServerRepository { return $rReturn; } - if (!empty($rLines)) { + if ($rLines !== []) { array_shift($rLines); } foreach ($rLines as $rLine) { $rSplit = explode(' ', preg_replace('!\s+!', ' ', trim($rLine))); - if (0 < strlen($rSplit[0]) && strpos($rSplit[5], 'xc_vm') !== false || $rSplit[5] == '/') { + if ($rSplit[0] !== '' && strpos($rSplit[5], 'xc_vm') !== false || $rSplit[5] == '/') { $rReturn[] = ['filesystem' => $rSplit[0], 'size' => $rSplit[1], 'used' => $rSplit[2], 'avail' => $rSplit[3], 'percentage' => $rSplit[4], 'mount' => implode(' ', array_slice($rSplit, 5, count($rSplit) - 5))]; } } @@ -418,11 +417,9 @@ class ServerRepository { */ public static function getAllowedIPs(bool $rForce = false) { global $rServers, $rSettings; - if ($rForce) { - } else { + if (!$rForce) { $rCache = FileCache::getCache('allowed_ips', 60); - if ($rCache === false) { - } else { + if ($rCache !== false) { return $rCache; } } @@ -438,19 +435,16 @@ class ServerRepository { $rIPs = array_merge($rIPs, json_decode($rServerInfo['whitelist_ips'], true)); } $rIPs[] = $rServerInfo['server_ip']; - if (!$rServerInfo['private_ip']) { - } else { + if ($rServerInfo['private_ip']) { $rIPs[] = $rServerInfo['private_ip']; } foreach (explode(',', $rServerInfo['domain_name'] ?? '') as $rIP) { - if (!filter_var($rIP, FILTER_VALIDATE_IP)) { - } else { + if (filter_var($rIP, FILTER_VALIDATE_IP)) { $rIPs[] = $rIP; } } } - if (empty($rSettings['allowed_ips_admin'])) { - } else { + if (!empty($rSettings['allowed_ips_admin'])) { $rIPs = array_merge($rIPs, explode(',', $rSettings['allowed_ips_admin'])); } FileCache::setCache('allowed_ips', $rIPs); @@ -480,8 +474,7 @@ class ServerRepository { public static function getPublicURL(?int $rServerID = null, ?string $rForceProtocol = null) { global $rSettings, $rServers; $rOriginatorID = null; - if (isset($rServerID)) { - } else { + if (!isset($rServerID)) { $rServerID = SERVER_ID; } if ($rForceProtocol) { @@ -496,13 +489,10 @@ class ServerRepository { $rProtocol = $rServers[$rServerID]['server_protocol'] ?? 'http'; } } - if (!$rServers[$rServerID]) { - } else { - if (!$rServers[$rServerID]['enable_proxy']) { - } else { + if ($rServers[$rServerID]) { + if ($rServers[$rServerID]['enable_proxy']) { $rProxyIDs = array_keys(ConnectionTracker::getProxies($rServerID)); - if (count($rProxyIDs) != 0) { - } else { + if (count($rProxyIDs) == 0) { $rProxyIDs = array_keys(ConnectionTracker::getProxies($rServerID, false)); } if (count($rProxyIDs) != 0) { @@ -519,8 +509,7 @@ class ServerRepository { $rDomain = (empty($rServers[$rServerID]['domain_name']) ? $rServers[$rServerID]['server_ip'] : explode(',', $rServers[$rServerID]['domain_name'])[0]); } $rServerURL = $rProtocol . '://' . $rDomain . ':' . $rServers[$rServerID][$rProtocol . '_broadcast_port'] . '/'; - if (!($rServers[$rServerID]['server_type'] == 1 && $rOriginatorID && $rServers[$rOriginatorID]['is_main'] == 0)) { - } else { + if ($rServers[$rServerID]['server_type'] == 1 && $rOriginatorID && $rServers[$rOriginatorID]['is_main'] == 0) { $rServerURL .= md5($rServerID . '_' . $rOriginatorID . '_' . OPENSSL_EXTRA) . '/'; } return $rServerURL; diff --git a/src/Domain/Server/ServerService.php b/src/Domain/Server/ServerService.php index be05626d..5e47133b 100644 --- a/src/Domain/Server/ServerService.php +++ b/src/Domain/Server/ServerService.php @@ -53,7 +53,7 @@ class ServerService { } foreach ($rData['http_broadcast_ports'] as $rPort) { - if (is_numeric($rPort) && 80 <= $rPort && $rPort <= 65535 && !in_array($rPort, ($rPorts['http'] ?: [])) && $rPort != $rData['rtmp_port']) { + if (is_numeric($rPort) && 80 <= $rPort && $rPort <= 65535 && !in_array($rPort, ($rPorts['http'])) && $rPort != $rData['rtmp_port']) { $rPorts['http'][] = $rPort; } } @@ -61,7 +61,7 @@ class ServerService { unset($rData['http_broadcast_ports']); foreach ($rData['https_broadcast_ports'] as $rPort) { - if (is_numeric($rPort) && 80 <= $rPort && $rPort <= 65535 && !in_array($rPort, ($rPorts['http'] ?: [])) && !in_array($rPort, ($rPorts['https'] ?: [])) && $rPort != $rData['rtmp_port']) { + if (is_numeric($rPort) && 80 <= $rPort && $rPort <= 65535 && !in_array($rPort, ($rPorts['http'])) && !in_array($rPort, ($rPorts['https'])) && $rPort != $rData['rtmp_port']) { $rPorts['https'][] = $rPort; } } @@ -126,7 +126,7 @@ class ServerService { if (strlen($rData['server_ip']) == 0 || !filter_var($rData['server_ip'], FILTER_VALIDATE_IP)) { return ['status' => STATUS_INVALID_IP, 'data' => $rData]; } - if (0 < strlen($rData['private_ip']) && !filter_var($rData['private_ip'], FILTER_VALIDATE_IP)) { + if ((string) $rData['private_ip'] !== '' && !filter_var($rData['private_ip'], FILTER_VALIDATE_IP)) { return ['status' => STATUS_INVALID_IP, 'data' => $rData]; } @@ -422,8 +422,7 @@ class ServerService { global $rServers; foreach ($db->get_rows() as $rRow) { - if (!$rServers[$rRow['server_id']]['server_online']) { - } else { + if ($rServers[$rRow['server_id']]['server_online']) { ApiClient::systemRequest($rRow['server_id'], ['action' => 'kill_plex']); } } diff --git a/src/Domain/Server/SettingsService.php b/src/Domain/Server/SettingsService.php index 042707b8..c8a19371 100644 --- a/src/Domain/Server/SettingsService.php +++ b/src/Domain/Server/SettingsService.php @@ -30,7 +30,6 @@ class SettingsService { * which a decimal(3,2) column refuses. * * @param mixed $rValue The submitted value. - * @return float|null */ public static function normalizeIdleBufferRatio(mixed $rValue): ?float { $rValue = str_replace(',', '.', trim((string) $rValue)); diff --git a/src/Domain/Stream/AdminStreamToken.php b/src/Domain/Stream/AdminStreamToken.php index 5c58839c..d29a02e9 100644 --- a/src/Domain/Stream/AdminStreamToken.php +++ b/src/Domain/Stream/AdminStreamToken.php @@ -50,7 +50,6 @@ final class AdminStreamToken { * * @param string $rawToken Encrypted token from the request. * @param string $key Decryption key (live_streaming_pass). - * @return self|null */ public static function decode(string $rawToken, string $key, bool $rAcceptLegacy): ?self { $rDecrypted = Encryption::readToken($rawToken, $key, OPENSSL_EXTRA, $rAcceptLegacy); @@ -82,7 +81,6 @@ final class AdminStreamToken { * @param bool $rSubnetMatch Compare only the leading three octets. * @param string|null $rClientIp Current client IP. * @param int|null $rNow Reference time (defaults to time()). - * @return bool */ public function isValid(bool $rSubnetMatch, ?string $rClientIp, ?int $rNow = null): bool { return $this->expires >= ($rNow ?? time()) diff --git a/src/Domain/Stream/CategoryService.php b/src/Domain/Stream/CategoryService.php index ae2092d1..da9e7185 100644 --- a/src/Domain/Stream/CategoryService.php +++ b/src/Domain/Stream/CategoryService.php @@ -30,8 +30,7 @@ class CategoryService { $db = self::db(); $rPostCategories = json_decode($rData['categories'], true); - if (0 >= count($rPostCategories)) { - } else { + if (0 < count($rPostCategories)) { foreach ($rPostCategories as $rOrder => $rPostCategory) { $db->query('UPDATE `streams_categories` SET `cat_order` = ?, `parent_id` = 0 WHERE `id` = ?;', intval($rOrder) + 1, $rPostCategory['id']); } @@ -130,8 +129,7 @@ class CategoryService { public static function filterLoaded(array $rCategories, ?string $rType = null) { $rReturn = []; foreach ($rCategories as $rCategory) { - if ($rCategory['category_type'] != $rType && $rType) { - } else { + if ($rCategory['category_type'] == $rType || !$rType) { $rReturn[] = $rCategory; } } @@ -190,8 +188,7 @@ class CategoryService { foreach ($db->get_rows() as $rRow) { $rRow['category_id'] = json_decode($rRow['category_id'], true); - if (($rKey = array_search($rID, $rRow['category_id'])) === false) { - } else { + if (($rKey = array_search($rID, $rRow['category_id'])) !== false) { unset($rRow['category_id'][$rKey]); } @@ -202,8 +199,7 @@ class CategoryService { foreach ($db->get_rows() as $rRow) { $rRow['category_id'] = json_decode($rRow['category_id'], true); - if (($rKey = array_search($rID, $rRow['category_id'])) === false) { - } else { + if (($rKey = array_search($rID, $rRow['category_id'])) !== false) { unset($rRow['category_id'][$rKey]); } diff --git a/src/Domain/Stream/ChannelService.php b/src/Domain/Stream/ChannelService.php index 6b9d6c2b..acaba3b1 100644 --- a/src/Domain/Stream/ChannelService.php +++ b/src/Domain/Stream/ChannelService.php @@ -97,8 +97,7 @@ class ChannelService { $rPrepare = QueryHelper::prepareArray(['bouquet_name' => $rBouquet, 'bouquet_channels' => [], 'bouquet_movies' => [], 'bouquet_series' => [], 'bouquet_radios' => []]); $rQuery = 'INSERT INTO `bouquets`(' . $rPrepare['columns'] . ') VALUES(' . $rPrepare['placeholder'] . ');'; - if (!$db->query($rQuery, ...$rPrepare['data'])) { - } else { + if ($db->query($rQuery, ...$rPrepare['data'])) { $rBouquetID = $db->last_insert_id(); $rBouquetCreate[$rBouquet] = $rBouquetID; } @@ -109,8 +108,7 @@ class ChannelService { $rPrepare = QueryHelper::prepareArray(['category_type' => 'live', 'category_name' => $rCategory, 'parent_id' => 0, 'cat_order' => 99, 'is_adult' => 0]); $rQuery = 'INSERT INTO `streams_categories`(' . $rPrepare['columns'] . ') VALUES(' . $rPrepare['placeholder'] . ');'; - if (!$db->query($rQuery, ...$rPrepare['data'])) { - } else { + if ($db->query($rQuery, ...$rPrepare['data'])) { $rCategoryID = $db->last_insert_id(); $rCategoryCreate[$rCategory] = $rCategoryID; } @@ -121,8 +119,7 @@ class ChannelService { if (isset($rBouquetCreate[$rBouquet])) { $rBouquets[] = $rBouquetCreate[$rBouquet]; } else { - if (!is_numeric($rBouquet)) { - } else { + if (is_numeric($rBouquet)) { $rBouquets[] = intval($rBouquet); } } @@ -140,13 +137,11 @@ class ChannelService { } $rArray['category_id'] = '[' . implode(',', array_map('intval', $rCategories)) . ']'; - if (!$rSettings['download_images']) { - } else { + if ($rSettings['download_images']) { $rArray['stream_icon'] = ImageUtils::downloadImage($rArray['stream_icon'], 3); } - if (isset($rData['edit'])) { - } else { + if (!isset($rData['edit'])) { $rArray['order'] = StreamRepository::getNextOrder(); } @@ -157,10 +152,8 @@ class ChannelService { $rInsertID = $db->last_insert_id(); $rStreamExists = []; - if (!isset($rData['edit'])) { - } else { + if (isset($rData['edit'])) { $db->query('SELECT `server_stream_id`, `server_id` FROM `streams_servers` WHERE `stream_id` = ?;', $rInsertID); - foreach ($db->get_rows() as $rRow) { $rStreamExists[intval($rRow['server_id'])] = intval($rRow['server_stream_id']); } @@ -170,18 +163,15 @@ class ChannelService { $rServerTree = json_decode($rData['server_tree_data'], true); foreach ($rServerTree as $rServer) { - if ($rServer['parent'] == '#') { - } else { + if ($rServer['parent'] != '#') { $rServerID = intval($rServer['id']); $rStreamsAdded[] = $rServerID; $rOD = intval(in_array($rServerID, ($rData['on_demand'] ?? []))); - if ($rServer['parent'] == 'source') { $rParent = null; } else { $rParent = intval($rServer['parent']); } - if (isset($rStreamExists[$rServerID])) { $db->query('UPDATE `streams_servers` SET `parent_id` = ?, `on_demand` = ? WHERE `server_stream_id` = ?;', $rParent, $rOD, $rStreamExists[$rServerID]); } else { @@ -191,8 +181,7 @@ class ChannelService { } foreach ($rStreamExists as $rServerID => $rDBID) { - if (in_array($rServerID, $rStreamsAdded)) { - } else { + if (!in_array($rServerID, $rStreamsAdded)) { StreamRepository::deleteStream($rInsertID, $rServerID, false, false); } } @@ -211,11 +200,9 @@ class ChannelService { BouquetService::addItems('stream', $rBouquet, $rInsertID); } - if (!isset($rData['edit'])) { - } else { + if (isset($rData['edit'])) { foreach (BouquetService::getAllSimple() as $rBouquet) { - if (in_array($rBouquet['id'], $rBouquets)) { - } else { + if (!in_array($rBouquet['id'], $rBouquets)) { BouquetService::removeItems('stream', $rBouquet['id'], $rInsertID); } } @@ -224,12 +211,10 @@ class ChannelService { StreamProcess::updateStream($rInsertID); return ['status' => STATUS_SUCCESS, 'data' => ['insert_id' => $rInsertID]]; - } else { - return ['status' => STATUS_FAILURE, 'data' => $rData]; } - } else { - return ['status' => STATUS_NO_SOURCES, 'data' => $rData]; + return ['status' => STATUS_FAILURE, 'data' => $rData]; } + return ['status' => STATUS_NO_SOURCES, 'data' => $rData]; } /** @@ -248,8 +233,7 @@ class ChannelService { $rArray = []; foreach (['allow_record', 'rtmp_output'] as $rKey) { - if (!isset($rData['c_' . $rKey])) { - } else { + if (isset($rData['c_' . $rKey])) { if (isset($rData[$rKey])) { $rArray[$rKey] = 1; } else { @@ -258,10 +242,8 @@ class ChannelService { } } - if (!isset($rData['c_transcode_profile_id'])) { - } else { + if (isset($rData['c_transcode_profile_id'])) { $rArray['transcode_profile_id'] = $rData['transcode_profile_id']; - if (0 < $rArray['transcode_profile_id']) { $rArray['enable_transcode'] = 1; } else { @@ -271,22 +253,16 @@ class ChannelService { $rStreamIDs = json_decode($rData['streams'], true); - if (0 >= count($rStreamIDs)) { - } else { + if (0 < count($rStreamIDs)) { $rCategoryMap = []; - - if (!(isset($rData['c_category_id']) && in_array($rData['category_id_type'], ['ADD', 'DEL']))) { - } else { + if (isset($rData['c_category_id']) && in_array($rData['category_id_type'], ['ADD', 'DEL'])) { $db->query('SELECT `id`, `category_id` FROM `streams` WHERE `id` IN (' . implode(',', array_map('intval', $rStreamIDs)) . ');'); - foreach ($db->get_rows() as $rRow) { $rCategoryMap[$rRow['id']] = (json_decode($rRow['category_id'], true) ?: []); } } - $rDeleteServers = $rProcessServers = $rStreamExists = []; $db->query('SELECT `stream_id`, `server_stream_id`, `server_id` FROM `streams_servers` WHERE `stream_id` IN (' . implode(',', array_map('intval', $rStreamIDs)) . ');'); - foreach ($db->get_rows() as $rRow) { $rStreamExists[intval($rRow['stream_id'])][intval($rRow['server_id'])] = intval($rRow['server_stream_id']); $rProcessServers[intval($rRow['stream_id'])][] = intval($rRow['server_id']); @@ -294,56 +270,43 @@ class ChannelService { $rBouquets = BouquetService::getAllSimple(); $rAddBouquet = $rDelBouquet = []; $rEncQuery = $rAddQuery = ''; - foreach ($rStreamIDs as $rStreamID) { - if (!isset($rData['c_category_id'])) { - } else { + if (isset($rData['c_category_id'])) { $rCategories = array_map('intval', $rData['category_id']); - if ($rData['category_id_type'] == 'ADD') { foreach (($rCategoryMap[$rStreamID] ?: []) as $rCategoryID) { - if (in_array($rCategoryID, $rCategories)) { - } else { + if (!in_array($rCategoryID, $rCategories)) { $rCategories[] = $rCategoryID; } } } else { - if ($rData['category_id_type'] != 'DEL') { - } else { + if ($rData['category_id_type'] == 'DEL') { $rNewCategories = $rCategoryMap[$rStreamID]; - foreach ($rCategories as $rCategoryID) { - if (($rKey = array_search($rCategoryID, $rNewCategories)) === false) { - } else { + if (($rKey = array_search($rCategoryID, $rNewCategories)) !== false) { unset($rNewCategories[$rKey]); } } $rCategories = $rNewCategories; } } - $rArray['category_id'] = '[' . implode(',', $rCategories) . ']'; } $rPrepare = QueryHelper::prepareArray($rArray); - if (0 >= count($rPrepare['data'])) { - } else { + if (0 < count($rPrepare['data'])) { $rPrepare['data'][] = $rStreamID; $rQuery = 'UPDATE `streams` SET ' . $rPrepare['update'] . ' WHERE `id` = ?;'; $db->query($rQuery, ...$rPrepare['data']); } - if (!isset($rData['c_server_tree'])) { - } else { + if (isset($rData['c_server_tree'])) { $rStreamsAdded = []; $rServerTree = json_decode($rData['server_tree_data'], true); - foreach ($rServerTree as $rServer) { - if ($rServer['parent'] == '#') { - } else { + if ($rServer['parent'] != '#') { $rServerID = intval($rServer['id']); - if (in_array($rData['server_type'], ['ADD', 'SET'])) { $rStreamsAdded[] = $rServerID; $rOD = intval(in_array($rServerID, ($rData['on_demand'] ?? []))); @@ -362,23 +325,17 @@ class ChannelService { $rProcessServers[$rStreamID][] = $rServerID; } else { - if (!isset($rStreamExists[$rStreamID][$rServerID])) { - } else { + if (isset($rStreamExists[$rStreamID][$rServerID])) { $rDeleteServers[$rServerID][] = $rStreamID; } } } } - - if ($rData['server_type'] != 'SET') { - } else { + if ($rData['server_type'] == 'SET') { foreach ($rStreamExists as $rServerID => $rDBID) { - if (in_array($rServerID, $rStreamsAdded)) { - } else { + if (!in_array($rServerID, $rStreamsAdded)) { $rDeleteServers[$rServerID][] = $rStreamID; - - if (($rKey = array_search($rServerID, $rProcessServers[$rStreamID])) === false) { - } else { + if (($rKey = array_search($rServerID, $rProcessServers[$rStreamID])) !== false) { unset($rProcessServers[$rStreamID][$rKey]); } } @@ -386,16 +343,14 @@ class ChannelService { } } - if (!isset($rData['c_bouquets'])) { - } else { + if (isset($rData['c_bouquets'])) { if ($rData['bouquets_type'] == 'SET') { foreach ($rData['bouquets'] as $rBouquet) { $rAddBouquet[$rBouquet][] = $rStreamID; } foreach ($rBouquets as $rBouquet) { - if (in_array($rBouquet['id'], $rData['bouquets'])) { - } else { + if (!in_array($rBouquet['id'], $rData['bouquets'])) { $rDelBouquet[$rBouquet['id']][] = $rStreamID; } } @@ -405,8 +360,7 @@ class ChannelService { $rAddBouquet[$rBouquet][] = $rStreamID; } } else { - if ($rData['bouquets_type'] != 'DEL') { - } else { + if ($rData['bouquets_type'] == 'DEL') { foreach ($rData['bouquets'] as $rBouquet) { $rDelBouquet[$rBouquet][] = $rStreamID; } @@ -415,47 +369,37 @@ class ChannelService { } } - if (!isset($rData['reencode_on_edit'])) { - } else { + if (isset($rData['reencode_on_edit'])) { foreach ($rProcessServers[$rStreamID] as $rServerID) { $rEncQuery .= "('channel', " . intval($rStreamID) . ', ' . intval($rServerID) . ', ' . time() . '),'; } } } - foreach ($rDeleteServers as $rServerID => $rDeleteIDs) { StreamRepository::deleteStreamsByServer($rDeleteIDs, $rServerID, false); } - foreach ($rAddBouquet as $rBouquetID => $rAddIDs) { BouquetService::addItems('stream', $rBouquetID, $rAddIDs); } - foreach ($rDelBouquet as $rBouquetID => $rRemIDs) { BouquetService::removeItems('stream', $rBouquetID, $rRemIDs); } - - if (empty($rAddQuery)) { - } else { + if (!empty($rAddQuery)) { $rAddQuery = rtrim($rAddQuery, ','); $db->query('INSERT INTO `streams_servers`(`stream_id`, `server_id`, `parent_id`, `on_demand`) VALUES ' . $rAddQuery . ';'); } - StreamProcess::updateStreams($rStreamIDs); - if (isset($rData['reencode_on_edit'])) { $db->query("UPDATE `streams_servers` SET `pids_create_channel` = '[]', `cchannel_rsources` = '[]' WHERE `stream_id` IN (" . implode(',', array_map('intval', $rStreamIDs)) . ');'); - if (empty($rEncQuery)) { - } else { + if (!empty($rEncQuery)) { $rEncQuery = rtrim($rEncQuery, ','); $db->query('INSERT INTO `queue`(`type`, `stream_id`, `server_id`, `added`) VALUES ' . $rEncQuery . ';'); } ApiClient::request(['action' => 'stream', 'sub' => 'stop', 'stream_ids' => array_values($rStreamIDs)]); } else { - if (!isset($rData['restart_on_edit'])) { - } else { + if (isset($rData['restart_on_edit'])) { ApiClient::request(['action' => 'stream', 'sub' => 'start', 'stream_ids' => array_values($rStreamIDs)]); } } diff --git a/src/Domain/Stream/ConnectionTracker.php b/src/Domain/Stream/ConnectionTracker.php index 5e9161e9..c17858ad 100644 --- a/src/Domain/Stream/ConnectionTracker.php +++ b/src/Domain/Stream/ConnectionTracker.php @@ -217,7 +217,6 @@ class ConnectionTracker { * * @param int $rStreamID Stream ID. * @param int $rAddPID Process PID to add. - * @return void */ public static function addToQueue(int $rStreamID, int $rAddPID): void { $rActivePIDs = $rPIDs = []; @@ -242,7 +241,6 @@ class ConnectionTracker { * * @param int $rStreamID Stream ID. * @param int $rPID Process PID to remove. - * @return void */ public static function removeFromQueue(int $rStreamID, int $rPID): void { $rQueueFile = SIGNALS_TMP_PATH . 'queue_' . intval($rStreamID); @@ -276,7 +274,7 @@ class ConnectionTracker { */ public static function updateConnection(array $rData, array $rChanges = [], ?string $rOption = null): ?array { $rRedis = RedisManager::instance(); - if (!$rRedis) { + if (!$rRedis instanceof \Redis) { return null; } $rOrigData = $rData; @@ -338,7 +336,7 @@ class ConnectionTracker { */ public static function redisSignal(int $rPID, int $rServerID, int $rRTMP, mixed $rCustomData = null) { $rRedis = RedisManager::instance(); - if (!$rRedis) { + if (!$rRedis instanceof \Redis) { return false; } // The payload is part of the key when there is one: pid-less signals @@ -361,7 +359,7 @@ class ConnectionTracker { */ public static function getUserConnections(array $rUserIDs, bool $rCount = false, bool $rKeysOnly = false): array { $rRedis = RedisManager::instance(); - if (!$rRedis) { + if (!$rRedis instanceof \Redis) { return []; } $rMulti = $rRedis->multi(); @@ -384,7 +382,7 @@ class ConnectionTracker { } $rRedisKeys = array_unique($rRedisKeys); if (!$rKeysOnly) { - if (!$rCount && !empty($rRedisKeys)) { + if (!$rCount && $rRedisKeys !== []) { foreach ($rRedis->mGet($rRedisKeys) as $rRow) { $rRow = igbinary_unserialize($rRow); $rConnectionMap[$rRow['user_id']][] = $rRow; @@ -408,7 +406,7 @@ class ConnectionTracker { */ public static function getServerConnections(array $rServerIDs, bool $rProxy = false, bool $rCount = false, bool $rKeysOnly = false): array { $rRedis = RedisManager::instance(); - if (!$rRedis) { + if (!$rRedis instanceof \Redis) { return []; } $rMulti = $rRedis->multi(); @@ -431,7 +429,7 @@ class ConnectionTracker { } $rRedisKeys = array_unique($rRedisKeys); if (!$rKeysOnly) { - if (!$rCount && !empty($rRedisKeys)) { + if (!$rCount && $rRedisKeys !== []) { foreach ($rRedis->mGet($rRedisKeys) as $rRow) { $rRow = igbinary_unserialize($rRow); $rConnectionMap[$rRow['server_id']][] = $rRow; @@ -452,7 +450,7 @@ class ConnectionTracker { */ public static function getFirstConnection(array $rUserIDs): array { $rRedis = RedisManager::instance(); - if (!$rRedis) { + if (!$rRedis instanceof \Redis) { return []; } $rMulti = $rRedis->multi(); @@ -469,7 +467,7 @@ class ConnectionTracker { $rRedisKeys[] = $rKeys[0]; } } - if (empty($rRedisKeys)) { + if ($rRedisKeys === []) { return $rConnectionMap; } foreach ($rRedis->mGet(array_unique($rRedisKeys)) as $rRow) { @@ -491,7 +489,7 @@ class ConnectionTracker { */ public static function getStreamConnections(array $rStreamIDs, bool $rGroup = true, bool $rCount = false): array { $rRedis = RedisManager::instance(); - if (!$rRedis) { + if (!$rRedis instanceof \Redis) { return []; } $rMulti = $rRedis->multi(); @@ -512,7 +510,7 @@ class ConnectionTracker { } } } - if (!$rCount && !empty($rRedisKeys)) { + if (!$rCount && $rRedisKeys !== []) { foreach ($rRedis->mGet(array_unique($rRedisKeys)) as $rRow) { $rRow = igbinary_unserialize($rRow); if ($rGroup) { @@ -549,7 +547,7 @@ class ConnectionTracker { * @return array stream_id => restreamer count. */ public static function attachedRestreamCounts(array $rStreamIDs, int $rServerID): array { - if (empty($rStreamIDs)) { + if ($rStreamIDs === []) { return []; } $db = self::db(); @@ -572,7 +570,7 @@ class ConnectionTracker { * @return array stream_id => viewer count. */ public static function onlineClientCounts(array $rStreamIDs, int $rServerID): array { - if (empty($rStreamIDs)) { + if ($rStreamIDs === []) { return []; } $db = self::db(); @@ -602,7 +600,7 @@ class ConnectionTracker { */ public static function getRedisConnections(?int $rUserID = null, ?int $rServerID = null, ?int $rStreamID = null, bool $rOpenOnly = false, bool $rCountOnly = false, bool $rGroup = true, bool $rHLSOnly = false): array { $rRedis = RedisManager::instance(); - if (!$rRedis) { + if (!$rRedis instanceof \Redis) { return ($rCountOnly ? [0, 0] : []); } $rReturn = ($rCountOnly ? [0, 0] : []); @@ -628,7 +626,7 @@ class ConnectionTracker { if (0 < count($rKeys)) { foreach ($rRedis->mGet(array_unique($rKeys)) as $rRow) { $rRow = igbinary_unserialize($rRow); - if (!($rServerID && $rServerID != $rRow['server_id']) && !($rStreamID && $rStreamID != $rRow['stream_id']) && !($rUserID && $rUserID != $rRow['user_id']) && !($rHLSOnly && $rRow['container'] == 'hls')) { + if ((!$rServerID || $rServerID == $rRow['server_id']) && (!$rStreamID || $rStreamID == $rRow['stream_id']) && (!$rUserID || $rUserID == $rRow['user_id']) && (!$rHLSOnly || $rRow['container'] != 'hls')) { $rUUID = ($rRow['user_id'] ?: $rRow['hmac_id'] . '_' . $rRow['hmac_identifier']); if ($rCountOnly) { $rReturn[0]++; @@ -661,7 +659,7 @@ class ConnectionTracker { */ public static function getConnection(string $rUUID): ?array { $rRedis = RedisManager::instance(); - if (!$rRedis) { + if (!$rRedis instanceof \Redis) { return null; } $raw = $rRedis->get($rUUID); @@ -692,9 +690,9 @@ class ConnectionTracker { * @return string 32-char hex connection id. */ public static function hlsConnectionKey(?int $rIsHMAC, string $rIdentifier, int|string $rUserId, int $rStreamId, string $rIp, string $rUserAgent): string { - $rIdentity = is_null($rIsHMAC) ? ('u' . intval($rUserId)) : ('h' . $rIsHMAC . '_' . (string) $rIdentifier); + $rIdentity = is_null($rIsHMAC) ? ('u' . intval($rUserId)) : ('h' . $rIsHMAC . '_' . $rIdentifier); - return md5('hls#' . $rIdentity . '#' . intval($rStreamId) . '#' . (string) $rIp . '#' . (string) $rUserAgent); + return md5('hls#' . $rIdentity . '#' . intval($rStreamId) . '#' . $rIp . '#' . $rUserAgent); } /** @@ -709,7 +707,7 @@ class ConnectionTracker { */ public static function createConnection(array $rData) { $rRedis = RedisManager::instance(); - if (!$rRedis) { + if (!$rRedis instanceof \Redis) { return false; } $rMulti = $rRedis->multi(); @@ -884,7 +882,7 @@ class ConnectionTracker { */ public static function getLineConnections(int $rUserID, bool $rActive = false, bool $rKeys = false): array { $rRedis = RedisManager::instance(); - if (!$rRedis) { + if (!$rRedis instanceof \Redis) { return []; } // zRangeByScore returns false on a failed connection — degrade to empty. @@ -904,7 +902,7 @@ class ConnectionTracker { */ public static function getEnded(): array { $rRedis = RedisManager::instance(); - if (!$rRedis) { + if (!$rRedis instanceof \Redis) { return []; } // sMembers/mGet return false on a failed connection — degrade to empty. @@ -947,7 +945,6 @@ class ConnectionTracker { * which that node's signals daemon turns into the same call. * * @param array $rConnection Connection row (needs uuid and server_id). - * @return void */ public static function dropDaemonViewer(array $rConnection): void { global $rSettings; @@ -984,16 +981,14 @@ class ConnectionTracker { if (!empty($rActivityInfo)) { global $rSettings, $rServers; $db = self::db(); - if (!$rSettings['redis_handler'] || is_object(RedisManager::instance())) { - } else { + if ($rSettings['redis_handler'] && !is_object(RedisManager::instance())) { RedisManager::ensureConnected(); } $rRedisObj = RedisManager::instance(); if (!$rRedisObj && $rSettings['redis_handler']) { return false; } - if (is_array($rActivityInfo)) { - } else { + if (!is_array($rActivityInfo)) { if (!$rSettings['redis_handler']) { if (strlen(strval($rActivityInfo)) == 32) { $db->query('SELECT * FROM `lines_live` WHERE `uuid` = ?', $rActivityInfo); @@ -1020,8 +1015,7 @@ class ConnectionTracker { } } else { if (($rActivityInfo['container'] ?? '') == 'hls') { - if (!(!$rRemove && $rEnd && $rActivityInfo['hls_end'] == 0)) { - } else { + if (!$rRemove && $rEnd && $rActivityInfo['hls_end'] == 0) { if ($rSettings['redis_handler']) { self::updateConnection($rActivityInfo, [], 'close'); } else { @@ -1033,8 +1027,7 @@ class ConnectionTracker { if (intval($rActivityInfo['pid']) === 0) { self::dropDaemonViewer($rActivityInfo); } elseif ($rActivityInfo['server_id'] == SERVER_ID) { - if (!($rActivityInfo['pid'] != getmypid() && is_numeric($rActivityInfo['pid']) && 0 < $rActivityInfo['pid'])) { - } else { + if ($rActivityInfo['pid'] != getmypid() && is_numeric($rActivityInfo['pid']) && 0 < $rActivityInfo['pid']) { posix_kill(intval($rActivityInfo['pid']), 9); } } else { @@ -1103,7 +1096,6 @@ class ConnectionTracker { * @param int $rDivergence Divergence value. * @param int|null $rIsHMAC HMAC ID. * @param string $rIdentifier HMAC identifier. - * @return void */ public static function writeOfflineActivity(array $rSettings, int $rServerID, int $rProxyID, int $rUserID, int $rStreamID, int $rStart, string $rUserAgent, string $rIP, string $rExtension, string $rGeoIP, string $rISP, string $rExternalDevice = '', int $rDivergence = 0, ?int $rIsHMAC = null, string $rIdentifier = ''): void { if ($rSettings['save_closed_connection'] != 0) { @@ -1137,8 +1129,7 @@ class ConnectionTracker { foreach ($rParentIDs as $rParentID) { foreach (self::getRedisConnections(null, $rParentID, null, true, false, false) as $rConnection) { - if ($rConnection['proxy_id'] != $rServerID) { - } else { + if ($rConnection['proxy_id'] == $rServerID) { $rCount++; } } @@ -1148,14 +1139,12 @@ class ConnectionTracker { } return $rCount; - } else { - if ($rProxy) { - $db->query('SELECT COUNT(*) AS `count` FROM `lines_live` WHERE `proxy_id` = ? AND `hls_end` = 0;', $rServerID); - } else { - $db->query('SELECT COUNT(*) AS `count` FROM `lines_live` WHERE `server_id` = ? AND `hls_end` = 0;', $rServerID); - } - - return $db->get_row()['count']; } + if ($rProxy) { + $db->query('SELECT COUNT(*) AS `count` FROM `lines_live` WHERE `proxy_id` = ? AND `hls_end` = 0;', $rServerID); + } else { + $db->query('SELECT COUNT(*) AS `count` FROM `lines_live` WHERE `server_id` = ? AND `hls_end` = 0;', $rServerID); + } + return $db->get_row()['count']; } } diff --git a/src/Domain/Stream/ProfileService.php b/src/Domain/Stream/ProfileService.php index a59a7749..fca4c201 100644 --- a/src/Domain/Stream/ProfileService.php +++ b/src/Domain/Stream/ProfileService.php @@ -32,7 +32,7 @@ class ProfileService { $rProfileOptions = []; if ($rData['gpu_device'] != 0) { - $rProfileOptions['software_decoding'] = (intval($rData['software_decoding']) ?: 0); + $rProfileOptions['software_decoding'] = (intval($rData['software_decoding'])); $rProfileOptions['gpu'] = ['val' => $rData['gpu_device'], 'cmd' => '']; $rProfileOptions['gpu']['device'] = intval(explode('_', $rData['gpu_device'])[1]); @@ -41,25 +41,21 @@ class ProfileService { $rCommand[] = '-hwaccel cuvid'; $rCommand[] = '-hwaccel_device ' . $rProfileOptions['gpu']['device']; - if (0 >= strlen($rData['resize'])) { - } else { + if ((string) $rData['resize'] !== '') { $rProfileOptions['gpu']['resize'] = $rData['resize']; $rCommand[] = '-resize ' . escapeshellcmd($rData['resize']); } - if (0 >= $rData['deint']) { - } else { + if (0 < $rData['deint']) { $rProfileOptions['gpu']['deint'] = intval($rData['deint']); $rCommand[] = '-deint ' . intval($rData['deint']); } $rCodec = ''; - if (0 >= strlen($rData['video_codec_gpu'])) { - } else { + if ((string) $rData['video_codec_gpu'] !== '') { $rProfileOptions['-vcodec'] = escapeshellcmd($rData['video_codec_gpu']); $rCommand[] = '{INPUT_CODEC}'; - switch ($rData['video_codec_gpu']) { case 'hevc_nvenc': $rCodec = 'hevc'; @@ -70,13 +66,11 @@ class ProfileService { } } - if (0 >= strlen($rData['preset_' . $rCodec])) { - } else { + if ((string) $rData['preset_' . $rCodec] !== '') { $rProfileOptions['-preset'] = escapeshellcmd($rData['preset_' . $rCodec]); } - if (0 >= strlen($rData['video_profile_' . $rCodec])) { - } else { + if ((string) $rData['video_profile_' . $rCodec] !== '') { $rProfileOptions['-profile:v'] = escapeshellcmd($rData['video_profile_' . $rCodec]); } @@ -86,121 +80,95 @@ class ProfileService { } else { $rCodec = ''; - if (0 >= strlen($rData['video_codec_gpu'])) { - } else { + if (0 < strlen($rData['video_codec_gpu'])) { $rProfileOptions['-vcodec'] = escapeshellcmd($rData['video_codec_gpu']); - - switch ($rData['video_codec_gpu']) { - case 'hevc_nvenc': - $rCodec = 'hevc'; - break; + if ($rData['video_codec_gpu'] === 'hevc_nvenc') { + $rCodec = 'hevc'; } $rCodec = 'h264'; } - if (0 >= strlen($rData['preset_' . $rCodec])) { - } else { + if (0 < strlen($rData['preset_' . $rCodec])) { $rProfileOptions['-preset'] = escapeshellcmd($rData['preset_' . $rCodec]); } - if (0 >= strlen($rData['video_profile_' . $rCodec])) { - } else { + if (0 < strlen($rData['video_profile_' . $rCodec])) { $rProfileOptions['-profile:v'] = escapeshellcmd($rData['video_profile_' . $rCodec]); } } } else { - if (0 >= strlen($rData['video_codec_cpu'])) { - } else { + if (0 < strlen($rData['video_codec_cpu'])) { $rProfileOptions['-vcodec'] = escapeshellcmd($rData['video_codec_cpu']); } - if (0 >= strlen($rData['preset_cpu'])) { - } else { + if (0 < strlen($rData['preset_cpu'])) { $rProfileOptions['-preset'] = escapeshellcmd($rData['preset_cpu']); } - if (0 >= strlen($rData['video_profile_cpu'])) { - } else { + if (0 < strlen($rData['video_profile_cpu'])) { $rProfileOptions['-profile:v'] = escapeshellcmd($rData['video_profile_cpu']); } } - if (0 >= strlen($rData['audio_codec'])) { - } else { + if ((string) $rData['audio_codec'] !== '') { $rProfileOptions['-acodec'] = escapeshellcmd($rData['audio_codec']); } - if (0 >= strlen($rData['video_bitrate'])) { - } else { + if ((string) $rData['video_bitrate'] !== '') { $rProfileOptions[3] = ['cmd' => '-b:v ' . intval($rData['video_bitrate']) . 'k', 'val' => intval($rData['video_bitrate'])]; } - if (0 >= strlen($rData['audio_bitrate'])) { - } else { + if ((string) $rData['audio_bitrate'] !== '') { $rProfileOptions[4] = ['cmd' => '-b:a ' . intval($rData['audio_bitrate']) . 'k', 'val' => intval($rData['audio_bitrate'])]; } - if (0 >= strlen($rData['min_tolerance'])) { - } else { + if ((string) $rData['min_tolerance'] !== '') { $rProfileOptions[5] = ['cmd' => '-minrate ' . intval($rData['min_tolerance']) . 'k', 'val' => intval($rData['min_tolerance'])]; } - if (0 >= strlen($rData['max_tolerance'])) { - } else { + if ((string) $rData['max_tolerance'] !== '') { $rProfileOptions[6] = ['cmd' => '-maxrate ' . intval($rData['max_tolerance']) . 'k', 'val' => intval($rData['max_tolerance'])]; } - if (0 >= strlen($rData['buffer_size'])) { - } else { + if ((string) $rData['buffer_size'] !== '') { $rProfileOptions[7] = ['cmd' => '-bufsize ' . intval($rData['buffer_size']) . 'k', 'val' => intval($rData['buffer_size'])]; } - if (0 >= strlen($rData['crf_value'])) { - } else { + if ((string) $rData['crf_value'] !== '') { $rProfileOptions[8] = ['cmd' => '-crf ' . intval($rData['crf_value']), 'val' => $rData['crf_value']]; } - if (0 >= strlen($rData['aspect_ratio'])) { - } else { + if ((string) $rData['aspect_ratio'] !== '') { $rProfileOptions[10] = ['cmd' => '-aspect ' . escapeshellcmd($rData['aspect_ratio']), 'val' => $rData['aspect_ratio']]; } - if (0 >= strlen($rData['framerate'])) { - } else { + if ((string) $rData['framerate'] !== '') { $rProfileOptions[11] = ['cmd' => '-r ' . intval($rData['framerate']), 'val' => intval($rData['framerate'])]; } - if (0 >= strlen($rData['samplerate'])) { - } else { + if ((string) $rData['samplerate'] !== '') { $rProfileOptions[12] = ['cmd' => '-ar ' . intval($rData['samplerate']), 'val' => intval($rData['samplerate'])]; } - if (0 >= strlen($rData['audio_channels'])) { - } else { + if ((string) $rData['audio_channels'] !== '') { $rProfileOptions[13] = ['cmd' => '-ac ' . intval($rData['audio_channels']), 'val' => intval($rData['audio_channels'])]; } - if (0 >= strlen($rData['threads'])) { - } else { + if ((string) $rData['threads'] !== '') { $rProfileOptions[15] = ['cmd' => '-threads ' . intval($rData['threads']), 'val' => intval($rData['threads'])]; } $rComplex = false; $rScale = $rOverlay = $rLogoInput = ''; - if (0 >= strlen($rData['logo_path'])) { - } else { + if ((string) $rData['logo_path'] !== '') { $rComplex = true; $rPos = array_map('intval', explode(':', $rData['logo_pos'])); - - if (count($rPos) == 2) { - } else { + if (count($rPos) != 2) { $rPos = [10, 10]; } - $rLogoInput = '-i ' . escapeshellarg($rData['logo_path']); $rProfileOptions[16] = ['cmd' => '', 'val' => $rData['logo_path'], 'pos' => implode(':', $rPos)]; - if ($rData['gpu_device'] != 0 && !$rData['software_decoding']) { $rOverlay = '[0:v]hwdownload,format=nv12 [base]; [base][1:v] overlay=' . $rPos[0] . ':' . $rPos[1]; } else { @@ -209,13 +177,12 @@ class ProfileService { } if ($rData['gpu_device'] == 0) { - if (!(isset($rData['yadif_filter']) && 0 < strlen($rData['scaling']))) { - } else { + if (isset($rData['yadif_filter']) && (string) $rData['scaling'] !== '') { $rComplex = true; } if ($rComplex) { - if (isset($rData['yadif_filter']) && 0 < strlen($rData['scaling'])) { + if (isset($rData['yadif_filter']) && (string) $rData['scaling'] !== '') { if (!$rData['software_decoding']) { $rScale = '[0:v]yadif,scale=' . escapeshellcmd($rData['scaling']) . '[bg];[bg][1:v]'; } else { @@ -225,41 +192,36 @@ class ProfileService { $rProfileOptions[9] = ['cmd' => '', 'val' => $rData['scaling']]; $rProfileOptions[17] = ['cmd' => '', 'val' => 1]; } else { - if (0 < strlen($rData['scaling'])) { + if ((string) $rData['scaling'] !== '') { $rScale = 'scale=' . escapeshellcmd($rData['scaling']); $rProfileOptions[9] = ['cmd' => '', 'val' => $rData['scaling']]; } else { - if (!isset($rData['yadif_filter'])) { - } else { + if (isset($rData['yadif_filter'])) { if (!$rData['software_decoding']) { $rScale = '[0:v]yadif[bg];[bg][1:v]'; } else { $rScale = 'yadif'; } - $rProfileOptions[17] = ['cmd' => '', 'val' => 1]; } } } } else { - if (0 >= strlen($rData['scaling'])) { - } else { + if (0 < strlen($rData['scaling'])) { $rProfileOptions[9] = ['cmd' => '-vf scale=' . escapeshellcmd($rData['scaling']), 'val' => $rData['scaling']]; } - if (!isset($rData['yadif_filter'])) { - } else { + if (isset($rData['yadif_filter'])) { $rProfileOptions[17] = ['cmd' => '-vf yadif', 'val' => 1]; } } } else { - if (!(0 < intval($rData['deint']) && 0 < strlen($rData['resize']))) { - } else { + if (0 < intval($rData['deint']) && (string) $rData['resize'] !== '') { $rComplex = true; } if ($rComplex) { - if (0 < intval($rData['deint']) && 0 < strlen($rData['resize'])) { + if (0 < intval($rData['deint']) && (string) $rData['resize'] !== '') { if (!$rData['software_decoding']) { $rScale = '[0:v]yadif,scale=' . escapeshellcmd($rData['resize']) . '[bg];[bg][1:v]'; } else { @@ -269,7 +231,7 @@ class ProfileService { $rProfileOptions[9] = ['cmd' => '', 'val' => $rData['resize']]; $rProfileOptions[17] = ['cmd' => '', 'val' => 1]; } else { - if (0 < strlen($rData['resize'])) { + if ((string) $rData['resize'] !== '') { if (!$rData['software_decoding']) { $rScale = '[0:v]scale=' . escapeshellcmd($rData['resize']) . '[bg];[bg][1:v]'; } else { @@ -278,49 +240,41 @@ class ProfileService { $rProfileOptions[9] = ['cmd' => '', 'val' => $rData['resize']]; } else { - if (0 >= intval($rData['deint'])) { - } else { + if (0 < intval($rData['deint'])) { if (!$rData['software_decoding']) { $rScale = '[0:v]yadif[bg];[bg][1:v]'; } else { $rScale = 'yadif'; } - $rProfileOptions[17] = ['cmd' => '', 'val' => 1]; } } } } else { - if (0 >= strlen($rData['resize'])) { - } else { + if (0 < strlen($rData['resize'])) { $rProfileOptions[9] = ['cmd' => '-vf scale=' . escapeshellcmd($rData['resize']), 'val' => $rData['resize']]; } - if (0 >= intval($rData['deint'])) { - } else { + if (0 < intval($rData['deint'])) { $rProfileOptions[17] = ['cmd' => '-vf yadif', 'val' => 1]; } } } - if (!$rComplex) { - } else { + if ($rComplex) { if (!empty($rScale) && substr($rScale, strlen($rScale) - 1, 1) != ']') { $rOverlay = ',' . $rOverlay; } else { - if (empty($rScale)) { - } else { + if (!empty($rScale)) { $rOverlay = ' ' . $rOverlay; } } - $rProfileOptions[16]['cmd'] = str_replace(['{SCALE}', '{OVERLAY}', '{LOGO}'], [$rScale, $rOverlay, $rLogoInput], '{LOGO} -filter_complex "{SCALE}{OVERLAY}"'); } $rArray['profile_options'] = json_encode($rProfileOptions, JSON_UNESCAPED_UNICODE); - if (!isset($rData['edit'])) { - } else { + if (isset($rData['edit'])) { $rArray['profile_id'] = $rData['edit']; } diff --git a/src/Domain/Stream/ProviderService.php b/src/Domain/Stream/ProviderService.php index f6b76c46..949cb5d3 100644 --- a/src/Domain/Stream/ProviderService.php +++ b/src/Domain/Stream/ProviderService.php @@ -74,9 +74,8 @@ class ProviderService { } return ['status' => STATUS_EXISTS_IP, 'data' => $rData]; - } else { - return ['status' => STATUS_INVALID_INPUT, 'data' => $rData]; } + return ['status' => STATUS_INVALID_INPUT, 'data' => $rData]; } /** diff --git a/src/Domain/User/GroupService.php b/src/Domain/User/GroupService.php index 8ce88de4..09218e6a 100644 --- a/src/Domain/User/GroupService.php +++ b/src/Domain/User/GroupService.php @@ -171,7 +171,7 @@ class GroupService { foreach ($db->get_rows() as $rRow) { $rRow['groups'] = json_decode($rRow['groups'], true); - if ($rKey = array_search($rID, $rRow['groups']) !== false) { + if (($rKey = array_search($rID, $rRow['groups'])) !== false) { unset($rRow['groups'][$rKey]); } diff --git a/src/Domain/User/ResellerAPI.php b/src/Domain/User/ResellerAPI.php index 9e5a035f..022c7616 100644 --- a/src/Domain/User/ResellerAPI.php +++ b/src/Domain/User/ResellerAPI.php @@ -51,8 +51,7 @@ class ResellerAPI { $rArray = ['line' => ['edit', 'trial', 'bouquets_selected', 'pair_id', 'username', 'password', 'member_id', 'package', 'contact', 'reseller_notes', 'allowed_ips', 'allowed_ua', 'bypass_ua', 'is_isplock', 'isp_clear'], 'mag' => ['edit', 'trial', 'bouquets_selected', 'pair_id', 'mac', 'member_id', 'package', 'parent_password', 'sn', 'stb_type', 'image_version', 'hw_version', 'device_id', 'device_id2', 'ver', 'reseller_notes', 'allowed_ips', 'is_isplock', 'isp_clear'], 'enigma' => ['edit', 'trial', 'bouquets_selected', 'pair_id', 'mac', 'member_id', 'package', 'modem_mac', 'local_ip', 'enigma_version', 'cpu', 'lversion', 'token', 'reseller_notes', 'allowed_ips', 'is_isplock', 'isp_clear'], 'user' => ['edit', 'username', 'password', 'owner_id', 'email', 'reseller_dns', 'notes', 'member_group_id'], 'ticket' => ['edit', 'message', 'title', 'respond'], 'profile' => ['email', 'password', 'api_key', 'reseller_dns', 'theme', 'hue', 'timezone']]; foreach ($rData as $rKey => $rValue) { - if (in_array($rKey, $rArray[$rType])) { - } else { + if (!in_array($rKey, $rArray[$rType])) { unset($rData[$rKey]); } } @@ -72,13 +71,11 @@ class ResellerAPI { self::$rServers = ServerRepository::getStreamingSimple($rPermissions); self::$rProxyServers = ServerRepository::getProxySimple($rPermissions); - if ($rUserID || !isset($_SESSION['reseller'])) { - } else { + if (!$rUserID && isset($_SESSION['reseller'])) { $rUserID = $_SESSION['reseller']; } - if (!$rUserID) { - } else { + if ($rUserID) { self::$rUserInfo = UserRepository::getRegisteredUserById($rUserID); self::$rPermissions = array_merge((AuthRepository::getPermissions(self::$rUserInfo['member_group_id']) ?: []), (AuthRepository::getGroupPermissions(self::$rUserInfo['id']) ?: [])); } @@ -96,8 +93,8 @@ class ResellerAPI { $rData = self::processData('profile', $rData); if (0 >= strlen($rData['email']) || filter_var($rData['email'], FILTER_VALIDATE_EMAIL)) { - if (0 < strlen($rData['password'])) { - if (!(strlen($rData['password']) < intval(self::$rPermissions['minimum_password_length']))) { + if ((string) $rData['password'] !== '') { + if (strlen($rData['password']) >= intval(self::$rPermissions['minimum_password_length'])) { $rPassword = Authenticator::hashPassword($rData['password']); } else { return ['status' => STATUS_INVALID_PASSWORD]; @@ -106,8 +103,7 @@ class ResellerAPI { $rPassword = self::$rUserInfo['password']; } - if (ctype_xdigit($rData['api_key']) && strlen($rData['api_key']) == 32) { - } else { + if (!ctype_xdigit($rData['api_key']) || strlen($rData['api_key']) != 32) { $rData['api_key'] = ''; } @@ -195,7 +191,7 @@ class ResellerAPI { } else { $rOverride = json_decode(self::$rUserInfo['override_packages'], true); - if (isset($rOverride[$rPackage['id']]['official_credits']) && 0 < strlen($rOverride[$rPackage['id']]['official_credits'])) { + if (isset($rOverride[$rPackage['id']]['official_credits']) && (string) $rOverride[$rPackage['id']]['official_credits'] !== '') { $rCost = intval($rOverride[$rPackage['id']]['official_credits']); } else { $rCost = intval($rPackage['official_credits']); @@ -222,19 +218,14 @@ class ResellerAPI { $rBouquets = array_values(json_decode($rPackage['bouquets'], true)); - if (!(self::$rPermissions['allow_change_bouquets'] && 0 < count($rData['bouquets_selected'] ?? []))) { - } else { + if (self::$rPermissions['allow_change_bouquets'] && 0 < count($rData['bouquets_selected'] ?? [])) { $rNewBouquets = []; - foreach ($rData['bouquets_selected'] as $rBouquetID) { - if (!in_array($rBouquetID, $rBouquets)) { - } else { + if (in_array($rBouquetID, $rBouquets)) { $rNewBouquets[] = $rBouquetID; } } - - if (0 >= count($rNewBouquets)) { - } else { + if (0 < count($rNewBouquets)) { $rBouquets = $rNewBouquets; } } @@ -269,28 +260,20 @@ class ResellerAPI { return ['status' => STATUS_INVALID_PACKAGE, 'data' => $rData]; } - if (!(isset($rData['edit']) && $rUserArray['package_id'])) { - } else { + if (isset($rData['edit']) && $rUserArray['package_id']) { $rPackage = PackageService::getById($rUserArray['package_id']); $rBouquets = array_values(json_decode($rPackage['bouquets'], true)); - - if (!(self::$rPermissions['allow_change_bouquets'] && 0 < count($rData['bouquets_selected'] ?? []))) { - } else { + if (self::$rPermissions['allow_change_bouquets'] && 0 < count($rData['bouquets_selected'] ?? [])) { $rNewBouquets = []; - foreach ($rData['bouquets_selected'] as $rBouquetID) { - if (!in_array($rBouquetID, $rBouquets)) { - } else { + if (in_array($rBouquetID, $rBouquets)) { $rNewBouquets[] = $rBouquetID; } } - - if (0 >= count($rNewBouquets)) { - } else { + if (0 < count($rNewBouquets)) { $rBouquets = $rNewBouquets; } } - $rUserArray['bouquet'] = AdminHelpers::sortArrayByArray($rBouquets, array_keys(BouquetService::getOrder())); $rUserArray['bouquet'] = '[' . implode(',', array_map('intval', $rUserArray['bouquet'])) . ']'; } @@ -308,11 +291,9 @@ class ResellerAPI { $rUserArray['member_id'] = self::$rUserInfo['id']; } - if (!self::$rPermissions['allow_restrictions']) { - } else { + if (self::$rPermissions['allow_restrictions']) { if (isset($rData['allowed_ips'])) { - if (is_array($rData['allowed_ips'])) { - } else { + if (!is_array($rData['allowed_ips'])) { $rData['allowed_ips'] = [$rData['allowed_ips']]; } @@ -320,15 +301,12 @@ class ResellerAPI { } else { $rUserArray['allowed_ips'] = '[]'; } - if (isset($rData['is_isplock'])) { $rUserArray['is_isplock'] = 1; } else { $rUserArray['is_isplock'] = 0; } - - if (strlen($rData['isp_clear']) != 0) { - } else { + if (strlen($rData['isp_clear']) == 0) { $rUserArray['isp_desc'] = ''; $rUserArray['as_number'] = null; } @@ -353,16 +331,13 @@ class ResellerAPI { $rPrepare = QueryHelper::prepareArray($rUserArray); $rQuery = 'REPLACE INTO `lines`(' . $rPrepare['columns'] . ') VALUES(' . $rPrepare['placeholder'] . ');'; - if (!$db->query($rQuery, ...$rPrepare['data'])) { - } else { + if ($db->query($rQuery, ...$rPrepare['data'])) { $rInsertID = $db->last_insert_id(); MagService::syncLineDevices($rInsertID); $db->query('INSERT INTO `signals`(`server_id`, `cache`, `time`, `custom_data`) VALUES(?, 1, ?, ?);', SERVER_ID, time(), json_encode(['type' => 'update_line', 'id' => $rInsertID])); $rArray['user_id'] = $rInsertID; unset($rArray['user'], $rArray['paired']); - - if (isset($rData['edit'])) { - } else { + if (!isset($rData['edit'])) { $rArray['ver'] = ''; $rArray['device_id2'] = $rArray['ver']; $rArray['device_id'] = $rArray['device_id2']; @@ -371,10 +346,8 @@ class ResellerAPI { $rArray['image_version'] = $rArray['stb_type']; $rArray['sn'] = $rArray['image_version']; } - $rPrepare = QueryHelper::prepareArray($rArray); $rQuery = 'REPLACE INTO `mag_devices`(' . $rPrepare['columns'] . ') VALUES(' . $rPrepare['placeholder'] . ');'; - if ($db->query($rQuery, ...$rPrepare['data'])) { $rInsertID = $db->last_insert_id(); @@ -400,9 +373,7 @@ class ResellerAPI { return ['status' => STATUS_SUCCESS, 'data' => ['insert_id' => $rInsertID]]; } - - if (isset($rData['edit'])) { - } else { + if (!isset($rData['edit'])) { $db->query('DELETE FROM `lines` WHERE `id` = ?;', $rInsertID); } } @@ -414,9 +385,8 @@ class ResellerAPI { } return ['status' => STATUS_INVALID_MAC, 'data' => $rData]; - } else { - return false; } + return false; } /** @@ -472,7 +442,7 @@ class ResellerAPI { } else { $rOverride = json_decode(self::$rUserInfo['override_packages'], true); - if (isset($rOverride[$rPackage['id']]['official_credits']) && 0 < strlen($rOverride[$rPackage['id']]['official_credits'])) { + if (isset($rOverride[$rPackage['id']]['official_credits']) && (string) $rOverride[$rPackage['id']]['official_credits'] !== '') { $rCost = intval($rOverride[$rPackage['id']]['official_credits']); } else { $rCost = intval($rPackage['official_credits']); @@ -499,19 +469,14 @@ class ResellerAPI { $rBouquets = array_values(json_decode($rPackage['bouquets'], true)); - if (!(self::$rPermissions['allow_change_bouquets'] && 0 < count($rData['bouquets_selected'] ?? []))) { - } else { + if (self::$rPermissions['allow_change_bouquets'] && 0 < count($rData['bouquets_selected'] ?? [])) { $rNewBouquets = []; - foreach ($rData['bouquets_selected'] as $rBouquetID) { - if (!in_array($rBouquetID, $rBouquets)) { - } else { + if (in_array($rBouquetID, $rBouquets)) { $rNewBouquets[] = $rBouquetID; } } - - if (0 >= count($rNewBouquets)) { - } else { + if (0 < count($rNewBouquets)) { $rBouquets = $rNewBouquets; } } @@ -546,28 +511,20 @@ class ResellerAPI { return ['status' => STATUS_INVALID_PACKAGE, 'data' => $rData]; } - if (!(isset($rData['edit']) && $rUserArray['package_id'])) { - } else { + if (isset($rData['edit']) && $rUserArray['package_id']) { $rPackage = PackageService::getById($rUserArray['package_id']); $rBouquets = array_values(json_decode($rPackage['bouquets'], true)); - - if (!(self::$rPermissions['allow_change_bouquets'] && 0 < count($rData['bouquets_selected'] ?? []))) { - } else { + if (self::$rPermissions['allow_change_bouquets'] && 0 < count($rData['bouquets_selected'] ?? [])) { $rNewBouquets = []; - foreach ($rData['bouquets_selected'] as $rBouquetID) { - if (!in_array($rBouquetID, $rBouquets)) { - } else { + if (in_array($rBouquetID, $rBouquets)) { $rNewBouquets[] = $rBouquetID; } } - - if (0 >= count($rNewBouquets)) { - } else { + if (0 < count($rNewBouquets)) { $rBouquets = $rNewBouquets; } } - $rUserArray['bouquet'] = AdminHelpers::sortArrayByArray($rBouquets, array_keys(BouquetService::getOrder())); $rUserArray['bouquet'] = '[' . implode(',', array_map('intval', $rUserArray['bouquet'])) . ']'; } @@ -585,11 +542,9 @@ class ResellerAPI { $rUserArray['member_id'] = self::$rUserInfo['id']; } - if (!self::$rPermissions['allow_restrictions']) { - } else { + if (self::$rPermissions['allow_restrictions']) { if (isset($rData['allowed_ips'])) { - if (is_array($rData['allowed_ips'])) { - } else { + if (!is_array($rData['allowed_ips'])) { $rData['allowed_ips'] = [$rData['allowed_ips']]; } @@ -597,15 +552,12 @@ class ResellerAPI { } else { $rUserArray['allowed_ips'] = '[]'; } - if (isset($rData['is_isplock'])) { $rUserArray['is_isplock'] = 1; } else { $rUserArray['is_isplock'] = 0; } - - if (strlen($rData['isp_clear']) != 0) { - } else { + if (strlen($rData['isp_clear']) == 0) { $rUserArray['isp_desc'] = ''; $rUserArray['as_number'] = null; } @@ -630,16 +582,13 @@ class ResellerAPI { $rPrepare = QueryHelper::prepareArray($rUserArray); $rQuery = 'REPLACE INTO `lines`(' . $rPrepare['columns'] . ') VALUES(' . $rPrepare['placeholder'] . ');'; - if (!$db->query($rQuery, ...$rPrepare['data'])) { - } else { + if ($db->query($rQuery, ...$rPrepare['data'])) { $rInsertID = $db->last_insert_id(); MagService::syncLineDevices($rInsertID); $db->query('INSERT INTO `signals`(`server_id`, `cache`, `time`, `custom_data`) VALUES(?, 1, ?, ?);', SERVER_ID, time(), json_encode(['type' => 'update_line', 'id' => $rInsertID])); $rArray['user_id'] = $rInsertID; unset($rArray['user'], $rArray['paired']); - - if (isset($rData['edit'])) { - } else { + if (!isset($rData['edit'])) { $rArray['token'] = ''; $rArray['lversion'] = $rArray['token']; $rArray['cpu'] = $rArray['lversion']; @@ -647,10 +596,8 @@ class ResellerAPI { $rArray['local_ip'] = $rArray['enigma_version']; $rArray['modem_mac'] = $rArray['local_ip']; } - $rPrepare = QueryHelper::prepareArray($rArray); $rQuery = 'REPLACE INTO `enigma2_devices`(' . $rPrepare['columns'] . ') VALUES(' . $rPrepare['placeholder'] . ');'; - if ($db->query($rQuery, ...$rPrepare['data'])) { $rInsertID = $db->last_insert_id(); @@ -676,9 +623,7 @@ class ResellerAPI { return ['status' => STATUS_SUCCESS, 'data' => ['insert_id' => $rInsertID]]; } - - if (isset($rData['edit'])) { - } else { + if (!isset($rData['edit'])) { $db->query('DELETE FROM `lines` WHERE `id` = ?;', $rInsertID); } } @@ -690,9 +635,8 @@ class ResellerAPI { } return ['status' => STATUS_INVALID_MAC, 'data' => $rData]; - } else { - return false; } + return false; } /** @@ -710,8 +654,7 @@ class ResellerAPI { $rArray = UserRepository::getRegisteredUserById($rData['edit']); if ($rArray && Authorization::check('user', $rArray['id'])) { - if ($rArray['id'] != self::$rUserInfo['id']) { - } else { + if ($rArray['id'] == self::$rUserInfo['id']) { return false; } } else { @@ -723,8 +666,7 @@ class ResellerAPI { unset($rArray['id']); } - if (self::$rPermissions['allow_change_username']) { - } else { + if (!self::$rPermissions['allow_change_username']) { if (isset($rArray['id'])) { $rData['username'] = $rArray['username']; } else { @@ -732,8 +674,7 @@ class ResellerAPI { } } - if (self::$rPermissions['allow_change_password']) { - } else { + if (!self::$rPermissions['allow_change_password']) { if (isset($rArray['id'])) { $rData['password'] = ''; } else { @@ -746,8 +687,7 @@ class ResellerAPI { if (!QueryHelper::checkExists('users', 'username', $rArray['username'], 'id', $rData['edit'] ?? null)) { $rArray['username'] = $rData['username']; - if (0 >= strlen($rData['password'])) { - } else { + if ((string) $rData['password'] !== '') { $rArray['password'] = Authenticator::hashPassword($rData['password']); } @@ -757,12 +697,9 @@ class ResellerAPI { $rArray['owner_id'] = self::$rUserInfo['id']; } - if (isset($rData['edit'])) { - } else { + if (!isset($rData['edit'])) { $rCost = intval(self::$rPermissions['create_sub_resellers_price']); - - if (self::$rUserInfo['credits'] - $rCost >= 0) { - } else { + if (self::$rUserInfo['credits'] - $rCost < 0) { return ['status' => STATUS_INSUFFICIENT_CREDITS, 'data' => $rData]; } } @@ -826,8 +763,7 @@ class ResellerAPI { if (isset($rData['edit'])) { $rArray = TicketRepository::getById($rData['edit']); - if ($rArray && Authorization::check('user', $rArray['member_id'])) { - } else { + if (!$rArray || !Authorization::check('user', $rArray['member_id'])) { return false; } } else { @@ -835,7 +771,7 @@ class ResellerAPI { unset($rArray['id']); } - if (!(strlen($rData['title']) == 0 && !isset($rData['respond']) || strlen($rData['message']) == 0)) { + if ((strlen($rData['title']) != 0 || isset($rData['respond'])) && strlen($rData['message']) != 0) { $rArray['member_id'] = self::$rUserInfo['id']; if (!isset($rData['respond'])) { @@ -891,8 +827,7 @@ class ResellerAPI { $rArray = UserRepository::getLineById($rData['edit']); $rOrigCredentials = ['username' => $rArray['username'], 'password' => $rArray['password']]; - if ($rArray && Authorization::check('line', $rArray['id'])) { - } else { + if (!$rArray || !Authorization::check('line', $rArray['id'])) { return false; } } else { @@ -926,7 +861,7 @@ class ResellerAPI { } else { $rOverride = json_decode(self::$rUserInfo['override_packages'], true); - if (isset($rOverride[$rPackage['id']]['official_credits']) && 0 < strlen($rOverride[$rPackage['id']]['official_credits'])) { + if (isset($rOverride[$rPackage['id']]['official_credits']) && (string) $rOverride[$rPackage['id']]['official_credits'] !== '') { $rCost = intval($rOverride[$rPackage['id']]['official_credits']); } else { $rCost = intval($rPackage['official_credits']); @@ -953,19 +888,14 @@ class ResellerAPI { $rBouquets = array_values(json_decode($rPackage['bouquets'], true)); - if (!(self::$rPermissions['allow_change_bouquets'] && 0 < count($rData['bouquets_selected'] ?? []))) { - } else { + if (self::$rPermissions['allow_change_bouquets'] && 0 < count($rData['bouquets_selected'] ?? [])) { $rNewBouquets = []; - foreach ($rData['bouquets_selected'] as $rBouquetID) { - if (!in_array($rBouquetID, $rBouquets)) { - } else { + if (in_array($rBouquetID, $rBouquets)) { $rNewBouquets[] = $rBouquetID; } } - - if (0 >= count($rNewBouquets)) { - } else { + if (0 < count($rNewBouquets)) { $rBouquets = $rNewBouquets; } } @@ -992,28 +922,20 @@ class ResellerAPI { return ['status' => STATUS_INVALID_PACKAGE, 'data' => $rData]; } - if (!(isset($rData['edit']) && $rArray['package_id'])) { - } else { + if (isset($rData['edit']) && $rArray['package_id']) { $rPackage = PackageService::getById($rArray['package_id']); $rBouquets = array_values(json_decode($rPackage['bouquets'], true)); - - if (!(self::$rPermissions['allow_change_bouquets'] && 0 < count($rData['bouquets_selected'] ?? []))) { - } else { + if (self::$rPermissions['allow_change_bouquets'] && 0 < count($rData['bouquets_selected'] ?? [])) { $rNewBouquets = []; - foreach ($rData['bouquets_selected'] as $rBouquetID) { - if (!in_array($rBouquetID, $rBouquets)) { - } else { + if (in_array($rBouquetID, $rBouquets)) { $rNewBouquets[] = $rBouquetID; } } - - if (0 >= count($rNewBouquets)) { - } else { + if (0 < count($rNewBouquets)) { $rBouquets = $rNewBouquets; } } - $rArray['bouquet'] = AdminHelpers::sortArrayByArray($rBouquets, array_keys(BouquetService::getOrder())); $rArray['bouquet'] = '[' . implode(',', array_map('intval', $rArray['bouquet'])) . ']'; } @@ -1029,8 +951,7 @@ class ResellerAPI { $rArray['member_id'] = self::$rUserInfo['id']; } - if (self::$rPermissions['allow_change_username']) { - } else { + if (!self::$rPermissions['allow_change_username']) { if (isset($rArray['id'])) { $rData['username'] = $rArray['username']; } else { @@ -1038,8 +959,7 @@ class ResellerAPI { } } - if (self::$rPermissions['allow_change_password']) { - } else { + if (!self::$rPermissions['allow_change_password']) { if (isset($rArray['id'])) { $rData['password'] = $rArray['password']; } else { @@ -1054,10 +974,8 @@ class ResellerAPI { $rData['username'] = $rArray['username']; } } else { - if (strlen($rData['username']) >= self::$rPermissions['minimum_username_length']) { - } else { - if (isset($rData['edit']) && $rData['username'] == $rOrigCredentials['username']) { - } else { + if (strlen($rData['username']) < self::$rPermissions['minimum_username_length']) { + if (!isset($rData['edit']) || $rData['username'] != $rOrigCredentials['username']) { return ['status' => STATUS_INVALID_USERNAME, 'data' => $rData]; } } @@ -1070,31 +988,25 @@ class ResellerAPI { $rData['password'] = $rArray['password']; } } else { - if (strlen($rData['password']) >= self::$rPermissions['minimum_password_length']) { - } else { - if (isset($rData['edit']) && $rData['password'] == $rOrigCredentials['password']) { - } else { + if (strlen($rData['password']) < self::$rPermissions['minimum_password_length']) { + if (!isset($rData['edit']) || $rData['password'] != $rOrigCredentials['password']) { return ['status' => STATUS_INVALID_PASSWORD, 'data' => $rData]; } } } - if (empty($rData['username'])) { - } else { + if (!empty($rData['username'])) { $rArray['username'] = $rData['username']; } - if (empty($rData['password'])) { - } else { + if (!empty($rData['password'])) { $rArray['password'] = $rData['password']; } if (!QueryHelper::checkExists('lines', 'username', $rArray['username'], 'id', $rData['edit'] ?? null)) { - if (!self::$rPermissions['allow_restrictions']) { - } else { + if (self::$rPermissions['allow_restrictions']) { if (isset($rData['allowed_ips'])) { - if (is_array($rData['allowed_ips'])) { - } else { + if (!is_array($rData['allowed_ips'])) { $rData['allowed_ips'] = [$rData['allowed_ips']]; } @@ -1102,10 +1014,8 @@ class ResellerAPI { } else { $rArray['allowed_ips'] = '[]'; } - if (isset($rData['allowed_ua'])) { - if (is_array($rData['allowed_ua'])) { - } else { + if (!is_array($rData['allowed_ua'])) { $rData['allowed_ua'] = [$rData['allowed_ua']]; } @@ -1113,31 +1023,25 @@ class ResellerAPI { } else { $rArray['allowed_ua'] = '[]'; } - if (isset($rData['bypass_ua'])) { $rArray['bypass_ua'] = 1; } else { $rArray['bypass_ua'] = 0; } - if (isset($rData['is_isplock'])) { $rArray['is_isplock'] = 1; } else { $rArray['is_isplock'] = 0; } - - if (strlen($rData['isp_clear']) != 0) { - } else { + if (strlen($rData['isp_clear']) == 0) { $rArray['isp_desc'] = ''; $rArray['as_number'] = null; } } - if (!isset($rPackage)) { - } else { + if (isset($rPackage)) { $rOutputs = []; $rAccessOutput = json_decode($rPackage['output_formats'], true) ?: []; - foreach ($rAccessOutput as $rOutputID) { $rOutputs[] = $rOutputID; } diff --git a/src/Domain/User/TicketRepository.php b/src/Domain/User/TicketRepository.php index e3fcbbea..f9abd825 100644 --- a/src/Domain/User/TicketRepository.php +++ b/src/Domain/User/TicketRepository.php @@ -39,8 +39,7 @@ class TicketRepository { foreach ($db->get_rows() as $rReply) { $rReply['message'] = htmlspecialchars($rReply['message']); - if (strlen($rReply['message']) >= 80) { - } else { + if (strlen($rReply['message']) < 80) { $rReply['message'] .= str_repeat('  ', 80 - strlen($rReply['message'])); } @@ -73,8 +72,7 @@ class TicketRepository { $db->query('SELECT `tickets`.`id`, `tickets`.`member_id`, `tickets`.`title`, `tickets`.`status`, `tickets`.`admin_read`, `tickets`.`user_read`, `users`.`username` FROM `tickets`, `users` WHERE `users`.`id` = `tickets`.`member_id` ORDER BY `id` DESC;'); } - if (0 >= $db->num_rows()) { - } else { + if (0 < $db->num_rows()) { foreach ($db->get_rows() as $rRow) { $db->query('SELECT MIN(`date`) AS `date` FROM `tickets_replies` WHERE `ticket_id` = ?;', $rRow['id']); @@ -89,8 +87,7 @@ class TicketRepository { $rRow['last_reply'] = date('Y-m-d H:i', $rLastResponse['date']); if ($rRow['member_id'] == $rID) { - if ($rRow['status'] == 0) { - } else { + if ($rRow['status'] != 0) { if ($rLastResponse['admin_reply']) { if ($rRow['user_read'] == 1) { $rRow['status'] = 3; @@ -106,8 +103,7 @@ class TicketRepository { } } } else { - if ($rRow['status'] == 0) { - } else { + if ($rRow['status'] != 0) { if ($rLastResponse['admin_reply']) { if ($rRow['user_read'] == 1) { $rRow['status'] = 6; diff --git a/src/Domain/User/UserRepository.php b/src/Domain/User/UserRepository.php index cce1969f..9ac4014e 100644 --- a/src/Domain/User/UserRepository.php +++ b/src/Domain/User/UserRepository.php @@ -32,12 +32,11 @@ class UserRepository { * @param string|null $rConIspName Detected ISP name (null/'' on a miss). * @param int $rIspViolate Current isp_violate flag. * @param string|null $rIspDesc ISP currently stored on the line. - * @return bool */ public static function ispChanged(?string $rConIspName, int $rIspViolate, ?string $rIspDesc): bool { return !empty($rConIspName) && $rIspViolate == 0 - && strtolower((string) $rConIspName) != strtolower((string) $rIspDesc); + && strtolower($rConIspName) != strtolower((string) $rIspDesc); } /** diff --git a/src/Domain/User/UserService.php b/src/Domain/User/UserService.php index 47260b0c..27863031 100644 --- a/src/Domain/User/UserService.php +++ b/src/Domain/User/UserService.php @@ -81,7 +81,7 @@ class UserService { if (substr($rKey, 0, 9) == 'override_') { $rID = intval(explode('override_', $rKey)[1]); - if (0 < strlen($rCredits)) { + if ((string) $rCredits !== '') { $rCredits = intval($rCredits); } else { $rCredits = null; @@ -111,9 +111,8 @@ class UserService { } return ['status' => STATUS_SUCCESS]; - } else { - return ['status' => STATUS_INVALID_INPUT, 'data' => $rData]; } + return ['status' => STATUS_INVALID_INPUT, 'data' => $rData]; } /** @@ -149,7 +148,7 @@ class UserService { } if (!QueryHelper::checkExists('users', 'username', $rArray['username'], 'id', $rData['edit'] ?? null)) { - if (strlen($rData['password']) > 0) { + if ((string) $rData['password'] !== '') { $rArray['password'] = Authenticator::hashPassword($rData['password']); } @@ -159,7 +158,7 @@ class UserService { if (substr($rKey, 0, 9) == 'override_') { $rID = intval(explode('override_', $rKey)[1]); - if (0 < strlen($rCredits)) { + if ((string) $rCredits !== '') { $rCredits = intval($rCredits); } else { $rCredits = null; @@ -197,15 +196,12 @@ class UserService { } return ['status' => STATUS_FAILURE, 'data' => $rData]; - } else { - return ['status' => STATUS_EXISTS_USERNAME, 'data' => $rData]; } - } else { - return ['status' => STATUS_INVALID_GROUP, 'data' => $rData]; + return ['status' => STATUS_EXISTS_USERNAME, 'data' => $rData]; } - } else { - return ['status' => STATUS_INVALID_INPUT, 'data' => $rData]; + return ['status' => STATUS_INVALID_GROUP, 'data' => $rData]; } + return ['status' => STATUS_INVALID_INPUT, 'data' => $rData]; } /** @@ -218,17 +214,17 @@ class UserService { */ public static function editAdminProfile(array $rData, array $rUserInfo, array $allowedLangs) { $db = self::db(); - if (!(0 >= strlen($rData['email']) || filter_var($rData['email'], FILTER_VALIDATE_EMAIL))) { + if ((string) $rData['email'] !== '' && !filter_var($rData['email'], FILTER_VALIDATE_EMAIL)) { return ['status' => STATUS_INVALID_EMAIL]; } - if (0 < strlen($rData['password'])) { + if ((string) $rData['password'] !== '') { $rPassword = Authenticator::hashPassword($rData['password']); } else { $rPassword = $rUserInfo['password']; } - if (!isset($rData['api_key']) || !(ctype_xdigit($rData['api_key']) && strlen($rData['api_key']) == 32)) { + if (!isset($rData['api_key']) || (!ctype_xdigit($rData['api_key']) || strlen($rData['api_key']) != 32)) { $rData['api_key'] = ''; } diff --git a/src/Domain/Vod/EpisodeService.php b/src/Domain/Vod/EpisodeService.php index a40ea21d..dbac4445 100644 --- a/src/Domain/Vod/EpisodeService.php +++ b/src/Domain/Vod/EpisodeService.php @@ -62,9 +62,9 @@ class EpisodeService { $rArray['stream_source'] = [$rData['stream_source'] ?? $rFallbackStreamSource]; $rMovieSubtitles = $rData['movie_subtitles'] ?? ''; - if (0 < strlen($rMovieSubtitles)) { + if ((string) $rMovieSubtitles !== '') { $rSplit = explode(':', $rMovieSubtitles); - if (2 < count($rSplit) && 0 < strlen($rSplit[2])) { + if (2 < count($rSplit) && $rSplit[2] !== '') { $rArray['movie_subtitles'] = ['files' => [$rSplit[2]], 'names' => ['Subtitles'], 'charset' => ['UTF-8'], 'location' => intval($rSplit[1])]; } else { $rArray['movie_subtitles'] = null; @@ -99,7 +99,7 @@ class EpisodeService { TMDbService::requireLibrary(); $rSeries = SeriesService::getById(intval($rData['series'])); - if (0 < strlen($rSettings['tmdb_language'])) { + if ((string) $rSettings['tmdb_language'] !== '') { $rTMDB = new \TMDB($rSettings['tmdb_api_key'], $rSettings['tmdb_language']); } else { $rTMDB = new \TMDB($rSettings['tmdb_api_key']); @@ -111,7 +111,7 @@ class EpisodeService { $rSplit = explode('_', $rKey); if ($rSplit[0] == 'episode' && $rSplit[2] == 'name') { - if (0 < strlen($rData['episode_' . $rSplit[1] . '_num'])) { + if ((string) $rData['episode_' . $rSplit[1] . '_num'] !== '') { $rImportArray = ['filename' => '', 'properties' => [], 'name' => '', 'episode' => 0, 'target_container' => '']; $rEpisodeNum = intval($rData['episode_' . $rSplit[1] . '_num']); $rImportArray['filename'] = 's:' . $rData['server'] . ':' . $rData['season_folder'] . $rFilename; @@ -129,7 +129,7 @@ class EpisodeService { foreach ($rJSON['episodes'] as $rEpisode) { if (intval($rEpisode['episode_number']) == $rEpisodeNum) { - if (0 < strlen($rEpisode['still_path'])) { + if ((string) $rEpisode['still_path'] !== '') { $rImage = 'https://image.tmdb.org/t/p/w600_and_h900_bestv2' . $rEpisode['still_path']; if ($rSettings['download_images']) { @@ -164,7 +164,7 @@ class EpisodeService { $rImportArray = ['filename' => $rArray['stream_source'][0], 'properties' => [], 'name' => $rArray['stream_display_name'], 'episode' => $rData['episode'], 'target_container' => $rData['target_container']]; $rMovieImage = $rData['movie_image'] ?? ''; - if ($rSettings['download_images'] && 0 < strlen($rMovieImage)) { + if ($rSettings['download_images'] && (string) $rMovieImage !== '') { $rMovieImage = ImageUtils::downloadImage($rMovieImage, 5); } diff --git a/src/Infrastructure/Bootstrap/ScopeBootstrapFactory.php b/src/Infrastructure/Bootstrap/ScopeBootstrapFactory.php index 239ccc74..d216ac4d 100644 --- a/src/Infrastructure/Bootstrap/ScopeBootstrapFactory.php +++ b/src/Infrastructure/Bootstrap/ScopeBootstrapFactory.php @@ -17,7 +17,6 @@ namespace XcVm\Infrastructure\Bootstrap; final class ScopeBootstrapFactory { /** * @param string $rScope 'admin' | 'reseller' | 'player' (others → admin). - * @return ScopeBootstrap */ public static function create(string $rScope): ScopeBootstrap { switch ($rScope) { diff --git a/src/Infrastructure/Database/DatabaseAware.php b/src/Infrastructure/Database/DatabaseAware.php index d8c75c5e..3cbcd95f 100644 --- a/src/Infrastructure/Database/DatabaseAware.php +++ b/src/Infrastructure/Database/DatabaseAware.php @@ -37,7 +37,7 @@ use XcVm\Core\Database\DatabaseHandler; */ trait DatabaseAware { /** @var DatabaseHandler|null Explicitly injected handler (optional). */ - private static $db = null; + private static $db; /** * Explicitly inject the database handler. @@ -46,7 +46,6 @@ trait DatabaseAware { * tests/mocks and backward compatibility with DomainDatabaseWiring. * * @param DatabaseHandler $db Database handler. - * @return void */ public static function setDb(DatabaseHandler $db): void { self::$db = $db; diff --git a/src/Infrastructure/Database/DatabaseFactory.php b/src/Infrastructure/Database/DatabaseFactory.php index ca695790..588e2ef7 100644 --- a/src/Infrastructure/Database/DatabaseFactory.php +++ b/src/Infrastructure/Database/DatabaseFactory.php @@ -18,7 +18,7 @@ use XcVm\Core\Database\DatabaseHandler; class DatabaseFactory { /** @var DatabaseHandler|null */ - private static $instance = null; + private static $instance; /** * Сохраняет экземпляр DatabaseHandler в singleton-реестре. diff --git a/src/Infrastructure/Redis/RedisManager.php b/src/Infrastructure/Redis/RedisManager.php index ea0175f0..6170afda 100644 --- a/src/Infrastructure/Redis/RedisManager.php +++ b/src/Infrastructure/Redis/RedisManager.php @@ -20,7 +20,7 @@ use XcVm\Infrastructure\Signal\SignalQueue; class RedisManager { /** @var \Redis|null Singleton instance */ - private static $instance = null; + private static $instance; /** @var int Last ping health-check timestamp */ private static $lastPingCheck = 0; @@ -41,7 +41,7 @@ class RedisManager { if ($rNow - self::$lastPingCheck > 30) { try { $rPong = self::$instance->ping(); - if ($rPong !== true && $rPong !== '+PONG' && $rPong !== 'PONG') { + if (!in_array($rPong, [true, '+PONG', 'PONG'], true)) { throw new \RedisException('unhealthy ping reply'); } self::$lastPingCheck = $rNow; @@ -106,7 +106,6 @@ class RedisManager { * * @param string $rKey Signal key. * @param mixed $rData Signal payload. - * @return void */ public static function setSignal(string $rKey, mixed $rData): void { SignalQueue::push($rKey, $rData); diff --git a/src/Infrastructure/ResellerApiDispatcher.php b/src/Infrastructure/ResellerApiDispatcher.php index c74edffe..ff5b9025 100644 --- a/src/Infrastructure/ResellerApiDispatcher.php +++ b/src/Infrastructure/ResellerApiDispatcher.php @@ -50,7 +50,7 @@ class ResellerApiDispatcher { public static function dispatch(string $action, ?array $rUserInfo, array $rPermissions): void { switch ($action) { case 'dashboard': - self::handleDashboard($rUserInfo, $rPermissions); + self::handleDashboard($rUserInfo); break; case 'connections': self::handleConnections($rUserInfo, $rPermissions); @@ -59,7 +59,7 @@ class ResellerApiDispatcher { self::handleLine($rUserInfo, $rPermissions); break; case 'line_activity': - self::handleLineActivity($rUserInfo, $rPermissions); + self::handleLineActivity($rPermissions); break; case 'adjust_credits': self::handleAdjustCredits($rUserInfo, $rPermissions); @@ -68,7 +68,7 @@ class ResellerApiDispatcher { self::handleRegUser($rUserInfo, $rPermissions); break; case 'ticket': - self::handleTicket($rUserInfo, $rPermissions); + self::handleTicket($rUserInfo); break; case 'mag': self::handleMag($rUserInfo, $rPermissions); @@ -77,49 +77,49 @@ class ResellerApiDispatcher { self::handleEnigma($rUserInfo, $rPermissions); break; case 'get_package': - self::handleGetPackage($rUserInfo, $rPermissions); + self::handleGetPackage($rUserInfo); break; case 'get_package_trial': - self::handleGetPackageTrial($rUserInfo, $rPermissions); + self::handleGetPackageTrial(); break; case 'header_stats': - self::handleHeaderStats($rUserInfo, $rPermissions); + self::handleHeaderStats($rUserInfo); break; case 'stats': - self::handleStats($rUserInfo, $rPermissions); + self::handleStats($rUserInfo); break; case 'userlist': - self::handleUserList($rUserInfo, $rPermissions); + self::handleUserList($rUserInfo); break; case 'send_event': self::handleSendEvent($rUserInfo, $rPermissions); break; case 'streamlist': - self::handleStreamList($rUserInfo, $rPermissions); + self::handleStreamList($rPermissions); break; case 'ip_whois': - self::handleIpWhois($rUserInfo, $rPermissions); + self::handleIpWhois(); break; case 'get_epg': - self::handleGetEpg($rUserInfo, $rPermissions); + self::handleGetEpg($rPermissions); break; case 'get_programme': - self::handleGetProgramme($rUserInfo, $rPermissions); + self::handleGetProgramme($rPermissions); break; case 'active_code_details': - self::handleActiveCodeDetails($rUserInfo, $rPermissions); + self::handleActiveCodeDetails($rUserInfo); break; case 'active_codes_mass': - self::handleActiveCodesMass($rUserInfo, $rPermissions); + self::handleActiveCodesMass($rUserInfo); break; case 'active_codes_batch_action': - self::handleActiveCodesBatchAction($rUserInfo, $rPermissions); + self::handleActiveCodesBatchAction($rUserInfo); break; case 'active_codes_export_txt': - self::handleActiveCodesExportTxt($rUserInfo, $rPermissions); + self::handleActiveCodesExportTxt($rUserInfo); break; case 'generate_active_codes': - self::handleGenerateActiveCodes($rUserInfo, $rPermissions); + self::handleGenerateActiveCodes($rUserInfo); break; } } @@ -128,10 +128,8 @@ class ResellerApiDispatcher { * Output reseller dashboard data (JSON) and exit. * * @param array $rUserInfo Authenticated reseller user. - * @param array $rPermissions Effective permissions. - * @return void */ - private static function handleDashboard(array $rUserInfo, array $rPermissions): void { + private static function handleDashboard(array $rUserInfo): void { $db = self::db(); $rReturn = ['open_connections' => 0, 'online_users' => 0, 'active_accounts' => 0, 'credits' => 0, 'credits_assigned' => 0]; @@ -170,7 +168,6 @@ class ResellerApiDispatcher { * * @param array $rUserInfo Authenticated reseller user. * @param array $rPermissions Effective permissions. - * @return void */ private static function handleConnections(array $rUserInfo, array $rPermissions): void { $db = self::db(); @@ -212,7 +209,6 @@ class ResellerApiDispatcher { * * @param array $rUserInfo Authenticated reseller user. * @param array $rPermissions Effective permissions. - * @return void */ private static function handleLine(array $rUserInfo, array $rPermissions): void { $db = self::db(); @@ -282,11 +278,9 @@ class ResellerApiDispatcher { /** * Output a line's activity log (JSON) and exit. * - * @param array $rUserInfo Authenticated reseller user. * @param array $rPermissions Effective permissions. - * @return void */ - private static function handleLineActivity(array $rUserInfo, array $rPermissions): void { + private static function handleLineActivity(array $rPermissions): void { $db = self::db(); if ($rPermissions['reseller_client_connection_logs']) { $rSub = RequestManager::get('sub'); @@ -330,7 +324,6 @@ class ResellerApiDispatcher { * * @param array $rUserInfo Authenticated reseller user. * @param array $rPermissions Effective permissions. - * @return void */ private static function handleAdjustCredits(array $rUserInfo, array $rPermissions): void { $db = self::db(); @@ -367,7 +360,6 @@ class ResellerApiDispatcher { * * @param array $rUserInfo Authenticated reseller user. * @param array $rPermissions Effective permissions. - * @return void */ private static function handleRegUser(array $rUserInfo, array $rPermissions): void { $db = self::db(); @@ -417,10 +409,8 @@ class ResellerApiDispatcher { * Submit/handle a support ticket (JSON) and exit. * * @param array $rUserInfo Authenticated reseller user. - * @param array $rPermissions Effective permissions. - * @return void */ - private static function handleTicket(array $rUserInfo, array $rPermissions): void { + private static function handleTicket(array $rUserInfo): void { $db = self::db(); $rTicket = TicketRepository::getById(RequestManager::get('ticket_id')); @@ -457,7 +447,6 @@ class ResellerApiDispatcher { * * @param array $rUserInfo Authenticated reseller user. * @param array $rPermissions Effective permissions. - * @return void */ private static function handleMag(array $rUserInfo, array $rPermissions): void { $db = self::db(); @@ -537,7 +526,6 @@ class ResellerApiDispatcher { * * @param array $rUserInfo Authenticated reseller user. * @param array $rPermissions Effective permissions. - * @return void */ private static function handleEnigma(array $rUserInfo, array $rPermissions): void { $db = self::db(); @@ -616,10 +604,8 @@ class ResellerApiDispatcher { * Output package details/options (JSON) and exit. * * @param array $rUserInfo Authenticated reseller user. - * @param array $rPermissions Effective permissions. - * @return void */ - private static function handleGetPackage(array $rUserInfo, array $rPermissions): void { + private static function handleGetPackage(array $rUserInfo): void { $db = self::db(); $rReturn = []; $rOverride = json_decode($rUserInfo['override_packages'], true); @@ -628,7 +614,7 @@ class ResellerApiDispatcher { if ($db->num_rows() == 1) { $rData = $db->get_row(); - if (isset($rOverride[$rData['id']]['official_credits']) && 0 < strlen($rOverride[$rData['id']]['official_credits'])) { + if (isset($rOverride[$rData['id']]['official_credits']) && (string) $rOverride[$rData['id']]['official_credits'] !== '') { $rData['cost_credits'] = $rOverride[$rData['id']]['official_credits']; } @@ -668,16 +654,11 @@ class ResellerApiDispatcher { /** * Output trial package details (JSON) and exit. - * - * @param array $rUserInfo Authenticated reseller user. - * @param array $rPermissions Effective permissions. - * @return void */ - private static function handleGetPackageTrial(array $rUserInfo, array $rPermissions): void { + private static function handleGetPackageTrial(): void { $db = self::db(); $rReturn = []; $db->query('SELECT `bouquets`, `trial_credits` AS `cost_credits`, `trial_duration`, `trial_duration_in`, `max_connections`, `is_isplock` FROM `users_packages` WHERE `id` = ?;', RequestManager::get('package_id')); - if ($db->num_rows() == 1) { $rData = $db->get_row(); $rData['exp_date'] = date('Y-m-d H:i', strtotime('+' . intval($rData['trial_duration']) . ' ' . $rData['trial_duration_in'])); @@ -702,10 +683,8 @@ class ResellerApiDispatcher { * Output header summary statistics (JSON) and exit. * * @param array $rUserInfo Authenticated reseller user. - * @param array $rPermissions Effective permissions. - * @return void */ - private static function handleHeaderStats(array $rUserInfo, array $rPermissions): void { + private static function handleHeaderStats(array $rUserInfo): void { $db = self::db(); $rReturn = ['total_connections' => 0, 'total_users' => 0]; @@ -738,10 +717,8 @@ class ResellerApiDispatcher { * Output reseller statistics (JSON) and exit. * * @param array $rUserInfo Authenticated reseller user. - * @param array $rPermissions Effective permissions. - * @return void */ - private static function handleStats(array $rUserInfo, array $rPermissions): void { + private static function handleStats(array $rUserInfo): void { $db = self::db(); $rReturn = ['open_connections' => 0, 'online_users' => 0, 'total_lines' => 0, 'total_users' => 0, 'owner_credits' => 0, 'user_credits' => 0, 'total_credits' => 0]; @@ -782,10 +759,8 @@ class ResellerApiDispatcher { * Output the reseller's user list (JSON) and exit. * * @param array $rUserInfo Authenticated reseller user. - * @param array $rPermissions Effective permissions. - * @return void */ - private static function handleUserList(array $rUserInfo, array $rPermissions): void { + private static function handleUserList(array $rUserInfo): void { $db = self::db(); $rReturn = ['total_count' => 0, 'items' => [], 'result' => true]; @@ -812,7 +787,6 @@ class ResellerApiDispatcher { * * @param array $rUserInfo Authenticated reseller user. * @param array $rPermissions Effective permissions. - * @return void */ private static function handleSendEvent(array $rUserInfo, array $rPermissions): void { $db = self::db(); @@ -858,11 +832,9 @@ class ResellerApiDispatcher { /** * Output the available stream list (JSON) and exit. * - * @param array $rUserInfo Authenticated reseller user. * @param array $rPermissions Effective permissions. - * @return void */ - private static function handleStreamList(array $rUserInfo, array $rPermissions): void { + private static function handleStreamList(array $rPermissions): void { $db = self::db(); if ($rPermissions['create_mag'] || $rPermissions['can_view_vod'] || $rPermissions['reseller_client_connection_logs']) { $rReturn = ['total_count' => 0, 'items' => [], 'result' => true]; @@ -889,39 +861,29 @@ class ResellerApiDispatcher { /** * Output WHOIS information for an IP (JSON) and exit. - * - * @param array $rUserInfo Authenticated reseller user. - * @param array $rPermissions Effective permissions. - * @return void */ - private static function handleIpWhois(array $rUserInfo, array $rPermissions): void { + private static function handleIpWhois(): void { $db = self::db(); $rIP = RequestManager::get('ip'); $rReader = new \MaxMind\Db\Reader(GEOLITE2C_BIN); $rResponse = $rReader->get($rIP); - if (isset($rResponse['location']['time_zone'])) { $rDate = new \DateTime('now', new \DateTimeZone($rResponse['location']['time_zone'])); $rResponse['location']['time'] = $rDate->format('Y-m-d H:i:s'); } - $rReader->close(); - if (RequestManager::has('isp')) { $rReader = new \MaxMind\Db\Reader(GEOISP_BIN); $rResponse['isp'] = $rReader->get($rIP); $rReader->close(); } - $rResponse['type'] = null; - if (!empty($rResponse['isp']['autonomous_system_number'])) { $db->query('SELECT `type` FROM `blocked_asns` WHERE `asn` = ?;', $rResponse['isp']['autonomous_system_number']); if ($db->num_rows() > 0) { $rResponse['type'] = $db->get_row()['type']; } } - echo json_encode(['result' => true, 'data' => $rResponse]); exit(); } @@ -929,11 +891,9 @@ class ResellerApiDispatcher { /** * Output EPG data for a stream (JSON) and exit. * - * @param array $rUserInfo Authenticated reseller user. * @param array $rPermissions Effective permissions. - * @return void */ - private static function handleGetEpg(array $rUserInfo, array $rPermissions): void { + private static function handleGetEpg(array $rPermissions): void { $db = self::db(); if ($rPermissions['can_view_vod']) { if (count($rPermissions['stream_ids']) != 0) { @@ -1004,7 +964,7 @@ class ResellerApiDispatcher { $rCategoryIDs = json_decode($rStream['category_id'], true); $rCategories = CategoryService::getAllByType('live'); - if (0 < strlen(RequestManager::get('category'))) { + if ((string) RequestManager::get('category') !== '') { $rCategory = ($rCategories[intval(RequestManager::get('category'))]['category_name'] ?: 'No Category'); } else { $rCategory = ($rCategories[$rCategoryIDs[0]]['category_name'] ?: 'No Category'); @@ -1031,11 +991,9 @@ class ResellerApiDispatcher { /** * Output a single EPG programme (JSON) and exit. * - * @param array $rUserInfo Authenticated reseller user. * @param array $rPermissions Effective permissions. - * @return void */ - private static function handleGetProgramme(array $rUserInfo, array $rPermissions): void { + private static function handleGetProgramme(array $rPermissions): void { $db = self::db(); if ($rPermissions['can_view_vod']) { $rTimezone = (RequestManager::get('timezone') ?: 'Europe/London'); @@ -1074,7 +1032,7 @@ class ResellerApiDispatcher { /** * Handle Active Code Details AJAX (modal view) */ - private static function handleActiveCodeDetails(?array $rUserInfo, array $rPermissions): void { + private static function handleActiveCodeDetails(?array $rUserInfo): void { $db = self::db(); $codeId = intval(RequestManager::get('id') ?? 0); if (!$codeId) { @@ -1178,7 +1136,7 @@ class ResellerApiDispatcher { /** * Handle Active Codes Mass Actions AJAX */ - private static function handleActiveCodesMass(?array $rUserInfo, array $rPermissions): void { + private static function handleActiveCodesMass(?array $rUserInfo): void { $subAction = trim(RequestManager::get('sub_action') ?? ''); $ids = json_decode(RequestManager::get('ids') ?? '[]', true) ?: []; $extra = [ @@ -1198,7 +1156,7 @@ class ResellerApiDispatcher { /** * Handle Batch Action AJAX (Enable, Disable, Delete) */ - private static function handleActiveCodesBatchAction(?array $rUserInfo, array $rPermissions): void { + private static function handleActiveCodesBatchAction(?array $rUserInfo): void { $db = self::db(); $batchName = trim(RequestManager::get('batch_name') ?? ''); $subAction = trim(RequestManager::get('sub_action') ?? ''); @@ -1233,7 +1191,7 @@ class ResellerApiDispatcher { /** * Handle Export Scratch Cards TXT */ - private static function handleActiveCodesExportTxt(?array $rUserInfo, array $rPermissions): void { + private static function handleActiveCodesExportTxt(?array $rUserInfo): void { $batchName = trim(RequestManager::get('batch_name') ?? ''); if (empty($batchName)) { exit('Invalid batch name'); @@ -1252,7 +1210,7 @@ class ResellerApiDispatcher { /** * Handle AJAX Code Generation */ - private static function handleGenerateActiveCodes(?array $rUserInfo, array $rPermissions): void { + private static function handleGenerateActiveCodes(?array $rUserInfo): void { $data = RequestManager::getAll(); $res = ActiveCodeService::generateCodes($data, $rUserInfo, false); diff --git a/tests/Unit/BouquetServiceTest.php b/tests/Unit/BouquetServiceTest.php new file mode 100644 index 00000000..2cb52fd7 --- /dev/null +++ b/tests/Unit/BouquetServiceTest.php @@ -0,0 +1,77 @@ +db = new TestDb(); + $this->db->exec( + 'CREATE TABLE bouquets (id INTEGER PRIMARY KEY, bouquet_channels TEXT, bouquet_movies TEXT, bouquet_radios TEXT, bouquet_series TEXT);' + ); + $this->db->query( + 'INSERT INTO bouquets (id, bouquet_channels, bouquet_movies, bouquet_radios, bouquet_series) VALUES (1, ?, ?, "[]", "[]");', + '[10,20,30]', + '[5,6]' + ); + BouquetService::setDb($this->db); + } + + private function channels(): array { + $this->db->query('SELECT `bouquet_channels` FROM `bouquets` WHERE `id` = 1;'); + return json_decode($this->db->get_col(), true); + } + + private function movies(): array { + $this->db->query('SELECT `bouquet_movies` FROM `bouquets` WHERE `id` = 1;'); + return json_decode($this->db->get_col(), true); + } + + public function testRemovesTheLastElementNotIndexOne(): void { + // id 30 is at index 2 — the broken variant would unset index 1 (=> 20). + BouquetService::removeItems('stream', 1, [30]); + $this->assertSame([10, 20], $this->channels()); + } + + public function testRemovesTheFirstElement(): void { + // id 10 is at index 0 — the broken variant would unset index 1 (=> 20). + BouquetService::removeItems('stream', 1, [10]); + $this->assertSame([20, 30], $this->channels()); + } + + public function testRemovesMultipleIds(): void { + BouquetService::removeItems('stream', 1, [10, 30]); + $this->assertSame([20], $this->channels()); + } + + public function testRemovingAbsentIdLeavesListUnchanged(): void { + BouquetService::removeItems('stream', 1, [999]); + $this->assertSame([10, 20, 30], $this->channels()); + } + + public function testAcceptsAScalarId(): void { + // array|int|string param: a single scalar is wrapped, not fatal. + BouquetService::removeItems('stream', 1, 20); + $this->assertSame([10, 30], $this->channels()); + } + + public function testTypeSelectsTheMoviesColumn(): void { + BouquetService::removeItems('movie', 1, [5]); + $this->assertSame([6], $this->movies()); + $this->assertSame([10, 20, 30], $this->channels(), 'channels untouched'); + } +} diff --git a/tests/Unit/MonitorCommandTest.php b/tests/Unit/MonitorCommandTest.php index c7cc7398..a5775b52 100644 --- a/tests/Unit/MonitorCommandTest.php +++ b/tests/Unit/MonitorCommandTest.php @@ -19,11 +19,17 @@ final class MonitorCommandTest extends TestCase { } } - /** Invoke a private static MonitorCommand method via reflection. */ + /** + * Invoke a private MonitorCommand method via reflection on a constructor-less + * instance. Works for both instance and (still) static helpers — a static + * method ignores the object argument. The tested helpers are pure (no $this), + * so a bare instance is sufficient. + */ private function call(string $method, ...$args) { $m = new ReflectionMethod(MonitorCommand::class, $method); $m->setAccessible(true); - return $m->invoke(null, ...$args); + $instance = (new \ReflectionClass(MonitorCommand::class))->newInstanceWithoutConstructor(); + return $m->invoke($instance, ...$args); } // ── parseFrameRate (label768/780/1047/1052/1057) ───────────