Caso não selecione a cidade, mudar para null
@ORM\PrePersist
@ORM\PreUpdate
337941
public function verificaCidade() {
        if (!is_null($this->getCidade()) && $this->getCidade()->getId() == '') {
            $this->setCidade(null);
        }
    }
999061
public function atendimentoAndamento($usuario, $unidade = null)
    {
        $status = [
            self::CHAMADO_PELA_MESA,
            self::ATENDIMENTO_INICIADO,
        ];
        try {
            $qb = $this->storage
                ->getManager()
                ->createQueryBuilder()
                ->select('e')
                ->from(Atendimento::class, 'e')
                ->where('e.usuario = :usuario')
                ->andWhere('e.status IN (:status)');
            
            $params = [
                'usuario' => $usuario,
                'status' => $status,
            ];
            
            if ($unidade) {
                $qb->andWhere('e.unidade = :unidade');
                $params['unidade'] = $unidade;
            }
            
            return $qb
                ->setParameters($params)
                ->getQuery()
                ->getOneOrNullResult();
        } catch (\Doctrine\ORM\NonUniqueResultException $e) {
            /*
             * caso tenha mais de um atendimento preso ao usuario,
             * libera os atendimentos e retorna null para o atendente chamar de novo.
             * BUG #213
             */
            $this->storage
                ->getManager()
                ->createQueryBuilder()
                ->update(Atendimento::class, 'e')
                ->set('e.status', ':status')
                ->set('e.usuario', ':null')
                ->where('e.usuario = :usuario')
                ->andWhere('e.status IN (:status)')
                ->setParameters([
                    'status'  => 1,
                    'null'    => null,
                    'usuario' => $usuario,
                    'status'  => $status
                ])
                ->getQuery()
                ->execute();

            return;
        }
    }
1012182
public function preUpdate($isNew = false)
    {
        if (null === $this->educations) {
            $this->getEducations();
        }
        if (null === $this->employments) {
            $this->getEmployments();
        }
        if (null === $this->link) {
            $this->getLink();
        }
    }
941289
public function beforeUpdate()
    {
        foreach ($this->models as $relationName => $config) {
            $this->markFilesAsPermanent($this->getRelationValues($relationName));
        }
    }
769922
protected function registerException()
    {
        $this->app->singleton('Nano7\Foundation\Contracts\Exception\ExceptionHandler', function ($app) {
            $except = new \Nano7\Foundation\Exception\ExceptionHandler();

            // Verificar se view foi adicionada
            if ($app->resolved('view')) {
                $except->setViewService($app['view']);
            }

            return $except;
        });
    }
350929
private function execute()
    {
        $this->connect();
        try {
            $this->create->execute($this->dados);
            $this->result = $this->conn->lastInsertId();
        } catch (\PDOException $e) {
            $this->result = null;
            $this->erro = "<b>Erro ao cadastrar: ({$this->tabela})</b> {$e->getMessage()}";
        }

        parent::setDefault();
    }
531968
public function beforeUpdate($event)
    {
        $fields = $this->fields;
        $nowDate = gmdate($this->databaseTimeFormat);
        if (!$this->isActuallyDirty()) {
            return;
        }

        if (isset($this->fields['modifiedField']) && !$this->owner->isAttributeChanged($this->fields['modifiedField'])) {
            $this->owner->{$this->fields['modifiedField']} = $nowDate;
        }
        if (isset($this->fields['modifiedByField']) && !$this->owner->isAttributeChanged($this->fields['modifiedByField'])) {
            $this->owner->{$this->fields['modifiedByField']} = self::_getUserId();
        }
    }
778631
public function handle()
    {
        $command = new ObfuscatePkg;
        $command->setArguments($this->arguments());

        if ($command->execute() === true) {

            echo shell_exec("composer dump-autoload");

            $this->info("A aplicação foi ofuscada com sucesso");
            $path_backup = $command->getBackupPath();
            $this->info("Um backup da aplicação original se encontra em {$path_backup}");

            return true;
        }

        $errors = $command->getObfuscator()->getErrorMessages();
        foreach ($errors as $message) {
            $this->error($message);
        }

        $runtime = $command->getObfuscator()->getRuntimeMessages();
        foreach ($runtime as $message) {
            $this->info($message);
        }

        return false;

    }
