Code and PHPDoc cleanup to green-light level 2 static analysis.

This commit is contained in:
Buster "Silver Eagle" Neece 2019-01-31 11:54:17 -06:00
parent fae265b9c8
commit 8a6701403a
63 changed files with 404 additions and 734 deletions

View File

@ -18,6 +18,7 @@
"azuracast/azuraforms": "dev-master",
"azuracast/nowplaying": "dev-master",
"bernard/bernard": "dev-master",
"brick/math": "^0.8.4",
"cakephp/chronos": "^1.1",
"doctrine/annotations": "^1.6",
"gettext/gettext": "^4.4",
@ -42,8 +43,7 @@
"symfony/validator": "^4.2",
"ramsey/uuid": "^3.8",
"wikimedia/composer-merge-plugin": "^1.4",
"zircote/swagger-php": "^3.0",
"brick/math": "^0.8.4"
"zircote/swagger-php": "^3.0"
},
"require-dev": {
"codeception/codeception": "^2.2",

View File

@ -89,7 +89,7 @@ return [
3 => '3 - '.__('Default'),
4 => '4',
5 => '5 - '.__('High'),
] + \App\Utilities::pairs(range(6, 25)),
] + array_combine(range(6, 25), range(6, 25)),
]
],

View File

@ -193,10 +193,10 @@ return function (\Azura\Container $di)
}
});
$view->registerFunction('truncate', function ($text, $length = 80) {
return \App\Utilities::truncate_text($text, $length);
return \App\Utilities::truncateText($text, $length);
});
$view->registerFunction('truncateUrl', function($url) {
return \App\Utilities::truncate_url($url);
return \App\Utilities::truncateUrl($url);
});
$view->addData([

View File

@ -246,10 +246,9 @@ dev-phpstan() {
#
dev-codeception() {
docker-compose -f docker-compose.sample.yml -f docker-compose.testing.yml build web
docker-compose -f docker-compose.sample.yml -f docker-compose.testing.yml run --user="azuracast" --rm web /var/azuracast/www/vendor/bin/codecept run --no-interaction --coverage --coverage-xml --fail-fast
docker-compose -f docker-compose.sample.yml -f docker-compose.testing.yml run --user="azuracast" --rm web vendor/codeception/codeception/codecept run --no-interaction --coverage --coverage-xml --fail-fast
}
#
# Stop all Docker containers and remove related volumes.
# Usage: ./docker.sh uninstall

View File

@ -4,9 +4,6 @@ parameters:
paths:
- src
fileExtensions:
- php
bootstrap: %rootDir%/../../../util/phpstan.php
universalObjectCratesClasses:
@ -22,8 +19,12 @@ parameters:
- '#Call to an undefined method Supervisor\\Supervisor::tailProcessLog().#'
- '#Call to an undefined method Supervisor\\Supervisor::signalProcess().#'
# PHPDocs
- '#PHPDoc tag .*#'
dynamicConstantNames:
- APP_IS_COMMAND_LINE
- APP_INSIDE_DOCKER
- APP_TESTING_MODE
- APP_APPLICATION_ENV
- APP_IN_PRODUCTION
includes:
- vendor/phpstan/phpstan-doctrine/extension.neon

View File

@ -44,7 +44,7 @@ class ListSettings extends CommandAbstract
$all_settings = $settings_repo->fetchAll();
foreach($all_settings as $setting_key => $setting_value) {
$value = print_r($setting_value, true);
$value = Utilities::truncate_text($value, 600);
$value = Utilities::truncateText($value, 600);
$rows[] = [$setting_key, $value];
}

View File

@ -99,7 +99,7 @@ class Setup extends CommandAbstract
'AzuraCast is now updated to the latest version!',
]);
} else {
$public_ip = Utilities::get_public_ip();
$public_ip = Utilities::getPublicIp();
$io->success([
'AzuraCast installation complete!',

View File

@ -24,7 +24,7 @@ abstract class AbstractGenericCrudController extends AbstractCrudController
$return = $this->_viewRecord($row, $router);
if ($is_bootgrid) {
return Utilities::flatten_array($return, '_');
return Utilities::flattenArray($return, '_');
}
return $return;

View File

@ -14,7 +14,7 @@ abstract class AbstractStationCrudController extends AbstractCrudController
/**
* @param Request $request
* @param Response $response
* @param $station_id
* @param int|string $station_id
* @return ResponseInterface
* @throws \Azura\Exception
*/
@ -36,7 +36,7 @@ abstract class AbstractStationCrudController extends AbstractCrudController
$paginator->setPostprocessor(function($row) use ($is_bootgrid, $router) {
$return = $this->_viewRecord($row, $router);
if ($is_bootgrid) {
return Utilities::flatten_array($return, '_');
return Utilities::flattenArray($return, '_');
}
return $return;
@ -48,7 +48,7 @@ abstract class AbstractStationCrudController extends AbstractCrudController
/**
* @param Request $request
* @param Response $response
* @param $station_id
* @param int|string $station_id
* @return ResponseInterface
*/
public function createAction(Request $request, Response $response, $station_id): ResponseInterface
@ -67,7 +67,7 @@ abstract class AbstractStationCrudController extends AbstractCrudController
/**
* @param Request $request
* @param Response $response
* @param $record_id
* @param int|string $record_id
* @return ResponseInterface
*/
public function getAction(Request $request, Response $response, $station_id, $record_id): ResponseInterface
@ -82,8 +82,8 @@ abstract class AbstractStationCrudController extends AbstractCrudController
/**
* @param Request $request
* @param Response $response
* @param $station_id
* @param $record_id
* @param int|string $station_id
* @param int|string $record_id
* @return ResponseInterface
*/
public function editAction(Request $request, Response $response, $station_id, $record_id): ResponseInterface
@ -104,8 +104,8 @@ abstract class AbstractStationCrudController extends AbstractCrudController
/**
* @param Request $request
* @param Response $response
* @param $station_id
* @param $record_id
* @param int|string $station_id
* @param int|string $record_id
* @return ResponseInterface
*/
public function deleteAction(Request $request, Response $response, $station_id, $record_id): ResponseInterface
@ -125,7 +125,7 @@ abstract class AbstractStationCrudController extends AbstractCrudController
/**
* @param Entity\Station $station
* @param $record_id
* @param int|string $record_id
* @return object|null
*/
protected function _getRecord(Entity\Station $station, $record_id)

View File

@ -65,7 +65,7 @@ class HistoryController
*
* @param Request $request
* @param Response $response
* @param $station_id
* @param int|string $station_id
* @return ResponseInterface
*/
public function __invoke(Request $request, Response $response, $station_id): ResponseInterface
@ -152,7 +152,7 @@ class HistoryController
$row->resolveUrls($router);
if ($is_bootgrid) {
return App\Utilities::flatten_array($row, '_');
return App\Utilities::flattenArray($row, '_');
}
return $row;

View File

@ -70,7 +70,7 @@ class QueueController extends AbstractStationCrudController
$paginator->setPostprocessor(function($row) use ($is_bootgrid, $router) {
$return = $this->_viewRecord($row, $router);
if ($is_bootgrid) {
return App\Utilities::flatten_array($return, '_');
return App\Utilities::flattenArray($return, '_');
}
return $return;

View File

@ -112,7 +112,7 @@ class RequestsController
$row->resolveUrls($router);
if ($is_bootgrid) {
return Utilities::flatten_array($row, '_');
return Utilities::flattenArray($row, '_');
}
return $row;

View File

@ -164,7 +164,7 @@ class ListController extends FilesControllerAbstract
$sort_by[] = \SORT_ASC;
}
$result = \App\Utilities::array_order_by($result, $sort_by);
$result = \App\Utilities::arrayOrderBy($result, $sort_by);
$num_results = count($result);

View File

@ -47,6 +47,12 @@ class PlaylistsController
$this->playlist_media_repo = $this->em->getRepository(Entity\StationPlaylistMedia::class);
}
/**
* @param Request $request
* @param Response $response
* @param int|string $station_id
* @return ResponseInterface
*/
public function indexAction(Request $request, Response $response, $station_id): ResponseInterface
{
$station = $request->getStation();
@ -93,7 +99,7 @@ class PlaylistsController
*
* @param Request $request
* @param Response $response
* @param $station_id
* @param int|string $station_id
* @return Response
*/
public function scheduleAction(Request $request, Response $response, $station_id): ResponseInterface

View File

@ -106,12 +106,12 @@ class Customization
/**
* Format the given UNIX timestamp into a locale-friendly time.
*
* @param $timestamp
* @param int $timestamp
* @param bool $use_utc
* @param bool $show_timezone_abbr
* @return string Formatted time for presentation.
*/
public function formatTime($timestamp = null, $use_utc = false, $show_timezone_abbr = false)
public function formatTime($timestamp = null, $use_utc = false, $show_timezone_abbr = false): string
{
$timestamp = $timestamp ?? time();
@ -130,7 +130,7 @@ class Customization
/**
* Format a date/time using PHP's IntlDateFormatter constants.
*
* @param $timestamp
* @param int $timestamp
* @param bool $use_utc
* @param int|null $date_display One of:
* IntlDateFormatter::NONE - Do not include
@ -141,7 +141,11 @@ class Customization
* @param int|null $time_display One of the above.
* @return string
*/
public function formatDateTime($timestamp, $use_utc = false, $date_display = \IntlDateFormatter::LONG, $time_display = \IntlDateFormatter::LONG)
public function formatDateTime(
$timestamp,
$use_utc = false,
$date_display = \IntlDateFormatter::LONG,
$time_display = \IntlDateFormatter::LONG): string
{
$timezone = ($use_utc) ? 'UTC' : date_default_timezone_get();
$locale = str_replace('.UTF-8', '', $this->getLocale());

View File

@ -73,10 +73,9 @@ class Analytics
*/
protected $station;
/**
* Analytics constructor.
/*
* @param Station|null $station
* @param $type
* @param string $type
* @param null $timestamp
* @param int $number_min
* @param int $number_max

View File

@ -17,7 +17,7 @@ class Listener
/**
* Listener constructor.
* @param Station $station
* @param $client
* @param array $client
*/
public function __construct(Station $station, $client)
{
@ -166,7 +166,7 @@ class Listener
/**
* @param int $timestamp_end
*/
public function setTimestampEnd(int $timestamp_end)
public function setTimestampEnd(int $timestamp_end): void
{
$this->timestamp_end = $timestamp_end;
}
@ -180,7 +180,7 @@ class Listener
}
/**
* @param $client
* @param array $client
* @return string
*/
public static function calculateListenerHash($client): string

View File

@ -9,7 +9,7 @@ class ApiKeyRepository extends Repository
/**
* Given an API key string in the format `identifier:verifier`, find and authenticate an API key.
*
* @param $key_string
* @param string $key_string
* @return Entity\User|null
*/
public function authenticate($key_string): ?Entity\User

View File

@ -11,8 +11,8 @@ class ListenerRepository extends Repository
* Get the number of unique listeners for a station during a specified time period.
*
* @param Entity\Station $station
* @param $timestamp_start
* @param $timestamp_end
* @param int $timestamp_start
* @param int $timestamp_end
* @return mixed
*/
public function getUniqueListeners(Entity\Station $station, $timestamp_start, $timestamp_end)
@ -32,7 +32,7 @@ class ListenerRepository extends Repository
* Update listener data for a station.
*
* @param Entity\Station $station
* @param $clients
* @param array $clients
*/
public function update(Entity\Station $station, $clients)
{

View File

@ -9,8 +9,6 @@ use Doctrine\ORM\Mapping;
class RolePermissionRepository extends Repository
{
/**
* TODO: Legacy
*
* @return array
*/
public function getActionsForAllRoles(): array
@ -30,8 +28,6 @@ class RolePermissionRepository extends Repository
}
/**
* TODO: Legacy functionality only used by existing administration form.
*
* @param Entity\Role $role
* @return array
*/
@ -54,10 +50,8 @@ class RolePermissionRepository extends Repository
}
/**
* TODO: Legacy functionality only used by existing administration form.
*
* @param Entity\Role $role
* @param $post_values
* @param array $post_values
*/
public function setActionsForRole(Entity\Role $role, $post_values): void
{

View File

@ -20,8 +20,8 @@ class SettingsRepository extends Repository
}
/**
* @param $key
* @param $value
* @param string $key
* @param mixed $value
*/
public function setSetting($key, $value): void
{
@ -41,7 +41,7 @@ class SettingsRepository extends Repository
}
/**
* @param $key
* @param string $key
*/
public function deleteSetting($key): void
{
@ -57,8 +57,8 @@ class SettingsRepository extends Repository
}
/**
* @param $key
* @param null $default_value
* @param string $key
* @param mixed|null $default_value
* @param bool $cached
* @return mixed|null
*/
@ -71,7 +71,7 @@ class SettingsRepository extends Repository
/**
* @return array
*/
public function fetchAll()
public function fetchAll(): array
{
$all_records_raw = $this->findAll();
@ -90,7 +90,7 @@ class SettingsRepository extends Repository
* @param string $order_dir
* @return array
*/
public function fetchArray($cached = true, $order_by = null, $order_dir = 'ASC')
public function fetchArray($cached = true, $order_by = null, $order_dir = 'ASC'): array
{
if (!self::$settings || !$cached) {
$settings_raw = $this->_em->createQuery('SELECT s FROM ' . $this->_entityName . ' s ORDER BY s.setting_key ASC')
@ -108,7 +108,7 @@ class SettingsRepository extends Repository
/**
* Force a clearing of the cache.
*/
public function clearCache()
public function clearCache(): void
{
// Regenerate cache and flush static value.
$this->fetchArray(false);

View File

@ -14,7 +14,10 @@ class SongHistoryRepository extends Repository
* @param UriInterface|null $base_url
* @return Entity\Api\SongHistory[]
*/
public function getHistoryForStation(Entity\Station $station, \App\ApiUtilities $api_utils, UriInterface $base_url = null)
public function getHistoryForStation(
Entity\Station $station,
\App\ApiUtilities $api_utils,
UriInterface $base_url = null): array
{
$num_entries = $station->getApiHistoryItems();
@ -43,7 +46,7 @@ class SongHistoryRepository extends Repository
/**
* @param Entity\Song $song
* @param Entity\Station $station
* @param $np
* @param array $np
* @return Entity\SongHistory
*/
public function register(Entity\Song $song, Entity\Station $station, $np): Entity\SongHistory
@ -58,80 +61,79 @@ class SongHistoryRepository extends Repository
$listeners = (int)$np['listeners']['current'];
if ($last_sh instanceof Entity\SongHistory && $last_sh->getSong() === $song) {
// Updating the existing SongHistory item with a new data point.
$last_sh->addDeltaPoint($listeners);
$this->_em->persist($last_sh);
$this->_em->flush();
return $last_sh;
} else {
// Wrapping up processing on the previous SongHistory item (if present).
if ($last_sh instanceof Entity\SongHistory) {
$last_sh->setTimestampEnd(time());
$last_sh->setListenersEnd($listeners);
// Calculate "delta" data for previous item, based on all data points.
if ($last_sh instanceof Entity\SongHistory) {
if ($last_sh->getSong() === $song) {
// Updating the existing SongHistory item with a new data point.
$last_sh->addDeltaPoint($listeners);
$delta_points = (array)$last_sh->getDeltaPoints();
$delta_positive = 0;
$delta_negative = 0;
$delta_total = 0;
for ($i = 1; $i < count($delta_points); $i++) {
$current_delta = $delta_points[$i];
$previous_delta = $delta_points[$i - 1];
$delta_delta = $current_delta - $previous_delta;
$delta_total += $delta_delta;
if ($delta_delta > 0) {
$delta_positive += $delta_delta;
} elseif ($delta_delta < 0) {
$delta_negative += abs($delta_delta);
}
}
$last_sh->setDeltaPositive($delta_positive);
$last_sh->setDeltaNegative($delta_negative);
$last_sh->setDeltaTotal($delta_total);
/** @var ListenerRepository $listener_repo */
$listener_repo = $this->_em->getRepository(Entity\Listener::class);
$last_sh->setUniqueListeners($listener_repo->getUniqueListeners($station, $last_sh->getTimestampStart(), time()));
$this->_em->persist($last_sh);
$this->_em->flush();
return $last_sh;
}
// Look for an already cued but unplayed song.
$sh = $this->_em->createQuery('SELECT sh FROM '.Entity\SongHistory::class.' sh
WHERE sh.station_id = :station_id
AND sh.song_id = :song_id
AND sh.timestamp_cued != 0
AND sh.timestamp_start = 0
ORDER BY sh.timestamp_cued DESC')
->setParameter('station_id', $station->getId())
->setParameter('song_id', $song->getId())
->setMaxResults(1)
->getOneOrNullResult();
// Wrapping up processing on the previous SongHistory item (if present).
$last_sh->setTimestampEnd(time());
$last_sh->setListenersEnd($listeners);
// Processing a new SongHistory item.
if (!($sh instanceof Entity\SongHistory))
{
$sh = new Entity\SongHistory($song, $station);
// Calculate "delta" data for previous item, based on all data points.
$last_sh->addDeltaPoint($listeners);
$delta_points = (array)$last_sh->getDeltaPoints();
$delta_positive = 0;
$delta_negative = 0;
$delta_total = 0;
for ($i = 1; $i < count($delta_points); $i++) {
$current_delta = $delta_points[$i];
$previous_delta = $delta_points[$i - 1];
$delta_delta = $current_delta - $previous_delta;
$delta_total += $delta_delta;
if ($delta_delta > 0) {
$delta_positive += $delta_delta;
} elseif ($delta_delta < 0) {
$delta_negative += abs($delta_delta);
}
}
$sh->setTimestampStart(time());
$sh->setListenersStart($listeners);
$sh->addDeltaPoint($listeners);
$last_sh->setDeltaPositive($delta_positive);
$last_sh->setDeltaNegative($delta_negative);
$last_sh->setDeltaTotal($delta_total);
$this->_em->persist($sh);
$this->_em->flush();
/** @var ListenerRepository $listener_repo */
$listener_repo = $this->_em->getRepository(Entity\Listener::class);
$last_sh->setUniqueListeners($listener_repo->getUniqueListeners($station, $last_sh->getTimestampStart(), time()));
return $sh;
$this->_em->persist($last_sh);
}
// Look for an already cued but unplayed song.
$sh = $this->_em->createQuery('SELECT sh FROM '.Entity\SongHistory::class.' sh
WHERE sh.station_id = :station_id
AND sh.song_id = :song_id
AND sh.timestamp_cued != 0
AND sh.timestamp_start = 0
ORDER BY sh.timestamp_cued DESC')
->setParameter('station_id', $station->getId())
->setParameter('song_id', $song->getId())
->setMaxResults(1)
->getOneOrNullResult();
// Processing a new SongHistory item.
if (!($sh instanceof Entity\SongHistory)) {
$sh = new Entity\SongHistory($song, $station);
}
$sh->setTimestampStart(time());
$sh->setListenersStart($listeners);
$sh->addDeltaPoint($listeners);
$this->_em->persist($sh);
$this->_em->flush();
return $sh;
}
}

View File

@ -23,47 +23,6 @@ class StationMediaRepository extends Repository
$this->song_repo = $this->_em->getRepository(Entity\Song::class);
}
/**
* @param Entity\Station $station
* @return array
*/
public function getRequestable(Entity\Station $station)
{
return $this->_em->createQuery('SELECT sm FROM ' . $this->_entityName . ' sm WHERE sm.station_id = :station_id ORDER BY sm.artist ASC, sm.title ASC')
->setParameter('station_id', $station->getId())
->getArrayResult();
}
/**
* @param Entity\Station $station
* @param $artist_name
* @return array
*/
public function getByArtist(Entity\Station $station, $artist_name)
{
return $this->_em->createQuery('SELECT sm FROM ' . $this->_entityName . ' sm WHERE sm.station_id = :station_id AND sm.artist LIKE :artist ORDER BY sm.title ASC')
->setParameter('station_id', $station->getId())
->setParameter('artist', $artist_name)
->getArrayResult();
}
/**
* @param Entity\Station $station
* @param $query
* @return array
*/
public function search(Entity\Station $station, $query)
{
// TODO: Replace this!
$db = $this->_em->getConnection();
$table_name = $this->_em->getClassMetadata(__CLASS__)->getTableName();
$stmt = $db->executeQuery('SELECT sm.* FROM ' . $db->quoteIdentifier($table_name) . ' AS sm WHERE sm.station_id = ? AND CONCAT(sm.title, \' \', sm.artist, \' \', sm.album) LIKE ?',
[$station->getId(), '%' . addcslashes($query, "%_") . '%']);
return $stmt->fetchAll();
}
/**
* @param Entity\Station $station
* @param string $tmp_path
@ -98,7 +57,7 @@ class StationMediaRepository extends Repository
/**
* @param Entity\Station $station
* @param $path
* @param string $path
* @return Entity\StationMedia
* @throws \Exception
*/

View File

@ -165,7 +165,7 @@ class StationPlaylistMediaRepository extends Repository
* ]
*
* @param Entity\StationPlaylist $playlist
* @param $mapping
* @param array $mapping
*/
public function setMediaOrder(Entity\StationPlaylist $playlist, $mapping)
{

View File

@ -70,7 +70,7 @@ class StationRepository extends Repository
$results = $this->fetchArray();
// Assemble select values and, if necessary, call $display callback.
foreach ((array)$results as $result) {
foreach ($results as $result) {
$key = $result[$pk];
$value = ($display === null) ? $result['name'] : $display($result);
$select[$key] = $value;
@ -80,7 +80,7 @@ class StationRepository extends Repository
}
/**
* @param $short_code
* @param string $short_code
* @return null|object
*/
public function findByShortCode($short_code)
@ -89,7 +89,7 @@ class StationRepository extends Repository
}
/**
* @param $data
* @param array $data
* @param Entity\Station|null $record
* @return Entity\Station
*/
@ -101,7 +101,7 @@ class StationRepository extends Repository
}
/**
* @param $data
* @param array $data
* @param Entity\Station $record
* @return Entity\Station
*/
@ -212,35 +212,6 @@ class StationRepository extends Repository
$this->_em->refresh($station);
}
public function clone(Entity\Station $record, array $data, array $options = [])
{
$new_record_data = $this->toArray($record);
$new_record_data['name'] = $data['name'];
$new_record_data['description'] = $data['description'];
$unset_values = [
'short_name',
'radio_base_dir',
'nowplaying',
'nowplaying_timestamp',
'is_streamer_live',
'needs_restart',
'has_started',
];
foreach($unset_values as $unset_value) {
unset($new_record_data[$unset_value]);
}
if ($options['clone_media'] === 'share') {
$new_record_data['radio_media_dir'] = $record->getRadioMediaDir();
} else {
unset($new_record_data['radio_media_dir']);
}
}
/**
* @param Entity\Station $station
* @throws \Exception
@ -251,7 +222,7 @@ class StationRepository extends Repository
// Remove media folders.
$radio_dir = $station->getRadioBaseDir();
\App\Utilities::rmdir_recursive($radio_dir);
\App\Utilities::rmdirRecursive($radio_dir);
// Save changes and continue to the last setup step.
$this->_em->remove($station);
@ -261,7 +232,7 @@ class StationRepository extends Repository
}
/**
* @param $port
* @param mixed|null $port
* @param Entity\Station|null $except_record
* @return bool
*/
@ -273,6 +244,7 @@ class StationRepository extends Repository
return isset($used_ports[$port]);
}
return false;
}
}

View File

@ -10,7 +10,7 @@ class StationRequestRepository extends Repository
* Submit a new request.
*
* @param Entity\Station $station
* @param $track_id
* @param int $track_id
* @param bool $is_authenticated
* @return mixed
* @throws \Azura\Exception
@ -18,7 +18,7 @@ class StationRequestRepository extends Repository
public function submit(Entity\Station $station, $track_id, $is_authenticated = false)
{
// Forbid web crawlers from using this feature.
if (\App\Utilities::is_crawler()) {
if (\App\Utilities::isCrawler()) {
throw new \Azura\Exception('Search engine crawlers are not permitted to use this feature.');
}
@ -50,7 +50,7 @@ class StationRequestRepository extends Repository
$user_ip = $_SERVER['REMOTE_ADDR'];
// Check for any request (on any station) within the last $threshold_seconds.
$threshold_mins = (int)($station->getRequestThreshold() ?? 5);
$threshold_mins = $station->getRequestThreshold() ?? 5;
$threshold_seconds = $threshold_mins * 60;
$recent_requests = $this->_em->createQuery('SELECT sr FROM ' . $this->_entityName . ' sr WHERE sr.ip = :user_ip AND sr.timestamp >= :threshold')

View File

@ -10,8 +10,8 @@ class StationStreamerRepository extends Repository
* Attempt to authenticate a streamer.
*
* @param Entity\Station $station
* @param $username
* @param $password
* @param string $username
* @param string $password
* @return Entity\StationStreamer|bool
*/
public function authenticate(Entity\Station $station, $username, $password)

View File

@ -7,8 +7,8 @@ use Azura\Doctrine\Repository;
class UserRepository extends Repository
{
/**
* @param $username
* @param $password
* @param string $username
* @param string $password
* @return bool|null|object
*/
public function authenticate($username, $password)
@ -21,18 +21,17 @@ class UserRepository extends Repository
if ($login_info->verifyPassword($password)) {
return $login_info;
} else {
return false;
}
return false;
}
/**
* Creates or returns an existing user with the specified e-mail address.
*
* @param $email
* @param string $email
* @return Entity\User
*/
public function getOrCreate($email)
public function getOrCreate($email): Entity\User
{
$user = $this->findOneBy(['email' => $email]);

View File

@ -57,7 +57,7 @@ class Role implements \JsonSerializable
}
/**
* @return mixed
* @return int
*/
public function getId(): int
{
@ -75,7 +75,7 @@ class Role implements \JsonSerializable
/**
* @param string $name
*/
public function setName(string $name)
public function setName(string $name): void
{
$this->name = $this->_truncateString($name, 100);
}

View File

@ -17,7 +17,7 @@ class Song
{
use Traits\TruncateStrings;
const SYNC_THRESHOLD = 604800; // 604800 = 1 week
public const SYNC_THRESHOLD = 604800; // 604800 = 1 week
/**
* @ORM\Column(name="id", type="string", length=50)
@ -155,9 +155,9 @@ class Song
/**
* Increment the play counter and last-played items.
*/
public function played()
public function played(): void
{
$this->play_count += 1;
++$this->play_count;
$this->last_played = time();
}
@ -191,7 +191,7 @@ class Song
}
/**
* @param $song_info
* @param array|object|string $song_info
* @return string
*/
public static function getSongHash($song_info): string
@ -212,12 +212,10 @@ class Song
// Generate hash.
if (!empty($song_info['text'])) {
$song_text = $song_info['text'];
} elseif (!empty($song_info['artist'])) {
$song_text = $song_info['artist'] . ' - ' . $song_info['title'];
} else {
if (!empty($song_info['artist'])) {
$song_text = $song_info['artist'] . ' - ' . $song_info['title'];
} else {
$song_text = $song_info['title'];
}
$song_text = $song_info['title'];
}
// Strip non-alphanumeric characters

View File

@ -13,7 +13,7 @@ use Psr\Http\Message\UriInterface;
*/
class SongHistory
{
const DEFAULT_DAYS_TO_KEEP = 60;
public const DEFAULT_DAYS_TO_KEEP = 60;
/**
* @ORM\Column(name="id", type="integer")
@ -224,7 +224,7 @@ class SongHistory
/**
* @return StationPlaylist|null
*/
public function getPlaylist()
public function getPlaylist(): ?StationPlaylist
{
return $this->playlist;
}
@ -232,7 +232,7 @@ class SongHistory
/**
* @param StationPlaylist|null $playlist
*/
public function setPlaylist(StationPlaylist $playlist = null)
public function setPlaylist(StationPlaylist $playlist = null): void
{
$this->playlist = $playlist;
}
@ -240,7 +240,7 @@ class SongHistory
/**
* @return StationMedia|null
*/
public function getMedia()
public function getMedia(): ?StationMedia
{
return $this->media;
}
@ -248,7 +248,7 @@ class SongHistory
/**
* @param StationMedia|null $media
*/
public function setMedia(StationMedia $media = null)
public function setMedia(StationMedia $media = null): void
{
$this->media = $media;
}
@ -256,7 +256,7 @@ class SongHistory
/**
* @return StationRequest|null
*/
public function getRequest()
public function getRequest(): ?StationRequest
{
return $this->request;
}
@ -264,7 +264,7 @@ class SongHistory
/**
* @param StationRequest|null $request
*/
public function setRequest($request)
public function setRequest($request): void
{
$this->request = $request;
}
@ -288,7 +288,7 @@ class SongHistory
/**
* @return int|null
*/
public function getTimestampCued()
public function getTimestampCued(): ?int
{
return $this->timestamp_cued;
}
@ -296,7 +296,7 @@ class SongHistory
/**
* @param int|null $timestamp_cued
*/
public function setTimestampCued($timestamp_cued)
public function setTimestampCued($timestamp_cued): void
{
$this->timestamp_cued = $timestamp_cued;
}
@ -309,7 +309,7 @@ class SongHistory
return $this->sent_to_autodj;
}
public function sentToAutodj()
public function sentToAutodj(): void
{
$this->sent_to_autodj = true;
}
@ -325,7 +325,7 @@ class SongHistory
/**
* @param int $timestamp_start
*/
public function setTimestampStart(int $timestamp_start)
public function setTimestampStart(int $timestamp_start): void
{
$this->timestamp_start = $timestamp_start;
}
@ -333,7 +333,7 @@ class SongHistory
/**
* @return int|null
*/
public function getDuration()
public function getDuration(): ?int
{
return $this->duration;
}
@ -341,7 +341,7 @@ class SongHistory
/**
* @param int|null $duration
*/
public function setDuration($duration)
public function setDuration($duration): void
{
$this->duration = $duration;
}
@ -349,7 +349,7 @@ class SongHistory
/**
* @return int|null
*/
public function getListenersStart()
public function getListenersStart(): ?int
{
return $this->listeners_start;
}
@ -357,7 +357,7 @@ class SongHistory
/**
* @param int|null $listeners_start
*/
public function setListenersStart($listeners_start)
public function setListenersStart($listeners_start): void
{
$this->listeners_start = $listeners_start;
}
@ -373,11 +373,14 @@ class SongHistory
/**
* @param int $timestamp_end
*/
public function setTimestampEnd(int $timestamp_end)
public function setTimestampEnd(int $timestamp_end): void
{
$this->timestamp_end = $timestamp_end;
}
/**
* @return int
*/
public function getTimestamp(): int
{
return (int)$this->timestamp_start;
@ -386,7 +389,7 @@ class SongHistory
/**
* @return int|null
*/
public function getListenersEnd()
public function getListenersEnd(): ?int
{
return $this->listeners_end;
}
@ -394,7 +397,7 @@ class SongHistory
/**
* @param int|null $listeners_end
*/
public function setListenersEnd($listeners_end)
public function setListenersEnd($listeners_end): void
{
$this->listeners_end = $listeners_end;
}
@ -402,7 +405,7 @@ class SongHistory
/**
* @return int|null
*/
public function getUniqueListeners()
public function getUniqueListeners(): ?int
{
return $this->unique_listeners;
}
@ -410,11 +413,14 @@ class SongHistory
/**
* @param int|null $unique_listeners
*/
public function setUniqueListeners($unique_listeners)
public function setUniqueListeners($unique_listeners): void
{
$this->unique_listeners = $unique_listeners;
}
/**
* @return int
*/
public function getListeners(): int
{
return (int)$this->listeners_start;
@ -431,7 +437,7 @@ class SongHistory
/**
* @param int $delta_total
*/
public function setDeltaTotal(int $delta_total)
public function setDeltaTotal(int $delta_total): void
{
$this->delta_total = $delta_total;
}
@ -447,7 +453,7 @@ class SongHistory
/**
* @param int $delta_positive
*/
public function setDeltaPositive(int $delta_positive)
public function setDeltaPositive(int $delta_positive): void
{
$this->delta_positive = $delta_positive;
}
@ -463,7 +469,7 @@ class SongHistory
/**
* @param int $delta_negative
*/
public function setDeltaNegative(int $delta_negative)
public function setDeltaNegative(int $delta_negative): void
{
$this->delta_negative = $delta_negative;
}
@ -477,9 +483,9 @@ class SongHistory
}
/**
* @param $delta_point
* @param mixed $delta_point
*/
public function addDeltaPoint($delta_point)
public function addDeltaPoint($delta_point): void
{
$delta_points = (array)$this->delta_points;
$delta_points[] = $delta_point;

View File

@ -381,13 +381,13 @@ class Station
}
/**
* @param $frontend_config
* @param array $frontend_config
* @param bool $force_overwrite
*/
public function setFrontendConfig($frontend_config, $force_overwrite = false): void
public function setFrontendConfig(array $frontend_config, $force_overwrite = false): void
{
$config = ($force_overwrite) ? [] : (array)$this->frontend_config;
foreach((array)$frontend_config as $cfg_key => $cfg_val) {
foreach($frontend_config as $cfg_key => $cfg_val) {
$config[$cfg_key] = $cfg_val;
}
@ -401,9 +401,9 @@ class Station
/**
* Set frontend configuration but do not overwrite existing values.
*
* @param $default_config
* @param array $default_config
*/
public function setFrontendConfigDefaults($default_config): void
public function setFrontendConfigDefaults(array $default_config): void
{
$frontend_config = (array)$this->frontend_config;
@ -441,13 +441,13 @@ class Station
}
/**
* @param $backend_config
* @param array $backend_config
* @param bool $force_overwrite
*/
public function setBackendConfig($backend_config, $force_overwrite = false): void
public function setBackendConfig(array $backend_config, $force_overwrite = false): void
{
$config = ($force_overwrite) ? [] : (array)$this->backend_config;
foreach((array)$backend_config as $cfg_key => $cfg_val) {
foreach($backend_config as $cfg_key => $cfg_val) {
$config[$cfg_key] = $cfg_val;
}
@ -488,7 +488,7 @@ class Station
/**
* Authenticate the supplied adapter API key.
*
* @param $api_key
* @param string $api_key
* @return bool
*/
public function validateAdapterApiKey($api_key): bool
@ -553,7 +553,7 @@ class Station
}
/**
* @param $new_dir
* @param string $new_dir
*/
public function setRadioBaseDir($new_dir): void
{
@ -571,10 +571,8 @@ class Station
$this->getRadioTempDir(),
];
foreach ($radio_dirs as $radio_dir) {
if (!file_exists($radio_dir)) {
if (!mkdir($radio_dir, 0777) && !is_dir($radio_dir)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $radio_dir));
}
if (!file_exists($radio_dir) && !mkdir($radio_dir, 0777) && !is_dir($radio_dir)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $radio_dir));
}
}
}
@ -609,7 +607,7 @@ class Station
/**
* Given an absolute path, return a path relative to this station's media directory.
*
* @param $full_path
* @param string $full_path
* @return string
*/
public function getRelativeMediaPath($full_path): string
@ -634,7 +632,7 @@ class Station
}
/**
* @param $new_dir
* @param string $new_dir
*/
public function setRadioMediaDir(?string $new_dir): void
{
@ -1103,7 +1101,7 @@ class Station
}
/**
* @param $name
* @param string $name
* @return string
*/
public static function getStationShortName($name): string

View File

@ -198,7 +198,7 @@ class StationMedia
/**
* @param Song|null $song
*/
public function setSong(Song $song = null)
public function setSong(Song $song = null): void
{
$this->song = $song;
}
@ -232,7 +232,7 @@ class StationMedia
/**
* @param null|string $title
*/
public function setTitle(string $title = null)
public function setTitle(string $title = null): void
{
$this->title = $this->_truncateString($title, 200);
}
@ -248,7 +248,7 @@ class StationMedia
/**
* @param null|string $artist
*/
public function setArtist(string $artist = null)
public function setArtist(string $artist = null): void
{
$this->artist = $this->_truncateString($artist, 200);
}
@ -264,7 +264,7 @@ class StationMedia
/**
* @param null|string $album
*/
public function setAlbum(string $album = null)
public function setAlbum(string $album = null): void
{
$this->album = $this->_truncateString($album, 200);
}
@ -272,7 +272,7 @@ class StationMedia
/**
* @return null|string
*/
public function getLyrics()
public function getLyrics(): ?string
{
return $this->lyrics;
}
@ -280,7 +280,7 @@ class StationMedia
/**
* @param null|string $lyrics
*/
public function setLyrics($lyrics)
public function setLyrics($lyrics): void
{
$this->lyrics = $lyrics;
}
@ -290,7 +290,7 @@ class StationMedia
*
* @return string
*/
public function getArtPath()
public function getArtPath(): string
{
return 'albumart://'.$this->unique_id.'.jpg';
}
@ -306,7 +306,7 @@ class StationMedia
/**
* @param null|string $isrc
*/
public function setIsrc(string $isrc = null)
public function setIsrc(string $isrc = null): void
{
$this->isrc = $isrc;
}
@ -320,9 +320,9 @@ class StationMedia
}
/**
* @param $length
* @param int $length
*/
public function setLength($length)
public function setLength($length): void
{
$length_min = floor($length / 60);
$length_sec = $length % 60;
@ -342,7 +342,7 @@ class StationMedia
/**
* @param null|string $length_text
*/
public function setLengthText(string $length_text = null)
public function setLengthText(string $length_text = null): void
{
$this->length_text = $length_text;
}
@ -358,7 +358,7 @@ class StationMedia
/**
* @param null|string $path
*/
public function setPath(string $path = null)
public function setPath(string $path = null): void
{
$this->path = $path;
}
@ -384,7 +384,7 @@ class StationMedia
/**
* @param int|null $mtime
*/
public function setMtime(int $mtime = null)
public function setMtime(int $mtime = null): void
{
$this->mtime = $mtime;
}
@ -460,7 +460,7 @@ class StationMedia
/**
* @param float|null $cue_in
*/
public function setCueIn($cue_in = null)
public function setCueIn($cue_in = null): void
{
if ($cue_in === '') {
$cue_in = null;
@ -480,7 +480,7 @@ class StationMedia
/**
* @param float|null $cue_out
*/
public function setCueOut($cue_out = null)
public function setCueOut($cue_out = null): void
{
if ($cue_out === '') {
$cue_out = null;
@ -517,11 +517,15 @@ class StationMedia
return $this->playlist_items;
}
/**
* @param StationPlaylist $playlist
* @return StationPlaylistMedia|null
*/
public function getItemForPlaylist(StationPlaylist $playlist): ?StationPlaylistMedia
{
$item = $this->playlist_items->filter(function($spm) use ($playlist) {
/** @var StationPlaylistMedia $spm */
return ($spm->getPlaylist()->getId() == $playlist->getId());
return $spm->getPlaylist()->getId() === $playlist->getId();
});
return $item->first() ?? null;
@ -586,7 +590,7 @@ class StationMedia
foreach ($annotation_types as $annotation_property => $annotation_name) {
if ($this->$annotation_property !== null) {
$prop = $this->$annotation_property;
$prop = mb_convert_encoding($prop, "UTF-8");
$prop = mb_convert_encoding($prop, 'UTF-8');
$prop = str_replace(['"', "\n", "\t", "\r"], ["'", '', '', ''], $prop);
if ($annotation_property === 'cue_out' && $prop < 0) {
@ -594,8 +598,8 @@ class StationMedia
}
// Convert Liquidsoap-specific annotations to floats.
if ('liq' === substr($annotation_name, 0, 3)
|| 'duration' === $annotation_name) {
if ('duration' === $annotation_name ||
0 === strpos($annotation_name, 'liq')) {
$prop = Liquidsoap::toFloat($prop);
}

View File

@ -50,7 +50,7 @@ class StationMediaCustomField
/**
* @ORM\Column(name="field_value", type="string", length=255, nullable=true)
* @var
* @var string
*/
protected $value;
@ -77,15 +77,15 @@ class StationMediaCustomField
}
/**
* @return mixed
* @return string|null
*/
public function getValue()
public function getValue(): ?string
{
return $this->value;
}
/**
* @param mixed $value
* @param string|null $value
*/
public function setValue($value): void
{

View File

@ -135,11 +135,11 @@ class StationMount implements StationMountInterface
}
/**
* Ensure all mountpoint names start with a leading slash.
* @param $new_name
* @param string $new_name
*/
public function setName(string $new_name)
public function setName(string $new_name): void
{
// Ensure all mount point names start with a leading slash.
$this->name = $this->_truncateString('/' . ltrim($new_name, '/'), 100);
}
@ -154,7 +154,7 @@ class StationMount implements StationMountInterface
/**
* @param bool $is_default
*/
public function setIsDefault(bool $is_default)
public function setIsDefault(bool $is_default): void
{
$this->is_default = $is_default;
}
@ -170,7 +170,7 @@ class StationMount implements StationMountInterface
/**
* @param bool $is_public
*/
public function setIsPublic(bool $is_public)
public function setIsPublic(bool $is_public): void
{
$this->is_public = $is_public;
}
@ -186,7 +186,7 @@ class StationMount implements StationMountInterface
/**
* @param null|string $fallback_mount
*/
public function setFallbackMount($fallback_mount)
public function setFallbackMount($fallback_mount): void
{
$this->fallback_mount = $fallback_mount;
}
@ -202,7 +202,7 @@ class StationMount implements StationMountInterface
/**
* @param null|string $relay_url
*/
public function setRelayUrl($relay_url)
public function setRelayUrl($relay_url): void
{
$this->relay_url = $relay_url;
}
@ -218,7 +218,7 @@ class StationMount implements StationMountInterface
/**
* @param null|string $authhash
*/
public function setAuthhash(string $authhash = null)
public function setAuthhash(string $authhash = null): void
{
$this->authhash = $authhash;
}
@ -234,7 +234,7 @@ class StationMount implements StationMountInterface
/**
* @param bool $enable_autodj
*/
public function setEnableAutodj(bool $enable_autodj)
public function setEnableAutodj(bool $enable_autodj): void
{
$this->enable_autodj = $enable_autodj;
}
@ -250,7 +250,7 @@ class StationMount implements StationMountInterface
/**
* @param null|string $autodj_format
*/
public function setAutodjFormat(string $autodj_format = null)
public function setAutodjFormat(string $autodj_format = null): void
{
$this->autodj_format = $autodj_format;
}
@ -266,7 +266,7 @@ class StationMount implements StationMountInterface
/**
* @param int|null $autodj_bitrate
*/
public function setAutodjBitrate(int $autodj_bitrate = null)
public function setAutodjBitrate(int $autodj_bitrate = null): void
{
$this->autodj_bitrate = $autodj_bitrate;
}
@ -282,7 +282,7 @@ class StationMount implements StationMountInterface
/**
* @param null|string $custom_listen_url
*/
public function setCustomListenUrl(string $custom_listen_url = null)
public function setCustomListenUrl(string $custom_listen_url = null): void
{
$this->custom_listen_url = $custom_listen_url;
}
@ -298,7 +298,7 @@ class StationMount implements StationMountInterface
/**
* @param null|string $frontend_config
*/
public function setFrontendConfig(string $frontend_config = null)
public function setFrontendConfig(string $frontend_config = null): void
{
$this->frontend_config = $frontend_config;
}

View File

@ -208,7 +208,7 @@ class StationPlaylist
/**
* @param string $name
*/
public function setName(string $name)
public function setName(string $name): void
{
$this->name = $this->_truncateString($name, 200);
}
@ -224,7 +224,7 @@ class StationPlaylist
/**
* @param string $type
*/
public function setType(string $type)
public function setType(string $type): void
{
$this->type = $type;
}
@ -322,7 +322,7 @@ class StationPlaylist
/**
* @param bool $is_enabled
*/
public function setIsEnabled(bool $is_enabled)
public function setIsEnabled(bool $is_enabled): void
{
$this->is_enabled = $is_enabled;
}
@ -338,7 +338,7 @@ class StationPlaylist
/**
* @param int $play_per_songs
*/
public function setPlayPerSongs(int $play_per_songs)
public function setPlayPerSongs(int $play_per_songs): void
{
$this->play_per_songs = $play_per_songs;
}
@ -354,7 +354,7 @@ class StationPlaylist
/**
* @param int $play_per_minutes
*/
public function setPlayPerMinutes(int $play_per_minutes)
public function setPlayPerMinutes(int $play_per_minutes): void
{
$this->play_per_minutes = $play_per_minutes;
}
@ -378,7 +378,7 @@ class StationPlaylist
/**
* @param int $schedule_start_time
*/
public function setScheduleStartTime(int $schedule_start_time)
public function setScheduleStartTime(int $schedule_start_time): void
{
$this->schedule_start_time = $schedule_start_time;
}
@ -402,7 +402,7 @@ class StationPlaylist
/**
* @param int $schedule_end_time
*/
public function setScheduleEndTime(int $schedule_end_time)
public function setScheduleEndTime(int $schedule_end_time): void
{
$this->schedule_end_time = $schedule_end_time;
}
@ -437,7 +437,7 @@ class StationPlaylist
/**
* @param array $schedule_days
*/
public function setScheduleDays($schedule_days)
public function setScheduleDays($schedule_days): void
{
$this->schedule_days = implode(',', (array)$schedule_days);
}
@ -491,7 +491,7 @@ class StationPlaylist
/**
* Given a day code (1-7) a-la date('N'), return if the playlist can be played on that day.
*
* @param $day_to_check
* @param int $day_to_check
* @return bool
*/
public function canPlayScheduledOnDay($day_to_check): bool
@ -520,7 +520,7 @@ class StationPlaylist
/**
* @param int $play_once_time
*/
public function setPlayOnceTime(int $play_once_time)
public function setPlayOnceTime(int $play_once_time): void
{
$this->play_once_time = $play_once_time;
}
@ -536,7 +536,7 @@ class StationPlaylist
/**
* @param array $play_once_days
*/
public function setPlayOnceDays($play_once_days)
public function setPlayOnceDays($play_once_days): void
{
$this->play_once_days = implode(',', (array)$play_once_days);
}
@ -572,7 +572,7 @@ class StationPlaylist
/**
* @param int $weight
*/
public function setWeight(int $weight)
public function setWeight(int $weight): void
{
$this->weight = $weight;
}
@ -614,7 +614,7 @@ class StationPlaylist
/**
* @param bool $include_in_automation
*/
public function setIncludeInAutomation(bool $include_in_automation)
public function setIncludeInAutomation(bool $include_in_automation): void
{
$this->include_in_automation = $include_in_automation;
}
@ -634,7 +634,7 @@ class StationPlaylist
* @param bool $absolute_paths
* @return string
*/
public function export($file_format = 'pls', $absolute_paths = false)
public function export($file_format = 'pls', $absolute_paths = false): string
{
$media_path = ($absolute_paths) ? $this->station->getRadioMediaDir().'/' : '';
@ -680,7 +680,7 @@ class StationPlaylist
/**
* Given a time code i.e. "2300", return a UNIX timestamp that can be used to format the time for display.
*
* @param $time_code
* @param string|int $time_code
* @return int
*/
public static function getTimestamp($time_code): int
@ -692,7 +692,7 @@ class StationPlaylist
/**
* Given a time code i.e. "2300", return a time suitable for HTML5 inputs, i.e. "23:00".
*
* @param $time_code
* @param string|int $time_code
* @return string
*/
public static function formatTimeCodeForInput($time_code): string
@ -705,7 +705,8 @@ class StationPlaylist
/**
* Return a \DateTime object (or null) for a given time code, by default in the UTC time zone.
*
* @param $time_code
* @param string|int $time_code
* @param Chronos|null $now
* @return Chronos
*/
public static function getDateTime($time_code, Chronos $now = null): Chronos

View File

@ -130,7 +130,7 @@ class User
/**
* @ORM\PrePersist
*/
public function preSave()
public function preSave(): void
{
$this->updated_at = time();
}
@ -146,7 +146,7 @@ class User
/**
* @return null|string
*/
public function getEmail()
public function getEmail(): ?string
{
return $this->email;
}
@ -154,7 +154,7 @@ class User
/**
* @param null|string $email
*/
public function setEmail($email)
public function setEmail($email): void
{
$this->email = $this->_truncateString($email, 100);
}
@ -162,7 +162,7 @@ class User
/**
* @param string $password
*/
public function setAuthPassword(string $password)
public function setAuthPassword(string $password): void
{
if (trim($password)) {
[$algo, $algo_opts] = $this->_getPasswordAlgorithm();
@ -171,10 +171,10 @@ class User
}
/**
* @param $password
* @param string $password
* @return bool
*/
public function verifyPassword($password)
public function verifyPassword($password): bool
{
if (password_verify($password, $this->auth_password)) {
[$algo, $algo_opts] = $this->_getPasswordAlgorithm();
@ -191,7 +191,7 @@ class User
/**
* @throws \Exception
*/
public function generateRandomPassword()
public function generateRandomPassword(): void
{
$this->setAuthPassword(bin2hex(random_bytes(20)));
}
@ -201,19 +201,19 @@ class User
*
* @return array [algorithm constant, algorithm options array]
*/
protected function _getPasswordAlgorithm()
protected function _getPasswordAlgorithm(): array
{
if (defined('PASSWORD_ARGON2I')) {
return [\PASSWORD_ARGON2I, []];
} else {
return [\PASSWORD_BCRYPT, []];
}
return [\PASSWORD_BCRYPT, []];
}
/**
* @return null|string
*/
public function getName()
public function getName(): ?string
{
return $this->name;
}
@ -221,7 +221,7 @@ class User
/**
* @param null|string $name
*/
public function setName($name)
public function setName($name): void
{
$this->name = $this->_truncateString($name, 100);
}
@ -229,7 +229,7 @@ class User
/**
* @return null|string
*/
public function getTimezone()
public function getTimezone(): ?string
{
return $this->timezone;
}
@ -237,7 +237,7 @@ class User
/**
* @param null|string $timezone
*/
public function setTimezone($timezone)
public function setTimezone($timezone): void
{
$this->timezone = $timezone;
}
@ -245,7 +245,7 @@ class User
/**
* @return null|string
*/
public function getLocale()
public function getLocale(): ?string
{
return $this->locale;
}
@ -253,7 +253,7 @@ class User
/**
* @param null|string $locale
*/
public function setLocale($locale)
public function setLocale($locale): void
{
$this->locale = $locale;
}
@ -261,7 +261,7 @@ class User
/**
* @return null|string
*/
public function getTheme()
public function getTheme(): ?string
{
return $this->theme;
}
@ -269,7 +269,7 @@ class User
/**
* @param null|string $theme
*/
public function setTheme($theme)
public function setTheme($theme): void
{
$this->theme = $theme;
}
@ -306,7 +306,11 @@ class User
return $this->api_keys;
}
public function getAvatar($size = 50)
/**
* @param int $size
* @return string
*/
public function getAvatar($size = 50): string
{
return \App\Service\Gravatar::get($this->email, $size, 'identicon');
}

View File

@ -7,7 +7,7 @@ use Symfony\Component\EventDispatcher\Event;
class GetNotifications extends Event
{
const NAME = 'get-notifications';
public const NAME = 'get-notifications';
/** @var User */
protected $current_user;

View File

@ -11,7 +11,7 @@ use Symfony\Component\EventDispatcher\Event;
*/
class AnnotateNextSong extends Event
{
const NAME = 'radio-liquidsoap-annotate-next-song';
public const NAME = 'radio-liquidsoap-annotate-next-song';
/** @var null|string|Entity\SongHistory The next song, if it's already calculated. */
protected $next_song;

View File

@ -7,7 +7,7 @@ use Symfony\Component\EventDispatcher\Event;
class GenerateRawNowPlaying extends Event
{
const NAME = 'radio-nowplaying-generate-raw';
public const NAME = 'radio-nowplaying-generate-raw';
/** @var Station */
protected $station;

View File

@ -6,7 +6,7 @@ use Symfony\Component\EventDispatcher\Event;
class GetNextSong extends Event
{
const NAME = 'autodj-next-song';
public const NAME = 'autodj-next-song';
/** @var null|string|Entity\SongHistory The next song, if it's already calculated. */
protected $next_song;

View File

@ -6,7 +6,7 @@ use Symfony\Component\EventDispatcher\Event;
class LoadNowPlaying extends Event
{
const NAME = 'radio-nowplaying-load';
public const NAME = 'radio-nowplaying-load';
/** @var NowPlaying[] */
protected $np = [];

View File

@ -6,7 +6,7 @@ use Symfony\Component\EventDispatcher\Event;
class WriteLiquidsoapConfiguration extends Event
{
const NAME = 'radio-liquidsoap-write-configuration';
public const NAME = 'radio-liquidsoap-write-configuration';
/** @var array */
protected $config_lines;

View File

@ -7,7 +7,7 @@ use Symfony\Component\EventDispatcher\Event;
class SendWebhooks extends Event
{
const NAME = 'webhooks-send';
public const NAME = 'webhooks-send';
/** @var Station */
protected $station;
@ -75,12 +75,12 @@ class SendWebhooks extends Event
}
/**
* @param $trigger_name
* @param string $trigger_name
* @return bool
*/
public function hasTrigger($trigger_name): bool
{
return in_array($trigger_name, $this->triggers);
return in_array($trigger_name, $this->triggers, true);
}
/**

View File

@ -17,7 +17,7 @@ class StationFilesystem extends MountManager
*/
public function copyToTemp($from, $to = null): string
{
list($prefix_from, $path_from) = $this->getPrefixAndPath($from);
[$prefix_from, $path_from] = $this->getPrefixAndPath($from);
if (null === $to) {
$random_prefix = substr(md5(random_bytes(8)), 0, 5);
@ -64,8 +64,8 @@ class StationFilesystem extends MountManager
/**
* "Upload" a local path into the Flysystem abstract filesystem.
*
* @param $local_path
* @param $to
* @param string $local_path
* @param string $to
* @param array $config
* @return bool
*/

View File

@ -27,7 +27,7 @@ class GetStation
/**
* @param Request $request
* @param Response $response
* @param $next
* @param callable $next
* @param bool $station_required
* @param string $station_param
* @return Response

View File

@ -14,11 +14,11 @@ class DoctrineEntityNormalizer extends AbstractNormalizer
{
use ObjectToPopulateTrait;
const DEEP_NORMALIZE = 'deep';
const NORMALIZE_TO_IDENTIFIERS = 'form_mode';
public const DEEP_NORMALIZE = 'deep';
public const NORMALIZE_TO_IDENTIFIERS = 'form_mode';
const CLASS_METADATA = 'class_metadata';
const ASSOCIATION_MAPPINGS = 'association_mappings';
public const CLASS_METADATA = 'class_metadata';
public const ASSOCIATION_MAPPINGS = 'association_mappings';
/** @var EntityManager */
protected $em;
@ -55,7 +55,7 @@ class DoctrineEntityNormalizer extends AbstractNormalizer
* @param mixed $object
* @param null $format
* @param array $context
* @return array|bool|float|int|string
* @return mixed
*/
public function normalize($object, $format = null, array $context = array())
{
@ -75,9 +75,7 @@ class DoctrineEntityNormalizer extends AbstractNormalizer
$value = $this->getAttributeValue($object, $attribute, $format, $context);
/**
* @var $callback callable|null
*/
/** @var callable|null $callback */
$callback = $context[self::CALLBACKS][$attribute] ?? $this->defaultContext[self::CALLBACKS][$attribute] ?? $this->callbacks[$attribute] ?? null;
if ($callback) {
$value = $callback($value, $object, $attribute, $format, $context);
@ -93,11 +91,11 @@ class DoctrineEntityNormalizer extends AbstractNormalizer
}
/**
* @param $object
* @param $prop_name
* @param object $object
* @param string $prop_name
* @param null $format
* @param array $context
* @return array|bool|float|int|string|null
* @return mixed
*/
protected function getAttributeValue($object, $prop_name, $format = null, array $context = array())
{
@ -158,9 +156,9 @@ class DoctrineEntityNormalizer extends AbstractNormalizer
*
* @param mixed $data
* @param string $class
* @param null $format
* @param string|null $format
* @param array $context
* @return object|void
* @return object
*/
public function denormalize($data, $class, $format = null, array $context = array())
{
@ -197,9 +195,7 @@ class DoctrineEntityNormalizer extends AbstractNormalizer
}
foreach ((array)$data as $attribute => $value) {
/**
* @var $callback callable|null
*/
/** @var callable|null $callback */
$callback = $context[self::CALLBACKS][$attribute] ?? $this->defaultContext[self::CALLBACKS][$attribute] ?? $this->callbacks[$attribute] ?? null;
if ($callback) {
$value = $callback($value, $object, $attribute, $format, $context);
@ -207,16 +203,18 @@ class DoctrineEntityNormalizer extends AbstractNormalizer
$this->setAttributeValue($object, $attribute, $value, $format, $context);
}
return $object;
}
/**
* @param $object
* @param $field
* @param $value
* @param object $object
* @param string $field
* @param mixed $value
* @param null $format
* @param array $context
*/
protected function setAttributeValue($object, $field, $value, $format = null, array $context = array())
protected function setAttributeValue($object, $field, $value, $format = null, array $context = array()): void
{
if (isset($context[self::ASSOCIATION_MAPPINGS][$field])) {
// Handle a mapping to another entity.
@ -265,7 +263,7 @@ class DoctrineEntityNormalizer extends AbstractNormalizer
}
/**
* @param $class
* @param object|string $class
* @return bool
*/
protected function _isEntity($class): bool
@ -286,8 +284,8 @@ class DoctrineEntityNormalizer extends AbstractNormalizer
}
/**
* @param $entity
* @param $key
* @param object $entity
* @param string $key
* @return mixed|null
*/
protected function _get($entity, $key)
@ -308,9 +306,9 @@ class DoctrineEntityNormalizer extends AbstractNormalizer
}
/**
* @param $entity
* @param $key
* @param $value
* @param object $entity
* @param string $key
* @param mixed $value
* @return mixed|null
*/
protected function _set($entity, $key, $value)
@ -325,7 +323,7 @@ class DoctrineEntityNormalizer extends AbstractNormalizer
/**
* Converts "getvar_name_blah" to "getVarNameBlah".
*
* @param $var
* @param string $var
* @param string $prefix
* @return string
*/

View File

@ -24,7 +24,6 @@ abstract class AbstractAdapter
protected $dispatcher;
/**
* AdapterAbstract constructor.
* @param EntityManager $em
* @param Supervisor $supervisor
* @param Logger $logger
@ -160,7 +159,7 @@ abstract class AbstractAdapter
* Internal handling of any Supervisor-related exception, to add richer data to it.
*
* @param FaultException $e
* @param $program_name
* @param string $program_name
* @param Entity\Station $station
*
* @throws \App\Exception\Supervisor

View File

@ -482,11 +482,11 @@ class Liquidsoap extends AbstractBackend implements EventSubscriberInterface
* Returns the URL that LiquidSoap should call when attempting to execute AzuraCast API commands.
*
* @param Entity\Station $station
* @param $endpoint
* @param string $endpoint
* @param array $params
* @return string
*/
protected function _getApiUrlCommand(Entity\Station $station, $endpoint, $params = [])
protected function _getApiUrlCommand(Entity\Station $station, $endpoint, $params = []): string
{
// Docker cURL-based API URL call with API authentication.
if (APP_INSIDE_DOCKER) {
@ -520,15 +520,15 @@ class Liquidsoap extends AbstractBackend implements EventSubscriberInterface
/**
* Configure the time offset
*
* @param $time_code
* @param int $time_code
* @return string
*/
protected function _getTime($time_code)
protected function _getTime($time_code): string
{
$hours = floor($time_code / 100);
$mins = $time_code % 100;
$system_time_zone = \App\Utilities::get_system_time_zone();
$system_time_zone = \App\Utilities::getSystemTimeZone();
$app_time_zone = 'UTC';
if ($system_time_zone !== $app_time_zone) {
@ -557,7 +557,7 @@ class Liquidsoap extends AbstractBackend implements EventSubscriberInterface
/**
* Filter a user-supplied string to be a valid LiquidSoap config entry.
*
* @param $string
* @param string $string
* @return mixed
*/
protected function _cleanUpString($string)
@ -568,7 +568,7 @@ class Liquidsoap extends AbstractBackend implements EventSubscriberInterface
/**
* Given an original name and a station, return a filtered prefixed variable identifying the station.
*
* @param $original_name
* @param string $original_name
* @param Entity\Station $station
* @return string
*/
@ -671,7 +671,7 @@ class Liquidsoap extends AbstractBackend implements EventSubscriberInterface
* If a station uses Manual AutoDJ mode, enqueue a request directly with Liquidsoap.
*
* @param Entity\Station $station
* @param $music_file
* @param string $music_file
* @return array
* @throws \Azura\Exception
*/
@ -732,7 +732,7 @@ class Liquidsoap extends AbstractBackend implements EventSubscriberInterface
* Execute the specified remote command on LiquidSoap via the telnet API.
*
* @param Entity\Station $station
* @param $command_str
* @param string $command_str
* @return array
* @throws \Azura\Exception
*/

View File

@ -73,8 +73,8 @@ abstract class AbstractFrontend extends \App\Radio\AbstractAdapter
* Get the AzuraCast station-watcher binary command for the specified adapter and watch URI.
*
* @param Entity\Station $station
* @param $adapter
* @param $watch_uri
* @param string $adapter
* @param string $watch_uri
* @return string
*/
protected function _getStationWatcherCommand(Entity\Station $station, $adapter, $watch_uri): string
@ -126,7 +126,7 @@ abstract class AbstractFrontend extends \App\Radio\AbstractAdapter
/**
* @param Entity\Station $station
* @param $mount
* @param Entity\StationMount|null $mount
* @param UriInterface|null $base_url
* @return UriInterface
*/

View File

@ -116,7 +116,7 @@ class Icecast extends AbstractFrontend
if (!empty($frontend_config['custom_config'])) {
$custom_conf = $this->_processCustomConfig($frontend_config['custom_config']);
if (!empty($custom_conf)) {
$config = Utilities::array_merge_recursive_distinct($config, $custom_conf);
$config = Utilities::arrayMergeRecursiveDistinct($config, $custom_conf);
}
}
@ -174,7 +174,7 @@ class Icecast extends AbstractFrontend
$reader = new \App\Xml\Reader;
$data = $reader->fromFile($icecast_path);
return Utilities::array_merge_recursive_distinct($defaults, $data);
return Utilities::arrayMergeRecursiveDistinct($defaults, $data);
}
return $defaults;
@ -284,7 +284,7 @@ class Icecast extends AbstractFrontend
$mount_conf = $this->_processCustomConfig($mount_row->getFrontendConfig());
if (!empty($mount_conf)) {
$mount = Utilities::array_merge_recursive_distinct($mount, $mount_conf);
$mount = Utilities::arrayMergeRecursiveDistinct($mount, $mount_conf);
}
}

View File

@ -28,7 +28,7 @@ abstract class AbstractRemote
/**
* @param Entity\StationRemote $remote
* @param $np
* @param array $np
* @param bool $include_clients
* @return bool
*/
@ -39,8 +39,8 @@ abstract class AbstractRemote
/**
* @param Entity\StationRemote $remote
* @param $np
* @param $adapter_class
* @param array $np
* @param string $adapter_class
* @param bool $include_clients
* @return bool
*/

View File

@ -119,9 +119,9 @@ class Flow
/**
* Check if all parts exist and are uploaded.
*
* @param $chunkBaseDir
* @param $targetSize
* @param $targetChunkNumber
* @param string $chunkBaseDir
* @param int $targetSize
* @param int $targetChunkNumber
* @return bool
*/
protected function _allPartsExist($chunkBaseDir, $targetSize, $targetChunkNumber): bool
@ -140,10 +140,10 @@ class Flow
/**
* Reassemble the file on the local destination disk and return the relevant information.
*
* @param $chunkBaseDir
* @param $chunkIdentifier
* @param $originalFileName
* @param $numChunks
* @param string $chunkBaseDir
* @param string $chunkIdentifier
* @param string $originalFileName
* @param int $numChunks
* @return array
*/
protected function _createFileFromChunks($chunkBaseDir, $chunkIdentifier, $originalFileName, $numChunks): array

View File

@ -7,34 +7,13 @@ namespace App;
class Utilities
{
/**
* Pretty print_r
*
* @param $var
* @param bool $return
* @return string
*/
public static function print_r($var, $return = false)
{
$return_value = '<pre style="font-size: 13px; font-family: Consolas, Courier New, Courier, monospace; color: #000; background: #EFEFEF; border: 1px solid #CCC; padding: 5px;">';
$return_value .= print_r($var, true);
$return_value .= '</pre>';
if ($return) {
return $return_value;
} else {
echo $return_value;
return null;
}
}
/**
* Generate a randomized password of specified length.
*
* @param $char_length
* @param int $char_length
* @return string
*/
public static function generatePassword($char_length = 8)
public static function generatePassword($char_length = 8): string
{
// String of all possible characters. Avoids using certain letters and numbers that closely resemble others.
$numeric_chars = str_split('234679');
@ -55,10 +34,10 @@ class Utilities
/**
* Convert a specified number of seconds into a date range.
*
* @param $timestamp
* @param int $timestamp
* @return string
*/
public static function timeToText($timestamp)
public static function timeToText($timestamp): string
{
return self::timeDifferenceText(0, $timestamp);
}
@ -66,12 +45,12 @@ class Utilities
/**
* Get the textual difference between two strings.
*
* @param $timestamp1
* @param $timestamp2
* @param int $timestamp1
* @param int $timestamp2
* @param int $precision
* @return string
*/
public static function timeDifferenceText($timestamp1, $timestamp2, $precision = 1)
public static function timeDifferenceText($timestamp1, $timestamp2, $precision = 1): string
{
$time_diff = abs($timestamp1 - $timestamp2);
@ -100,34 +79,15 @@ class Utilities
return sprintf(n__("%d month", "%d months", $time_num), $time_num);
}
/**
* Forced-GMT strtotime alternative.
*
* @param $time
* @param null $now
* @return int
*/
public static function gstrtotime($time, $now = null)
{
$prev_timezone = @date_default_timezone_get();
@date_default_timezone_set('UTC');
$timestamp = strtotime($time, $now);
@date_default_timezone_set($prev_timezone);
return $timestamp;
}
/**
* Truncate text (adding "..." if needed)
*
* @param $text
* @param string $text
* @param int $limit
* @param string $pad
* @return string
*/
public static function truncate_text($text, $limit = 80, $pad = '...')
public static function truncateText($text, $limit = 80, $pad = '...'): string
{
mb_internal_encoding('UTF-8');
@ -135,12 +95,12 @@ class Utilities
return $text;
}
$wrapped_text = self::mb_wordwrap($text, $limit, "{N}", true);
$shortened_text = mb_substr($wrapped_text, 0, strpos($wrapped_text, "{N}"));
$wrapped_text = self::mbWordwrap($text, $limit, '{N}', true);
$shortened_text = mb_substr($wrapped_text, 0, strpos($wrapped_text, '{N}'));
// Prevent the padding string from bumping up against punctuation.
$punctuation = ['.', ',', ';', '?', '!'];
if (in_array(mb_substr($shortened_text, -1), $punctuation)) {
if (in_array(mb_substr($shortened_text, -1), $punctuation, true)) {
$shortened_text = mb_substr($shortened_text, 0, -1);
}
@ -150,13 +110,13 @@ class Utilities
/**
* UTF-8 capable replacement for wordwrap function.
*
* @param $str
* @param string $str
* @param int $width
* @param string $break
* @param bool $cut
* @return string
*/
public static function mb_wordwrap($str, $width = 75, $break = "\n", $cut = false)
public static function mbWordwrap($str, $width = 75, $break = "\n", $cut = false): string
{
$lines = explode($break, $str);
foreach ($lines as &$line) {
@ -193,76 +153,15 @@ class Utilities
/**
* Truncate URL in text-presentable format (i.e. "http://www.example.com" becomes "example.com")
*
* @param $url
* @param string $url
* @param int $length
* @return string
*/
public static function truncate_url($url, $length = 40)
public static function truncateUrl($url, $length = 40): string
{
$url = str_replace(['http://', 'https://', 'www.'], ['', '', ''], $url);
$url = str_replace(['http://', 'https://', 'www.'], '', $url);
return self::truncate_text(rtrim($url, '/'), $length);
}
/**
* Join one or more items into an array.
*
* @param array $items
* @return string
*/
public static function join_compound(array $items)
{
$count = count($items);
if ($count == 0) {
return '';
}
if ($count == 1) {
return $items[0];
}
return implode(', ', array_slice($items, 0, -1)) . ' and ' . end($items);
}
/**
* Create an array where the keys and values match each other.
*
* @param $array
* @return array
*/
public static function pairs($array)
{
return array_combine($array, $array);
}
/**
* Split an array into "columns", typically for display purposes.
*
* @param $array
* @param int $num_cols
* @param bool $preserve_keys
* @return array
*/
public static function columns($array, $num_cols = 2, $preserve_keys = true)
{
$items_total = (int)count($array);
$items_per_col = ceil($items_total / $num_cols);
return array_chunk($array, $items_per_col, $preserve_keys);
}
/**
* Split an array into "rows", typically for display purposes.
*
* @param $array
* @param int $num_per_row
* @param bool $preserve_keys
* @return array
*/
public static function rows($array, $num_per_row = 3, $preserve_keys = true)
{
return array_chunk($array, $num_per_row, $preserve_keys);
return self::truncateText(rtrim($url, '/'), $length);
}
/**
@ -290,12 +189,12 @@ class Utilities
* @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
* @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
*/
public static function array_merge_recursive_distinct(array &$array1, array &$array2)
public static function arrayMergeRecursiveDistinct(array &$array1, array &$array2): array
{
$merged = $array1;
foreach ($array2 as $key => &$value) {
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
$merged[$key] = self::array_merge_recursive_distinct($merged[$key], $value);
$merged[$key] = self::arrayMergeRecursiveDistinct($merged[$key], $value);
} else {
$merged[$key] = $value;
}
@ -304,39 +203,17 @@ class Utilities
return $merged;
}
/**
* Return all keys in a multi-dimensional array.
* Useful for getting all possible values in an optgroup-stacked select dropdown.
*
* @param $array
* @return array The keys found.
*/
public static function array_keys_recursive($array)
{
$keys = [];
foreach ((array)$array as $key => $value) {
if (is_array($value)) {
$keys = array_merge($keys, self::array_keys_recursive($value));
} else {
$keys[] = $key;
}
}
return $keys;
}
/**
* Sort a supplied array (the first argument) by one or more indices, specified in this format:
* arrayOrderBy($data, [ 'index_name', SORT_ASC, 'index2_name', SORT_DESC ])
*
* Internally uses array_multisort().
*
* @param $data
* @param array $data
* @param array $args
* @return mixed
*/
public static function array_order_by($data, array $args = [])
public static function arrayOrderBy($data, array $args = [])
{
if (empty($args)) {
return $data;
@ -358,125 +235,6 @@ class Utilities
return array_pop($args);
}
/**
* Split a URL into an array (similar to parse_url() itself) but with cleaner parameter handling.
*
* @param $url
* @return mixed
*/
public static function parse_url($url)
{
$url_parts = @parse_url($url);
$url_parts['path_clean'] = trim($url_parts['path'], '/');
$url_parts['query_arr'] = self::convert_url_query($url_parts['query']);
return $url_parts;
}
/**
* Convert the query string of a URL into an array of keys and values.
*
* @param $query
* @return array
*/
public static function convert_url_query($query)
{
$queryParts = explode('&', $query);
$params = [];
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
return $params;
}
/**
* Construct a URL based on an array returned from parseUrl().
*
* @param $url
* @return string
*/
public static function build_url($url)
{
is_array($url) || $url = parse_url($url);
if (is_array($url['query'])) {
$url['query'] = http_build_query($url['query']);
}
if (isset($url['path']) && substr($url['path'], 0, 1) !== '/') {
$url['path'] = '/' . $url['path'];
}
$parsed_string = '';
if (isset($url['scheme'])) {
$parsed_string .= $url['scheme'] . '://';
}
if (isset($url['user'])) {
$parsed_string .= $url['user'];
if (isset($url['pass'])) {
$parsed_string .= ':' . $url['pass'];
}
$parsed_string .= '@';
}
if (isset($url['host'])) {
$parsed_string .= $url['host'];
}
if (isset($url['port'])) {
$parsed_string .= ':' . $url['port'];
}
if (!empty($url['path'])) {
$parsed_string .= $url['path'];
} else {
$parsed_string .= '/';
}
if (isset($url['query'])) {
$parsed_string .= '?' . $url['query'];
}
if (isset($url['fragment'])) {
$parsed_string .= '#' . $url['fragment'];
}
return $parsed_string;
}
/**
* Construct a URL based on an array returned from parseUrl().
*
* @param $needle The value we're looking for
* @param $haystack The array we're looking through
* @param $strict If true, checks type as well
* @return string
*/
public static function recursive_array_search($needle, $haystack, $strict = false)
{
foreach ($haystack as $key => $value) {
if (is_array($value)) {
// Value is an array, check that instead!
$nextKey = self::recursive_array_search($needle, $value, $strict);
if ($nextKey) {
return $nextKey;
}
} else {
if ($strict ? $value === $needle : $value == $needle) {
return $key;
}
}
}
return false;
}
/**
* Detect if the User-Agent matches common crawler UAs.
* Not expected to be 100% accurate or trustworthy, just used to prevent
@ -484,12 +242,12 @@ class Utilities
*
* @return bool
*/
public static function is_crawler()
public static function isCrawler(): bool
{
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
$crawlers_agents = strtolower('Bloglines subscriber|Dumbot|Sosoimagespider|QihooBot|FAST-WebCrawler|Superdownloads Spiderman|LinkWalker|msnbot|ASPSeek|WebAlta Crawler|Lycos|FeedFetcher-Google|Yahoo|YoudaoBot|AdsBot-Google|Googlebot|Scooter|Gigabot|Charlotte|eStyle|AcioRobot|GeonaBot|msnbot-media|Baidu|CocoCrawler|Google|Charlotte t|Yahoo! Slurp China|Sogou web spider|YodaoBot|MSRBOT|AbachoBOT|Sogou head spider|AltaVista|IDBot|Sosospider|Yahoo! Slurp|Java VM|DotBot|LiteFinder|Yeti|Rambler|Scrubby|Baiduspider|accoona');
$crawlers = explode("|", $crawlers_agents);
$crawlers = explode('|', $crawlers_agents);
foreach ($crawlers as $crawler) {
if (strpos($ua, trim($crawler)) !== false) {
@ -504,7 +262,7 @@ class Utilities
* Get the system time zone.
* @return string
*/
public static function get_system_time_zone()
public static function getSystemTimeZone(): string
{
if (APP_INSIDE_DOCKER) {
return 'UTC';
@ -540,14 +298,14 @@ class Utilities
/**
* Recursively remove a directory and its contents.
*
* @param $dir
* @param string $dir
*/
public static function rmdir_recursive($dir)
public static function rmdirRecursive($dir): void
{
if (is_dir($dir)) {
$files = array_diff(scandir($dir), ['.', '..']);
$files = array_diff(scandir($dir, \SCANDIR_SORT_NONE), ['.', '..']);
foreach ($files as $file) {
self::rmdir_recursive($dir . '/' . $file);
self::rmdirRecursive($dir . '/' . $file);
}
@rmdir($dir);
@ -556,29 +314,16 @@ class Utilities
}
}
/**
* Convert from a bytes number to text (i.e.
*
* @param $bytes
* @return string
*/
public static function bytes_to_text($bytes)
{
$si_prefix = ['B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB'];
$base = 1024;
$class = min((int)log($bytes, $base), count($si_prefix) - 1);
return sprintf('%1.2f', $bytes / pow($base, $class)) . ' ' . $si_prefix[$class];
}
/**
* Attempt to fetch the most likely "external" IP for this instance.
*
* @return false|string
*/
public static function get_public_ip()
public static function getPublicIp()
{
if (APP_INSIDE_DOCKER) {
if (APP_IN_PRODUCTION) {
$public_ip = @file_get_contents("http://ipecho.net/plain");
$public_ip = @file_get_contents('http://ipecho.net/plain');
if (!empty($public_ip)) {
return $public_ip;
}
@ -587,7 +332,7 @@ class Utilities
return 'localhost';
}
return getHostByName(getHostName()) ?? 'localhost';
return gethostbyname(gethostname()) ?? 'localhost';
}
/**
@ -612,7 +357,7 @@ class Utilities
* @param null $prefix
* @return array
*/
public static function flatten_array($array, $separator = '.', $prefix = null): array
public static function flattenArray($array, $separator = '.', $prefix = null): array
{
if (!is_array($array)) {
if (is_object($array)) {
@ -628,7 +373,7 @@ class Utilities
foreach($array as $key => $value) {
$return_key = $prefix ? $prefix.$separator.$key : $key;
if (\is_array($value)) {
$return = array_merge($return, self::flatten_array($value, $separator, $return_key));
$return = array_merge($return, self::flattenArray($value, $separator, $return_key));
} else {
$return[$return_key] = $value;
}

View File

@ -11,7 +11,7 @@ use Symfony\Component\Process\Process;
class Version
{
/** @var string Version that is displayed if no Git repository information is present. */
const FALLBACK_VERSION = '0.9.1';
public const FALLBACK_VERSION = '0.9.1';
/** @var Cache */
protected $cache;
@ -33,7 +33,7 @@ class Version
/**
* @return string The current tagged version.
*/
public function getVersion()
public function getVersion(): string
{
$details = $this->getDetails();
return $details['tag'] ?? self::FALLBACK_VERSION;
@ -42,7 +42,7 @@ class Version
/**
* @return string A textual representation of the current installed version.
*/
public function getVersionText()
public function getVersionText(): string
{
$details = $this->getDetails();
@ -124,7 +124,7 @@ class Version
/**
* Run the specified process and return its output.
*
* @param $proc
* @param array $proc
* @param string $default
* @return string
*/
@ -140,7 +140,4 @@ class Version
return trim($process->getOutput());
}
}

View File

@ -21,7 +21,7 @@ abstract class AbstractConnector implements ConnectorInterface
$this->http_client = $http_client;
}
public function shouldDispatch(SendWebhooks $event, array $triggers): bool
public function shouldDispatch(SendWebhooks $event, array $triggers = null): bool
{
if (empty($triggers)) {
return true;
@ -45,7 +45,7 @@ abstract class AbstractConnector implements ConnectorInterface
*/
public function _replaceVariables(array $raw_vars, Entity\Api\NowPlaying $np): array
{
$values = Utilities::flatten_array($np, '.');
$values = Utilities::flattenArray($np, '.');
$vars = [];
foreach($raw_vars as $var_key => $var_value) {
@ -86,7 +86,7 @@ abstract class AbstractConnector implements ConnectorInterface
/**
* Determine if a passed URL is valid and return it if so, or return null otherwise.
*
* @param $url_string
* @param string $url_string
* @return string|null
*/
protected function _getValidUrl($url_string): ?string

View File

@ -13,7 +13,7 @@ interface ConnectorInterface
* @param array|null $triggers The configured triggers for this connector.
* @return bool
*/
public function shouldDispatch(SendWebhooks $event, array $triggers): bool;
public function shouldDispatch(SendWebhooks $event, array $triggers = null): bool;
/**
* Trigger the webhook for the specified station, now playing entry, and specified configuration.

View File

@ -28,7 +28,7 @@ class Local extends AbstractConnector
$this->settings_repo = $settings_repo;
}
public function shouldDispatch(SendWebhooks $event, array $triggers): bool
public function shouldDispatch(SendWebhooks $event, array $triggers = null): bool
{
return true;
}

View File

@ -8,7 +8,7 @@ use Monolog\Logger;
class TuneIn extends AbstractConnector
{
public function shouldDispatch(SendWebhooks $event, array $triggers): bool
public function shouldDispatch(SendWebhooks $event, array $triggers = null): bool
{
return $event->hasTrigger('song_changed');
}

View File

@ -155,7 +155,7 @@ class Dispatcher implements EventSubscriberInterface
/**
* Directly access a webhook connector of the specified type.
*
* @param $type
* @param string $type
* @return Connector\ConnectorInterface
*/
public function getConnector($type): Connector\ConnectorInterface

View File

@ -1,4 +1,4 @@
<?php //[STAMP] dae8bf1d779a4fdcb67206ca7df9e81f
<?php //[STAMP] dbee19fa951537a50feb8f99cb8144f8
namespace _generated;
// This class was automatically generated by build task
@ -170,7 +170,7 @@ trait FunctionalTesterActions
* For checking the raw source code, use `seeInSource()`.
*
* @param string $text
* @param string $selector optional
* @param array|string $selector optional
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::see()
*/
@ -208,7 +208,7 @@ trait FunctionalTesterActions
* For checking the raw source code, use `seeInSource()`.
*
* @param string $text
* @param string $selector optional
* @param array|string $selector optional
* @see \Codeception\Lib\InnerBrowser::see()
*/
public function see($text, $selector = null) {
@ -245,7 +245,7 @@ trait FunctionalTesterActions
* For checking the raw source code, use `seeInSource()`.
*
* @param string $text
* @param string $selector optional
* @param array|string $selector optional
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Lib\InnerBrowser::dontSee()
*/
@ -281,7 +281,7 @@ trait FunctionalTesterActions
* For checking the raw source code, use `seeInSource()`.
*
* @param string $text
* @param string $selector optional
* @param array|string $selector optional
* @see \Codeception\Lib\InnerBrowser::dontSee()
*/
public function dontSee($text, $selector = null) {

View File

@ -1,4 +1,4 @@
<?php //[STAMP] 1cd6dc9d0ddc4d1fe6ebdcea2a1c7f3b
<?php //[STAMP] 005cdd3808f64fcc6304507bf3571ce7
namespace _generated;
// This class was automatically generated by build task

View File

@ -8,11 +8,6 @@ class UtilitiesTest extends \Codeception\Test\Unit
public function testUtilities()
{
$test_arr = ['test' => true, 'sub_test' => ['sub_test_1' => 42]];
$test_result = \App\Utilities::print_r($test_arr, true);
$expected_result = print_r($test_arr, true);
$this->assertContains($expected_result, $test_result);
$test_result = \App\Utilities::generatePassword(10);
$this->assertTrue(strlen($test_result) == 10);
@ -20,24 +15,14 @@ class UtilitiesTest extends \Codeception\Test\Unit
$expected_result = '100 days';
$this->assertEquals($expected_result, $test_result);
$time = time();
$test_result = \App\Utilities::gstrtotime('+5 minutes', $time);
$expected_result = $time+(60*5);
$this->assertEquals($test_result, $expected_result);
$test_string = 'Lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet';
$test_result = \App\Utilities::truncate_text($test_string, 15);
$test_result = \App\Utilities::truncateText($test_string, 15);
$expected_result = 'Lorem ipsum...';
$this->assertEquals($test_result, $expected_result);
$test_url = 'https://www.twitter.com/';
$test_result = \App\Utilities::truncate_url($test_url);
$test_result = \App\Utilities::truncateUrl($test_url);
$expected_result = 'twitter.com';
$this->assertEquals($test_result, $expected_result);
$test_array = ['one', 'two', 'three'];
$test_result = \App\Utilities::join_compound($test_array);
$expected_result = 'one, two and three';
$this->assertEquals($test_result, $expected_result);
}
}