all files / eslint-plugin-angular/rules/ di-unused.js

100% Statements 27/27
91.67% Branches 11/12
100% Functions 8/8
100% Lines 27/27
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73                          84×     160× 160× 160× 76×         89× 17×   72× 148× 76×   72× 143× 72×   71×   70× 45×     72×       84×                     11× 11×         84× 84×        
/**
 * disallow unused DI parameters
 *
 * Unused dependencies should not be injected.
 *
 * @version 0.8.0
 * @category bestPractice
 */
'use strict';
 
var angularRule = require('./utils/angular-rule');
 
 
module.exports = angularRule(function(context) {
    // Keeps track of visited scopes in the collectAngularScopes function to prevent infinite recursion on circular references.
    var visitedScopes = [];
 
    // This collects the variable scopes for the injectible functions which have been collected.
    function collectAngularScopes(scope) {
        Eif (visitedScopes.indexOf(scope) === -1) {
            visitedScopes.push(scope);
            scope.childScopes.forEach(function(child) {
                collectAngularScopes(child);
            });
        }
    }
 
    function reportUnusedVariables(callee, fn) {
        if (!fn) {
            return;
        }
        visitedScopes.some(function(scope) {
            if (scope.block !== fn) {
                return;
            }
            scope.variables.forEach(function(variable) {
                if (variable.name === 'arguments') {
                    return;
                }
                if (fn.params.indexOf(variable.identifiers[0]) === -1) {
                    return;
                }
                if (variable.references.length === 0) {
                    context.report(fn, 'Unused injected value {{name}}', variable);
                }
            });
            return true;
        });
    }
 
    return {
        'angular:animation': reportUnusedVariables,
        'angular:config': reportUnusedVariables,
        'angular:controller': reportUnusedVariables,
        'angular:directive': reportUnusedVariables,
        'angular:factory': reportUnusedVariables,
        'angular:filter': reportUnusedVariables,
        'angular:inject': reportUnusedVariables,
        'angular:run': reportUnusedVariables,
        'angular:service': reportUnusedVariables,
        'angular:provider': function(callee, providerFn, $get) {
            reportUnusedVariables(null, providerFn);
            reportUnusedVariables(null, $get);
        },
 
        // Actually find and report unused injected variables.
        'Program:exit': function() {
            var globalScope = context.getScope();
            collectAngularScopes(globalScope);
        }
    };
});