diff --git a/analysis_options.yaml b/analysis_options.yaml index fa8474b6..d1a52392 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -5,5 +5,6 @@ analyzer: linter: rules: - avoid_slow_async_io + - curly_braces_in_flow_control_structures - unnecessary_const - unnecessary_new \ No newline at end of file diff --git a/lib/src/core/controller.dart b/lib/src/core/controller.dart index 738ec014..558dbe13 100644 --- a/lib/src/core/controller.dart +++ b/lib/src/core/controller.dart @@ -105,8 +105,8 @@ class Controller { var injection = preInject(reflectedMethod, app.container.reflector); - if (exposeDecl?.allowNull?.isNotEmpty == true) - injection.optional?.addAll(exposeDecl.allowNull); + if (exposeDecl?.allowNull?.isNotEmpty == true) { + injection.optional?.addAll(exposeDecl.allowNull);} routeMappings[name] = routable.addRoute(exposeDecl.method, exposeDecl.path, handleContained(reflectedMethod, injection), diff --git a/lib/src/core/driver.dart b/lib/src/core/driver.dart index c78faa33..cf87f5e2 100644 --- a/lib/src/core/driver.dart +++ b/lib/src/core/driver.dart @@ -149,9 +149,10 @@ abstract class Driver< } return f.catchError((e, StackTrace st) { - if (e is FormatException) + if (e is FormatException) { throw AngelHttpException.badRequest(message: e.message) ..stackTrace = st; + } throw AngelHttpException(e, stackTrace: st, statusCode: 500, @@ -172,10 +173,11 @@ abstract class Driver< } else { var zoneSpec = ZoneSpecification( print: (self, parent, zone, line) { - if (app.logger != null) + if (app.logger != null) { app.logger.info(line); - else + } else { parent.print(zone, line); + } }, handleUncaughtError: (self, parent, zone, error, stackTrace) { var trace = Trace.from(stackTrace ?? StackTrace.current).terse; @@ -259,9 +261,9 @@ abstract class Driver< Future handleError; - if (!res.isOpen) + if (!res.isOpen) { handleError = Future.value(); - else { + } else { res.statusCode = e.statusCode; handleError = Future.sync(() => app.errorHandler(e, req, res)).then((result) { diff --git a/lib/src/core/hooked_service.dart b/lib/src/core/hooked_service.dart index 8e9e60d2..00216f49 100644 --- a/lib/src/core/hooked_service.dart +++ b/lib/src/core/hooked_service.dart @@ -63,13 +63,14 @@ class HookedService> } Map _stripReq(Map params) { - if (params == null) + if (params == null) { return params; - else + } else { return params.keys .where((key) => key != '__requestctx' && key != '__responsectx') .fold>( {}, (map, key) => map..[key] = params[key]); + } } /// Closes any open [StreamController]s on this instance. **Internal use only**. @@ -109,8 +110,9 @@ class HookedService> final listeners = >[] ..addAll(isAfter == true ? after : before); - if (hooks != null) + if (hooks != null) { listeners.addAll(isAfter == true ? hooks.after : hooks.before); + } listeners.forEach(dispatcher.listen); } @@ -469,8 +471,9 @@ class HookedService> HookedServiceEvent event, [HookedServiceEventListener callback]) { Future f; - if (callback != null && event?._canceled != true) + if (callback != null && event?._canceled != true) { f = Future.sync(() => callback(event)); + } f ??= Future.value(); return f.then((_) => dispatcher._emit(event)); } @@ -533,7 +536,7 @@ class HookedServiceEvent> { T service; HookedServiceEvent(this._isAfter, this._request, this._response, this.service, - String this._eventName, + this._eventName, {Id id, this.data, Map params, this.result}) { _id = id; _params = params ?? {}; @@ -557,8 +560,9 @@ class HookedServiceEventDispatcher> { /// Fires an event, and returns it once it is either canceled, or all listeners have run. Future> _emit( HookedServiceEvent event) { - if (event?._canceled == true || event == null || listeners.isEmpty) + if (event?._canceled == true || event == null || listeners.isEmpty) { return Future.value(event); + } var f = Future>.value(event); diff --git a/lib/src/core/injection.dart b/lib/src/core/injection.dart index 078320eb..3c2a300c 100644 --- a/lib/src/core/injection.dart +++ b/lib/src/core/injection.dart @@ -39,8 +39,9 @@ resolveInjection(requirement, InjectionRequest injection, RequestContext req, if (value == null && param.required != false) throw param.error; return value; } else if (requirement is String) { - if (req.container.hasNamed(requirement)) + if (req.container.hasNamed(requirement)) { return req.container.findByName(requirement); + } if (req.params.containsKey(requirement)) { return req.params[requirement]; } else if ((propFromApp = req.app.findProperty(requirement)) != null) @@ -62,14 +63,16 @@ resolveInjection(requirement, InjectionRequest injection, RequestContext req, _primitiveTypes.contains(type)) { return await resolveInjection( key, injection, req, res, throwOnUnresolved, container); - } else + } else { return await resolveInjection( type, injection, req, res, throwOnUnresolved, container); + } } else if (requirement is Type && requirement != dynamic) { try { var futureType = container.reflector.reflectFutureOf(requirement); - if (container.has(futureType.reflectedType)) + if (container.has(futureType.reflectedType)) { return await container.make(futureType.reflectedType); + } } on UnsupportedError { // Ignore. } diff --git a/lib/src/core/map_service.dart b/lib/src/core/map_service.dart index 29e443dd..e628a4a6 100644 --- a/lib/src/core/map_service.dart +++ b/lib/src/core/map_service.dart @@ -39,18 +39,19 @@ class MapService extends Service> { return (Map item) { if (item['id'] == null) return false; - else if (autoIdAndDateFields != false) + else if (autoIdAndDateFields != false) { return item['id'] == id?.toString(); - else + } else { return item['id'] == id; + } }; } @override Future>> index([Map params]) { - if (allowQuery == false || params == null || params['query'] is! Map) + if (allowQuery == false || params == null || params['query'] is! Map) { return Future.value(items); - else { + } else { var query = params['query'] as Map; return Future.value(items.where((item) { @@ -75,10 +76,11 @@ class MapService extends Service> { @override Future> create(Map data, [Map params]) { - if (data is! Map) + if (data is! Map) { throw AngelHttpException.badRequest( message: 'MapService does not support `create` with ${data.runtimeType}.'); + } var now = DateTime.now().toIso8601String(); var result = Map.from(data); @@ -95,10 +97,11 @@ class MapService extends Service> { @override Future> modify(String id, Map data, [Map params]) { - if (data is! Map) + if (data is! Map) { throw AngelHttpException.badRequest( message: 'MapService does not support `modify` with ${data.runtimeType}.'); + } if (!items.any(_matchesId(id))) return create(data, params); return read(id).then((item) { @@ -106,10 +109,11 @@ class MapService extends Service> { if (idx < 0) return create(data, params); var result = Map.from(item)..addAll(data); - if (autoIdAndDateFields == true) + if (autoIdAndDateFields == true) { result ..[autoSnakeCaseNames == false ? 'updatedAt' : 'updated_at'] = DateTime.now().toIso8601String(); + } return Future.value(items[idx] = result); }); } @@ -117,16 +121,18 @@ class MapService extends Service> { @override Future> update(String id, Map data, [Map params]) { - if (data is! Map) + if (data is! Map) { throw AngelHttpException.badRequest( message: 'MapService does not support `update` with ${data.runtimeType}.'); + } if (!items.any(_matchesId(id))) return create(data, params); return read(id).then((old) { - if (!items.remove(old)) + if (!items.remove(old)) { throw AngelHttpException.notFound( message: 'No record found for ID $id'); + } var result = Map.from(data); if (autoIdAndDateFields == true) { @@ -158,11 +164,12 @@ class MapService extends Service> { } return read(id, params).then((result) { - if (items.remove(result)) + if (items.remove(result)) { return result; - else + } else { throw AngelHttpException.notFound( message: 'No record found for ID $id'); + } }); } } diff --git a/lib/src/core/metadata.dart b/lib/src/core/metadata.dart index 03c497a4..877073ff 100644 --- a/lib/src/core/metadata.dart +++ b/lib/src/core/metadata.dart @@ -70,30 +70,38 @@ class Parameter { /// Returns an error that can be thrown when the parameter is not present. get error { - if (cookie?.isNotEmpty == true) + if (cookie?.isNotEmpty == true) { return AngelHttpException.badRequest( message: 'Missing required cookie "$cookie".'); - if (header?.isNotEmpty == true) + } + if (header?.isNotEmpty == true) { return AngelHttpException.badRequest( message: 'Missing required header "$header".'); - if (query?.isNotEmpty == true) + } + if (query?.isNotEmpty == true) { return AngelHttpException.badRequest( message: 'Missing required query parameter "$query".'); - if (session?.isNotEmpty == true) + } + if (session?.isNotEmpty == true) { return StateError('Session does not contain required key "$session".'); + } } /// Obtains a value for this parameter from a [RequestContext]. getValue(RequestContext req) { - if (cookie?.isNotEmpty == true) + if (cookie?.isNotEmpty == true) { return req.cookies.firstWhere((c) => c.name == cookie)?.value ?? defaultValue; - if (header?.isNotEmpty == true) + } + if (header?.isNotEmpty == true) { return req.headers.value(header) ?? defaultValue; - if (session?.isNotEmpty == true) + } + if (session?.isNotEmpty == true) { return req.session[session] ?? defaultValue; - if (query?.isNotEmpty == true) + } + if (query?.isNotEmpty == true) { return req.uri.queryParameters[query] ?? defaultValue; + } return defaultValue; } } diff --git a/lib/src/core/request_context.dart b/lib/src/core/request_context.dart index 381964e2..f50f6e29 100644 --- a/lib/src/core/request_context.dart +++ b/lib/src/core/request_context.dart @@ -202,18 +202,20 @@ abstract class RequestContext { : contentType?.toString(); // Change to assert - if (contentTypeString == null) + if (contentTypeString == null) { throw ArgumentError( 'RequestContext.accepts expects the `contentType` parameter to NOT be null.'); + } _acceptHeaderCache ??= headers.value('accept'); if (_acceptHeaderCache == null) return false; - else if (strict != true && _acceptHeaderCache.contains('*/*')) + else if (strict != true && _acceptHeaderCache.contains('*/*')) { return true; - else + } else { return _acceptHeaderCache.contains(contentTypeString); + } } /// Returns as `true` if the client's `Accept` header indicates that it will accept any response content type. diff --git a/lib/src/core/response_context.dart b/lib/src/core/response_context.dart index 35d8b537..9f9ee1e1 100644 --- a/lib/src/core/response_context.dart +++ b/lib/src/core/response_context.dart @@ -76,10 +76,11 @@ abstract class ResponseContext int get statusCode => _statusCode; set statusCode(int value) { - if (!isOpen) + if (!isOpen) { throw closed(); - else + } else { _statusCode = value ?? 200; + } } /// Returns `true` if the response is still available for processing by Angel. @@ -114,10 +115,11 @@ abstract class ResponseContext /// /// If [value] is `null`, then the header will be removed. set contentLength(int value) { - if (value == null) + if (value == null) { headers.remove('content-length'); - else + } else { headers['content-length'] = value.toString(); + } } /// Gets or sets the content type to send back to a client. @@ -262,21 +264,24 @@ abstract class ResponseContext // UserController@show List split = action.split("@"); - if (split.length < 2) + if (split.length < 2) { throw Exception( "Controller redirects must take the form of 'Controller@action'. You gave: $action"); + } Controller controller = app.controllers[split[0].replaceAll(_straySlashes, '')]; - if (controller == null) + if (controller == null) { throw Exception("Could not find a controller named '${split[0]}'"); + } Route matched = controller.routeMappings[split[1]]; - if (matched == null) + if (matched == null) { throw Exception( "Controller '${split[0]}' does not contain any action named '${split[1]}'"); + } final head = controller .findExpose(app.container.reflector) @@ -314,8 +319,9 @@ abstract class ResponseContext ? MediaType('application', 'octet-stream') : MediaType.parse(mimeType); - if (correspondingRequest.method != 'HEAD') + if (correspondingRequest.method != 'HEAD') { return file.openRead().pipe(this); + } } /// Configure the response to write to an intermediate response buffer, rather than to the stream directly. @@ -352,10 +358,11 @@ abstract class ResponseContext void writeCharCode(int charCode) { if (!isOpen && isBuffered) throw closed(); - else if (!isBuffered) + else if (!isBuffered) { add([charCode]); - else + } else { buffer.addByte(charCode); + } } @override @@ -392,18 +399,20 @@ class _LockableBytesBuilderImpl implements LockableBytesBuilder { @override void add(List bytes) { - if (_closed) + if (_closed) { throw _deny(); - else + } else { _buf.add(bytes); + } } @override void addByte(int byte) { - if (_closed) + if (_closed) { throw _deny(); - else + } else { _buf.addByte(byte); + } } @override diff --git a/lib/src/core/routable.dart b/lib/src/core/routable.dart index 1253e8a8..e98ac39a 100644 --- a/lib/src/core/routable.dart +++ b/lib/src/core/routable.dart @@ -26,9 +26,9 @@ RequestHandler chain(Iterable handlers) { for (var handler in handlers) { if (handler == null) break; - if (runPipeline == null) + if (runPipeline == null) { runPipeline = () => Future.sync(() => handler(req, res)); - else { + } else { var current = runPipeline; runPipeline = () => current().then((result) => !res.isOpen ? Future.value(result) diff --git a/lib/src/core/server.dart b/lib/src/core/server.dart index b6a62b7e..a072c1c1 100644 --- a/lib/src/core/server.dart +++ b/lib/src/core/server.dart @@ -275,8 +275,9 @@ class Angel extends Routable { return result; } else if (result != null) { return res.serialize(result); - } else + } else { return res.isOpen; + } }); } diff --git a/lib/src/core/service.dart b/lib/src/core/service.dart index 25e70816..bbe147be 100644 --- a/lib/src/core/service.dart +++ b/lib/src/core/service.dart @@ -21,7 +21,7 @@ class Providers { /// The transport through which the client is accessing this service. final String via; - const Providers(String this.via); + const Providers(this.via); static const String viaRest = "rest"; static const String viaWebsocket = "websocket"; @@ -206,10 +206,11 @@ class Service extends Routable { return (id == true || id?.toString() == 'true') as T; else if (T == double) return double.parse(id.toString()) as T; - else if (T == num) + else if (T == num) { return num.parse(id.toString()) as T; - else + } else { return id as T; + } } /// Generates RESTful routes pointing to this class's methods. diff --git a/lib/src/http/http_request_context.dart b/lib/src/http/http_request_context.dart index 264a9474..42538ce1 100644 --- a/lib/src/http/http_request_context.dart +++ b/lib/src/http/http_request_context.dart @@ -80,10 +80,11 @@ class HttpRequestContext extends RequestContext { String override = request.method; - if (app.allowMethodOverrides == true) + if (app.allowMethodOverrides == true) { override = request.headers.value('x-http-method-override')?.toUpperCase() ?? request.method; + } ctx.app = app; ctx._contentType = request.headers.contentType == null diff --git a/lib/src/http/http_response_context.dart b/lib/src/http/http_response_context.dart index eb4b49e9..3ec53236 100644 --- a/lib/src/http/http_response_context.dart +++ b/lib/src/http/http_response_context.dart @@ -73,9 +73,10 @@ class HttpResponseContext extends ResponseContext { @override set contentType(MediaType value) { super.contentType = value; - if (!_streamInitialized) + if (!_streamInitialized) { rawResponse.headers.contentType = ContentType(value.type, value.subtype, parameters: value.parameters); + } } bool _openStream() { @@ -184,8 +185,9 @@ class HttpResponseContext extends ResponseContext { rawResponse.add(data); } - } else + } else { buffer.add(data); + } } @override diff --git a/lib/src/http2/http2_response_context.dart b/lib/src/http2/http2_response_context.dart index 594ca7ec..7e033fbc 100644 --- a/lib/src/http2/http2_response_context.dart +++ b/lib/src/http2/http2_response_context.dart @@ -189,8 +189,9 @@ class Http2ResponseContext extends ResponseContext { stream.sendData(data); } - } else + } else { buffer.add(data); + } } @override diff --git a/lib/src/safe_stream_controller.dart b/lib/src/safe_stream_controller.dart index 836df164..bd2de680 100644 --- a/lib/src/safe_stream_controller.dart +++ b/lib/src/safe_stream_controller.dart @@ -62,9 +62,9 @@ class _SingleSafeCtrl implements SafeCtrl { @override void whenInitialized(void callback()) { if (!_initialized) { - if (!_hasListener) + if (!_hasListener) { _initializer = callback; - else { + } else { _initializer(); _initialized = true; } @@ -112,9 +112,9 @@ class _BroadcastSafeCtrl implements SafeCtrl { @override void whenInitialized(void callback()) { if (!_initialized) { - if (_listeners <= 0) + if (_listeners <= 0) { _initializer = callback; - else { + } else { _initializer(); _initialized = true; } diff --git a/test/common.dart b/test/common.dart index 0227f8a1..84b98550 100644 --- a/test/common.dart +++ b/test/common.dart @@ -7,7 +7,7 @@ class Todo extends Model { String text; String over; - Todo({String this.text, String this.over}); + Todo({this.text, this.over}); Map toJson() { return { diff --git a/test/controller_test.dart b/test/controller_test.dart index 8701bfc6..3ca9ecac 100644 --- a/test/controller_test.dart +++ b/test/controller_test.dart @@ -63,8 +63,9 @@ main() { res.redirectToAction("TodoController@foo", {"foo": "world"})); // Register as a singleton, just for the purpose of this test - if (!app.container.has()) + if (!app.container.has()) { app.container.registerSingleton(ctrl = TodoController()); + } // Using mountController(); await app.mountController(); diff --git a/test/streaming_test.dart b/test/streaming_test.dart index 233a5226..6b9d12e3 100644 --- a/test/streaming_test.dart +++ b/test/streaming_test.dart @@ -94,8 +94,9 @@ main() { await http.handleRequest(rq); var body = await rq.response.transform(utf8.decoder).join(); - if (rq.response.statusCode != 32) + if (rq.response.statusCode != 32) { throw 'overwrite should throw error; response: $body'; + } } on StateError { // Success }