725463
public function redirecionar(Atendimento $atendimento, $unidade, $servico, $usuario = null)
    {
        $status = $atendimento->getStatus();
        
        if (!in_array($status, [ self::ATENDIMENTO_INICIADO, self::ATENDIMENTO_ENCERRADO ])) {
            throw new Exception('Não pode redirecionar esse atendimento.');
        }
        
        if (!($unidade instanceof Unidade)) {
            $unidade = $this->storage
                ->getRepository(Unidade::class)
                ->find($unidade);
        }
        
        if (!($servico instanceof Servico)) {
            $servico = $this->storage
                ->getRepository(Servico::class)
                ->find($servico);
        }
        
        if ($usuario !== null && !($usuario instanceof Usuario)) {
            $usuario = $this->storage
                ->getRepository(Usuario::class)
                ->find($usuario);
        }
        
        $this->dispatcher->createAndDispatch('attending.pre-redirect', [$atendimento, $unidade, $servico, $usuario], true);
        
        $atendimento->setStatus(self::ERRO_TRIAGEM);
        $atendimento->setDataFim(new DateTime());
        
        $tempoPermanencia = $atendimento->getDataFim()->diff($atendimento->getDataChegada());
        $tempoAtendimento = new \DateInterval('P0M');
        
        $atendimento->setTempoPermanencia($tempoPermanencia);
        $atendimento->setTempoAtendimento($tempoAtendimento);
        
        $novo = $this->copyToRedirect($atendimento, $unidade, $servico, $usuario);
        
        $om = $this->storage->getManager();
        $om->merge($atendimento);
        $om->persist($novo);
        
        $om->flush();

        $this->dispatcher->createAndDispatch('attending.redirect', [$atendimento, $novo], true);

        return $novo;
    }
1333218
private function getPreparedInsertUpdate()
    {
        if (is_null($this->preparedInsertUpdate)) {
            $this->preparedInsertUpdate = $this->getServer()
                ->insert($this->tableName)
                ->set($this->keyColumnName, ':id')
                ->set($this->valueColumnName, ':value')
                ->set($this->expireColumnName, ':expire')
                ->onDuplicateKey($this->keyColumnName)
                ->set($this->valueColumnName, ':newValue')
                ->set($this->expireColumnName, ':newExpire');
        }

        return $this->preparedInsertUpdate;
    }
383292
public function postUpdate()
    {
        /** @var ObjectManager $om */
        $om = $this->container->get('claroline.persistence.object_manager');

        /** @var MaskManager $maskManager */
        $maskManager = $this->container->get('claroline.manager.mask_manager');

        /** @var ResourceType $pathType */
        $quizType = $om
            ->getRepository('Claroline\CoreBundle\Entity\Resource\ResourceType')
            ->findOneBy(['name' => 'ujm_exercise']);

        $this->log('Renaming mask decoder `VIEW_DOCIMOLOGY` to `view_docimology`...');
        $maskManager->renameMask($quizType, 'VIEW_DOCIMOLOGY', 'view_docimology');

        $this->log('Renaming mask decoder `MANAGE_PAPERS` to `manage_papers`...');
        $maskManager->renameMask($quizType, 'MANAGE_PAPERS', 'manage_papers');

        $om->flush();

        $this->log('Set exo numbering...');

        $sql = "UPDATE ujm_exercise SET numbering = 'none' WHERE numbering ='' OR numbering = NULL";
        $sth = $this->container->get('doctrine.dbal.default_connection')->prepare($sql);
        $sth->execute();

        $this->log('Clean old schema table...');
        $drop = 'DROP TABLE IF EXISTS ujm_link_hint_paper;';
        $dropSth = $this->container->get('doctrine.dbal.default_connection')->prepare($drop);
        $dropSth->execute();
    }
894159
private function execute()
    {
        $this->connect();
        try {
            $this->create->execute($this->dados);
            $this->result = $this->conn->lastInsertId();
            $this->react = new React("create", str_replace(PRE, '', $this->tabela), array_merge(["id" => $this->result], $this->dados));
        } catch (\PDOException $e) {
            $this->result = null;
            $this->erro = "<b>Erro ao cadastrar: ({$this->tabela})</b> {$e->getMessage()}";
        }

        parent::setDefault();
    }
357824
public function commit()
    {
        try {
            $toUpdate = array_merge($this->getFieldsToUpdate(), $this->getFieldsToDelete());

            if (! empty($toUpdate)) {
                $idField  = $this->_item->getIdField();

                $query = "
                    UPDATE
                        `" . $this->getDbPrefix() . $this->_item->getDbContainer() . "`
                    SET
                        " . $this->_getPreparedFields($toUpdate) . "
                    WHERE
                        `$idField` = ?";

                if (! array_key_exists($idField, $toUpdate)) {
                    $toUpdate[$idField] = $this->_item->getId()->getOrig();
                }

                $prepared = Agl::app()->getDb()->getConnection()->prepare($query);

                if (! $prepared->execute(array_values($toUpdate))) {
                    $error = $prepared->errorInfo();
                    throw new Exception("The update query failed (table '" . $this->getDbPrefix() . $this->_item->getDbContainer() . "') with message '" . $error[2] . "'");
                }

                if (Agl::app()->isDebugMode()) {
                    Agl::app()->getDb()->incrementCounter();
                }

                return $prepared->rowCount();
            }
        } catch (Exception $e) {
            throw new Exception($e);
        }

        return true;
    }
237667
private function execute()
    {
        $this->connect();
        try {
            $this->update->execute(array_merge($this->dados, $this->places));
            $this->result = true;

            foreach ($this->resultsUpdates[0] as $col => $value) {
                if(!isset($this->dados[$col]))
                    $this->dados[$col] = $value;
            }

            $this->react = new React("update", str_replace(PRE, '', $this->tabela), $this->dados, $this->resultsUpdates);
        } catch (\PDOException $e) {
            $this->result = null;
            $this->erro = "<b>(Update) Erro ao Ler: ({$this->tabela})</b> {$e->getMessage()}";
        }

        parent::setDefault();
    }
308893
public function prepareQuery()
    {
        $query = $this->model->newQuery();
        $primaryTable = $this->model->getTable();
        $selects = [$primaryTable.'.*'];
        $joins = [];
        $withs = [];

        /**
         * @event backend.list.extendQueryBefore
         * Provides an opportunity to modify the `$query` object before the List widget applies its scopes to it.
         *
         * Example usage:
         *
         *     Event::listen('backend.list.extendQueryBefore', function($listWidget, $query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         * Or
         *
         *     $listWidget->bindEvent('list.extendQueryBefore', function ($query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         */
        $this->fireSystemEvent('backend.list.extendQueryBefore', [$query]);

        /*
         * Prepare searchable column names
         */
        $primarySearchable = [];
        $relationSearchable = [];

        $columnsToSearch = [];
        if (!empty($this->searchTerm) && ($searchableColumns = $this->getSearchableColumns())) {
            foreach ($searchableColumns as $column) {
                /*
                 * Related
                 */
                if ($this->isColumnRelated($column)) {
                    $table = $this->model->makeRelation($column->relation)->getTable();
                    $columnName = isset($column->sqlSelect)
                        ? DbDongle::raw($this->parseTableName($column->sqlSelect, $table))
                        : $table . '.' . $column->valueFrom;

                    $relationSearchable[$column->relation][] = $columnName;
                }
                /*
                 * Primary
                 */
                else {
                    $columnName = isset($column->sqlSelect)
                        ? DbDongle::raw($this->parseTableName($column->sqlSelect, $primaryTable))
                        : DbDongle::cast(Db::getTablePrefix() . $primaryTable . '.' . $column->columnName, 'TEXT');

                    $primarySearchable[] = $columnName;
                }
            }
        }

        /*
         * Prepare related eager loads (withs) and custom selects (joins)
         */
        foreach ($this->getVisibleColumns() as $column) {

            // If useRelationCount is enabled, eager load the count of the relation into $relation_count
            if ($column->relation && @$column->config['useRelationCount']) {
                $query->withCount($column->relation);
            }

            if (!$this->isColumnRelated($column) || (!isset($column->sqlSelect) && !isset($column->valueFrom))) {
                continue;
            }

            if (isset($column->valueFrom)) {
                $withs[] = $column->relation;
            }

            $joins[] = $column->relation;
        }

        /*
         * Add eager loads to the query
         */
        if ($withs) {
            $query->with(array_unique($withs));
        }

        /*
         * Apply search term
         */
        $query->where(function ($innerQuery) use ($primarySearchable, $relationSearchable, $joins) {

            /*
             * Search primary columns
             */
            if (count($primarySearchable) > 0) {
                $this->applySearchToQuery($innerQuery, $primarySearchable, 'or');
            }

            /*
             * Search relation columns
             */
            if ($joins) {
                foreach (array_unique($joins) as $join) {
                    /*
                     * Apply a supplied search term for relation columns and
                     * constrain the query only if there is something to search for
                     */
                    $columnsToSearch = array_get($relationSearchable, $join, []);

                    if (count($columnsToSearch) > 0) {
                        $innerQuery->orWhereHas($join, function ($_query) use ($columnsToSearch) {
                            $this->applySearchToQuery($_query, $columnsToSearch);
                        });
                    }
                }
            }

        });

        /*
         * Custom select queries
         */
        foreach ($this->getVisibleColumns() as $column) {
            if (!isset($column->sqlSelect)) {
                continue;
            }

            $alias = $query->getQuery()->getGrammar()->wrap($column->columnName);

            /*
             * Relation column
             */
            if (isset($column->relation)) {

                // @todo Find a way...
                $relationType = $this->model->getRelationType($column->relation);
                if ($relationType == 'morphTo') {
                    throw new ApplicationException('The relationship morphTo is not supported for list columns.');
                }

                $table =  $this->model->makeRelation($column->relation)->getTable();
                $sqlSelect = $this->parseTableName($column->sqlSelect, $table);

                /*
                 * Manipulate a count query for the sub query
                 */
                $relationObj = $this->model->{$column->relation}();
                $countQuery = $relationObj->getRelationExistenceQuery($relationObj->getRelated()->newQueryWithoutScopes(), $query);

                $joinSql = $this->isColumnRelated($column, true)
                    ? DbDongle::raw("group_concat(" . $sqlSelect . " separator ', ')")
                    : DbDongle::raw($sqlSelect);

                $joinSql = $countQuery->select($joinSql)->toSql();

                $selects[] = Db::raw("(".$joinSql.") as ".$alias);
            }
            /*
             * Primary column
             */
            else {
                $sqlSelect = $this->parseTableName($column->sqlSelect, $primaryTable);
                $selects[] = DbDongle::raw($sqlSelect . ' as '. $alias);
            }
        }

        /*
         * Apply sorting
         */
        if (($sortColumn = $this->getSortColumn()) && !$this->showTree) {
            if (($column = array_get($this->allColumns, $sortColumn)) && $column->valueFrom) {
                $sortColumn = $this->isColumnPivot($column)
                    ? 'pivot_' . $column->valueFrom
                    : $column->valueFrom;
            }

            // Set the sorting column to $relation_count if useRelationCount enabled
            if (isset($column->relation) && @$column->config['useRelationCount']) {
                $sortColumn = $column->relation . '_count';
            }

            $query->orderBy($sortColumn, $this->sortDirection);
        }

        /*
         * Apply filters
         */
        foreach ($this->filterCallbacks as $callback) {
            $callback($query);
        }

        /*
         * Add custom selects
         */
        $query->addSelect($selects);

        /**
         * @event backend.list.extendQuery
         * Provides an opportunity to modify and / or return the `$query` object after the List widget has applied its scopes to it and before it's used to get the records.
         *
         * Example usage:
         *
         *     Event::listen('backend.list.extendQuery', function($listWidget, $query) {
         *         $newQuery = MyModel::newQuery();
         *         return $newQuery;
         *     });
         *
         * Or
         *
         *     $listWidget->bindEvent('list.extendQuery', function ($query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         */
        if ($event = $this->fireSystemEvent('backend.list.extendQuery', [$query])) {
            return $event;
        }

        return $query;
    }
741391
function ObjectDeepFind(obj, propertyPath) {
	
    // Divide todas as propriedades pelo .
	var paths = propertyPath.split('.');
	
    // Copia o objeto
	var currentObj = obj;

    // Para cada propriedade vou pegar a próxima até encontrar o valor do path inteiro da propriedade
	for (var i = 0; i < paths.length; ++i) {
		if (currentObj[paths[i]] == undefined) {
			return undefined;
		} else {
			currentObj = currentObj[paths[i]];
		}
	}
	
	return currentObj;
}
788344
public function gerarCampoLivre(ArrayObject $data)
    {
        $this->alterarTamanho('NossoNumero', 17);
        $this->alterarTamanho('CodigoCedente', 7); // 06 digitos + DV
        $this->alterarTamanho('CampoLivre', 18);   // 17 digitos + DV

        $data['CodigoCedente'] .= Number::modulo11($data['CodigoCedente'], 0, 0, false);

        $nossoNumero = StringBuilder::normalize($data['NossoNumero'], 17);

        $constante1 = '2'; // 1ª posição do Nosso Numero: Tipo de Cobrança (1-Registrada / 2-Sem Registro)
        $constante2 = '4'; // 2ª posição do Nosso Número: Identificador da Emissão do Boleto (4-Beneficiário)
        $sequencia1 = (String) substr($nossoNumero, 2, 3);
        $sequencia2 = (String) substr($nossoNumero, 5, 3);
        $sequencia3 = (String) substr($nossoNumero, 8, 9);

        if ($data['Carteira'] == 'RG') {
            $constante1 = '1'; // 1ª posição do Nosso Numero: Tipo de Cobrança (1-Registrada / 2-Sem Registro)
        }

        $data['CampoLivre'] = $sequencia1 . $constante1 . $sequencia2 . $constante2 . $sequencia3;

        // Calculando o DV do campo livre
        $campoLivre = $data['CodigoCedente'] . $data['CampoLivre'];
        $data['CampoLivre'] .= Number::modulo11($campoLivre, 0, 0, false);

        $this->layout = ':Banco:Moeda:FatorVencimento:Valor:CodigoCedente:CampoLivre';
    }